forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

hw_decode.rs588 lines, 24.0 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::mux::{self, Mp4Muxer, VideoParams};
23use engine::scratch::Scratch;
24use engine::hw::HwSession;
25use engine::tonemap::{ToneMapper, Transfer};
26
27fn asset(name: &str) -> PathBuf {
28 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
29 .join("../../assets")
30 .join(name)
31}
32
33/// What the decode funnel converts this file's planes in, so a conversion done
34/// by hand here is the one `DecodeSession` would have done.
35fn color_of(path: &Path) -> ColorDescription {
36 Demuxer::open(path).expect("open for colour").0.color
37}
38
39fn open_hw(path: &Path) -> HwSession {
40 HwSession::open(path).expect("no hardware decode plugin/driver available")
41}
42
43/// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA).
44fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
45 let path = asset(name);
46 let color = color_of(&path);
47 let mut hw = open_hw(&path);
48 let meta = hw.meta().expect("meta");
49 assert_eq!(
50 (meta.width, meta.height),
51 (1280, 720),
52 "{name} container dims"
53 );
54
55 let mut count = 0usize;
56 let mut frame_30 = Vec::new();
57 let start = Instant::now();
58 while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") {
59 assert_eq!((w, h), (1280, 720), "{name} frame {count} dims");
60 if count == 30 {
61 frame_30 = i420_to_bgra(&color, y, u, v, w as usize, h as usize);
62 }
63 count += 1;
64 }
65 eprintln!(
66 "{name}: {count} hardware frames in {:?} ({:?}/frame)",
67 start.elapsed(),
68 start.elapsed() / count.max(1) as u32
69 );
70 (count, frame_30)
71}
72
73/// The plugin must refuse junk by returning null, never by unwinding into us.
74#[test]
75#[ignore = "needs libengine_hw.so and a VA-API driver"]
76fn rejects_unopenable_files() {
77 assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none());
78 assert!(
79 HwSession::open(Path::new("/etc/hostname")).is_none(),
80 "not an mp4"
81 );
82}
83
84/// 24 frames cut from a 2160p HDR remux that used to give a black picture and
85/// an instant `eof`: at 3840x2160 with CTB 64 the picture is 34 CTB rows, so
86/// wavefront slices carry `num_entry_point_offsets == 33` (§7.4.7.1 allows up
87/// to PicHeightInCtbsY - 1) and the vendored parser indexed a `[u32; 32]` with
88/// 32. Conformant stream, panicking parser -- caught at the plugin edge, which
89/// is exactly why it reached the user as a silent eof.
90#[test]
91#[ignore = "needs libengine_hw.so and a VA-API driver"]
92fn hardware_decodes_4k_wavefront_slices() {
93 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv");
94 let mut hw = open_hw(&path);
95 let mut count = 0usize;
96 while let Some((_, _, _, w, h)) = hw.next_frame().expect("hardware decode") {
97 assert_eq!((w, h), (3840, 2160), "frame {count} dims");
98 count += 1;
99 }
100 assert!(count > 0, "4K wavefront stream decoded no pictures");
101}
102
103/// ...and the same file with its slice bytes scrambled -- a stream the plugin
104/// opens and then cannot decode a picture out of -- is refused at the door, in
105/// words that do not send the user installing a plugin they already have. The
106/// case this whole bug arrived as: never a black picture and a silent `eof`.
107#[test]
108#[ignore = "needs libengine_hw.so and a VA-API driver"]
109fn an_undecodable_hevc_stream_is_refused_by_name() {
110 let good = std::fs::read(
111 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv"),
112 )
113 .expect("read the 4K fixture");
114 // Every SPS in it (`nal_unit_type` 33, so the two header bytes are 42 01)
115 // gets `sps_max_sub_layers_minus1 = 7`, which §7.4.3.2.1 does not allow and
116 // the parser now refuses instead of indexing a 7-long array with 7.
117 let mut broken = good.clone();
118 let mut patched = 0;
119 for i in 0..broken.len() - 2 {
120 if broken[i] == 0x42 && broken[i + 1] == 0x01 {
121 broken[i + 2] |= 0x0e;
122 patched += 1;
123 }
124 }
125 assert!(patched > 0, "no SPS found in the fixture");
126 let path = Scratch::file("undecodable_hevc", "mkv");
127 std::fs::write(&path, &broken).expect("write the broken copy");
128
129 let refused = DecodeSession::open(&path)
130 .expect_err("a stream with no decodable picture must not open")
131 .to_string();
132 assert_eq!(refused, Codec::Hevc.undecodable());
133}
134
135#[test]
136#[ignore = "needs libengine_hw.so and a VA-API driver"]
137fn hardware_decodes_baseline() {
138 let (count, _) = decode_all_hw("test_baseline.mp4");
139 assert_eq!(count, 150);
140}
141
142#[test]
143#[ignore = "needs libengine_hw.so and a VA-API driver"]
144fn hardware_decodes_high_profile() {
145 // B-frames: the plugin emits display order (DPB bumping happens inside
146 // cros-codecs), so a clean run to EOF is the check we can make headlessly.
147 let (count, _) = decode_all_hw("test_high.mp4");
148 assert_eq!(count, 150);
149}
150
151/// Seeking may only change *when* a picture arrives, never the picture: both
152/// backends must land on bytes identical to a linear decode of the same index.
153#[test]
154#[ignore = "needs libengine_hw.so and a VA-API driver"]
155fn seek_matches_linear() {
156 const TARGET: u32 = 60;
157 let path = asset("test_baseline.mp4");
158
159 // Software side first, pinned like the test above. SAFETY: --test-threads=1.
160 unsafe { std::env::set_var("VE_SW", "1") };
161 let (_, rx) = DecodeSession::open(&path).expect("software open");
162 let linear = rx
163 .into_iter()
164 .find(|f| f.index == TARGET)
165 .expect("software frame 60")
166 .bgra;
167
168 let start = Instant::now();
169 let (_, rx, _cancel) = DecodeSession::open_at(&path, TARGET).expect("software open_at");
170 let seeked = rx.into_iter().next().expect("no frame after software seek");
171 eprintln!("software seek to {TARGET} took {:?}", start.elapsed());
172 assert_eq!(seeked.index, TARGET, "first frame after seek is the target");
173 assert_eq!(seeked.bgra, linear, "software seek != software linear");
174
175 let start = Instant::now();
176 let mut hw = HwSession::open_at(&path, TARGET).expect("no plugin/driver available");
177 let (y, u, v, w, h) = hw
178 .next_frame()
179 .expect("hardware decode")
180 .expect("no frame after hardware seek");
181 eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed());
182 assert_eq!(
183 i420_to_bgra(&color_of(&path), y, u, v, w as usize, h as usize),
184 linear,
185 "hardware seek != software linear"
186 );
187}
188
189/// The same promise as [`seek_matches_linear`], made of every container and
190/// codec pair there is a fixture for and at targets on, either side of and away
191/// from a keyframe -- because which of them holds is a property of the *stream's
192/// structure*, not of the seek code alone.
193///
194/// An open-GOP HEVC stream (x265's default, so `test_hevc.mkv` and its 10-bit
195/// twin, and every film off a disc or a web rip) stores the CRA that opens a GOP
196/// *ahead of* the RASL leading pictures that are shown *before* it: keyframe 30
197/// on screen is the 28th block in the file. A seek that counts stored positions
198/// rather than displayed pictures therefore hands back a picture two frames
199/// later than the index it labels, and by a different amount in a GOP with
200/// another number of leading pictures. `test_baseline.mp4` alone never showed
201/// it: it has exactly one keyframe, at frame 0, where the two orders agree.
202#[test]
203#[ignore = "needs libengine_hw.so and a VA-API driver"]
204fn seek_matches_linear_every_container() {
205 // Sanitize at entry: sibling tests leak `VE_SW=1` by design and run before
206 // this one alphabetically, and a leaked pin makes the plugin-only HEVC
207 // fixtures refuse at open. The hardware path for these, including AV1's
208 // fixture: the point is the seek against the same seat a linear decode ran
209 // on, which the tests below pin for the software seat. SAFETY:
210 // --test-threads=1, which the documented invocation keeps.
211 unsafe { std::env::remove_var("VE_SW") };
212 for name in [
213 "test_baseline.mp4",
214 "test_high.mp4",
215 "test_hevc.mp4",
216 "test_hevc.mkv",
217 "test_hevc10.mkv",
218 "test_h264.mkv",
219 "test_av1.mkv",
220 ] {
221 let path = asset(name);
222 let (meta, rx) = DecodeSession::open(&path).unwrap_or_else(|e| panic!("{name}: open: {e}"));
223 // On a keyframe, either side of one, well inside a GOP, the first
224 // picture and the last -- deduplicated for a fixture short enough that
225 // some of those coincide.
226 let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1];
227 targets.retain(|&t| t < meta.frame_count);
228 targets.sort_unstable();
229 targets.dedup();
230 let linear: Vec<(u32, Vec<u8>)> = rx
231 .into_iter()
232 .filter(|f| targets.contains(&f.index))
233 .map(|f| (f.index, f.bgra))
234 .collect();
235 assert_eq!(
236 linear.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
237 targets,
238 "{name}: linear decode never delivered every target"
239 );
240 for (target, want) in linear {
241 let (_, rx, _cancel) = DecodeSession::open_at(&path, target)
242 .unwrap_or_else(|e| panic!("{name}: open_at({target}): {e}"));
243 let seeked = rx
244 .into_iter()
245 .next()
246 .unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"));
247 assert_eq!(
248 seeked.index, target,
249 "{name}: first frame after seek is not the target"
250 );
251 assert!(
252 seeked.bgra == want,
253 "{name}: seek to {target} handed back a different picture than a linear decode of {target}"
254 );
255 }
256 }
257}
258
259/// Drains a bounded session, returning the indices it delivered. The loop ends
260/// only on `RecvError`, i.e. the worker closed the channel by itself.
261fn range_indices(path: &Path, start: u32, end: u32) -> Vec<u32> {
262 let (_, rx, _cancel) = DecodeSession::open_range(path, start, end).expect("open_range");
263 let mut got = Vec::new();
264 while let Ok(frame) = rx.recv() {
265 got.push(frame.index);
266 }
267 got
268}
269
270/// A bounded range must stop on its own — both backends — with `Frame::index`
271/// still the absolute source index, and then disconnect rather than hang.
272#[test]
273#[ignore = "needs libengine_hw.so and a VA-API driver"]
274fn range_stops_at_end() {
275 const START: u32 = 30;
276 const END: u32 = 60;
277 let path = asset("test_baseline.mp4");
278 let want: Vec<u32> = (START..END).collect();
279
280 // Another test in this binary may already have pinned VE_SW; clear it so
281 // the hardware half really is hardware. SAFETY: --test-threads=1.
282 unsafe { std::env::remove_var("VE_SW") };
283 assert_eq!(range_indices(&path, START, END), want, "hardware range");
284
285 unsafe { std::env::set_var("VE_SW", "1") };
286 assert_eq!(range_indices(&path, START, END), want, "software range");
287
288 // Degenerate ranges close cleanly instead of decoding to EOF.
289 assert!(range_indices(&path, 30, 30).is_empty(), "empty range");
290 assert!(range_indices(&path, 60, 30).is_empty(), "inverted range");
291 // Past the end is clamped to the frame count.
292 assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range");
293}
294
295/// The real thing: a 4K HDR10 film through the funnel, against the picture the
296/// same planes gave before the tone map was in it (BT.2020 matrix, HDR codes
297/// shown as if they were SDR -- flat and grey-washed, which is the complaint
298/// this whole path answers). Colour has to come *up*, not down, and the picture
299/// has to land somewhere a display can show rather than at either rail.
300///
301/// Gated on the film being here: it is a 20 GB download, not a fixture. HEVC
302/// Main 10, so this is a hardware-only test in every sense.
303#[test]
304#[ignore = "needs libengine_hw.so, a VA-API driver and the film"]
305fn the_hdr_film_renders_tone_mapped() {
306 // Two minutes in: past the studio logos, inside lit footage.
307 const TARGET: u32 = 3000;
308 let Some(path) = engine::real_library::film("hevc_4k_hdr") else {
309 return;
310 };
311 let path = path.as_path();
312 // SAFETY: --test-threads=1. There is no software HEVC decoder, so a pinned
313 // VE_SW from another test in this binary would refuse the file outright.
314 unsafe { std::env::remove_var("VE_SW") };
315
316 // The old picture, by hand off the plugin's own planes: the funnel did
317 // exactly this before the tone map, and it is what the comparison needs.
318 let mut hw = HwSession::open_at(path, TARGET).expect("no plugin/driver available");
319 let (y, u, v, w, h) = hw
320 .next_frame()
321 .expect("hardware decode")
322 .expect("no frame at the seek");
323 let (w, h) = (w as usize, h as usize);
324 let (y, u, v) = (y.to_vec(), u.to_vec(), v.to_vec());
325 let untouched = i420_to_bgra(&color_of(path), &y, &u, &v, w, h);
326
327 // ...and the picture the engine shows now, through the funnel itself.
328 let (_, rx, _cancel) = DecodeSession::open_at(path, TARGET).expect("open the film");
329 let shown = rx.recv().expect("a frame off the funnel").bgra;
330 assert_eq!(shown.len(), untouched.len(), "frame size");
331
332 // Saturation, as the mean distance from grey per pixel...
333 let spread = |bgra: &[u8]| -> f64 {
334 let total: u64 = bgra
335 .chunks_exact(4)
336 .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap()))
337 .sum();
338 total as f64 / (bgra.len() / 4) as f64
339 };
340 // ...and mean luma, in the limited-range code the tone map's anchors are in.
341 let luma = |bgra: &[u8]| -> f64 {
342 let total: f64 = bgra
343 .chunks_exact(4)
344 .map(|px| {
345 0.2126 * f64::from(px[2]) + 0.7152 * f64::from(px[1]) + 0.0722 * f64::from(px[0])
346 })
347 .sum();
348 16.0 + 219.0 * (total / (bgra.len() / 4) as f64) / 255.0
349 };
350 let (was, now) = (spread(&untouched), spread(&shown));
351 eprintln!(
352 "frame {TARGET}: saturation {was:.1} -> {now:.1}, mean luma {:.1} -> {:.1}",
353 luma(&untouched),
354 luma(&shown)
355 );
356 assert!(
357 now > was,
358 "the tone-mapped frame is no more colourful: {now}"
359 );
360 let mean = luma(&shown);
361 assert!(
362 (24.0..=200.0).contains(&mean),
363 "the tone-mapped frame sits at one end of the scale: mean luma {mean}"
364 );
365
366 // The funnel's own budget at this size: the map plus the conversion, which
367 // is what an HDR frame costs on top of the decode. Fastest of five, for the
368 // reason `tonemap::perf_4k_and_1080p` documents.
369 let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default(), None);
370 let sdr = ColorDescription {
371 matrix: Matrix::Bt709,
372 transfer: engine::colorspace::Transfer::Sdr,
373 full_range: false,
374 };
375 let mut best = f64::MAX;
376 for _ in 0..5 {
377 let (mut my, mut mu, mut mv) = (y.clone(), u.clone(), v.clone());
378 let t = Instant::now();
379 mapper.map(&mut my, &mut mu, &mut mv, w, h);
380 let _ = i420_to_bgra(&sdr, &my, &mu, &mv, w, h);
381 best = best.min(t.elapsed().as_secs_f64() * 1000.0);
382 }
383 eprintln!("{w}x{h} tone map + convert: {best:.1} ms/frame");
384 assert!(best <= 39.0, "{best:.1} ms/frame over the 39 ms budget");
385}
386
387/// H.264 8-bit decode is bit-exact by conformance, so the two backends must
388/// agree. A mismatch means a driver deviation and is reported, not swallowed.
389#[test]
390#[ignore = "needs libengine_hw.so and a VA-API driver"]
391fn hardware_matches_software_on_frame_30() {
392 let (_, hw) = decode_all_hw("test_baseline.mp4");
393
394 // Pin the comparison side to software ourselves: without this, running the
395 // suite without VE_SW=1 would compare hardware against hardware and pass
396 // vacuously. SAFETY: the suite is documented to run with --test-threads=1.
397 unsafe { std::env::set_var("VE_SW", "1") };
398
399 let start = Instant::now();
400 let (_, rx) = DecodeSession::open(asset("test_baseline.mp4")).expect("software open");
401 let sw = rx
402 .into_iter()
403 .find(|f| f.index == 30)
404 .expect("software frame 30")
405 .bgra;
406 eprintln!("software reached frame 30 in {:?}", start.elapsed());
407
408 assert_eq!(hw.len(), sw.len(), "frame size");
409 let diff = hw.iter().zip(&sw).filter(|(a, b)| a != b).count();
410 eprintln!("frame 30 differing bytes: {diff} / {}", hw.len());
411 assert_eq!(diff, 0, "hardware and software decode disagree");
412}
413
414/// The AV1 twin of [`hardware_matches_software_on_frame_30`]: the plugin's
415/// VA-API decoder against the project's own `ec-av1`, whole file, byte for
416/// byte -- 8-bit AV1 decode is bit-exact by the same conformance argument the
417/// H.264 twin makes, and a mismatch means a deviation in one of the two
418/// decoders, reported rather than swallowed.
419#[test]
420#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
421fn av1_hardware_matches_software_on_every_frame() {
422 const NAME: &str = "test_av1.mkv";
423 let (hw_count, hw_frame_30) = decode_all_hw(NAME);
424
425 // Pin the comparison side to software ourselves: without this, running the
426 // suite without VE_SW=1 would compare hardware against hardware and pass
427 // vacuously. SAFETY: the suite is documented to run with --test-threads=1.
428 unsafe { std::env::set_var("VE_SW", "1") };
429 let path = asset(NAME);
430 let start = Instant::now();
431 let (meta, rx) = DecodeSession::open(&path).expect("software open");
432 let mut sw_count = 0usize;
433 let mut sw_frame_30 = Vec::new();
434 for frame in rx {
435 if frame.index == 30 {
436 sw_frame_30 = frame.bgra;
437 }
438 sw_count += 1;
439 }
440 let sw_elapsed = start.elapsed();
441 unsafe { std::env::remove_var("VE_SW") };
442 eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}");
443 assert_eq!(sw_count, hw_count, "frame count");
444 assert_eq!(sw_count, usize::try_from(meta.frame_count).expect("count"));
445 assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size");
446 let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count();
447 eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len());
448 assert_eq!(diff, 0, "hardware and software AV1 decode disagree");
449}
450
451/// The 10-bit twin: the plugin reads a P010 surface back as the high byte of
452/// each pair; `ec-av1` hands `u16` planes the seat downshifts by two. Same
453/// truncation, same picture -- or one of the two seats is wrong.
454#[test]
455#[ignore = "needs libengine_hw.so and a VA-API driver with 10-bit AV1 decode"]
456fn av1_ten_bit_hardware_matches_software_on_every_frame() {
457 const NAME: &str = "test_av1_10.mkv";
458 let (hw_count, hw_frame_30) = decode_all_hw(NAME);
459 // SAFETY: the suite is documented to run with --test-threads=1.
460 unsafe { std::env::set_var("VE_SW", "1") };
461 let path = asset(NAME);
462 let start = Instant::now();
463 let (_, rx) = DecodeSession::open(&path).expect("software open");
464 let mut sw_count = 0usize;
465 let mut sw_frame_30 = Vec::new();
466 for frame in rx {
467 if frame.index == 30 {
468 sw_frame_30 = frame.bgra;
469 }
470 sw_count += 1;
471 }
472 let sw_elapsed = start.elapsed();
473 unsafe { std::env::remove_var("VE_SW") };
474 eprintln!("{NAME}: hardware {hw_count} frames, software {sw_count} frames in {sw_elapsed:?}");
475 assert_eq!(sw_count, hw_count, "frame count");
476 assert_eq!(hw_frame_30.len(), sw_frame_30.len(), "frame size");
477 let diff = hw_frame_30.iter().zip(&sw_frame_30).filter(|(a, b)| a != b).count();
478 eprintln!("frame 30 differing bytes: {diff} / {}", sw_frame_30.len());
479 assert_eq!(diff, 0, "hardware and software 10-bit AV1 decode disagree");
480}
481
482/// Annex-B NAL payloads (start codes stripped, trailing zeros trimmed).
483fn nals(annex_b: &[u8]) -> Vec<&[u8]> {
484 let mut out = Vec::new();
485 let mut start = None;
486 let mut i = 0;
487 while i + 2 < annex_b.len() {
488 if annex_b[i] == 0 && annex_b[i + 1] == 0 && annex_b[i + 2] == 1 {
489 if let Some(s) = start {
490 out.push(&annex_b[s..i]);
491 }
492 i += 3;
493 start = Some(i);
494 } else {
495 i += 1;
496 }
497 }
498 if let Some(s) = start {
499 out.push(&annex_b[s..]);
500 }
501 out
502}
503
504/// One access unit as a length-prefixed AVCC sample with `cabac_zero_word` --
505/// `zeros` zero bytes -- inside the *last* coded NAL's declared length. That is
506/// byte-for-byte what a phone-camera encoder writes, and what a decoder that
507/// stops consuming at the last NAL leaves behind as "not a NAL".
508fn sample_with_trailing_zeros(annex_b: &[u8], zeros: usize) -> (Vec<u8>, bool) {
509 let mut coded: Vec<&[u8]> = Vec::new();
510 let mut key = false;
511 for nal in nals(annex_b) {
512 let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
513 let nal = &nal[..end];
514 if nal.is_empty() {
515 continue;
516 }
517 match nal[0] & 0x1f {
518 7 | 8 | 6 | 9 => continue, // parameter sets/SEI live in avcC or are dropped
519 5 => key = true,
520 _ => {}
521 }
522 coded.push(nal);
523 }
524 let mut sample = Vec::new();
525 let last = coded.len().saturating_sub(1);
526 for (i, nal) in coded.iter().enumerate() {
527 let len = nal.len() + if i == last { zeros } else { 0 };
528 sample.extend_from_slice(&(len as u32).to_be_bytes());
529 sample.extend_from_slice(nal);
530 if i == last {
531 sample.extend(std::iter::repeat_n(0u8, zeros));
532 }
533 }
534 (sample, key)
535}
536
537/// An mp4 cut from `test_baseline.mp4` whose every H.264 sample ends in four
538/// zero bytes.
539fn write_trailing_zero_fixture(src: &Path, out: &Path, frames: usize) {
540 let (meta, mut demuxer) = Demuxer::open(src).expect("open fixture source");
541 let first = demuxer.next_access_unit().expect("read").expect("au");
542 let (sps, pps) = mux::parameter_sets(&first).expect("parameter sets in the first au");
543 let mut muxer = Mp4Muxer::create(
544 out,
545 &VideoParams {
546 width: meta.width,
547 height: meta.height,
548 frame_rate: meta.frame_rate,
549 sps,
550 pps,
551 },
552 None,
553 )
554 .expect("create fixture");
555 let (sample, key) = sample_with_trailing_zeros(&first, 4);
556 muxer.write_coded_sample(&sample, key).expect("first sample");
557 for _ in 1..frames {
558 let Some(au) = demuxer.next_access_unit().expect("read") else {
559 break;
560 };
561 let (sample, key) = sample_with_trailing_zeros(&au, 4);
562 muxer.write_coded_sample(&sample, key).expect("sample");
563 }
564 muxer.finish().expect("finish fixture");
565}
566
567/// A phone-camera mp4 ends its every coded sample in `cabac_zero_word`. The
568/// plugin consumed each access unit only up to the last NAL cros-codecs
569/// reported and fed the leftover zero bytes back as if they were the next unit;
570/// `Nalu::next` refuses a buffer with no start code ("No NAL found"), so the
571/// whole session failed with code -2 before the first picture -- the export's
572/// `hardware decode failed (code -2)` on a file VA-API otherwise decodes.
573#[test]
574#[ignore = "needs libengine_hw.so and a VA-API driver"]
575fn hardware_decodes_samples_with_trailing_zero_words() {
576 let out = Scratch::file("ve_hw_trailing_zeros", "mp4");
577 write_trailing_zero_fixture(&asset("test_baseline.mp4"), &out, 30);
578 let mut hw = open_hw(&out);
579 let mut count = 0usize;
580 while let Some((_, _, _, w, h)) = hw
581 .next_frame()
582 .expect("hardware decode of trailing-zero samples")
583 {
584 assert_eq!((w, h), (1280, 720), "frame {count} dims");
585 count += 1;
586 }
587 assert_eq!(count, 30, "every picture decoded");
588}