forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'ec-hw-vpp-p010'

Browse files at this commit

ca94f2420791eb439636b86ac2015a1f95ec8b26Ahmet Kaan GümüşParent: 2b4d691cffd9af
crates/ec-hw/src/enc/mod.rsmodified+65 -12
@@ -18,7 +18,7 @@ use std::sync::Arc;
18 use ec_va::caps::{Entrypoint, Profile};18 use ec_va::caps::{Entrypoint, Profile};
19 use ec_va::{19 use ec_va::{
20 Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture,20 Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture,
21- Surface, SurfaceSpec, sys,21+ Surface, SurfaceSpec, Vpp, sys,
22 };22 };
23 23
24 use crate::error::{Error, Result};24 use crate::error::{Error, Result};
@@ -185,6 +185,15 @@ pub struct Encoder {
185 profile: Profile,185 profile: Profile,
186 /// An upload image, reused across frames.186 /// An upload image, reused across frames.
187 upload: Option<Image>,187 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,
188 }197 }
189 198
190 impl Encoder {199 impl Encoder {
@@ -286,6 +295,9 @@ impl Encoder {
286 tunings_dirty: true,295 tunings_dirty: true,
287 profile,296 profile,
288 upload: None,297 upload: None,
298+ vpp: None,
299+ vpp_surfaces: Vec::new(),
300+ vpp_next: 0,
289 })301 })
290 }302 }
291 303
@@ -322,27 +334,38 @@ impl Encoder {
322 /// (e.g. a transcode) wants — the alternative is a full frame through334 /// (e.g. a transcode) wants — the alternative is a full frame through
323 /// system memory and back for no reason.335 /// system memory and back for no reason.
324 ///336 ///
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+ ///
325 /// Refused, rather than silently working around, when:349 /// Refused, rather than silently working around, when:
326 /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id350 /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id
327 /// only means anything on the display that created it.351 /// only means anything on the display that created it.
328- /// - `frame` is 10-bit (P010): every profile this crate encodes352+ /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate
329- /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless353+ /// encodes, and no VPP conversion this crate builds, has a destination
330- /// destination for the extra two bits — call [`Frame::to_i420`] and354+ /// for a 12-bit source.
331- /// [`Encoder::encode`] if the truncation is acceptable.
332 /// - `frame`'s coded size does not match this encoder's: the surface355 /// - `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 with356+ /// formats have to agree for the driver to read one as the other, and
334- /// no VPP conversion pass, and this crate does not carry a VPP-free357+ /// the VPP conversion pass (when one runs) does not resize.
335- /// fallback for a mismatched size.
336 pub fn encode_frame(358 pub fn encode_frame(
337 &mut self,359 &mut self,
338 frame: &crate::frame::Frame,360 frame: &crate::frame::Frame,
339 meta: FrameMetadata,361 meta: FrameMetadata,
340 ) -> Result<CodedFrame> {362 ) -> Result<CodedFrame> {
341- if frame.bit_depth != 8 {363+ if frame.bit_depth != 8 && frame.bit_depth != 10 {
342 return Err(Error::unsupported(364 return Err(Error::unsupported(
343 format!("encode_frame of a {}-bit source", frame.bit_depth),365 format!("encode_frame of a {}-bit source", frame.bit_depth),
344- "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \366+ "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit, and \
345- decode to I420 with Frame::to_i420 and call Encoder::encode instead",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",
346 ));369 ));
347 }370 }
348 if !Arc::ptr_eq(frame.surface().display(), self.context.display()) {371 if !Arc::ptr_eq(frame.surface().display(), self.context.display()) {
@@ -356,7 +379,37 @@ impl Encoder {
356 self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1379 self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
357 )));380 )));
358 }381 }
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)?)
360 }413 }
361 414
362 /// Shared submission path for [`Encoder::encode`] and415 /// Shared submission path for [`Encoder::encode`] and
crates/ec-hw/tests/gpu.rsmodified+213 -0
@@ -1508,6 +1508,219 @@ fn ten_bit_4k_frame_path_is_realtime() {
1508 println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}");1508 println!("target: decode+to_i420_16 <= 39.00 ms/frame median (24 fps budget); got {got:.2}");
1509 }1509 }
1510 1510
1511+const REELD: &str = "/home/user/Downloads/reeld\
1512+ /reeld.mkv";
1513+
1514+/// `Encoder::encode_frame` of a 10-bit (P010) source, through the VPP
1515+/// NV12 conversion, against the CPU path (`to_i420` + `encode`) — the same
1516+/// shape as `encode_frame_zero_copy_matches_the_cpu_path`, but for a real
1517+/// P010 4K HDR source instead of a synthetic 8-bit one, and comparing Y and
1518+/// UV PSNR separately rather than the combined figure.
1519+#[test]
1520+fn encode_frame_accepts_p010_via_vpp() {
1521+ let Some(display) = display() else { return };
1522+ let path = Path::new(REELD);
1523+ if !path.exists() {
1524+ eprintln!("skipped: film not present");
1525+ return;
1526+ }
1527+ let frames = 10usize;
1528+ let Some(data) = elementary(path, Codec::H265, frames) else {
1529+ eprintln!("skipped: no elementary stream");
1530+ return;
1531+ };
1532+
1533+ // 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.
1541+ for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
1542+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1543+ let mut zc_stream = Vec::new();
1544+ let mut cpu_stream = Vec::new();
1545+ let mut count = 0i64;
1546+ let mut zero_copy: Option<Encoder> = None;
1547+ let mut cpu_path: Option<Encoder> = None;
1548+ let mut refused = false;
1549+
1550+ decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| {
1551+ if refused {
1552+ return;
1553+ }
1554+ let (w, h) = frame.display_size;
1555+ let zero_copy = zero_copy.get_or_insert_with(|| {
1556+ let mut cfg = EncoderConfig::new(target, w, h);
1557+ cfg.gop_size = 30;
1558+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1559+ Encoder::new(&display, cfg).expect("zero-copy encoder opens")
1560+ });
1561+ let cpu_path = cpu_path.get_or_insert_with(|| {
1562+ let mut cfg = EncoderConfig::new(target, w, h);
1563+ cfg.gop_size = 30;
1564+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
1565+ Encoder::new(&display, cfg).expect("cpu-path encoder opens")
1566+ });
1567+ let meta = FrameMetadata {
1568+ timestamp: count,
1569+ force_keyframe: false,
1570+ };
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+ }
1587+ let i420 = frame.to_i420().expect("readback for the CPU-path baseline");
1588+ let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)");
1589+ cpu_stream.extend_from_slice(&cpu.data);
1590+ count += 1;
1591+ })
1592+ .expect("decode");
1593+ if refused {
1594+ continue;
1595+ }
1596+ assert_eq!(
1597+ count as usize, frames,
1598+ "{target:?}: decoded {count} of {frames}"
1599+ );
1600+
1601+ let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens");
1602+ let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens");
1603+ let mut zc_frames = Vec::new();
1604+ let mut cpu_frames = Vec::new();
1605+ decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| {
1606+ zc_frames.push(f.to_i420().expect("readback"))
1607+ })
1608+ .expect("decode zero-copy stream");
1609+ decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| {
1610+ cpu_frames.push(f.to_i420().expect("readback"))
1611+ })
1612+ .expect("decode CPU-path stream");
1613+ assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy frame count");
1614+ assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path frame count");
1615+
1616+ let widen = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() };
1617+ let mut worst_y = f64::INFINITY;
1618+ let mut worst_uv = f64::INFINITY;
1619+ for (a, b) in zc_frames.iter().zip(&cpu_frames) {
1620+ let y_db = plane_psnr(&widen(&a.y), &widen(&b.y), 255.0);
1621+ let uv_db = plane_psnr(
1622+ &[widen(&a.u), widen(&a.v)].concat(),
1623+ &[widen(&b.u), widen(&b.v)].concat(),
1624+ 255.0,
1625+ );
1626+ worst_y = worst_y.min(y_db);
1627+ worst_uv = worst_uv.min(uv_db);
1628+ }
1629+ println!("{target:?} encode_frame (P010 via VPP) vs CPU path: worst Y {worst_y:.1} dB, worst UV {worst_uv:.1} dB");
1630+ assert!(worst_y >= 40.0, "{target:?}: worst Y {worst_y:.1} dB vs the CPU path");
1631+ assert!(worst_uv >= 40.0, "{target:?}: worst UV {worst_uv:.1} dB vs the CPU path");
1632+ }
1633+}
1634+
1635+/// Median ms/frame at 3840x2160 for `decode+encode_frame` (P010 zero-copy,
1636+/// through VPP) against `decode+to_i420+encode` (CPU path) — the number that
1637+/// says whether the VPP conversion is cheap enough to keep the zero-copy path
1638+/// meaningfully faster than reading the frame back to system memory.
1639+///
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.
1646+#[test]
1647+fn p010_zero_copy_encode_is_realtime() {
1648+ let Some(display) = display() else { return };
1649+ let path = Path::new(REELD);
1650+ if !path.exists() {
1651+ eprintln!("skipped: film not present");
1652+ return;
1653+ }
1654+ let limit = 60usize;
1655+ let Some(data) = elementary(path, Codec::H265, limit) else {
1656+ eprintln!("skipped: no elementary stream");
1657+ return;
1658+ };
1659+ let units = split_access_units(&data, Codec::H265);
1660+ assert!(units.len() > limit, "film clip too short for {limit} frames");
1661+
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;
1695+ }
1696+ }
1697+ }
1698+ assert!(
1699+ durations.len() >= limit,
1700+ "{name}: only {} of {limit} frames encoded",
1701+ durations.len()
1702+ );
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+ }
1714+ }
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+ );
1722+}
1723+
1511 /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in1724 /// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in
1512 /// decode order, even though they display before it (they predict from1725 /// decode order, even though they display before it (they predict from
1513 /// pictures the CRA's own random-access point does not have). A decoder1726 /// pictures the CRA's own random-access point does not have). A decoder
crates/ec-va/src/lib.rsmodified+2 -0
@@ -47,6 +47,7 @@ pub mod error;
47 pub mod picture;47 pub mod picture;
48 pub mod surface;48 pub mod surface;
49 pub mod sys;49 pub mod sys;
50+pub mod vpp;
50 51
51 pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str};52 pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str};
52 pub use config::{Config, ConfigAttrib, SurfaceCaps};53 pub use config::{Config, ConfigAttrib, SurfaceCaps};
@@ -58,6 +59,7 @@ pub use picture::{
58 pub use surface::{59 pub use surface::{
59 Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec,60 Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec,
60 };61 };
62+pub use vpp::Vpp;
61 63
62 /// Major libva version this crate's ABI transcription targets.64 /// Major libva version this crate's ABI transcription targets.
63 pub const MIN_VA_MAJOR: i32 = 1;65 pub const MIN_VA_MAJOR: i32 = 1;
crates/ec-va/src/picture.rsmodified+6 -0
@@ -152,6 +152,12 @@ impl Context {
152 pub fn size(&self) -> (u32, u32) {152 pub fn size(&self) -> (u32, u32) {
153 (self.width, self.height)153 (self.width, self.height)
154 }154 }
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+ }
155 }161 }
156 162
157 impl std::fmt::Debug for Context {163 impl std::fmt::Debug for Context {
crates/ec-va/src/sys.rsmodified+111 -0
@@ -149,6 +149,32 @@ pub const VAEncSliceParameterBufferType: VABufferType = 24;
149 pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25;149 pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25;
150 pub const VAEncPackedHeaderDataBufferType: VABufferType = 26;150 pub const VAEncPackedHeaderDataBufferType: VABufferType = 26;
151 pub const VAEncMiscParameterBufferType: VABufferType = 27;151 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;
152 178
153 // Packed header bits an encoder may take over (`va.h:1199-1231`).179 // Packed header bits an encoder may take over (`va.h:1199-1231`).
154 pub const VA_ENC_PACKED_HEADER_NONE: u32 = 0x0000_0000;180 pub const VA_ENC_PACKED_HEADER_NONE: u32 = 0x0000_0000;
@@ -323,6 +349,66 @@ pub struct VARectangle {
323 pub height: u16,349 pub height: u16,
324 }350 }
325 351
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+
326 // ---------------------------------------------------------------------------412 // ---------------------------------------------------------------------------
327 // Entry points413 // Entry points
328 // ---------------------------------------------------------------------------414 // ---------------------------------------------------------------------------
@@ -509,6 +595,13 @@ unsafe extern "C" {
509 dest_width: c_uint,595 dest_width: c_uint,
510 dest_height: c_uint,596 dest_height: c_uint,
511 ) -> VAStatus;597 ) -> 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;
512 }605 }
513 606
514 #[link(name = "va-drm")]607 #[link(name = "va-drm")]
@@ -580,6 +673,24 @@ const _: () = {
580 673
581 assert!(size_of::<VARectangle>() == 8 && align_of::<VARectangle>() == 2);674 assert!(size_of::<VARectangle>() == 8 && align_of::<VARectangle>() == 2);
582 675
676+ assert!(
677+ size_of::<VAProcColorProperties>() == 8 && align_of::<VAProcColorProperties>() == 1
678+ );
679+
680+ // 64-bit `va_vpp.h:886`: 25 fields down to `output_hdr_metadata` (152
681+ // bytes on this target) plus `va_reserved[VA_PADDING_LARGE - 16]` (16
682+ // `u32`s, 64 bytes) = 224.
683+ assert!(
684+ size_of::<VAProcPipelineParameterBuffer>() == 224
685+ && align_of::<VAProcPipelineParameterBuffer>() == 8
686+ );
687+ assert!(offset_of!(VAProcPipelineParameterBuffer, surface_region) == 8);
688+ assert!(offset_of!(VAProcPipelineParameterBuffer, input_color_properties) == 132);
689+ assert!(offset_of!(VAProcPipelineParameterBuffer, output_color_properties) == 140);
690+ assert!(offset_of!(VAProcPipelineParameterBuffer, processing_mode) == 148);
691+ assert!(offset_of!(VAProcPipelineParameterBuffer, output_hdr_metadata) == 152);
692+ assert!(offset_of!(VAProcPipelineParameterBuffer, va_reserved) == 160);
693+
583 // Assumption 2: C `enum` and `unsigned int` are both 4 bytes here.694 // Assumption 2: C `enum` and `unsigned int` are both 4 bytes here.
584 assert!(size_of::<VAStatus>() == 4);695 assert!(size_of::<VAStatus>() == 4);
585 assert!(size_of::<VAGenericID>() == 4);696 assert!(size_of::<VAGenericID>() == 4);
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+}
crates/ec-va/tests/gpu.rsmodified+45 -0
@@ -477,6 +477,51 @@ fn context_keeps_its_dependencies_alive() {
477 assert!(display.is_valid());477 assert!(display.is_valid());
478 }478 }
479 479
480+// --------------------------------------------------------------------------
481+// VPP
482+// --------------------------------------------------------------------------
483+
484+/// `vaQueryVideoProcFilters` on the real display: whatever this driver
485+/// advertises, the call must succeed and return values `Vpp` can act on. Not
486+/// a claim about which filters exist — radeonsi's list is print-only here —
487+/// just that the query path works end to end.
488+#[test]
489+fn vpp_filters_probe() {
490+ let _serial = serial();
491+ let display = display();
492+ let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1080), 1).expect("pool");
493+ let vpp = ec_va::Vpp::new(&display, sys::VA_RT_FORMAT_YUV420, &targets).expect("vpp opens");
494+ let filters = vpp.filters().expect("vaQueryVideoProcFilters");
495+ println!("radeonsi VAProcFilterType list: {filters:?}");
496+ println!(
497+ "HighDynamicRangeToneMapping (8) advertised: {}",
498+ filters.contains(&sys::VAProcFilterHighDynamicRangeToneMapping)
499+ );
500+}
501+
502+/// `Vpp::convert` end to end: a P010 source surface into an NV12 destination,
503+/// no readback — the conversion `ec-hw`'s `encode_frame` relies on for a
504+/// 10-bit source.
505+#[test]
506+fn vpp_converts_p010_to_nv12() {
507+ let _serial = serial();
508+ let display = display();
509+ let src_spec = SurfaceSpec::p010(64, 64);
510+ let source = Surface::create(&display, &src_spec).expect("p010 source surface");
511+ let dest_targets = Surface::create_pool(&display, &SurfaceSpec::nv12(64, 64), 1).expect("pool");
512+ let vpp = ec_va::Vpp::new(
513+ &display,
514+ sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10,
515+ &dest_targets,
516+ )
517+ .expect("vpp opens");
518+ let dest = vpp
519+ .convert(&source, Arc::clone(&dest_targets[0]))
520+ .expect("convert");
521+ assert_eq!(dest.id(), dest_targets[0].id());
522+ assert!(display.is_valid());
523+}
524+
480 // --------------------------------------------------------------------------525 // --------------------------------------------------------------------------
481 // helpers526 // helpers
482 // --------------------------------------------------------------------------527 // --------------------------------------------------------------------------