Skip to main content

kodecs_vaapi/
encode.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4//
5// Adapted from discord/cros-codecs (encoder/stateless/h264/vaapi.rs), itself
6// BSD-3-Clause / Copyright The ChromiumOS Authors. See LICENSE.cros-codecs.
7
8//! Thin VA-API H.264 and H.265 encoder built on the vendored libva binding.
9//!
10//! For H.264 it writes the SPS, PPS, and slice headers with kodecs-h264, and
11//! drives libva directly for surface upload +
12//! slice submission, rather than vendoring cros-codecs's generic multi-backend
13//! encoder framework. The per-frame VA buffer population is ported from
14//! cros-codecs's `encoder/stateless/h264/vaapi.rs`. H.265 writes its own
15//! parameter sets and slice headers (see `h265.rs`).
16//!
17//! Low-latency only: IPPP (no B-frames), one reference frame, matching the
18//! VideoToolbox / Media Foundation / NVENC backends in moq-video.
19//!
20//! Three ways in, cheapest first:
21//! - [`Encoder::encode_dmabuf`] with an NV12 DMA-BUF at the encoder's size
22//!   encodes the producer's memory in place.
23//! - [`Encoder::encode_dmabuf`] with any other importable DMA-BUF (packed RGB
24//!   from a screen capture, YUYV from a camera, NV12 at another size) converts
25//!   and scales it into the encoder's own surface with the video processor, on
26//!   the GPU.
27//! - [`Encoder::encode_nv12`] uploads CPU pixels.
28//!
29//! Checked on Intel Meteor Lake and Arrow Lake with the iHD driver, and on an
30//! AMD RX 9070 with radeonsi, by decoding with ffmpeg's software decoder: CPU
31//! and DMA-BUF input come back above 35 dB luma PSNR, and BGRX converts to
32//! BT.601 and BT.709 with every channel within 6 code values of the reference.
33//! The low-power entrypoint is untested, since those devices expose the full
34//! one.
35
36use std::num::NonZeroU32;
37use std::path::PathBuf;
38use std::rc::Rc;
39use std::sync::Arc;
40
41use anyhow::Context as _;
42
43use crate::codec::Codec;
44use crate::dmabuf::DmaBuf;
45use crate::vpp::Processor;
46use crate::{
47	BufferType, Color, Config as VaConfig, Context, Display, EncCodedBuffer, EncMiscParameter,
48	EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter,
49	EncPackedHeaderType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
50	EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264, H264EncFrameCropOffsets,
51	H264EncPicFields, H264EncSeqFields, H264VuiFields, ImageMut, MappedCodedBuffer, Picture, PictureH264, RcFlags,
52	Surface, SurfaceMemoryDescriptor, UsageHint, VAConfigAttrib, VAConfigAttribType, VAEntrypoint, VAImageFormat,
53	VAProfile, VA_ATTRIB_NOT_SUPPORTED, VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE,
54	VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_ARGB, VA_FOURCC_BGRA, VA_FOURCC_BGRX, VA_FOURCC_NV12, VA_FOURCC_RGBA,
55	VA_FOURCC_RGBX, VA_FOURCC_XRGB, VA_INVALID_ID, VA_PICTURE_H264_INVALID, VA_PICTURE_H264_SHORT_TERM_REFERENCE,
56	VA_RC_CBR, VA_RC_VBR, VA_RT_FORMAT_YUV420,
57};
58use kodecs_h264::{
59	Level, NaluHeader, NaluType, Pps, PpsBuilder, Profile, SliceHeader, SliceHeaderBuilder, SliceType, Sps, SpsBuilder,
60};
61
62mod h265;
63
64/// Quantizer bounds for the rate controller.
65///
66/// The floor is the quality: the rate controller holds the stream to
67/// [`Config::bitrate`], and a calm scene the floor already codes cleanly spends
68/// less instead of buying a finer quantizer than anyone can see. 24 is the
69/// coarsest that kept a 720p30 talking head at VMAF 95, the usual mark for
70/// transparent, on both iHD (Arrow Lake: 95.8 at 2.9 Mbit/s under a 4 Mbit/s
71/// cap, H.265 95.7 at 1.6 under 2.8) and radeonsi (RX 9070: 95.4 at 1.7, H.265
72/// 95.4 at 1.5). It also keeps an IDR on easy content from taking a large share
73/// of the rate. The ceiling is the codecs' own: iHD and radeonsi both honor it,
74/// so a lower one sets a smallest picture, and a stream asked for less
75/// overshoots its rate several times over. A lower ceiling does steady iHD's
76/// H.264 IDRs, but under congestion missing the rate costs more than that.
77const MIN_QP: u8 = 24;
78const MAX_QP: u8 = 51;
79/// The HRD buffer, in frames of the bitrate, sent with every picture. The
80/// driver's own default is a second of the rate, which let a second of high
81/// motion run half again over the bitrate on radeonsi. It is also what a still
82/// scene banks: the first busy frames after one spend all of it, so that second
83/// runs this many frames over the bitrate.
84pub const HRD_FRAMES: u32 = 3;
85/// Window over which libva's rate controller targets the configured bitrate.
86///
87/// This matches cros-codecs. The old `framerate * 1000` value confused frames
88/// per second with seconds and gave a 30 fps encoder a 30-second window.
89pub const RATE_CONTROL_WINDOW_MS: u32 = 1_500;
90/// `max_frame_num` upper bound for the low-delay GOP; matches cros-codecs.
91const LIMIT: u32 = 2048;
92
93/// Encoder configuration. Dimensions must be even (4:2:0 chroma).
94#[derive(Clone, Debug)]
95pub struct Config {
96	/// The format to encode, H.264 unless set. Main profile either way.
97	pub codec: Codec,
98	pub width: u32,
99	pub height: u32,
100	pub framerate: u32,
101	/// The bitrate in bits per second the stream is held to. A calm scene
102	/// spends less; see [`RateControl`].
103	pub bitrate: u32,
104	/// Keyframe interval in frames.
105	pub gop: NonZeroU32,
106	/// DRM render node to open (e.g. `/dev/dri/renderD128`).
107	///
108	/// `None`, the default, opens the first node whose driver can encode
109	/// [`codec`](Self::codec), and [`Encoder::config`] then names the node it
110	/// picked.
111	pub device: Option<PathBuf>,
112	/// Color space written into the SPS, and the target of a conversion from RGB.
113	///
114	/// Defaults to [`Color::infer`] for the height, which is what a decoder
115	/// assumes for an unlabelled stream.
116	pub color: Color,
117}
118
119/// The rate control mode that holds a stream to [`Config::bitrate`], picked at
120/// open for the driver.
121///
122/// Either way the bitrate is the ceiling the driver's rate controller aims to
123/// hold the stream under, through the [`HRD_FRAMES`] buffer, and the quantizer
124/// floor is its quality, so a calm scene falls below the bitrate. It is a
125/// target, not a guarantee: a busy second can still overshoot it by a few
126/// percent (iHD's H.264 peaked at 4.36 Mbit/s in one second under 4 Mbit/s). Neither driver's
127/// `VA_RC_QVBR` gets there: on iHD it held a high-motion clip to 59% of the
128/// bitrate whatever the quality factor, and on radeonsi it scored 93.3 VMAF at
129/// the full bitrate where CBR and the floor scored 95.4 at 43% of it.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum RateControl {
132	/// `VA_RC_VBR` with the bitrate as both target and peak, for iHD, whose CBR
133	/// ignores the floor and spends the bitrate on a still picture.
134	Variable,
135	/// `VA_RC_CBR` without filler, for every other driver. radeonsi honors the
136	/// floor and the HRD here, where its VBR let a high-motion second run half
137	/// again over the bitrate.
138	Constant,
139}
140
141impl RateControl {
142	/// The mode for the driver named `vendor` (`vaQueryVendorString`), whose
143	/// `VAConfigAttribRateControl` reads `offered`.
144	fn pick(vendor: &str, offered: u32) -> Self {
145		match vendor.starts_with("Intel iHD driver") && offered & VA_RC_VBR != 0 {
146			true => Self::Variable,
147			false => Self::Constant,
148		}
149	}
150
151	fn va(self) -> u32 {
152		match self {
153			Self::Variable => VA_RC_VBR,
154			Self::Constant => VA_RC_CBR,
155		}
156	}
157}
158
159/// Per-frame reference metadata. (Mirrors cros-codecs `DpbEntryMeta`.)
160#[derive(Copy, Clone)]
161struct FrameMeta {
162	poc: u32,
163	frame_num: u32,
164}
165
166impl FrameMeta {
167	/// Returns the H.264 order count and frame number of the picture `count` pictures after an IDR.
168	///
169	/// frame_num counts modulo MaxFrameNum, and the slice header carries only
170	/// the low bits of the picture order count; the full count goes to the
171	/// driver in the picture parameters.
172	fn new(count: u32) -> Self {
173		Self {
174			poc: count.wrapping_mul(2),
175			frame_num: count % LIMIT,
176		}
177	}
178}
179
180/// The picture a P picture predicts from: the previous one.
181#[derive(Copy, Clone)]
182struct Reference {
183	/// Its reconstructed surface.
184	surface: crate::bindings::VASurfaceID,
185	/// How many pictures after the IDR it came.
186	count: u32,
187}
188
189/// What one picture's parameter buffers are built from.
190struct PictureInfo<'a> {
191	idr: bool,
192	/// How many IDR pictures came before this one.
193	idr_id: u32,
194	/// How many pictures after the IDR this one comes.
195	count: u32,
196	/// The surface its reconstruction is written to.
197	recon: crate::bindings::VASurfaceID,
198	reference: Option<Reference>,
199	coded: &'a EncCodedBuffer,
200	bitrate: u32,
201}
202
203/// The bitstream syntax of the stream being encoded.
204enum Syntax {
205	H264 {
206		sps: Arc<Sps>,
207		pps: Arc<Pps>,
208		/// The packed header kinds the driver takes from us; it writes the rest.
209		packed: u32,
210	},
211	H265 {
212		stream: h265::Stream,
213		/// The packed header kinds the driver takes from us; it writes the rest.
214		packed: u32,
215	},
216}
217
218/// A VA-API H.264 or H.265 encoder. Built once, fed NV12 frames, emits an Annex-B stream.
219pub struct Encoder {
220	config: Config,
221	syntax: Syntax,
222
223	// Source surface (reused; NV12 re-uploaded per frame) and a 2-deep
224	// reconstructed surface ring (current + previous reference for IPPP).
225	input: Option<Surface<()>>,
226	/// The driver's NV12 image format, which [`Encoder::encode_nv12`] uploads through; `None` when it has none.
227	nv12: Option<VAImageFormat>,
228	recon: Vec<Surface<()>>,
229	/// Reference from the previous encoded frame: (recon index, pictures after the IDR).
230	reference: Option<(usize, u32)>,
231
232	counter: u32,
233	/// IDR pictures coded so far, so two in a row carry different H.264 `idr_pic_id`s.
234	idrs: u32,
235
236	/// The video processor converting and scaling DMA-BUF input, opened on the
237	/// first frame that needs it.
238	processor: Option<Processor>,
239	/// Set by a bitrate change, and cleared by the next frame, which asks the
240	/// driver to restart its rate controller at the new target.
241	reset_rate_control: bool,
242	rate_control: RateControl,
243
244	// Drop order: encode resources before the display they belong to.
245	coded: EncCodedBuffer,
246	coded_size: usize,
247	context: Rc<Context>,
248	_va_config: VaConfig,
249	display: Arc<Display>,
250}
251
252impl Encoder {
253	/// Opens [`Config::device`], or the first render node that encodes [`Config::codec`], and sets up an encode session for `config`.
254	///
255	/// # Errors
256	///
257	/// Fails when the frame size is zero or odd, when libva cannot be loaded, when the named node cannot be opened
258	/// or does not encode the codec (a named node is never swapped for
259	/// another), when no node encodes it, and when the driver refuses the
260	/// session or, for H.265, requires a coding tool this encoder does not write
261	/// or takes no packed sequence header.
262	pub fn new(mut config: Config) -> anyhow::Result<Self> {
263		let (width, height) = (config.width, config.height);
264		if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
265			anyhow::bail!("a {width}x{height} frame, which 4:2:0 chroma needs nonzero and even");
266		}
267		let codec = config.codec;
268		let (device, display) = match config.device.take() {
269			Some(device) => {
270				let display = Display::open_drm_display(&device)
271					.map_err(|e| anyhow::anyhow!("open DRM display {device:?}: {e:?}"))?;
272				(device, display)
273			}
274			None => crate::display::open_first(|display| probe(display, codec))
275				.map_err(|e| e.context(format!("find a render node that encodes {codec:?}")))?,
276		};
277
278		let entrypoint = encode_entrypoint(&display, codec)?;
279		let rate_control = RateControl::pick(
280			&display.query_vendor_string().unwrap_or_default(),
281			config_attribute(
282				&display,
283				codec,
284				entrypoint,
285				VAConfigAttribType::VAConfigAttribRateControl,
286			),
287		);
288		let mut attrs = vec![
289			VAConfigAttrib {
290				type_: VAConfigAttribType::VAConfigAttribRTFormat,
291				value: VA_RT_FORMAT_YUV420,
292			},
293			VAConfigAttrib {
294				type_: VAConfigAttribType::VAConfigAttribRateControl,
295				value: rate_control.va(),
296			},
297		];
298		// The parameter sets go out as packed headers, so the VUI (color, frame
299		// buffering) and the level are ours. For H.264 that is the SPS and PPS;
300		// iHD takes them without being told, and a driver that follows the spec
301		// writes its own unless the config asks. For H.265 it is the VPS, SPS and
302		// PPS as one sequence header. Each slice header is packed too, as ffmpeg
303		// packs them; the driver writes the slice headers if it does not take
304		// them. radeonsi needs them for H.264: it takes the slice's NAL header
305		// from the packed one, and drops the packed parameter sets without one.
306		let wanted = match codec {
307			Codec::H264 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE,
308			Codec::H265 => VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_SLICE,
309		};
310		let packed = packed_headers(&display, codec, entrypoint) & wanted;
311		// VA's H.265 sequence parameters have no conformance window and carry no
312		// VUI here, so an SPS the driver writes would lose the crop and the color.
313		if codec == Codec::H265 && packed & VA_ENC_PACKED_HEADER_SEQUENCE == 0 {
314			anyhow::bail!("the driver takes no packed H.265 sequence header, which the crop and color need");
315		}
316		if packed != 0 {
317			attrs.push(VAConfigAttrib {
318				type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
319				value: packed,
320			});
321		} else {
322			tracing::warn!("the driver takes no packed {codec:?} headers; the stream carries the driver's own");
323		}
324		let mut va_config = display
325			.create_config(attrs, profile(codec), entrypoint)
326			.map_err(|e| anyhow::anyhow!("create VA config: {e:?}"))?;
327
328		let syntax = match codec {
329			Codec::H264 => {
330				let (sps, pps) = build_sps_pps(&config);
331				Syntax::H264 { sps, pps, packed }
332			}
333			Codec::H265 => Syntax::H265 {
334				stream: h265::Stream::new(&display, entrypoint, &mut va_config, &config)?,
335				packed,
336			},
337		};
338		// H.264 sizes the context and its references to the frame, which has
339		// always worked; H.265 to whole minimum coding blocks, as ffmpeg does,
340		// and to the driver's surface alignment.
341		let size = match &syntax {
342			Syntax::H264 { .. } => (config.width, config.height),
343			Syntax::H265 { stream, .. } => stream.coded(),
344		};
345
346		let context = display
347			.create_context::<()>(&va_config, size.0, size.1, None, true)
348			.map_err(|e| anyhow::anyhow!("create VA context: {e:?}"))?;
349
350		let coded_size = coded_size(config.bitrate);
351		let coded = context
352			.create_enc_coded(coded_size)
353			.map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
354
355		let input = make_surface(&display, (config.width, config.height))?;
356		let nv12 = display
357			.query_image_formats()
358			.map_err(|e| anyhow::anyhow!("query image formats: {e:?}"))?
359			.into_iter()
360			.find(|format| format.fourcc == VA_FOURCC_NV12);
361		let recon = vec![make_surface(&display, size)?, make_surface(&display, size)?];
362
363		tracing::info!(
364			"opened VA-API {codec:?} encoder on {:?}: {}x{} @ {}fps, {} bps, {:?} rate control, low power: {}",
365			device,
366			config.width,
367			config.height,
368			config.framerate,
369			config.bitrate,
370			rate_control,
371			entrypoint == VAEntrypoint::VAEntrypointEncSliceLP,
372		);
373		config.device = Some(device);
374		Ok(Self {
375			config,
376			syntax,
377			input: Some(input),
378			nv12,
379			recon,
380			reference: None,
381			counter: 0,
382			idrs: 0,
383			processor: None,
384			reset_rate_control: false,
385			rate_control,
386			coded,
387			coded_size,
388			context,
389			_va_config: va_config,
390			display,
391		})
392	}
393
394	/// Encodes one tightly-packed NV12 frame, returning Annex-B (with the
395	/// parameter sets inline on each IDR). `keyframe` forces an IDR.
396	///
397	/// # Errors
398	///
399	/// Fails when `nv12` is shorter than a frame at the encoder's size, when the
400	/// driver has no NV12 image format, and when the upload or the encode fails.
401	pub fn encode_nv12(&mut self, nv12: &[u8], keyframe: bool) -> anyhow::Result<Vec<u8>> {
402		let format = self
403			.nv12
404			.ok_or_else(|| anyhow::anyhow!("driver has no NV12 image format"))?;
405		let mut input = self.input.take().expect("input surface present");
406		let result = upload_nv12(format, &mut input, self.config.width, self.config.height, nv12)
407			.and_then(|()| self.encode_surface(&input, keyframe));
408		self.input = Some(input);
409		result
410	}
411
412	/// Encodes one frame held in a DMA-BUF, returning Annex-B like
413	/// [`encode_nv12`](Self::encode_nv12).
414	///
415	/// An NV12 buffer at the encoder's size, which the encoder reads without
416	/// padding (whole macroblocks for H.264; for H.265, whole minimum coding
417	/// blocks at the driver's surface alignment), and whose
418	/// [`color`](DmaBuf::color) is the stream's or unknown, is imported and
419	/// encoded in place. Any other mapped format or size goes through the video processor into the encoder's own surface
420	/// first: scaled to the encoder's size and converted to [`Config::color`].
421	/// A YUV buffer with no color of its own is taken to be in that space
422	/// already. Nothing reaches the CPU on either path.
423	///
424	/// The macroblock condition is not a formality: the encoder reads whole
425	/// macroblocks, so it reads 1088 rows of a 1080-row picture, and a producer
426	/// that places the chroma plane right after the last visible luma row
427	/// (PipeWire does) has nothing there to read.
428	///
429	/// The producer must have finished writing the buffer; this does not wait
430	/// on its fence.
431	///
432	/// # Errors
433	///
434	/// Fails when the driver refuses to import the buffer (an unsupported
435	/// modifier or layout), when the device has no video processor and the
436	/// buffer needs one, and when the encode itself fails. The encoder stays
437	/// usable after a refused import, so a caller can fall back to
438	/// [`encode_nv12`](Self::encode_nv12) for the same frame.
439	pub fn encode_dmabuf(&mut self, buffer: DmaBuf, keyframe: bool) -> anyhow::Result<Vec<u8>> {
440		let fourcc = buffer
441			.fourcc()
442			.ok_or_else(|| anyhow::anyhow!("no VA-API format for DRM format {:#010x}", buffer.drm_format))?;
443		let color = self.config.color;
444		let size = (self.config.width, self.config.height);
445		let unpadded = match &self.syntax {
446			Syntax::H264 { .. } => size.0 % 16 == 0 && size.1 % 16 == 0,
447			Syntax::H265 { stream, .. } => stream.coded() == size,
448		};
449		let in_place = fourcc == VA_FOURCC_NV12
450			&& (buffer.width, buffer.height) == size
451			&& unpadded
452			&& buffer.color.is_none_or(|own| own == color);
453		if in_place {
454			let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_ENCODER))?;
455			return self.encode_surface(&source, keyframe);
456		}
457
458		let input_color = match is_rgb(fourcc) {
459			true => None,
460			false => Some(buffer.color.unwrap_or(color)),
461		};
462		let source = buffer.import(&self.display, Some(UsageHint::USAGE_HINT_VPP_READ))?;
463		let input = self.input.take().expect("input surface present");
464		let result = self
465			.processor()
466			.and_then(|processor| processor.blit(&source, &input, input_color, Some(color)))
467			.and_then(|()| self.encode_surface(&input, keyframe));
468		self.input = Some(input);
469		result
470	}
471
472	/// Changes [`Config::bitrate`], in bits per second, from the next frame on.
473	///
474	/// The rate control parameters go out with every frame, so this neither
475	/// forces an IDR nor rebuilds the session; the next frame also asks the
476	/// driver to reset its rate controller. It then converges over its window,
477	/// [`RATE_CONTROL_WINDOW_MS`].
478	///
479	/// The level in the SPS is not revisited, so a rate far above the one the
480	/// stream opened with can exceed what that level allows.
481	///
482	/// # Errors
483	///
484	/// Fails for a bitrate of zero, and when a larger coded buffer for the new
485	/// rate cannot be allocated, in which case the old rate stays.
486	pub fn set_bitrate(&mut self, bitrate: u32) -> anyhow::Result<()> {
487		if bitrate == 0 {
488			anyhow::bail!("a bitrate of zero");
489		}
490		let size = coded_size(bitrate);
491		if size > self.coded_size {
492			// A higher rate can produce a picture larger than the buffer sized for
493			// the old one, and a truncated picture is corrupt rather than short.
494			self.coded = self
495				.context
496				.create_enc_coded(size)
497				.map_err(|e| anyhow::anyhow!("create coded buffer: {e:?}"))?;
498			self.coded_size = size;
499		}
500		if bitrate != self.config.bitrate {
501			self.reset_rate_control = true;
502		}
503		self.config.bitrate = bitrate;
504		Ok(())
505	}
506
507	/// Returns how the bitrate is spent, picked at open from what the driver offers.
508	pub fn rate_control(&self) -> RateControl {
509		self.rate_control
510	}
511
512	/// Returns the configuration in effect, including a bitrate changed since opening and the render node picked when none was named.
513	pub fn config(&self) -> &Config {
514		&self.config
515	}
516
517	/// Returns the video processor, opening it on first use.
518	fn processor(&mut self) -> anyhow::Result<&Processor> {
519		if self.processor.is_none() {
520			self.processor = Some(Processor::with_display(Arc::clone(&self.display))?);
521		}
522		Ok(self.processor.as_ref().expect("opened above"))
523	}
524
525	/// Encodes the picture in `source`, which must be NV12 at the encoder's size.
526	fn encode_surface<D: SurfaceMemoryDescriptor>(
527		&mut self,
528		source: &Surface<D>,
529		keyframe: bool,
530	) -> anyhow::Result<Vec<u8>> {
531		let is_idr = keyframe || self.counter % self.config.gop.get() == 0;
532		if is_idr {
533			// An IDR restarts the picture count and drops the reference.
534			self.counter = 0;
535			self.reference = None;
536		}
537
538		let recon_idx = (self.counter as usize) % self.recon.len();
539		// The reference is the previous picture's reconstruction, for a P picture.
540		let reference = match (is_idr, self.reference) {
541			(false, Some((index, count))) => Some(Reference {
542				surface: self.recon[index].id(),
543				count,
544			}),
545			_ => None,
546		};
547		let info = PictureInfo {
548			idr: is_idr,
549			idr_id: self.idrs,
550			count: self.counter,
551			recon: self.recon[recon_idx].id(),
552			reference,
553			coded: &self.coded,
554			bitrate: self.config.bitrate,
555		};
556		let buffers = match &self.syntax {
557			Syntax::H264 { sps, pps, packed } => h264_buffers(sps, pps, &info, *packed)?,
558			Syntax::H265 { stream, packed } => stream.buffers(&self.config, &info, *packed),
559		};
560
561		let mut picture = Picture::new(self.counter as u64, Rc::clone(&self.context), source);
562
563		// VA-API spec buffer order: sequence, picture, slice, then packed headers,
564		// then rate-control misc params.
565		for buffer in buffers {
566			picture.add_buffer(self.create(buffer)?);
567		}
568
569		let bits_per_second = self.config.bitrate;
570		let rc = EncMiscParameterRateControl::new(
571			bits_per_second,
572			100,                    // target_percentage: VBR's target is its peak
573			RATE_CONTROL_WINDOW_MS, // window_size (ms)
574			u32::from((MIN_QP + MAX_QP) / 2),
575			MIN_QP as u32,
576			0, // basic_unit_size
577			// Do not let rate control drop a frame to meet the bitrate. A live
578			// encoder has already admitted this frame into the media timeline.
579			// Nor pad a cheap one up to it: filler bits carry no picture.
580			RcFlags::new(u32::from(self.reset_rate_control), 1, 1, 0, 0, 0, 0, 0, 0),
581			0, // icq_quality_factor
582			MAX_QP as u32,
583			0, // quality_factor
584			0, // target_frame_size
585		);
586		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::RateControl(rc)))?);
587		// After the rate control parameters, which radeonsi reads as resetting the buffer.
588		let hrd = hrd_size(bits_per_second, self.config.framerate);
589		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::HRD(
590			EncMiscParameterHRD::new(hrd, hrd),
591		)))?);
592
593		let framerate = EncMiscParameterFrameRate::new(self.config.framerate, 0);
594		picture.add_buffer(self.create(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(framerate)))?);
595
596		let picture = picture.begin().map_err(|e| anyhow::anyhow!("picture begin: {e:?}"))?;
597		let picture = picture.render().map_err(|e| anyhow::anyhow!("picture render: {e:?}"))?;
598		let picture = picture.end().map_err(|e| anyhow::anyhow!("picture end: {e:?}"))?;
599		// Sync (PictureEnd -> PictureSync) so the source is no longer read and
600		// the coded buffer is ready.
601		picture
602			.sync()
603			.map_err(|(e, _)| anyhow::anyhow!("picture sync: {e:?}"))?;
604
605		// The reconstructed surface syncs implicitly; read the coded bitstream.
606		let bitstream = self.read_coded()?;
607
608		self.reference = Some((recon_idx, self.counter));
609		self.counter += 1;
610		self.idrs = self.idrs.wrapping_add(u32::from(is_idr));
611		self.reset_rate_control = false;
612		Ok(bitstream)
613	}
614
615	fn create(&self, buffer: BufferType) -> anyhow::Result<crate::Buffer> {
616		self.context
617			.create_buffer(buffer)
618			.map_err(|e| anyhow::anyhow!("create VA buffer: {e:?}"))
619	}
620
621	fn read_coded(&self) -> anyhow::Result<Vec<u8>> {
622		let mapped = MappedCodedBuffer::new(&self.coded).map_err(|e| anyhow::anyhow!("map coded buffer: {e:?}"))?;
623		let mut out = Vec::new();
624		for segment in mapped.iter() {
625			out.extend_from_slice(segment.buf);
626		}
627		Ok(out)
628	}
629}
630
631/// Checks that `display`'s driver can encode `codec`, which is what [`Encoder::new`] needs of a render node.
632///
633/// # Errors
634///
635/// Fails when the driver offers neither the full nor the low-power Main
636/// profile encode entrypoint for `codec`, or cannot be asked.
637pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
638	encode_entrypoint(display, codec).map(drop)
639}
640
641/// Returns the VA profile `codec` is encoded in.
642fn profile(codec: Codec) -> VAProfile::Type {
643	match codec {
644		Codec::H264 => VAProfile::VAProfileH264Main,
645		Codec::H265 => h265::PROFILE,
646	}
647}
648
649/// Returns the entrypoint to encode `codec` with: the full one, or the low-power one where it is all there is.
650///
651/// Some Intel parts expose encode only through `VAEntrypointEncSliceLP`.
652fn encode_entrypoint(display: &Display, codec: Codec) -> anyhow::Result<VAEntrypoint::Type> {
653	let entrypoints = display
654		.query_config_entrypoints(profile(codec))
655		.map_err(|e| anyhow::anyhow!("query {codec:?} Main entrypoints: {e:?}"))?;
656	pick_entrypoint(&entrypoints).ok_or_else(|| anyhow::anyhow!("the device has no {codec:?} Main encode entrypoint"))
657}
658
659/// Returns the encode entrypoint to use out of those a device offers: the full one when present.
660fn pick_entrypoint(offered: &[VAEntrypoint::Type]) -> Option<VAEntrypoint::Type> {
661	[VAEntrypoint::VAEntrypointEncSlice, VAEntrypoint::VAEntrypointEncSliceLP]
662		.into_iter()
663		.find(|entrypoint| offered.contains(entrypoint))
664}
665
666/// Returns the packed header kinds the driver takes for `codec` at `entrypoint`.
667///
668/// Zero when it takes none, or when asking fails.
669fn packed_headers(display: &Display, codec: Codec, entrypoint: VAEntrypoint::Type) -> u32 {
670	config_attribute(
671		display,
672		codec,
673		entrypoint,
674		VAConfigAttribType::VAConfigAttribEncPackedHeaders,
675	)
676}
677
678/// Returns the bits of attribute `type_` the driver offers for encoding `codec`, or none when it does not say.
679fn config_attribute(
680	display: &Display,
681	codec: Codec,
682	entrypoint: VAEntrypoint::Type,
683	type_: VAConfigAttribType::Type,
684) -> u32 {
685	let mut attrs = [VAConfigAttrib { type_, value: 0 }];
686	if display
687		.get_config_attributes(profile(codec), entrypoint, &mut attrs)
688		.is_err()
689		|| attrs[0].value & VA_ATTRIB_NOT_SUPPORTED != 0
690	{
691		return 0;
692	}
693	attrs[0].value
694}
695
696/// Returns the lowest H.264 level, from 4 up, whose frame size and macroblock rate cover the stream.
697///
698/// Only those two limits: the level's maximum bitrate is not checked.
699///
700/// Level 4 is the floor because it was the fixed level before, and decoders
701/// take the DPB size from `max_dec_frame_buffering` rather than from the level,
702/// so a lower one would buy nothing. Above 1080p (a 1440p or 4K screen share) a
703/// fixed level 4 would declare a stream its decoder may refuse.
704fn level(width: u32, height: u32, framerate: u32) -> Level {
705	// H.264 Table A-1: (level, MaxMBPS, MaxFS).
706	const LEVELS: [(Level, u64, u64); 8] = [
707		(Level::L4, 245_760, 8_192),
708		(Level::L4_2, 522_240, 8_704),
709		(Level::L5, 589_824, 22_080),
710		(Level::L5_1, 983_040, 36_864),
711		(Level::L5_2, 2_073_600, 36_864),
712		(Level::L6, 4_177_920, 139_264),
713		(Level::L6_1, 8_355_840, 139_264),
714		(Level::L6_2, 16_711_680, 139_264),
715	];
716	let frame = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
717	let rate = frame * u64::from(framerate.max(1));
718	LEVELS
719		.into_iter()
720		.find(|&(_, max_rate, max_frame)| frame <= max_frame && rate <= max_rate)
721		.map(|(level, _, _)| level)
722		.unwrap_or(Level::L6_2)
723}
724
725/// Returns the HRD buffer in bits for `bitrate`: [`HRD_FRAMES`] frames of it.
726fn hrd_size(bitrate: u32, framerate: u32) -> u32 {
727	(u64::from(bitrate) * u64::from(HRD_FRAMES) / u64::from(framerate.max(1))).min(u64::from(u32::MAX)) as u32
728}
729
730/// Returns the coded buffer size in bytes for `bitrate`: two seconds of it, and at least 1.5 MB.
731fn coded_size(bitrate: u32) -> usize {
732	(bitrate as usize / 4).max(1_500_000)
733}
734
735/// Returns whether the VA fourcc `fourcc` is packed RGB, which has no YUV matrix of its own.
736fn is_rgb(fourcc: u32) -> bool {
737	matches!(
738		fourcc,
739		VA_FOURCC_BGRX | VA_FOURCC_BGRA | VA_FOURCC_RGBX | VA_FOURCC_RGBA | VA_FOURCC_XRGB | VA_FOURCC_ARGB
740	)
741}
742
743/// Allocate one NV12 encode surface.
744fn make_surface(display: &Arc<Display>, (width, height): (u32, u32)) -> anyhow::Result<Surface<()>> {
745	let mut surfaces = display
746		.create_surfaces::<()>(
747			VA_RT_FORMAT_YUV420,
748			Some(VA_FOURCC_NV12),
749			width,
750			height,
751			Some(UsageHint::USAGE_HINT_ENCODER),
752			vec![()],
753		)
754		.map_err(|e| anyhow::anyhow!("create surface: {e:?}"))?;
755	surfaces.pop().ok_or_else(|| anyhow::anyhow!("no surface created"))
756}
757
758/// Uploads tightly-packed NV12 into `surface` through an image in `format`,
759/// honoring the image's per-plane offsets and pitches, without reading the
760/// surface back first.
761fn upload_nv12(
762	format: VAImageFormat,
763	surface: &mut Surface<()>,
764	width: u32,
765	height: u32,
766	data: &[u8],
767) -> anyhow::Result<()> {
768	let (w, h) = (width as usize, height as usize);
769	let luma = w * h;
770	let expected = luma + w * (h / 2);
771	if data.len() < expected {
772		anyhow::bail!("NV12 frame is {} bytes, {width}x{height} needs {expected}", data.len());
773	}
774
775	let mut image =
776		ImageMut::create_uninitialized(surface, format).map_err(|e| anyhow::anyhow!("create image: {e:?}"))?;
777	let va_image = *image.image();
778	let dest: &mut [u8] = image.as_mut();
779	let planes = [(&data[..luma], h), (&data[luma..expected], h / 2)];
780	for (plane, (src, rows)) in planes.into_iter().enumerate() {
781		let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
782		fill_plane(dest, offset, pitch, src, w, rows)?;
783	}
784	image.put().map_err(|e| anyhow::anyhow!("put image: {e:?}"))
785}
786
787/// Copies `rows` rows of `width` bytes from tightly packed `src` into the image
788/// plane at `offset` with `pitch` bytes per row, failing when the plane does
789/// not hold them.
790fn fill_plane(
791	dst: &mut [u8],
792	offset: usize,
793	pitch: usize,
794	src: &[u8],
795	width: usize,
796	rows: usize,
797) -> anyhow::Result<()> {
798	if rows == 0 || width == 0 {
799		return Ok(());
800	}
801	// The last row needs only `width` bytes, not a whole pitch.
802	let end = (rows - 1)
803		.checked_mul(pitch)
804		.and_then(|start| start.checked_add(offset)?.checked_add(width));
805	if pitch < width || end.is_none_or(|end| end > dst.len()) {
806		anyhow::bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
807	}
808	for (row, src) in src.chunks_exact(width).take(rows).enumerate() {
809		let start = offset + row * pitch;
810		dst[start..start + width].copy_from_slice(src);
811	}
812	Ok(())
813}
814
815/// Build the SPS/PPS for a low-latency IPPP stream. Ported from
816/// discord/cros-codecs `LowDelayH264Delegate::new_sequence` (BSD-3-Clause).
817fn build_sps_pps(config: &Config) -> (Arc<Sps>, Arc<Pps>) {
818	let level = level(config.width, config.height, config.framerate);
819	let (primaries, transfer, matrix) = config.color.vui();
820	let sps = SpsBuilder::new()
821		.seq_parameter_set_id(0)
822		.profile_idc(Profile::Main)
823		.chroma_format_idc(1)
824		.level_idc(level)
825		.max_frame_num(LIMIT)
826		.pic_order_cnt_type(0)
827		.max_pic_order_cnt_lsb(LIMIT * 2)
828		.max_num_ref_frames(1)
829		.frame_mbs_only_flag(true)
830		.direct_8x8_inference_flag(level >= Level::L3)
831		.resolution(config.width, config.height)
832		.bit_depth_luma(8)
833		.bit_depth_chroma(8)
834		.aspect_ratio(1, 1)
835		.timing_info(1, config.framerate * 2, false)
836		.video_signal_type(config.color.full_range, primaries, transfer, matrix)
837		.max_num_reorder_frames(0)
838		.max_dec_frame_buffering(1)
839		.build();
840
841	let pps = PpsBuilder::new(Arc::clone(&sps))
842		.pic_parameter_set_id(0)
843		.pic_init_qp(26)
844		.entropy_coding_mode_flag(true)
845		.transform_8x8_mode_flag(false)
846		.deblocking_filter_control_present_flag(true)
847		.num_ref_idx_l0_default_active(1)
848		.num_ref_idx_l1_default_active_minus1(0)
849		.build();
850
851	(sps, pps)
852}
853
854/// Returns the parameter buffers of one H.264 picture, then the packed headers the driver takes: the SPS and PPS on an IDR, and the slice header.
855fn h264_buffers(sps: &Sps, pps: &Arc<Pps>, picture: &PictureInfo<'_>, packed: u32) -> anyhow::Result<Vec<BufferType>> {
856	let meta = FrameMeta::new(picture.count);
857	let slice_type = if picture.idr { SliceType::I } else { SliceType::P };
858	let header = SliceHeaderBuilder::new(pps)
859		.slice_type(slice_type)
860		.first_mb_in_slice(0)
861		.frame_num(meta.frame_num as u16)
862		.pic_order_cnt_lsb((meta.poc % (LIMIT * 2)) as u16)
863		// Only consecutive IDRs must differ.
864		.idr_pic_id((picture.idr_id % 2) as u16)
865		.build();
866	let macroblocks = (sps.pic_width_in_mbs_minus1 as u32 + 1) * (sps.pic_height_in_map_units_minus1 as u32 + 1);
867	let reference = picture
868		.reference
869		.map(|reference| (reference.surface, FrameMeta::new(reference.count)));
870
871	let mut buffers = vec![
872		build_enc_seq_param(sps, picture.bitrate, LIMIT, 0),
873		build_enc_pic_param(pps, picture.coded, picture.recon, meta, picture.idr, reference),
874		build_enc_slice_param(pps, &header, reference, macroblocks),
875	];
876	if picture.idr && packed & VA_ENC_PACKED_HEADER_SEQUENCE != 0 {
877		buffers.extend(packed_parameter_sets(sps, pps)?);
878	}
879	if packed & VA_ENC_PACKED_HEADER_SLICE != 0 {
880		let mut nal = Vec::new();
881		// Every picture is a short-term reference, an IDR the strongest.
882		let nal_header = match picture.idr {
883			true => NaluHeader {
884				ref_idc: 3,
885				type_: NaluType::SliceIdr,
886			},
887			false => NaluHeader {
888				ref_idc: 1,
889				type_: NaluType::Slice,
890			},
891		};
892		let trailing = header
893			.write(nal_header, pps, &mut nal)
894			.context("write the slice header")?;
895		// The slice data follows the header's last bit, not its padded last byte.
896		let bits = nal.len() * 8 - usize::from(trailing);
897		buffers.extend(packed_header(EncPackedHeaderType::Slice, &nal, bits));
898	}
899	Ok(buffers)
900}
901
902/// Returns the SPS and PPS as packed headers, which go out with every IDR.
903fn packed_parameter_sets(sps: &Sps, pps: &Pps) -> anyhow::Result<[BufferType; 4]> {
904	let mut sps_nal = Vec::new();
905	sps.write(3, &mut sps_nal).context("write the SPS")?;
906	let mut pps_nal = Vec::new();
907	pps.write(3, &mut pps_nal).context("write the PPS")?;
908
909	let [sps_param, sps_data] = packed_header(EncPackedHeaderType::Sequence, &sps_nal, sps_nal.len() * 8);
910	let [pps_param, pps_data] = packed_header(EncPackedHeaderType::Picture, &pps_nal, pps_nal.len() * 8);
911	Ok([sps_param, sps_data, pps_param, pps_data])
912}
913
914fn build_invalid_pic() -> PictureH264 {
915	PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
916}
917
918fn build_h264_pic(surface_id: u32, meta: FrameMeta) -> PictureH264 {
919	PictureH264::new(
920		surface_id,
921		meta.frame_num,
922		VA_PICTURE_H264_SHORT_TERM_REFERENCE,
923		meta.poc as i32,
924		meta.poc as i32,
925	)
926}
927
928/// Ported from cros-codecs `build_enc_seq_param` (BSD-3-Clause).
929fn build_enc_seq_param(sps: &Sps, bits_per_second: u32, intra_period: u32, ip_period: u32) -> BufferType {
930	let seq_fields = H264EncSeqFields::new(
931		sps.chroma_format_idc as u32,
932		sps.frame_mbs_only_flag as u32,
933		sps.mb_adaptive_frame_field_flag as u32,
934		sps.seq_scaling_matrix_present_flag as u32,
935		sps.direct_8x8_inference_flag as u32,
936		sps.log2_max_frame_num_minus4 as u32,
937		sps.pic_order_cnt_type as u32,
938		sps.log2_max_pic_order_cnt_lsb_minus4 as u32,
939		sps.delta_pic_order_always_zero_flag as u32,
940	);
941
942	let frame_crop = if sps.frame_cropping_flag {
943		Some(H264EncFrameCropOffsets::new(
944			sps.frame_crop_left_offset,
945			sps.frame_crop_right_offset,
946			sps.frame_crop_top_offset,
947			sps.frame_crop_bottom_offset,
948		))
949	} else {
950		None
951	};
952
953	let vui_fields = if sps.vui_parameters_present_flag {
954		Some(H264VuiFields::new(
955			sps.vui_parameters.aspect_ratio_idc as u32,
956			sps.vui_parameters.timing_info_present_flag as u32,
957			sps.vui_parameters.bitstream_restriction_flag as u32,
958			sps.vui_parameters.log2_max_mv_length_horizontal,
959			sps.vui_parameters.log2_max_mv_length_vertical,
960			sps.vui_parameters.fixed_frame_rate_flag as u32,
961			sps.vui_parameters.low_delay_hrd_flag as u32,
962			sps.vui_parameters.motion_vectors_over_pic_boundaries_flag as u32,
963		))
964	} else {
965		None
966	};
967
968	let mut offset_for_ref_frame = [0i32; 256];
969	offset_for_ref_frame[..255].copy_from_slice(&sps.offset_for_ref_frame[..]);
970
971	BufferType::EncSequenceParameter(EncSequenceParameter::H264(EncSequenceParameterBufferH264::new(
972		sps.seq_parameter_set_id,
973		sps.level_idc as u8,
974		intra_period,
975		intra_period,
976		ip_period,
977		bits_per_second,
978		sps.max_num_ref_frames as u32,
979		sps.pic_width_in_mbs_minus1 + 1,
980		sps.pic_height_in_map_units_minus1 + 1,
981		&seq_fields,
982		sps.bit_depth_luma_minus8,
983		sps.bit_depth_chroma_minus8,
984		sps.num_ref_frames_in_pic_order_cnt_cycle,
985		sps.offset_for_non_ref_pic,
986		sps.offset_for_top_to_bottom_field,
987		offset_for_ref_frame,
988		frame_crop,
989		vui_fields,
990		sps.vui_parameters.aspect_ratio_idc,
991		sps.vui_parameters.sar_width as u32,
992		sps.vui_parameters.sar_height as u32,
993		sps.vui_parameters.num_units_in_tick,
994		sps.vui_parameters.time_scale,
995	)))
996}
997
998/// Ported from cros-codecs `build_enc_pic_param` (BSD-3-Clause).
999fn build_enc_pic_param(
1000	pps: &Pps,
1001	coded: &EncCodedBuffer,
1002	recon_id: u32,
1003	meta: FrameMeta,
1004	is_idr: bool,
1005	reference: Option<(u32, FrameMeta)>,
1006) -> BufferType {
1007	let pic_fields = H264EncPicFields::new(
1008		is_idr as u32,
1009		1, // reference_pic_flag: this frame is a short-term reference
1010		pps.entropy_coding_mode_flag as u32,
1011		pps.weighted_pred_flag as u32,
1012		pps.weighted_bipred_idc as u32,
1013		pps.constrained_intra_pred_flag as u32,
1014		pps.transform_8x8_mode_flag as u32,
1015		pps.deblocking_filter_control_present_flag as u32,
1016		pps.redundant_pic_cnt_present_flag as u32,
1017		0,
1018		pps.pic_scaling_matrix_present_flag as u32,
1019	);
1020
1021	let curr_pic = build_h264_pic(recon_id, meta);
1022	let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| build_invalid_pic());
1023	if let Some((id, m)) = reference {
1024		reference_frames[0] = build_h264_pic(id, m);
1025	}
1026
1027	BufferType::EncPictureParameter(EncPictureParameter::H264(EncPictureParameterBufferH264::new(
1028		curr_pic,
1029		reference_frames,
1030		coded.id(),
1031		pps.pic_parameter_set_id,
1032		pps.sps.seq_parameter_set_id,
1033		0,
1034		meta.frame_num as u16,
1035		(pps.pic_init_qp_minus26 + 26) as u8,
1036		pps.num_ref_idx_l0_default_active_minus1,
1037		pps.num_ref_idx_l1_default_active_minus1,
1038		pps.chroma_qp_index_offset,
1039		pps.second_chroma_qp_index_offset,
1040		&pic_fields,
1041	)))
1042}
1043
1044/// Ported from cros-codecs `build_enc_slice_param` (BSD-3-Clause), simplified for
1045/// IPPP (no weighted prediction, single reference in list 0).
1046fn build_enc_slice_param(
1047	pps: &Pps,
1048	header: &SliceHeader,
1049	reference: Option<(u32, FrameMeta)>,
1050	num_macroblocks: u32,
1051) -> BufferType {
1052	let mut ref_pic_list_0: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1053	if let Some((id, m)) = reference {
1054		ref_pic_list_0[0] = build_h264_pic(id, m);
1055	}
1056	let ref_pic_list_1: [PictureH264; 32] = std::array::from_fn(|_| build_invalid_pic());
1057
1058	let (num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1) = if header.num_ref_idx_active_override_flag {
1059		(header.num_ref_idx_l0_active_minus1, header.num_ref_idx_l1_active_minus1)
1060	} else {
1061		(
1062			pps.num_ref_idx_l0_default_active_minus1,
1063			pps.num_ref_idx_l1_default_active_minus1,
1064		)
1065	};
1066
1067	BufferType::EncSliceParameter(EncSliceParameter::H264(EncSliceParameterBufferH264::new(
1068		header.first_mb_in_slice,
1069		num_macroblocks,
1070		VA_INVALID_ID,
1071		header.slice_type as u8,
1072		pps.pic_parameter_set_id,
1073		header.idr_pic_id,
1074		header.pic_order_cnt_lsb,
1075		header.delta_pic_order_cnt_bottom,
1076		header.delta_pic_order_cnt,
1077		header.direct_spatial_mv_pred_flag as u8,
1078		header.num_ref_idx_active_override_flag as u8,
1079		num_ref_idx_l0_active_minus1,
1080		num_ref_idx_l1_active_minus1,
1081		ref_pic_list_0,
1082		ref_pic_list_1,
1083		header.pred_weight_table.luma_log2_weight_denom,
1084		header.pred_weight_table.chroma_log2_weight_denom,
1085		0,
1086		header.pred_weight_table.luma_weight_l0,
1087		[0i16; 32],
1088		0,
1089		header.pred_weight_table.chroma_weight_l0,
1090		[[0i16; 2]; 32],
1091		0,
1092		header.pred_weight_table.luma_weight_l1,
1093		[0i16; 32],
1094		0,
1095		header.pred_weight_table.chroma_weight_l1,
1096		[[0i16; 2]; 32],
1097		header.cabac_init_idc,
1098		header.slice_qp_delta,
1099		header.disable_deblocking_filter_idc,
1100		header.slice_alpha_c0_offset_div2,
1101		header.slice_beta_offset_div2,
1102	)))
1103}
1104
1105/// Returns the packed-header parameter and data buffers for the first `bits` of `data`, a NAL unit that carries its own emulation prevention.
1106fn packed_header(kind: EncPackedHeaderType, data: &[u8], bits: usize) -> [BufferType; 2] {
1107	let param = BufferType::EncPackedHeaderParameter(EncPackedHeaderParameter::new(kind, bits as u32, true));
1108	let payload = BufferType::EncPackedHeaderData(data.to_vec());
1109	[param, payload]
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114	use std::path::PathBuf;
1115	use std::process::Command;
1116	use std::sync::atomic::{AtomicU32, Ordering};
1117
1118	use super::*;
1119	use crate::dmabuf::DmaBuf;
1120	use crate::{VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420};
1121
1122	// A size every driver encodes: radeonsi's H.265 minimum on VCN 5 is 384 wide.
1123	const WIDTH: u32 = 640;
1124	const HEIGHT: u32 = 480;
1125	const CODECS: [Codec; 2] = [Codec::H264, Codec::H265];
1126
1127	fn config(codec: Codec) -> Config {
1128		Config {
1129			codec,
1130			width: WIDTH,
1131			height: HEIGHT,
1132			framerate: 30,
1133			bitrate: 2_000_000,
1134			gop: NonZeroU32::new(30).unwrap(),
1135			device: None,
1136			color: Color::infer(HEIGHT),
1137		}
1138	}
1139
1140	fn encoder(config: Config) -> Encoder {
1141		Encoder::new(config).expect("open the VA-API encoder")
1142	}
1143
1144	/// The NAL unit types that open an IDR access unit: the IDR slice, then the parameter sets it carries.
1145	fn idr_types(codec: Codec) -> (u8, &'static [u8]) {
1146		match codec {
1147			Codec::H264 => (5, &[7, 8]),
1148			Codec::H265 => (19, &[32, 33, 34]),
1149		}
1150	}
1151
1152	/// A diagonal gradient with a block moving across it, so a stale or
1153	/// misplaced reference shows up as the block in the wrong place.
1154	fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
1155		let (w, h) = (width as usize, height as usize);
1156		let mut data = vec![128u8; w * h + w * h.div_ceil(2)];
1157		for y in 0..h {
1158			for x in 0..w {
1159				data[y * w + x] = (32 + (x + y) * 160 / (w + h)) as u8;
1160			}
1161		}
1162		let x0 = (step as usize * 8) % (w / 2);
1163		for y in h / 4..h / 2 {
1164			for x in x0..x0 + w / 4 {
1165				data[y * w + x] = 220;
1166			}
1167		}
1168		data
1169	}
1170
1171	/// Returns a temporary file path unique to this call.
1172	///
1173	/// The tests run as threads of one process, so the process id alone would
1174	/// let two of them share a file.
1175	///
1176	/// Its extension names `codec`, for ffmpeg to pick the demuxer by.
1177	fn temp_path(codec: Codec, label: &str) -> PathBuf {
1178		static NEXT: AtomicU32 = AtomicU32::new(0);
1179		let index = NEXT.fetch_add(1, Ordering::Relaxed);
1180		let extension = match codec {
1181			Codec::H264 => "264",
1182			Codec::H265 => "265",
1183		};
1184		std::env::temp_dir().join(format!(
1185			"kodecs-vaapi-{label}-{}-{index}.{extension}",
1186			std::process::id()
1187		))
1188	}
1189
1190	/// Decodes an Annex-B stream with ffmpeg's software decoder into NV12
1191	/// pictures.
1192	fn ffmpeg_decode(codec: Codec, stream: &[u8], name: &str) -> Vec<u8> {
1193		// ffmpeg reads the elementary stream from a file rather than a pipe, so
1194		// the test never has to drain its output while still writing its input.
1195		let path = temp_path(codec, name);
1196		std::fs::write(&path, stream).expect("write the elementary stream");
1197		let output = Command::new("ffmpeg")
1198			.args(["-v", "error", "-i"])
1199			.arg(&path)
1200			.args(["-pix_fmt", "nv12", "-f", "rawvideo", "-"])
1201			.output();
1202		let _ = std::fs::remove_file(&path);
1203		let output = output.expect("run ffmpeg");
1204		assert!(
1205			output.status.success(),
1206			"ffmpeg refused the stream: {}",
1207			String::from_utf8_lossy(&output.stderr)
1208		);
1209		output.stdout
1210	}
1211
1212	/// Asks ffprobe for the stream's `color_range,color_space`.
1213	fn ffprobe_color(codec: Codec, stream: &[u8]) -> Option<String> {
1214		let path = temp_path(codec, "probe");
1215		std::fs::write(&path, stream).expect("write the elementary stream");
1216		let output = Command::new("ffprobe")
1217			.args([
1218				"-v",
1219				"error",
1220				"-show_entries",
1221				"stream=color_range,color_space",
1222				"-of",
1223				"csv=p=0",
1224			])
1225			.arg(&path)
1226			.output()
1227			.ok();
1228		let _ = std::fs::remove_file(&path);
1229		Some(String::from_utf8(output?.stdout).ok()?.trim().to_string())
1230	}
1231
1232	/// Returns the peak signal-to-noise ratio of the luma planes, in dB.
1233	fn luma_psnr(a: &[u8], b: &[u8], width: u32, height: u32) -> f64 {
1234		let len = (width * height) as usize;
1235		let mse = a[..len]
1236			.iter()
1237			.zip(&b[..len])
1238			.map(|(&x, &y)| (x as f64 - y as f64).powi(2))
1239			.sum::<f64>()
1240			/ len as f64;
1241		10.0 * (255.0f64.powi(2) / mse.max(1e-9)).log10()
1242	}
1243
1244	/// Returns the mean of the samples in a rectangle of one plane.
1245	fn mean(
1246		plane: &[u8],
1247		stride: usize,
1248		(x0, y0, x1, y1): (usize, usize, usize, usize),
1249		step: usize,
1250		at: usize,
1251	) -> f64 {
1252		let mut sum = 0.0;
1253		let mut count = 0.0;
1254		for y in y0..y1 {
1255			for x in x0..x1 {
1256				sum += plane[y * stride + x * step + at] as f64;
1257				count += 1.0;
1258			}
1259		}
1260		sum / count
1261	}
1262
1263	/// Returns the NAL unit types in an Annex-B access unit.
1264	fn nal_types(codec: Codec, unit: &[u8]) -> Vec<u8> {
1265		let mut types = Vec::new();
1266		let mut i = 0;
1267		while i + 3 < unit.len() {
1268			if unit[i..i + 3] == [0, 0, 1] {
1269				types.push(match codec {
1270					Codec::H264 => unit[i + 3] & 0x1f,
1271					Codec::H265 => (unit[i + 3] >> 1) & 0x3f,
1272				});
1273				i += 3;
1274			}
1275			i += 1;
1276		}
1277		types
1278	}
1279
1280	/// Returns a driver surface of `fourcc` on `display` whose pixels are unspecified.
1281	fn blank_surface(display: &Arc<Display>, fourcc: u32, rt_format: u32, (width, height): (u32, u32)) -> Surface<()> {
1282		display
1283			.create_surfaces(
1284				rt_format,
1285				Some(fourcc),
1286				width,
1287				height,
1288				Some(UsageHint::USAGE_HINT_EXPORT),
1289				vec![()],
1290			)
1291			.expect("allocate a surface")
1292			.pop()
1293			.expect("one surface")
1294	}
1295
1296	/// Returns the driver's image format for `fourcc`.
1297	fn image_format(display: &Display, fourcc: u32) -> VAImageFormat {
1298		display
1299			.query_image_formats()
1300			.expect("query image formats")
1301			.into_iter()
1302			.find(|f| f.fourcc == fourcc)
1303			.expect("the driver has an image format for the surface format")
1304	}
1305
1306	/// Returns a driver surface of `fourcc` on `display`, every pixel written by `fill` through an image.
1307	fn surface_with(
1308		display: &Arc<Display>,
1309		fourcc: u32,
1310		rt_format: u32,
1311		size: (u32, u32),
1312		fill: impl FnOnce(&mut [u8], &crate::bindings::VAImage),
1313	) -> Surface<()> {
1314		let mut surface = blank_surface(display, fourcc, rt_format, size);
1315		let mut image =
1316			ImageMut::create_uninitialized(&mut surface, image_format(display, fourcc)).expect("create an image");
1317		let va_image = *image.image();
1318		fill(image.as_mut(), &va_image);
1319		image.put().expect("put the image");
1320		surface.sync().expect("sync the filled surface");
1321		surface
1322	}
1323
1324	/// Returns an NV12 surface holding `nv12_frame`, exported as a DMA-BUF.
1325	fn nv12_dmabuf(display: &Arc<Display>, (width, height): (u32, u32), step: u32) -> DmaBuf {
1326		let mut surface = blank_surface(display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1327		let format = image_format(display, VA_FOURCC_NV12);
1328		upload_nv12(format, &mut surface, width, height, &nv12_frame(width, height, step)).expect("upload");
1329		DmaBuf::from_prime(surface.export_prime().expect("export the surface")).expect("one object")
1330	}
1331
1332	/// With no node named, the encoder opens one that encodes its codec and
1333	/// records which. A named node is used or refused, never swapped for another.
1334	#[test]
1335	#[ignore = "requires a VA-API render node"]
1336	fn the_render_node_is_found_or_named() {
1337		for codec in CODECS {
1338			let encoder = encoder(config(codec));
1339			let device = encoder.config().device.clone().expect("the picked node is recorded");
1340			let display = Display::open_drm_display(&device).expect("reopen the picked node");
1341			probe(&display, codec).expect("the picked node encodes the codec");
1342
1343			let named = Config {
1344				device: Some(PathBuf::from("/dev/null")),
1345				..config(codec)
1346			};
1347			assert!(
1348				Encoder::new(named).is_err(),
1349				"a named node that is not a render node was swapped for one that is"
1350			);
1351		}
1352	}
1353
1354	/// CPU NV12 in, a stream out that an independent decoder reads back as the
1355	/// same pictures, at a size that is whole coding blocks and at one that is not.
1356	#[test]
1357	#[ignore = "requires a VA-API render node and FFmpeg"]
1358	fn nv12_round_trips_through_a_software_decoder() {
1359		for codec in CODECS {
1360			for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1361				let mut encoder = encoder(Config {
1362					width,
1363					height,
1364					..config(codec)
1365				});
1366				let mut stream = Vec::new();
1367				let mut frames = Vec::new();
1368				for step in 0..10 {
1369					let frame = nv12_frame(width, height, step);
1370					stream.extend(encoder.encode_nv12(&frame, false).expect("encode"));
1371					frames.push(frame);
1372				}
1373				let decoded = ffmpeg_decode(codec, &stream, "nv12");
1374				let len = frames[0].len();
1375				assert_eq!(
1376					decoded.len(),
1377					len * frames.len(),
1378					"{codec:?} at {width}x{height}: ffmpeg decoded a different count or size"
1379				);
1380				for (index, frame) in frames.iter().enumerate() {
1381					let psnr = luma_psnr(frame, &decoded[index * len..], width, height);
1382					assert!(
1383						psnr > 35.0,
1384						"{codec:?} at {width}x{height}: picture {index} decoded at {psnr:.1} dB"
1385					);
1386				}
1387			}
1388		}
1389	}
1390
1391	/// The SPS names the color space the encoder was configured with.
1392	#[test]
1393	#[ignore = "requires a VA-API render node and FFmpeg"]
1394	fn the_stream_is_labelled_with_its_color_space() {
1395		for codec in CODECS {
1396			for (color, expected) in [(Color::BT601, "tv,smpte170m"), (Color::BT709, "tv,bt709")] {
1397				let mut encoder = encoder(Config { color, ..config(codec) });
1398				let unit = encoder
1399					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1400					.expect("encode");
1401				let found = ffprobe_color(codec, &unit).expect("run the FFmpeg tools");
1402				assert_eq!(found, expected, "{codec:?}");
1403			}
1404		}
1405	}
1406
1407	/// A plane fills when its last row holds just the frame's width, not a
1408	/// whole pitch, and fails rather than panics when it holds less.
1409	#[test]
1410	fn a_plane_fills_up_to_its_last_byte_and_no_further() {
1411		let src = [1, 2, 3, 4, 5, 6];
1412		// Three rows of two bytes at a pitch of four, starting at offset one:
1413		// the last row ends at byte 1 + 2 * 4 + 2 = 11.
1414		let mut tight = [0; 11];
1415		fill_plane(&mut tight, 1, 4, &src, 2, 3).expect("the last row fits");
1416		assert_eq!(tight, [0, 1, 2, 0, 0, 3, 4, 0, 0, 5, 6]);
1417
1418		assert!(fill_plane(&mut [0; 10], 1, 4, &src, 2, 3).is_err(), "a byte short");
1419		assert!(
1420			fill_plane(&mut [0; 16], 0, 1, &src, 2, 3).is_err(),
1421			"a pitch narrower than a row"
1422		);
1423		assert!(
1424			fill_plane(&mut [0; 4], 0, usize::MAX, &src, 2, 3).is_err(),
1425			"a pitch that overflows"
1426		);
1427		fill_plane(&mut [], 0, 4, &[], 2, 0).expect("no rows need no room");
1428	}
1429
1430	/// A size 4:2:0 chroma cannot halve is refused before any device opens.
1431	#[test]
1432	fn an_odd_or_empty_size_is_refused() {
1433		for (width, height) in [(641, 480), (640, 479), (0, 480), (640, 0)] {
1434			let err = Encoder::new(Config {
1435				width,
1436				height,
1437				..config(Codec::H264)
1438			})
1439			.err()
1440			.expect("refused");
1441			assert!(err.to_string().contains("even"), "{width}x{height}: {err:#}");
1442		}
1443	}
1444
1445	/// The write-only upload puts exactly the frame's pixels into the surface,
1446	/// as a `vaGetImage` read-back of it sees them.
1447	#[test]
1448	#[ignore = "requires a VA-API render node"]
1449	fn an_upload_reads_back_as_the_same_pixels() {
1450		let display = Display::open().expect("no VA-API display");
1451		for (width, height) in [(WIDTH, HEIGHT), (852, 478)] {
1452			let frame = nv12_frame(width, height, 3);
1453			let mut surface = blank_surface(&display, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420, (width, height));
1454			let format = image_format(&display, VA_FOURCC_NV12);
1455			upload_nv12(format, &mut surface, width, height, &frame).expect("upload");
1456
1457			let image =
1458				crate::Image::create_from(&surface, format, (width, height), (width, height)).expect("read back");
1459			let (va_image, data) = (*image.image(), image.as_ref());
1460			let (w, h) = (width as usize, height as usize);
1461			for (plane, rows, src) in [(0, h, &frame[..w * h]), (1, h / 2, &frame[w * h..])] {
1462				let (offset, pitch) = (va_image.offsets[plane] as usize, va_image.pitches[plane] as usize);
1463				for (row, src) in src.chunks_exact(w).take(rows).enumerate() {
1464					let at = offset + row * pitch;
1465					assert_eq!(&data[at..at + w], src, "{width}x{height} plane {plane} row {row}");
1466				}
1467			}
1468		}
1469	}
1470
1471	/// An IDR opens every group, and only there, carrying the parameter sets.
1472	#[test]
1473	#[ignore = "requires a VA-API render node"]
1474	fn keyframes_follow_the_group_length() {
1475		for codec in CODECS {
1476			let mut encoder = encoder(Config {
1477				gop: NonZeroU32::new(10).unwrap(),
1478				..config(codec)
1479			});
1480			let (idr_type, parameter_sets) = idr_types(codec);
1481			for step in 0..25 {
1482				let unit = encoder
1483					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), false)
1484					.expect("encode");
1485				let types = nal_types(codec, &unit);
1486				let idr = types.contains(&idr_type);
1487				assert_eq!(idr, step % 10 == 0, "{codec:?} frame {step} has NAL types {types:?}");
1488				if idr {
1489					assert!(
1490						parameter_sets.iter().all(|kind| types.contains(kind)),
1491						"a {codec:?} IDR carries its parameter sets: {types:?}"
1492					);
1493				}
1494			}
1495			// A forced keyframe restarts the count: the next IDR is a group later.
1496			for step in 0..=10 {
1497				let unit = encoder
1498					.encode_nv12(&nv12_frame(WIDTH, HEIGHT, step), step == 0)
1499					.expect("encode");
1500				assert_eq!(
1501					nal_types(codec, &unit).contains(&idr_type),
1502					step % 10 == 0,
1503					"{codec:?} frame {step} after the forced keyframe"
1504				);
1505			}
1506		}
1507	}
1508
1509	#[test]
1510	fn the_full_entrypoint_wins_and_low_power_is_the_fallback() {
1511		use VAEntrypoint::{
1512			VAEntrypointEncSlice as Full, VAEntrypointEncSliceLP as LowPower, VAEntrypointVLD as Decode,
1513		};
1514		assert_eq!(pick_entrypoint(&[Decode, LowPower, Full]), Some(Full));
1515		assert_eq!(pick_entrypoint(&[Decode, LowPower]), Some(LowPower));
1516		assert_eq!(pick_entrypoint(&[Decode]), None);
1517	}
1518
1519	/// A buffer the driver refuses leaves the encoder usable, so the caller's
1520	/// CPU fallback can encode the same frame.
1521	#[test]
1522	#[ignore = "requires a VA-API render node and FFmpeg"]
1523	fn a_refused_import_leaves_the_encoder_usable() {
1524		let mut encoder = encoder(config(Codec::H264));
1525		let display = Display::open().expect("no VA-API display");
1526		// A format with no mapping, and a real buffer under a modifier no driver has.
1527		let unmapped = DmaBuf {
1528			drm_format: u32::from_le_bytes(*b"ZZZZ"),
1529			..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1530		};
1531		assert!(encoder.encode_dmabuf(unmapped, true).is_err());
1532		let unknown_modifier = DmaBuf {
1533			modifier: 0x00ff_ffff_ffff_fffe,
1534			..nv12_dmabuf(&display, (WIDTH, HEIGHT), 0)
1535		};
1536		assert!(encoder.encode_dmabuf(unknown_modifier, true).is_err());
1537
1538		let unit = encoder
1539			.encode_nv12(&nv12_frame(WIDTH, HEIGHT, 0), true)
1540			.expect("the CPU path still encodes");
1541		let decoded = ffmpeg_decode(Codec::H264, &unit, "refused");
1542		let psnr = luma_psnr(&nv12_frame(WIDTH, HEIGHT, 0), &decoded, WIDTH, HEIGHT);
1543		assert!(psnr > 35.0, "decoded at {psnr:.1} dB");
1544	}
1545
1546	/// A buffer short of whole coding blocks is not encoded in place: the
1547	/// encoder reads whole blocks, so it goes through the video processor into
1548	/// the padded input surface. That is 1080 rows for H.264, which reads 1088,
1549	/// and 1076 for H.265, whose minimum coding blocks are 8 or 16 rows.
1550	#[test]
1551	#[ignore = "requires a VA-API render node and FFmpeg"]
1552	fn a_buffer_short_of_whole_coding_blocks_is_blitted() {
1553		for (codec, (width, height)) in [(Codec::H264, (1920, 1080)), (Codec::H265, (1920, 1076))] {
1554			let mut encoder = encoder(Config {
1555				width,
1556				height,
1557				bitrate: 4_000_000,
1558				color: Color::infer(height),
1559				..config(codec)
1560			});
1561			let display = Display::open().expect("no VA-API display");
1562			let unit = encoder
1563				.encode_dmabuf(nv12_dmabuf(&display, (width, height), 0), true)
1564				.expect("encode the DMA-BUF");
1565			let decoded = ffmpeg_decode(codec, &unit, "short");
1566			let frame = nv12_frame(width, height, 0);
1567			assert_eq!(decoded.len(), frame.len(), "{codec:?} decoded at another size");
1568			let psnr = luma_psnr(&frame, &decoded, width, height);
1569			assert!(psnr > 35.0, "{codec:?} decoded at {psnr:.1} dB");
1570		}
1571	}
1572
1573	/// A YUV buffer labelled with another color space is converted into the
1574	/// stream's, not relabelled.
1575	#[test]
1576	#[ignore = "requires a VA-API render node and FFmpeg"]
1577	fn a_yuv_dmabuf_in_another_space_is_converted() {
1578		for codec in CODECS {
1579			yuv_dmabuf_in_another_space_is_converted(codec);
1580		}
1581	}
1582
1583	fn yuv_dmabuf_in_another_space_is_converted(codec: Codec) {
1584		let mut encoder = encoder(Config {
1585			color: Color::BT601,
1586			..config(codec)
1587		});
1588		let display = Display::open().expect("no VA-API display");
1589		// Flat red, written in BT.709.
1590		let [y, u, v] = limited([255, 0, 0], Color::BT709).map(|value| value.round() as u8);
1591		let surface = surface_with(
1592			&display,
1593			VA_FOURCC_NV12,
1594			VA_RT_FORMAT_YUV420,
1595			(WIDTH, HEIGHT),
1596			|data, image| {
1597				for row in 0..HEIGHT as usize {
1598					let at = image.offsets[0] as usize + row * image.pitches[0] as usize;
1599					data[at..at + WIDTH as usize].fill(y);
1600				}
1601				for row in 0..HEIGHT as usize / 2 {
1602					let at = image.offsets[1] as usize + row * image.pitches[1] as usize;
1603					for pair in data[at..at + WIDTH as usize].chunks_exact_mut(2) {
1604						pair.copy_from_slice(&[u, v]);
1605					}
1606				}
1607			},
1608		);
1609		let buffer = DmaBuf {
1610			color: Some(Color::BT709),
1611			..DmaBuf::from_prime(surface.export_prime().expect("export")).expect("one object")
1612		};
1613		let unit = encoder.encode_dmabuf(buffer, true).expect("encode");
1614		let decoded = ffmpeg_decode(codec, &unit, "yuv-color");
1615
1616		let (w, h) = (WIDTH as usize, HEIGHT as usize);
1617		let (luma, chroma) = decoded.split_at(w * h);
1618		let actual = [
1619			mean(luma, w, (w / 4, h / 4, w * 3 / 4, h * 3 / 4), 1, 0),
1620			mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 0),
1621			mean(chroma, w, (w / 8, h / 8, w * 3 / 8, h * 3 / 8), 2, 1),
1622		];
1623		let expected = limited([255, 0, 0], Color::BT601);
1624		for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1625			assert!(
1626				(a - e).abs() < 6.0,
1627				"{codec:?} channel {channel}: decoded {a:.1}, expected BT.601 {e:.1}"
1628			);
1629		}
1630	}
1631
1632	/// An NV12 DMA-BUF at the encoder's size is encoded from the producer's memory.
1633	#[test]
1634	#[ignore = "requires a VA-API render node and FFmpeg"]
1635	fn an_nv12_dmabuf_encodes_in_place() {
1636		for codec in CODECS {
1637			let mut encoder = encoder(config(codec));
1638			let display = Display::open().expect("no VA-API display");
1639			let mut stream = Vec::new();
1640			for step in 0..5 {
1641				let buffer = nv12_dmabuf(&display, (WIDTH, HEIGHT), step);
1642				stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1643			}
1644			let decoded = ffmpeg_decode(codec, &stream, "dmabuf");
1645			let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1646			assert_eq!(decoded.len(), 5 * len, "{codec:?}");
1647			for step in 0..5 {
1648				let psnr = luma_psnr(
1649					&nv12_frame(WIDTH, HEIGHT, step),
1650					&decoded[step as usize * len..],
1651					WIDTH,
1652					HEIGHT,
1653				);
1654				assert!(psnr > 35.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1655			}
1656		}
1657	}
1658
1659	/// An NV12 DMA-BUF at another size is scaled to the encoder's on the GPU.
1660	#[test]
1661	#[ignore = "requires a VA-API render node and FFmpeg"]
1662	fn a_dmabuf_at_another_size_is_scaled() {
1663		for codec in CODECS {
1664			dmabuf_at_another_size_is_scaled(codec);
1665		}
1666	}
1667
1668	fn dmabuf_at_another_size_is_scaled(codec: Codec) {
1669		let mut encoder = encoder(config(codec));
1670		let display = Display::open().expect("no VA-API display");
1671		let mut stream = Vec::new();
1672		for step in 0..3 {
1673			let buffer = nv12_dmabuf(&display, (WIDTH * 2, HEIGHT * 2), step);
1674			stream.extend(encoder.encode_dmabuf(buffer, false).expect("encode the DMA-BUF"));
1675		}
1676		let decoded = ffmpeg_decode(codec, &stream, "scaled");
1677		let len = nv12_frame(WIDTH, HEIGHT, 0).len();
1678		assert_eq!(decoded.len(), 3 * len, "{codec:?}: the output is at the encoder's size");
1679		// Compare against the source scaled on the CPU by point sampling, which
1680		// differs from the GPU filter only at edges. 25 dB separates a scale
1681		// from a crop, which scores about 16 dB on this gradient.
1682		for step in 0..3u32 {
1683			let source = nv12_frame(WIDTH * 2, HEIGHT * 2, step);
1684			let mut expected = vec![0u8; (WIDTH * HEIGHT) as usize];
1685			for y in 0..HEIGHT as usize {
1686				for x in 0..WIDTH as usize {
1687					expected[y * WIDTH as usize + x] = source[(y * 2) * (WIDTH as usize * 2) + x * 2];
1688				}
1689			}
1690			let psnr = luma_psnr(&expected, &decoded[step as usize * len..], WIDTH, HEIGHT);
1691			assert!(psnr > 25.0, "{codec:?} picture {step} decoded at {psnr:.1} dB");
1692		}
1693	}
1694
1695	/// A packed RGB DMA-BUF is converted on the GPU into the configured color space.
1696	#[test]
1697	#[ignore = "requires a VA-API render node and FFmpeg"]
1698	fn an_rgb_dmabuf_is_converted_to_the_configured_space() {
1699		// Four flat quadrants, so the check reads colors rather than edges.
1700		const QUADRANTS: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];
1701		for (codec, color) in CODECS
1702			.into_iter()
1703			.flat_map(|codec| [(codec, Color::BT601), (codec, Color::BT709)])
1704		{
1705			let mut encoder = encoder(Config { color, ..config(codec) });
1706			let display = Display::open().expect("no VA-API display");
1707			let surface = surface_with(
1708				&display,
1709				VA_FOURCC_BGRX,
1710				VA_RT_FORMAT_RGB32,
1711				(WIDTH, HEIGHT),
1712				|data, image| {
1713					let pitch = image.pitches[0] as usize;
1714					let offset = image.offsets[0] as usize;
1715					for y in 0..HEIGHT as usize {
1716						for x in 0..WIDTH as usize {
1717							let quadrant = (y >= HEIGHT as usize / 2) as usize * 2 + (x >= WIDTH as usize / 2) as usize;
1718							let [r, g, b] = QUADRANTS[quadrant];
1719							let at = offset + y * pitch + x * 4;
1720							data[at..at + 4].copy_from_slice(&[b, g, r, 255]);
1721						}
1722					}
1723				},
1724			);
1725			let exported = surface.export_prime().expect("export");
1726			let buffer = DmaBuf::from_prime(exported).expect("one object");
1727			assert_eq!(buffer.drm_format, crate::dmabuf::drm::XRGB8888);
1728			let unit = encoder.encode_dmabuf(buffer, false).expect("encode the RGB DMA-BUF");
1729			let decoded = ffmpeg_decode(codec, &unit, "rgb");
1730
1731			let (w, h) = (WIDTH as usize, HEIGHT as usize);
1732			let (luma, chroma) = decoded.split_at(w * h);
1733			for (quadrant, rgb) in QUADRANTS.iter().enumerate() {
1734				let (qx, qy) = (quadrant % 2, quadrant / 2);
1735				// The middle half of each quadrant, clear of the chroma bleed at its edges.
1736				let area = |scale: usize| {
1737					let (qw, qh) = (w / 2 / scale, h / 2 / scale);
1738					(
1739						qx * qw + qw / 4,
1740						qy * qh + qh / 4,
1741						qx * qw + qw * 3 / 4,
1742						qy * qh + qh * 3 / 4,
1743					)
1744				};
1745				let actual = [
1746					mean(luma, w, area(1), 1, 0),
1747					mean(chroma, w, area(2), 2, 0),
1748					mean(chroma, w, area(2), 2, 1),
1749				];
1750				let expected = limited(*rgb, color);
1751				for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
1752					assert!(
1753						(a - e).abs() < 6.0,
1754						"{codec:?} {color:?} quadrant {quadrant} channel {channel}: decoded {a:.1}, expected {e:.1}"
1755					);
1756				}
1757			}
1758		}
1759	}
1760
1761	#[test]
1762	fn the_level_covers_the_frame_size_and_rate() {
1763		assert_eq!(level(320, 240, 30), Level::L4);
1764		assert_eq!(level(1920, 1080, 30), Level::L4);
1765		assert_eq!(level(1920, 1080, 60), Level::L4_2);
1766		assert_eq!(level(2560, 1440, 30), Level::L5);
1767		assert_eq!(level(3840, 2160, 30), Level::L5_1);
1768		assert_eq!(level(3840, 2160, 60), Level::L5_2);
1769	}
1770
1771	/// Returns the limited-range Y'CbCr of an RGB color, per BT.601 or BT.709.
1772	fn limited([r, g, b]: [u8; 3], color: Color) -> [f64; 3] {
1773		let (kr, kb) = match color.matrix {
1774			crate::Matrix::Bt601 => (0.299, 0.114),
1775			crate::Matrix::Bt709 => (0.2126, 0.0722),
1776		};
1777		let (r, g, b) = (r as f64, g as f64, b as f64);
1778		let y = kr * r + (1.0 - kr - kb) * g + kb * b;
1779		[
1780			16.0 + y * 219.0 / 255.0,
1781			128.0 + (b - y) / (2.0 * (1.0 - kb)) * 224.0 / 255.0,
1782			128.0 + (r - y) / (2.0 * (1.0 - kr)) * 224.0 / 255.0,
1783		]
1784	}
1785
1786	/// Lowering the bitrate mid-stream shrinks the pictures without an IDR, and
1787	/// the rate controller holds the stream near each target.
1788	#[test]
1789	#[ignore = "requires a VA-API render node"]
1790	fn a_bitrate_change_takes_effect_without_a_keyframe() {
1791		for codec in CODECS {
1792			bitrate_change_takes_effect_without_a_keyframe(codec);
1793		}
1794	}
1795
1796	fn bitrate_change_takes_effect_without_a_keyframe(codec: Codec) {
1797		let mut encoder = encoder(Config {
1798			gop: NonZeroU32::new(1_000).unwrap(),
1799			..config(codec)
1800		});
1801		let (idr_type, _) = idr_types(codec);
1802		// A zone plate whose phase moves every picture: detail motion
1803		// compensation cannot predict, so 2 Mbps is spent, yet the drivers
1804		// can code it at 250 kbps when the quantizer may go high enough.
1805		let frame = |step: u32| {
1806			let (w, h) = (WIDTH as usize, HEIGHT as usize);
1807			let mut frame = vec![128u8; w * h + w * h.div_ceil(2)];
1808			for y in 0..h {
1809				for x in 0..w {
1810					let (dx, dy) = (x as f64 - w as f64 / 2.0, y as f64 - h as f64 / 2.0);
1811					let phase = (dx * dx + dy * dy) * 0.002 + f64::from(step) * 0.5;
1812					frame[y * w + x] = (128.0 + 100.0 * phase.cos()) as u8;
1813				}
1814			}
1815			frame
1816		};
1817		// The mean picture size over the second half of 60 frames, once the
1818		// rate controller has settled.
1819		// Also asserts that no picture after the first is an IDR.
1820		let average = |encoder: &mut Encoder, from: u32| {
1821			let sizes: Vec<usize> = (from..from + 60)
1822				.map(|step| {
1823					let unit = encoder.encode_nv12(&frame(step), false).expect("encode");
1824					if step > 0 {
1825						assert!(
1826							!nal_types(codec, &unit).contains(&idr_type),
1827							"{codec:?} picture {step} is an IDR"
1828						);
1829					}
1830					unit.len()
1831				})
1832				.collect();
1833			sizes[30..].iter().sum::<usize>() / 30
1834		};
1835
1836		// A settled stream within a quarter above its target; a quantizer
1837		// ceiling the rate controller cannot get past misses by double or more.
1838		let within = |bytes: usize, bitrate: u32| {
1839			let target = bitrate as usize / 8 / 30;
1840			assert!(
1841				bytes * 4 <= target * 5,
1842				"{codec:?} at {bitrate} bps: {bytes} bytes per picture, the target is {target}"
1843			);
1844		};
1845
1846		let high = average(&mut encoder, 0);
1847		within(high, 2_000_000);
1848		encoder.set_bitrate(250_000).expect("set the bitrate");
1849		assert_eq!(encoder.config().bitrate, 250_000);
1850		assert!(encoder.set_bitrate(0).is_err(), "a zero bitrate is refused");
1851		let low = average(&mut encoder, 60);
1852		eprintln!("{codec:?} mean picture at 2 Mbps: {high} bytes, at 250 kbps: {low} bytes");
1853		within(low, 250_000);
1854		assert!(
1855			low * 3 < high,
1856			"{codec:?}: the rate did not drop: {high} -> {low} bytes per picture"
1857		);
1858	}
1859}