forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

hw_decode.rs407 lines, 16.6 KiBHistoryRawDownload
1//! Hardware path checks. These need a built `libengine_hw.so` plus a working
2//! VA-API driver, so they are `#[ignore]`d by default. Run them with:
3//!
4//! ```text
5//! cargo build --workspace --release
6//! LD_LIBRARY_PATH=target/release \
7//! cargo test -p engine --release --test hw_decode -- --ignored --nocapture --test-threads=1
8//! ```
9//!
10//! The comparison test pins [`DecodeSession`] to the software decoder itself
11//! (it sets `VE_SW=1` in-process, hence the required `--test-threads=1`); the
12//! hardware side goes through [`HwSession`] directly and can never silently be
13//! a fallback.
14
15use std::path::{Path, PathBuf};
16use std::time::Instant;
17
18use engine::DecodeSession;
19use engine::colorspace::{ColorDescription, Matrix};
20use engine::convert::i420_to_bgra;
21use engine::demux::{Codec, Demuxer};
22use engine::scratch::Scratch;
23use engine::hw::HwSession;
24use engine::tonemap::{ToneMapper, Transfer};
25
26fn asset(name: &str) -> PathBuf {
27 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28 .join("../../assets")
29 .join(name)
30}
31
32/// What the decode funnel converts this file's planes in, so a conversion done
33/// by hand here is the one `DecodeSession` would have done.
34fn color_of(path: &Path) -> ColorDescription {
35 Demuxer::open(path).expect("open for colour").0.color
36}
37
38fn open_hw(path: &Path) -> HwSession {
39 HwSession::open(path).expect("no hardware decode plugin/driver available")
40}
41
42/// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA).
43fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
44 let path = asset(name);
45 let color = color_of(&path);
46 let mut hw = open_hw(&path);
47 let meta = hw.meta().expect("meta");
48 assert_eq!(
49 (meta.width, meta.height),
50 (1280, 720),
51 "{name} container dims"
52 );
53
54 let mut count = 0usize;
55 let mut frame_30 = Vec::new();
56 let start = Instant::now();
57 while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") {
58 assert_eq!((w, h), (1280, 720), "{name} frame {count} dims");
59 if count == 30 {
60 frame_30 = i420_to_bgra(&color, y, u, v, w as usize, h as usize);
61 }
62 count += 1;
63 }
64 eprintln!(
65 "{name}: {count} hardware frames in {:?} ({:?}/frame)",
66 start.elapsed(),
67 start.elapsed() / count.max(1) as u32
68 );
69 (count, frame_30)
70}
71
72/// The plugin must refuse junk by returning null, never by unwinding into us.
73#[test]
74#[ignore = "needs libengine_hw.so and a VA-API driver"]
75fn rejects_unopenable_files() {
76 assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none());
77 assert!(
78 HwSession::open(Path::new("/etc/hostname")).is_none(),
79 "not an mp4"
80 );
81}
82
83/// 24 frames cut from a 2160p HDR remux that used to give a black picture and
84/// an instant `eof`: at 3840x2160 with CTB 64 the picture is 34 CTB rows, so
85/// wavefront slices carry `num_entry_point_offsets == 33` (§7.4.7.1 allows up
86/// to PicHeightInCtbsY - 1) and the vendored parser indexed a `[u32; 32]` with
87/// 32. Conformant stream, panicking parser -- caught at the plugin edge, which
88/// is exactly why it reached the user as a silent eof.
89#[test]
90#[ignore = "needs libengine_hw.so and a VA-API driver"]
91fn hardware_decodes_4k_wavefront_slices() {
92 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv");
93 let mut hw = open_hw(&path);
94 let mut count = 0usize;
95 while let Some((_, _, _, w, h)) = hw.next_frame().expect("hardware decode") {
96 assert_eq!((w, h), (3840, 2160), "frame {count} dims");
97 count += 1;
98 }
99 assert!(count > 0, "4K wavefront stream decoded no pictures");
100}
101
102/// ...and the same file with its slice bytes scrambled -- a stream the plugin
103/// opens and then cannot decode a picture out of -- is refused at the door, in
104/// words that do not send the user installing a plugin they already have. The
105/// case this whole bug arrived as: never a black picture and a silent `eof`.
106#[test]
107#[ignore = "needs libengine_hw.so and a VA-API driver"]
108fn an_undecodable_hevc_stream_is_refused_by_name() {
109 let good = std::fs::read(
110 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv"),
111 )
112 .expect("read the 4K fixture");
113 // Every SPS in it (`nal_unit_type` 33, so the two header bytes are 42 01)
114 // gets `sps_max_sub_layers_minus1 = 7`, which §7.4.3.2.1 does not allow and
115 // the parser now refuses instead of indexing a 7-long array with 7.
116 let mut broken = good.clone();
117 let mut patched = 0;
118 for i in 0..broken.len() - 2 {
119 if broken[i] == 0x42 && broken[i + 1] == 0x01 {
120 broken[i + 2] |= 0x0e;
121 patched += 1;
122 }
123 }
124 assert!(patched > 0, "no SPS found in the fixture");
125 let path = Scratch::file("undecodable_hevc", "mkv");
126 std::fs::write(&path, &broken).expect("write the broken copy");
127
128 let refused = DecodeSession::open(&path)
129 .expect_err("a stream with no decodable picture must not open")
130 .to_string();
131 assert_eq!(refused, Codec::Hevc.undecodable());
132}
133
134#[test]
135#[ignore = "needs libengine_hw.so and a VA-API driver"]
136fn hardware_decodes_baseline() {
137 let (count, _) = decode_all_hw("test_baseline.mp4");
138 assert_eq!(count, 150);
139}
140
141#[test]
142#[ignore = "needs libengine_hw.so and a VA-API driver"]
143fn hardware_decodes_high_profile() {
144 // B-frames: the plugin emits display order (DPB bumping happens inside
145 // cros-codecs), so a clean run to EOF is the check we can make headlessly.
146 let (count, _) = decode_all_hw("test_high.mp4");
147 assert_eq!(count, 150);
148}
149
150/// Seeking may only change *when* a picture arrives, never the picture: both
151/// backends must land on bytes identical to a linear decode of the same index.
152#[test]
153#[ignore = "needs libengine_hw.so and a VA-API driver"]
154fn seek_matches_linear() {
155 const TARGET: u32 = 60;
156 let path = asset("test_baseline.mp4");
157
158 // Software side first, pinned like the test above. SAFETY: --test-threads=1.
159 unsafe { std::env::set_var("VE_SW", "1") };
160 let (_, rx) = DecodeSession::open(&path).expect("software open");
161 let linear = rx
162 .into_iter()
163 .find(|f| f.index == TARGET)
164 .expect("software frame 60")
165 .bgra;
166
167 let start = Instant::now();
168 let (_, rx, _cancel) = DecodeSession::open_at(&path, TARGET).expect("software open_at");
169 let seeked = rx.into_iter().next().expect("no frame after software seek");
170 eprintln!("software seek to {TARGET} took {:?}", start.elapsed());
171 assert_eq!(seeked.index, TARGET, "first frame after seek is the target");
172 assert_eq!(seeked.bgra, linear, "software seek != software linear");
173
174 let start = Instant::now();
175 let mut hw = HwSession::open_at(&path, TARGET).expect("no plugin/driver available");
176 let (y, u, v, w, h) = hw
177 .next_frame()
178 .expect("hardware decode")
179 .expect("no frame after hardware seek");
180 eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed());
181 assert_eq!(
182 i420_to_bgra(&color_of(&path), y, u, v, w as usize, h as usize),
183 linear,
184 "hardware seek != software linear"
185 );
186}
187
188/// The same promise as [`seek_matches_linear`], made of every container and
189/// codec pair there is a fixture for and at targets on, either side of and away
190/// from a keyframe -- because which of them holds is a property of the *stream's
191/// structure*, not of the seek code alone.
192///
193/// An open-GOP HEVC stream (x265's default, so `test_hevc.mkv` and its 10-bit
194/// twin, and every film off a disc or a web rip) stores the CRA that opens a GOP
195/// *ahead of* the RASL leading pictures that are shown *before* it: keyframe 30
196/// on screen is the 28th block in the file. A seek that counts stored positions
197/// rather than displayed pictures therefore hands back a picture two frames
198/// later than the index it labels, and by a different amount in a GOP with
199/// another number of leading pictures. `test_baseline.mp4` alone never showed
200/// it: it has exactly one keyframe, at frame 0, where the two orders agree.
201#[test]
202#[ignore = "needs libengine_hw.so and a VA-API driver"]
203fn seek_matches_linear_every_container() {
204 // The hardware path for all of these: there is no software HEVC or AV1
205 // decoder to compare against. SAFETY: --test-threads=1.
206 unsafe { std::env::remove_var("VE_SW") };
207 for name in [
208 "test_baseline.mp4",
209 "test_high.mp4",
210 "test_hevc.mp4",
211 "test_hevc.mkv",
212 "test_hevc10.mkv",
213 "test_h264.mkv",
214 "test_av1.mkv",
215 ] {
216 let path = asset(name);
217 let (meta, rx) = DecodeSession::open(&path).unwrap_or_else(|e| panic!("{name}: open: {e}"));
218 // On a keyframe, either side of one, well inside a GOP, the first
219 // picture and the last -- deduplicated for a fixture short enough that
220 // some of those coincide.
221 let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1];
222 targets.retain(|&t| t < meta.frame_count);
223 targets.sort_unstable();
224 targets.dedup();
225 let linear: Vec<(u32, Vec<u8>)> = rx
226 .into_iter()
227 .filter(|f| targets.contains(&f.index))
228 .map(|f| (f.index, f.bgra))
229 .collect();
230 assert_eq!(
231 linear.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
232 targets,
233 "{name}: linear decode never delivered every target"
234 );
235 for (target, want) in linear {
236 let (_, rx, _cancel) = DecodeSession::open_at(&path, target)
237 .unwrap_or_else(|e| panic!("{name}: open_at({target}): {e}"));
238 let seeked = rx
239 .into_iter()
240 .next()
241 .unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"));
242 assert_eq!(
243 seeked.index, target,
244 "{name}: first frame after seek is not the target"
245 );
246 assert!(
247 seeked.bgra == want,
248 "{name}: seek to {target} handed back a different picture than a linear decode of {target}"
249 );
250 }
251 }
252}
253
254/// Drains a bounded session, returning the indices it delivered. The loop ends
255/// only on `RecvError`, i.e. the worker closed the channel by itself.
256fn range_indices(path: &Path, start: u32, end: u32) -> Vec<u32> {
257 let (_, rx, _cancel) = DecodeSession::open_range(path, start, end).expect("open_range");
258 let mut got = Vec::new();
259 while let Ok(frame) = rx.recv() {
260 got.push(frame.index);
261 }
262 got
263}
264
265/// A bounded range must stop on its own — both backends — with `Frame::index`
266/// still the absolute source index, and then disconnect rather than hang.
267#[test]
268#[ignore = "needs libengine_hw.so and a VA-API driver"]
269fn range_stops_at_end() {
270 const START: u32 = 30;
271 const END: u32 = 60;
272 let path = asset("test_baseline.mp4");
273 let want: Vec<u32> = (START..END).collect();
274
275 // Another test in this binary may already have pinned VE_SW; clear it so
276 // the hardware half really is hardware. SAFETY: --test-threads=1.
277 unsafe { std::env::remove_var("VE_SW") };
278 assert_eq!(range_indices(&path, START, END), want, "hardware range");
279
280 unsafe { std::env::set_var("VE_SW", "1") };
281 assert_eq!(range_indices(&path, START, END), want, "software range");
282
283 // Degenerate ranges close cleanly instead of decoding to EOF.
284 assert!(range_indices(&path, 30, 30).is_empty(), "empty range");
285 assert!(range_indices(&path, 60, 30).is_empty(), "inverted range");
286 // Past the end is clamped to the frame count.
287 assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range");
288}
289
290/// The real thing: a 4K HDR10 film through the funnel, against the picture the
291/// same planes gave before the tone map was in it (BT.2020 matrix, HDR codes
292/// shown as if they were SDR -- flat and grey-washed, which is the complaint
293/// this whole path answers). Colour has to come *up*, not down, and the picture
294/// has to land somewhere a display can show rather than at either rail.
295///
296/// Gated on the film being here: it is a 20 GB download, not a fixture. HEVC
297/// Main 10, so this is a hardware-only test in every sense.
298#[test]
299#[ignore = "needs libengine_hw.so, a VA-API driver and the film"]
300fn the_hdr_film_renders_tone_mapped() {
301 // Two minutes in: past the studio logos, inside lit footage.
302 const TARGET: u32 = 3000;
303 let Some(path) = engine::real_library::film("hevc_4k_hdr") else {
304 return;
305 };
306 let path = path.as_path();
307 // SAFETY: --test-threads=1. There is no software HEVC decoder, so a pinned
308 // VE_SW from another test in this binary would refuse the file outright.
309 unsafe { std::env::remove_var("VE_SW") };
310
311 // The old picture, by hand off the plugin's own planes: the funnel did
312 // exactly this before the tone map, and it is what the comparison needs.
313 let mut hw = HwSession::open_at(path, TARGET).expect("no plugin/driver available");
314 let (y, u, v, w, h) = hw
315 .next_frame()
316 .expect("hardware decode")
317 .expect("no frame at the seek");
318 let (w, h) = (w as usize, h as usize);
319 let (y, u, v) = (y.to_vec(), u.to_vec(), v.to_vec());
320 let untouched = i420_to_bgra(&color_of(path), &y, &u, &v, w, h);
321
322 // ...and the picture the engine shows now, through the funnel itself.
323 let (_, rx, _cancel) = DecodeSession::open_at(path, TARGET).expect("open the film");
324 let shown = rx.recv().expect("a frame off the funnel").bgra;
325 assert_eq!(shown.len(), untouched.len(), "frame size");
326
327 // Saturation, as the mean distance from grey per pixel...
328 let spread = |bgra: &[u8]| -> f64 {
329 let total: u64 = bgra
330 .chunks_exact(4)
331 .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap()))
332 .sum();
333 total as f64 / (bgra.len() / 4) as f64
334 };
335 // ...and mean luma, in the limited-range code the tone map's anchors are in.
336 let luma = |bgra: &[u8]| -> f64 {
337 let total: f64 = bgra
338 .chunks_exact(4)
339 .map(|px| {
340 0.2126 * f64::from(px[2]) + 0.7152 * f64::from(px[1]) + 0.0722 * f64::from(px[0])
341 })
342 .sum();
343 16.0 + 219.0 * (total / (bgra.len() / 4) as f64) / 255.0
344 };
345 let (was, now) = (spread(&untouched), spread(&shown));
346 eprintln!(
347 "frame {TARGET}: saturation {was:.1} -> {now:.1}, mean luma {:.1} -> {:.1}",
348 luma(&untouched),
349 luma(&shown)
350 );
351 assert!(
352 now > was,
353 "the tone-mapped frame is no more colourful: {now}"
354 );
355 let mean = luma(&shown);
356 assert!(
357 (24.0..=200.0).contains(&mean),
358 "the tone-mapped frame sits at one end of the scale: mean luma {mean}"
359 );
360
361 // The funnel's own budget at this size: the map plus the conversion, which
362 // is what an HDR frame costs on top of the decode. Fastest of five, for the
363 // reason `tonemap::perf_4k_and_1080p` documents.
364 let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default(), None);
365 let sdr = ColorDescription {
366 matrix: Matrix::Bt709,
367 transfer: engine::colorspace::Transfer::Sdr,
368 full_range: false,
369 };
370 let mut best = f64::MAX;
371 for _ in 0..5 {
372 let (mut my, mut mu, mut mv) = (y.clone(), u.clone(), v.clone());
373 let t = Instant::now();
374 mapper.map(&mut my, &mut mu, &mut mv, w, h);
375 let _ = i420_to_bgra(&sdr, &my, &mu, &mv, w, h);
376 best = best.min(t.elapsed().as_secs_f64() * 1000.0);
377 }
378 eprintln!("{w}x{h} tone map + convert: {best:.1} ms/frame");
379 assert!(best <= 39.0, "{best:.1} ms/frame over the 39 ms budget");
380}
381
382/// H.264 8-bit decode is bit-exact by conformance, so the two backends must
383/// agree. A mismatch means a driver deviation and is reported, not swallowed.
384#[test]
385#[ignore = "needs libengine_hw.so and a VA-API driver"]
386fn hardware_matches_software_on_frame_30() {
387 let (_, hw) = decode_all_hw("test_baseline.mp4");
388
389 // Pin the comparison side to software ourselves: without this, running the
390 // suite without VE_SW=1 would compare hardware against hardware and pass
391 // vacuously. SAFETY: the suite is documented to run with --test-threads=1.
392 unsafe { std::env::set_var("VE_SW", "1") };
393
394 let start = Instant::now();
395 let (_, rx) = DecodeSession::open(asset("test_baseline.mp4")).expect("software open");
396 let sw = rx
397 .into_iter()
398 .find(|f| f.index == 30)
399 .expect("software frame 30")
400 .bgra;
401 eprintln!("software reached frame 30 in {:?}", start.elapsed());
402
403 assert_eq!(hw.len(), sw.len(), "frame size");
404 let diff = hw.iter().zip(&sw).filter(|(a, b)| a != b).count();
405 eprintln!("frame 30 differing bytes: {diff} / {}", hw.len());
406 assert_eq!(diff, 0, "hardware and software decode disagree");
407}