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