diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index c71c6402..317b1b7c 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use ec_va::caps::{Entrypoint, Profile}; use ec_va::{ Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture, - Surface, SurfaceSpec, sys, + Surface, SurfaceSpec, Vpp, sys, }; use crate::error::{Error, Result}; @@ -185,6 +185,15 @@ pub struct Encoder { profile: Profile, /// An upload image, reused across frames. upload: Option, + /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] + /// on a 10-bit source; built lazily, since most encoders never see one. + vpp: Option, + /// The small pool [`Encoder::vpp`] converts into, round-robined rather + /// than pool-acquired: each conversion is fully synced before this + /// encoder's own picture submission returns, so two surfaces are enough + /// to never hand out one still in flight. + vpp_surfaces: Vec>, + vpp_next: usize, } impl Encoder { @@ -286,6 +295,9 @@ impl Encoder { tunings_dirty: true, profile, upload: None, + vpp: None, + vpp_surfaces: Vec::new(), + vpp_next: 0, }) } @@ -322,27 +334,38 @@ impl Encoder { /// (e.g. a transcode) wants — the alternative is a full frame through /// system memory and back for no reason. /// + /// A 10-bit (P010) source is also zero-copy through the driver's own + /// video-processing pipeline: [`Encoder`] keeps a small VPP-owned NV12 + /// surface pool (built lazily, on the first 10-bit frame) and converts + /// into it on the GPU (`VAProfileNone`/`VAEntrypointVideoProc`) before + /// submitting exactly as for an 8-bit source — still no read-back to + /// system memory. Every profile this crate encodes (`H264High`, + /// `HEVCMain`) is itself 8-bit, so the low two bits are truncated the + /// same way [`Frame::to_i420`]'s CPU path truncates them (VPP's rounding + /// may differ by a code point; see `gpu.rs`'s PSNR comparison of the two + /// paths for the measured difference) — call [`Frame::to_i420_16`] + /// instead if the extra precision must survive encoding. + /// /// Refused, rather than silently working around, when: /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id /// only means anything on the display that created it. - /// - `frame` is 10-bit (P010): every profile this crate encodes - /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless - /// destination for the extra two bits — call [`Frame::to_i420`] and - /// [`Encoder::encode`] if the truncation is acceptable. + /// - `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 with - /// no VPP conversion pass, and this crate does not carry a VPP-free - /// fallback for a mismatched size. + /// formats have to agree for the driver to read one as the other, and + /// the VPP conversion pass (when one runs) does not resize. pub fn encode_frame( &mut self, frame: &crate::frame::Frame, meta: FrameMetadata, ) -> Result { - if frame.bit_depth != 8 { + if frame.bit_depth != 8 && frame.bit_depth != 10 { return Err(Error::unsupported( format!("encode_frame of a {}-bit source", frame.bit_depth), - "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \ - decode to I420 with Frame::to_i420 and call Encoder::encode instead", + "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit, and \ + the VPP conversion this crate builds only reads P010 (10-bit); decode to I420 \ + with Frame::to_i420 and call Encoder::encode instead", )); } if !Arc::ptr_eq(frame.surface().display(), self.context.display()) { @@ -356,7 +379,37 @@ impl Encoder { self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1 ))); } - self.encode_surface(Arc::clone(frame.surface()), meta) + let source = if frame.bit_depth == 10 { + self.nv12_from_p010(frame.surface())? + } 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> { + 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)?; + let vpp = Vpp::new( + display, + sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10, + &surfaces, + )?; + self.vpp_surfaces = surfaces; + self.vpp = Some(vpp); + } + 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)?) } /// Shared submission path for [`Encoder::encode`] and diff --git a/crates/ec-va/src/lib.rs b/crates/ec-va/src/lib.rs index 2b86750a..e06eaabd 100644 --- a/crates/ec-va/src/lib.rs +++ b/crates/ec-va/src/lib.rs @@ -47,6 +47,7 @@ pub mod error; pub mod picture; pub mod surface; pub mod sys; +pub mod vpp; pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str}; pub use config::{Config, ConfigAttrib, SurfaceCaps}; @@ -58,6 +59,7 @@ pub use picture::{ pub use surface::{ Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec, }; +pub use vpp::Vpp; /// Major libva version this crate's ABI transcription targets. pub const MIN_VA_MAJOR: i32 = 1; diff --git a/crates/ec-va/src/picture.rs b/crates/ec-va/src/picture.rs index bdbf2b30..fcfa2c82 100644 --- a/crates/ec-va/src/picture.rs +++ b/crates/ec-va/src/picture.rs @@ -152,6 +152,12 @@ impl Context { pub fn size(&self) -> (u32, u32) { (self.width, self.height) } + + /// The raw context id, for calls with no typestate-protected wrapper + /// (e.g. `vaQueryVideoProcFilters`). + pub(crate) fn raw_id(&self) -> sys::VAContextID { + self.id + } } impl std::fmt::Debug for Context { diff --git a/crates/ec-va/src/sys.rs b/crates/ec-va/src/sys.rs index 16c1511a..a568f409 100644 --- a/crates/ec-va/src/sys.rs +++ b/crates/ec-va/src/sys.rs @@ -149,6 +149,32 @@ pub const VAEncSliceParameterBufferType: VABufferType = 24; pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25; pub const VAEncPackedHeaderDataBufferType: VABufferType = 26; pub const VAEncMiscParameterBufferType: VABufferType = 27; +/// `va.h:2086`, the VPP pipeline parameter buffer. +pub const VAProcPipelineParameterBufferType: VABufferType = 41; + +// VPP filter types (`va_vpp.h:238-258`); only `None` and the HDR tone-mapping +// filter are used here, but the whole ordinal run is transcribed since a +// caller matching `vaQueryVideoProcFilters` output needs every value to tell +// "no filter" from "a filter this build has no constant for". +pub type VAProcFilterType = i32; +pub const VAProcFilterNone: VAProcFilterType = 0; +pub const VAProcFilterNoiseReduction: VAProcFilterType = 1; +pub const VAProcFilterDeinterlacing: VAProcFilterType = 2; +pub const VAProcFilterSharpening: VAProcFilterType = 3; +pub const VAProcFilterColorBalance: VAProcFilterType = 4; +pub const VAProcFilterSkinToneEnhancement: VAProcFilterType = 5; +pub const VAProcFilterTotalColorCorrection: VAProcFilterType = 6; +pub const VAProcFilterHVSNoiseReduction: VAProcFilterType = 7; +pub const VAProcFilterHighDynamicRangeToneMapping: VAProcFilterType = 8; +pub const VAProcFilter3DLUT: VAProcFilterType = 9; +/// Sizes a `vaQueryVideoProcFilters` output array; never returned by it. +pub const VAProcFilterCount: VAProcFilterType = 10; + +/// `VAProcColorStandardType`, `va_vpp.h:306`. `0` ("None") is what this crate +/// always passes: implicit colour handling, no explicit conversion request. +pub type VAProcColorStandardType = i32; +/// `VAProcMode`, `va_vpp.h:447`. `0` is the driver-chosen default pipeline. +pub type VAProcMode = i32; // Packed header bits an encoder may take over (`va.h:1199-1231`). pub const VA_ENC_PACKED_HEADER_NONE: u32 = 0x0000_0000; @@ -323,6 +349,66 @@ pub struct VARectangle { pub height: u16, } +/// `VAProcColorProperties`, `va_vpp.h:683`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct VAProcColorProperties { + pub chroma_sample_location: u8, + pub color_range: u8, + pub colour_primaries: u8, + pub transfer_characteristics: u8, + pub matrix_coefficients: u8, + pub reserved: [u8; 3], +} + +/// `VAProcPipelineParameterBuffer`, `va_vpp.h:886`. +/// +/// Every field this crate does not set goes to its zero/NULL default, which +/// libva documents as "whole surface, no filters, driver-chosen colour +/// handling" (va_vpp.h:899,920,956,976) — the plain conversion this crate +/// asks for. `va_reserved` must stay zeroed (`VA_PADDING_LARGE` - 16 = 16 +/// `u32`s on a 64-bit target, the layout the struct trailer promises). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VAProcPipelineParameterBuffer { + pub surface: VASurfaceID, + pub surface_region: *const VARectangle, + pub surface_color_standard: VAProcColorStandardType, + pub output_region: *const VARectangle, + pub output_background_color: u32, + pub output_color_standard: VAProcColorStandardType, + pub pipeline_flags: u32, + pub filter_flags: u32, + pub filters: *mut VABufferID, + pub num_filters: u32, + pub forward_references: *mut VASurfaceID, + pub num_forward_references: u32, + pub backward_references: *mut VASurfaceID, + pub num_backward_references: u32, + pub rotation_state: u32, + pub blend_state: *const c_void, + pub mirror_state: u32, + pub additional_outputs: *mut VASurfaceID, + pub num_additional_outputs: u32, + pub input_surface_flag: u32, + pub output_surface_flag: u32, + pub input_color_properties: VAProcColorProperties, + pub output_color_properties: VAProcColorProperties, + pub processing_mode: VAProcMode, + pub output_hdr_metadata: *const c_void, + pub va_reserved: [u32; 16], +} + +impl Default for VAProcPipelineParameterBuffer { + fn default() -> Self { + // SAFETY: every field is an integer, a struct of integers, or a + // pointer; the all-zero bit pattern is a valid (NULL / 0) value of + // each, matching the "whole surface, no extra filters" defaults the + // header documents. + unsafe { std::mem::zeroed() } + } +} + // --------------------------------------------------------------------------- // Entry points // --------------------------------------------------------------------------- @@ -509,6 +595,13 @@ unsafe extern "C" { dest_width: c_uint, dest_height: c_uint, ) -> VAStatus; + /// `va_vpp.h:1518`. Filters a VPP context's config supports. + pub fn vaQueryVideoProcFilters( + dpy: VADisplay, + context: VAContextID, + filters: *mut VAProcFilterType, + num_filters: *mut c_uint, + ) -> VAStatus; } #[link(name = "va-drm")] diff --git a/crates/ec-va/src/vpp.rs b/crates/ec-va/src/vpp.rs new file mode 100644 index 00000000..505132d5 --- /dev/null +++ b/crates/ec-va/src/vpp.rs @@ -0,0 +1,104 @@ +//! [`Vpp`] — a `VAProfileNone` / `VAEntrypointVideoProc` video-processing +//! pipeline: GPU-resident surface conversion (format, and any filter the +//! driver advertises) with no system-memory round trip. +//! +//! This is the same `Config`/`Context`/`Buffer`/`Picture` machinery decode and +//! encode use — VPP is just another entrypoint on the same display, and +//! `Picture`'s typestate protocol applies unchanged. + +use std::sync::Arc; + +use crate::caps::{Entrypoint, Profile}; +use crate::config::{Config, ConfigAttrib}; +use crate::display::Display; +use crate::error::Result; +use crate::picture::{Buffer, Context, Picture}; +use crate::surface::Surface; +use crate::sys; + +/// A video-processing pipeline bound to one display. +pub struct Vpp { + context: Arc, +} + +impl Vpp { + /// Build a pipeline whose config accepts `rt_formats` (the OR of every + /// `VA_RT_FORMAT_*` a surface fed through it will use, source or + /// destination — one config covers both ends of a conversion) and whose + /// context targets `targets` (every surface this pipeline will render + /// into; VA-API contexts, like decode/encode ones, are created with the + /// full set of render targets up front). + pub fn new(display: &Arc, rt_formats: u32, targets: &[Arc]) -> Result { + let config = Config::new( + display, + Profile::None, + Entrypoint::VideoProc, + &[ConfigAttrib::rt_format(rt_formats)], + )?; + // The size a VPP context is created with is informational only — each + // submission carries its own source and destination surfaces, which + // may be smaller or larger — so the first target's size is as good a + // hint as any. + let (width, height) = targets + .first() + .map(|s| s.size()) + .unwrap_or((1, 1)); + let context = Context::new(&config, width, height, 0, targets)?; + Ok(Vpp { context }) + } + + /// `VAProcFilterType` values this pipeline's driver advertises + /// (`vaQueryVideoProcFilters`), e.g. to check for + /// `VAProcFilterHighDynamicRangeToneMapping` before asking for it. + pub fn filters(&self) -> Result> { + let mut filters = vec![0i32; sys::VAProcFilterCount as usize]; + let mut count = filters.len() as u32; + // SAFETY: `filters` has room for exactly `count` entries and `count` + // is passed alongside; libva writes only within that bound and + // rewrites `count` to the number actually filled in (va_vpp.h:1518). + let status = unsafe { + sys::vaQueryVideoProcFilters( + self.context.display().handle(), + self.context_id(), + filters.as_mut_ptr(), + &mut count, + ) + }; + crate::error::check("vaQueryVideoProcFilters", status)?; + filters.truncate(count as usize); + Ok(filters) + } + + /// Convert `source` into `dest`: one pipeline-parameter buffer, one + /// `begin`/`render`/`end`/`sync` submission, whole-surface, no filters, + /// driver-chosen colour handling — the plain format conversion this + /// crate exists for. Returns `dest` back, synced and ready to read or + /// hand to an encoder. + pub fn convert(&self, source: &Arc, dest: Arc) -> Result> { + let param = sys::VAProcPipelineParameterBuffer { + surface: source.id(), + ..Default::default() + }; + // SAFETY: `VAProcPipelineParameterBuffer` is the exact repr(C) + // parameter struct for `VAProcPipelineParameterBufferType` + // (va_vpp.h:886); it has no padding-sensitive invariants beyond the + // zeroed reserved tail `Default` already establishes. + 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 + // equivalent to route through `Picture`. + self.context.raw_id() + } +}