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