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