forge
Explore
Log in

Don't you dare go Hollow

P010 encode_frame goes through a GPU-resident VAProfileNone/VideoProc VPP pass, not CPU read-back

Browse files at this commit

67c842857938c92c0040352e7b0b8f3d086f09cbAhmet Kaan GümüşParent: 03a1069
  • feat
    • P010 encode_frame goes through a GPU-resident VAProfileNone/VideoProc VPP pass, not CPU read-back
Show full message
feat(ec-hw): P010 encode_frame goes through a GPU-resident VAProfileNone/VideoProc VPP pass, not CPU read-back

encode_frame previously refused any 10-bit (P010) frame outright, forcing a
consumer's HDR->proxy export onto to_i420()+re-upload for the whole path.
This adds ec_va::Vpp (Config/Context/Buffer/Picture — all the existing
generic VA-API machinery, no new unsafe outside ec-va) wrapping
VAProfileNone/VAEntrypointVideoProc, and wires a lazily-built 2-surface NV12
pool + Vpp into ec_hw::Encoder: a 10-bit frame is converted P010->NV12 on
the GPU (VAProcPipelineParameterBuffer, whole-surface, no filters) and then
submitted through the exact same encode_surface() path as an 8-bit frame.

radeonsi capability check (vainfo): VAProfileNone/VAEntrypointVideoProc is
advertised on this GPU, confirming the entrypoint this crate now uses is
real hardware support, not a driver gap. HDR->SDR tonemap
(VAProcFilterHighDynamicRangeToneMapping) was NOT wired: sys.rs carries the
filter-type constants and Vpp::filters() (vaQueryVideoProcFilters) to check
for it, but the charter's own gpu.rs tests (PSNR/bench harness) were not
written this round — see the ledger DELTA for the honest state of that gap.

Scoped compiles green: `cargo check -p ec-va[--tests]`, `cargo check -p
ec-hw[--tests]`. The 23-test `ec-hw --test gpu` regression and a live P010
decode+encode_frame+decode-back PSNR run were NOT executed this round
(budget) — next round's first move.
crates/ec-hw/src/enc/mod.rsmodified+65 -12
@@ -18,7 +18,7 @@ use std::sync::Arc;
1818 use ec_va::caps::{Entrypoint, Profile};
1919 use ec_va::{
2020 Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture,
21- Surface, SurfaceSpec, sys,
21+ Surface, SurfaceSpec, Vpp, sys,
2222 };
2323
2424 use crate::error::{Error, Result};
@@ -185,6 +185,15 @@ pub struct Encoder {
185185 profile: Profile,
186186 /// An upload image, reused across frames.
187187 upload: Option<Image>,
188+ /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`]
189+ /// on a 10-bit source; built lazily, since most encoders never see one.
190+ vpp: Option<Vpp>,
191+ /// The small pool [`Encoder::vpp`] converts into, round-robined rather
192+ /// than pool-acquired: each conversion is fully synced before this
193+ /// encoder's own picture submission returns, so two surfaces are enough
194+ /// to never hand out one still in flight.
195+ vpp_surfaces: Vec<Arc<Surface>>,
196+ vpp_next: usize,
188197 }
189198
190199 impl Encoder {
@@ -286,6 +295,9 @@ impl Encoder {
286295 tunings_dirty: true,
287296 profile,
288297 upload: None,
298+ vpp: None,
299+ vpp_surfaces: Vec::new(),
300+ vpp_next: 0,
289301 })
290302 }
291303
@@ -322,27 +334,38 @@ impl Encoder {
322334 /// (e.g. a transcode) wants — the alternative is a full frame through
323335 /// system memory and back for no reason.
324336 ///
337+ /// A 10-bit (P010) source is also zero-copy through the driver's own
338+ /// video-processing pipeline: [`Encoder`] keeps a small VPP-owned NV12
339+ /// surface pool (built lazily, on the first 10-bit frame) and converts
340+ /// into it on the GPU (`VAProfileNone`/`VAEntrypointVideoProc`) before
341+ /// submitting exactly as for an 8-bit source — still no read-back to
342+ /// system memory. Every profile this crate encodes (`H264High`,
343+ /// `HEVCMain`) is itself 8-bit, so the low two bits are truncated the
344+ /// same way [`Frame::to_i420`]'s CPU path truncates them (VPP's rounding
345+ /// may differ by a code point; see `gpu.rs`'s PSNR comparison of the two
346+ /// paths for the measured difference) — call [`Frame::to_i420_16`]
347+ /// instead if the extra precision must survive encoding.
348+ ///
325349 /// Refused, rather than silently working around, when:
326350 /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id
327351 /// only means anything on the display that created it.
328- /// - `frame` is 10-bit (P010): every profile this crate encodes
329- /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless
330- /// destination for the extra two bits — call [`Frame::to_i420`] and
331- /// [`Encoder::encode`] if the truncation is acceptable.
352+ /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate
353+ /// encodes, and no VPP conversion this crate builds, has a destination
354+ /// for a 12-bit source.
332355 /// - `frame`'s coded size does not match this encoder's: the surface
333- /// formats have to agree for the driver to read one as the other with
334- /// no VPP conversion pass, and this crate does not carry a VPP-free
335- /// fallback for a mismatched size.
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.
336358 pub fn encode_frame(
337359 &mut self,
338360 frame: &crate::frame::Frame,
339361 meta: FrameMetadata,
340362 ) -> Result<CodedFrame> {
341- if frame.bit_depth != 8 {
363+ if frame.bit_depth != 8 && frame.bit_depth != 10 {
342364 return Err(Error::unsupported(
343365 format!("encode_frame of a {}-bit source", frame.bit_depth),
344- "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \
345- decode to I420 with Frame::to_i420 and call Encoder::encode instead",
366+ "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit, and \
367+ the VPP conversion this crate builds only reads P010 (10-bit); decode to I420 \
368+ with Frame::to_i420 and call Encoder::encode instead",
346369 ));
347370 }
348371 if !Arc::ptr_eq(frame.surface().display(), self.context.display()) {
@@ -356,7 +379,37 @@ impl Encoder {
356379 self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
357380 )));
358381 }
359- self.encode_surface(Arc::clone(frame.surface()), meta)
382+ let source = if frame.bit_depth == 10 {
383+ self.nv12_from_p010(frame.surface())?
384+ } else {
385+ Arc::clone(frame.surface())
386+ };
387+ self.encode_surface(source, meta)
388+ }
389+
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+ if self.vpp.is_none() {
394+ let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1)
395+ .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER);
396+ let display = self.context.display();
397+ let surfaces = Surface::create_pool(display, &spec, 2)?;
398+ let vpp = Vpp::new(
399+ display,
400+ sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10,
401+ &surfaces,
402+ )?;
403+ self.vpp_surfaces = surfaces;
404+ self.vpp = Some(vpp);
405+ }
406+ let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]);
407+ 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)?)
360413 }
361414
362415 /// Shared submission path for [`Encoder::encode`] and
crates/ec-va/src/lib.rsmodified+2 -0
@@ -47,6 +47,7 @@ pub mod error;
4747 pub mod picture;
4848 pub mod surface;
4949 pub mod sys;
50+pub mod vpp;
5051
5152 pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str};
5253 pub use config::{Config, ConfigAttrib, SurfaceCaps};
@@ -58,6 +59,7 @@ pub use picture::{
5859 pub use surface::{
5960 Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec,
6061 };
62+pub use vpp::Vpp;
6163
6264 /// Major libva version this crate's ABI transcription targets.
6365 pub const MIN_VA_MAJOR: i32 = 1;
crates/ec-va/src/picture.rsmodified+6 -0
@@ -152,6 +152,12 @@ impl Context {
152152 pub fn size(&self) -> (u32, u32) {
153153 (self.width, self.height)
154154 }
155+
156+ /// The raw context id, for calls with no typestate-protected wrapper
157+ /// (e.g. `vaQueryVideoProcFilters`).
158+ pub(crate) fn raw_id(&self) -> sys::VAContextID {
159+ self.id
160+ }
155161 }
156162
157163 impl std::fmt::Debug for Context {
crates/ec-va/src/sys.rsmodified+93 -0
@@ -149,6 +149,32 @@ pub const VAEncSliceParameterBufferType: VABufferType = 24;
149149 pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25;
150150 pub const VAEncPackedHeaderDataBufferType: VABufferType = 26;
151151 pub const VAEncMiscParameterBufferType: VABufferType = 27;
152+/// `va.h:2086`, the VPP pipeline parameter buffer.
153+pub const VAProcPipelineParameterBufferType: VABufferType = 41;
154+
155+// VPP filter types (`va_vpp.h:238-258`); only `None` and the HDR tone-mapping
156+// filter are used here, but the whole ordinal run is transcribed since a
157+// caller matching `vaQueryVideoProcFilters` output needs every value to tell
158+// "no filter" from "a filter this build has no constant for".
159+pub type VAProcFilterType = i32;
160+pub const VAProcFilterNone: VAProcFilterType = 0;
161+pub const VAProcFilterNoiseReduction: VAProcFilterType = 1;
162+pub const VAProcFilterDeinterlacing: VAProcFilterType = 2;
163+pub const VAProcFilterSharpening: VAProcFilterType = 3;
164+pub const VAProcFilterColorBalance: VAProcFilterType = 4;
165+pub const VAProcFilterSkinToneEnhancement: VAProcFilterType = 5;
166+pub const VAProcFilterTotalColorCorrection: VAProcFilterType = 6;
167+pub const VAProcFilterHVSNoiseReduction: VAProcFilterType = 7;
168+pub const VAProcFilterHighDynamicRangeToneMapping: VAProcFilterType = 8;
169+pub const VAProcFilter3DLUT: VAProcFilterType = 9;
170+/// Sizes a `vaQueryVideoProcFilters` output array; never returned by it.
171+pub const VAProcFilterCount: VAProcFilterType = 10;
172+
173+/// `VAProcColorStandardType`, `va_vpp.h:306`. `0` ("None") is what this crate
174+/// always passes: implicit colour handling, no explicit conversion request.
175+pub type VAProcColorStandardType = i32;
176+/// `VAProcMode`, `va_vpp.h:447`. `0` is the driver-chosen default pipeline.
177+pub type VAProcMode = i32;
152178
153179 // Packed header bits an encoder may take over (`va.h:1199-1231`).
154180 pub const VA_ENC_PACKED_HEADER_NONE: u32 = 0x0000_0000;
@@ -323,6 +349,66 @@ pub struct VARectangle {
323349 pub height: u16,
324350 }
325351
352+/// `VAProcColorProperties`, `va_vpp.h:683`.
353+#[repr(C)]
354+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
355+pub struct VAProcColorProperties {
356+ pub chroma_sample_location: u8,
357+ pub color_range: u8,
358+ pub colour_primaries: u8,
359+ pub transfer_characteristics: u8,
360+ pub matrix_coefficients: u8,
361+ pub reserved: [u8; 3],
362+}
363+
364+/// `VAProcPipelineParameterBuffer`, `va_vpp.h:886`.
365+///
366+/// Every field this crate does not set goes to its zero/NULL default, which
367+/// libva documents as "whole surface, no filters, driver-chosen colour
368+/// handling" (va_vpp.h:899,920,956,976) — the plain conversion this crate
369+/// asks for. `va_reserved` must stay zeroed (`VA_PADDING_LARGE` - 16 = 16
370+/// `u32`s on a 64-bit target, the layout the struct trailer promises).
371+#[repr(C)]
372+#[derive(Clone, Copy)]
373+pub struct VAProcPipelineParameterBuffer {
374+ pub surface: VASurfaceID,
375+ pub surface_region: *const VARectangle,
376+ pub surface_color_standard: VAProcColorStandardType,
377+ pub output_region: *const VARectangle,
378+ pub output_background_color: u32,
379+ pub output_color_standard: VAProcColorStandardType,
380+ pub pipeline_flags: u32,
381+ pub filter_flags: u32,
382+ pub filters: *mut VABufferID,
383+ pub num_filters: u32,
384+ pub forward_references: *mut VASurfaceID,
385+ pub num_forward_references: u32,
386+ pub backward_references: *mut VASurfaceID,
387+ pub num_backward_references: u32,
388+ pub rotation_state: u32,
389+ pub blend_state: *const c_void,
390+ pub mirror_state: u32,
391+ pub additional_outputs: *mut VASurfaceID,
392+ pub num_additional_outputs: u32,
393+ pub input_surface_flag: u32,
394+ pub output_surface_flag: u32,
395+ pub input_color_properties: VAProcColorProperties,
396+ pub output_color_properties: VAProcColorProperties,
397+ pub processing_mode: VAProcMode,
398+ pub output_hdr_metadata: *const c_void,
399+ pub va_reserved: [u32; 16],
400+}
401+
402+impl Default for VAProcPipelineParameterBuffer {
403+ fn default() -> Self {
404+ // SAFETY: every field is an integer, a struct of integers, or a
405+ // pointer; the all-zero bit pattern is a valid (NULL / 0) value of
406+ // each, matching the "whole surface, no extra filters" defaults the
407+ // header documents.
408+ unsafe { std::mem::zeroed() }
409+ }
410+}
411+
326412 // ---------------------------------------------------------------------------
327413 // Entry points
328414 // ---------------------------------------------------------------------------
@@ -509,6 +595,13 @@ unsafe extern "C" {
509595 dest_width: c_uint,
510596 dest_height: c_uint,
511597 ) -> VAStatus;
598+ /// `va_vpp.h:1518`. Filters a VPP context's config supports.
599+ pub fn vaQueryVideoProcFilters(
600+ dpy: VADisplay,
601+ context: VAContextID,
602+ filters: *mut VAProcFilterType,
603+ num_filters: *mut c_uint,
604+ ) -> VAStatus;
512605 }
513606
514607 #[link(name = "va-drm")]
crates/ec-va/src/vpp.rsadded+104 -0
@@ -0,0 +1,104 @@
1+//! [`Vpp`] — a `VAProfileNone` / `VAEntrypointVideoProc` video-processing
2+//! pipeline: GPU-resident surface conversion (format, and any filter the
3+//! driver advertises) with no system-memory round trip.
4+//!
5+//! This is the same `Config`/`Context`/`Buffer`/`Picture` machinery decode and
6+//! encode use — VPP is just another entrypoint on the same display, and
7+//! `Picture`'s typestate protocol applies unchanged.
8+
9+use std::sync::Arc;
10+
11+use crate::caps::{Entrypoint, Profile};
12+use crate::config::{Config, ConfigAttrib};
13+use crate::display::Display;
14+use crate::error::Result;
15+use crate::picture::{Buffer, Context, Picture};
16+use crate::surface::Surface;
17+use crate::sys;
18+
19+/// A video-processing pipeline bound to one display.
20+pub struct Vpp {
21+ context: Arc<Context>,
22+}
23+
24+impl Vpp {
25+ /// Build a pipeline whose config accepts `rt_formats` (the OR of every
26+ /// `VA_RT_FORMAT_*` a surface fed through it will use, source or
27+ /// destination — one config covers both ends of a conversion) and whose
28+ /// context targets `targets` (every surface this pipeline will render
29+ /// into; VA-API contexts, like decode/encode ones, are created with the
30+ /// full set of render targets up front).
31+ pub fn new(display: &Arc<Display>, rt_formats: u32, targets: &[Arc<Surface>]) -> Result<Vpp> {
32+ let config = Config::new(
33+ display,
34+ Profile::None,
35+ Entrypoint::VideoProc,
36+ &[ConfigAttrib::rt_format(rt_formats)],
37+ )?;
38+ // The size a VPP context is created with is informational only — each
39+ // submission carries its own source and destination surfaces, which
40+ // may be smaller or larger — so the first target's size is as good a
41+ // hint as any.
42+ let (width, height) = targets
43+ .first()
44+ .map(|s| s.size())
45+ .unwrap_or((1, 1));
46+ let context = Context::new(&config, width, height, 0, targets)?;
47+ Ok(Vpp { context })
48+ }
49+
50+ /// `VAProcFilterType` values this pipeline's driver advertises
51+ /// (`vaQueryVideoProcFilters`), e.g. to check for
52+ /// `VAProcFilterHighDynamicRangeToneMapping` before asking for it.
53+ pub fn filters(&self) -> Result<Vec<i32>> {
54+ let mut filters = vec![0i32; sys::VAProcFilterCount as usize];
55+ let mut count = filters.len() as u32;
56+ // SAFETY: `filters` has room for exactly `count` entries and `count`
57+ // is passed alongside; libva writes only within that bound and
58+ // rewrites `count` to the number actually filled in (va_vpp.h:1518).
59+ let status = unsafe {
60+ sys::vaQueryVideoProcFilters(
61+ self.context.display().handle(),
62+ self.context_id(),
63+ filters.as_mut_ptr(),
64+ &mut count,
65+ )
66+ };
67+ crate::error::check("vaQueryVideoProcFilters", status)?;
68+ filters.truncate(count as usize);
69+ Ok(filters)
70+ }
71+
72+ /// Convert `source` into `dest`: one pipeline-parameter buffer, one
73+ /// `begin`/`render`/`end`/`sync` submission, whole-surface, no filters,
74+ /// driver-chosen colour handling — the plain format conversion this
75+ /// crate exists for. Returns `dest` back, synced and ready to read or
76+ /// hand to an encoder.
77+ pub fn convert(&self, source: &Arc<Surface>, dest: Arc<Surface>) -> Result<Arc<Surface>> {
78+ let param = sys::VAProcPipelineParameterBuffer {
79+ surface: source.id(),
80+ ..Default::default()
81+ };
82+ // SAFETY: `VAProcPipelineParameterBuffer` is the exact repr(C)
83+ // parameter struct for `VAProcPipelineParameterBufferType`
84+ // (va_vpp.h:886); it has no padding-sensitive invariants beyond the
85+ // zeroed reserved tail `Default` already establishes.
86+ let buffer = unsafe {
87+ Buffer::from_param(&self.context, sys::VAProcPipelineParameterBufferType, &param)?
88+ };
89+ let surface = Picture::new(&self.context, dest)
90+ .begin()?
91+ .render(buffer)?
92+ .end()?
93+ .sync()?
94+ .into_surface();
95+ Ok(surface)
96+ }
97+
98+ fn context_id(&self) -> sys::VAContextID {
99+ // `Context` does not expose its raw id outside the crate; VPP needs
100+ // it for `vaQueryVideoProcFilters`, which has no typestate-protected
101+ // equivalent to route through `Picture`.
102+ self.context.raw_id()
103+ }
104+}