Skip to main content

kodecs_vaapi/
vpp.rs

1//! Video post-processing: the `VAEntrypointVideoProc` pipeline.
2//!
3//! The one operation is a blit from one surface into another, which the video
4//! processor stretches to fit the destination and converts to the destination's
5//! format on the way. That covers three jobs without the pixels leaving the GPU:
6//!
7//! - Scaling: blit into a smaller or larger surface. [`Processor::resize`]
8//!   blits into NV12 surfaces it recycles per size and exports the result.
9//! - Color conversion: blit a packed RGB or YUYV surface into an NV12 one, the
10//!   format an encoder takes. [`Processor::blit`] takes the YUV space to write.
11//! - Re-tiling: blit into a surface of the same size and format. The destination
12//!   is one the driver allocated for itself, so the blit rewrites the pixels
13//!   into whatever tiling the driver prefers for a fresh allocation. That is how
14//!   a DMA-BUF carrying a format modifier some other API refuses to import
15//!   becomes one it accepts. Measured on Intel Meteor Lake with iHD 26.1.5 (the
16//!   `retile_round_trip` test prints it), a decode target exports at
17//!   `0x100000000000009` (`I915_FORMAT_MOD_4_TILED`), which Mesa's Vulkan driver
18//!   lists, so that combination does not need it. Older iHD releases wrote
19//!   `Y_TILED` (`0x100000000000002`), which Mesa does not list.
20//!
21//! ```no_run
22//! # fn example(buffer: kodecs_vaapi::dmabuf::DmaBuf) -> anyhow::Result<()> {
23//! use kodecs_vaapi::vpp::Processor;
24//!
25//! let processor = Processor::new("/dev/dri/renderD128")?;
26//! let retiled = processor.retile(buffer)?;
27//! let exported = retiled.export_prime().map_err(|e| anyhow::anyhow!("export: {e:?}"))?;
28//! # let _ = exported;
29//! # Ok(())
30//! # }
31//! ```
32
33use 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
48/// ITU-T H.273 code points for an explicitly described side of a blit.
49const PRIMARIES_BT709: u8 = 1;
50const TRANSFER_BT709: u8 = 1;
51const MATRIX_UNSPECIFIED: u8 = 2;
52
53/// Checks that `display`'s driver offers video post-processing, which is what [`Processor::with_display`] needs of a render node.
54///
55/// # Errors
56///
57/// Fails when the driver has no `VAEntrypointVideoProc`, or cannot be asked.
58pub 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
68/// A video post-processor on one device.
69///
70/// Holds the display, the VPP configuration, and per destination size a
71/// processing context and the surfaces [`resize`](Self::resize) writes into,
72/// which are what cost something to build. A caller converting every frame of
73/// a stream, or of a few renditions, pays for each once.
74pub struct Processor {
75	display: Arc<Display>,
76	/// How the driver reads a named color space; see [`Colors`].
77	colors: Colors,
78	/// The NV12 surfaces [`resize`](Self::resize) writes into, recycled per size.
79	outputs: RefCell<HashMap<(u32, u32), SurfacePool>>,
80	// Drop order: the contexts before the config they were created from.
81	contexts: RefCell<HashMap<(u32, u32), Rc<Context>>>,
82	config: VaConfig,
83}
84
85impl Processor {
86	/// Opens `device` and configures it for video post-processing.
87	///
88	/// `device` is a DRM render node, e.g. `/dev/dri/renderD128`. Pick the one
89	/// matching the device that will consume the result: the blit only stays on
90	/// the GPU when both ends are the same device.
91	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	/// Opens the first device whose driver can post-process, if any.
99	///
100	/// Mirrors [`Display::open`], and is what a caller with no opinion about
101	/// which GPU should use. A machine with more than one wants
102	/// [`Processor::new`] or [`Processor::with_display`] instead.
103	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	/// Configures an already open display for video post-processing.
110	///
111	/// Sharing the display with a decoder or an encoder is what lets a surface
112	/// move between them: a surface belongs to the display that created it.
113	///
114	/// # Errors
115	///
116	/// Fails when the device has no `VAEntrypointVideoProc`, which is how a
117	/// caller finds out before the first frame rather than during it.
118	pub fn with_display(display: Arc<Display>) -> anyhow::Result<Self> {
119		// Asking for the attribute is the probe: a device without the VPP
120		// entrypoint fails here instead of at vaCreateConfig, with an error that
121		// says which entrypoint was missing.
122		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		// Mesa's VA frontend serves every Gallium driver, radeonsi included.
143		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	/// Returns the display this processor runs on, to share with a decoder or an encoder.
157	pub fn display(&self) -> &Arc<Display> {
158		&self.display
159	}
160
161	/// Imports an exported DMA-BUF as a surface on this processor's display, without copying it.
162	///
163	/// The returned surface owns `buffer`, so the descriptor stays open exactly
164	/// as long as the surface referring to it.
165	///
166	/// # Errors
167	///
168	/// See [`DmaBuf::import`].
169	pub fn import(&self, buffer: DmaBuf) -> anyhow::Result<Surface<DmaBuf>> {
170		buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))
171	}
172
173	/// Blits `input` into `output`, scaling to the size of `output` and converting to its format.
174	///
175	/// `input_color` and `output_color` name the YUV space on each side. Leave
176	/// the input side `None` for an RGB input, which has no matrix; set the
177	/// output side to the space a YUV destination should be written in. A side
178	/// left `None` is up to the driver, which is right for a blit that only
179	/// re-tiles, and for a scale that names neither side. Returns once the
180	/// destination holds the result.
181	///
182	/// # Errors
183	///
184	/// Fails when either surface belongs to another display, and when the
185	/// driver refuses the blit (a format pair or scale it cannot do).
186	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		// A surface id means something only on the display that made it, and
198		// the driver would read another display's id as one of its own.
199		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			// A picture that failed half way can leave the context mid-picture,
208			// so the next blit of this size starts on a fresh one.
209			self.contexts.borrow_mut().remove(&size);
210		}
211		result
212	}
213
214	/// Scales `input` to `width` by `height` and converts it to NV12, returning the result exported.
215	///
216	/// The output comes from a pool per size, so a stream of frames costs no
217	/// allocation per frame: once the returned frame drops, its surface is the
218	/// next one written at that size. A frame still held is never written over;
219	/// the next resize allocates another surface instead. At most one free
220	/// surface is kept per size, and any returned past that is destroyed. See
221	/// [`blit`](Self::blit) for the colors.
222	///
223	/// The frame's timestamp is zero, for the caller to set.
224	///
225	/// # Errors
226	///
227	/// Fails when the destination cannot be allocated or exported, and as
228	/// [`blit`](Self::blit) does.
229	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	/// Blits `input` into a new driver-allocated surface of `fourcc`, `width` and `height`.
250	///
251	/// The destination is hinted as post-processing output that will be
252	/// exported, so [`Surface::export_prime`] works on it. See
253	/// [`blit`](Self::blit) for the colors.
254	///
255	/// # Errors
256	///
257	/// Fails for a format with no render target mapping, when the destination
258	/// cannot be allocated, and as [`blit`](Self::blit) does.
259	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	/// Imports `buffer` and blits it into a driver-allocated surface of the same format and size.
287	///
288	/// This is the whole re-tile. Export the result with
289	/// [`Surface::export_prime`] and read the modifier off the object to see what
290	/// the driver chose.
291	/// Destroying the returned surface does not invalidate an export taken from
292	/// it, since the exported descriptor holds its own reference on the
293	/// underlying buffer.
294	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	/// Returns the processing context for a destination of `size`, building it on first use.
303	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		// No render targets: a VPP context takes its destination per picture, and
309		// binding it to one surface would make every other destination a rebuild.
310		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
319/// Runs one blit on `context` and waits for it to finish.
320fn 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/// How a driver's video processor reads a named color space.
344///
345/// A [`Color`] is a matrix and a range and nothing more, as every other
346/// conversion in the stack is, so a blit has to change those two alone. A
347/// named standard asks iHD for exactly that. Mesa takes the BT.601 standard to
348/// mean SMPTE 170M primaries and transfer as well, and gamut-maps red and green
349/// by up to 10 code values, so it is given each side explicitly with the same
350/// primaries and transfer on both. iHD reads an explicit side by its primaries
351/// alone, which is why the two cannot share one form.
352#[derive(Clone, Copy, Debug, PartialEq, Eq)]
353enum Colors {
354	Standard,
355	Explicit,
356}
357
358/// Returns a pipeline parameter buffer describing a plain blit of `surface`.
359///
360/// No regions (so the whole input stretched over the whole output), no
361/// filters, no references, no rotation or mirroring, and each side's color
362/// space and range as given, in the form `colors` names. A side left `None` is
363/// the driver's default for its format.
364fn 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	/// A driver-allocated NV12 surface survives a round trip through the
418	/// post-processor, and the modifier the driver picked is printed.
419	///
420	/// Skips without a VA-API device, so it is a no-op on a builder and real
421	/// coverage on a machine with a GPU. What it asserts is that the whole
422	/// sequence runs (import an exported DMA-BUF, blit, export the result); the
423	/// modifier the driver picks is hardware policy, so it is printed rather
424	/// than asserted.
425	#[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		// A decode-hinted surface, which is the allocation whose tiling is the
432		// problem a re-tile exists for.
433		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	/// An NV12 surface whose left half has luma `left` and right half `right`, so a crop and a scale differ.
468	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	/// Reads `frame` back and returns the luma at the middle of its left and right halves.
509	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	/// Whether every value is within 4 of the expected one.
517	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	/// The inode of an exported frame's descriptor, which names the allocation
522	/// behind it: every DMA-BUF gets its own on the anonymous dma-buf filesystem,
523	/// while each export of one surface is a new descriptor.
524	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	/// A surface scaled by the processor exports and reads back at its new
535	/// size, with the picture scaled rather than cropped.
536	#[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	/// A resize writes into the surface of an output that was let go, never
553	/// into one still held, and keeps at most one free surface per size.
554	#[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}