forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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