forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcda6d0eTahinli3 months ago476 commits

hw_encode.rs288 lines, 11.6 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, HwPicture, 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/// The zero-copy path: a picture the hardware decoder wrote goes into the
144/// hardware encoder as the buffer it was decoded into, never read back and never
145/// written out again -- which is what makes an export of an untouched clip cost
146/// no `vaGetImage`, no colour conversion and no upload per frame.
147///
148/// Two things are checked and the second is the one that matters. That the
149/// buffers are handed over *at all* (a driver whose export the plugin refuses
150/// falls back to pixels, silently and correctly, which would make a speed claim
151/// a lie). And that what came out is what went in: the encoded stream is decoded
152/// in software and compared against the same file decoded through the read-back
153/// path, so a wrong plane offset, a swapped object or an unsynchronised surface
154/// -- the ways an imported buffer goes wrong -- fails here instead of shipping
155/// as a garbled export.
156#[test]
157#[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"]
158fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
159 const FRAMES: usize = 24;
160 let asset =
161 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
162 let (width, height) = (1280u32, 720u32);
163 let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else {
164 println!("no hardware encoder here -- skipping");
165 return;
166 };
167 let Some(want) = encoder.dma_want(width, height) else {
168 panic!("a hardware encoder that takes no imported buffer at all");
169 };
170 let mut session = HwSession::open(&asset).expect("hardware decode of the fixture");
171
172 let mut stream = Vec::new();
173 let mut buffers = 0;
174 for index in 0..FRAMES {
175 match session.next_frame_dma(want).expect("hardware decode") {
176 Some(HwPicture::Dma(dma)) => {
177 assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}");
178 buffers += 1;
179 if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") {
180 stream.extend_from_slice(au);
181 }
182 }
183 Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"),
184 None => panic!("the fixture ran out at frame {index}"),
185 }
186 }
187 while let Some(au) = encoder.drain().expect("drain") {
188 stream.extend_from_slice(au);
189 }
190 assert_eq!(buffers, FRAMES, "every picture came over as a buffer");
191
192 // The same file down the path this one exists to avoid, which is the only
193 // honest reference for "the encoder read the right pixels".
194 let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture");
195 let coded = decode(&stream);
196 assert_eq!(coded.len(), FRAMES, "decoded picture count");
197 for (index, frame) in coded.iter().enumerate() {
198 let (y, u, v, w, h) = reference
199 .next_frame()
200 .expect("read-back decode")
201 .expect("the fixture is longer than this");
202 assert_eq!((w, h), (width, height), "frame {index}");
203 for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)]
204 .iter()
205 .enumerate()
206 {
207 // Lossy CBR against the source picture: the same tolerance the
208 // synthetic round trip above uses, and nowhere near what a swapped
209 // plane or a stale surface would cost.
210 let diff = mean_abs_diff(got, want);
211 assert!(
212 diff < 6.0,
213 "frame {index} plane {plane} drifted by {diff:.2}"
214 );
215 }
216 }
217}
218
219/// What the process boundary costs, at the size an export is really written at.
220///
221/// The encoder lives in a child now ([`engine::hwproc`]) so that a driver's
222/// `abort()` cannot take the editor with it, and the price of that has to be
223/// small enough that nobody would trade it back: pictures reach the child
224/// through a shared mapping rather than down a pipe, so a frame costs one
225/// `memcpy` and a ten-byte message. `VE_HW_INPROCESS` pins the seat the way it
226/// used to be, which is the only honest baseline there is.
227///
228/// This is the *worst* case on purpose: an untouched clip's pictures never leave
229/// the GPU at all (`a_decoded_buffer_is_encoded_without_ever_being_read_back`,
230/// whose descriptors cross the same socket), so nothing an export really does is
231/// slower than this.
232#[test]
233#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"]
234fn isolating_the_encoder_costs_little_at_1080p() {
235 const FRAMES: u32 = 60;
236 let (width, height) = (1920u32, 1080u32);
237 let mut spent = Vec::new();
238 for inprocess in [true, false] {
239 // SAFETY-of-a-sort: the ignored run is `--test-threads=1`, which is
240 // what this file's own header already requires of its env pins.
241 unsafe {
242 match inprocess {
243 true => std::env::set_var("VE_HW_INPROCESS", "1"),
244 false => std::env::remove_var("VE_HW_INPROCESS"),
245 }
246 }
247 let started = Instant::now();
248 let Some((_, units)) = encode(width, height, FRAMES) else {
249 println!("no hardware encoder here -- skipping");
250 return;
251 };
252 assert_eq!(units, FRAMES, "one access unit per fed picture");
253 spent.push(started.elapsed().as_secs_f64());
254 }
255 let (local, remote) = (spent[0], spent[1]);
256 println!(
257 "1080p x{FRAMES}: in-process {:.1} fps, isolated {:.1} fps ({:.0}% of it)",
258 f64::from(FRAMES) / local,
259 f64::from(FRAMES) / remote,
260 100.0 * local / remote
261 );
262 assert!(
263 local / remote >= 0.85,
264 "isolation kept only {:.0}% of the in-process rate",
265 100.0 * local / remote
266 );
267}
268
269/// Decode and encode resolve through two independent symbol tables, so an
270/// encoder that cannot load must not cost us the decoder (and vice versa).
271///
272/// This is the positive half only: the negative half -- a plugin built without
273/// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's
274/// verifier, not here.
275#[test]
276#[ignore]
277fn decode_and_encode_load_independently() {
278 let asset =
279 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
280 assert!(
281 HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(),
282 "encode table"
283 );
284 assert!(HwSession::open(&asset).is_some(), "decode table");
285 // Order reversed: neither table's `OnceLock` may have primed the other.
286 assert!(HwSession::open(&asset).is_some());
287 assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());
288}