forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'ec-hw-vpp-region'

Browse files at this commit

6af547f85087fdd297ceab2f6c6a02132e86d272Ahmet Kaan GümüşParent: f9940e158e23aa
crates/ec-hw/src/enc/mod.rsmodified+54 -19
@@ -352,9 +352,18 @@ impl Encoder {
352352 /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate
353353 /// encodes, and no VPP conversion this crate builds, has a destination
354354 /// for a 12-bit source.
355- /// - `frame`'s coded size does not match this encoder's: the surface
356- /// formats have to agree for the driver to read one as the other, and
357- /// the VPP conversion pass (when one runs) does not resize.
355+ ///
356+ /// A `frame` whose coded size does not match this encoder's (a common
357+ /// case: HEVC block-rounds to 32, so a 3840x2160 source's 2160 stays
358+ /// unrounded while the encoder's coded height becomes 2176) is not
359+ /// refused — it goes through the same VPP pool a 10-bit source uses,
360+ /// placed by explicit region rather than a whole-surface convert: only
361+ /// `frame.display_size` is read from the source and written into the
362+ /// destination at `(0, 0)`, so the padding rows/columns beyond it are
363+ /// never touched by the copy. Those padding pixels are still fed to the
364+ /// encoder as part of the coded surface, so the pool is painted black
365+ /// once, on creation, rather than left as whatever the driver's fresh
366+ /// allocation happened to contain.
358367 pub fn encode_frame(
359368 &mut self,
360369 frame: &crate::frame::Frame,
@@ -373,28 +382,33 @@ impl Encoder {
373382 "encode_frame: the frame was decoded on a different Display than this encoder",
374383 ));
375384 }
376- if frame.coded_size != self.coded_size {
377- return Err(Error::config(format!(
378- "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}",
379- self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
380- )));
381- }
382- let source = if frame.bit_depth == 10 {
383- self.nv12_from_p010(frame.surface())?
385+ let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size {
386+ self.vpp_into_pool(frame.surface(), frame.display_size)?
384387 } else {
385388 Arc::clone(frame.surface())
386389 };
387390 self.encode_surface(source, meta)
388391 }
389392
390- /// Convert a P010 surface into this encoder's coded size, in NV12, on the
391- /// GPU. Builds the VPP pipeline and its two-surface pool on first use.
392- fn nv12_from_p010(&mut self, source: &Arc<Surface>) -> Result<Arc<Surface>> {
393+ /// Place a source surface's visible rect into this encoder's coded size,
394+ /// in NV12, on the GPU: a whole-surface convert when the source is
395+ /// already the encoder's coded size (the common 10-bit case), a region
396+ /// copy/convert otherwise. Builds the VPP pipeline and its two-surface
397+ /// pool on first use, painting the pool black so any padding beyond
398+ /// `display_size` a region copy never touches is deterministic.
399+ fn vpp_into_pool(
400+ &mut self,
401+ source: &Arc<Surface>,
402+ display_size: (u32, u32),
403+ ) -> Result<Arc<Surface>> {
393404 if self.vpp.is_none() {
394405 let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1)
395406 .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER);
396407 let display = self.context.display();
397408 let surfaces = Surface::create_pool(display, &spec, 2)?;
409+ for s in &surfaces {
410+ Self::fill_black(s, self.coded_size)?;
411+ }
398412 let vpp = Vpp::new(
399413 display,
400414 sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10,
@@ -405,11 +419,32 @@ impl Encoder {
405419 }
406420 let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]);
407421 self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len();
408- Ok(self
409- .vpp
410- .as_ref()
411- .expect("just built above if it was None")
412- .convert(source, dest)?)
422+ let vpp = self.vpp.as_ref().expect("just built above if it was None");
423+ if display_size == self.coded_size {
424+ Ok(vpp.convert(source, dest)?)
425+ } else {
426+ let rect = (0, 0, display_size.0, display_size.1);
427+ Ok(vpp.convert_region(source, rect, dest, rect)?)
428+ }
429+ }
430+
431+ /// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the
432+ /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a
433+ /// region copy's untouched padding reads the same deterministic value on
434+ /// every driver instead of whatever the fresh allocation contained.
435+ fn fill_black(surface: &Arc<Surface>, size: (u32, u32)) -> Result<()> {
436+ let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?;
437+ {
438+ let mut mapped = image.map()?;
439+ if let Some(y) = mapped.plane_mut(0) {
440+ y.fill(16);
441+ }
442+ if let Some(uv) = mapped.plane_mut(1) {
443+ uv.fill(128);
444+ }
445+ }
446+ surface.write_from(&image, size.0, size.1)?;
447+ Ok(())
413448 }
414449
415450 /// Shared submission path for [`Encoder::encode`] and
crates/ec-hw/tests/gpu.rsmodified+113 -85
@@ -1531,13 +1531,14 @@ fn encode_frame_accepts_p010_via_vpp() {
15311531 };
15321532
15331533 // This film's HEVC SPS `pic_height_in_luma_samples` is 2160, which is a
1534- // multiple of the H.264 encode block size (16) but not the HEVC one
1535- // (32, next_multiple_of gives 2176) — `encode_frame` refuses that
1536- // mismatch by documented design ("frame's coded size does not match
1537- // this encoder's ... the VPP conversion pass does not resize") rather
1538- // than silently stretching the picture, so the HEVC target is expected
1539- // to be *refused* here, not to round-trip; only H.264 gets the full
1540- // encode/decode/PSNR comparison.
1534+ // multiple of the H.264 encode block size (16) but not the HEVC one (32,
1535+ // next_multiple_of gives 2176) — `encode_frame` no longer refuses that
1536+ // mismatch: it routes through the VPP pool by explicit region
1537+ // (`Encoder::vpp_into_pool`), so both targets get the full
1538+ // encode/decode/PSNR comparison, and the HEVC one additionally gets an
1539+ // `ffprobe` check that the visible size in the produced stream is still
1540+ // 3840x2160 (the encoder's own cropping, not a VPP resize).
1541+ let (mut w, mut h) = (0u32, 0u32);
15411542 for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
15421543 let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
15431544 let mut zc_stream = Vec::new();
@@ -1545,13 +1546,13 @@ fn encode_frame_accepts_p010_via_vpp() {
15451546 let mut count = 0i64;
15461547 let mut zero_copy: Option<Encoder> = None;
15471548 let mut cpu_path: Option<Encoder> = None;
1548- let mut refused = false;
1549+ let refused = false;
15491550
15501551 decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
15511552 if refused {
15521553 return;
15531554 }
1554- let (w, h) = frame.display_size;
1555+ (w, h) = frame.display_size;
15551556 let zero_copy = zero_copy.get_or_insert_with(|| {
15561557 let mut cfg = EncoderConfig::new(target, w, h);
15571558 cfg.gop_size = 30;
@@ -1568,22 +1569,10 @@ fn encode_frame_accepts_p010_via_vpp() {
15681569 timestamp: count,
15691570 force_keyframe: false,
15701571 };
1571- match zero_copy.encode_frame(&frame, meta) {
1572- Ok(zc) => zc_stream.extend_from_slice(&zc.data),
1573- Err(e) if target == EncCodec::H265 => {
1574- println!(
1575- "{target:?}: encode_frame refused as documented (block size vs SPS \
1576- pic height): {e}"
1577- );
1578- assert!(
1579- e.to_string().contains("encoder surfaces are"),
1580- "unexpected refusal reason: {e}"
1581- );
1582- refused = true;
1583- return;
1584- }
1585- Err(e) => panic!("encode_frame (zero copy, P010 via VPP): {e}"),
1586- }
1572+ let zc = zero_copy
1573+ .encode_frame(&frame, meta)
1574+ .expect("encode_frame (zero copy, P010 via VPP, size mismatch routed through VPP)");
1575+ zc_stream.extend_from_slice(&zc.data);
15871576 let i420 = frame.to_i420().expect("readback for the CPU-path baseline");
15881577 let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)");
15891578 cpu_stream.extend_from_slice(&cpu.data);
@@ -1629,6 +1618,35 @@ fn encode_frame_accepts_p010_via_vpp() {
16291618 println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB");
16301619 assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path");
16311620 assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path");
1621+
1622+ // The size-mismatch route (HEVC: 2160 visible vs 2176 coded) places
1623+ // the picture by VPP region rather than encoder cropping alone, so
1624+ // confirm the encoder's own SPS conformance window still reports the
1625+ // real 3840x2160 — not the padded 2176 the coded surface carries.
1626+ let dir = std::env::temp_dir().join(format!("ec-hw-vpp-region-{target:?}"));
1627+ std::fs::create_dir_all(&dir).expect("temp dir");
1628+ let path = dir.join(match target {
1629+ EncCodec::H264 => "out.264",
1630+ EncCodec::H265 => "out.265",
1631+ EncCodec::Av1 => "out.obu",
1632+ });
1633+ std::fs::write(&path, &zc_stream).expect("write bitstream");
1634+ let probe = Command::new("ffprobe")
1635+ .args([
1636+ "-v",
1637+ "error",
1638+ "-select_streams",
1639+ "v:0",
1640+ "-show_entries",
1641+ "stream=width,height",
1642+ "-of",
1643+ "csv=p=0",
1644+ ])
1645+ .arg(&path)
1646+ .output()
1647+ .expect("ffprobe runs");
1648+ let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string();
1649+ assert_eq!(dims, format!("{w},{h}"), "{target:?}: ffprobe sees {dims}");
16321650 }
16331651 }
16341652
@@ -1637,12 +1655,10 @@ fn encode_frame_accepts_p010_via_vpp() {
16371655 /// says whether the VPP conversion is cheap enough to keep the zero-copy path
16381656 /// meaningfully faster than reading the frame back to system memory.
16391657 ///
1640-/// Targets H.264: this film's HEVC SPS `pic_height_in_luma_samples` (2160)
1641-/// is not a multiple of this crate's HEVC encode block size (32), so
1642-/// `encode_frame` refuses the HEVC target on this file by documented design
1643-/// (see `encode_frame_accepts_p010_via_vpp`) — 2160 *is* a multiple of the
1644-/// H.264 block size (16), so H.264 is the target that actually exercises the
1645-/// zero-copy path on this real source.
1658+/// Both H.264 (coded size already matches this film's 2160 visible height,
1659+/// so the P010->NV12 convert is whole-surface) and HEVC (2160 is not a
1660+/// multiple of the 32-block HEVC coded size, so `encode_frame` also takes
1661+/// the VPP region-copy route — `Encoder::vpp_into_pool`) get a bench row.
16461662 #[test]
16471663 fn p010_zero_copy_encode_is_realtime() {
16481664 let Some(display) = display() else { return };
@@ -1659,66 +1675,78 @@ fn p010_zero_copy_encode_is_realtime() {
16591675 let units = split_access_units(&data, Codec::H265);
16601676 assert!(units.len() > limit, "film clip too short for {limit} frames");
16611677
1662- println!("{:<24} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms");
1663- let mut zc_median = None;
1664- let mut cpu_median = None;
1665- for (name, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] {
1666- let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1667- let mut encoder: Option<Encoder> = None;
1668- let mut durations: Vec<Duration> = Vec::new();
1669- let mut count = 0i64;
1670- 'outer: for (i, unit) in units.iter().enumerate() {
1671- decoder.decode(unit, i as i64).expect("decode");
1672- while let Some(frame) = decoder.next_frame() {
1673- let (w, h) = frame.display_size;
1674- let encoder = encoder.get_or_insert_with(|| {
1675- let mut cfg = EncoderConfig::new(EncCodec::H264, w, h);
1676- cfg.gop_size = 30;
1677- cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1678- Encoder::new(&display, cfg).expect("encoder opens")
1679- });
1680- let meta = FrameMetadata {
1681- timestamp: count,
1682- force_keyframe: false,
1683- };
1684- let t0 = Instant::now();
1685- if zero_copy {
1686- encoder.encode_frame(&frame, meta).expect("encode_frame");
1687- } else {
1688- let i420 = frame.to_i420().expect("readback");
1689- encoder.encode(&i420, meta).expect("encode");
1690- }
1691- durations.push(t0.elapsed());
1692- count += 1;
1693- if durations.len() >= limit {
1694- break 'outer;
1678+ println!("{:<28} {:>10} {:>10} {:>10}", "stage", "median ms", "min ms", "max ms");
1679+ // (target, zero-copy median ms, CPU-path median ms) rows, filled in order.
1680+ let mut rows: Vec<(EncCodec, f64, f64)> = Vec::new();
1681+ for target in [EncCodec::H264, EncCodec::H265] {
1682+ let mut zc_median = None;
1683+ let mut cpu_median = None;
1684+ for (label, zero_copy) in [("decode+encode_frame", true), ("decode+to_i420+encode", false)] {
1685+ let name = format!("{target:?} {label}");
1686+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1687+ let mut encoder: Option<Encoder> = None;
1688+ let mut durations: Vec<Duration> = Vec::new();
1689+ let mut count = 0i64;
1690+ 'outer: for (i, unit) in units.iter().enumerate() {
1691+ decoder.decode(unit, i as i64).expect("decode");
1692+ while let Some(frame) = decoder.next_frame() {
1693+ let (w, h) = frame.display_size;
1694+ let encoder = encoder.get_or_insert_with(|| {
1695+ let mut cfg = EncoderConfig::new(target, w, h);
1696+ cfg.gop_size = 30;
1697+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1698+ Encoder::new(&display, cfg).expect("encoder opens")
1699+ });
1700+ let meta = FrameMetadata {
1701+ timestamp: count,
1702+ force_keyframe: false,
1703+ };
1704+ let t0 = Instant::now();
1705+ if zero_copy {
1706+ encoder.encode_frame(&frame, meta).expect("encode_frame");
1707+ } else {
1708+ let i420 = frame.to_i420().expect("readback");
1709+ encoder.encode(&i420, meta).expect("encode");
1710+ }
1711+ durations.push(t0.elapsed());
1712+ count += 1;
1713+ if durations.len() >= limit {
1714+ break 'outer;
1715+ }
16951716 }
16961717 }
1718+ assert!(
1719+ durations.len() >= limit,
1720+ "{name}: only {} of {limit} frames encoded",
1721+ durations.len()
1722+ );
1723+ durations.sort();
1724+ let ms = |d: Duration| d.as_secs_f64() * 1000.0;
1725+ let median = ms(durations[durations.len() / 2]);
1726+ let min = ms(durations[0]);
1727+ let max = ms(durations[durations.len() - 1]);
1728+ println!("{name:<28} {median:>10.2} {min:>10.2} {max:>10.2}");
1729+ if zero_copy {
1730+ zc_median = Some(median);
1731+ } else {
1732+ cpu_median = Some(median);
1733+ }
16971734 }
1735+ rows.push((
1736+ target,
1737+ zc_median.expect("zero-copy phase ran"),
1738+ cpu_median.expect("CPU-path phase ran"),
1739+ ));
1740+ }
1741+ for (target, zc, cpu) in rows {
1742+ println!(
1743+ "target: {target:?} decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})"
1744+ );
16981745 assert!(
1699- durations.len() >= limit,
1700- "{name}: only {} of {limit} frames encoded",
1701- durations.len()
1746+ zc <= 20.0,
1747+ "{target:?}: decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)"
17021748 );
1703- durations.sort();
1704- let ms = |d: Duration| d.as_secs_f64() * 1000.0;
1705- let median = ms(durations[durations.len() / 2]);
1706- let min = ms(durations[0]);
1707- let max = ms(durations[durations.len() - 1]);
1708- println!("{name:<24} {median:>10.2} {min:>10.2} {max:>10.2}");
1709- if zero_copy {
1710- zc_median = Some(median);
1711- } else {
1712- cpu_median = Some(median);
1713- }
17141749 }
1715- let zc = zc_median.expect("zero-copy phase ran");
1716- let cpu = cpu_median.expect("CPU-path phase ran");
1717- println!("target: decode+encode_frame <= 20.00 ms/frame median; got {zc:.2} (CPU path {cpu:.2})");
1718- assert!(
1719- zc <= 20.0,
1720- "decode+encode_frame median {zc:.2} ms/frame exceeds the 20 ms budget (CPU path: {cpu:.2} ms)"
1721- );
17221750 }
17231751
17241752 /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in
crates/ec-va/src/vpp.rsmodified+49 -0
@@ -95,6 +95,55 @@ impl Vpp {
9595 Ok(surface)
9696 }
9797
98+ /// Convert `source` into `dest` like [`Vpp::convert`], but reading only
99+ /// `source_region` of `source` and writing only `dest_region` of `dest` —
100+ /// no scaling (both regions are the same size in every caller today),
101+ /// just a placement: the pixels outside `dest_region` are left exactly as
102+ /// `dest` already had them. This is how a visible picture smaller than
103+ /// its block-aligned coded surface (e.g. a 2160-tall HEVC source, whose
104+ /// coded height rounds to 2176) lands inside a differently-padded
105+ /// destination without a resize.
106+ pub fn convert_region(
107+ &self,
108+ source: &Arc<Surface>,
109+ source_region: (u32, u32, u32, u32),
110+ dest: Arc<Surface>,
111+ dest_region: (u32, u32, u32, u32),
112+ ) -> Result<Arc<Surface>> {
113+ let sr = sys::VARectangle {
114+ x: source_region.0 as i16,
115+ y: source_region.1 as i16,
116+ width: source_region.2 as u16,
117+ height: source_region.3 as u16,
118+ };
119+ let dr = sys::VARectangle {
120+ x: dest_region.0 as i16,
121+ y: dest_region.1 as i16,
122+ width: dest_region.2 as u16,
123+ height: dest_region.3 as u16,
124+ };
125+ let param = sys::VAProcPipelineParameterBuffer {
126+ surface: source.id(),
127+ surface_region: &sr,
128+ output_region: &dr,
129+ ..Default::default()
130+ };
131+ // SAFETY: `surface_region`/`output_region` point at `sr`/`dr`, which
132+ // outlive this call (built here, read only while `Buffer::from_param`
133+ // constructs the driver buffer below); otherwise identical to
134+ // `convert`'s safety argument.
135+ let buffer = unsafe {
136+ Buffer::from_param(&self.context, sys::VAProcPipelineParameterBufferType, &param)?
137+ };
138+ let surface = Picture::new(&self.context, dest)
139+ .begin()?
140+ .render(buffer)?
141+ .end()?
142+ .sync()?
143+ .into_surface();
144+ Ok(surface)
145+ }
146+
98147 fn context_id(&self) -> sys::VAContextID {
99148 // `Context` does not expose its raw id outside the crate; VPP needs
100149 // it for `vaQueryVideoProcFilters`, which has no typestate-protected