forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

bitrate.rs292 lines, 12.4 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#[test]
174fn a_matroska_states_its_sound_too_and_its_picture_is_unchanged() {
175 // Both mkv fixtures carry `-c:a aac -b:a 128k` (`gen_fixtures.sh:158,223`),
176 // so an absent audio row here is a missing measurement, not a silent file --
177 // and a film library is overwhelmingly Matroska, so this is the common case.
178 //
179 // The video numbers are pinned so that adding the sound track to the walk
180 // cannot move the picture. The numerator is the one `ffprobe
181 // -select_streams v -show_entries packet=size` sums independently -- 716 834
182 // bytes for test_av1.mkv. The denominator is `Info.Duration`, **2.023 s**,
183 // not the picture's own 2.000 s: the AAC track outlasts the last frame by
184 // 23 ms and the file really is that long (`ffprobe format=duration` agrees).
185 // These were 2_867_336 / 2_086_260 while the divisor was the video track,
186 // i.e. 1.1 % high, which is the same defect the lopsided fixture shows at
187 // 30x.
188 for (name, video_bps) in [("test_av1.mkv", 2_834_736), ("test_hevc.mkv", 2_062_540)] {
189 let rate = probe_bitrate(&asset(name));
190 no_field_is_zero(name, rate);
191 assert_eq!(rate.video, Some(video_bps), "{name}: picture moved");
192 let audio = rate
193 .audio
194 .unwrap_or_else(|| panic!("{name}: no audio rate, and it has a 128k AAC track"));
195 assert!(
196 (100_000..170_000).contains(&audio),
197 "{name}: audio {audio} bps, asked for 128000"
198 );
199 }
200}
201
202#[test]
203fn the_mp4_rows_are_what_the_encoder_was_asked_for() {
204 // `gen_fixtures.sh:18` writes test_av.mp4's sound at `-b:a 128k`. Nothing
205 // reads `esds.avg_bitrate` any more -- the sample table is what the track
206 // actually spends -- so this is the check that walking the `stsz` lands
207 // where the declared number did. `ffprobe` puts this track at 132 311 and
208 // the picture at 3 119 464, both over the same 5 s the `mvhd` states.
209 let rate = probe_bitrate(&asset("test_av.mp4"));
210 assert_eq!(rate.video, Some(3_119_464), "test_av.mp4: picture");
211 let audio = rate.audio.expect("test_av.mp4: no audio rate");
212 assert!(
213 (120_000..140_000).contains(&audio),
214 "test_av.mp4: audio {audio} bps, asked for 128000"
215 );
216}
217
218#[test]
219fn a_dual_audio_file_names_the_track_it_would_play_and_says_there_are_others() {
220 // `test_multiaudio.mp4` is the shape a real dual-audio mp4 has:
221 // an AAC stereo track and a fatter AC-3 one in the same file. Whichever the
222 // bitrate row names, it names *one* of three, and the danger is calling a
223 // 0.13 Mb/s stereo track "sound" on a file whose selling point is the AC-3.
224 //
225 // The pick is the first audio track in file order, which is the same rule
226 // `AudioSession::probe_streams` numbers stream 0 by and the same one
227 // playback and export open. Asserted against `probe_streams` itself rather
228 // than against a constant, so the two can never drift apart silently: the
229 // bitrate row and the audio row of one card describe one track.
230 let name = "test_multiaudio.mp4";
231 let path = asset(name);
232 let streams = engine::AudioSession::probe_streams(&path).expect(name);
233 assert!(
234 streams.len() > 1,
235 "{name}: the fixture stopped being multi-audio, this test is now vacuous"
236 );
237 let rate = probe_bitrate(&path);
238 let audio = rate.audio.expect("no audio rate");
239
240 // Stream 0 is the 44.1k AAC stereo one (`gen_fixtures.sh:41`); the AC-3 at
241 // 192k is stream 2. Naming the wrong one would land near 192000.
242 assert_eq!(streams[0].index, 0, "{name}: stream order moved");
243 assert_eq!(streams[0].codec, "aac", "{name}: stream 0 is not the AAC one");
244 assert!(
245 (110_000..145_000).contains(&audio),
246 "{name}: audio {audio} bps is not stream 0's ~127 kbps AAC -- the row \
247 and the audio row now name different tracks"
248 );
249 // And the signal that it is one of several: the caller has the count in
250 // hand from the same probe it already runs, so a card can say so. This
251 // asserts the count is *reachable*, which is what makes the single number
252 // honest rather than a silent pick.
253 assert_eq!(streams.len(), 3, "{name}");
254}
255
256#[test]
257fn a_still_states_no_rate_at_all() {
258 // A still has no playing time of its own -- its length on the timeline is
259 // whatever the clip is stretched to -- so there is no per-second anything
260 // to divide 1507 bytes by. All three fields absent is the honest answer;
261 // any number here would be invented.
262 let rate = probe_bitrate(&asset("test_still.png"));
263 no_field_is_zero("test_still.png", rate);
264 assert_eq!(rate, MediaBitrate::default(), "test_still.png");
265}
266
267#[test]
268fn a_file_that_will_not_open_states_no_rate_either() {
269 // Not an error and not a zero: a probe run over a whole library meets these
270 // and the card simply has no row.
271 let rate = probe_bitrate(Path::new("/nonexistent/nothing.mp4"));
272 assert_eq!(rate, MediaBitrate::default());
273 no_field_is_zero("missing", rate);
274}
275
276#[test]
277fn no_decoder_is_opened() {
278 // The whole point of the probe: it is cheap enough to run over every file a
279 // library lists. Decoding one frame of 10-bit HEVC costs far more than this
280 // budget, so a wall clock is what proves no decoder was opened -- 2 s of
281 // 720p Main 10 through the header path is single-digit milliseconds.
282 let path = asset("test_hevc10.mkv");
283 let started = Instant::now();
284 let rate = probe_bitrate(&path);
285 let elapsed = started.elapsed();
286 no_field_is_zero("test_hevc10.mkv", rate);
287 assert!(rate.total.is_some(), "test_hevc10.mkv: no total");
288 assert!(
289 elapsed.as_millis() < 50,
290 "probe_bitrate took {elapsed:?}, which is decode territory"
291 );
292}