1use std::cell::RefCell;
34use std::collections::HashMap;
35use std::path::Path;
36use std::rc::Rc;
37use std::sync::Arc;
38
39use crate::decode::ExportedFrame;
40use crate::dmabuf::{rt_format, DmaBuf};
41use crate::pool::SurfacePool;
42use crate::{
43 bindings, BufferType, Color, Config as VaConfig, Context, Display, Picture, ProcColorProperties,
44 ProcPipelineParameterBuffer, Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType,
45 VAEntrypoint, VAProfile,
46};
47
48const PRIMARIES_BT709: u8 = 1;
50const TRANSFER_BT709: u8 = 1;
51const MATRIX_UNSPECIFIED: u8 = 2;
52
53pub fn probe(display: &Display) -> anyhow::Result<()> {
59 let entrypoints = display
60 .query_config_entrypoints(VAProfile::VAProfileNone)
61 .map_err(|e| anyhow::anyhow!("query video processing entrypoints: {e:?}"))?;
62 match entrypoints.contains(&VAEntrypoint::VAEntrypointVideoProc) {
63 true => Ok(()),
64 false => anyhow::bail!("the driver has no video post-processing entrypoint"),
65 }
66}
67
68pub struct Processor {
75 display: Arc<Display>,
76 colors: Colors,
78 outputs: RefCell<HashMap<(u32, u32), SurfacePool>>,
80 contexts: RefCell<HashMap<(u32, u32), Rc<Context>>>,
82 config: VaConfig,
83}
84
85impl Processor {
86 pub fn new<P: AsRef<Path>>(device: P) -> anyhow::Result<Self> {
92 let device = device.as_ref();
93 let display =
94 Display::open_drm_display(device).map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e}"))?;
95 Self::with_display(display)
96 }
97
98 pub fn open() -> anyhow::Result<Self> {
104 let (_, display) =
105 crate::display::open_first(probe).map_err(|e| e.context("find a render node that post-processes video"))?;
106 Self::with_display(display)
107 }
108
109 pub fn with_display(display: Arc<Display>) -> anyhow::Result<Self> {
119 let mut attrs = [VAConfigAttrib {
123 type_: VAConfigAttribType::VAConfigAttribRTFormat,
124 value: 0,
125 }];
126 display
127 .get_config_attributes(
128 VAProfile::VAProfileNone,
129 VAEntrypoint::VAEntrypointVideoProc,
130 &mut attrs,
131 )
132 .map_err(|e| anyhow::anyhow!("query VPP config attributes: {e:?}"))?;
133
134 let config = display
135 .create_config(
136 attrs.to_vec(),
137 VAProfile::VAProfileNone,
138 VAEntrypoint::VAEntrypointVideoProc,
139 )
140 .map_err(|e| anyhow::anyhow!("create VPP config: {e:?}"))?;
141
142 let colors = match display.query_vendor_string() {
144 Ok(vendor) if vendor.starts_with("Mesa Gallium driver") => Colors::Explicit,
145 _ => Colors::Standard,
146 };
147 Ok(Self {
148 display,
149 colors,
150 outputs: RefCell::new(HashMap::new()),
151 contexts: RefCell::new(HashMap::new()),
152 config,
153 })
154 }
155
156 pub fn display(&self) -> &Arc<Display> {
158 &self.display
159 }
160
161 pub fn import(&self, buffer: DmaBuf) -> anyhow::Result<Surface<DmaBuf>> {
170 buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))
171 }
172
173 pub fn blit<D, E>(
187 &self,
188 input: &Surface<D>,
189 output: &Surface<E>,
190 input_color: Option<Color>,
191 output_color: Option<Color>,
192 ) -> anyhow::Result<()>
193 where
194 D: SurfaceMemoryDescriptor,
195 E: SurfaceMemoryDescriptor,
196 {
197 if !Arc::ptr_eq(input.display(), &self.display) || !Arc::ptr_eq(output.display(), &self.display) {
200 anyhow::bail!("a VPP blit between surfaces of another display");
201 }
202 let size = output.size();
203 let context = self.context(size)?;
204 let parameters = pipeline(input.id(), self.colors, input_color, output_color);
205 let result = run_blit(&context, output, parameters);
206 if result.is_err() {
207 self.contexts.borrow_mut().remove(&size);
210 }
211 result
212 }
213
214 pub fn resize<D: SurfaceMemoryDescriptor>(
230 &self,
231 input: &Surface<D>,
232 size: (u32, u32),
233 input_color: Option<Color>,
234 output_color: Option<Color>,
235 ) -> anyhow::Result<ExportedFrame> {
236 let output = self
237 .outputs
238 .borrow_mut()
239 .entry(size)
240 .or_insert_with(|| {
241 let hint = UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT;
242 SurfacePool::new(&self.display, size, hint, 1)
243 })
244 .alloc()?;
245 self.blit(input, output.get(), input_color, output_color)?;
246 ExportedFrame::export(Arc::new(output), 0, size)
247 }
248
249 fn process<D: SurfaceMemoryDescriptor>(
260 &self,
261 input: &Surface<D>,
262 fourcc: u32,
263 (width, height): (u32, u32),
264 input_color: Option<Color>,
265 output_color: Option<Color>,
266 ) -> anyhow::Result<Surface<()>> {
267 let rt_format = rt_format(fourcc).ok_or_else(|| anyhow::anyhow!("no RT format for fourcc {fourcc:#x}"))?;
268 let output = self
269 .display
270 .create_surfaces(
271 rt_format,
272 Some(fourcc),
273 width,
274 height,
275 Some(UsageHint::USAGE_HINT_VPP_WRITE | UsageHint::USAGE_HINT_EXPORT),
276 vec![()],
277 )
278 .map_err(|e| anyhow::anyhow!("allocate a {width}x{height} VPP output surface: {e:?}"))?
279 .pop()
280 .ok_or_else(|| anyhow::anyhow!("vaCreateSurfaces returned no surface"))?;
281
282 self.blit(input, &output, input_color, output_color)?;
283 Ok(output)
284 }
285
286 pub fn retile(&self, buffer: DmaBuf) -> anyhow::Result<Surface<()>> {
295 let fourcc = buffer
296 .fourcc()
297 .ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
298 let input = self.import(buffer)?;
299 self.process(&input, fourcc, input.size(), None, None)
300 }
301
302 fn context(&self, (width, height): (u32, u32)) -> anyhow::Result<Rc<Context>> {
304 let mut contexts = self.contexts.borrow_mut();
305 if let Some(context) = contexts.get(&(width, height)) {
306 return Ok(Rc::clone(context));
307 }
308 let context = self
311 .display
312 .create_context::<()>(&self.config, width, height, None, true)
313 .map_err(|e| anyhow::anyhow!("create a {width}x{height} VPP context: {e:?}"))?;
314 contexts.insert((width, height), Rc::clone(&context));
315 Ok(context)
316 }
317}
318
319fn run_blit<E: SurfaceMemoryDescriptor>(
321 context: &Rc<Context>,
322 output: &Surface<E>,
323 parameters: ProcPipelineParameterBuffer,
324) -> anyhow::Result<()> {
325 let buffer = context
326 .create_buffer(BufferType::ProcPipelineParameter(parameters))
327 .map_err(|e| anyhow::anyhow!("create VPP pipeline buffer: {e:?}"))?;
328
329 let mut picture = Picture::new(0, Rc::clone(context), output);
330 picture.add_buffer(buffer);
331 picture
332 .begin()
333 .map_err(|e| anyhow::anyhow!("vaBeginPicture: {e:?}"))?
334 .render()
335 .map_err(|e| anyhow::anyhow!("vaRenderPicture: {e:?}"))?
336 .end()
337 .map_err(|e| anyhow::anyhow!("vaEndPicture: {e:?}"))?
338 .sync()
339 .map_err(|(e, _)| anyhow::anyhow!("vaSyncSurface: {e:?}"))?;
340 Ok(())
341}
342
343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
353enum Colors {
354 Standard,
355 Explicit,
356}
357
358fn pipeline(
365 surface: bindings::VASurfaceID,
366 colors: Colors,
367 input_color: Option<Color>,
368 output_color: Option<Color>,
369) -> ProcPipelineParameterBuffer {
370 let named = input_color.is_some() || output_color.is_some();
371 let side = |color: Option<Color>| match (colors, color) {
372 (Colors::Explicit, _) if named => {
373 let (range, matrix) = color.map_or((0, MATRIX_UNSPECIFIED), |color| (color.va_range(), color.vui().2));
374 (
375 bindings::_VAProcColorStandardType_VAProcColorStandardExplicit as u8,
376 ProcColorProperties::new(0, range, PRIMARIES_BT709, TRANSFER_BT709, matrix),
377 )
378 }
379 (_, Some(color)) => (
380 color.va_standard(),
381 ProcColorProperties::new(0, color.va_range(), 0, 0, 0),
382 ),
383 (_, None) => (0, ProcColorProperties::default()),
384 };
385 let (input_standard, input_properties) = side(input_color);
386 let (output_standard, output_properties) = side(output_color);
387 ProcPipelineParameterBuffer::new(
388 surface,
389 None,
390 input_standard,
391 None,
392 0,
393 output_standard,
394 0,
395 0,
396 None,
397 None,
398 None,
399 0,
400 None,
401 0,
402 None,
403 0,
404 0,
405 input_properties,
406 output_properties,
407 0,
408 None,
409 )
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415 use crate::{VA_FOURCC_NV12, VA_RT_FORMAT_YUV420};
416
417 #[test]
426 #[ignore = "requires a VA-API render node"]
427 fn retile_round_trip() {
428 let display = Display::open().expect("no VA-API display");
429 let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
430
431 let mut surfaces = processor
434 .display()
435 .create_surfaces(
436 VA_RT_FORMAT_YUV420,
437 Some(VA_FOURCC_NV12),
438 640,
439 480,
440 Some(UsageHint::USAGE_HINT_DECODER | UsageHint::USAGE_HINT_EXPORT),
441 vec![()],
442 )
443 .expect("allocate a decode surface");
444 let decoded = surfaces.pop().expect("one surface");
445 let exported = decoded.export_prime().expect("export the decode surface");
446 let source_modifier = exported.objects[0].drm_format_modifier;
447 let (fourcc, size, planes) = (
448 exported.fourcc,
449 (exported.width, exported.height),
450 exported.layers[0].num_planes,
451 );
452 let buffer = DmaBuf::from_prime(exported).expect("a composed export is one object");
453
454 let retiled = processor.retile(buffer).expect("re-tile the decode surface");
455 let output = retiled.export_prime().expect("export the re-tiled surface");
456 let target_modifier = output.objects[0].drm_format_modifier;
457
458 eprintln!("modifier {source_modifier:#x} -> {target_modifier:#x}");
459 assert_eq!(output.fourcc, fourcc, "the blit preserves the pixel format");
460 assert_eq!((output.width, output.height), size);
461 assert_eq!(output.objects.len(), 1, "a composed export is one object");
462 assert_eq!(
463 output.layers[0].num_planes, planes,
464 "the blit preserves the plane count"
465 );
466 }
467 fn split_surface(processor: &Processor, (width, height): (u32, u32), [left, right]: [u8; 2]) -> Surface<()> {
469 let mut source = processor
470 .display()
471 .create_surfaces(
472 VA_RT_FORMAT_YUV420,
473 Some(VA_FOURCC_NV12),
474 width,
475 height,
476 Some(UsageHint::USAGE_HINT_EXPORT),
477 vec![()],
478 )
479 .expect("allocate a surface")
480 .pop()
481 .expect("one surface");
482 let format = processor
483 .display()
484 .query_image_formats()
485 .expect("query image formats")
486 .into_iter()
487 .find(|f| f.fourcc == VA_FOURCC_NV12)
488 .expect("an NV12 image format");
489 {
490 let mut image = crate::ImageMut::create_uninitialized(&mut source, format).expect("create an image");
491 let va_image = *image.image();
492 let data = image.as_mut();
493 for y in 0..height as usize {
494 let row = va_image.offsets[0] as usize + y * va_image.pitches[0] as usize;
495 for x in 0..width as usize {
496 data[row + x] = if x < width as usize / 2 { left } else { right };
497 }
498 }
499 for y in 0..height as usize / 2 {
500 let row = va_image.offsets[1] as usize + y * va_image.pitches[1] as usize;
501 data[row..row + width as usize].fill(128);
502 }
503 image.put().expect("put the image");
504 }
505 source
506 }
507
508 fn halves(frame: &ExportedFrame) -> [u8; 2] {
510 let data = frame.download().expect("read the frame back").data;
511 let (w, h) = (frame.width as usize, frame.height as usize);
512 assert_eq!(data.len(), w * h * 3 / 2);
513 [data[h / 2 * w + w / 8], data[h / 2 * w + w * 7 / 8]]
514 }
515
516 fn near(actual: [u8; 2], expected: [u8; 2]) -> bool {
518 actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) < 4)
519 }
520
521 fn inode(frame: &ExportedFrame) -> u64 {
525 use std::os::unix::fs::MetadataExt as _;
526
527 let fd = frame.descriptor.objects[0]
528 .fd
529 .try_clone()
530 .expect("duplicate the descriptor");
531 std::fs::File::from(fd).metadata().expect("stat the descriptor").ino()
532 }
533
534 #[test]
537 #[ignore = "requires a VA-API render node"]
538 fn a_scaled_surface_reads_back_at_its_new_size() {
539 let display = Display::open().expect("no VA-API display");
540 let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
541
542 let source = split_surface(&processor, (640, 480), [40, 200]);
543 let exported = processor
544 .resize(&source, (320, 240), None, None)
545 .expect("scale the surface");
546 assert_eq!((exported.width, exported.height), (320, 240));
547 assert_eq!(exported.descriptor.fourcc, VA_FOURCC_NV12);
548 let read = halves(&exported);
549 assert!(near(read, [40, 200]), "read back {read:?}");
550 }
551
552 #[test]
555 #[ignore = "requires a VA-API render node"]
556 fn a_released_output_is_written_into_again() {
557 let display = Display::open().expect("no VA-API display");
558 let processor = Processor::with_display(display).expect("device has no video post-processing entrypoint");
559 let dark_left = split_surface(&processor, (640, 480), [40, 200]);
560 let dark_right = split_surface(&processor, (640, 480), [200, 40]);
561 let size = (320, 240);
562 let resize = |source| processor.resize(source, size, None, None).expect("resize");
563
564 let first = resize(&dark_left);
565 let released = inode(&first);
566 drop(first);
567 let held = resize(&dark_left);
568 assert_eq!(inode(&held), released, "the released output was not written into again");
569
570 let other = resize(&dark_right);
571 assert_ne!(inode(&other), inode(&held), "an output still held was written over");
572 let (read, other_read) = (halves(&held), halves(&other));
573 assert!(near(read, [40, 200]), "the held output now reads {read:?}");
574 assert!(near(other_read, [200, 40]), "the second output reads {other_read:?}");
575
576 drop(held);
577 drop(other);
578 let outputs = processor.outputs.borrow();
579 let pool = &outputs[&size];
580 assert_eq!(pool.allocated.get(), 2, "two outputs held at once need two surfaces");
581 assert_eq!(
582 pool.free.surfaces.lock().unwrap().len(),
583 1,
584 "one free surface is kept per size, and the other destroyed"
585 );
586 }
587}