kodecs-vaapi 0.3.3

VA-API H.264 and H.265 hardware encode and decode, forked from discord/cros-libva and discord/cros-codecs, with libva loaded at runtime
Documentation
//! What the hardware tests share: the render node they run on, and fixtures.

use std::os::fd::OwnedFd;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

use crate::{Codec, Display, ImageMut, Surface, UsageHint, VAImage, VAImageFormat};

/// The render node every hardware test opens, from `KODECS_VAAPI_DEVICE`.
///
/// Fixtures, encoders, and decoders share one node, so a DMA-BUF one makes is
/// importable by the next and each run exercises a single GPU. `just vaapi`
/// sets it to each Intel and AMD node in turn.
pub fn device() -> PathBuf {
	match std::env::var_os("KODECS_VAAPI_DEVICE") {
		Some(path) => PathBuf::from(path),
		None => panic!("set KODECS_VAAPI_DEVICE to a render node, or run `just vaapi`"),
	}
}

/// Opens [`device`].
pub fn display() -> Arc<Display> {
	let device = device();
	Display::open_drm_display(&device).unwrap_or_else(|err| panic!("open {}: {err}", device.display()))
}

/// A diagonal gradient with a block moving across it, so a stale or
/// misplaced reference shows up as the block in the wrong place.
pub fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
	let (w, h) = (width as usize, height as usize);
	let mut data = vec![128u8; w * h + w * h.div_ceil(2)];
	for y in 0..h {
		for x in 0..w {
			data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
		}
	}
	let x0 = (step as usize * 8) % (w / 2);
	for y in h / 4..h / 2 {
		for x in x0..x0 + w / 4 {
			data[y * w + x] = 220;
		}
	}
	data
}

/// Returns a temporary file path unique to this call, whose extension names
/// `codec` for ffmpeg to pick the demuxer by.
///
/// The tests run as threads of one process, so the process id alone would
/// let two of them share a file.
pub fn temp_path(codec: Codec) -> PathBuf {
	static NEXT: AtomicU32 = AtomicU32::new(0);
	let index = NEXT.fetch_add(1, Ordering::Relaxed);
	let extension = match codec {
		Codec::H264 => "264",
		Codec::H265 => "265",
	};
	std::env::temp_dir().join(format!("kodecs-vaapi-{}-{index}.{extension}", std::process::id()))
}

/// Decodes an Annex-B stream with ffmpeg's software decoder into packed NV12
/// pictures, one after another.
pub fn ffmpeg_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
	// ffmpeg reads the elementary stream from a file rather than a pipe, so
	// the test never has to drain its output while still writing its input.
	let path = temp_path(codec);
	std::fs::write(&path, stream).expect("write the elementary stream");
	let output = Command::new("ffmpeg")
		.args(["-v", "error", "-i"])
		.arg(&path)
		.args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
		.output();
	let _ = std::fs::remove_file(&path);
	let output = output.expect("run ffmpeg");
	assert!(
		output.status.success(),
		"ffmpeg refused the stream: {}",
		String::from_utf8_lossy(&output.stderr)
	);
	output.stdout
}

/// Returns a driver surface of `fourcc` on `display` whose pixels are unspecified.
pub fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
	display
		.create_surfaces(
			rt_format,
			Some(fourcc),
			width,
			height,
			Some(UsageHint::USAGE_HINT_EXPORT),
			vec![()],
		)
		.expect("allocate a surface")
		.pop()
		.expect("one surface")
}

/// Returns the driver's image format for `fourcc`.
pub fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
	display
		.query_image_formats()
		.expect("query image formats")
		.into_iter()
		.find(|f| f.fourcc == fourcc)
		.expect("the driver has an image format for the surface format")
}

/// Returns a driver surface of `fourcc` on `display`, every pixel written by `fill` through an image.
pub fn surface_with(
	display: &Arc<Display>,
	fourcc: u32,
	rt_format: u32,
	size: (u32, u32),
	fill: impl FnOnce(&mut [u8], &VAImage),
) -> Surface<()> {
	let mut surface = blank_surface(display, fourcc, rt_format, size);
	let mut image =
		ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
	let va_image = *image.image();
	fill(image.as_mut(), &va_image);
	image.put().expect("put the image");
	surface.sync().expect("sync the filled surface");
	surface
}

/// The inode of a descriptor, which for a DMA-BUF names the allocation behind
/// it: every buffer gets its own on the anonymous dma-buf filesystem, while
/// each export of one surface is a new descriptor.
pub fn inode(fd: &OwnedFd) -> u64 {
	use std::os::unix::fs::MetadataExt as _;

	// Stat a duplicate, so the descriptor the caller holds is untouched and
	// the `File` wrapper closes only its own copy.
	let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
	file.metadata().expect("stat the descriptor").ino()
}