use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use crate::decode::ExportedFrame;
use crate::dmabuf::{rt_format, DmaBuf};
use crate::pool::SurfacePool;
use crate::{
bindings, BufferType, Color, Config as VaConfig, Context, Display, Picture, ProcColorProperties,
ProcPipelineParameterBuffer, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
VAEntrypoint, VAProfile,
};
const PRIMARIES_BT709: u8 = 1;
const TRANSFER_BT709: u8 = 1;
const MATRIX_UNSPECIFIED: u8 = 2;
pub fn probe(display: &Display) -> anyhow::Result<()> {
let entrypoints = display
.query_config_entrypoints(VAProfile::VAProfileNone)
.map_err(|e| anyhow::anyhow!("query video processing entrypoints: {e:?}"))?;
match entrypoints.contains(&VAEntrypoint::VAEntrypointVideoProc) {
true => Ok(()),
false => anyhow::bail!("the driver has no video post-processing entrypoint"),
}
}
pub struct Processor {
display: Arc<Display>,
colors: Colors,
outputs: RefCell<HashMap<(u32, u32), SurfacePool>>,
contexts: RefCell<HashMap<(u32, u32), Rc<Context>>>,
config: VaConfig,
}
impl Processor {
pub fn new<P: AsRef<Path>>(device: P) -> anyhow::Result<Self> {
let device = device.as_ref();
let display =
Display::open_drm_display(device).map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e}"))?;
Self::with_display(display)
}
pub fn open() -> anyhow::Result<Self> {
let (_, display) = crate::display::open_first(|display| probe(display))
.map_err(|e| e.context("find a render node that post-processes video"))?;
Self::with_display(display)
}
pub fn with_display(display: Arc<Display>) -> anyhow::Result<Self> {
let mut attrs = [VAConfigAttrib {
type_: VAConfigAttribType::VAConfigAttribRTFormat,
value: 0,
}];
display
.get_config_attributes(
VAProfile::VAProfileNone,
VAEntrypoint::VAEntrypointVideoProc,
&mut attrs,
)
.map_err(|e| anyhow::anyhow!("query VPP config attributes: {e:?}"))?;
let config = display
.create_config(
attrs.to_vec(),
VAProfile::VAProfileNone,
VAEntrypoint::VAEntrypointVideoProc,
)
.map_err(|e| anyhow::anyhow!("create VPP config: {e:?}"))?;
let colors = match display.query_vendor_string() {
Ok(vendor) if vendor.starts_with("Mesa Gallium driver") => Colors::Explicit,
_ => Colors::Standard,
};
Ok(Self {
display,
colors,
outputs: RefCell::new(HashMap::new()),
contexts: RefCell::new(HashMap::new()),
config,
})
}
pub fn display(&self) -> &Arc<Display> {
&self.display
}
pub fn import(&self, buffer: DmaBuf) -> anyhow::Result<Surface<DmaBuf>> {
buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))
}
pub fn blit<D, E>(
&self,
input: &Surface<D>,
output: &Surface<E>,
input_color: Option<Color>,
output_color: Option<Color>,
) -> anyhow::Result<()>
where
D: SurfaceMemoryDescriptor,
E: SurfaceMemoryDescriptor,
{
if !Arc::ptr_eq(input.display(), &self.display) || !Arc::ptr_eq(output.display(), &self.display) {
anyhow::bail!("a VPP blit between surfaces of another display");
}
let size = output.size();
let context = self.context(size)?;
let parameters = pipeline(input.id(), self.colors, input_color, output_color);
let result = run_blit(&context, output, parameters);
if result.is_err() {
self.contexts.borrow_mut().remove(&size);
}
result
}
pub fn resize<D: SurfaceMemoryDescriptor>(
&self,
input: &Surface<D>,
size: (u32, u32),
input_color: Option<Color>,
output_color: Option<Color>,
) -> anyhow::Result<ExportedFrame> {
let output = self
.outputs
.borrow_mut()
.entry(size)
.or_insert_with(|| {
let hint = UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT;
SurfacePool::new(&self.display, size, hint, 1)
})
.alloc()?;
self.blit(input, output.get(), input_color, output_color)?;
ExportedFrame::export(Arc::new(output), 0, size)
}
fn process<D: SurfaceMemoryDescriptor>(
&self,
input: &Surface<D>,
fourcc: u32,
(width, height): (u32, u32),
input_color: Option<Color>,
output_color: Option<Color>,
) -> anyhow::Result<Surface<()>> {
let rt_format = rt_format(fourcc).ok_or_else(|| anyhow::anyhow!("no RT format for fourcc {fourcc:#x}"))?;
let output = self
.display
.create_surfaces(
rt_format,
Some(fourcc),
width,
height,
Some(UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT),
vec![()],
)
.map_err(|e| anyhow::anyhow!("allocate a {width}x{height} VPP output surface: {e:?}"))?
.pop()
.ok_or_else(|| anyhow::anyhow!("vaCreateSurfaces returned no surface"))?;
self.blit(input, &output, input_color, output_color)?;
Ok(output)
}
pub fn retile(&self, buffer: DmaBuf) -> anyhow::Result<Surface<()>> {
let fourcc = buffer
.fourcc()
.ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
let input = self.import(buffer)?;
self.process(&input, fourcc, input.size(), None, None)
}
fn context(&self, (width, height): (u32, u32)) -> anyhow::Result<Rc<Context>> {
let mut contexts = self.contexts.borrow_mut();
if let Some(context) = contexts.get(&(width, height)) {
return Ok(Rc::clone(context));
}
let context = self
.display
.create_context::<()>(&self.config, width, height, None, true)
.map_err(|e| anyhow::anyhow!("create a {width}x{height} VPP context: {e:?}"))?;
contexts.insert((width, height), Rc::clone(&context));
Ok(context)
}
}
fn run_blit<E: SurfaceMemoryDescriptor>(
context: &Rc<Context>,
output: &Surface<E>,
parameters: ProcPipelineParameterBuffer,
) -> anyhow::Result<()> {
let buffer = context
.create_buffer(BufferType::ProcPipelineParameter(parameters))
.map_err(|e| anyhow::anyhow!("create VPP pipeline buffer: {e:?}"))?;
let mut picture = Picture::new(0, Rc::clone(context), output);
picture.add_buffer(buffer);
picture
.begin()
.map_err(|e| anyhow::anyhow!("vaBeginPicture: {e:?}"))?
.render()
.map_err(|e| anyhow::anyhow!("vaRenderPicture: {e:?}"))?
.end()
.map_err(|e| anyhow::anyhow!("vaEndPicture: {e:?}"))?
.sync()
.map_err(|(e, _)| anyhow::anyhow!("vaSyncSurface: {e:?}"))?;
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Colors {
Standard,
Explicit,
}
fn pipeline(
surface: bindings::VASurfaceID,
colors: Colors,
input_color: Option<Color>,
output_color: Option<Color>,
) -> ProcPipelineParameterBuffer {
let named = input_color.is_some() || output_color.is_some();
let side = |color: Option<Color>| match (colors, color) {
(Colors::Explicit, _) if named => {
let (range, matrix) = color.map_or((0, MATRIX_UNSPECIFIED), |color| (color.va_range(), color.vui().2));
(
bindings::_VAProcColorStandardType_VAProcColorStandardExplicit as u8,
ProcColorProperties::new(0, range, PRIMARIES_BT709, TRANSFER_BT709, matrix),
)
}
(_, Some(color)) => (
color.va_standard(),
ProcColorProperties::new(0, color.va_range(), 0, 0, 0),
),
(_, None) => (0, ProcColorProperties::default()),
};
let (input_standard, input_properties) = side(input_color);
let (output_standard, output_properties) = side(output_color);
ProcPipelineParameterBuffer::new(
surface,
None,
input_standard,
None,
0,
output_standard,
0,
0,
None,
None,
None,
0,
None,
0,
None,
0,
0,
input_properties,
output_properties,
0,
None,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{VA_FOURCC_NV12, VA_RT_FORMAT_YUV420};
#[test]
#[ignore = "requires a VA-API render node"]
fn retile_round_trip() {
let display = Display::open().expect("no VA-API display");
let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
let mut surfaces = processor
.display()
.create_surfaces(
VA_RT_FORMAT_YUV420,
Some(VA_FOURCC_NV12),
640,
480,
Some(UsageHint::USAGE_HINT_DECODER | UsageHint::USAGE_HINT_EXPORT),
vec![()],
)
.expect("allocate a decode surface");
let decoded = surfaces.pop().expect("one surface");
let exported = decoded.export_prime().expect("export the decode surface");
let source_modifier = exported.objects[0].drm_format_modifier;
let (fourcc, size, planes) = (
exported.fourcc,
(exported.width, exported.height),
exported.layers[0].num_planes,
);
let buffer = DmaBuf::from_prime(exported).expect("a composed export is one object");
let retiled = processor.retile(buffer).expect("re-tile the decode surface");
let output = retiled.export_prime().expect("export the re-tiled surface");
let target_modifier = output.objects[0].drm_format_modifier;
eprintln!("modifier {source_modifier:#x} -> {target_modifier:#x}");
assert_eq!(output.fourcc, fourcc, "the blit preserves the pixel format");
assert_eq!((output.width, output.height), size);
assert_eq!(output.objects.len(), 1, "a composed export is one object");
assert_eq!(
output.layers[0].num_planes, planes,
"the blit preserves the plane count"
);
}
fn split_surface(processor: &Processor, (width, height): (u32, u32), [left, right]: [u8; 2]) -> Surface<()> {
let mut source = processor
.display()
.create_surfaces(
VA_RT_FORMAT_YUV420,
Some(VA_FOURCC_NV12),
width,
height,
Some(UsageHint::USAGE_HINT_EXPORT),
vec![()],
)
.expect("allocate a surface")
.pop()
.expect("one surface");
let format = processor
.display()
.query_image_formats()
.expect("query image formats")
.into_iter()
.find(|f| f.fourcc == VA_FOURCC_NV12)
.expect("an NV12 image format");
{
let mut image = crate::ImageMut::create_uninitialized(&mut source, format).expect("create an image");
let va_image = *image.image();
let data = image.as_mut();
for y in 0..height as usize {
let row = va_image.offsets[0] as usize + y * va_image.pitches[0] as usize;
for x in 0..width as usize {
data[row + x] = if x < width as usize / 2 { left } else { right };
}
}
for y in 0..height as usize / 2 {
let row = va_image.offsets[1] as usize + y * va_image.pitches[1] as usize;
data[row..row + width as usize].fill(128);
}
image.put().expect("put the image");
}
source
}
fn halves(frame: &ExportedFrame) -> [u8; 2] {
let data = frame.download().expect("read the frame back").data;
let (w, h) = (frame.width as usize, frame.height as usize);
assert_eq!(data.len(), w * h * 3 / 2);
[data[h / 2 * w + w / 8], data[h / 2 * w + w * 7 / 8]]
}
fn near(actual: [u8; 2], expected: [u8; 2]) -> bool {
actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) < 4)
}
fn inode(frame: &ExportedFrame) -> u64 {
use std::os::unix::fs::MetadataExt as _;
let fd = frame.descriptor.objects[0]
.fd
.try_clone()
.expect("duplicate the descriptor");
std::fs::File::from(fd).metadata().expect("stat the descriptor").ino()
}
#[test]
#[ignore = "requires a VA-API render node"]
fn a_scaled_surface_reads_back_at_its_new_size() {
let display = Display::open().expect("no VA-API display");
let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
let source = split_surface(&processor, (640, 480), [40, 200]);
let exported = processor
.resize(&source, (320, 240), None, None)
.expect("scale the surface");
assert_eq!((exported.width, exported.height), (320, 240));
assert_eq!(exported.descriptor.fourcc, VA_FOURCC_NV12);
let read = halves(&exported);
assert!(near(read, [40, 200]), "read back {read:?}");
}
#[test]
#[ignore = "requires a VA-API render node"]
fn a_released_output_is_written_into_again() {
let display = Display::open().expect("no VA-API display");
let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
let dark_left = split_surface(&processor, (640, 480), [40, 200]);
let dark_right = split_surface(&processor, (640, 480), [200, 40]);
let size = (320, 240);
let resize = |source| processor.resize(source, size, None, None).expect("resize");
let first = resize(&dark_left);
let released = inode(&first);
drop(first);
let held = resize(&dark_left);
assert_eq!(inode(&held), released, "the released output was not written into again");
let other = resize(&dark_right);
assert_ne!(inode(&other), inode(&held), "an output still held was written over");
let (read, other_read) = (halves(&held), halves(&other));
assert!(near(read, [40, 200]), "the held output now reads {read:?}");
assert!(near(other_read, [200, 40]), "the second output reads {other_read:?}");
drop(held);
drop(other);
let outputs = processor.outputs.borrow();
let pool = &outputs[&size];
assert_eq!(pool.allocated.get(), 2, "two outputs held at once need two surfaces");
assert_eq!(
pool.free.surfaces.lock().unwrap().len(),
1,
"one free surface is kept per size, and the other destroyed"
);
}
}