Skip to main content

kodecs_vaapi/
decode.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 (`decoder/stateless/h264.rs` and
6// `decoder/stateless/h264/vaapi.rs`), itself BSD-3-Clause / Copyright The
7// ChromiumOS Authors. See LICENSE.cros-codecs.
8
9//! Thin VA-API H.264 and H.265 decoder built on the vendored libva binding.
10//!
11//! The mirror of [`crate::encode`]. It parses H.264 parameter sets and slices
12//! with kodecs-h264, and reuses the backend-agnostic layers (`codec::h264`,
13//! `codec::h265`) from discord/cros-codecs (BSD-3-Clause) for H.265 parsing,
14//! reference marking, and DPB bumping, then drives libva directly rather than
15//! vendoring cros-codecs's generic multi-backend decoder framework. The
16//! per-picture and per-slice VA buffer population is ported from cros-codecs's
17//! `decoder/stateless/h264/vaapi.rs` and, in `h265.rs`, from
18//! `decoder/stateless/h265.rs` and `decoder/stateless/h265/vaapi.rs`.
19//!
20//! Feed [`Decoder::decode`] one Annex-B access unit at a time. Its picture is
21//! submitted and completed before the call returns, rather than when the next
22//! unit's first slice arrives, so the hardware is never left holding a
23//! half-submitted picture between calls.
24//!
25//! Output trails input by the reorder depth the SPS declares. H.264 bumps
26//! the DPB when a new picture needs a frame buffer (C.4.5.3), and also lets a
27//! picture out as soon as more pictures wait than the SPS's reorder limit
28//! allows, so a stream that declares no reordering comes out as it decodes
29//! rather than one picture behind. An SPS without `bitstream_restriction`
30//! declares nothing, so E.2.1 infers the DPB size and such a stream still
31//! trails by it. H.265 bumps by the SPS's reorder limit (C.5.2) to the same
32//! effect. A stream with B-frames still holds pictures back, so [`Frame`]
33//! carries the timestamp of the access unit it was coded in, and
34//! [`Decoder::flush`] is what releases the tail at the end of a stream.
35//!
36//! Progressive 8-bit 4:2:0 only: a sequence that is interlaced, deeper than 8
37//! bits, or not 4:2:0 is rejected rather than decoded wrongly. That covers every
38//! stream this crate's encoder, WebRTC, or a browser's `VideoEncoder` produces.
39//! H.265 is the Main profile, with Main 10 and Main Still Picture streams that
40//! hold 8-bit samples decoded the same way. Left and top cropping are rejected;
41//! right and bottom cropping are supported.
42
43use std::io::Cursor;
44use std::path::PathBuf;
45use std::rc::Rc;
46use std::sync::Arc;
47
48use anyhow::{anyhow, bail, Context as _};
49
50use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists};
51use crate::codec::h264::picture::{Field, IsIdr, PictureData, Reference};
52use crate::codec::Codec;
53use crate::pool::{PooledSurface, SurfacePool};
54use crate::{
55	bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields,
56	H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter,
57	PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib,
58	VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
59	VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420,
60	VA_SLICE_DATA_FLAG_ALL,
61};
62use kodecs_h264::{
63	Level, MaxLongTermFrameIdx, Nalu, NaluType, Parser, Pps, Profile, RefPicListModification, Slice, SliceHeader,
64	SliceType, Sps,
65};
66
67mod h265;
68
69/// Decoder configuration.
70#[derive(Clone, Debug)]
71pub struct Config {
72	/// The format to decode, H.264 unless set.
73	pub codec: Codec,
74	/// DRM render node to open (e.g. `/dev/dri/renderD128`).
75	///
76	/// `None`, the default, opens the first node whose driver can decode
77	/// [`codec`](Self::codec).
78	pub device: Option<PathBuf>,
79}
80
81impl Config {
82	/// Returns an H.264 configuration that opens the first render node whose driver can decode it.
83	pub fn new() -> Self {
84		Self {
85			codec: Codec::H264,
86			device: None,
87		}
88	}
89}
90
91impl Default for Config {
92	fn default() -> Self {
93		Self::new()
94	}
95}
96
97/// One decoded picture, downloaded to client memory as tightly packed NV12.
98#[derive(Clone)]
99pub struct Frame {
100	/// Timestamp of the access unit this picture was coded in, as handed to
101	/// [`Decoder::decode`].
102	pub timestamp: u64,
103	/// Visible width in pixels, i.e. after the SPS cropping rectangle.
104	pub width: u32,
105	/// Visible height in pixels.
106	pub height: u32,
107	/// NV12 planes with no row padding: `width * height` luma bytes followed by
108	/// `width * height / 2` interleaved chroma bytes.
109	pub data: Vec<u8>,
110}
111
112/// One decoded picture, left in the surface the hardware wrote it into.
113///
114/// The GPU counterpart of [`Frame`]: same picture, same timestamp, but a DRM
115/// PRIME descriptor for the surface rather than a copy of its pixels. The
116/// descriptor owns the exported file descriptors and the surface travels with
117/// it, so both the allocation and libva's handle on it outlive the decoder.
118///
119/// The export is NV12 in one object holding both planes, which is what the
120/// Intel and AMD drivers produce. Read the modifier off the object before
121/// assuming anything about the layout: a decode target is tiled, and the plane
122/// pitches carry padding the visible size does not imply. That is also why
123/// [`ExportedFrame::download`] goes back through the surface instead of reading
124/// the file descriptor as rows.
125///
126/// Dropping the frame hands its surface back to the decoder, which decodes a
127/// later picture into it. So keep the frame for as long as anything reads the
128/// descriptor or an import of it: a GPU consumer holds it until the work that
129/// samples it has finished, not merely until that work is submitted. A frame
130/// that outlives its decoder, or the sequence it was decoded in, releases its
131/// surface to the driver instead.
132///
133/// This is [`Send`] and [`Sync`] even though [`Decoder`] is neither: a surface
134/// is a display and an id, both of which libva serializes internally, and none
135/// of the decoder's `Rc`s come along.
136pub struct ExportedFrame {
137	/// Timestamp of the access unit this picture was coded in, as handed to
138	/// [`Decoder::decode_exported`].
139	pub timestamp: u64,
140	/// Visible width in pixels, i.e. after the SPS cropping rectangle.
141	pub width: u32,
142	/// Visible height in pixels.
143	pub height: u32,
144	/// The surface's export: format, modifier, and the offset and pitch of each
145	/// plane.
146	pub descriptor: DrmPrimeSurfaceDescriptor,
147	/// The surface the picture was decoded into, held here so the decoder does
148	/// not decode into it again until this drops, and so
149	/// [`ExportedFrame::download`] has something to map.
150	surface: Arc<PooledSurface>,
151}
152
153impl ExportedFrame {
154	/// Exports `surface`, an NV12 picture from somewhere other than the decoder, the way the decoder exports its own.
155	///
156	/// A picture the video processor produced, such as a scaled copy of a
157	/// captured frame, then reaches its consumer with the same descriptor and
158	/// the same [`download`](Self::download) fallback as a decoded one, so one
159	/// consumer handles both. `timestamp` is carried through untouched.
160	///
161	/// # Errors
162	///
163	/// Fails when the surface is not NV12, cannot be synced, or the driver will
164	/// not export it.
165	pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result<Self> {
166		let size = surface.size();
167		Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size)
168	}
169
170	/// Exports `surface`, whose picture is the top-left `width` by `height` of it, copying nothing.
171	///
172	/// The frame holds a reference to the surface, so a pool does not hand it
173	/// out again while the caller holds the descriptor, and
174	/// [`download`](Self::download) can still map it.
175	pub(crate) fn export(
176		surface: Arc<PooledSurface>,
177		timestamp: u64,
178		(width, height): (u32, u32),
179	) -> anyhow::Result<Self> {
180		surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
181		let descriptor = surface
182			.get()
183			.export_prime()
184			.map_err(|e| anyhow!("export the surface: {e:?}"))?;
185		if descriptor.fourcc != VA_FOURCC_NV12 {
186			anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc);
187		}
188		Ok(Self {
189			timestamp,
190			width,
191			height,
192			descriptor,
193			surface,
194		})
195	}
196
197	/// Reads this picture back to client memory as tightly packed NV12.
198	///
199	/// The way back for a caller that took a descriptor and then found itself
200	/// with a consumer that wants bytes. It costs the read [`Decoder::decode`]
201	/// would have done up front, so prefer that entry point when nothing on the
202	/// path draws on the GPU.
203	///
204	/// Same layout as [`Frame::data`], with the driver's row padding dropped.
205	pub fn download(&self) -> anyhow::Result<Frame> {
206		read_back(self.surface.get(), self.timestamp, self.width, self.height)
207	}
208}
209
210impl std::fmt::Debug for ExportedFrame {
211	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212		f.debug_struct("ExportedFrame")
213			.field("timestamp", &self.timestamp)
214			.field("width", &self.width)
215			.field("height", &self.height)
216			.field("fourcc", &self.descriptor.fourcc)
217			.finish()
218	}
219}
220
221impl std::fmt::Debug for Frame {
222	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223		f.debug_struct("Frame")
224			.field("timestamp", &self.timestamp)
225			.field("width", &self.width)
226			.field("height", &self.height)
227			.field("bytes", &self.data.len())
228			.finish()
229	}
230}
231
232/// A VA-API H.264 or H.265 decoder. Built once, fed Annex-B access units, emits NV12.
233///
234/// # Examples
235///
236/// ```no_run
237/// use kodecs_vaapi::decode::{Config, Decoder};
238///
239/// # fn main() -> anyhow::Result<()> {
240/// # let access_units: Vec<Vec<u8>> = Vec::new();
241/// let mut decoder = Decoder::new(Config::new())?;
242/// let mut pictures = Vec::new();
243///
244/// for (index, access_unit) in access_units.iter().enumerate() {
245///     pictures.extend(decoder.decode(access_unit, index as u64)?);
246/// }
247///
248/// // Output trails input, so the tail of the stream only arrives here.
249/// pictures.extend(decoder.flush()?);
250/// # Ok(())
251/// # }
252/// ```
253pub struct Decoder {
254	inner: Inner,
255}
256
257/// The decoder for each format. They share the VA plumbing: [`Sequence`],
258/// [`Handle`], and the read-back and export of a decoded picture.
259enum Inner {
260	H264(H264),
261	H265(h265::Decoder),
262}
263
264/// The H.264 decoder.
265struct H264 {
266	parser: Parser,
267	dpb: Dpb<Handle>,
268	/// Cached variables from the previous reference picture.
269	prev_ref_pic_info: PrevReferencePicInfo,
270	/// Cached variables from the previous picture.
271	prev_pic_info: PrevPicInfo,
272	max_long_term_frame_idx: MaxLongTermFrameIdx,
273	/// VA state for the active sequence, rebuilt when the SPS changes something
274	/// the config, context, or surface pool depends on.
275	sequence: Option<Sequence>,
276	/// Pictures bumped out of the DPB, in output order, awaiting download.
277	ready: Vec<Handle>,
278	/// Drop order: everything above borrows the display.
279	display: Arc<Display>,
280}
281
282impl Decoder {
283	/// Opens [`Config::device`], or the first render node that decodes
284	/// [`Config::codec`], and checks that the driver exposes a decode
285	/// entrypoint for it.
286	///
287	/// The VA config, context, and surface pool are built later, from the first
288	/// SPS, since their profile and size come from the stream. This still fails
289	/// early enough for a caller to fall back to another decoder when libva is
290	/// missing, the node cannot be opened, or the driver does not decode the
291	/// codec. A named node is never swapped for another.
292	pub fn new(config: Config) -> anyhow::Result<Self> {
293		let codec = config.codec;
294		let (device, display) = match config.device {
295			Some(device) => {
296				let display =
297					Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
298				probe(&display, codec)?;
299				(device, display)
300			}
301			None => crate::display::open_first(|display| probe(display, codec))
302				.map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
303		};
304
305		tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
306		let inner = match codec {
307			Codec::H264 => Inner::H264(H264::new(display)),
308			Codec::H265 => Inner::H265(h265::Decoder::new(display)),
309		};
310		Ok(Self { inner })
311	}
312
313	/// Decodes one Annex-B access unit, returning the pictures that came due, in
314	/// output order.
315	///
316	/// `timestamp` is opaque and travels with the picture coded in this access
317	/// unit, so it survives DPB reordering. Parameter sets are read from the
318	/// stream, so an access unit carrying only an SPS and a PPS decodes to no
319	/// frames.
320	pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
321		self.submit(access_unit, timestamp)?;
322		self.take_frames()
323	}
324
325	/// Decodes one Annex-B access unit, leaving the pictures that came due on
326	/// the GPU.
327	///
328	/// The same decode as [`Decoder::decode`], differing only in what the caller
329	/// gets back: a DRM PRIME descriptor for each picture's surface instead of a
330	/// copy of its pixels. For a consumer that draws on the GPU that is the
331	/// whole picture never touching system memory.
332	///
333	/// An exported surface stays out of the recycling pool until the
334	/// [`ExportedFrame`] drops, since the next picture would otherwise be decoded
335	/// over pixels the consumer still holds a descriptor for. A consumer that
336	/// lets each picture go once it has drawn it therefore costs no allocation
337	/// per picture; one that holds on to pictures costs one surface per picture
338	/// held.
339	///
340	/// A consumer that turns out to want bytes after all is not stuck: the
341	/// surface travels with the descriptor, and [`ExportedFrame::download`] reads
342	/// it back.
343	pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
344		self.submit(access_unit, timestamp)?;
345		self.take_exported()
346	}
347
348	/// Decodes one access unit, leaving the pictures that came due in the ready
349	/// queue for whichever of [`Decoder::take_frames`] or
350	/// [`Decoder::take_exported`] the caller asked for.
351	fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
352		let nalus = match &mut self.inner {
353			Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
354			Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
355		};
356
357		// A decoder cannot tell a truncated unit from a complete one, so a
358		// caller that hands us the wrong container gets silence. Say so once per
359		// unit rather than leaving them to wonder where their pictures went.
360		if nalus == 0 && !access_unit.is_empty() {
361			tracing::warn!(
362				"access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
363				access_unit.len()
364			);
365		}
366		Ok(())
367	}
368
369	/// Returns every picture still held in the DPB, in output order.
370	///
371	/// The DPB lets a picture out only when a later one needs it to (C.4.5.3
372	/// for H.264, C.5.2 for H.265), so a stream that simply stops leaves its
373	/// tail sitting there. This releases that tail and empties the DPB, so a
374	/// second call returns nothing.
375	///
376	/// The parsed parameter sets survive, and nothing here waits for an IDR: a
377	/// stream picked up part way through decodes against an empty DPB, which
378	/// gives distorted pictures until its next IDR rather than an error.
379	pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
380		self.reset();
381		self.take_frames()
382	}
383
384	/// [`Decoder::flush`] for a caller taking its pictures on the GPU.
385	pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
386		self.reset();
387		self.take_exported()
388	}
389
390	/// Moves the DPB to the ready queue and forgets the state the next picture
391	/// would otherwise be derived against.
392	fn reset(&mut self) {
393		match &mut self.inner {
394			Inner::H264(decoder) => decoder.reset(),
395			Inner::H265(decoder) => decoder.reset(),
396		}
397	}
398
399	/// The pictures bumped out of the DPB, in output order, awaiting download.
400	fn ready(&mut self) -> &mut Vec<Handle> {
401		match &mut self.inner {
402			Inner::H264(decoder) => &mut decoder.ready,
403			Inner::H265(decoder) => &mut decoder.ready,
404		}
405	}
406
407	/// Downloads every picture waiting in the ready queue.
408	fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
409		std::mem::take(self.ready()).iter().map(download).collect()
410	}
411
412	/// Exports every picture waiting in the ready queue, leaving the pixels
413	/// where the hardware wrote them.
414	fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
415		std::mem::take(self.ready()).iter().map(export).collect()
416	}
417
418	/// The VA state of the active sequence, for tests that look at its pool.
419	#[cfg(test)]
420	fn sequence(&self) -> Option<&Sequence> {
421		match &self.inner {
422			Inner::H264(decoder) => decoder.sequence.as_ref(),
423			Inner::H265(decoder) => decoder.sequence.as_ref(),
424		}
425	}
426}
427
428impl H264 {
429	fn new(display: Arc<Display>) -> Self {
430		Self {
431			parser: Parser::default(),
432			dpb: Dpb::default(),
433			prev_ref_pic_info: PrevReferencePicInfo::default(),
434			prev_pic_info: PrevPicInfo::default(),
435			max_long_term_frame_idx: MaxLongTermFrameIdx::default(),
436			sequence: None,
437			ready: Vec::new(),
438			display,
439		}
440	}
441
442	/// Decodes one access unit into the ready queue, returning how many NAL units it held.
443	fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
444		let mut cursor = Cursor::new(access_unit);
445		let mut current: Option<CurrentPicture> = None;
446		let mut nalus = 0usize;
447
448		// `Nalu::next` reports the end of the buffer as an error, so a truncated
449		// unit is indistinguishable from a complete one and simply stops us.
450		while let Ok(nalu) = Nalu::next(&mut cursor) {
451			nalus += 1;
452			match nalu.header.type_ {
453				NaluType::Sps => {
454					self.parser.parse_sps(&nalu).map_err(|e| anyhow!("parse SPS: {e}"))?;
455				}
456				NaluType::Pps => {
457					self.parser.parse_pps(&nalu).map_err(|e| anyhow!("parse PPS: {e}"))?;
458				}
459				// Data partitions B and C, and the SVC and MVC extensions, carry nothing the base
460				// layer decodes.
461				kind if kind.is_slice() => {
462					let slice = self
463						.parser
464						.parse_slice_header(nalu)
465						.map_err(|e| anyhow!("parse slice header: {e}"))?;
466
467					let mut picture = match current.take() {
468						// An access unit normally holds one picture, but nothing
469						// forces that: `first_mb_in_slice == 0` starts a new one,
470						// so the picture in flight is done.
471						Some(picture) if slice.header.first_mb_in_slice == 0 => {
472							self.finish_picture(picture)?;
473							self.begin_picture(&slice, timestamp)?
474						}
475						Some(picture) => picture,
476						None => self.begin_picture(&slice, timestamp)?,
477					};
478
479					self.decode_slice(&mut picture, &slice)?;
480					current = Some(picture);
481				}
482				other => tracing::trace!("ignoring NAL unit of type {other:?}"),
483			}
484		}
485
486		// Finishing here rather than on the next unit's first slice keeps the
487		// hardware from holding a half-submitted picture between calls.
488		if let Some(picture) = current.take() {
489			self.finish_picture(picture)?;
490		}
491
492		Ok(nalus)
493	}
494
495	/// Moves the DPB to the ready queue and forgets the order count state the
496	/// next picture would otherwise be derived against.
497	fn reset(&mut self) {
498		self.drain();
499		self.prev_ref_pic_info = PrevReferencePicInfo::default();
500		self.prev_pic_info = PrevPicInfo::default();
501		self.max_long_term_frame_idx = MaxLongTermFrameIdx::default();
502	}
503
504	/// Moves everything left in the DPB to the ready queue.
505	fn drain(&mut self) {
506		self.ready.extend(self.dpb.drain().into_iter().flatten());
507	}
508
509	/// Applies `sps` to the DPB limits, rebuilding the VA config, context, and
510	/// surface pool if it changes anything they depend on.
511	fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
512		let info = SequenceInfo::new(sps)?;
513		// C.4.5.3: the DPB limits follow the active SPS whether or not the VA
514		// state has to be rebuilt.
515		self.dpb
516			.set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));
517
518		let format = Format {
519			codec: Codec::H264,
520			profile: va_profile(sps)?,
521			coded: info.coded,
522			visible: info.visible,
523			max_dpb_frames: info.max_dpb_frames,
524		};
525		if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
526			return Ok(());
527		}
528
529		// Surfaces are about to change shape, so let everything decoded against
530		// the old sequence out first. Those handles keep their own surfaces (and
531		// through them the old pool) alive until they are downloaded.
532		self.drain();
533
534		self.sequence = Some(Sequence::new(&self.display, format)?);
535		Ok(())
536	}
537
538	/// Starts a picture: computes its order count, updates the DPB's picture
539	/// numbers, and hands the driver the picture parameters.
540	fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
541		let pps = Arc::clone(
542			self.parser
543				.get_pps(slice.header.pic_parameter_set_id)
544				.context("slice refers to an unknown PPS")?,
545		);
546		let sps = Arc::clone(&pps.sps);
547		self.apply_sps(&sps)?;
548
549		if slice.nalu.header.idr_pic_flag() {
550			self.prev_ref_pic_info.frame_num = 0;
551		}
552
553		let frame_num = u32::from(slice.header.frame_num);
554		if frame_num != self.prev_ref_pic_info.frame_num
555			&& frame_num != (self.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num()
556		{
557			self.handle_frame_num_gap(&sps, frame_num, timestamp)?;
558		}
559
560		let pic = self.init_current_pic(slice, &sps, timestamp)?;
561		let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic);
562
563		// `apply_sps` above either kept the sequence or built a new one.
564		let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
565		let context = Rc::clone(&sequence.context);
566		let handle = sequence.handle(timestamp)?;
567
568		let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
569		let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
570		picture.add_buffer(create_buffer(&context, pic_param)?);
571		picture.add_buffer(create_buffer(&context, build_iq_matrix(&pps))?);
572
573		tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
574		Ok(CurrentPicture {
575			pic,
576			pps,
577			handle,
578			picture,
579			ref_pic_lists,
580		})
581	}
582
583	/// Hands the driver one slice: its parameters, its reference lists, and the
584	/// slice NAL itself.
585	fn decode_slice(&mut self, current: &mut CurrentPicture, slice: &Slice) -> anyhow::Result<()> {
586		// A VA slice parameter carries both of these in 16 bits, so refuse what
587		// would otherwise be truncated into a plausible wrong offset. Only a
588		// picture past 65536 macroblocks, which is beyond 8K, gets close.
589		if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
590			bail!(
591				"slice starts at macroblock {}, past what a VA slice parameter addresses",
592				slice.header.first_mb_in_slice
593			);
594		}
595		if slice.header.header_bit_size > usize::from(u16::MAX) {
596			bail!(
597				"slice header is {} bits long, past what a VA slice parameter addresses",
598				slice.header.header_bit_size
599			);
600		}
601
602		// A slice may refer to a different PPS than the one that started the
603		// picture, as long as it names the same SPS.
604		let pps = Arc::clone(
605			self.parser
606				.get_pps(slice.header.pic_parameter_set_id)
607				.context("slice refers to an unknown PPS")?,
608		);
609		if SequenceInfo::new(&pps.sps)? != SequenceInfo::new(&current.pps.sps)? {
610			bail!("invalid stream: the sequence changed between slices of one picture");
611		}
612		current.pps = Arc::clone(&pps);
613
614		let (list0, list1) = self.create_ref_pic_lists(&current.pic, &slice.header, &current.ref_pic_lists)?;
615		let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
616
617		let slice_param = build_slice_param(&slice.header, slice.nalu.as_ref().len(), &list0, &list1, &pps.sps, &pps);
618		current.picture.add_buffer(create_buffer(context, slice_param)?);
619		current.picture.add_buffer(create_buffer(
620			context,
621			BufferType::SliceData(slice.nalu.as_ref().to_vec()),
622		)?);
623
624		Ok(())
625	}
626
627	/// Submits the picture to the hardware, then runs the reference marking and
628	/// bumping the specification calls for once a picture is decoded.
629	fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
630		let CurrentPicture {
631			mut pic,
632			pps,
633			handle,
634			picture,
635			..
636		} = current;
637
638		run(picture)?;
639		tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
640
641		if pic.is_ref() {
642			self.reference_pic_marking(&mut pic, &pps.sps)?;
643			self.prev_ref_pic_info.fill(&pic);
644		}
645		self.prev_pic_info.fill(&pic);
646
647		// C.4.5.3 clause 3: a picture with memory_management_control_operation
648		// equal to 5 empties the DPB.
649		if pic.has_mmco_5 {
650			self.drain();
651		}
652
653		// C.4.4 and C.4.5: free what the marking released, then store or output.
654		self.dpb
655			.finish_picture(pic, handle, &mut self.ready)
656			.map_err(|e| anyhow!("store picture in DPB: {e}"))?;
657
658		Ok(())
659	}
660
661	/// Builds the picture for `slice` and makes room for it in the DPB.
662	fn init_current_pic(&mut self, slice: &Slice, sps: &Sps, timestamp: u64) -> anyhow::Result<PictureData> {
663		// Progressive only, so a picture is never the second field of a frame.
664		let mut pic = PictureData::new_from_slice(slice, sps, timestamp, None);
665		self.compute_pic_order_count(&mut pic, sps)?;
666
667		if matches!(pic.is_idr, IsIdr::Yes { .. }) {
668			// C.4.5.3 clause 2: an IDR bumps the whole DPB, unless
669			// no_output_of_prior_pics_flag says to discard it instead (C.4.4).
670			if pic.ref_pic_marking.no_output_of_prior_pics_flag {
671				self.dpb.clear();
672			} else {
673				self.drain();
674			}
675		}
676
677		self.dpb
678			.update_pic_nums(u32::from(slice.header.frame_num), sps.max_frame_num(), &pic);
679
680		Ok(pic)
681	}
682
683	/// 8.2.5.2: invents the pictures for the frame numbers a lossy stream skipped,
684	/// so reference marking keeps working.
685	fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32, timestamp: u64) -> anyhow::Result<()> {
686		if self.dpb.is_empty() {
687			return Ok(());
688		}
689
690		if !sps.gaps_in_frame_num_value_allowed_flag {
691			bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
692		}
693		tracing::debug!("frame_num gap up to {frame_num}");
694
695		let max_frame_num = sps.max_frame_num();
696		let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
697		while unused != frame_num {
698			let mut pic = PictureData::new_non_existing(unused, timestamp);
699			self.compute_pic_order_count(&mut pic, sps)?;
700
701			self.dpb.update_pic_nums(unused, max_frame_num, &pic);
702			self.dpb.sliding_window_marking(&mut pic, sps);
703			self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
704			self.dpb
705				.store_picture(pic.into_rc(), None)
706				.map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
707
708			unused = (unused + 1) % max_frame_num;
709		}
710
711		Ok(())
712	}
713
714	/// 8.2.1: derives the picture order count, which drives output ordering.
715	fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
716		pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
717	}
718
719	/// 8.2.5.1: marks the decoded picture as used or unused for reference.
720	fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
721		if matches!(pic.is_idr, IsIdr::Yes { .. }) {
722			self.dpb.mark_all_as_unused_for_ref();
723
724			if pic.ref_pic_marking.long_term_reference_flag {
725				pic.set_reference(Reference::LongTerm, false);
726				pic.long_term_frame_idx = 0;
727				self.max_long_term_frame_idx = MaxLongTermFrameIdx::Idx(0);
728			} else {
729				pic.set_reference(Reference::ShortTerm, false);
730				self.max_long_term_frame_idx = MaxLongTermFrameIdx::NoLongTermFrameIndices;
731			}
732
733			return Ok(());
734		}
735
736		if pic.ref_pic_marking.adaptive_ref_pic_marking_mode_flag {
737			self.handle_memory_management_ops(pic)?;
738		} else {
739			self.dpb.sliding_window_marking(pic, sps);
740		}
741
742		Ok(())
743	}
744
745	/// 8.2.5.4: runs the picture's adaptive memory management control operations.
746	fn handle_memory_management_ops(&mut self, pic: &mut PictureData) -> Result<(), MmcoError> {
747		let markings = pic.ref_pic_marking.clone();
748
749		for marking in &markings.inner {
750			match marking.memory_management_control_operation {
751				0 => break,
752				1 => self.dpb.mmco_op_1(pic, marking)?,
753				2 => self.dpb.mmco_op_2(pic, marking)?,
754				3 => self.dpb.mmco_op_3(pic, marking)?,
755				4 => self.max_long_term_frame_idx = self.dpb.mmco_op_4(marking),
756				5 => self.max_long_term_frame_idx = self.dpb.mmco_op_5(pic),
757				6 => self.dpb.mmco_op_6(pic, marking),
758				other => return Err(MmcoError::UnknownMmco(other)),
759			}
760		}
761
762		Ok(())
763	}
764
765	/// 8.2.4: derives RefPicList0 and RefPicList1 for one slice, from the
766	/// per-picture lists the DPB built.
767	fn create_ref_pic_lists<'a>(
768		&'a self,
769		pic: &PictureData,
770		hdr: &SliceHeader,
771		lists: &ReferencePicLists,
772	) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
773		let list0 = match hdr.slice_type {
774			SliceType::P | SliceType::Sp => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0)?,
775			SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0)?,
776			_ => Vec::new(),
777		};
778
779		let list1 = match hdr.slice_type {
780			SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1)?,
781			_ => Vec::new(),
782		};
783
784		Ok((list0, list1))
785	}
786
787	/// 8.2.4.3: applies the slice header's reference picture list modifications.
788	fn modify_ref_pic_list<'a>(
789		&'a self,
790		pic: &PictureData,
791		hdr: &SliceHeader,
792		list1: bool,
793		indices: &[usize],
794	) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
795		let (modify, num_ref_idx_active_minus1, modifications) = if list1 {
796			(
797				hdr.ref_pic_list_modification_flag_l1,
798				hdr.num_ref_idx_l1_active_minus1,
799				&hdr.ref_pic_list_modification_l1,
800			)
801		} else {
802			(
803				hdr.ref_pic_list_modification_flag_l0,
804				hdr.num_ref_idx_l0_active_minus1,
805				&hdr.ref_pic_list_modification_l0,
806			)
807		};
808
809		let mut list: DpbPicRefList<'a, Handle> = indices
810			.iter()
811			.map(|&i| &self.dpb.entries()[i])
812			.take(usize::from(num_ref_idx_active_minus1) + 1)
813			.collect();
814
815		if !modify {
816			return Ok(list);
817		}
818
819		let mut pic_num_pred = pic.pic_num;
820		let mut ref_idx = 0;
821
822		for modification in modifications {
823			match modification.modification_of_pic_nums_idc {
824				idc @ (0 | 1) => self.short_term_modification(
825					pic,
826					&mut list,
827					num_ref_idx_active_minus1,
828					hdr.max_pic_num as i32,
829					idc,
830					modification,
831					&mut pic_num_pred,
832					&mut ref_idx,
833				)?,
834				2 => self.long_term_modification(&mut list, num_ref_idx_active_minus1, modification, &mut ref_idx)?,
835				3 => break,
836				other => bail!("unexpected modification_of_pic_nums_idc {other}"),
837			}
838		}
839
840		Ok(list)
841	}
842
843	/// 8.2.4.3.1: modification for short-term reference pictures.
844	fn short_term_modification<'a>(
845		&'a self,
846		pic: &PictureData,
847		list: &mut DpbPicRefList<'a, Handle>,
848		num_ref_idx_active_minus1: u8,
849		max_pic_num: i32,
850		idc: u8,
851		modification: &RefPicListModification,
852		pic_num_pred: &mut i32,
853		ref_idx: &mut usize,
854	) -> anyhow::Result<()> {
855		if modification.abs_diff_pic_num_minus1 >= max_pic_num as u32 {
856			bail!("short-term picture number difference exceeds MaxPicNum");
857		}
858		let abs_diff_pic_num = modification.abs_diff_pic_num_minus1 as i32 + 1;
859
860		let pic_num_no_wrap = if idc == 0 {
861			if *pic_num_pred - abs_diff_pic_num < 0 {
862				*pic_num_pred - abs_diff_pic_num + max_pic_num
863			} else {
864				*pic_num_pred - abs_diff_pic_num
865			}
866		} else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
867			*pic_num_pred + abs_diff_pic_num - max_pic_num
868		} else {
869			*pic_num_pred + abs_diff_pic_num
870		};
871
872		*pic_num_pred = pic_num_no_wrap;
873
874		let pic_num = if pic_num_no_wrap > pic.pic_num {
875			pic_num_no_wrap - max_pic_num
876		} else {
877			pic_num_no_wrap
878		};
879
880		let entry = self
881			.dpb
882			.find_short_term_with_pic_num(pic_num)
883			.with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
884
885		Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| {
886			target.pic_num_f(max_pic_num) != pic_num
887		});
888
889		Ok(())
890	}
891
892	/// 8.2.4.3.2: modification for long-term reference pictures.
893	fn long_term_modification<'a>(
894		&'a self,
895		list: &mut DpbPicRefList<'a, Handle>,
896		num_ref_idx_active_minus1: u8,
897		modification: &RefPicListModification,
898		ref_idx: &mut usize,
899	) -> anyhow::Result<()> {
900		let long_term_pic_num = modification.long_term_pic_num;
901		let max_long_term_frame_idx = self.max_long_term_frame_idx;
902
903		let entry = self
904			.dpb
905			.find_long_term_with_long_term_pic_num(long_term_pic_num)
906			.with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
907
908		Self::insert_modification(list, entry, num_ref_idx_active_minus1, ref_idx, |target| {
909			target.long_term_pic_num_f(max_long_term_frame_idx) != u64::from(long_term_pic_num)
910		});
911
912		Ok(())
913	}
914
915	/// The shared tail of 8.2.4.3.1 and 8.2.4.3.2: insert `entry` at `ref_idx`,
916	/// then shuffle out the duplicate `keep` identifies and re-truncate the list.
917	fn insert_modification<'a>(
918		list: &mut DpbPicRefList<'a, Handle>,
919		entry: &'a DpbEntry<Handle>,
920		num_ref_idx_active_minus1: u8,
921		ref_idx: &mut usize,
922		keep: impl Fn(&PictureData) -> bool,
923	) {
924		// A modification past the end of the list is a stream error; the spec
925		// only defines indices within num_ref_idx_lX_active_minus1 + 1.
926		let at = (*ref_idx).min(list.len());
927		list.insert(at, entry);
928		*ref_idx = at + 1;
929
930		let mut next = *ref_idx;
931		for current in *ref_idx..=usize::from(num_ref_idx_active_minus1) + 1 {
932			if current >= list.len() {
933				break;
934			}
935
936			if keep(&list[current].pic.borrow()) {
937				list[next] = list[current];
938				next += 1;
939			}
940		}
941
942		list.truncate(usize::from(num_ref_idx_active_minus1) + 1);
943	}
944}
945
946/// The picture currently being assembled, held across the slices that make it up.
947struct CurrentPicture {
948	pic: PictureData,
949	/// PPS active for the last slice seen.
950	pps: Arc<Pps>,
951	/// Handle to the surface the driver renders into.
952	handle: Handle,
953	picture: Picture<crate::PictureNew, Handle>,
954	/// Per-picture reference lists, modified per slice.
955	ref_pic_lists: ReferencePicLists,
956}
957
958/// A decoded picture: the surface holding it plus what the caller needs to read
959/// it back. Cloned into the DPB, so the surface is not recycled while it is still
960/// a reference or still waiting to be output.
961#[derive(Clone)]
962struct Handle {
963	surface: Arc<PooledSurface>,
964	timestamp: u64,
965	width: u32,
966	height: u32,
967}
968
969impl std::borrow::Borrow<Surface<()>> for Handle {
970	fn borrow(&self) -> &Surface<()> {
971		self.surface.get()
972	}
973}
974
975/// The properties of an SPS that the VA config, context, and surface pool are
976/// built from. A change in any of them forces them to be rebuilt.
977#[derive(Clone, Debug, PartialEq, Eq)]
978struct SequenceInfo {
979	visible: (u32, u32),
980	coded: (u32, u32),
981	profile_idc: u8,
982	bit_depth_luma_minus8: u8,
983	bit_depth_chroma_minus8: u8,
984	chroma_format_idc: u8,
985	frame_mbs_only_flag: bool,
986	max_dpb_frames: usize,
987}
988
989impl SequenceInfo {
990	fn new(sps: &Sps) -> anyhow::Result<Self> {
991		if !sps.frame_mbs_only_flag {
992			bail!("interlaced H.264 is not supported");
993		}
994		if sps.chroma_format_idc != 1 {
995			bail!(
996				"only 4:2:0 chroma is supported, got chroma_format_idc {}",
997				sps.chroma_format_idc
998			);
999		}
1000		if sps.bit_depth_luma_minus8 != 0 || sps.bit_depth_chroma_minus8 != 0 {
1001			bail!(
1002				"only 8-bit samples are supported, got {}-bit luma and {}-bit chroma",
1003				sps.bit_depth_luma_minus8 + 8,
1004				sps.bit_depth_chroma_minus8 + 8
1005			);
1006		}
1007
1008		if sps.frame_cropping_flag && (sps.frame_crop_left_offset != 0 || sps.frame_crop_top_offset != 0) {
1009			bail!("left and top H.264 cropping is not supported");
1010		}
1011		let (crop_right, crop_bottom) = if sps.frame_cropping_flag {
1012			(sps.frame_crop_right_offset, sps.frame_crop_bottom_offset)
1013		} else {
1014			(0, 0)
1015		};
1016		let width = crop_right
1017			.checked_mul(2)
1018			.and_then(|crop| sps.width().checked_sub(crop))
1019			.context("invalid horizontal H.264 crop")?;
1020		let height = crop_bottom
1021			.checked_mul(2)
1022			.and_then(|crop| sps.height().checked_sub(crop))
1023			.context("invalid vertical H.264 crop")?;
1024		if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 {
1025			bail!("visible size {width}x{height} is not a non-zero even 4:2:0 size");
1026		}
1027
1028		Ok(Self {
1029			visible: (width, height),
1030			coded: (sps.width(), sps.height()),
1031			profile_idc: sps.profile_idc,
1032			bit_depth_luma_minus8: sps.bit_depth_luma_minus8,
1033			bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8,
1034			chroma_format_idc: sps.chroma_format_idc,
1035			frame_mbs_only_flag: sps.frame_mbs_only_flag,
1036			max_dpb_frames: sps.max_dpb_frames().context("unknown H.264 level_idc")?,
1037		})
1038	}
1039}
1040
1041/// What the VA config, context, and surface pool of a sequence are built for.
1042/// A change in any of it rebuilds them.
1043#[derive(Clone, Debug, PartialEq, Eq)]
1044struct Format {
1045	codec: Codec,
1046	profile: VAProfile::Type,
1047	coded: (u32, u32),
1048	/// The size after cropping, which is what a [`Frame`] reports.
1049	visible: (u32, u32),
1050	/// The most pictures the DPB holds, which bounds what the pool keeps free.
1051	max_dpb_frames: usize,
1052}
1053
1054/// The VA state for one coded video sequence.
1055struct Sequence {
1056	format: Format,
1057	pool: SurfacePool,
1058	// Drop order: the context must go before the config it was created from.
1059	context: Rc<Context>,
1060	_config: VaConfig,
1061}
1062
1063impl Sequence {
1064	fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
1065		let attrs = vec![VAConfigAttrib {
1066			type_: VAConfigAttribType::VAConfigAttribRTFormat,
1067			value: VA_RT_FORMAT_YUV420,
1068		}];
1069		let config = display
1070			.create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
1071			.map_err(|e| anyhow!("create VA config: {e:?}"))?;
1072
1073		let (coded_width, coded_height) = format.coded;
1074		let context = display
1075			.create_context::<()>(&config, coded_width, coded_height, None, true)
1076			.map_err(|e| anyhow!("create VA context: {e:?}"))?;
1077
1078		let (width, height) = format.visible;
1079		tracing::info!(
1080			"VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
1081			 VA profile {}, DPB {} frames",
1082			format.codec,
1083			format.profile,
1084			format.max_dpb_frames
1085		);
1086
1087		// What the decoder itself can need at once: a full DPB plus the picture
1088		// being decoded. Anything free beyond that was let go by a consumer that
1089		// had been holding pictures, and is memory the stream will not ask for
1090		// again.
1091		let capacity = format.max_dpb_frames + 1;
1092		Ok(Self {
1093			pool: SurfacePool::new(
1094				display,
1095				(coded_width, coded_height),
1096				UsageHint::USAGE_HINT_DECODER,
1097				capacity,
1098			),
1099			format,
1100			context,
1101			_config: config,
1102		})
1103	}
1104
1105	/// Returns a surface to decode a picture coded at `timestamp` into.
1106	fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
1107		let (width, height) = self.format.visible;
1108		Ok(Handle {
1109			surface: Arc::new(self.pool.alloc()?),
1110			timestamp,
1111			width,
1112			height,
1113		})
1114	}
1115}
1116
1117/// Submits a picture with all its buffers added, and waits for it to decode.
1118///
1119/// The wait comes before the surface enters the DPB: it is about to be read as
1120/// a reference by later pictures, and the caller may never ask for its pixels.
1121/// Dropping the synced picture frees the VA buffers with it.
1122fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
1123	let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
1124	let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
1125	let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
1126	drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
1127	Ok(())
1128}
1129
1130/// Returns how many H.264 frames may wait for output before the one with the
1131/// lowest order count is due.
1132///
1133/// The VUI's `max_num_reorder_frames` when the SPS carries it, else the
1134/// inference E.2.1 makes from the profile, which is the DPB size for most
1135/// streams. An order count derived from `frame_num` (8.2.1.3) makes output
1136/// order decoding order, so such a stream reorders nothing whatever its VUI
1137/// says. A limit past the DPB size is out of range, and the DPB size bounds it.
1138fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
1139	if sps.pic_order_cnt_type == 2 {
1140		return 0;
1141	}
1142	// The inference without a VUI limit is the DPB size.
1143	sps.max_num_reorder_frames()
1144		.map_or(max_dpb_frames, |frames| frames as usize)
1145		.min(max_dpb_frames)
1146}
1147
1148/// Exports a decoded surface as a DRM PRIME descriptor, copying nothing.
1149fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
1150	ExportedFrame::export(
1151		Arc::clone(&handle.surface),
1152		handle.timestamp,
1153		(handle.width, handle.height),
1154	)
1155}
1156
1157/// Reads a decoded surface back to client memory as tightly packed NV12.
1158fn download(handle: &Handle) -> anyhow::Result<Frame> {
1159	read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
1160}
1161
1162/// Reads `surface` back to client memory as tightly packed NV12, cropped to
1163/// `width` by `height`.
1164///
1165/// The one read-back path, shared by the picture a decoder downloads itself and
1166/// the one a caller took as a descriptor and later wants on the CPU after all.
1167fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
1168	surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
1169
1170	let visible = (width, height);
1171
1172	// vaDeriveImage exposes the surface's own buffer, so the copy below is the
1173	// only one. Not every driver can derive every surface; fall back to
1174	// vaCreateImage + vaGetImage, which always works but copies inside the driver
1175	// first.
1176	// Safe since a decoded surface is written again only once the pool hands it
1177	// out, after every handle and export of it has dropped, and the caller holds one.
1178	match unsafe { Image::derive_shared(surface, visible) } {
1179		Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
1180			return pack_nv12(&image, timestamp, width, height);
1181		}
1182		Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
1183		Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
1184	}
1185
1186	let format = surface
1187		.display()
1188		.query_image_formats()
1189		.map_err(|e| anyhow!("query image formats: {e:?}"))?
1190		.into_iter()
1191		.find(|format| format.fourcc == VA_FOURCC_NV12)
1192		.context("driver has no NV12 image format")?;
1193	let image = Image::create_from(surface, format, surface.size(), visible)
1194		.map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
1195
1196	pack_nv12(&image, timestamp, width, height)
1197}
1198
1199/// Copies a mapped NV12 image into a tightly packed buffer, dropping the row
1200/// padding the driver's pitch may carry.
1201fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
1202	let va_image = image.image();
1203	let src: &[u8] = image.as_ref();
1204	let (width, height) = (frame_width as usize, frame_height as usize);
1205	let chroma_rows = height / 2;
1206
1207	let mut data = vec![0u8; width * (height + chroma_rows)];
1208	let (luma, chroma) = data.split_at_mut(width * height);
1209	copy_plane(
1210		luma,
1211		src,
1212		va_image.offsets[0] as usize,
1213		va_image.pitches[0] as usize,
1214		width,
1215		height,
1216	)?;
1217	copy_plane(
1218		chroma,
1219		src,
1220		va_image.offsets[1] as usize,
1221		va_image.pitches[1] as usize,
1222		width,
1223		chroma_rows,
1224	)?;
1225
1226	Ok(Frame {
1227		timestamp,
1228		width: frame_width,
1229		height: frame_height,
1230		data,
1231	})
1232}
1233
1234/// Copies `rows` rows of `width` bytes out of a strided plane.
1235fn copy_plane(
1236	dst: &mut [u8],
1237	src: &[u8],
1238	offset: usize,
1239	pitch: usize,
1240	width: usize,
1241	rows: usize,
1242) -> anyhow::Result<()> {
1243	if rows == 0 {
1244		return Ok(());
1245	}
1246	let end = offset + pitch * (rows - 1) + width;
1247	if pitch < width || src.len() < end {
1248		bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
1249	}
1250
1251	for row in 0..rows {
1252		let from = offset + row * pitch;
1253		dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
1254	}
1255
1256	Ok(())
1257}
1258
1259/// Checks that `display`'s driver can decode `codec`, which is what [`Decoder::new`] needs of a render node.
1260///
1261/// # Errors
1262///
1263/// Fails unless the driver offers `VAEntrypointVLD` for a Constrained
1264/// Baseline, Main, or High profile (H.264) or for the Main profile (H.265),
1265/// or when it cannot be asked.
1266pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
1267	let profiles = display
1268		.query_config_profiles()
1269		.map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
1270
1271	let supported = profiles
1272		.into_iter()
1273		.filter(|profile| match codec {
1274			Codec::H264 => matches!(
1275				*profile,
1276				VAProfile::VAProfileH264ConstrainedBaseline
1277					| VAProfile::VAProfileH264Main
1278					| VAProfile::VAProfileH264High
1279			),
1280			Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
1281		})
1282		.any(|profile| {
1283			display
1284				.query_config_entrypoints(profile)
1285				.is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
1286		});
1287
1288	if !supported {
1289		bail!("driver exposes no {codec:?} decode entrypoint");
1290	}
1291
1292	Ok(())
1293}
1294
1295/// Maps the SPS profile onto the VA profile to open the config with.
1296fn va_profile(sps: &Sps) -> anyhow::Result<VAProfile::Type> {
1297	let profile = Profile::try_from(sps.profile_idc).map_err(|e| anyhow!("{e}"))?;
1298
1299	Ok(match profile {
1300		// VA-API has no plain Baseline profile, and the picture parameter buffer
1301		// has no way to describe the FMO and ASO tools that are all that separate
1302		// it from Constrained Baseline (num_slice_groups_minus1 is pinned to 0
1303		// below), so both map here. A stream that really uses them decodes wrong
1304		// rather than not at all, which no encoder in this decade emits.
1305		Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
1306		Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
1307		// The bit depth and chroma format are checked separately, so a High10 or
1308		// High422 SPS only reaches here when its samples are 8-bit 4:2:0.
1309		Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
1310		other => bail!("unsupported H.264 profile {other:?}"),
1311	})
1312}
1313
1314fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
1315	context
1316		.create_buffer(buffer)
1317		.map_err(|e| anyhow!("create VA buffer: {e:?}"))
1318}
1319
1320/// The first frame_num 8.2.5.2 invents a picture for, before `frame_num`.
1321///
1322/// Sliding-window marking keeps only the last `max_num_ref_frames` of the
1323/// invented pictures, so inventing the earlier ones would change nothing but the
1324/// work a lossy or hostile stream costs: up to MaxFrameNum pictures per slice.
1325fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
1326	let max_frame_num = sps.max_frame_num();
1327	let first = (prev_frame_num + 1) % max_frame_num;
1328	let missing = (frame_num + max_frame_num - first) % max_frame_num;
1329	// Marking keeps one reference even when the SPS declares none.
1330	let window = u32::from(sps.max_num_ref_frames).max(1);
1331	let skipped = missing.saturating_sub(window);
1332	(first + skipped) % max_frame_num
1333}
1334
1335/// 8.2.1: derives `pic`'s picture order count, which drives output ordering.
1336///
1337/// Fails a picture whose order count leaves the `i32` range the
1338/// specification bounds it to, as a hostile stream's can. The specification
1339/// bounds only the final counts, so the sums on the way are taken wider.
1340fn pic_order_count(
1341	prev_ref: &PrevReferencePicInfo,
1342	prev: &mut PrevPicInfo,
1343	pic: &mut PictureData,
1344	sps: &Sps,
1345) -> anyhow::Result<()> {
1346	let overflow = || anyhow!("picture order count overflows");
1347	match pic.pic_order_cnt_type {
1348		// 8.2.1.1
1349		0 => {
1350			let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1351				(0, 0)
1352			} else if prev_ref.has_mmco_5 {
1353				if matches!(prev_ref.field, Field::Bottom) {
1354					(0, 0)
1355				} else {
1356					(0, prev_ref.top_field_order_cnt)
1357				}
1358			} else {
1359				(prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
1360			};
1361
1362			let max_pic_order_cnt_lsb: i32 = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
1363			// Both are below 2^16, except a previous top field order count
1364			// after a memory_management_control_operation 5, which is any `i32`.
1365			let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
1366			let half = i64::from(max_pic_order_cnt_lsb / 2);
1367
1368			pic.pic_order_cnt_msb = if lsb_delta >= half {
1369				prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
1370			} else if -lsb_delta > half {
1371				prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
1372			} else {
1373				Some(prev_pic_order_cnt_msb)
1374			}
1375			.ok_or_else(overflow)?;
1376
1377			if !matches!(pic.field, Field::Bottom) {
1378				pic.top_field_order_cnt = pic
1379					.pic_order_cnt_msb
1380					.checked_add(pic.pic_order_cnt_lsb)
1381					.ok_or_else(overflow)?;
1382			}
1383
1384			if !matches!(pic.field, Field::Top) {
1385				pic.bottom_field_order_cnt = if matches!(pic.field, Field::Frame) {
1386					pic.top_field_order_cnt.checked_add(pic.delta_pic_order_cnt_bottom)
1387				} else {
1388					pic.pic_order_cnt_msb.checked_add(pic.pic_order_cnt_lsb)
1389				}
1390				.ok_or_else(overflow)?;
1391			}
1392		}
1393
1394		// 8.2.1.2
1395		1 => {
1396			if prev.has_mmco_5 {
1397				prev.frame_num_offset = 0;
1398			}
1399
1400			pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1401
1402			let mut abs_frame_num = if sps.num_ref_frames_in_pic_order_cnt_cycle != 0 {
1403				pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
1404			} else {
1405				0
1406			};
1407
1408			if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
1409				abs_frame_num -= 1;
1410			}
1411
1412			// Never overflows: under 2^32 cycles of a cycle sum under 2^39,
1413			// plus a few hundred `i32` terms, stays far inside `i128`.
1414			let mut expected_pic_order_cnt: i128 = 0;
1415
1416			if abs_frame_num > 0 {
1417				if sps.num_ref_frames_in_pic_order_cnt_cycle == 0 {
1418					bail!("invalid num_ref_frames_in_pic_order_cnt_cycle");
1419				}
1420
1421				let cycle_len = u32::from(sps.num_ref_frames_in_pic_order_cnt_cycle);
1422				let cycles = (abs_frame_num - 1) / cycle_len;
1423				// The cycle is only summed up to the position this frame sits
1424				// at within it, not all the way round.
1425				let position_in_cycle = (abs_frame_num - 1) % cycle_len;
1426				expected_pic_order_cnt = i128::from(cycles) * i128::from(sps.expected_delta_per_pic_order_cnt_cycle);
1427
1428				for i in 0..=position_in_cycle {
1429					expected_pic_order_cnt += i128::from(sps.offset_for_ref_frame[i as usize]);
1430				}
1431			}
1432
1433			if pic.nal_ref_idc == 0 {
1434				expected_pic_order_cnt += i128::from(sps.offset_for_non_ref_pic);
1435			}
1436
1437			let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
1438			let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
1439			let to_bottom = i128::from(sps.offset_for_top_to_bottom_field);
1440			match pic.field {
1441				Field::Frame => {
1442					pic.top_field_order_cnt = count(top)?;
1443					pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
1444				}
1445				Field::Top => {
1446					pic.top_field_order_cnt = count(top)?;
1447				}
1448				Field::Bottom => {
1449					pic.bottom_field_order_cnt = count(top + to_bottom)?;
1450				}
1451			}
1452		}
1453
1454		// 8.2.1.3
1455		2 => {
1456			if prev.has_mmco_5 {
1457				prev.frame_num_offset = 0;
1458			}
1459
1460			pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
1461
1462			let pic_order_cnt = if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1463				0
1464			} else {
1465				let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
1466				i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
1467			};
1468
1469			if matches!(pic.field, Field::Frame | Field::Top) {
1470				pic.top_field_order_cnt = pic_order_cnt;
1471			}
1472			if matches!(pic.field, Field::Frame | Field::Bottom) {
1473				pic.bottom_field_order_cnt = pic_order_cnt;
1474			}
1475		}
1476
1477		other => bail!("invalid pic_order_cnt_type {other}"),
1478	}
1479
1480	pic.pic_order_cnt = match pic.field {
1481		Field::Frame => std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt),
1482		Field::Top => pic.top_field_order_cnt,
1483		Field::Bottom => pic.bottom_field_order_cnt,
1484	};
1485
1486	Ok(())
1487}
1488
1489/// 8-6 and 8-11: the FrameNumOffset of `pic`, which grows by MaxFrameNum each
1490/// time frame_num wraps without an IDR.
1491fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
1492	Ok(if matches!(pic.is_idr, IsIdr::Yes { .. }) {
1493		0
1494	} else if prev.frame_num > pic.frame_num {
1495		prev.frame_num_offset
1496			.checked_add(sps.max_frame_num())
1497			.context("FrameNumOffset overflows")?
1498	} else {
1499		prev.frame_num_offset
1500	})
1501}
1502
1503/// Cached variables from the previous reference picture, needed by 8.2.1.
1504#[derive(Debug)]
1505struct PrevReferencePicInfo {
1506	frame_num: u32,
1507	has_mmco_5: bool,
1508	top_field_order_cnt: i32,
1509	pic_order_cnt_msb: i32,
1510	pic_order_cnt_lsb: i32,
1511	field: Field,
1512}
1513
1514impl Default for PrevReferencePicInfo {
1515	fn default() -> Self {
1516		Self {
1517			frame_num: 0,
1518			has_mmco_5: false,
1519			top_field_order_cnt: 0,
1520			pic_order_cnt_msb: 0,
1521			pic_order_cnt_lsb: 0,
1522			field: Field::Frame,
1523		}
1524	}
1525}
1526
1527impl PrevReferencePicInfo {
1528	fn fill(&mut self, pic: &PictureData) {
1529		self.has_mmco_5 = pic.has_mmco_5;
1530		self.top_field_order_cnt = pic.top_field_order_cnt;
1531		self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
1532		self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
1533		self.field = pic.field;
1534		self.frame_num = pic.frame_num;
1535	}
1536}
1537
1538/// Cached variables from the previous picture, needed by 8.2.1.
1539#[derive(Debug, Default)]
1540struct PrevPicInfo {
1541	frame_num: u32,
1542	frame_num_offset: u32,
1543	has_mmco_5: bool,
1544}
1545
1546impl PrevPicInfo {
1547	fn fill(&mut self, pic: &PictureData) {
1548		self.frame_num = pic.frame_num;
1549		self.has_mmco_5 = pic.has_mmco_5;
1550		self.frame_num_offset = pic.frame_num_offset;
1551	}
1552}
1553
1554/// The surface a DPB entry decoded into, or `VA_INVALID_ID` for the non-existing
1555/// pictures invented for a frame_num gap.
1556fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
1557	match handle {
1558		Some(handle) => handle.surface.id(),
1559		None => VA_INVALID_ID,
1560	}
1561}
1562
1563/// Ported from cros-codecs `fill_va_h264_pic` (BSD-3-Clause). Progressive only,
1564/// so the field cases collapse to the frame one.
1565fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
1566	let mut flags = 0;
1567	let frame_idx = match pic.reference() {
1568		Reference::LongTerm => {
1569			flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
1570			pic.long_term_frame_idx
1571		}
1572		Reference::ShortTerm => {
1573			flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1574			pic.frame_num
1575		}
1576		Reference::None => pic.frame_num,
1577	};
1578
1579	PictureH264::new(
1580		surface_id,
1581		frame_idx,
1582		flags,
1583		pic.top_field_order_cnt,
1584		pic.bottom_field_order_cnt,
1585	)
1586}
1587
1588/// Builds the picture used to fill the array slots there is no reference for.
1589fn build_invalid_va_h264_pic() -> PictureH264 {
1590	PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
1591}
1592
1593/// Ported from cros-codecs `build_iq_matrix` (BSD-3-Clause). VA-API wants the
1594/// scaling lists in raster order, the PPS carries them zig-zag.
1595fn build_iq_matrix(pps: &Pps) -> BufferType {
1596	const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
1597	#[rustfmt::skip]
1598	const ZIGZAG_8X8: [usize; 64] = [
1599		0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
1600		20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
1601		58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
1602	];
1603
1604	let mut scaling_list4x4 = [[0u8; 16]; 6];
1605	for (list, src) in scaling_list4x4.iter_mut().zip(pps.scaling_lists_4x4.iter()) {
1606		for (i, &value) in src.iter().enumerate() {
1607			list[ZIGZAG_4X4[i]] = value;
1608		}
1609	}
1610
1611	let mut scaling_list8x8 = [[0u8; 64]; 2];
1612	for (list, src) in scaling_list8x8.iter_mut().zip(pps.scaling_lists_8x8.iter()) {
1613		for (i, &value) in src.iter().enumerate() {
1614			list[ZIGZAG_8X8[i]] = value;
1615		}
1616	}
1617
1618	BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
1619		scaling_list4x4,
1620		scaling_list8x8,
1621	)))
1622}
1623
1624/// Ported from cros-codecs `build_pic_param` (BSD-3-Clause).
1625fn build_pic_param(
1626	hdr: &SliceHeader,
1627	pic: &PictureData,
1628	surface_id: bindings::VASurfaceID,
1629	dpb: &Dpb<Handle>,
1630	sps: &Sps,
1631	pps: &Pps,
1632) -> BufferType {
1633	let curr_pic = fill_va_h264_pic(pic, surface_id);
1634
1635	let short_term = dpb
1636		.short_term_refs_iter()
1637		.filter(|entry| !entry.pic.borrow().nonexisting);
1638	let mut refs: Vec<PictureH264> = short_term
1639		.chain(dpb.long_term_refs_iter())
1640		.take(16)
1641		.map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference)))
1642		.collect();
1643	refs.resize_with(16, build_invalid_va_h264_pic);
1644	let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
1645
1646	let seq_fields = H264SeqFields::new(
1647		sps.chroma_format_idc as u32,
1648		sps.separate_colour_plane_flag as u32,
1649		sps.gaps_in_frame_num_value_allowed_flag as u32,
1650		sps.frame_mbs_only_flag as u32,
1651		sps.mb_adaptive_frame_field_flag as u32,
1652		sps.direct_8x8_inference_flag as u32,
1653		// See A.3.3.2.
1654		(sps.level_idc >= Level::L3_1 as u8) as u32,
1655		sps.log2_max_frame_num_minus4 as u32,
1656		sps.pic_order_cnt_type as u32,
1657		sps.log2_max_pic_order_cnt_lsb_minus4 as u32,
1658		sps.delta_pic_order_always_zero_flag as u32,
1659	);
1660
1661	let pic_fields = H264PicFields::new(
1662		pps.entropy_coding_mode_flag as u32,
1663		pps.weighted_pred_flag as u32,
1664		pps.weighted_bipred_idc as u32,
1665		pps.transform_8x8_mode_flag as u32,
1666		hdr.field_pic_flag as u32,
1667		pps.constrained_intra_pred_flag as u32,
1668		pps.bottom_field_pic_order_in_frame_present_flag as u32,
1669		pps.deblocking_filter_control_present_flag as u32,
1670		pps.redundant_pic_cnt_present_flag as u32,
1671		(pic.nal_ref_idc != 0) as u32,
1672	);
1673
1674	// SequenceInfo rejects interlaced input, so map units are frame macroblocks.
1675	let picture_height_in_mbs_minus1 = sps.pic_height_in_map_units_minus1;
1676
1677	BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
1678		curr_pic,
1679		refs,
1680		sps.pic_width_in_mbs_minus1,
1681		picture_height_in_mbs_minus1,
1682		sps.bit_depth_luma_minus8,
1683		sps.bit_depth_chroma_minus8,
1684		sps.max_num_ref_frames,
1685		&seq_fields,
1686		// FMO is not expressible in VA-API.
1687		0,
1688		0,
1689		0,
1690		pps.pic_init_qp_minus26,
1691		pps.pic_init_qs_minus26,
1692		pps.chroma_qp_index_offset,
1693		pps.second_chroma_qp_index_offset,
1694		&pic_fields,
1695		hdr.frame_num,
1696	)))
1697}
1698
1699/// Ported from cros-codecs `fill_ref_pic_list` (BSD-3-Clause).
1700fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
1701	let mut pics: Vec<PictureH264> = list
1702		.iter()
1703		.take(32)
1704		.map(|entry| fill_va_h264_pic(&entry.pic.borrow(), va_surface_id(&entry.reference)))
1705		.collect();
1706	pics.resize_with(32, build_invalid_va_h264_pic);
1707
1708	pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
1709}
1710
1711/// Ported from cros-codecs `build_slice_param` (BSD-3-Clause).
1712fn build_slice_param(
1713	hdr: &SliceHeader,
1714	slice_size: usize,
1715	list0: &[&DpbEntry<Handle>],
1716	list1: &[&DpbEntry<Handle>],
1717	sps: &Sps,
1718	pps: &Pps,
1719) -> BufferType {
1720	let pwt = &hdr.pred_weight_table;
1721
1722	let mut luma_weight_l0 = [0i16; 32];
1723	let mut luma_offset_l0 = [0i16; 32];
1724	let mut chroma_weight_l0 = [[0i16; 2]; 32];
1725	let mut chroma_offset_l0 = [[0i16; 2]; 32];
1726
1727	let mut luma_weight_l1 = [0i16; 32];
1728	let mut luma_offset_l1 = [0i16; 32];
1729	let mut chroma_weight_l1 = [[0i16; 2]; 32];
1730	let mut chroma_offset_l1 = [[0i16; 2]; 32];
1731
1732	// Explicit weighted prediction: P and SP slices weight list 0 only, B slices
1733	// weight both. Implicit (weighted_bipred_idc 2) is derived by the hardware.
1734	let fill_l0 = (pps.weighted_pred_flag && (hdr.slice_type.is_p() || hdr.slice_type.is_sp()))
1735		|| (pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b());
1736	let fill_l1 = pps.weighted_bipred_idc == 1 && hdr.slice_type.is_b();
1737	let chroma = sps.chroma_array_type() != 0;
1738
1739	if fill_l0 {
1740		for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) {
1741			luma_weight_l0[i] = pwt.luma_weight_l0[i];
1742			luma_offset_l0[i] = i16::from(pwt.luma_offset_l0[i]);
1743			if chroma {
1744				for j in 0..2 {
1745					chroma_weight_l0[i][j] = pwt.chroma_weight_l0[i][j];
1746					chroma_offset_l0[i][j] = i16::from(pwt.chroma_offset_l0[i][j]);
1747				}
1748			}
1749		}
1750	}
1751
1752	if fill_l1 {
1753		for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) {
1754			luma_weight_l1[i] = pwt.luma_weight_l1[i];
1755			luma_offset_l1[i] = i16::from(pwt.luma_offset_l1[i]);
1756			if chroma {
1757				for j in 0..2 {
1758					chroma_weight_l1[i][j] = pwt.chroma_weight_l1[i][j];
1759					chroma_offset_l1[i][j] = i16::from(pwt.chroma_offset_l1[i][j]);
1760				}
1761			}
1762		}
1763	}
1764
1765	BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
1766		slice_size as u32,
1767		0,
1768		VA_SLICE_DATA_FLAG_ALL,
1769		hdr.header_bit_size as u16,
1770		hdr.first_mb_in_slice as u16,
1771		hdr.slice_type as u8,
1772		hdr.direct_spatial_mv_pred_flag as u8,
1773		hdr.num_ref_idx_l0_active_minus1,
1774		hdr.num_ref_idx_l1_active_minus1,
1775		hdr.cabac_init_idc,
1776		hdr.slice_qp_delta,
1777		hdr.disable_deblocking_filter_idc,
1778		hdr.slice_alpha_c0_offset_div2,
1779		hdr.slice_beta_offset_div2,
1780		fill_ref_pic_list(list0),
1781		fill_ref_pic_list(list1),
1782		pwt.luma_log2_weight_denom,
1783		pwt.chroma_log2_weight_denom,
1784		fill_l0 as u8,
1785		luma_weight_l0,
1786		luma_offset_l0,
1787		(fill_l0 && chroma) as u8,
1788		chroma_weight_l0,
1789		chroma_offset_l0,
1790		fill_l1 as u8,
1791		luma_weight_l1,
1792		luma_offset_l1,
1793		(fill_l1 && chroma) as u8,
1794		chroma_weight_l1,
1795		chroma_offset_l1,
1796	)))
1797}
1798
1799#[cfg(test)]
1800mod tests {
1801	use std::os::fd::OwnedFd;
1802	use std::process::Command;
1803
1804	use super::*;
1805
1806	fn progressive_sps() -> Sps {
1807		Sps {
1808			frame_mbs_only_flag: true,
1809			chroma_format_idc: 1,
1810			pic_width_in_mbs_minus1: 19,
1811			pic_height_in_map_units_minus1: 14,
1812			// The DPB size comes from the level, and `Default` leaves `level_idc` at 0, which names none.
1813			level_idc: Level::L3 as u8,
1814			..Default::default()
1815		}
1816	}
1817
1818	/// A frame_num gap invents pictures only for the last max_num_ref_frames of
1819	/// the missing frame numbers, however many a stream skips, wrap included.
1820	#[test]
1821	fn a_frame_num_gap_invents_only_the_reference_window() {
1822		// MaxFrameNum 16, two reference frames.
1823		let sps = Sps {
1824			max_num_ref_frames: 2,
1825			..progressive_sps()
1826		};
1827		// No gap: nothing to invent.
1828		assert_eq!(first_invented(3, 4, &sps), 4);
1829		// One missing frame number, within the window.
1830		assert_eq!(first_invented(3, 5, &sps), 4);
1831		// Six missing, 4..=9: only 8 and 9 are invented.
1832		assert_eq!(first_invented(3, 10, &sps), 8);
1833		// Four missing across the wrap, 15, 0, 1, 2: only 1 and 2.
1834		assert_eq!(first_invented(14, 3, &sps), 1);
1835		// The largest gap MaxFrameNum allows costs no more than the window.
1836		assert_eq!(first_invented(4, 3, &sps), 1);
1837
1838		// Marking keeps one reference even when the SPS declares none, so the
1839		// gap still invents the picture that replaces it.
1840		let none = Sps {
1841			max_num_ref_frames: 0,
1842			..progressive_sps()
1843		};
1844		assert_eq!(first_invented(0, 3, &none), 2);
1845	}
1846
1847	/// A non-IDR frame of `pic_order_cnt_type` 0 with `lsb`, after a reference
1848	/// picture at `prev_msb` and `prev_lsb`, with MaxPicOrderCntLsb 256.
1849	fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
1850		let sps = Sps {
1851			log2_max_pic_order_cnt_lsb_minus4: 4,
1852			..progressive_sps()
1853		};
1854		let mut pic = PictureData::default();
1855		pic.pic_order_cnt_lsb = lsb;
1856		pic.nal_ref_idc = 1;
1857		pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
1858		Ok(pic.pic_order_cnt)
1859	}
1860
1861	fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
1862		PrevReferencePicInfo {
1863			pic_order_cnt_msb: msb,
1864			pic_order_cnt_lsb: lsb,
1865			..Default::default()
1866		}
1867	}
1868
1869	/// 8.2.1.1: the lsb wrapping either way moves the msb a whole cycle, and an
1870	/// order count pushed past the `i32` range fails the picture instead of
1871	/// overflowing.
1872	#[test]
1873	fn the_picture_order_count_wraps_and_never_overflows() {
1874		assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
1875		assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
1876		assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
1877		assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
1878		assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
1879
1880		// After a memory_management_control_operation 5 the previous lsb is a
1881		// top field order count, any `i32`, which the lsb comparison takes too.
1882		let after_mmco5 = PrevReferencePicInfo {
1883			has_mmco_5: true,
1884			top_field_order_cnt: i32::MIN,
1885			..Default::default()
1886		};
1887		assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
1888	}
1889
1890	/// 8.2.1.3: FrameNumOffset grows by MaxFrameNum each time frame_num wraps,
1891	/// and fails the picture instead of overflowing.
1892	#[test]
1893	fn the_frame_num_offset_never_overflows() {
1894		let sps = Sps {
1895			pic_order_cnt_type: 2,
1896			..progressive_sps()
1897		};
1898		let order_count = |frame_num_offset| {
1899			let mut prev = PrevPicInfo {
1900				frame_num: 5,
1901				frame_num_offset,
1902				has_mmco_5: false,
1903			};
1904			let mut pic = PictureData::default();
1905			pic.pic_order_cnt_type = 2;
1906			pic.frame_num = 1;
1907			pic.nal_ref_idc = 1;
1908			pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1909		};
1910		// MaxFrameNum is 16, so the wrap adds 16 to the offset.
1911		assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
1912		assert!(order_count(u32::MAX - 3).is_err());
1913		// The offset fits but twice the absolute frame number does not.
1914		assert!(order_count(i32::MAX as u32 / 2).is_err());
1915	}
1916
1917	/// 8.2.1.3: only the final order count must fit, so a non-reference picture
1918	/// one past where a reference picture overflows still decodes.
1919	#[test]
1920	fn the_type2_order_count_is_checked_whole() {
1921		let sps = Sps {
1922			pic_order_cnt_type: 2,
1923			..progressive_sps()
1924		};
1925		let order_count = |nal_ref_idc| {
1926			// The wrap from frame_num 5 to 1 makes the absolute frame number 2^30.
1927			let mut prev = PrevPicInfo {
1928				frame_num: 5,
1929				frame_num_offset: (1 << 30) - 17,
1930				has_mmco_5: false,
1931			};
1932			let mut pic = PictureData::default();
1933			pic.pic_order_cnt_type = 2;
1934			pic.frame_num = 1;
1935			pic.nal_ref_idc = nal_ref_idc;
1936			pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
1937		};
1938		assert_eq!(order_count(0).unwrap(), i32::MAX);
1939		assert!(order_count(1).is_err());
1940	}
1941
1942	/// 8.2.1.2: only the final bottom field order count must fit, not the sum
1943	/// on the way to it.
1944	#[test]
1945	fn the_type1_bottom_field_is_checked_whole() {
1946		let sps = Sps {
1947			pic_order_cnt_type: 1,
1948			offset_for_top_to_bottom_field: i32::MAX,
1949			..progressive_sps()
1950		};
1951		let bottom = |field, delta0, delta1| {
1952			let mut pic = PictureData::default();
1953			pic.pic_order_cnt_type = 1;
1954			pic.nal_ref_idc = 1;
1955			pic.field = field;
1956			pic.delta_pic_order_cnt0 = delta0;
1957			pic.delta_pic_order_cnt1 = delta1;
1958			pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
1959				.map(|()| pic.bottom_field_order_cnt)
1960		};
1961		assert_eq!(bottom(Field::Frame, 2, -i32::MAX).unwrap(), 2);
1962		assert_eq!(bottom(Field::Bottom, 2 - i32::MAX, 0).unwrap(), 2);
1963		assert!(bottom(Field::Frame, 2, 0).is_err());
1964		assert!(bottom(Field::Bottom, 2, 0).is_err());
1965	}
1966
1967	#[test]
1968	fn rejects_nonzero_crop_origins() {
1969		for (left, top) in [(1, 0), (0, 1)] {
1970			let sps = Sps {
1971				frame_cropping_flag: true,
1972				frame_crop_left_offset: left,
1973				frame_crop_top_offset: top,
1974				..progressive_sps()
1975			};
1976			assert!(SequenceInfo::new(&sps)
1977				.unwrap_err()
1978				.to_string()
1979				.contains("left and top"));
1980		}
1981	}
1982
1983	#[test]
1984	fn crop_only_updates_change_sequence_identity() {
1985		let original = SequenceInfo::new(&progressive_sps()).unwrap();
1986		for (right, bottom, expected) in [(1, 0, (318, 240)), (0, 1, (320, 238))] {
1987			let cropped = SequenceInfo::new(&Sps {
1988				frame_cropping_flag: true,
1989				frame_crop_right_offset: right,
1990				frame_crop_bottom_offset: bottom,
1991				..progressive_sps()
1992			})
1993			.unwrap();
1994			assert_eq!(original.coded, cropped.coded);
1995			assert_eq!(cropped.visible, expected);
1996			assert_ne!(original, cropped);
1997		}
1998	}
1999
2000	#[test]
2001	fn rejects_invalid_crop_dimensions() {
2002		for crop in [160, 161, u32::MAX] {
2003			assert!(SequenceInfo::new(&Sps {
2004				frame_cropping_flag: true,
2005				frame_crop_right_offset: crop,
2006				..progressive_sps()
2007			})
2008			.is_err());
2009		}
2010	}
2011
2012	#[test]
2013	fn maximum_progressive_height_does_not_overflow_va_parameters() {
2014		let sps = Arc::new(Sps {
2015			pic_height_in_map_units_minus1: u16::MAX,
2016			..progressive_sps()
2017		});
2018		let params = build_pic_param(
2019			&SliceHeader::default(),
2020			&PictureData::new_non_existing(0, 0),
2021			VA_INVALID_ID,
2022			&Dpb::default(),
2023			&sps,
2024			&kodecs_h264::PpsBuilder::new(Arc::clone(&sps)).build(),
2025		);
2026		let BufferType::PictureParameter(PictureParameter::H264(params)) = params else {
2027			panic!("expected H.264 picture parameters");
2028		};
2029		assert_eq!(params.inner().picture_height_in_mbs_minus1, u16::MAX);
2030		assert!(SequenceInfo::new(&Sps {
2031			frame_mbs_only_flag: false,
2032			..progressive_sps()
2033		})
2034		.is_err());
2035	}
2036
2037	/// Encoder settings shared by the tests that need a stream rather than a
2038	/// particular picture.
2039	fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
2040		crate::encode::Config {
2041			codec: crate::Codec::H264,
2042			width,
2043			height,
2044			framerate: 30,
2045			bitrate: 2_000_000,
2046			gop: std::num::NonZeroU32::new(30).unwrap(),
2047			color: crate::Color::infer(height),
2048			device: None,
2049		}
2050	}
2051
2052	/// A gray field with a moving block, so a picture that decoded into the
2053	/// wrong surface is visible as the block being in the wrong place.
2054	fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
2055		let (w, h) = (width as usize, height as usize);
2056		let mut data = vec![128u8; w * h * 3 / 2];
2057		let x0 = (step * 16) as usize % (w / 2);
2058		for y in h / 4..h / 2 {
2059			for x in x0..x0 + w / 4 {
2060				data[y * w + x] = 235;
2061			}
2062		}
2063		data
2064	}
2065
2066	/// Exported pictures the caller still holds never share a surface.
2067	///
2068	/// The invariant `export` exists to keep: a held surface stays out of the
2069	/// pool, because recycling it would have a later picture decoded over pixels
2070	/// the caller still holds a descriptor for. Two pictures coming
2071	/// back with the same modifier and layout is expected; two coming back on
2072	/// the same allocation is the bug. The modifier itself is hardware policy,
2073	/// so it is printed rather than asserted.
2074	#[test]
2075	#[ignore = "requires a VA-API render node"]
2076	fn exported_pictures_do_not_share_a_surface() {
2077		let (width, height) = (320u32, 240u32);
2078		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2079		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2080
2081		let mut exported = Vec::new();
2082		for step in 0..8 {
2083			let unit = encoder
2084				.encode_nv12(&nv12_frame(width, height, step), step == 0)
2085				.expect("encode a picture");
2086			exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
2087		}
2088		exported.extend(decoder.flush_exported().expect("flush the decoder"));
2089		assert!(!exported.is_empty(), "the decoder produced no pictures");
2090
2091		let first = &exported[0];
2092		eprintln!(
2093			"exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
2094			exported.len(),
2095			first.width,
2096			first.height,
2097			first.descriptor.fourcc,
2098			first.descriptor.objects[0].drm_format_modifier
2099		);
2100
2101		let mut seen = Vec::new();
2102		for (index, frame) in exported.iter().enumerate() {
2103			assert_eq!((frame.width, frame.height), (width, height));
2104			assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
2105			assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
2106			assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
2107
2108			// Two live descriptors for one allocation would mean the pool handed
2109			// a held surface back out. The inode behind a DMA-BUF names the
2110			// buffer, and is what identifies one allocation from another.
2111			let inode = inode(&frame.descriptor.objects[0].fd);
2112			assert!(
2113				!seen.contains(&inode),
2114				"picture {index} was decoded into an allocation an earlier one still holds"
2115			);
2116			seen.push(inode);
2117		}
2118	}
2119
2120	/// With no node named, the decoder opens one that decodes H.264. A named
2121	/// node is used or refused, never swapped for another.
2122	#[test]
2123	#[ignore = "requires a VA-API render node"]
2124	fn the_render_node_is_found_or_named() {
2125		if let Err(err) = Decoder::new(Config::new()) {
2126			panic!("no VA-API H.264 decoder: {err:#}");
2127		}
2128		let named = Config {
2129			device: Some(PathBuf::from("/dev/null")),
2130			..Config::new()
2131		};
2132		assert!(
2133			Decoder::new(named).is_err(),
2134			"a named node that is not a render node was swapped for one that is"
2135		);
2136	}
2137
2138	/// Every picture fed in comes back out, the tail only on flush.
2139	///
2140	/// A stream with B-frames holds pictures in the DPB until later ones come
2141	/// out ahead of them, so a stream that simply stops leaves its tail there.
2142	/// The first assertion keeps the test honest, since a decoder that held
2143	/// nothing back would satisfy the rest without a flush ever running.
2144	#[test]
2145	#[ignore = "requires a VA-API render node and FFmpeg"]
2146	fn flush_returns_the_pictures_the_dpb_still_holds() {
2147		const PICTURES: usize = 10;
2148
2149		let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
2150		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2151
2152		let mut streamed = Vec::new();
2153		for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
2154			streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
2155		}
2156		assert!(
2157			streamed.len() < PICTURES,
2158			"the DPB held nothing back, so this test proves nothing"
2159		);
2160
2161		let flushed = decoder.flush().expect("flush the decoder");
2162		let mut timestamps: Vec<u64> = streamed
2163			.iter()
2164			.chain(&flushed)
2165			.map(|picture| picture.timestamp)
2166			.collect();
2167		timestamps.sort_unstable();
2168		assert_eq!(
2169			timestamps,
2170			(0..PICTURES as u64).collect::<Vec<_>>(),
2171			"the stream lost pictures at its end"
2172		);
2173
2174		// The bumping process marks what it hands out, so a second flush finds
2175		// nothing and a caller that flushes twice never sees a picture twice.
2176		assert!(decoder.flush().expect("flush an empty decoder").is_empty());
2177	}
2178
2179	/// An H.264 stream coded without reordering comes out as it decodes, from
2180	/// this crate's encoder and from libx264.
2181	///
2182	/// Both declare one frame buffer, which C.4.5.3 would empty only when the
2183	/// next picture needs it, so each picture used to come out one access unit
2184	/// late. The two cover both ways a stream rules reordering out: this
2185	/// crate's encoder writes `max_num_reorder_frames` 0 in its VUI, and libx264
2186	/// without B-frames derives the order count from `frame_num` (type 2).
2187	#[test]
2188	#[ignore = "requires a VA-API render node and FFmpeg"]
2189	fn h264_without_reordering_comes_out_as_it_decodes() {
2190		const PICTURES: usize = 10;
2191		let (width, height) = (320u32, 240u32);
2192
2193		let mut streams = Vec::new();
2194		match crate::encode::Encoder::new(encoder_config(width, height)) {
2195			Ok(mut encoder) => {
2196				let units = (0..PICTURES)
2197					.map(|step| {
2198						encoder
2199							.encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
2200							.expect("encode a picture")
2201					})
2202					.collect::<Vec<_>>();
2203				streams.push(("VA-API", units));
2204			}
2205			Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
2206		}
2207		match software_encode(Codec::H264, (width, height), PICTURES, false) {
2208			Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
2209			None => panic!("FFmpeg with libx264 is required"),
2210		}
2211
2212		for (encoder, units) in streams {
2213			let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2214			for (index, unit) in units.iter().enumerate() {
2215				let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2216				let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2217				assert_eq!(
2218					timestamps,
2219					[index as u64],
2220					"{encoder}: access unit {index} was held back"
2221				);
2222			}
2223			assert!(decoder.flush().expect("flush the decoder").is_empty());
2224		}
2225	}
2226
2227	/// The reorder limit comes from the VUI, is bounded by the DPB size, and is
2228	/// zero whenever the order count follows `frame_num`.
2229	#[test]
2230	fn the_reorder_limit_follows_the_sps() {
2231		let sps = || Sps {
2232			level_idc: Level::L3 as u8,
2233			max_num_ref_frames: 1,
2234			..progressive_sps()
2235		};
2236		// 8100 macroblocks over 300 per picture, capped at 16.
2237		assert_eq!(sps().max_dpb_frames(), Some(16));
2238		assert_eq!(
2239			reorder_limit(&sps(), 16),
2240			16,
2241			"without a VUI, the inference is the DPB size"
2242		);
2243
2244		let mut declared = Sps {
2245			vui_parameters_present_flag: true,
2246			..sps()
2247		};
2248		declared.vui_parameters.bitstream_restriction_flag = true;
2249		declared.vui_parameters.max_num_reorder_frames = 0;
2250		declared.vui_parameters.max_dec_frame_buffering = 1;
2251		assert_eq!(
2252			reorder_limit(&declared, declared.max_dpb_frames().unwrap()),
2253			0,
2254			"the VUI's limit applies"
2255		);
2256
2257		declared.vui_parameters.max_num_reorder_frames = 5;
2258		declared.vui_parameters.max_dec_frame_buffering = 2;
2259		assert_eq!(
2260			reorder_limit(&declared, declared.max_dpb_frames().unwrap()),
2261			2,
2262			"the DPB size bounds the VUI's limit"
2263		);
2264
2265		let derived = Sps {
2266			pic_order_cnt_type: 2,
2267			..sps()
2268		};
2269		assert_eq!(
2270			reorder_limit(&derived, 16),
2271			0,
2272			"an order count from frame_num reorders nothing"
2273		);
2274	}
2275
2276	/// A picture the consumer has let go of is decoded into again rather than
2277	/// replaced by a new allocation, and the recycled surfaces still carry the
2278	/// right pictures.
2279	///
2280	/// Each picture is read back and dropped before the next access unit goes
2281	/// in, the way a renderer that draws a picture and moves on behaves. Without
2282	/// recycling this allocated one surface per picture.
2283	#[test]
2284	#[ignore = "requires a VA-API render node"]
2285	fn a_dropped_export_is_decoded_into_again() {
2286		const PICTURES: u32 = 60;
2287		let (width, height) = (320u32, 240u32);
2288		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2289		let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2290		let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2291
2292		let mut compared = 0;
2293		for step in 0..PICTURES {
2294			let unit = encoder
2295				.encode_nv12(&nv12_frame(width, height, step), step == 0)
2296				.expect("encode a picture");
2297			let exported = exporting
2298				.decode_exported(&unit, step as u64)
2299				.expect("decode to a descriptor");
2300			let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
2301			assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2302			for (gpu, cpu) in exported.iter().zip(&downloaded) {
2303				let read_back = gpu.download().expect("read the exported surface back");
2304				assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
2305				compared += 1;
2306			}
2307		}
2308		assert!(compared > 0, "the decoder produced no pictures");
2309
2310		let pool = &exporting.sequence().expect("a sequence").pool;
2311		let allocated = pool.allocated.get();
2312		eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
2313		assert!(
2314			allocated <= pool.free.capacity,
2315			"{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
2316			pool.free.capacity
2317		);
2318	}
2319
2320	/// A consumer that holds many pictures and then lets them all go leaves at
2321	/// most the pool's capacity behind, and the next pictures reuse those.
2322	#[test]
2323	#[ignore = "requires a VA-API render node"]
2324	fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
2325		const HELD: u32 = 40;
2326		let (width, height) = (320u32, 240u32);
2327		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2328		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2329
2330		let mut step = 0;
2331		let mut decode = |decoder: &mut Decoder| {
2332			let unit = encoder
2333				.encode_nv12(&nv12_frame(width, height, step), step == 0)
2334				.expect("encode a picture");
2335			step += 1;
2336			decoder.decode_exported(&unit, step as u64).expect("decode a picture")
2337		};
2338
2339		let mut held = Vec::new();
2340		for _ in 0..HELD {
2341			held.extend(decode(&mut decoder));
2342		}
2343		let pool = &decoder.sequence().expect("a sequence").pool;
2344		let allocated = pool.allocated.get();
2345		assert!(
2346			allocated >= held.len(),
2347			"{} pictures held on {allocated} surfaces",
2348			held.len()
2349		);
2350
2351		drop(held);
2352		let free = pool.free.surfaces.lock().unwrap().len();
2353		assert!(
2354			free <= pool.free.capacity,
2355			"{free} surfaces left free, more than the capacity of {}",
2356			pool.free.capacity
2357		);
2358
2359		for _ in 0..10 {
2360			drop(decode(&mut decoder));
2361		}
2362		let pool = &decoder.sequence().expect("a sequence").pool;
2363		assert_eq!(
2364			pool.allocated.get(),
2365			allocated,
2366			"pictures after the release did not reuse the free surfaces"
2367		);
2368	}
2369
2370	/// An exported picture crosses threads, which is the point of handing one to
2371	/// a renderer: the decoder runs on its own thread and the frame outlives it.
2372	/// [`Decoder`] is neither [`Send`] nor [`Sync`], so this pins that the export
2373	/// does not inherit that.
2374	#[test]
2375	fn an_exported_frame_is_send_and_sync() {
2376		const fn assert_send_sync<T: Send + Sync>() {}
2377		assert_send_sync::<ExportedFrame>();
2378	}
2379
2380	/// An exported picture reads back to the same pixels the ordinary path
2381	/// downloads.
2382	///
2383	/// The invariant that lets a GPU-resident frame keep a CPU fallback: the
2384	/// surface travels with the descriptor, so `vaDeriveImage` still
2385	/// reaches the picture the descriptor points at. One stream through two
2386	/// decoders, so both sides see the same pictures in the same order and the
2387	/// comparison is exact rather than approximate.
2388	#[test]
2389	#[ignore = "requires a VA-API render node"]
2390	fn an_exported_picture_downloads_to_the_same_pixels() {
2391		let (width, height) = (320u32, 240u32);
2392		let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2393		let mut exporting = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2394		let mut downloading = Decoder::new(Config::new()).expect("a second decoder");
2395
2396		let mut exported = Vec::new();
2397		let mut downloaded = Vec::new();
2398		for step in 0..8 {
2399			let unit = encoder
2400				.encode_nv12(&nv12_frame(width, height, step), step == 0)
2401				.expect("encode a picture");
2402			exported.extend(
2403				exporting
2404					.decode_exported(&unit, step as u64)
2405					.expect("decode to a descriptor"),
2406			);
2407			downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
2408		}
2409		exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
2410		downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
2411
2412		assert!(!exported.is_empty(), "the decoder produced no pictures");
2413		assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
2414
2415		for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
2416			let read_back = gpu.download().expect("read the exported surface back");
2417			assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
2418			assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
2419			assert!(
2420				read_back.data == cpu.data,
2421				"picture {index} read back differently than it downloaded"
2422			);
2423		}
2424	}
2425
2426	/// Every picture matches what ffmpeg's software decoder makes of the same
2427	/// stream, bit for bit, in either codec.
2428	///
2429	/// The test that says this is a decoder rather than plumbing. The streams
2430	/// are coded with B-frames and three reference frames, so matching the
2431	/// reference means the reference lists, the picture order counts, and the
2432	/// DPB bumping are all right, not just the surfaces. The second size crops
2433	/// on the right and bottom. Half the pictures are taken as descriptors and
2434	/// downloaded after, so both ways out are checked.
2435	#[test]
2436	#[ignore = "requires a VA-API render node and FFmpeg"]
2437	fn decoded_pictures_match_a_software_decoder() {
2438		const PICTURES: usize = 30;
2439
2440		for codec in [Codec::H264, Codec::H265] {
2441			for (width, height) in [(320u32, 240u32), (852, 478)] {
2442				let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
2443					panic!("no ffmpeg that encodes {codec:?}");
2444				};
2445				let reference = software_decode(codec, &stream);
2446
2447				let picture_len = (width * height * 3 / 2) as usize;
2448				assert_eq!(
2449					reference.len(),
2450					PICTURES * picture_len,
2451					"ffmpeg decoded a different count"
2452				);
2453
2454				let Ok(mut decoder) = Decoder::new(Config { codec, ..Config::new() }) else {
2455					panic!("no VA-API {codec:?} decoder");
2456				};
2457
2458				let units = split_access_units(codec, &stream);
2459				let mut decoded = Vec::new();
2460				for (index, unit) in units.iter().enumerate() {
2461					if index % 2 == 0 {
2462						decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2463					} else {
2464						for exported in decoder
2465							.decode_exported(unit, index as u64)
2466							.expect("decode an access unit")
2467						{
2468							decoded.push(exported.download().expect("download an exported picture"));
2469						}
2470					}
2471				}
2472				decoded.extend(decoder.flush().expect("flush the decoder"));
2473				assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
2474
2475				let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2476				assert!(
2477					timestamps.windows(2).any(|pair| pair[0] > pair[1]),
2478					"the {codec:?} stream came out in decode order, so nothing here tests reordering"
2479				);
2480				timestamps.sort_unstable();
2481				assert_eq!(
2482					timestamps,
2483					(0..PICTURES as u64).collect::<Vec<_>>(),
2484					"a {codec:?} picture's timestamp did not survive reordering"
2485				);
2486
2487				for (index, picture) in decoded.iter().enumerate() {
2488					assert_eq!((picture.width, picture.height), (width, height));
2489					assert!(
2490						picture.data == reference[index * picture_len..][..picture_len],
2491						"{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
2492					);
2493				}
2494			}
2495		}
2496	}
2497
2498	/// An H.265 stream coded without reordering comes out as it decodes: C.5.2
2499	/// bumps by the SPS's reorder limit, which is zero, rather than holding
2500	/// pictures until the DPB fills the way H.264's C.4.5.3 does.
2501	#[test]
2502	#[ignore = "requires a VA-API render node and FFmpeg"]
2503	fn h265_without_reordering_comes_out_as_it_decodes() {
2504		const PICTURES: usize = 10;
2505
2506		let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
2507		let mut decoder = Decoder::new(Config {
2508			codec: Codec::H265,
2509			..Config::new()
2510		})
2511		.expect("no VA-API H.265 decoder");
2512
2513		for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2514			let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
2515			let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2516			assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
2517		}
2518		assert!(decoder.flush().expect("flush the decoder").is_empty());
2519	}
2520
2521	/// A 4K H.265 stream coded with wavefronts, as x265 codes by default, signals
2522	/// an entry point per CTB row: 33 at 64-pixel CTBs, past what a fixed array
2523	/// of 32 held.
2524	#[test]
2525	#[ignore = "requires a VA-API render node and FFmpeg"]
2526	fn a_4k_h265_wavefront_stream_decodes() {
2527		const PICTURES: usize = 2;
2528		let size = (3840, 2160);
2529
2530		let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
2531		let mut decoder = Decoder::new(Config {
2532			codec: Codec::H265,
2533			..Config::new()
2534		})
2535		.expect("no VA-API H.265 decoder");
2536
2537		let mut decoded = Vec::new();
2538		for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
2539			decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2540		}
2541		decoded.extend(decoder.flush().expect("flush the decoder"));
2542		assert_eq!(decoded.len(), PICTURES);
2543		assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
2544	}
2545
2546	/// A second H.265 sequence at another size decodes at that size, and the
2547	/// first sequence's tail comes out ahead of it.
2548	#[test]
2549	#[ignore = "requires a VA-API render node and FFmpeg"]
2550	fn a_new_h265_sequence_decodes_at_its_own_size() {
2551		const PER_SEQUENCE: usize = 6;
2552		let sizes = [(320u32, 240u32), (192u32, 144u32)];
2553
2554		let mut stream = Vec::new();
2555		for &size in &sizes {
2556			let sequence =
2557				software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
2558			stream.extend(sequence);
2559		}
2560		let mut decoder = Decoder::new(Config {
2561			codec: Codec::H265,
2562			..Config::new()
2563		})
2564		.expect("no VA-API H.265 decoder");
2565
2566		let mut decoded = Vec::new();
2567		let units = split_access_units(Codec::H265, &stream);
2568		for (index, unit) in units.iter().enumerate() {
2569			decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
2570		}
2571		decoded.extend(decoder.flush().expect("flush the decoder"));
2572
2573		let expected: Vec<(u32, u32)> = sizes
2574			.iter()
2575			.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
2576			.collect();
2577		let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2578		assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2579
2580		for picture in &decoded {
2581			let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2582			assert_eq!(
2583				picture.data.len(),
2584				expected_len,
2585				"a picture was read back at the wrong size"
2586			);
2587		}
2588	}
2589
2590	/// A second sequence at another size decodes at that size, and the first
2591	/// sequence's tail comes out ahead of it.
2592	///
2593	/// What `apply_sps` promises: an SPS that changes the coded size rebuilds the
2594	/// VA context and the surface pool, and everything decoded against the old
2595	/// one is let out first so no picture is read back at the wrong size.
2596	#[test]
2597	#[ignore = "requires a VA-API render node"]
2598	fn a_new_sequence_decodes_at_its_own_size() {
2599		const PER_SEQUENCE: u32 = 6;
2600		let sizes = [(320u32, 240u32), (192u32, 144u32)];
2601
2602		let mut decoder = Decoder::new(Config::new()).expect("no VA-API H.264 decoder");
2603
2604		let mut decoded = Vec::new();
2605		let mut timestamp = 0u64;
2606		for &(width, height) in &sizes {
2607			let mut encoder =
2608				crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
2609			for step in 0..PER_SEQUENCE {
2610				let unit = encoder
2611					.encode_nv12(&nv12_frame(width, height, step), step == 0)
2612					.expect("encode a picture");
2613				decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
2614				timestamp += 1;
2615			}
2616		}
2617		decoded.extend(decoder.flush().expect("flush the decoder"));
2618
2619		let expected: Vec<(u32, u32)> = sizes
2620			.iter()
2621			.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
2622			.collect();
2623		let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
2624		assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
2625
2626		let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
2627		assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());
2628
2629		for picture in &decoded {
2630			let expected_len = (picture.width * picture.height * 3 / 2) as usize;
2631			assert_eq!(
2632				picture.data.len(),
2633				expected_len,
2634				"a picture was read back at the wrong size"
2635			);
2636		}
2637	}
2638
2639	/// Runs ffmpeg with `args`, returning its standard output, or `None` when
2640	/// ffmpeg is missing or refused the arguments.
2641	fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2642		let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
2643		if !output.status.success() {
2644			eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
2645			return None;
2646		}
2647		Some(output.stdout)
2648	}
2649
2650	/// Encodes `pictures` of ffmpeg's test pattern at `size`, with two B-frames
2651	/// and three reference frames when `reorder` is set and neither otherwise,
2652	/// returning the Annex-B stream. `None` without ffmpeg or its encoder.
2653	fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
2654		let source = format!("testsrc2=size={width}x{height}:rate=30");
2655		let pictures = pictures.to_string();
2656		let mut args = vec![
2657			"-f",
2658			"lavfi",
2659			"-i",
2660			&source,
2661			"-frames:v",
2662			&pictures,
2663			"-pix_fmt",
2664			"yuv420p",
2665		];
2666
2667		let x265;
2668		match codec {
2669			Codec::H264 => args.extend([
2670				"-c:v",
2671				"libx264",
2672				"-profile:v",
2673				"main",
2674				"-bf",
2675				if reorder { "2" } else { "0" },
2676				"-refs",
2677				if reorder { "3" } else { "1" },
2678				"-g",
2679				"15",
2680				"-f",
2681				"h264",
2682			]),
2683			Codec::H265 => {
2684				// x265's defaults are open GOPs, so the second keyframe is a CRA
2685				// picture with leading pictures that refer across it.
2686				x265 = if reorder {
2687					"bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
2688				} else {
2689					"bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
2690				};
2691				args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
2692			}
2693		}
2694		args.push("-");
2695		ffmpeg(&args)
2696	}
2697
2698	/// Decodes `stream` with ffmpeg into packed NV12, one picture after another.
2699	fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
2700		// ffmpeg reads the elementary stream from a file rather than a pipe, so
2701		// the test never has to drain its output while still writing its input.
2702		static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2703		let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2704		let extension = match codec {
2705			Codec::H264 => "264",
2706			Codec::H265 => "265",
2707		};
2708		let path = std::env::temp_dir().join(format!(
2709			"kodecs-vaapi-decode-{}-{count}.{extension}",
2710			std::process::id()
2711		));
2712		std::fs::write(&path, stream).expect("write the elementary stream");
2713		let decoded = ffmpeg(&[
2714			"-i",
2715			path.to_str().expect("a UTF-8 temporary path"),
2716			"-pix_fmt",
2717			"nv12",
2718			"-f",
2719			"rawvideo",
2720			"-",
2721		]);
2722		let _ = std::fs::remove_file(&path);
2723		decoded.expect("ffmpeg decodes what it just encoded")
2724	}
2725
2726	/// Splits an Annex-B elementary stream into access units.
2727	///
2728	/// A unit ends at the first slice of the next picture, or at a parameter
2729	/// set, SEI, or delimiter that comes before one.
2730	fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
2731		let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
2732			.filter(|&i| stream[i..i + 3] == [0, 0, 1])
2733			.collect();
2734
2735		let mut units = Vec::new();
2736		let mut current: Vec<u8> = Vec::new();
2737		let mut current_has_picture = false;
2738
2739		for (index, &start) in starts.iter().enumerate() {
2740			let end = starts.get(index + 1).copied().unwrap_or(stream.len());
2741			let nal = &stream[start + 3..end];
2742			// The first bit after the NAL header is first_mb_in_slice == 0 for
2743			// H.264 and first_slice_segment_in_pic_flag for H.265: either way, set
2744			// on the first slice of a picture.
2745			let (is_slice, starts_picture, starts_unit) = match codec {
2746				Codec::H264 => {
2747					let nal_type = nal[0] & 0x1f;
2748					let is_slice = (1..=5).contains(&nal_type);
2749					(is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
2750				}
2751				Codec::H265 => {
2752					let nal_type = (nal[0] >> 1) & 0x3f;
2753					let is_slice = nal_type <= 31;
2754					(
2755						is_slice,
2756						is_slice && nal[2] & 0x80 != 0,
2757						matches!(nal_type, 32..=35 | 39),
2758					)
2759				}
2760			};
2761
2762			if current_has_picture && (starts_picture || starts_unit) {
2763				units.push(std::mem::take(&mut current));
2764				current_has_picture = false;
2765			}
2766
2767			current.extend_from_slice(&stream[start..end]);
2768			current_has_picture |= is_slice;
2769		}
2770
2771		if !current.is_empty() {
2772			units.push(current);
2773		}
2774		units
2775	}
2776
2777	/// The inode of a descriptor, which for a DMA-BUF names the allocation
2778	/// behind it: every buffer gets its own on the anonymous dma-buf filesystem.
2779	fn inode(fd: &OwnedFd) -> u64 {
2780		use std::os::unix::fs::MetadataExt as _;
2781
2782		// Stat a duplicate, so the descriptor the caller holds is untouched and
2783		// the `File` wrapper closes only its own copy.
2784		let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
2785		file.metadata().expect("stat the descriptor").ino()
2786	}
2787}