forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

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