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-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index a6928ac4..91904af6 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -1508,6 +1508,219 @@ fn ten_bit_4k_frame_path_is_realtime() { println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}"); } +const REELD: &str = "/home/user/Downloads/reeld\ + /reeld.mkv"; + +/// `Encoder::encode_frame` of a 10-bit (P010) source, through the VPP +/// NV12 conversion, against the CPU path (`to_i420` + `encode`) — the same +/// shape as `encode_frame_zero_copy_matches_the_cpu_path`, but for a real +/// P010 4K HDR source instead of a synthetic 8-bit one, and comparing Y and +/// UV PSNR separately rather than the combined figure. +#[test] +fn encode_frame_accepts_p010_via_vpp() { + let Some(display) = display() else { return }; + let path = Path::new(REELD); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let frames = 10usize; + let Some(data) = elementary(path, Codec::H265, frames) else { + eprintln!("skipped: no elementary stream"); + return; + }; + + // 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. + 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(); + let mut cpu_stream = Vec::new(); + let mut count = 0i64; + let mut zero_copy: Option = None; + let mut cpu_path: Option = None; + let mut refused = false; + + decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { + if refused { + return; + } + let (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; + cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; + Encoder::new(&display, cfg).expect("zero-copy encoder opens") + }); + let cpu_path = cpu_path.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("cpu-path encoder opens") + }); + let meta = FrameMetadata { + 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 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); + count += 1; + }) + .expect("decode"); + if refused { + continue; + } + assert_eq!( + count as usize, frames, + "{target:?}: decoded {count} of {frames}" + ); + + let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); + let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); + let mut zc_frames = Vec::new(); + let mut cpu_frames = Vec::new(); + decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { + zc_frames.push(f.to_i420().expect("readback")) + }) + .expect("decode zero-copy stream"); + decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { + cpu_frames.push(f.to_i420().expect("readback")) + }) + .expect("decode CPU-path stream"); + assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy frame count"); + assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path frame count"); + + let widen = |v: &[u8]| -> Vec { v.iter().map(|&s| u16::from(s)).collect() }; + let mut worst_y = f64::INFINITY; + let mut worst_uv = f64::INFINITY; + for (a, b) in zc_frames.iter().zip(&cpu_frames) { + let y_db = plane_psnr(&widen(&a.y), &widen(&b.y), 255.0); + let uv_db = plane_psnr( + &[widen(&a.u), widen(&a.v)].concat(), + &[widen(&b.u), widen(&b.v)].concat(), + 255.0, + ); + worst_y = worst_y.min(y_db); + worst_uv = worst_uv.min(uv_db); + } + 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"); + } +} + +/// Median ms/frame at 3840x2160 for `decode+encode_frame` (P010 zero-copy, +/// through VPP) against `decode+to_i420+encode` (CPU path) — the number that +/// 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. +#[test] +fn p010_zero_copy_encode_is_realtime() { + let Some(display) = display() else { return }; + let path = Path::new(REELD); + if !path.exists() { + eprintln!("skipped: film not present"); + return; + } + let limit = 60usize; + let Some(data) = elementary(path, Codec::H265, limit) else { + eprintln!("skipped: no elementary stream"); + return; + }; + 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; + } + } + } + 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:<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 /// decode order, even though they display before it (they predict from /// pictures the CRA's own random-access point does not have). A decoder 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..ea73d487 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")] @@ -580,6 +673,24 @@ const _: () = { assert!(size_of::() == 8 && align_of::() == 2); + assert!( + size_of::() == 8 && align_of::() == 1 + ); + + // 64-bit `va_vpp.h:886`: 25 fields down to `output_hdr_metadata` (152 + // bytes on this target) plus `va_reserved[VA_PADDING_LARGE - 16]` (16 + // `u32`s, 64 bytes) = 224. + assert!( + size_of::() == 224 + && align_of::() == 8 + ); + assert!(offset_of!(VAProcPipelineParameterBuffer, surface_region) == 8); + assert!(offset_of!(VAProcPipelineParameterBuffer, input_color_properties) == 132); + assert!(offset_of!(VAProcPipelineParameterBuffer, output_color_properties) == 140); + assert!(offset_of!(VAProcPipelineParameterBuffer, processing_mode) == 148); + assert!(offset_of!(VAProcPipelineParameterBuffer, output_hdr_metadata) == 152); + assert!(offset_of!(VAProcPipelineParameterBuffer, va_reserved) == 160); + // Assumption 2: C `enum` and `unsigned int` are both 4 bytes here. assert!(size_of::() == 4); assert!(size_of::() == 4); 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() + } +} diff --git a/crates/ec-va/tests/gpu.rs b/crates/ec-va/tests/gpu.rs index b91d727b..5eda1fc7 100644 --- a/crates/ec-va/tests/gpu.rs +++ b/crates/ec-va/tests/gpu.rs @@ -477,6 +477,51 @@ fn context_keeps_its_dependencies_alive() { assert!(display.is_valid()); } +// -------------------------------------------------------------------------- +// VPP +// -------------------------------------------------------------------------- + +/// `vaQueryVideoProcFilters` on the real display: whatever this driver +/// advertises, the call must succeed and return values `Vpp` can act on. Not +/// a claim about which filters exist — radeonsi's list is print-only here — +/// just that the query path works end to end. +#[test] +fn vpp_filters_probe() { + let _serial = serial(); + let display = display(); + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1080), 1).expect("pool"); + let vpp = ec_va::Vpp::new(&display, sys::VA_RT_FORMAT_YUV420, &targets).expect("vpp opens"); + let filters = vpp.filters().expect("vaQueryVideoProcFilters"); + println!("radeonsi VAProcFilterType list: {filters:?}"); + println!( + "HighDynamicRangeToneMapping (8) advertised: {}", + filters.contains(&sys::VAProcFilterHighDynamicRangeToneMapping) + ); +} + +/// `Vpp::convert` end to end: a P010 source surface into an NV12 destination, +/// no readback — the conversion `ec-hw`'s `encode_frame` relies on for a +/// 10-bit source. +#[test] +fn vpp_converts_p010_to_nv12() { + let _serial = serial(); + let display = display(); + let src_spec = SurfaceSpec::p010(64, 64); + let source = Surface::create(&display, &src_spec).expect("p010 source surface"); + let dest_targets = Surface::create_pool(&display, &SurfaceSpec::nv12(64, 64), 1).expect("pool"); + let vpp = ec_va::Vpp::new( + &display, + sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10, + &dest_targets, + ) + .expect("vpp opens"); + let dest = vpp + .convert(&source, Arc::clone(&dest_targets[0])) + .expect("convert"); + assert_eq!(dest.id(), dest_targets[0].id()); + assert!(display.is_valid()); +} + // -------------------------------------------------------------------------- // helpers // --------------------------------------------------------------------------