forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

hw_encode.rs518 lines, 20.0 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 (`ec-h264` driven by hand, not `DecodeSession`), so a bug in the
13//! session plumbing cannot cancel out a plugin bug; the independent witness for
14//! the stream's well-formedness is ffmpeg, in the export suite.
15
16#[path = "support/hwchild.rs"]
17mod hwchild;
18
19use std::time::{Duration, Instant};
20
21use engine::hw::{HwEncoder, HwPicture, HwSession};
22use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
23use ec_core::{Packet, TimeBase};
24use ec_h264::H264Decoder;
25
26const FPS: u32 = 30;
27const BITRATE: u64 = 4_000_000;
28
29/// A moving diagonal gradient: something that actually costs bits, so the
30/// encoder cannot make the whole test pass by emitting skip frames.
31fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
32 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
33 let mut y = vec![0u8; width * height];
34 for row in 0..height {
35 for col in 0..width {
36 y[row * width + col] = (row + col + index as usize * 5) as u8;
37 }
38 }
39 let u = vec![64u8.wrapping_add(index as u8); cw * ch];
40 let v = vec![192u8.wrapping_sub(index as u8); cw * ch];
41 (y, u, v)
42}
43
44/// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus
45/// the number of access units the plugin handed back.
46fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> {
47 let mut encoder = HwEncoder::open(width, height, FPS, 1, BITRATE)?;
48 let mut stream = Vec::new();
49 let mut units = 0;
50 // Timed around the plugin call only: building the synthetic picture is not
51 // part of what an export would pay.
52 let mut spent = Duration::ZERO;
53 for index in 0..count {
54 let (y, u, v) = synthetic(index, width as usize, height as usize);
55 let started = Instant::now();
56 let coded = encoder
57 .encode(&y, &u, &v, width, height, false)
58 .expect("encode");
59 if let Some(au) = coded {
60 stream.extend_from_slice(au);
61 units += 1;
62 }
63 spent += started.elapsed();
64 }
65 while let Some(au) = encoder.drain().expect("drain") {
66 stream.extend_from_slice(au);
67 units += 1;
68 }
69 let per_frame = spent.as_secs_f64() * 1000.0 / count as f64;
70 println!("{width}x{height}: {count} frames, {units} AUs, {per_frame:.2} ms/frame");
71 Some((stream, units))
72}
73
74fn decode(stream: &[u8]) -> Vec<Decoded> {
75 let mut decoder =
76 H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec-h264 takes its codec id");
77 let mut frames = Vec::new();
78 for au in access_units(stream) {
79 decoder
80 .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice()))
81 .expect("software decode of the hardware-encoded stream");
82 collect(&mut decoder, &mut frames);
83 }
84 decoder
85 .flush()
86 .expect("flush of the hardware-encoded stream");
87 collect(&mut decoder, &mut frames);
88 frames
89}
90
91/// Takes everything the decoder has released so far.
92fn collect(decoder: &mut H264Decoder, frames: &mut Vec<Decoded>) {
93 while let Ok(frame) = decoder.receive_frame() {
94 let ec_core::frame::Frame::Video(pic) = frame else {
95 continue;
96 };
97 frames.push(Decoded {
98 width: pic.width as usize,
99 height: pic.height as usize,
100 y: pic.planes[0].data[..].to_vec(),
101 u: pic.planes[1].data[..].to_vec(),
102 v: pic.planes[2].data[..].to_vec(),
103 });
104 }
105}
106
107/// One decoded picture as plain planes, whatever the decoder calls them.
108struct Decoded {
109 width: usize,
110 height: usize,
111 y: Vec<u8>,
112 u: Vec<u8>,
113 v: Vec<u8>,
114}
115
116/// Splits an Annex-B stream into access units: a new one at each slice NAL
117/// that follows a picture, parameter sets and SEI riding with the slice that
118/// follows them. The plugin emits one AU per picture; the split exists so the
119/// decoder sees the packet shape a demuxer hands it for a file.
120fn access_units(stream: &[u8]) -> Vec<Vec<u8>> {
121 // (offset of the start code, its length); the sentinel ends the last NAL.
122 let mut bounds: Vec<(usize, usize)> = Vec::new();
123 let mut i = 0;
124 while i + 2 < stream.len() {
125 if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 {
126 bounds.push(if i > 0 && stream[i - 1] == 0 {
127 (i - 1, 4)
128 } else {
129 (i, 3)
130 });
131 i += 3;
132 } else {
133 i += 1;
134 }
135 }
136 bounds.push((stream.len(), 0));
137 let mut aus: Vec<Vec<u8>> = Vec::new();
138 let mut current: Vec<u8> = Vec::new();
139 let mut has_slice = false;
140 for pair in bounds.windows(2) {
141 let (at, sc) = pair[0];
142 let nal = &stream[at..pair[1].0];
143 let kind = nal[sc] & 0x1f;
144 let slice = kind == 1 || kind == 5;
145 if slice && has_slice {
146 aus.push(std::mem::take(&mut current));
147 has_slice = false;
148 }
149 current.extend_from_slice(nal);
150 has_slice |= slice;
151 }
152 if !current.is_empty() {
153 aus.push(current);
154 }
155 aus
156}
157
158fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
159 assert_eq!(a.len(), b.len());
160 a.iter()
161 .zip(b)
162 .map(|(x, y)| x.abs_diff(*y) as f64)
163 .sum::<f64>()
164 / a.len() as f64
165}
166
167#[test]
168#[ignore]
169fn round_trips_sixty_frames() {
170 hwchild::require();
171 let (width, height) = (1280u32, 720u32);
172 let (stream, units) =
173 encode(width, height, 60).expect("no hardware encode plugin/driver available");
174 assert_eq!(units, 60, "one access unit per fed picture");
175
176 let frames = decode(&stream);
177 assert_eq!(frames.len(), 60, "decoded picture count");
178 for (index, frame) in frames.iter().enumerate() {
179 assert_eq!(
180 (frame.width, frame.height),
181 (width as usize, height as usize),
182 "frame {index} dimensions"
183 );
184 }
185
186 // The pictures have to survive the I420 -> NV12 upload, not merely exist:
187 // a dropped plane or a swapped U/V would sail past a count-only check.
188 // Tolerances are generous because this is lossy CBR, but nowhere near the
189 // ~64 a U/V swap costs on these chroma values.
190 for index in [0usize, 30, 59] {
191 let (y, u, v) = synthetic(index as u32, width as usize, height as usize);
192 let frame = &frames[index];
193 for (plane, (got, want)) in [(&frame.y, &y), (&frame.u, &u), (&frame.v, &v)]
194 .iter()
195 .enumerate()
196 {
197 let diff = mean_abs_diff(got, want);
198 println!("frame {index} plane {plane}: mean abs diff {diff:.2}");
199 assert!(
200 diff < 6.0,
201 "frame {index} plane {plane} drifted by {diff:.2}"
202 );
203 }
204 }
205}
206
207/// 322x242 is even (NV12 needs that) but neither dimension is a multiple of 16,
208/// so the surface is padded and the encoded stream has to crop it back. This is
209/// the 1080p case in miniature: 1080 pads to 1088.
210#[test]
211#[ignore]
212fn round_trips_unaligned_dimensions() {
213 hwchild::require();
214 let (width, height) = (322u32, 242u32);
215 let Some((stream, units)) = encode(width, height, 10) else {
216 println!("driver refused {width}x{height}, software encode would take over -- skipping");
217 return;
218 };
219 assert_eq!(units, 10);
220
221 let frames = decode(&stream);
222 assert_eq!(frames.len(), 10);
223 assert_eq!(
224 (frames[0].width, frames[0].height),
225 (width as usize, height as usize),
226 "padding must be cropped away again"
227 );
228}
229
230/// The zero-copy path: a picture the hardware decoder wrote goes into the
231/// hardware encoder as the buffer it was decoded into, never read back and never
232/// written out again -- which is what makes an export of an untouched clip cost
233/// no `vaGetImage`, no colour conversion and no upload per frame.
234///
235/// Two things are checked and the second is the one that matters. That the
236/// buffers are handed over *at all* (a driver whose export the plugin refuses
237/// falls back to pixels, silently and correctly, which would make a speed claim
238/// a lie). And that what came out is what went in: the encoded stream is decoded
239/// in software and compared against the same file decoded through the read-back
240/// path, so a wrong plane offset, a swapped object or an unsynchronised surface
241/// -- the ways an imported buffer goes wrong -- fails here instead of shipping
242/// as a garbled export.
243#[test]
244#[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"]
245fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
246 hwchild::require();
247 const FRAMES: usize = 24;
248 let asset =
249 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
250 let (width, height) = (1280u32, 720u32);
251 let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else {
252 println!("no hardware encoder here -- skipping");
253 return;
254 };
255 let Some(want) = encoder.dma_want(width, height) else {
256 panic!("a hardware encoder that takes no imported buffer at all");
257 };
258 let mut session = HwSession::open(&asset).expect("hardware decode of the fixture");
259
260 let mut stream = Vec::new();
261 let mut buffers = 0;
262 for index in 0..FRAMES {
263 match session.next_frame_dma(want).expect("hardware decode") {
264 Some(HwPicture::Dma(dma)) => {
265 assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}");
266 buffers += 1;
267 if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") {
268 stream.extend_from_slice(au);
269 }
270 }
271 Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"),
272 None => panic!("the fixture ran out at frame {index}"),
273 }
274 }
275 while let Some(au) = encoder.drain().expect("drain") {
276 stream.extend_from_slice(au);
277 }
278 assert_eq!(buffers, FRAMES, "every picture came over as a buffer");
279
280 // The same file down the path this one exists to avoid, which is the only
281 // honest reference for "the encoder read the right pixels".
282 let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture");
283 let coded = decode(&stream);
284 assert_eq!(coded.len(), FRAMES, "decoded picture count");
285 for (index, frame) in coded.iter().enumerate() {
286 let (y, u, v, w, h) = reference
287 .next_frame()
288 .expect("read-back decode")
289 .expect("the fixture is longer than this");
290 assert_eq!((w, h), (width, height), "frame {index}");
291 for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)]
292 .iter()
293 .enumerate()
294 {
295 // Lossy CBR against the source picture: the same tolerance the
296 // synthetic round trip above uses, and nowhere near what a swapped
297 // plane or a stale surface would cost.
298 let diff = mean_abs_diff(got, want);
299 assert!(
300 diff < 6.0,
301 "frame {index} plane {plane} drifted by {diff:.2}"
302 );
303 }
304 }
305}
306
307/// What the process boundary costs, at the size an export is really written at.
308///
309/// The encoder lives in a child now ([`engine::hwproc`]) so that a driver's
310/// `abort()` cannot take the editor with it, and the price of that has to be
311/// small enough that nobody would trade it back: pictures reach the child
312/// through a shared mapping rather than down a pipe, so a frame costs one
313/// `memcpy` and a ten-byte message. `VE_HW_INPROCESS` pins the seat the way it
314/// used to be, which is the only honest baseline there is.
315///
316/// This is the *worst* case on purpose: an untouched clip's pictures never leave
317/// the GPU at all (`a_decoded_buffer_is_encoded_without_ever_being_read_back`,
318/// whose descriptors cross the same socket), so nothing an export really does is
319/// slower than this.
320#[test]
321#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"]
322fn isolating_the_encoder_costs_little_at_1080p() {
323 hwchild::require();
324 const FRAMES: u32 = 60;
325 let (width, height) = (1920u32, 1080u32);
326 let mut spent = Vec::new();
327 for inprocess in [true, false] {
328 // The ignored run is `--test-threads=1`, which is what this file's own
329 // header already requires of its env pins.
330 match inprocess {
331 true => engine::envcfg::set("VE_HW_INPROCESS", "1"),
332 false => engine::envcfg::unset("VE_HW_INPROCESS"),
333 }
334 let started = Instant::now();
335 let Some((_, units)) = encode(width, height, FRAMES) else {
336 println!("no hardware encoder here -- skipping");
337 return;
338 };
339 assert_eq!(units, FRAMES, "one access unit per fed picture");
340 spent.push(started.elapsed().as_secs_f64());
341 }
342 let (local, remote) = (spent[0], spent[1]);
343 println!(
344 "1080p x{FRAMES}: in-process {:.1} fps, isolated {:.1} fps ({:.0}% of it)",
345 f64::from(FRAMES) / local,
346 f64::from(FRAMES) / remote,
347 100.0 * local / remote
348 );
349 assert!(
350 local / remote >= 0.85,
351 "isolation kept only {:.0}% of the in-process rate",
352 100.0 * local / remote
353 );
354}
355
356/// Decode and encode resolve through two independent symbol tables, so an
357/// encoder that cannot load must not cost us the decoder (and vice versa).
358///
359/// This is the positive half only: the negative half -- a plugin built without
360/// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's
361/// verifier, not here.
362#[test]
363#[ignore]
364fn decode_and_encode_load_independently() {
365 hwchild::require();
366 let asset =
367 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
368 assert!(
369 HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(),
370 "encode table"
371 );
372 assert!(HwSession::open(&asset).is_some(), "decode table");
373 // Order reversed: neither table's `OnceLock` may have primed the other.
374 assert!(HwSession::open(&asset).is_some());
375 assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());
376}
377
378/// Per slice: `(is_idr, frame_num, pic_order_cnt_lsb)`, read by [`slice_counters`].
379type SliceCounters = Vec<(bool, u32, Option<u32>)>;
380
381/// Walks the Annex B stream and reads, per slice, `(is_idr, frame_num,
382/// pic_order_cnt_lsb)`, plus the SPS `level_idc`. Main profile, POC type 0 and
383/// frame_mbs_only -- the SPS the vendored encoder writes -- is all this reads;
384/// the test fails loudly on anything else rather than guessing.
385fn slice_counters(stream: &[u8]) -> (u8, u32, SliceCounters) {
386 struct Bits<'a>(&'a [u8], usize);
387 impl Bits<'_> {
388 fn bit(&mut self) -> u32 {
389 let b = (self.0[self.1 / 8] >> (7 - self.1 % 8)) & 1;
390 self.1 += 1;
391 u32::from(b)
392 }
393 fn bits(&mut self, n: u32) -> u32 {
394 (0..n).fold(0, |v, _| (v << 1) | self.bit())
395 }
396 fn ue(&mut self) -> u32 {
397 let mut zeros = 0;
398 while self.bit() == 0 {
399 zeros += 1;
400 }
401 (1 << zeros) - 1 + self.bits(zeros)
402 }
403 }
404 fn unescape(bytes: &[u8]) -> Vec<u8> {
405 let mut out = Vec::with_capacity(bytes.len());
406 let mut zeros = 0;
407 for &b in bytes {
408 if zeros >= 2 && b == 3 {
409 zeros = 0;
410 continue;
411 }
412 out.push(b);
413 zeros = if b == 0 { zeros + 1 } else { 0 };
414 }
415 out
416 }
417 let mut nals = Vec::new();
418 let mut i = 0;
419 while i + 3 <= stream.len() {
420 if stream[i..i + 3] == [0, 0, 1] {
421 nals.push(i + 3);
422 i += 3;
423 } else {
424 i += 1;
425 }
426 }
427 let (mut level, mut log2_fn, mut log2_poc) = (0u8, 0u32, 0u32);
428 let mut out = Vec::new();
429 for (n, &s) in nals.iter().enumerate() {
430 let e = nals.get(n + 1).map_or(stream.len(), |&x| x - 3);
431 let kind = stream[s] & 0x1f;
432 // Only the header is needed; 64 bytes of RBSP covers every field read.
433 let rbsp = unescape(&stream[s + 1..e.min(s + 1 + 64)]);
434 let mut b = Bits(&rbsp, 0);
435 match kind {
436 7 => {
437 let profile = b.bits(8);
438 assert_eq!(profile, 77, "Main profile SPS expected");
439 b.bits(8);
440 level = b.bits(8) as u8;
441 b.ue();
442 log2_fn = b.ue() + 4;
443 // Type 0 carries `pic_order_cnt_lsb` in every slice; type 2 derives
444 // the order from `frame_num` (legal without B-frames) and carries
445 // no lsb at all, which is what ec-hw writes.
446 match b.ue() {
447 0 => log2_poc = b.ue() + 4,
448 2 => log2_poc = 0,
449 other => panic!("pic_order_cnt_type {other} is not one this encoder writes"),
450 }
451 }
452 1 | 5 => {
453 assert!(log2_fn > 0, "slice before any SPS");
454 b.ue();
455 b.ue();
456 b.ue();
457 let frame_num = b.bits(log2_fn);
458 if kind == 5 {
459 b.ue();
460 }
461 let poc = (log2_poc > 0).then(|| b.bits(log2_poc));
462 out.push((kind == 5, frame_num, poc));
463 }
464 _ => {}
465 }
466 }
467 (level, 1 << log2_fn, out)
468}
469
470/// The driver on this box writes `frame_num = 0` and `pic_order_cnt_lsb = 0`
471/// into every slice it codes (mesa radeonsi 26.1.7, measured on three real
472/// exports); phones' stateful decoders then judder every few seconds. The
473/// plugin rewrites both, and this is the stream-level proof: over two GOPs the
474/// counters step the way 7.4.3 wants, restart at the second IDR, and the level
475/// is the one Table A-1 gives 1080p30 -- not the `L4` that used to be
476/// hard-coded for every size. `HW_ENCODE_DUMP=<path>` keeps the stream for
477/// `ffmpeg -bsf:v trace_headers`.
478#[test]
479#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"]
480fn slice_headers_carry_frame_num_and_poc() {
481 hwchild::require();
482 let (width, height) = (1920u32, 1080u32);
483 let count = 100; // a 2 s GOP at 30 fps is 60: two IDRs, frame_num wraps at 32
484 let (stream, units) =
485 encode(width, height, count).expect("no hardware encode plugin/driver available");
486 assert_eq!(units, count);
487 if let Ok(path) = std::env::var("HW_ENCODE_DUMP") {
488 std::fs::write(&path, &stream).expect("dump");
489 println!("stream written to {path}");
490 }
491 let (level, max_frame_num, slices) = slice_counters(&stream);
492 assert_eq!(level, 40, "1920x1080 at 30 fps is level 4.0");
493 assert_eq!(slices.len() as u32, count, "one slice per picture");
494 let idrs: Vec<usize> = slices
495 .iter()
496 .enumerate()
497 .filter(|(_, s)| s.0)
498 .map(|(i, _)| i)
499 .collect();
500 assert_eq!(idrs, vec![0, 60], "an IDR every 2 s GOP");
501 let mut since_idr = 0u32;
502 for (i, &(idr, frame_num, poc)) in slices.iter().enumerate() {
503 if idr {
504 since_idr = 0;
505 }
506 // The modulus is the SPS's own: the encoder picks it, and it need not be 32.
507 assert_eq!(frame_num, since_idr % max_frame_num, "slice {i} frame_num");
508 // Type 2 has no lsb to check: its order is the frame_num's, checked above.
509 if let Some(poc) = poc {
510 assert_eq!(poc, (since_idr * 2) % 64, "slice {i} pic_order_cnt_lsb");
511 }
512 since_idr += 1;
513 }
514 let distinct: std::collections::BTreeSet<u32> = slices.iter().map(|s| s.1).collect();
515 assert!(distinct.len() > 1, "frame_num never moved -- the rewrite did not run");
516 // The rewrite is header-only: the picture still decodes.
517 assert_eq!(decode(&stream).len(), count as usize);
518}