//! Hardware encode checks. These need a built `libengine_hw.so` plus a working //! VA-API driver with an H.264 encode entrypoint, so they are `#[ignore]`d by //! default. Run them with: //! //! ```text //! cargo build --workspace --release //! LD_LIBRARY_PATH=target/release \ //! cargo test -p engine --release --test hw_encode -- --ignored --nocapture --test-threads=1 //! ``` //! //! The round trip goes out through the plugin and back in through the *software* //! decoder (`ec-h264` driven by hand, not `DecodeSession`), so a bug in the //! session plumbing cannot cancel out a plugin bug; the independent witness for //! the stream's well-formedness is ffmpeg, in the export suite. #[path = "support/hwchild.rs"] mod hwchild; use std::time::{Duration, Instant}; use engine::hw::{HwEncoder, HwPicture, HwSession}; use engine::hwproc::SeatRate; use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; use ec_core::{Packet, TimeBase}; use ec_h264::H264Decoder; const FPS: u32 = 30; const BITRATE: u64 = 4_000_000; /// A moving diagonal gradient: something that actually costs bits, so the /// encoder cannot make the whole test pass by emitting skip frames. fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec) { let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); let mut y = vec![0u8; width * height]; for row in 0..height { for col in 0..width { y[row * width + col] = (row + col + index as usize * 5) as u8; } } let u = vec![64u8.wrapping_add(index as u8); cw * ch]; let v = vec![192u8.wrapping_sub(index as u8); cw * ch]; (y, u, v) } /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus /// the number of access units the plugin handed back. fn encode(width: u32, height: u32, count: u32) -> Option<(Vec, u32)> { let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None)?; let mut stream = Vec::new(); let mut units = 0; // Timed around the plugin call only: building the synthetic picture is not // part of what an export would pay. let mut spent = Duration::ZERO; for index in 0..count { let (y, u, v) = synthetic(index, width as usize, height as usize); let started = Instant::now(); let coded = encoder .encode(&y, &u, &v, width, height, false) .expect("encode"); if let Some(au) = coded { stream.extend_from_slice(au); units += 1; } spent += started.elapsed(); } while let Some(au) = encoder.drain().expect("drain") { stream.extend_from_slice(au); units += 1; } let per_frame = spent.as_secs_f64() * 1000.0 / count as f64; println!("{width}x{height}: {count} frames, {units} AUs, {per_frame:.2} ms/frame"); Some((stream, units)) } fn decode(stream: &[u8]) -> Vec { let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec-h264 takes its codec id"); let mut frames = Vec::new(); for au in access_units(stream) { decoder .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice())) .expect("software decode of the hardware-encoded stream"); collect(&mut decoder, &mut frames); } decoder .flush() .expect("flush of the hardware-encoded stream"); collect(&mut decoder, &mut frames); frames } /// Takes everything the decoder has released so far. fn collect(decoder: &mut H264Decoder, frames: &mut Vec) { while let Ok(frame) = decoder.receive_frame() { let ec_core::frame::Frame::Video(pic) = frame else { continue; }; frames.push(Decoded { width: pic.width as usize, height: pic.height as usize, y: pic.planes[0].data[..].to_vec(), u: pic.planes[1].data[..].to_vec(), v: pic.planes[2].data[..].to_vec(), }); } } /// One decoded picture as plain planes, whatever the decoder calls them. struct Decoded { width: usize, height: usize, y: Vec, u: Vec, v: Vec, } /// Splits an Annex-B stream into access units: a new one at each slice NAL /// that follows a picture, parameter sets and SEI riding with the slice that /// follows them. The plugin emits one AU per picture; the split exists so the /// decoder sees the packet shape a demuxer hands it for a file. fn access_units(stream: &[u8]) -> Vec> { // (offset of the start code, its length); the sentinel ends the last NAL. let mut bounds: Vec<(usize, usize)> = Vec::new(); let mut i = 0; while i + 2 < stream.len() { if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 { bounds.push(if i > 0 && stream[i - 1] == 0 { (i - 1, 4) } else { (i, 3) }); i += 3; } else { i += 1; } } bounds.push((stream.len(), 0)); let mut aus: Vec> = Vec::new(); let mut current: Vec = Vec::new(); let mut has_slice = false; for pair in bounds.windows(2) { let (at, sc) = pair[0]; let nal = &stream[at..pair[1].0]; let kind = nal[sc] & 0x1f; let slice = kind == 1 || kind == 5; if slice && has_slice { aus.push(std::mem::take(&mut current)); has_slice = false; } current.extend_from_slice(nal); has_slice |= slice; } if !current.is_empty() { aus.push(current); } aus } fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { assert_eq!(a.len(), b.len()); a.iter() .zip(b) .map(|(x, y)| x.abs_diff(*y) as f64) .sum::() / a.len() as f64 } #[test] #[ignore] fn round_trips_sixty_frames() { hwchild::require(); let (width, height) = (1280u32, 720u32); let (stream, units) = encode(width, height, 60).expect("no hardware encode plugin/driver available"); assert_eq!(units, 60, "one access unit per fed picture"); let frames = decode(&stream); assert_eq!(frames.len(), 60, "decoded picture count"); for (index, frame) in frames.iter().enumerate() { assert_eq!( (frame.width, frame.height), (width as usize, height as usize), "frame {index} dimensions" ); } // The pictures have to survive the I420 -> NV12 upload, not merely exist: // a dropped plane or a swapped U/V would sail past a count-only check. // Tolerances are generous because this is lossy CBR, but nowhere near the // ~64 a U/V swap costs on these chroma values. for index in [0usize, 30, 59] { let (y, u, v) = synthetic(index as u32, width as usize, height as usize); let frame = &frames[index]; for (plane, (got, want)) in [(&frame.y, &y), (&frame.u, &u), (&frame.v, &v)] .iter() .enumerate() { let diff = mean_abs_diff(got, want); println!("frame {index} plane {plane}: mean abs diff {diff:.2}"); assert!( diff < 6.0, "frame {index} plane {plane} drifted by {diff:.2}" ); } } } /// 322x242 is even (NV12 needs that) but neither dimension is a multiple of 16, /// so the surface is padded and the encoded stream has to crop it back. This is /// the 1080p case in miniature: 1080 pads to 1088. #[test] #[ignore] fn round_trips_unaligned_dimensions() { hwchild::require(); let (width, height) = (322u32, 242u32); let Some((stream, units)) = encode(width, height, 10) else { println!("driver refused {width}x{height}, software encode would take over -- skipping"); return; }; assert_eq!(units, 10); let frames = decode(&stream); assert_eq!(frames.len(), 10); assert_eq!( (frames[0].width, frames[0].height), (width as usize, height as usize), "padding must be cropped away again" ); } /// The zero-copy path: a picture the hardware decoder wrote goes into the /// hardware encoder as the buffer it was decoded into, never read back and never /// written out again -- which is what makes an export of an untouched clip cost /// no `vaGetImage`, no colour conversion and no upload per frame. /// /// Two things are checked and the second is the one that matters. That the /// buffers are handed over *at all* (a driver whose export the plugin refuses /// falls back to pixels, silently and correctly, which would make a speed claim /// a lie). And that what came out is what went in: the encoded stream is decoded /// in software and compared against the same file decoded through the read-back /// path, so a wrong plane offset, a swapped object or an unsynchronised surface /// -- the ways an imported buffer goes wrong -- fails here instead of shipping /// as a garbled export. #[test] #[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"] fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { hwchild::require(); const FRAMES: usize = 24; let asset = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); let (width, height) = (1280u32, 720u32); let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None) else { println!("no hardware encoder here -- skipping"); return; }; let Some(want) = encoder.dma_want(width, height) else { panic!("a hardware encoder that takes no imported buffer at all"); }; let mut session = HwSession::open(&asset).expect("hardware decode of the fixture"); let mut stream = Vec::new(); let mut buffers = 0; for index in 0..FRAMES { match session.next_frame_dma(want).expect("hardware decode") { Some(HwPicture::Dma(dma)) => { assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}"); buffers += 1; if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") { stream.extend_from_slice(au); } } Some(HwPicture::Pixels(..) | HwPicture::Wide(..)) => panic!("frame {index} was read back after all"), None => panic!("the fixture ran out at frame {index}"), } } while let Some(au) = encoder.drain().expect("drain") { stream.extend_from_slice(au); } assert_eq!(buffers, FRAMES, "every picture came over as a buffer"); // The same file down the path this one exists to avoid, which is the only // honest reference for "the encoder read the right pixels". let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture"); let coded = decode(&stream); assert_eq!(coded.len(), FRAMES, "decoded picture count"); for (index, frame) in coded.iter().enumerate() { let (y, u, v, w, h) = reference .next_frame() .expect("read-back decode") .expect("the fixture is longer than this"); assert_eq!((w, h), (width, height), "frame {index}"); for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)] .iter() .enumerate() { // Lossy CBR against the source picture: the same tolerance the // synthetic round trip above uses, and nowhere near what a swapped // plane or a stale surface would cost. let diff = mean_abs_diff(got, want); assert!( diff < 6.0, "frame {index} plane {plane} drifted by {diff:.2}" ); } } } /// What the process boundary costs, at the size an export is really written at. /// /// The encoder lives in a child now ([`engine::hwproc`]) so that a driver's /// `abort()` cannot take the editor with it, and the price of that has to be /// small enough that nobody would trade it back: pictures reach the child /// through a shared mapping rather than down a pipe, so a frame costs one /// `memcpy` and a ten-byte message. `VE_HW_INPROCESS` pins the seat the way it /// used to be, which is the only honest baseline there is. /// /// This is the *worst* case on purpose: an untouched clip's pictures never leave /// the GPU at all (`a_decoded_buffer_is_encoded_without_ever_being_read_back`, /// whose descriptors cross the same socket), so nothing an export really does is /// slower than this. #[test] #[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"] fn isolating_the_encoder_costs_little_at_1080p() { hwchild::require(); const FRAMES: u32 = 60; let (width, height) = (1920u32, 1080u32); let mut spent = Vec::new(); for inprocess in [true, false] { // The ignored run is `--test-threads=1`, which is what this file's own // header already requires of its env pins. match inprocess { true => engine::envcfg::set("VE_HW_INPROCESS", "1"), false => engine::envcfg::unset("VE_HW_INPROCESS"), } let started = Instant::now(); let Some((_, units)) = encode(width, height, FRAMES) else { println!("no hardware encoder here -- skipping"); return; }; assert_eq!(units, FRAMES, "one access unit per fed picture"); spent.push(started.elapsed().as_secs_f64()); } let (local, remote) = (spent[0], spent[1]); println!( "1080p x{FRAMES}: in-process {:.1} fps, isolated {:.1} fps ({:.0}% of it)", f64::from(FRAMES) / local, f64::from(FRAMES) / remote, 100.0 * local / remote ); assert!( local / remote >= 0.85, "isolation kept only {:.0}% of the in-process rate", 100.0 * local / remote ); } /// Decode and encode resolve through two independent symbol tables, so an /// encoder that cannot load must not cost us the decoder (and vice versa). /// /// This is the positive half only: the negative half -- a plugin built without /// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's /// verifier, not here. #[test] #[ignore] fn decode_and_encode_load_independently() { hwchild::require(); let asset = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); assert!( HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some(), "encode table" ); assert!(HwSession::open(&asset).is_some(), "decode table"); // Order reversed: neither table's `OnceLock` may have primed the other. assert!(HwSession::open(&asset).is_some()); assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some()); } /// Per slice: `(is_idr, frame_num, pic_order_cnt_lsb)`, read by [`slice_counters`]. type SliceCounters = Vec<(bool, u32, Option)>; /// Walks the Annex B stream and reads, per slice, `(is_idr, frame_num, /// pic_order_cnt_lsb)`, plus the SPS `level_idc`. Main profile, POC type 0 and /// frame_mbs_only -- the SPS the vendored encoder writes -- is all this reads; /// the test fails loudly on anything else rather than guessing. fn slice_counters(stream: &[u8]) -> (u8, u32, SliceCounters) { struct Bits<'a>(&'a [u8], usize); impl Bits<'_> { fn bit(&mut self) -> u32 { let b = (self.0[self.1 / 8] >> (7 - self.1 % 8)) & 1; self.1 += 1; u32::from(b) } fn bits(&mut self, n: u32) -> u32 { (0..n).fold(0, |v, _| (v << 1) | self.bit()) } fn ue(&mut self) -> u32 { let mut zeros = 0; while self.bit() == 0 { zeros += 1; } (1 << zeros) - 1 + self.bits(zeros) } } fn unescape(bytes: &[u8]) -> Vec { let mut out = Vec::with_capacity(bytes.len()); let mut zeros = 0; for &b in bytes { if zeros >= 2 && b == 3 { zeros = 0; continue; } out.push(b); zeros = if b == 0 { zeros + 1 } else { 0 }; } out } let mut nals = Vec::new(); let mut i = 0; while i + 3 <= stream.len() { if stream[i..i + 3] == [0, 0, 1] { nals.push(i + 3); i += 3; } else { i += 1; } } let (mut level, mut log2_fn, mut log2_poc) = (0u8, 0u32, 0u32); let mut out = Vec::new(); for (n, &s) in nals.iter().enumerate() { let e = nals.get(n + 1).map_or(stream.len(), |&x| x - 3); let kind = stream[s] & 0x1f; // Only the header is needed; 64 bytes of RBSP covers every field read. let rbsp = unescape(&stream[s + 1..e.min(s + 1 + 64)]); let mut b = Bits(&rbsp, 0); match kind { 7 => { let profile = b.bits(8); assert_eq!(profile, 77, "Main profile SPS expected"); b.bits(8); level = b.bits(8) as u8; b.ue(); log2_fn = b.ue() + 4; // Type 0 carries `pic_order_cnt_lsb` in every slice; type 2 derives // the order from `frame_num` (legal without B-frames) and carries // no lsb at all, which is what ec-hw writes. match b.ue() { 0 => log2_poc = b.ue() + 4, 2 => log2_poc = 0, other => panic!("pic_order_cnt_type {other} is not one this encoder writes"), } } 1 | 5 => { assert!(log2_fn > 0, "slice before any SPS"); b.ue(); b.ue(); b.ue(); let frame_num = b.bits(log2_fn); if kind == 5 { b.ue(); } let poc = (log2_poc > 0).then(|| b.bits(log2_poc)); out.push((kind == 5, frame_num, poc)); } _ => {} } } (level, 1 << log2_fn, out) } /// The driver on this box writes `frame_num = 0` and `pic_order_cnt_lsb = 0` /// into every slice it codes (mesa radeonsi 26.1.7, measured on three real /// exports); phones' stateful decoders then judder every few seconds. The /// plugin rewrites both, and this is the stream-level proof: over two GOPs the /// counters step the way 7.4.3 wants, restart at the second IDR, and the level /// is the one Table A-1 gives 1080p30 -- not the `L4` that used to be /// hard-coded for every size. `HW_ENCODE_DUMP=` keeps the stream for /// `ffmpeg -bsf:v trace_headers`. #[test] #[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"] fn slice_headers_carry_frame_num_and_poc() { hwchild::require(); let (width, height) = (1920u32, 1080u32); let count = 100; // a 2 s GOP at 30 fps is 60: two IDRs, frame_num wraps at 32 let (stream, units) = encode(width, height, count).expect("no hardware encode plugin/driver available"); assert_eq!(units, count); if let Ok(path) = std::env::var("HW_ENCODE_DUMP") { std::fs::write(&path, &stream).expect("dump"); println!("stream written to {path}"); } let (level, max_frame_num, slices) = slice_counters(&stream); assert_eq!(level, 40, "1920x1080 at 30 fps is level 4.0"); assert_eq!(slices.len() as u32, count, "one slice per picture"); let idrs: Vec = slices .iter() .enumerate() .filter(|(_, s)| s.0) .map(|(i, _)| i) .collect(); assert_eq!(idrs, vec![0, 60], "an IDR every 2 s GOP"); let mut since_idr = 0u32; for (i, &(idr, frame_num, poc)) in slices.iter().enumerate() { if idr { since_idr = 0; } // The modulus is the SPS's own: the encoder picks it, and it need not be 32. assert_eq!(frame_num, since_idr % max_frame_num, "slice {i} frame_num"); // Type 2 has no lsb to check: its order is the frame_num's, checked above. if let Some(poc) = poc { assert_eq!(poc, (since_idr * 2) % 64, "slice {i} pic_order_cnt_lsb"); } since_idr += 1; } let distinct: std::collections::BTreeSet = slices.iter().map(|s| s.1).collect(); assert!(distinct.len() > 1, "frame_num never moved -- the rewrite did not run"); // The rewrite is header-only: the picture still decodes. assert_eq!(decode(&stream).len(), count as usize); }