forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

bitrate.rs325 lines, 13.8 KiBHistoryRawDownload
1//! `probe_bitrate`: the number a properties card shows, and the two rules that
2//! make it worth showing -- it is the file's real bytes over the file's real
3//! seconds, and a field the container never stated is absent rather than zero.
4
5use std::path::{Path, PathBuf};
6use std::time::Instant;
7
8use engine::{MediaBitrate, probe_bitrate};
9
10fn asset(name: &str) -> PathBuf {
11 Path::new(env!("CARGO_MANIFEST_DIR"))
12 .join("../../assets")
13 .join(name)
14}
15
16/// What the fixture generator asked ffmpeg for, in seconds -- `-duration`/
17/// `-t` in `scripts/gen_fixtures.sh`. The independent half of the check: the
18/// probe derives its seconds from the container (frame count over frame rate,
19/// or the audio header), and this derives them from nowhere but the script that
20/// wrote the file.
21const FIXTURES: &[(&str, f64)] = &[
22 ("test_av.mp4", 5.0),
23 ("test_av1.mkv", 2.0),
24 ("test_hevc.mkv", 2.0),
25 ("test_tone_48k.wav", 3.0),
26];
27
28/// Every fixture with a container to read, well-shaped or not. The two rules
29/// below are held over all of them rather than over the tidy ones.
30const CONTAINERS: &[&str] = &[
31 "test_av.mp4",
32 "test_av1.mkv",
33 "test_hevc.mkv",
34 "test_hevc10.mkv",
35 "test_multiaudio.mp4",
36 "test_multiaudio.mkv",
37 "test_ac3.mkv",
38 "test_eac3.mkv",
39 "test_subs.mkv",
40 "test_vp9.mp4",
41 "test_h264.mkv",
42 "test_tone_48k.wav",
43 "test_short_video_long_audio.mp4",
44];
45
46/// No field is ever `Some(0)`: a zero read off a card is a measurement, and
47/// "the header did not say" is not one. Held over every field of every fixture,
48/// including the ones with no bitrate at all.
49fn no_field_is_zero(name: &str, rate: MediaBitrate) {
50 for (field, value) in [
51 ("total", rate.total),
52 ("video", rate.video),
53 ("audio", rate.audio),
54 ] {
55 assert_ne!(value, Some(0), "{name}: {field} came back a fabricated zero");
56 }
57}
58
59#[test]
60fn a_breakdown_adds_up() {
61 // The relation that makes the three numbers one line rather than three
62 // unrelated ones: they are disjoint byte counts over a shared denominator,
63 // so the parts cannot outweigh the whole and the whole cannot outweigh the
64 // file. Asserted over every container fixture, not trusted to the
65 // well-shaped ones -- a total *below* its own components is impossible, and
66 // a total above the file's byte rate means the denominator is too small,
67 // which is exactly what dividing by the video track used to do.
68 for &name in CONTAINERS {
69 let path = asset(name);
70 let bytes = std::fs::metadata(&path).expect(name).len();
71 let rate = probe_bitrate(&path);
72 no_field_is_zero(name, rate);
73 let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
74 let parts = rate.video.unwrap_or(0) + rate.audio.unwrap_or(0);
75 assert!(
76 total >= parts,
77 "{name}: total {total} is under its own parts {parts}"
78 );
79 // The ceiling: no file plays in less than no time, so no rate can beat
80 // the whole file delivered over the shortest plausible duration. One
81 // second is that floor -- every fixture here is longer.
82 assert!(
83 total <= bytes * 8,
84 "{name}: total {total} exceeds the file's own {} bits",
85 bytes * 8
86 );
87 }
88}
89
90#[test]
91fn a_long_soundtrack_over_a_short_picture_divides_by_the_file() {
92 // The lopsided container (`gen_fixtures.sh`): 2 s of video under 60 s of
93 // audio. Dividing 574 222 bytes by the *picture's* 2 s claimed 4 181 048 bps
94 // -- thirty times the truth, and a "total" smaller than its own components
95 // when written out. `ffprobe -show_entries format=bit_rate` says 76 562, and
96 // the container states its own 60 s in the `mvhd` for anyone who asks.
97 let name = "test_short_video_long_audio.mp4";
98 let path = asset(name);
99 let bytes = std::fs::metadata(&path).expect(name).len();
100 let rate = probe_bitrate(&path);
101 no_field_is_zero(name, rate);
102
103 let total = rate.total.expect("no total");
104 let expected = bytes as f64 * 8.0 / 60.0;
105 let error = (total as f64 - expected).abs() / expected;
106 assert!(
107 error < 0.05,
108 "{name}: total {total} is {:.1} % off the file over its own 60 s ({expected:.0})",
109 error * 100.0
110 );
111 // The picture is a fifth of the sound here, which is the whole point: a
112 // component measured over the video's 2 s would come out above the total.
113 let video = rate.video.expect("no video rate");
114 let audio = rate.audio.expect("no audio rate");
115 assert!(video < audio, "{name}: video {video} >= audio {audio}");
116 assert!(
117 video + audio <= total,
118 "{name}: parts {} beat the total {total}",
119 video + audio
120 );
121}
122
123#[test]
124fn total_is_the_file_over_its_seconds() {
125 for &(name, secs) in FIXTURES {
126 let path = asset(name);
127 let bytes = std::fs::metadata(&path).expect(name).len();
128 let expected = bytes as f64 * 8.0 / secs;
129
130 let rate = probe_bitrate(&path);
131 no_field_is_zero(name, rate);
132 let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
133
134 let error = (total as f64 - expected).abs() / expected;
135 assert!(
136 error < 0.05,
137 "{name}: total {total} bps is {:.1} % off {expected:.0} bps \
138 ({bytes} bytes over {secs} s)",
139 error * 100.0
140 );
141 }
142}
143
144#[test]
145fn a_stream_the_container_states_is_stated_and_no_stream_is_invented() {
146 // Every A/V fixture here has a picture, so the video row is a claim the
147 // container can always answer -- an mkv out of its own block index, an mp4
148 // out of its sample table. It must be under the whole file's rate too: a
149 // track cannot cost more than the file it sits in.
150 for &(name, secs) in FIXTURES {
151 let rate = probe_bitrate(&asset(name));
152 let total = rate.total.unwrap_or_else(|| panic!("{name}: no total"));
153 if name.ends_with(".wav") {
154 // One stream, no picture: the sound *is* the file, and there is no
155 // video row to state.
156 assert_eq!(rate.video, None, "{name}: a wav has no picture");
157 assert_eq!(rate.audio, Some(total), "{name}");
158 continue;
159 }
160 let video = rate.video.unwrap_or_else(|| panic!("{name}: no video rate"));
161 assert!(video < total, "{name}: video {video} >= file {total}");
162 // Sanity on the units: 5 s of 1280x720 is neither 2 kbps nor 2 Gbps.
163 assert!(
164 (10_000..100_000_000).contains(&video),
165 "{name}: video {video} bps is not a plausible rate for {secs} s of 720p"
166 );
167 if let Some(audio) = rate.audio {
168 assert!(audio < total, "{name}: audio {audio} >= file {total}");
169 }
170 }
171}
172
173/// The picture's bits per second as `ffprobe` reads it off the file: the video
174/// packets' bytes over `format=duration`, both taken from the file and neither
175/// from the probe under test.
176fn ffprobe_picture_bps(name: &str) -> u64 {
177 let run = |entries: &[&str]| {
178 let out = std::process::Command::new("ffprobe")
179 .args(["-v", "error"])
180 .args(entries)
181 .arg(asset(name))
182 .output()
183 .expect("ffprobe runs");
184 String::from_utf8(out.stdout).expect("ffprobe prints utf-8")
185 };
186 let bytes: u64 = run(&["-select_streams", "v", "-show_entries", "packet=size", "-of", "csv=p=0"])
187 .lines()
188 .filter(|l| !l.trim().is_empty())
189 .map(|l| l.trim().parse::<u64>().expect("a packet size"))
190 .sum();
191 let secs: f64 = run(&["-show_entries", "format=duration", "-of", "csv=p=0"])
192 .trim()
193 .parse()
194 .expect("a duration");
195 (bytes as f64 * 8.0 / secs).round() as u64
196}
197
198#[test]
199fn a_matroska_states_its_sound_too_and_its_picture_is_unchanged() {
200 // Both mkv fixtures carry `-c:a aac -b:a 128k` (`gen_fixtures.sh:158,223`),
201 // so an absent audio row here is a missing measurement, not a silent file --
202 // and a film library is overwhelmingly Matroska, so this is the common case.
203 //
204 // The picture is checked against what ffprobe reads from the file itself,
205 // so that adding the sound track to the walk cannot move it, and so that
206 // the fixtures can be regenerated without this test caring. The numerator is the one `ffprobe
207 // -select_streams v -show_entries packet=size` sums independently -- 716 834
208 // bytes for test_av1.mkv. The denominator is `Info.Duration`, **2.023 s**,
209 // not the picture's own 2.000 s: the AAC track outlasts the last frame by
210 // 23 ms and the file really is that long (`ffprobe format=duration` agrees).
211 // These were 2_867_336 / 2_086_260 while the divisor was the video track,
212 // i.e. 1.1 % high, which is the same defect the lopsided fixture shows at
213 // 30x.
214 for name in ["test_av1.mkv", "test_hevc.mkv"] {
215 let rate = probe_bitrate(&asset(name));
216 no_field_is_zero(name, rate);
217 // A tenth of a percent is the probe's integer rounding and nothing
218 // more. The 1.1 % divisor error this guards against is well outside it.
219 let expected = ffprobe_picture_bps(name);
220 let video = rate.video.unwrap_or_else(|| panic!("{name}: no picture rate"));
221 assert!(
222 video.abs_diff(expected) * 1000 <= expected,
223 "{name}: picture moved: {video} bps, ffprobe reads {expected}"
224 );
225 let audio = rate
226 .audio
227 .unwrap_or_else(|| panic!("{name}: no audio rate, and it has a 128k AAC track"));
228 assert!(
229 (100_000..170_000).contains(&audio),
230 "{name}: audio {audio} bps, asked for 128000"
231 );
232 }
233}
234
235#[test]
236fn the_mp4_rows_are_what_the_encoder_was_asked_for() {
237 // `gen_fixtures.sh:18` writes test_av.mp4's sound at `-b:a 128k`. Nothing
238 // reads `esds.avg_bitrate` any more -- the sample table is what the track
239 // actually spends -- so this is the check that walking the `stsz` lands
240 // where the declared number did. `ffprobe` puts this track at 132 311 and
241 // the picture at 3 119 464, both over the same 5 s the `mvhd` states.
242 let rate = probe_bitrate(&asset("test_av.mp4"));
243 assert_eq!(rate.video, Some(3_119_464), "test_av.mp4: picture");
244 let audio = rate.audio.expect("test_av.mp4: no audio rate");
245 assert!(
246 (120_000..140_000).contains(&audio),
247 "test_av.mp4: audio {audio} bps, asked for 128000"
248 );
249}
250
251#[test]
252fn a_dual_audio_file_names_the_track_it_would_play_and_says_there_are_others() {
253 // `test_multiaudio.mp4` is the shape a real dual-audio mp4 has:
254 // an AAC stereo track and a fatter AC-3 one in the same file. Whichever the
255 // bitrate row names, it names *one* of three, and the danger is calling a
256 // 0.13 Mb/s stereo track "sound" on a file whose selling point is the AC-3.
257 //
258 // The pick is the first audio track in file order, which is the same rule
259 // `AudioSession::probe_streams` numbers stream 0 by and the same one
260 // playback and export open. Asserted against `probe_streams` itself rather
261 // than against a constant, so the two can never drift apart silently: the
262 // bitrate row and the audio row of one card describe one track.
263 let name = "test_multiaudio.mp4";
264 let path = asset(name);
265 let streams = engine::AudioSession::probe_streams(&path).expect(name);
266 assert!(
267 streams.len() > 1,
268 "{name}: the fixture stopped being multi-audio, this test is now vacuous"
269 );
270 let rate = probe_bitrate(&path);
271 let audio = rate.audio.expect("no audio rate");
272
273 // Stream 0 is the 44.1k AAC stereo one (`gen_fixtures.sh:41`); the AC-3 at
274 // 192k is stream 2. Naming the wrong one would land near 192000.
275 assert_eq!(streams[0].index, 0, "{name}: stream order moved");
276 assert_eq!(streams[0].codec, "aac", "{name}: stream 0 is not the AAC one");
277 assert!(
278 (110_000..145_000).contains(&audio),
279 "{name}: audio {audio} bps is not stream 0's ~127 kbps AAC -- the row \
280 and the audio row now name different tracks"
281 );
282 // And the signal that it is one of several: the caller has the count in
283 // hand from the same probe it already runs, so a card can say so. This
284 // asserts the count is *reachable*, which is what makes the single number
285 // honest rather than a silent pick.
286 assert_eq!(streams.len(), 3, "{name}");
287}
288
289#[test]
290fn a_still_states_no_rate_at_all() {
291 // A still has no playing time of its own -- its length on the timeline is
292 // whatever the clip is stretched to -- so there is no per-second anything
293 // to divide 1507 bytes by. All three fields absent is the honest answer;
294 // any number here would be invented.
295 let rate = probe_bitrate(&asset("test_still.png"));
296 no_field_is_zero("test_still.png", rate);
297 assert_eq!(rate, MediaBitrate::default(), "test_still.png");
298}
299
300#[test]
301fn a_file_that_will_not_open_states_no_rate_either() {
302 // Not an error and not a zero: a probe run over a whole library meets these
303 // and the card simply has no row.
304 let rate = probe_bitrate(Path::new("/nonexistent/nothing.mp4"));
305 assert_eq!(rate, MediaBitrate::default());
306 no_field_is_zero("missing", rate);
307}
308
309#[test]
310fn no_decoder_is_opened() {
311 // The whole point of the probe: it is cheap enough to run over every file a
312 // library lists. Decoding one frame of 10-bit HEVC costs far more than this
313 // budget, so a wall clock is what proves no decoder was opened -- 2 s of
314 // 720p Main 10 through the header path is single-digit milliseconds.
315 let path = asset("test_hevc10.mkv");
316 let started = Instant::now();
317 let rate = probe_bitrate(&path);
318 let elapsed = started.elapsed();
319 no_field_is_zero("test_hevc10.mkv", rate);
320 assert!(rate.total.is_some(), "test_hevc10.mkv: no total");
321 assert!(
322 elapsed.as_millis() < 50,
323 "probe_bitrate took {elapsed:?}, which is decode territory"
324 );
325}