forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

hw_encode.rs162 lines, 5.9 KiBHistoryRawDownload
1//! Hardware encode checks. These need a built `libengine_hw.so` plus a working
2//! VA-API driver with an H.264 encode entrypoint, so they are `#[ignore]`d by
3//! default. Run them with:
4//!
5//! ```text
6//! cargo build --workspace --release
7//! LD_LIBRARY_PATH=target/release \
8//! cargo test -p engine --release --test hw_encode -- --ignored --nocapture --test-threads=1
9//! ```
10//!
11//! The round trip goes out through the plugin and back in through the *software*
12//! decoder (`rusty_h264` directly, not `DecodeSession`), so a bug on one side
13//! cannot cancel out a bug on the other.
14
15use std::time::{Duration, Instant};
16
17use engine::hw::{HwEncoder, HwSession};
18
19const FPS: u32 = 30;
20const BITRATE: u64 = 4_000_000;
21
22/// A moving diagonal gradient: something that actually costs bits, so the
23/// encoder cannot make the whole test pass by emitting skip frames.
24fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
25 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
26 let mut y = vec![0u8; width * height];
27 for row in 0..height {
28 for col in 0..width {
29 y[row * width + col] = (row + col + index as usize * 5) as u8;
30 }
31 }
32 let u = vec![64u8.wrapping_add(index as u8); cw * ch];
33 let v = vec![192u8.wrapping_sub(index as u8); cw * ch];
34 (y, u, v)
35}
36
37/// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus
38/// the number of access units the plugin handed back.
39fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> {
40 let mut encoder = HwEncoder::open(width, height, FPS, 1, BITRATE)?;
41 let mut stream = Vec::new();
42 let mut units = 0;
43 // Timed around the plugin call only: building the synthetic picture is not
44 // part of what an export would pay.
45 let mut spent = Duration::ZERO;
46 for index in 0..count {
47 let (y, u, v) = synthetic(index, width as usize, height as usize);
48 let started = Instant::now();
49 let coded = encoder
50 .encode(&y, &u, &v, width, height, false)
51 .expect("encode");
52 if let Some(au) = coded {
53 stream.extend_from_slice(au);
54 units += 1;
55 }
56 spent += started.elapsed();
57 }
58 while let Some(au) = encoder.drain().expect("drain") {
59 stream.extend_from_slice(au);
60 units += 1;
61 }
62 let per_frame = spent.as_secs_f64() * 1000.0 / count as f64;
63 println!("{width}x{height}: {count} frames, {units} AUs, {per_frame:.2} ms/frame");
64 Some((stream, units))
65}
66
67fn decode(stream: &[u8]) -> Vec<rusty_h264::YuvFrame> {
68 rusty_h264::Decoder::new()
69 .decode_stream(stream)
70 .expect("software decode of the hardware-encoded stream")
71}
72
73fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
74 assert_eq!(a.len(), b.len());
75 a.iter()
76 .zip(b)
77 .map(|(x, y)| x.abs_diff(*y) as f64)
78 .sum::<f64>()
79 / a.len() as f64
80}
81
82#[test]
83#[ignore]
84fn round_trips_sixty_frames() {
85 let (width, height) = (1280u32, 720u32);
86 let (stream, units) =
87 encode(width, height, 60).expect("no hardware encode plugin/driver available");
88 assert_eq!(units, 60, "one access unit per fed picture");
89
90 let frames = decode(&stream);
91 assert_eq!(frames.len(), 60, "decoded picture count");
92 for (index, frame) in frames.iter().enumerate() {
93 assert_eq!(
94 (frame.width, frame.height),
95 (width as usize, height as usize),
96 "frame {index} dimensions"
97 );
98 }
99
100 // The pictures have to survive the I420 -> NV12 upload, not merely exist:
101 // a dropped plane or a swapped U/V would sail past a count-only check.
102 // Tolerances are generous because this is lossy CBR, but nowhere near the
103 // ~64 a U/V swap costs on these chroma values.
104 for index in [0usize, 30, 59] {
105 let (y, u, v) = synthetic(index as u32, width as usize, height as usize);
106 let frame = &frames[index];
107 for (plane, (got, want)) in [(&frame.y, &y), (&frame.u, &u), (&frame.v, &v)]
108 .iter()
109 .enumerate()
110 {
111 let diff = mean_abs_diff(got, want);
112 println!("frame {index} plane {plane}: mean abs diff {diff:.2}");
113 assert!(
114 diff < 6.0,
115 "frame {index} plane {plane} drifted by {diff:.2}"
116 );
117 }
118 }
119}
120
121/// 322x242 is even (NV12 needs that) but neither dimension is a multiple of 16,
122/// so the surface is padded and the encoded stream has to crop it back. This is
123/// the 1080p case in miniature: 1080 pads to 1088.
124#[test]
125#[ignore]
126fn round_trips_unaligned_dimensions() {
127 let (width, height) = (322u32, 242u32);
128 let Some((stream, units)) = encode(width, height, 10) else {
129 println!("driver refused {width}x{height}, software encode would take over -- skipping");
130 return;
131 };
132 assert_eq!(units, 10);
133
134 let frames = decode(&stream);
135 assert_eq!(frames.len(), 10);
136 assert_eq!(
137 (frames[0].width, frames[0].height),
138 (width as usize, height as usize),
139 "padding must be cropped away again"
140 );
141}
142
143/// Decode and encode resolve through two independent symbol tables, so an
144/// encoder that cannot load must not cost us the decoder (and vice versa).
145///
146/// This is the positive half only: the negative half -- a plugin built without
147/// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's
148/// verifier, not here.
149#[test]
150#[ignore]
151fn decode_and_encode_load_independently() {
152 let asset =
153 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
154 assert!(
155 HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(),
156 "encode table"
157 );
158 assert!(HwSession::open(&asset).is_some(), "decode table");
159 // Order reversed: neither table's `OnceLock` may have primed the other.
160 assert!(HwSession::open(&asset).is_some());
161 assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());
162}