From 58e23aa550ad65ebd1fa0c608a993fb1ce7d8b77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 17:05:54 +0300 Subject: [PATCH] feat(ec-hw): route coded-size-mismatched encode_frame sources through VPP region copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Encoder::encode_frame refused any source whose coded_size differed from the encoder's block-rounded one (HEVC rounds to 32, so a 3840x2160 source's 2160 stayed unrounded while the HEVC coded height became 2176). Add Vpp::convert_region (crates/ec-va/src/vpp.rs) — a VAProcPipelineParameterBuffer submission with explicit surface_region/output_region rectangles, no scaling — and route both 10-bit (P010) and now 8-bit coded-size-mismatched sources through it into the encoder's own NV12 pool, placed at (0,0) using frame.display_size. Encoder's own SPS conformance window / frame_cropping (already sized from EncoderConfig.width/height, independent of the source frame) makes the produced stream report the true visible size, not the padded coded one. The pool is painted black/neutral-chroma once on creation (Encoder::fill_black) so the padding rows a region copy never touches are deterministic rather than driver-fresh-allocation garbage. Real 4K HEVC Main10 mkv (3840x2160): - encode_frame_accepts_p010_via_vpp: HEVC now accepted and round-trips (worst Y inf dB, worst UV 96.2 dB vs the CPU path; H264 worst Y/UV inf dB), and ffprobe confirms the produced stream is 3840x2160 for both targets. - p010_zero_copy_encode_is_realtime (--release): H264 zero-copy 6.52 ms/frame median (CPU path 18.80), HEVC zero-copy 5.29 ms/frame median (CPU path 16.95) — both under the 20 ms/frame target. cargo test -p ec-va -- --test-threads=1: 13 + 6 doctests, all green. cargo test -p ec-hw --release --test gpu -- --test-threads=1: 27 passed. --- crates/ec-hw/src/enc/mod.rs | 73 +++++++++---- crates/ec-hw/tests/gpu.rs | 198 ++++++++++++++++++++---------------- crates/ec-va/src/vpp.rs | 49 +++++++++ 3 files changed, 216 insertions(+), 104 deletions(-) diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 317b1b7c..fae8fa61 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -352,9 +352,18 @@ impl Encoder { /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate /// encodes, and no VPP conversion this crate builds, has a destination /// for a 12-bit source. - /// - `frame`'s coded size does not match this encoder's: the surface - /// formats have to agree for the driver to read one as the other, and - /// the VPP conversion pass (when one runs) does not resize. + /// + /// A `frame` whose coded size does not match this encoder's (a common + /// case: HEVC block-rounds to 32, so a 3840x2160 source's 2160 stays + /// unrounded while the encoder's coded height becomes 2176) is not + /// refused — it goes through the same VPP pool a 10-bit source uses, + /// placed by explicit region rather than a whole-surface convert: only + /// `frame.display_size` is read from the source and written into the + /// destination at `(0, 0)`, so the padding rows/columns beyond it are + /// never touched by the copy. Those padding pixels are still fed to the + /// encoder as part of the coded surface, so the pool is painted black + /// once, on creation, rather than left as whatever the driver's fresh + /// allocation happened to contain. pub fn encode_frame( &mut self, frame: &crate::frame::Frame, @@ -373,28 +382,33 @@ impl Encoder { "encode_frame: the frame was decoded on a different Display than this encoder", )); } - if frame.coded_size != self.coded_size { - return Err(Error::config(format!( - "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}", - self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1 - ))); - } - let source = if frame.bit_depth == 10 { - self.nv12_from_p010(frame.surface())? + let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { + self.vpp_into_pool(frame.surface(), frame.display_size)? } else { Arc::clone(frame.surface()) }; self.encode_surface(source, meta) } - /// Convert a P010 surface into this encoder's coded size, in NV12, on the - /// GPU. Builds the VPP pipeline and its two-surface pool on first use. - fn nv12_from_p010(&mut self, source: &Arc) -> Result> { + /// Place a source surface's visible rect into this encoder's coded size, + /// in NV12, on the GPU: a whole-surface convert when the source is + /// already the encoder's coded size (the common 10-bit case), a region + /// copy/convert otherwise. Builds the VPP pipeline and its two-surface + /// pool on first use, painting the pool black so any padding beyond + /// `display_size` a region copy never touches is deterministic. + fn vpp_into_pool( + &mut self, + source: &Arc, + display_size: (u32, u32), + ) -> Result> { if self.vpp.is_none() { let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); let display = self.context.display(); let surfaces = Surface::create_pool(display, &spec, 2)?; + for s in &surfaces { + Self::fill_black(s, self.coded_size)?; + } let vpp = Vpp::new( display, sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10, @@ -405,11 +419,32 @@ impl Encoder { } let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]); self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); - Ok(self - .vpp - .as_ref() - .expect("just built above if it was None") - .convert(source, dest)?) + let vpp = self.vpp.as_ref().expect("just built above if it was None"); + if display_size == self.coded_size { + Ok(vpp.convert(source, dest)?) + } else { + let rect = (0, 0, display_size.0, display_size.1); + Ok(vpp.convert_region(source, rect, dest, rect)?) + } + } + + /// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the + /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a + /// region copy's untouched padding reads the same deterministic value on + /// every driver instead of whatever the fresh allocation contained. + fn fill_black(surface: &Arc, size: (u32, u32)) -> Result<()> { + let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; + { + let mut mapped = image.map()?; + if let Some(y) = mapped.plane_mut(0) { + y.fill(16); + } + if let Some(uv) = mapped.plane_mut(1) { + uv.fill(128); + } + } + surface.write_from(&image, size.0, size.1)?; + Ok(()) } /// Shared submission path for [`Encoder::encode`] and diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 91904af6..da88096c 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -1531,13 +1531,14 @@ fn encode_frame_accepts_p010_via_vpp() { }; // This film's HEVC SPS `pic_height_in_luma_samples` is 2160, which is a - // multiple of the H.264 encode block size (16) but not the HEVC one - // (32, next_multiple_of gives 2176) — `encode_frame` refuses that - // mismatch by documented design ("frame's coded size does not match - // this encoder's ... the VPP conversion pass does not resize") rather - // than silently stretching the picture, so the HEVC target is expected - // to be *refused* here, not to round-trip; only H.264 gets the full - // encode/decode/PSNR comparison. + // multiple of the H.264 encode block size (16) but not the HEVC one (32, + // next_multiple_of gives 2176) — `encode_frame` no longer refuses that + // mismatch: it routes through the VPP pool by explicit region + // (`Encoder::vpp_into_pool`), so both targets get the full + // encode/decode/PSNR comparison, and the HEVC one additionally gets an + // `ffprobe` check that the visible size in the produced stream is still + // 3840x2160 (the encoder's own cropping, not a VPP resize). + let (mut w, mut h) = (0u32, 0u32); for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); let mut zc_stream = Vec::new(); @@ -1545,13 +1546,13 @@ fn encode_frame_accepts_p010_via_vpp() { let mut count = 0i64; let mut zero_copy: Option = None; let mut cpu_path: Option = None; - let mut refused = false; + let refused = false; decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { if refused { return; } - let (w, h) = frame.display_size; + (w, h) = frame.display_size; let zero_copy = zero_copy.get_or_insert_with(|| { let mut cfg = EncoderConfig::new(target, w, h); cfg.gop_size = 30; @@ -1568,22 +1569,10 @@ fn encode_frame_accepts_p010_via_vpp() { timestamp: count, force_keyframe: false, }; - match zero_copy.encode_frame(&frame, meta) { - Ok(zc) => zc_stream.extend_from_slice(&zc.data), - Err(e) if target == EncCodec::H265 => { - println!( - "{target:?}: encode_frame refused as documented (block size vs SPS \ - pic height): {e}" - ); - assert!( - e.to_string().contains("encoder surfaces are"), - "unexpected refusal reason: {e}" - ); - refused = true; - return; - } - Err(e) => panic!("encode_frame (zero copy, P010 via VPP): {e}"), - } + let zc = zero_copy + .encode_frame(&frame, meta) + .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)"); + zc_stream.extend_from_slice(&zc.data); let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); cpu_stream.extend_from_slice(&cpu.data); @@ -1629,6 +1618,35 @@ fn encode_frame_accepts_p010_via_vpp() { println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB"); assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path"); assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path"); + + // The size-mismatch route (HEVC: 2160 visible vs 2176 coded) places + // the picture by VPP region rather than encoder cropping alone, so + // confirm the encoder's own SPS conformance window still reports the + // real 3840x2160 — not the padded 2176 the coded surface carries. + let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}")); + std::fs::create_dir_all(&dir).expect("temp dir"); + let path = dir.join(match target { + EncCodec::H264 => "out.264", + EncCodec::H265 => "out.265", + EncCodec::Av1 => "out.obu", + }); + std::fs::write(&path, &zc_stream).expect("write bitstream"); + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe runs"); + let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string(); + assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}"); } } @@ -1637,12 +1655,10 @@ fn encode_frame_accepts_p010_via_vpp() { /// says whether the VPP conversion is cheap enough to keep the zero-copy path /// meaningfully faster than reading the frame back to system memory. /// -/// Targets H.264: this film's HEVC SPS `pic_height_in_luma_samples` (2160) -/// is not a multiple of this crate's HEVC encode block size (32), so -/// `encode_frame` refuses the HEVC target on this file by documented design -/// (see `encode_frame_accepts_p010_via_vpp`) — 2160 *is* a multiple of the -/// H.264 block size (16), so H.264 is the target that actually exercises the -/// zero-copy path on this real source. +/// Both H.264 (coded size already matches this film's 2160 visible height, +/// so the P010->NV12 convert is whole-surface) and HEVC (2160 is not a +/// multiple of the 32-block HEVC coded size, so `encode_frame` also takes +/// the VPP region-copy route — `Encoder::vpp_into_pool`) get a bench row. #[test] fn p010_zero_copy_encode_is_realtime() { let Some(display) = display() else { return }; @@ -1659,66 +1675,78 @@ fn p010_zero_copy_encode_is_realtime() { let units = split_access_units(&data, Codec::H265); assert!(units.len() > limit, "film clip too short for {limit} frames"); - println!("{:<24} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); - let mut zc_median = None; - let mut cpu_median = None; - for (name, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut encoder: Option = None; - let mut durations: Vec = Vec::new(); - let mut count = 0i64; - 'outer: for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - let (w, h) = frame.display_size; - let encoder = encoder.get_or_insert_with(|| { - let mut cfg = EncoderConfig::new(EncCodec::H264, w, h); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - Encoder::new(&display, cfg).expect("encoder opens") - }); - let meta = FrameMetadata { - timestamp: count, - force_keyframe: false, - }; - let t0 = Instant::now(); - if zero_copy { - encoder.encode_frame(&frame, meta).expect("encode_frame"); - } else { - let i420 = frame.to_i420().expect("readback"); - encoder.encode(&i420, meta).expect("encode"); - } - durations.push(t0.elapsed()); - count += 1; - if durations.len() >= limit { - break 'outer; + println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms"); + // (target, zero-copy median ms, CPU-path median ms) rows, filled in order. + let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new(); + for target in [EncCodec::H264, EncCodec::H265] { + let mut zc_median = None; + let mut cpu_median = None; + for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] { + let name = format!("{target:?} {label}"); + let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); + let mut encoder: Option = None; + let mut durations: Vec = Vec::new(); + let mut count = 0i64; + 'outer: for (i, unit) in units.iter().enumerate() { + decoder.decode(unit, i as i64).expect("decode"); + while let Some(frame) = decoder.next_frame() { + let (w, h) = frame.display_size; + let encoder = encoder.get_or_insert_with(|| { + let mut cfg = EncoderConfig::new(target, w, h); + cfg.gop_size = 30; + cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; + Encoder::new(&display, cfg).expect("encoder opens") + }); + let meta = FrameMetadata { + timestamp: count, + force_keyframe: false, + }; + let t0 = Instant::now(); + if zero_copy { + encoder.encode_frame(&frame, meta).expect("encode_frame"); + } else { + let i420 = frame.to_i420().expect("readback"); + encoder.encode(&i420, meta).expect("encode"); + } + durations.push(t0.elapsed()); + count += 1; + if durations.len() >= limit { + break 'outer; + } } } + assert!( + durations.len() >= limit, + "{name}: only {} of {limit} frames encoded", + durations.len() + ); + durations.sort(); + let ms = |d: Duration| d.as_secs_f64() * 1000.0; + let median = ms(durations[durations.len() / 2]); + let min = ms(durations[0]); + let max = ms(durations[durations.len() - 1]); + println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}"); + if zero_copy { + zc_median = Some(median); + } else { + cpu_median = Some(median); + } } + rows.push(( + target, + zc_median.expect("zero-copy phase ran"), + cpu_median.expect("CPU-path phase ran"), + )); + } + for (target, zc, cpu) in rows { + println!( + "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})" + ); assert!( - durations.len() >= limit, - "{name}: only {} of {limit} frames encoded", - durations.len() + zc <= 20.0, + "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" ); - durations.sort(); - let ms = |d: Duration| d.as_secs_f64() * 1000.0; - let median = ms(durations[durations.len() / 2]); - let min = ms(durations[0]); - let max = ms(durations[durations.len() - 1]); - println!("{name:<24} {median:>10.2} {min:>10.2} {max:>10.2}"); - if zero_copy { - zc_median = Some(median); - } else { - cpu_median = Some(median); - } } - let zc = zc_median.expect("zero-copy phase ran"); - let cpu = cpu_median.expect("CPU-path phase ran"); - println!("target: decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})"); - assert!( - zc <= 20.0, - "decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)" - ); } /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in diff --git a/crates/ec-va/src/vpp.rs b/crates/ec-va/src/vpp.rs index 505132d5..29d3f876 100644 --- a/crates/ec-va/src/vpp.rs +++ b/crates/ec-va/src/vpp.rs @@ -95,6 +95,55 @@ impl Vpp { Ok(surface) } + /// Convert `source` into `dest` like [`Vpp::convert`], but reading only + /// `source_region` of `source` and writing only `dest_region` of `dest` — + /// no scaling (both regions are the same size in every caller today), + /// just a placement: the pixels outside `dest_region` are left exactly as + /// `dest` already had them. This is how a visible picture smaller than + /// its block-aligned coded surface (e.g. a 2160-tall HEVC source, whose + /// coded height rounds to 2176) lands inside a differently-padded + /// destination without a resize. + pub fn convert_region( + &self, + source: &Arc, + source_region: (u32, u32, u32, u32), + dest: Arc, + dest_region: (u32, u32, u32, u32), + ) -> Result> { + let sr = sys::VARectangle { + x: source_region.0 as i16, + y: source_region.1 as i16, + width: source_region.2 as u16, + height: source_region.3 as u16, + }; + let dr = sys::VARectangle { + x: dest_region.0 as i16, + y: dest_region.1 as i16, + width: dest_region.2 as u16, + height: dest_region.3 as u16, + }; + let param = sys::VAProcPipelineParameterBuffer { + surface: source.id(), + surface_region: &sr, + output_region: &dr, + ..Default::default() + }; + // SAFETY: `surface_region`/`output_region` point at `sr`/`dr`, which + // outlive this call (built here, read only while `Buffer::from_param` + // constructs the driver buffer below); otherwise identical to + // `convert`'s safety argument. + let buffer = unsafe { + Buffer::from_param(&self.context, sys::VAProcPipelineParameterBufferType, ¶m)? + }; + let surface = Picture::new(&self.context, dest) + .begin()? + .render(buffer)? + .end()? + .sync()? + .into_surface(); + Ok(surface) + } + fn context_id(&self) -> sys::VAContextID { // `Context` does not expose its raw id outside the crate; VPP needs // it for `vaQueryVideoProcFilters`, which has no typestate-protected