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