Skip to main content

moq_video/decode/
decoder.rs

1//! Video decoder front end.
2//!
3//! Prepares each container frame for a [`Backend`](super::backend::Backend):
4//! converts length-prefixed H.264 / H.265 payloads to Annex-B and injects the
5//! description's parameter sets ahead of keyframes, leaving Annex-B payloads,
6//! AV1 OBU temporal units, and VP8 / VP9 frames untouched. Gates output until the
7//! first keyframe so the backend never sees a delta frame it can't decode.
8//!
9//! The catalog's `description` decides the NAL framing, never the codec
10//! prefix. A configuration record (avcC / hvcC) means length-prefixed NAL units
11//! of its length size, its parameter sets seeding every keyframe; no record
12//! means Annex-B carrying its own parameter sets. The prefix only says where
13//! the parameter sets live: avc3 / hev1 may repeat them in band beside a
14//! record, as the fMP4 and HLS imports publish. CMAF samples are always
15//! length-prefixed, so a CMAF track needs its record.
16//!
17//! A Legacy or LOC avc1 / hvc1 track with no record contradicts itself and is
18//! read as Annex-B rather than refused, as older `@moq/publish` builds labelled
19//! their Annex-B output: length-prefixed payloads without their parameter sets
20//! could not be decoded anyway, so the lenient reading only ever turns an error
21//! into a picture.
22
23use std::collections::VecDeque;
24use std::marker::PhantomData;
25use std::rc::Rc;
26
27use bytes::Bytes;
28use hang::catalog::{AV1, Container, VP9, VideoCodec, VideoConfig};
29use moq_mux::codec::{annexb, h264, h265};
30use moq_net::Timestamp;
31
32use super::backend::{self, Codec};
33use crate::{Color, Error, Frame, Output, Size};
34
35/// Which decoder implementation to use. `#[non_exhaustive]` so new selection
36/// strategies can be added without breaking external `match`es.
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum Backend {
40	/// Prefer a platform hardware decoder, falling back to enabled software.
41	#[default]
42	Auto,
43	/// Hardware only; error if none is available.
44	Hardware,
45	/// Software only (OpenH264 and libvpx, when their features are enabled).
46	Software,
47	/// A specific backend by name, e.g. `"videotoolbox"`, `"mediacodec"`,
48	/// `"nvdec"`, `"vaapi"`, `"v4l2"`, `"openh264"`, or `"vpx"`.
49	Named(String),
50}
51
52/// Decoder configuration: the codec implementation and the frames it hands back.
53///
54/// Nothing here is about the track: where a [`Consumer`](super::Consumer)
55/// starts and how far it may lag live are its [`Options`](super::Options).
56///
57/// `#[non_exhaustive]`: build via [`Config::new`] (or `default()`) and set the
58/// optional fields, so future knobs don't break callers.
59#[derive(Clone, Debug, Default)]
60#[non_exhaustive]
61pub struct Config {
62	/// Which backend to use.
63	pub backend: Backend,
64	/// Where decoded pictures live.
65	///
66	/// [`Output::Native`] hands back whatever the backend decoded into: a
67	/// `CVPixelBuffer` from VideoToolbox, a Direct3D11 texture from Media
68	/// Foundation, a CUDA buffer from NVDEC, a DMA-BUF from VAAPI, CPU I420 from
69	/// OpenH264. A consumer that draws imports those directly (`render::Renderer`),
70	/// and a transcoder re-encodes them in place. [`Output::Cpu`] delivers every
71	/// picture as [`Surface::I420`](crate::Surface::I420): a backend that can
72	/// decode straight to system memory does, the rest download each picture.
73	/// Ask for it when the pixels are headed for the CPU anyway, since a GPU
74	/// surface handed out and downloaded later costs an allocation the backend
75	/// could have skipped. [`Output::Render`] keeps the surfaces
76	/// `render::Renderer` imports and downloads the rest; a player that draws
77	/// asks `render::output` of its device, which picks it where the device
78	/// imports.
79	pub output: Output,
80	/// Ask the decoder to scale its output to this size (both dimensions even)
81	/// instead of the stream's native one.
82	///
83	/// A hint, not a contract: a hardware decoder with a built-in scaler (NVDEC)
84	/// honors it for free, every other backend ignores it, so the frames still
85	/// carry whatever size they decoded at. A caller that needs exactly this
86	/// size checks each [`Frame::size`](crate::Frame::size) and applies
87	/// [`Frame::resize`](crate::Frame::resize) to the rest; the hint only lets a
88	/// decoder that can make that a no-op do so.
89	pub scale_hint: Option<Size>,
90	/// The hardware the decoder opens. [`Device::Auto`](crate::Device::Auto)
91	/// (the default) picks one: VA-API the first render node that encodes,
92	/// decodes, and scales, so a DMA-BUF moves between them without a copy;
93	/// NVDEC the first CUDA device; V4L2 the first node that decodes H.264,
94	/// which a driver whose format enumeration is wrong can defeat. Name the
95	/// encoder's device so a frame passes to it without a copy.
96	pub device: crate::Device,
97}
98
99impl Config {
100	/// A default config: automatic backend selection, native output, no scaling.
101	pub fn new() -> Self {
102		Self::default()
103	}
104}
105
106/// How to turn a container payload into a backend access unit.
107enum Conversion {
108	/// The payload is already in the backend's input framing: Annex-B for an
109	/// H.264 / H.265 track with no record, OBU temporal units for AV1, one coded
110	/// frame for VP8 / VP9.
111	Passthrough,
112	/// An H.264 / H.265 track with a record: length-prefixed NALs.
113	/// Replace the length prefixes with start codes and prepend `keyframe_prefix`
114	/// (the description's parameter sets, empty when they are all in band) ahead
115	/// of every keyframe. `pins_size` is whether the description carries an
116	/// SPS, which fixes the picture size for the whole track.
117	LengthPrefixed {
118		length_size: usize,
119		keyframe_prefix: Bytes,
120		pins_size: bool,
121	},
122}
123
124impl Conversion {
125	/// The backend access unit for one container payload.
126	fn access_unit(&self, payload: &Bytes, keyframe: bool) -> Result<Bytes, Error> {
127		match self {
128			// Cheap refcount bump; the backend splits codec units off this buffer.
129			Self::Passthrough => Ok(payload.clone()),
130			Self::LengthPrefixed {
131				length_size,
132				keyframe_prefix,
133				..
134			} => {
135				let prefix = keyframe.then(|| keyframe_prefix.as_ref());
136				Ok(annexb::from_length_prefixed(payload, *length_size, prefix).map_err(moq_mux::Error::from)?)
137			}
138		}
139	}
140}
141
142/// The most colour switches a decoder waits on. Each one is a keyframe whose
143/// pictures the backend still holds behind earlier ones, so a decoder never needs
144/// more than it holds pictures: at most 16 for H.264 and H.265, and this leaves
145/// room for a hardware pipeline beyond that, as the consumer's arrivals do.
146const SWITCHES: usize = 32;
147
148/// Decodes container payloads (the codec bitstream) into raw [`Frame`]s.
149///
150/// The bring-your-own-payload layer under [`Consumer`](super::Consumer): use it
151/// when the frames don't come from a plain track subscription, e.g. a transcoder
152/// serving individually fetched groups. Feed it the payload of each container
153/// frame in decode order; it converts length-prefixed H.264 / H.265 to Annex-B,
154/// passes AV1 OBU temporal units through, and gates output until the first
155/// keyframe.
156///
157/// A decoder is bound to the thread that opens it. Use [`Sink`](super::Sink)
158/// when the owner can move between threads.
159///
160/// ```compile_fail
161/// fn move_to_another_thread(decoder: moq_video::decode::Decoder) {
162///     std::thread::spawn(move || drop(decoder));
163/// }
164/// ```
165pub struct Decoder {
166	backend: Box<dyn backend::Backend>,
167	codec: Codec,
168	conversion: Conversion,
169	output: Output,
170	got_keyframe: bool,
171	/// The space the stream's pictures are in: what the last keyframe's SPS
172	/// signalled, or the guess for the catalog's coded size. Labels the pictures
173	/// a backend hands back unlabelled, which keeps their space once a decoder
174	/// scale or a resize moves them across 576 lines.
175	color: Option<Color>,
176	/// Spaces later keyframes switched to, each from that keyframe's timestamp.
177	/// A reordering backend can still be holding pictures from before the
178	/// switch, which keep the old space until output reaches the keyframe.
179	switches: VecDeque<(Timestamp, Option<Color>)>,
180	/// Set by [`flush`](Self::flush) until the tail is received or more input
181	/// arrives, so a switch no picture reached still applies to the next stream.
182	flushed: bool,
183	/// Keeps direct use bound to the constructing thread, regardless of backend.
184	_thread_bound: PhantomData<Rc<()>>,
185}
186
187impl Decoder {
188	/// Build a decoder for the catalog's video config.
189	///
190	/// A codec or description this build cannot decode is
191	/// [`Error::UnsupportedCodec`], and so is a stream every decoder for its codec
192	/// refused because its device cannot decode it. When any of them failed to open
193	/// for another reason, such as a missing driver, the result is
194	/// [`Error::NoDecoder`], a fault rather than a property of the track.
195	pub fn new(catalog: &VideoConfig, config: &Config) -> Result<Self, Error> {
196		// The description decides the framing, never the codec prefix: with a
197		// configuration record the NAL units are length-prefixed by its length size,
198		// without one they are Annex-B. CMAF samples are always length-prefixed, so
199		// they need the record.
200		let cmaf = matches!(catalog.container, Container::Cmaf { .. });
201		let description = catalog
202			.description
203			.as_ref()
204			.filter(|description| !description.is_empty());
205		let (codec, conversion) = match &catalog.codec {
206			VideoCodec::H264(h264) => {
207				let conversion = match description {
208					Some(avcc) => {
209						let params = h264::Avcc::parse(avcc)
210							.map_err(|err| Error::UnsupportedCodec(format!("invalid avcC description: {err}")))?;
211						let keyframe_prefix = annexb::build_prefix(params.sps.iter().chain(params.pps.iter()));
212						Conversion::LengthPrefixed {
213							length_size: params.length_size,
214							keyframe_prefix,
215							pins_size: !params.sps.is_empty(),
216						}
217					}
218					None => annexb_conversion(cmaf, h264.inline, "H.264", "avcC")?,
219				};
220				(Codec::H264, conversion)
221			}
222			VideoCodec::H265(h265) => {
223				let conversion = match description {
224					Some(hvcc) => {
225						let params = h265::Hvcc::parse(hvcc)
226							.map_err(|err| Error::UnsupportedCodec(format!("invalid hvcC description: {err}")))?;
227						let keyframe_prefix =
228							annexb::build_prefix(params.vps.iter().chain(params.sps.iter()).chain(params.pps.iter()));
229						Conversion::LengthPrefixed {
230							length_size: params.length_size,
231							keyframe_prefix,
232							pins_size: !params.sps.is_empty(),
233						}
234					}
235					None => annexb_conversion(cmaf, h265.in_band, "H.265", "hvcC")?,
236				};
237				(Codec::H265, conversion)
238			}
239			VideoCodec::AV1(av1) if is_supported_av1(av1) => (Codec::Av1, Conversion::Passthrough),
240			VideoCodec::VP8 => (Codec::Vp8, Conversion::Passthrough),
241			VideoCodec::VP9(vp9) if is_supported_vp9(vp9) => (Codec::Vp9, Conversion::Passthrough),
242			other => return Err(Error::UnsupportedCodec(other.to_string())),
243		};
244
245		// Refused here for every backend, so a hint no backend reads is still
246		// checked rather than silently carried. NV12 output is what every
247		// scaler produces, and its chroma is 2x2 subsampled.
248		if let Some(size) = config.scale_hint {
249			size.validate("decoder scale hint")?;
250		}
251
252		let backend = backend::open(&stream(catalog, codec, &conversion), config)?;
253		tracing::debug!(decoder = backend.name(), "opened video decoder");
254		Ok(Self {
255			backend,
256			codec,
257			conversion,
258			output: config.output,
259			got_keyframe: false,
260			color: declared(catalog),
261			switches: VecDeque::new(),
262			flushed: false,
263			_thread_bound: PhantomData,
264		})
265	}
266
267	/// The decoder backend name in use, e.g. `"videotoolbox"`.
268	pub fn name(&self) -> &str {
269		self.backend.name()
270	}
271
272	/// Submit one container frame, whose raw frames come out of
273	/// [`receive`](Self::receive). `timestamp` is this frame's presentation time;
274	/// it rides through the decoder and comes back on each output frame, so a
275	/// reordering decoder (B-frames) stamps every picture with its own
276	/// presentation time rather than this access unit's. With no reordering the
277	/// two coincide.
278	pub fn decode(&mut self, payload: &Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error> {
279		// Wait for the first keyframe: a decoder started mid-GOP can't decode
280		// delta frames, and the parameter sets ride along with the keyframe.
281		if !self.got_keyframe && !keyframe {
282			return Ok(());
283		}
284
285		self.flushed = false;
286		let submitted = self.submit(payload, timestamp, keyframe);
287		// Set by how the keyframe went rather than by its arrival: one that failed
288		// leaves nothing for the deltas behind it to predict from.
289		if keyframe {
290			self.got_keyframe = submitted.is_ok();
291		}
292		submitted
293	}
294
295	/// Convert one access unit and hand it to the backend.
296	fn submit(&mut self, payload: &Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error> {
297		let access_unit = self.conversion.access_unit(payload, keyframe)?;
298		let signalled = keyframe
299			.then(|| super::vui::signalled(self.codec, &access_unit))
300			.flatten();
301		// A refused keyframe yields no picture, so its switch would wait for one forever.
302		self.backend.decode(access_unit, timestamp, keyframe)?;
303		if keyframe {
304			self.switch(timestamp, signalled);
305		}
306		Ok(())
307	}
308
309	/// Record the space a keyframe at `timestamp` switched to, if it signalled one.
310	fn switch(&mut self, timestamp: Timestamp, signalled: Option<Option<Color>>) {
311		// Nothing decoded before a keyframe presents at or after it, so a switch there was
312		// never going to be reached: only timestamps that run backwards leave one.
313		while self.switches.back().is_some_and(|(at, _)| *at >= timestamp) {
314			self.switches.pop_back();
315		}
316		let Some(color) = signalled else { return };
317		if self.switches.back().map_or(self.color, |(_, color)| *color) == color {
318			return;
319		}
320		// A backend that drops pictures leaves switches no output reaches. The oldest is
321		// applied early rather than kept, so the queue stays bounded.
322		if self.switches.len() == SWITCHES
323			&& let Some((_, color)) = self.switches.pop_front()
324		{
325			self.color = color;
326		}
327		self.switches.push_back((timestamp, color));
328	}
329
330	/// Pop the oldest ready raw frame, or `None` while the decoder holds the rest.
331	///
332	/// Call until it returns `None` after each [`decode`](Self::decode) and
333	/// [`flush`](Self::flush).
334	pub fn receive(&mut self) -> Result<Option<Frame>, Error> {
335		let Some(frame) = self.backend.receive()? else {
336			// The tail is out, so a switch no picture reached still applies.
337			if std::mem::take(&mut self.flushed)
338				&& let Some((_, color)) = self.switches.drain(..).next_back()
339			{
340				self.color = color;
341			}
342			return Ok(None);
343		};
344		self.deliver(frame).map(Some)
345	}
346
347	/// Mark the end of input, so [`receive`](Self::receive) returns the frames
348	/// the backend still holds once the stream has ended.
349	///
350	/// Call this after the last access unit, and receive, before dropping the
351	/// decoder. The decoder remains reusable and waits for a keyframe before
352	/// accepting the next stream.
353	pub fn flush(&mut self) -> Result<(), Error> {
354		self.got_keyframe = false;
355		self.backend.flush()?;
356		self.flushed = true;
357		Ok(())
358	}
359
360	/// Put a backend picture in the representation [`Config::output`] asked for.
361	///
362	/// The one place the choice is enforced, so a backend only has to know
363	/// about it when decoding to the CPU directly is cheaper than downloading
364	/// afterwards (VAAPI). A surface with no CPU path fails here rather than
365	/// arriving GPU-resident at a caller that said it could not take one.
366	fn deliver(&mut self, frame: Frame) -> Result<Frame, Error> {
367		// Output is in presentation order, and nothing decoded after a keyframe is
368		// shown before it, so a picture's timestamp says which side of a switch it
369		// is on.
370		while let Some(&(at, color)) = self.switches.front()
371			&& frame.timestamp >= at
372		{
373			self.color = color;
374			self.switches.pop_front();
375		}
376		let mut surface = self.output.convert(frame.surface)?;
377		if let Some(color) = self.color {
378			surface.label(color);
379		}
380		Ok(Frame::new(frame.timestamp, surface))
381	}
382
383	/// Submit one container frame and collect everything it readied.
384	#[cfg(test)]
385	pub(crate) fn decode_all(
386		&mut self,
387		payload: &Bytes,
388		timestamp: Timestamp,
389		keyframe: bool,
390	) -> Result<Vec<Frame>, Error> {
391		self.decode(payload, timestamp, keyframe)?;
392		self.receive_all()
393	}
394
395	/// Flush and collect the tail.
396	#[cfg(test)]
397	pub(crate) fn flush_all(&mut self) -> Result<Vec<Frame>, Error> {
398		self.flush()?;
399		self.receive_all()
400	}
401
402	#[cfg(test)]
403	fn receive_all(&mut self) -> Result<Vec<Frame>, Error> {
404		let mut frames = Vec::new();
405		while let Some(frame) = self.receive()? {
406			frames.push(frame);
407		}
408		Ok(frames)
409	}
410}
411
412/// The space the catalog declares for the stream, until a keyframe says.
413///
414/// H.264 and H.265 signal theirs in every keyframe, so this only lasts for
415/// AV1 and VP9 on a backend that reports none. Their codec strings default an
416/// omitted colour to BT.709 limited, so that pairing says nothing and the
417/// coded size's guess stands in; any other was written on purpose.
418fn declared(catalog: &VideoConfig) -> Option<Color> {
419	use crate::color::{CodePoints, Range};
420
421	let coded = catalog
422		.coded_width
423		.zip(catalog.coded_height)
424		.map(|(width, height)| Size::new(width, height));
425	let (primaries, transfer, matrix, full_range) = match &catalog.codec {
426		VideoCodec::VP9(vp9) => (
427			vp9.color_primaries,
428			vp9.transfer_characteristics,
429			vp9.matrix_coefficients,
430			vp9.full_range,
431		),
432		VideoCodec::AV1(av1) => (
433			av1.color_primaries,
434			av1.transfer_characteristics,
435			av1.matrix_coefficients,
436			av1.full_range,
437		),
438		_ => return coded.map(Color::infer),
439	};
440	if (primaries, transfer, matrix, full_range) == (1, 1, 1, false) {
441		return coded.map(Color::infer);
442	}
443	let codes = CodePoints {
444		primaries,
445		transfer,
446		matrix,
447	};
448	let range = match full_range {
449		true => Range::Full,
450		false => Range::Limited,
451	};
452	// An unspecified field among declared ones takes the guess for the coded
453	// size, or for SD when the catalog has none.
454	Color::from_code_points(Some(codes), range, coded.unwrap_or_default())
455}
456
457/// The conversion for an H.264 / H.265 track with no configuration record:
458/// its frames are Annex-B and carry their own parameter sets.
459///
460/// A CMAF track has no Annex-B framing, so one without a record is refused. A
461/// Legacy or LOC track whose codec says its parameter sets are out of band
462/// (avc1 / hvc1) contradicts itself, but its frames can only decode if they
463/// carry them, so it is read as Annex-B rather than refused.
464fn annexb_conversion(cmaf: bool, in_band: bool, codec: &str, record: &str) -> Result<Conversion, Error> {
465	if cmaf {
466		return Err(Error::UnsupportedCodec(format!(
467			"CMAF {codec} track is missing its {record} description"
468		)));
469	}
470	if !in_band {
471		tracing::warn!(
472			"{codec} track says its parameter sets are out of band but has no {record}; reading it as Annex-B"
473		);
474	}
475	Ok(Conversion::Passthrough)
476}
477
478/// What the catalog says about the stream before its first picture, for the
479/// backends to ask their devices with.
480fn stream(catalog: &VideoConfig, codec: Codec, conversion: &Conversion) -> backend::Stream {
481	let (parameter_sets, pins_size) = match conversion {
482		Conversion::LengthPrefixed {
483			keyframe_prefix,
484			pins_size,
485			..
486		} => (
487			(!keyframe_prefix.is_empty()).then(|| keyframe_prefix.clone()),
488			*pins_size,
489		),
490		Conversion::Passthrough => (None, false),
491	};
492	backend::Stream {
493		codec,
494		h264_profile: match &catalog.codec {
495			VideoCodec::H264(h264) => Some(h264.profile),
496			_ => None,
497		},
498		// The catalog's coded size is a ceiling the picture resizes below in
499		// band, so it is the picture's size only when the description's SPS
500		// pins it.
501		size: catalog
502			.coded_width
503			.zip(catalog.coded_height)
504			.filter(|_| pins_size)
505			.map(|(width, height)| Size::new(width, height)),
506		parameter_sets,
507	}
508}
509
510fn is_supported_av1(av1: &AV1) -> bool {
511	av1.bitdepth == 8 && !av1.mono_chrome && av1.chroma_subsampling_x && av1.chroma_subsampling_y
512}
513
514/// Profile 0 is 8-bit 4:2:0, with either chroma siting (`vpcC` 0 or 1).
515fn is_supported_vp9(vp9: &VP9) -> bool {
516	vp9.profile == 0 && vp9.bit_depth == 8 && vp9.chroma_subsampling <= 1
517}
518
519#[cfg(test)]
520mod tests {
521	#![cfg_attr(
522		not(feature = "openh264"),
523		allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
524	)]
525
526	use moq_net::Timestamp;
527
528	use super::backend::{self, Codec, probe};
529	use crate::encode::{Backend as EncodeBackend, Config as EncodeConfig, Encoder};
530	use crate::frame::I420;
531	use crate::{Frame, Surface};
532
533	/// The `index`th frame of a flat `size` stream at 30fps, every pixel at RGB
534	/// `level`.
535	fn flat_frame(index: u64, level: u8, size: crate::Size) -> Frame {
536		let rgba = vec![level; size.pixels() as usize * 4];
537		let surface = Surface::rgba(&rgba, size).unwrap();
538		Frame::new(Timestamp::from_micros(index * 33_333).unwrap(), surface)
539	}
540
541	/// The `index`th frame of a mid-gray 320x240 stream, at 30fps.
542	fn gray_frame(index: u64) -> Frame {
543		flat_frame(index, 0x80, gray_size())
544	}
545
546	/// Assert a decoded picture is the expected size and looks like the gray frame
547	/// we encoded. Mid-gray RGBA (0x80) is a flat picture: BT.601 limited-range
548	/// luma near 125 and neutral chroma near 128. Averaging each plane catches
549	/// plane swaps, stride bugs, and a misread Y/UV split that a size check misses.
550	fn assert_gray(i420: &I420, width: u32, height: u32) {
551		assert_eq!(i420.width, width);
552		assert_eq!(i420.height, height);
553		let luma = (width * height) as usize;
554		// Tightly-packed I420: luma + two quarter-size chroma planes.
555		assert_eq!(i420.data.len(), luma * 3 / 2);
556
557		let avg = |plane: &[u8]| plane.iter().map(|&b| b as u32).sum::<u32>() / plane.len() as u32;
558		let y = avg(&i420.data[..luma]);
559		let u = avg(&i420.data[luma..luma + luma / 4]);
560		let v = avg(&i420.data[luma + luma / 4..]);
561		assert!((110..=140).contains(&y), "luma {y} off for a gray frame");
562		assert!((118..=138).contains(&u), "u {u} off for a gray frame");
563		assert!((118..=138).contains(&v), "v {v} off for a gray frame");
564	}
565
566	/// Encode 10 gray frames with `encoder`, decode them through `decoder`, and
567	/// assert each decoded picture round-trips. Keyframe gating is exercised (the
568	/// first packet is a keyframe with inline parameter sets).
569	fn round_trip(mut encoder: Encoder, mut decoder: Box<dyn backend::Backend>, expect_name: &str) {
570		assert_eq!(decoder.name(), expect_name);
571
572		let mut decoded = Vec::new();
573		let mut decode = |encoded: crate::encode::Encoded| {
574			decoded.extend(
575				decoder
576					.decode_all(encoded.payload, encoded.timestamp, encoded.keyframe)
577					.unwrap(),
578			);
579		};
580		for i in 0..10u64 {
581			if i == 0 {
582				encoder.cut().unwrap();
583			}
584			// Distinct, spread-apart timestamps so a round-tripped value is unambiguous.
585			for encoded in encoder.encode_all(&gray_frame(i)).unwrap() {
586				decode(encoded);
587			}
588		}
589		// A pipelined encoder (MediaCodec) still holds the last frames.
590		for encoded in encoder.flush_all().unwrap() {
591			decode(encoded);
592		}
593		decoded.extend(decoder.flush_all().unwrap());
594
595		assert!(!decoded.is_empty(), "decoder produced no frames");
596		for out in &decoded {
597			assert_gray(&out.surface.to_i420().unwrap(), 320, 240);
598		}
599
600		// The timestamp rides through the codec and comes back on each picture,
601		// including any tail released by the drain. It returns in presentation order:
602		// strictly increasing and drawn from the values we fed.
603		let micros: Vec<u128> = decoded.iter().map(|d| d.timestamp.as_micros().unwrap()).collect();
604		assert!(
605			micros.windows(2).all(|w| w[0] < w[1]),
606			"decoded timestamps not strictly increasing: {micros:?}"
607		);
608		assert!(
609			micros.iter().all(|&t| t % 33_333 == 0 && t < 333_330),
610			"decoded timestamp outside the fed set: {micros:?}"
611		);
612	}
613
614	/// A decoder config selecting one backend by kind.
615	fn decode_config(kind: super::Backend) -> super::Config {
616		super::Config {
617			backend: kind,
618			..super::Config::new()
619		}
620	}
621
622	#[cfg(feature = "openh264")]
623	/// An openh264 (software H.264) encoder for a `size` test stream at 30fps.
624	fn h264_software_encoder(size: crate::Size) -> Encoder {
625		Encoder::new(&EncodeConfig {
626			backend: EncodeBackend::Software,
627			..EncodeConfig::new(size.width, size.height, crate::FrameRate::new(30, 1).unwrap())
628		})
629		.expect("openh264 encoder")
630	}
631
632	/// The size the gray test stream is encoded at.
633	fn gray_size() -> crate::Size {
634		crate::Size::new(320, 240)
635	}
636
637	#[test]
638	#[cfg(feature = "openh264")]
639	fn openh264_round_trip() {
640		let decoder =
641			backend::open(&Codec::H264.into(), &decode_config(super::Backend::Software)).expect("openh264 decoder");
642		round_trip(h264_software_encoder(gray_size()), decoder, "openh264");
643	}
644
645	/// A description-less avc1 track from WebCodecs carries Annex-B payloads with
646	/// its parameter sets in band, the only framing that can decode without avcC.
647	#[test]
648	#[cfg(feature = "openh264")]
649	fn avc1_without_avcc_decodes_as_annexb() {
650		// The catalog shape observed from @moq/publish: `"codec": "avc1.640028"`
651		// and no `description`.
652		let h264 = hang::catalog::H264 {
653			inline: false,
654			profile: 0x64,
655			constraints: 0x00,
656			level: 0x28,
657		};
658		let catalog = hang::catalog::VideoConfig::new(h264);
659		assert_eq!(catalog.codec.to_string(), "avc1.640028");
660		assert!(catalog.description.is_none());
661
662		let mut decoder = super::Decoder::new(&catalog, &decode_config(super::Backend::Software))
663			.expect("a description-less avc1 track opens rather than erroring");
664		assert!(
665			matches!(decoder.conversion, super::Conversion::Passthrough),
666			"a description-less avc1 track is read as Annex-B"
667		);
668
669		// openh264 emits Annex-B access units with SPS/PPS inline ahead of each
670		// IDR, which is the bitstream WebCodecs produces in `annexb` format.
671		let mut encoder = h264_software_encoder(gray_size());
672		let mut decoded = Vec::new();
673		for i in 0..5u64 {
674			let keyframe = i == 0;
675			if keyframe {
676				encoder.cut().unwrap();
677			}
678			for encoded in encoder.encode_all(&gray_frame(i)).unwrap() {
679				assert!(
680					encoded.payload.starts_with(&[0, 0, 0, 1]) || encoded.payload.starts_with(&[0, 0, 1]),
681					"the test feeds Annex-B, not length-prefixed NALs"
682				);
683				decoded.extend(
684					decoder
685						.decode_all(&encoded.payload, encoded.timestamp, keyframe)
686						.unwrap(),
687				);
688			}
689		}
690
691		assert!(!decoded.is_empty(), "decoder produced no frames");
692		for out in &decoded {
693			assert_gray(&out.surface.to_i420().unwrap(), 320, 240);
694		}
695	}
696
697	/// Rewrite an Annex-B access unit as 4-byte length-prefixed NAL units, the
698	/// framing of an MP4 sample.
699	fn length_prefixed(annexb: &bytes::Bytes) -> bytes::Bytes {
700		let mut buf = annexb.clone();
701		let mut nals = moq_mux::codec::annexb::NalIterator::new(&mut buf);
702		let mut out = Vec::new();
703		let mut push = |nal: bytes::Bytes| {
704			out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
705			out.extend_from_slice(&nal);
706		};
707		for nal in nals.by_ref() {
708			push(nal.unwrap());
709		}
710		if let Some(nal) = nals.flush().unwrap() {
711			push(nal);
712		}
713		out.into()
714	}
715
716	/// A CMAF avc3 track: length-prefixed samples with SPS/PPS in band, under an
717	/// avcC that lists none. `inline` says where the parameter sets are, not how
718	/// the NAL units are framed, so the decoder still converts to Annex-B.
719	#[test]
720	#[cfg(feature = "openh264")]
721	fn cmaf_avc3_decodes_length_prefixed_samples() {
722		let mut catalog = hang::catalog::VideoConfig::new(hang::catalog::H264 {
723			inline: true,
724			profile: 0x42,
725			constraints: 0xc0,
726			level: 0x1f,
727		});
728		catalog.container = hang::catalog::Container::Cmaf {
729			init: bytes::Bytes::new(),
730		};
731		// configurationVersion, profile, compatibility, level, 4-byte lengths, no SPS, no PPS.
732		catalog.description = Some(bytes::Bytes::from_static(&[0x01, 0x42, 0xc0, 0x1f, 0xff, 0xe0, 0x00]));
733
734		let mut decoder = super::Decoder::new(&catalog, &decode_config(super::Backend::Software)).unwrap();
735		let mut encoder = h264_software_encoder(gray_size());
736		let mut decoded = Vec::new();
737		for i in 0..5u64 {
738			let keyframe = i == 0;
739			if keyframe {
740				encoder.cut().unwrap();
741			}
742			for encoded in encoder.encode_all(&gray_frame(i)).unwrap() {
743				let sample = length_prefixed(&encoded.payload);
744				decoded.extend(decoder.decode_all(&sample, encoded.timestamp, keyframe).unwrap());
745			}
746		}
747		decoded.extend(decoder.flush_all().unwrap());
748
749		assert!(!decoded.is_empty(), "decoder produced no frames");
750		for out in &decoded {
751			assert_gray(&out.surface.to_i420().unwrap(), 320, 240);
752		}
753	}
754
755	/// An Annex-B H.265 track exported to fMP4 and imported back is a CMAF hev1
756	/// track: length-prefixed samples, parameter sets in band. The decoder reads the
757	/// framing from the container and hands the backend start-coded NAL units.
758	#[tokio::test]
759	async fn hev1_cmaf_round_trip_reaches_the_backend_as_annexb() {
760		let (origin, driver) = moq_net::origin::Producer::new(Default::default());
761		tokio::spawn(moq_net::time::run(driver));
762		let source = origin.route("test", Default::default()).unwrap();
763		let mut source_catalog =
764			moq_mux::catalog::Producer::new(&mut source.broadcast().clone(), moq_mux::catalog::Config::default())
765				.unwrap();
766		let track = source
767			.broadcast()
768			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
769			.unwrap();
770		let mut config = hev1_catalog(true);
771		config.coded_width = Some(64);
772		config.coded_height = Some(64);
773		source_catalog
774			.modify(source_catalog.next_timestamp())
775			.unwrap()
776			.video
777			.renditions
778			.insert("video".to_string(), config);
779		let mut producer = moq_mux::container::Producer::new(
780			track,
781			moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video),
782		);
783		producer
784			.write(moq_mux::container::Frame {
785				timestamp: Timestamp::from_micros(0).unwrap(),
786				decode: None,
787				duration: Some(Timestamp::from_micros(33_333).unwrap()),
788				payload: hevc_keyframe(),
789				keyframe: true,
790			})
791			.unwrap();
792		let _finished = producer.finish().unwrap();
793
794		let broadcast = origin.consume().request("test", None).await.unwrap();
795		let catalog = moq_mux::catalog::Consumer::<()>::new(&broadcast, moq_mux::catalog::CatalogFormat::Hang)
796			.await
797			.unwrap();
798		let mut export =
799			moq_mux::container::fmp4::Export::new(moq_mux::Source::new(origin.consume(), broadcast), catalog)
800				.with_delay(moq_mux::container::Delay::default().with_max(std::time::Duration::from_secs(30)));
801		let init = export.next().await.unwrap().expect("CMAF init");
802		let fragment = export.next().await.unwrap().expect("CMAF fragment");
803
804		let mut broadcast = moq_net::broadcast::Info::new().produce();
805		let subscriber = broadcast.consume();
806		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
807		let mut import = moq_mux::container::fmp4::Import::new(broadcast, catalog.reserve()).with_cmaf(true);
808		import.decode(&init).unwrap();
809		import.decode(&fragment).unwrap();
810
811		let snapshot = catalog.snapshot();
812		let (name, config) = snapshot.video.renditions.iter().next().expect("video rendition");
813		let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
814			panic!("expected H.265, got {}", config.codec);
815		};
816		assert!(h265.in_band, "the export writes hev1");
817		assert!(matches!(config.container, hang::catalog::Container::Cmaf { .. }));
818
819		let track = subscriber
820			.track(name)
821			.unwrap()
822			.subscribe(
823				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
824					moq_net::track::Start::Live {
825						min: Some(std::time::Duration::from_secs(30)),
826						max: Some(std::time::Duration::from_secs(30)),
827					},
828				)]),
829			)
830			.await
831			.unwrap();
832		let mut track =
833			moq_mux::container::Consumer::new(track, moq_mux::catalog::hang::Wire::try_from(config).unwrap());
834		let sample = loop {
835			let read = track.read().await.unwrap().expect("an imported sample");
836			if let moq_mux::container::Read::Frame { frame, .. } = read {
837				break frame;
838			}
839		};
840		assert!(sample.keyframe);
841
842		let decoder = super::Decoder::new(
843			config,
844			&decode_config(super::Backend::Named(probe::BUFFERED_NAME.into())),
845		)
846		.unwrap();
847		let access_unit = decoder
848			.conversion
849			.access_unit(&sample.payload, sample.keyframe)
850			.unwrap();
851		let types = hevc_nal_types(&access_unit);
852		// VPS (32), SPS (33), PPS (34), then the IDR_W_RADL slice (20): every NAL
853		// found by its start code, and the parameter sets ahead of the slice.
854		assert_eq!(types.first(), Some(&32), "{types:?}");
855		assert!(types.contains(&33) && types.contains(&34), "{types:?}");
856		assert_eq!(types.last(), Some(&20), "{types:?}");
857	}
858
859	/// One keyframe of a 64x64 HEVC stream from x265, as Annex-B.
860	fn hevc_keyframe() -> bytes::Bytes {
861		const VPS: &[u8] = &[
862			0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x02, 0x20, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00,
863			0x03, 0x00, 0x1e, 0x95, 0x98, 0x09,
864		];
865		const SPS: &[u8] = &[
866			0x42, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x1e,
867			0xa0, 0x20, 0x81, 0x04, 0xd9, 0x65, 0x66, 0x92, 0x4c, 0xaf, 0x01, 0x68, 0x08, 0x00, 0x00, 0x03, 0x00, 0x08,
868			0x00, 0x00, 0x03, 0x00, 0xf0, 0x40,
869		];
870		const PPS: &[u8] = &[0x44, 0x01, 0xc1, 0x72, 0xb4, 0x22, 0x40];
871		const IDR: &[u8] = &[0x28, 0x01, 0xaf, 0x08, 0x60, 0xf9, 0x2a, 0x5c, 0xf3, 0x65, 0x62, 0xe8];
872		let mut keyframe = Vec::new();
873		for nal in [VPS, SPS, PPS, IDR] {
874			keyframe.extend_from_slice(&[0, 0, 0, 1]);
875			keyframe.extend_from_slice(nal);
876		}
877		keyframe.into()
878	}
879
880	/// The H.265 NAL unit types of an Annex-B access unit, in order.
881	fn hevc_nal_types(access_unit: &bytes::Bytes) -> Vec<u8> {
882		let mut buf = access_unit.clone();
883		let mut nals = moq_mux::codec::annexb::NalIterator::new(&mut buf);
884		let mut types = Vec::new();
885		for nal in nals.by_ref() {
886			types.push(nal.unwrap()[0] >> 1);
887		}
888		types.extend(nals.flush().unwrap().map(|nal| nal[0] >> 1));
889		types
890	}
891
892	fn hev1_catalog(in_band: bool) -> hang::catalog::VideoConfig {
893		hang::catalog::VideoConfig::new(hang::catalog::H265 {
894			in_band,
895			profile_space: 0,
896			profile_idc: 2,
897			profile_compatibility_flags: [0x20, 0, 0, 0],
898			tier_flag: false,
899			level_idc: 0x1e,
900			constraint_flags: [0x90, 0, 0, 0, 0, 0],
901		})
902	}
903
904	/// A Legacy hev1 track with an hvcC, as `moq publish fmp4` and the HLS import
905	/// publish ffmpeg's default HEVC MP4: the record says the frames are
906	/// length-prefixed, whatever the codec prefix says about the parameter sets.
907	#[test]
908	fn legacy_hev1_with_a_record_is_length_prefixed() {
909		let mut hvc1 = moq_mux::codec::h265::Hvc1::new();
910		let sample = hvc1
911			.transform(hevc_keyframe())
912			.unwrap()
913			.expect("a length-prefixed sample");
914		let mut catalog = hev1_catalog(true);
915		catalog.description = Some(hvc1.hvcc().expect("an hvcC").clone());
916
917		let decoder = super::Decoder::new(
918			&catalog,
919			&decode_config(super::Backend::Named(probe::BUFFERED_NAME.into())),
920		)
921		.unwrap();
922		let access_unit = decoder.conversion.access_unit(&sample, true).unwrap();
923		// VPS (32), SPS (33), PPS (34) from the record, then the IDR_W_RADL slice (20).
924		assert_eq!(hevc_nal_types(&access_unit), [32, 33, 34, 20]);
925	}
926
927	/// An hvc1 track with no record carries Annex-B with its parameter sets, the
928	/// only framing that decodes without one, as H.264 reads a record-less avc1.
929	#[test]
930	fn hvc1_without_a_record_is_annexb() {
931		let decoder = super::Decoder::new(
932			&hev1_catalog(false),
933			&decode_config(super::Backend::Named(probe::BUFFERED_NAME.into())),
934		)
935		.unwrap();
936		let keyframe = hevc_keyframe();
937		let access_unit = decoder.conversion.access_unit(&keyframe, true).unwrap();
938		assert_eq!(hevc_nal_types(&access_unit), [32, 33, 34, 20]);
939	}
940
941	/// A CMAF track has no Annex-B framing, so one with no record is refused.
942	#[test]
943	fn cmaf_hev1_without_a_record_is_refused() {
944		let mut catalog = hev1_catalog(true);
945		catalog.container = hang::catalog::Container::Cmaf {
946			init: bytes::Bytes::new(),
947		};
948		let config = decode_config(super::Backend::Named(probe::BUFFERED_NAME.into()));
949		assert!(super::Decoder::new(&catalog, &config).is_err());
950	}
951
952	/// A reordering backend still holds the old sequence's last picture when a
953	/// keyframe switches space, and that picture keeps the space it was coded
954	/// in.
955	#[test]
956	#[cfg(feature = "openh264")]
957	fn a_held_picture_keeps_the_space_it_was_coded_in() {
958		use crate::Color;
959
960		let size = crate::Size::new(64, 64);
961		let keyframe = |color: Color| {
962			let mut encoder = Encoder::new(&EncodeConfig {
963				backend: EncodeBackend::Software,
964				color: Some(color),
965				..EncodeConfig::new(size.width, size.height, crate::FrameRate::new(30, 1).unwrap())
966			})
967			.unwrap();
968			encoder.cut().unwrap();
969			let i420 = I420::new(size, vec![0x80; I420::len(size).unwrap()]).unwrap();
970			let frame = Frame::new(
971				Timestamp::from_micros(0).unwrap(),
972				Surface::I420(i420.with_color(color)),
973			);
974			encoder.encode_all(&frame).unwrap().remove(0).payload
975		};
976		let (first, second) = (
977			Timestamp::from_micros(0).unwrap(),
978			Timestamp::from_micros(33_333).unwrap(),
979		);
980
981		let kind = super::Backend::Named(probe::BUFFERED_NAME.into());
982		let mut decoder = super::Decoder::new(&probe_catalog(), &decode_config(kind)).unwrap();
983		assert!(
984			decoder
985				.decode_all(&keyframe(Color::BT709), first, true)
986				.unwrap()
987				.is_empty()
988		);
989		let held = decoder.decode_all(&keyframe(Color::BT601), second, true).unwrap();
990		assert_eq!(held.len(), 1);
991		assert_eq!(held[0].timestamp, first);
992		assert_eq!(held[0].surface.color(), Some(Color::BT709));
993		let tail = decoder.flush_all().unwrap();
994		assert_eq!(tail[0].timestamp, second);
995		assert_eq!(tail[0].surface.color(), Some(Color::BT601));
996	}
997
998	/// The colour switches a decoder waits on stay bounded whatever a publisher's
999	/// keyframes signal: spaces that alternate while no picture comes back, and
1000	/// keyframe timestamps that run backwards.
1001	#[test]
1002	fn color_switches_stay_bounded() {
1003		let mut catalog = hang::catalog::VideoConfig::new(hang::catalog::H265 {
1004			in_band: true,
1005			profile_space: 0,
1006			profile_idc: 2,
1007			profile_compatibility_flags: [0x20, 0, 0, 0],
1008			tier_flag: false,
1009			level_idc: 0x1e,
1010			constraint_flags: [0x90, 0, 0, 0, 0, 0],
1011		});
1012		catalog.coded_width = Some(64);
1013		catalog.coded_height = Some(64);
1014		let kind = super::Backend::Named(probe::HOLDING_NAME.into());
1015		let mut decoder = super::Decoder::new(&catalog, &decode_config(kind)).unwrap();
1016		let keyframe = |index: u64| {
1017			let sps = match index % 2 {
1018				0 => super::super::vui::SPS_HDR10,
1019				_ => super::super::vui::SPS_NVENC,
1020			};
1021			bytes::Bytes::from([&[0, 0, 0, 1], sps].concat())
1022		};
1023
1024		for index in 0..100u64 {
1025			let at = Timestamp::from_micros(index * 1_000).unwrap();
1026			decoder.decode(&keyframe(index), at, true).unwrap();
1027			assert!(decoder.switches.len() <= super::SWITCHES);
1028		}
1029		assert_eq!(decoder.switches.len(), super::SWITCHES);
1030		for index in (0..100u64).rev() {
1031			let at = Timestamp::from_micros(index).unwrap();
1032			decoder.decode(&keyframe(index), at, true).unwrap();
1033			assert!(
1034				decoder.switches.len() <= 1,
1035				"a switch after a later keyframe stays queued"
1036			);
1037		}
1038	}
1039
1040	/// A VP9 catalog that declares BT.2020 PQ labels the pictures a backend
1041	/// hands back unlabelled with it, rather than the coded size's guess; one
1042	/// with the codec string's defaults keeps the guess.
1043	#[test]
1044	fn a_declared_vp9_space_labels_the_pictures() {
1045		use crate::Color;
1046		use crate::color::{Matrix, Primaries, Range, Transfer};
1047
1048		// SD, so the guess (BT.601) differs from the codec string's default.
1049		let color = |vp9: hang::catalog::VP9| {
1050			let mut catalog = hang::catalog::VideoConfig::new(hang::catalog::VP9 { bit_depth: 8, ..vp9 });
1051			catalog.coded_width = Some(640);
1052			catalog.coded_height = Some(480);
1053			let kind = super::Backend::Named(probe::BUFFERED_NAME.into());
1054			let mut decoder = super::Decoder::new(&catalog, &decode_config(kind)).unwrap();
1055			let payload = bytes::Bytes::from_static(&[0]);
1056			decoder
1057				.decode_all(&payload, Timestamp::from_micros(0).unwrap(), true)
1058				.unwrap();
1059			decoder.flush_all().unwrap().remove(0).surface.color()
1060		};
1061
1062		let pq = hang::catalog::VP9 {
1063			color_primaries: 9,
1064			transfer_characteristics: 16,
1065			matrix_coefficients: 9,
1066			..Default::default()
1067		};
1068		let expected = Color {
1069			matrix: Matrix::Bt2020,
1070			range: Range::Limited,
1071			primaries: Primaries::Bt2020,
1072			transfer: Transfer::Pq,
1073		};
1074		assert_eq!(color(pq), Some(expected));
1075		assert_eq!(color(Default::default()), Some(Color::BT601));
1076	}
1077
1078	/// A keyframe the backend fails to decode leaves the gate closed, so the
1079	/// deltas behind it never reach a codec holding no reference for them.
1080	#[test]
1081	fn a_keyframe_that_fails_to_decode_keeps_the_gate_closed() {
1082		let kind = super::Backend::Named(probe::IMMEDIATE_NAME.into());
1083		let mut decoder = super::Decoder::new(&probe_catalog(), &decode_config(kind)).unwrap();
1084		let at = |micros| Timestamp::from_micros(micros).unwrap();
1085
1086		let corrupt = bytes::Bytes::from_static(probe::CORRUPT);
1087		assert!(decoder.decode_all(&corrupt, at(0), true).is_err());
1088		let delta = bytes::Bytes::from_static(&[0]);
1089		assert!(decoder.decode_all(&delta, at(33_333), false).unwrap().is_empty());
1090
1091		// The next keyframe that decodes opens it.
1092		assert_eq!(decoder.decode_all(&delta, at(66_666), true).unwrap().len(), 1);
1093		assert_eq!(decoder.decode_all(&delta, at(99_999), false).unwrap().len(), 1);
1094
1095		// And one that fails mid-stream closes it again.
1096		assert!(decoder.decode_all(&corrupt, at(133_332), true).is_err());
1097		assert!(decoder.decode_all(&delta, at(166_665), false).unwrap().is_empty());
1098	}
1099
1100	/// An inline-H.264 catalog the test probes accept.
1101	fn probe_catalog() -> hang::catalog::VideoConfig {
1102		hang::catalog::VideoConfig::new(hang::catalog::H264 {
1103			inline: true,
1104			profile: 0x42,
1105			constraints: 0,
1106			level: 30,
1107		})
1108	}
1109
1110	/// The native probe opened through the front end with `output` and
1111	/// `scale_hint`, and the frame it decodes one access unit to.
1112	fn decode_native(output: crate::Output, scale_hint: Option<crate::Size>) -> Frame {
1113		let config = super::Config {
1114			backend: super::Backend::Named(probe::NATIVE_NAME.into()),
1115			output,
1116			scale_hint,
1117			..Default::default()
1118		};
1119		let mut decoder = super::Decoder::new(&probe_catalog(), &config).expect("the native probe opens");
1120		let mut frames = decoder
1121			.decode_all(
1122				&bytes::Bytes::from_static(b"access unit"),
1123				Timestamp::from_micros(0).unwrap(),
1124				true,
1125			)
1126			.unwrap();
1127		assert_eq!(frames.len(), 1, "the probe decodes one picture per access unit");
1128		frames.pop().unwrap()
1129	}
1130
1131	/// The output choice and the scale hint reach the backend as configured,
1132	/// through the same front end every consumer opens through.
1133	#[test]
1134	fn output_and_scale_hint_reach_the_backend() {
1135		let _probe = probe::native_exclusive();
1136		let hint = crate::Size::new(160, 120);
1137		decode_native(crate::Output::Cpu, Some(hint));
1138
1139		let opened = probe::native_opened().expect("the backend recorded its config");
1140		assert_eq!(opened.output, crate::Output::Cpu);
1141		assert_eq!(opened.scale_hint, Some(hint));
1142	}
1143
1144	/// The catalog's coded size reaches the backends only when the description's
1145	/// SPS pins it. Otherwise it is a ceiling the picture resizes below in band,
1146	/// so a device must not refuse the stream by it.
1147	#[test]
1148	fn only_a_pinned_size_reaches_the_backends() {
1149		let mut catalog = probe_catalog();
1150		catalog.coded_width = Some(8192);
1151		catalog.coded_height = Some(8192);
1152
1153		let in_band = super::stream(&catalog, Codec::H264, &super::Conversion::Passthrough);
1154		assert_eq!(in_band.size, None);
1155
1156		// A description with only a PPS leaves the SPS, and so the size, in band.
1157		let unpinned = super::Conversion::LengthPrefixed {
1158			length_size: 4,
1159			keyframe_prefix: bytes::Bytes::from_static(b"\0\0\0\x01pps"),
1160			pins_size: false,
1161		};
1162		let pps_only = super::stream(&catalog, Codec::H264, &unpinned);
1163		assert_eq!(pps_only.size, None);
1164		assert!(pps_only.parameter_sets.is_some());
1165
1166		let pinned = super::Conversion::LengthPrefixed {
1167			length_size: 4,
1168			keyframe_prefix: bytes::Bytes::from_static(b"\0\0\0\x01sps"),
1169			pins_size: true,
1170		};
1171		let described = super::stream(&catalog, Codec::H264, &pinned);
1172		assert_eq!(described.size, Some(crate::Size::new(8192, 8192)));
1173	}
1174
1175	/// CPU output is enforced by the front end, so a backend that hands back
1176	/// its native surface still delivers I420, and native output leaves the
1177	/// surface alone.
1178	///
1179	/// Only Apple platforms can build a native surface without a device, so this is
1180	/// where the conversion is exercised; elsewhere the probe's pictures are
1181	/// already CPU pixels and the assertion pins that native output does not
1182	/// invent a download.
1183	#[test]
1184	fn cpu_output_converts_native_frames() {
1185		let _probe = probe::native_exclusive();
1186		let cpu = decode_native(crate::Output::Cpu, None);
1187		assert!(
1188			matches!(cpu.surface, Surface::I420(_)),
1189			"CPU output delivered a native surface"
1190		);
1191		assert_eq!(cpu.size(), probe::SIZE);
1192
1193		let native = decode_native(crate::Output::Native, None);
1194		#[cfg(apple)]
1195		assert!(
1196			matches!(native.surface, Surface::PixelBuffer(_)),
1197			"native output downloaded the picture"
1198		);
1199		#[cfg(not(apple))]
1200		assert!(matches!(native.surface, Surface::I420(_)));
1201	}
1202
1203	/// The scale hint is only a hint: a backend without a scaler decodes at the
1204	/// stream's size, and the exact size comes from an explicit resize.
1205	#[test]
1206	fn scale_hint_is_not_enforced() {
1207		let _probe = probe::native_exclusive();
1208		let target = crate::Size::new(160, 120);
1209		let frame = decode_native(crate::Output::Cpu, Some(target));
1210		assert_eq!(frame.size(), probe::SIZE, "the front end scaled behind the backend");
1211
1212		let resized = frame.resize(target, &crate::resize::Config::default()).unwrap();
1213		assert_eq!(resized.size(), target);
1214	}
1215
1216	/// A hint no backend could honor is refused when the decoder opens, for
1217	/// every backend, rather than carried by the ones that ignore it.
1218	#[test]
1219	fn odd_scale_hint_is_refused() {
1220		let _probe = probe::native_exclusive();
1221		let config = super::Config {
1222			backend: super::Backend::Named(probe::NATIVE_NAME.into()),
1223			scale_hint: Some(crate::Size::new(161, 121)),
1224			..super::Config::new()
1225		};
1226		let Err(err) = super::Decoder::new(&probe_catalog(), &config) else {
1227			panic!("an odd scale hint opened a decoder");
1228		};
1229		assert!(
1230			!matches!(err, crate::Error::NoDecoder(_)),
1231			"refused for the wrong reason: {err}"
1232		);
1233		assert!(
1234			probe::native_opened().is_none(),
1235			"the backend was opened before the hint was checked"
1236		);
1237	}
1238
1239	#[test]
1240	fn av1_is_supported_by_hardware_only() {
1241		let catalog = hang::catalog::VideoConfig::new(hang::catalog::AV1::default());
1242		let config = decode_config(super::Backend::Software);
1243		let Err(err) = super::Decoder::new(&catalog, &config) else {
1244			panic!("software AV1 decode unexpectedly opened");
1245		};
1246		assert!(matches!(err, crate::Error::UnsupportedCodec(_)), "{err:?}");
1247	}
1248
1249	#[test]
1250	fn av1_rejects_unsupported_catalog_shape() {
1251		let av1 = hang::catalog::AV1 {
1252			bitdepth: 10,
1253			..hang::catalog::AV1::default()
1254		};
1255		let catalog = hang::catalog::VideoConfig::new(av1);
1256		let config = decode_config(super::Backend::Auto);
1257		let Err(err) = super::Decoder::new(&catalog, &config) else {
1258			panic!("10-bit AV1 decode unexpectedly opened");
1259		};
1260		assert!(matches!(err, crate::Error::UnsupportedCodec(_)));
1261	}
1262
1263	#[cfg(all(apple, feature = "openh264"))]
1264	#[test]
1265	fn videotoolbox_round_trip() {
1266		let decoder = backend::open(
1267			&Codec::H264.into(),
1268			&decode_config(super::Backend::Named("videotoolbox".into())),
1269		)
1270		.expect("videotoolbox decoder");
1271		round_trip(h264_software_encoder(gray_size()), decoder, "videotoolbox");
1272	}
1273
1274	/// With the OpenH264 fallback compiled in beside the platform's hardware
1275	/// codec, automatic selection opens the hardware one to encode and to decode.
1276	#[cfg(all(feature = "openh264", any(apple, all(target_os = "android", feature = "mediacodec"))))]
1277	#[cfg_attr(
1278		target_os = "android",
1279		ignore = "needs an Android device or emulator: just rs android-test"
1280	)]
1281	#[test]
1282	fn auto_prefers_hardware_over_openh264() {
1283		let hardware = if cfg!(target_os = "android") {
1284			"mediacodec"
1285		} else {
1286			"videotoolbox"
1287		};
1288		// The fallback opens here, so passing it over below is selection's choice.
1289		assert_eq!(h264_software_encoder(gray_size()).name(), "openh264");
1290
1291		let size = gray_size();
1292		let encoder = Encoder::new(&EncodeConfig::new(
1293			size.width,
1294			size.height,
1295			crate::FrameRate::new(30, 1).unwrap(),
1296		))
1297		.expect("an automatic encoder");
1298		assert_eq!(encoder.name(), hardware);
1299		let decoder = backend::open(&Codec::H264.into(), &super::Config::new()).expect("an automatic decoder");
1300		round_trip(encoder, decoder, hardware);
1301	}
1302
1303	/// Encode `count` gray frames and decode them, returning the decoded pictures.
1304	/// The shared setup for the residency and re-encode tests below.
1305	#[cfg(all(apple, feature = "openh264"))]
1306	fn decode_gray(count: u64) -> Vec<Frame> {
1307		let mut encoder = h264_software_encoder(gray_size());
1308		let mut decoder = backend::open(
1309			&Codec::H264.into(),
1310			&decode_config(super::Backend::Named("videotoolbox".into())),
1311		)
1312		.expect("videotoolbox decoder");
1313
1314		let mut decoded = Vec::new();
1315		for i in 0..count {
1316			let keyframe = i == 0;
1317			if keyframe {
1318				encoder.cut().unwrap();
1319			}
1320			for encoded in encoder.encode_all(&gray_frame(i)).unwrap() {
1321				decoded.extend(
1322					decoder
1323						.decode_all(encoded.payload, encoded.timestamp, keyframe)
1324						.unwrap(),
1325				);
1326			}
1327		}
1328
1329		assert!(!decoded.is_empty(), "decoder produced no frames");
1330		decoded
1331	}
1332
1333	/// VideoToolbox hands back its `CVPixelBuffer` rather than packing to I420 in
1334	/// the output callback, which is what leaves a render or re-encode path free of
1335	/// a CPU round trip. `round_trip` above only checks the pixels, so it passes
1336	/// either way: this is the test that pins the frame's residency.
1337	#[cfg(all(apple, feature = "openh264"))]
1338	#[test]
1339	fn videotoolbox_decode_stays_gpu_resident() {
1340		for out in &decode_gray(3) {
1341			assert!(
1342				matches!(out.surface, Surface::PixelBuffer(_)),
1343				"VideoToolbox decode downloaded to the CPU instead of keeping its surface"
1344			);
1345		}
1346	}
1347
1348	/// The multi-rung transcode path stays on hardware through decode, resize, and
1349	/// encode. The residency assertion catches a CPU fallback even when the pixels
1350	/// and dimensions still look right.
1351	#[cfg(all(apple, feature = "openh264"))]
1352	#[test]
1353	fn videotoolbox_resized_surface_reencodes_in_place() {
1354		let decoded = decode_gray(3);
1355		let resized: Vec<_> = decoded
1356			.iter()
1357			.map(|frame| {
1358				frame
1359					.resize(crate::Size::new(160, 120), &crate::resize::Config::default())
1360					.unwrap()
1361			})
1362			.collect();
1363		for frame in &resized {
1364			assert_eq!(frame.size(), crate::Size::new(160, 120));
1365			assert!(
1366				matches!(frame.surface, Surface::PixelBuffer(_)),
1367				"VideoToolbox resize downloaded to the CPU"
1368			);
1369		}
1370
1371		let encoder = Encoder::new(&EncodeConfig {
1372			backend: EncodeBackend::Named("videotoolbox".into()),
1373			..EncodeConfig::new(160, 120, crate::FrameRate::new(30, 1).unwrap())
1374		});
1375		let Ok(mut encoder) = encoder else {
1376			eprintln!("skipping: no VideoToolbox H.264 hardware encoder available");
1377			return;
1378		};
1379
1380		let mut packets = 0;
1381		for (i, out) in resized.iter().enumerate() {
1382			if i == 0 {
1383				encoder.cut().unwrap();
1384			}
1385			packets += encoder.encode_all(out).unwrap().len();
1386		}
1387		packets += encoder.flush_all().unwrap().len();
1388
1389		assert!(packets > 0, "re-encoding decoded surfaces produced no packets");
1390	}
1391
1392	/// H.265 has no software path, so the HEVC round-trip rides VideoToolbox on
1393	/// both ends: hardware HEVC encode emitting hev1 (inline VPS/SPS/PPS) and
1394	/// hardware HEVC decode. Skips cleanly on a Mac without HEVC hardware (older
1395	/// Intel models predating the HEVC encoder).
1396	#[cfg(apple)]
1397	#[test]
1398	fn videotoolbox_hevc_round_trip() {
1399		let encoder = Encoder::new(&EncodeConfig {
1400			backend: EncodeBackend::Named("videotoolbox".into()),
1401			codec: crate::encode::Codec::H265,
1402			..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1403		});
1404		let Ok(encoder) = encoder else {
1405			eprintln!("skipping: no VideoToolbox H.265 hardware encoder available");
1406			return;
1407		};
1408		let decoder = backend::open(
1409			&Codec::H265.into(),
1410			&decode_config(super::Backend::Named("videotoolbox".into())),
1411		)
1412		.expect("videotoolbox H.265 decoder");
1413		round_trip(encoder, decoder, "videotoolbox");
1414	}
1415
1416	/// The same over VA-API: HEVC encode emitting hev1 and HEVC decode, both on
1417	/// the render node the two share. Skips without a VA-API H.265 encoder, which
1418	/// includes radeonsi at this size (its H.265 minimum width is 384).
1419	#[cfg(all(target_os = "linux", feature = "vaapi"))]
1420	#[test]
1421	fn vaapi_hevc_round_trip() {
1422		let encoder = match Encoder::new(&EncodeConfig {
1423			backend: EncodeBackend::Named("vaapi".into()),
1424			codec: crate::encode::Codec::H265,
1425			..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1426		}) {
1427			Ok(encoder) => encoder,
1428			// No H.265 encoder, or none this small: AMD's VCN 5 starts at 384 wide.
1429			Err(err) => {
1430				eprintln!("skipping: no VA-API H.265 encoder at 320x240: {err}");
1431				return;
1432			}
1433		};
1434		let decoder = backend::open(
1435			&Codec::H265.into(),
1436			&decode_config(super::Backend::Named("vaapi".into())),
1437		)
1438		.expect("a VA-API H.265 decoder beside the encoder");
1439		round_trip(encoder, decoder, "vaapi");
1440	}
1441
1442	#[cfg(all(target_os = "windows", feature = "openh264"))]
1443	#[test]
1444	fn mediafoundation_round_trip() {
1445		// Requires a hardware decoder MFT (GPU). Skip on machines without one
1446		// rather than fail: CI runners are often headless.
1447		let Ok(decoder) = backend::open(
1448			&Codec::H264.into(),
1449			&decode_config(super::Backend::Named("mediafoundation".into())),
1450		) else {
1451			eprintln!("skipping: no Media Foundation H.264 hardware decoder available");
1452			return;
1453		};
1454		round_trip(h264_software_encoder(gray_size()), decoder, "mediafoundation");
1455	}
1456
1457	/// A distinct RGB level per frame index, so a caller holding several decoded
1458	/// pictures at once can tell them apart. Spaced far enough apart that lossy
1459	/// coding can't blur two of them together, which caps how long a stream this
1460	/// builds.
1461	#[cfg(all(target_os = "windows", feature = "openh264"))]
1462	fn level(index: u64) -> u8 {
1463		u8::try_from(0x20 + index * 0x10).expect("test stream is short enough to keep its levels distinct")
1464	}
1465
1466	/// The limited-range BT.601 luma a flat [`level`] frame decodes to.
1467	#[cfg(all(target_os = "windows", feature = "openh264"))]
1468	fn expected_luma(level: u8) -> u32 {
1469		16 + (219 * level as u32) / 255
1470	}
1471
1472	/// Decode `count` frames of a `size` [`level`] stream through the Media
1473	/// Foundation hardware decoder, holding every picture rather than consuming it
1474	/// as it arrives. `None` when this machine has no hardware decoder.
1475	#[cfg(all(target_os = "windows", feature = "openh264"))]
1476	fn decode_levels(count: u64, size: crate::Size) -> Option<(Vec<Frame>, Box<dyn backend::Backend>)> {
1477		let mut encoder = h264_software_encoder(size);
1478		let decoder = backend::open(
1479			&Codec::H264.into(),
1480			&decode_config(super::Backend::Named("mediafoundation".into())),
1481		);
1482		let Ok(mut decoder) = decoder else {
1483			eprintln!("skipping: no Media Foundation H.264 hardware decoder available");
1484			return None;
1485		};
1486
1487		let mut decoded = Vec::new();
1488		for i in 0..count {
1489			let keyframe = i == 0;
1490			if keyframe {
1491				encoder.cut().unwrap();
1492			}
1493			for encoded in encoder.encode_all(&flat_frame(i, level(i), size)).unwrap() {
1494				decoded.extend(
1495					decoder
1496						.decode_all(encoded.payload, encoded.timestamp, keyframe)
1497						.unwrap(),
1498				);
1499			}
1500		}
1501
1502		assert!(!decoded.is_empty(), "decoder produced no frames");
1503		// The decoder goes back to the caller rather than being dropped here: its
1504		// `ComGuard` tears Media Foundation down for the whole thread, and a test
1505		// that keeps working with the frames afterwards would be doing so in a
1506		// process no application resembles.
1507		Some((decoded, decoder))
1508	}
1509
1510	/// Every plane of a decoded flat frame: its average luma, and its average U and
1511	/// V, which stay neutral because the source is gray. Chroma is the half that
1512	/// catches a bad plane split, since the UV plane sits after the *texture's* luma
1513	/// rows rather than the frame's.
1514	#[cfg(all(target_os = "windows", feature = "openh264"))]
1515	fn plane_averages(frame: &Frame) -> (u32, u32, u32) {
1516		let i420 = frame.surface.to_i420().unwrap();
1517		let average = |plane: &[u8]| plane.iter().map(|&b| b as u32).sum::<u32>() / plane.len() as u32;
1518		(average(i420.y()), average(i420.u()), average(i420.v()))
1519	}
1520
1521	/// A decoded frame comes back as a GPU texture rather than downloaded pixels,
1522	/// which is what leaves a render or re-encode path free of a CPU round trip.
1523	/// `round_trip` above only checks the pixels, so it passes either way: this is
1524	/// the test that pins the frame's residency.
1525	#[cfg(all(target_os = "windows", feature = "openh264"))]
1526	#[test]
1527	fn mediafoundation_decode_stays_gpu_resident() {
1528		let Some((decoded, _decoder)) = decode_levels(3, gray_size()) else {
1529			return;
1530		};
1531		for out in &decoded {
1532			assert!(
1533				matches!(out.surface, Surface::Texture(_)),
1534				"Media Foundation decode downloaded to the CPU instead of keeping its picture on the GPU"
1535			);
1536		}
1537	}
1538
1539	/// Held frames keep their own pixels. The decoder decodes into a short array of
1540	/// picture buffers and recycles a slice as soon as its sample is released, so
1541	/// handing that slice out as the frame would let later pictures overwrite
1542	/// frames a consumer is still holding: the decoder's texture has to be copied
1543	/// into one of ours on the way out.
1544	///
1545	/// A distinct level per frame is what makes that visible; a fixed test picture
1546	/// looks identical either way.
1547	#[cfg(all(target_os = "windows", feature = "openh264"))]
1548	#[test]
1549	fn mediafoundation_held_frames_keep_their_pixels() {
1550		// More frames than the decoder's pool has slices (8 on the hardware this
1551		// was written against, one per picture), so it has to recycle the slices
1552		// the earliest frames came out of.
1553		let Some((decoded, _decoder)) = decode_levels(12, gray_size()) else {
1554			return;
1555		};
1556
1557		for (i, out) in decoded.iter().enumerate() {
1558			let (luma, _, _) = plane_averages(out);
1559			let want = expected_luma(level(i as u64));
1560			// Half the gap between adjacent levels, so a frame showing a neighbour's
1561			// picture fails rather than squeaking through.
1562			assert!(
1563				luma.abs_diff(want) <= 6,
1564				"frame {i} decoded to luma {luma}, expected about {want}: the decoder recycled its picture buffer"
1565			);
1566		}
1567	}
1568
1569	/// A height that isn't a whole number of macroblocks is coded padded (180 rows
1570	/// become 192), and the frame has to be the picture rather than the padding.
1571	///
1572	/// Chroma is the assertion that bites: the interleaved UV plane starts after
1573	/// the *texture's* luma rows, so reading a padded texture as if it were the
1574	/// frame lands in the last luma rows and colors the picture with them.
1575	#[cfg(all(target_os = "windows", feature = "openh264"))]
1576	#[test]
1577	fn mediafoundation_decode_crops_coded_padding() {
1578		let size = crate::Size::new(320, 180);
1579		let Some((decoded, _decoder)) = decode_levels(3, size) else {
1580			return;
1581		};
1582
1583		for (i, out) in decoded.iter().enumerate() {
1584			assert_eq!(out.size(), size, "frame {i} came back at the coded size");
1585			let (luma, u, v) = plane_averages(out);
1586			assert!(
1587				luma.abs_diff(expected_luma(level(i as u64))) <= 6,
1588				"frame {i} luma {luma} is not its own picture"
1589			);
1590			// Gray in, so both chroma planes stay neutral.
1591			assert!(
1592				u.abs_diff(128) <= 4 && v.abs_diff(128) <= 4,
1593				"frame {i} chroma ({u}, {v}) is not neutral: the plane split read into the padding"
1594			);
1595		}
1596	}
1597
1598	/// The transcode path stays on hardware from decode through re-encode: the
1599	/// hardware encoder MFT takes the decoded texture on the same Direct3D11
1600	/// device, no download and no upload. The residency assertion catches a CPU
1601	/// fallback even when the pixels and dimensions still look right.
1602	///
1603	/// Decoding what comes back is the other half, and the one that pins the blit:
1604	/// the encoder reads the texture on its own timeline, so a copy that never
1605	/// landed still produces packets, just of the wrong picture.
1606	#[cfg(all(target_os = "windows", feature = "openh264"))]
1607	#[test]
1608	fn mediafoundation_decoded_texture_reencodes_in_place() {
1609		let size = gray_size();
1610		let Some((decoded, _decoder)) = decode_levels(3, size) else {
1611			return;
1612		};
1613		for out in &decoded {
1614			assert!(
1615				matches!(out.surface, Surface::Texture(_)),
1616				"Media Foundation decode downloaded to the CPU"
1617			);
1618		}
1619
1620		let encoder = Encoder::new(&EncodeConfig {
1621			backend: EncodeBackend::Named("mediafoundation".into()),
1622			..EncodeConfig::new(size.width, size.height, crate::FrameRate::new(30, 1).unwrap())
1623		});
1624		let Ok(mut encoder) = encoder else {
1625			eprintln!("skipping: no Media Foundation H.264 hardware encoder available");
1626			return;
1627		};
1628
1629		let mut reencoded = Vec::new();
1630		for (i, out) in decoded.iter().enumerate() {
1631			if i == 0 {
1632				encoder.cut().unwrap();
1633			}
1634			reencoded.extend(encoder.encode_all(out).unwrap());
1635		}
1636		reencoded.extend(encoder.flush_all().unwrap());
1637		assert!(
1638			!reencoded.is_empty(),
1639			"re-encoding decoded textures produced no packets"
1640		);
1641
1642		// Back to pixels through the software decoder, so this leans on nothing the
1643		// hardware path just did.
1644		let mut decoder =
1645			backend::open(&Codec::H264.into(), &decode_config(super::Backend::Software)).expect("openh264 decoder");
1646		let mut out = Vec::new();
1647		for (i, encoded) in reencoded.iter().enumerate() {
1648			out.extend(
1649				decoder
1650					.decode_all(encoded.payload.clone(), encoded.timestamp, i == 0)
1651					.unwrap(),
1652			);
1653		}
1654
1655		// Every frame, not merely some: a hardware encoder holding its tail back is
1656		// what this file's flush exists to stop, and a per-frame check alone cannot
1657		// see a stream that came back one short.
1658		assert_eq!(out.len(), decoded.len(), "the re-encoded stream lost frames");
1659		for (i, frame) in out.iter().enumerate() {
1660			assert_eq!(frame.size(), size, "re-encoded frame {i} changed size");
1661			let (luma, _, _) = plane_averages(frame);
1662			let want = expected_luma(level(i as u64));
1663			assert!(
1664				luma.abs_diff(want) <= 6,
1665				"re-encoded frame {i} came back as luma {luma}, expected about {want}"
1666			);
1667		}
1668	}
1669
1670	/// The multi-rung transcode path stays on hardware through decode, resize, and
1671	/// encode: the Direct3D11 video processor scales the decoded texture on its own
1672	/// device and the encoder MFT reads the result in place. The residency
1673	/// assertion catches a CPU fallback even when the pixels and dimensions still
1674	/// look right, which is what a ladder pays for once per rung.
1675	#[cfg(all(target_os = "windows", feature = "openh264"))]
1676	#[test]
1677	#[ignore = "explicit live-DXVA GPU probe; VideoProcessorBlt can hang on affected drivers"]
1678	fn mediafoundation_resized_texture_reencodes_in_place() {
1679		let target = crate::Size::new(160, 120);
1680		let resize = crate::resize::Config::default();
1681		let Some((decoded, _decoder)) = decode_levels(3, gray_size()) else {
1682			return;
1683		};
1684		let Some(device) = decoded.iter().find_map(|frame| match &frame.surface {
1685			Surface::Texture(texture) => Some(texture.device()),
1686			_ => None,
1687		}) else {
1688			panic!("Media Foundation decode did not return a Direct3D11 texture");
1689		};
1690		if !crate::frame::d3d11::supports_nv12_render_target(device) {
1691			eprintln!("skipping: driver cannot render to NV12");
1692			return;
1693		}
1694		let resized: Vec<_> = decoded
1695			.iter()
1696			.map(|frame| frame.resize(target, &resize).unwrap())
1697			.collect();
1698		for frame in &resized {
1699			assert_eq!(frame.size(), target);
1700			assert!(
1701				matches!(frame.surface, Surface::Texture(_)),
1702				"Direct3D11 resize downloaded to the CPU"
1703			);
1704		}
1705
1706		let encoder = Encoder::new(&EncodeConfig {
1707			backend: EncodeBackend::Named("mediafoundation".into()),
1708			..EncodeConfig::new(target.width, target.height, crate::FrameRate::new(30, 1).unwrap())
1709		});
1710		let Ok(mut encoder) = encoder else {
1711			eprintln!("skipping: no Media Foundation H.264 hardware encoder available");
1712			return;
1713		};
1714
1715		let mut packets = 0;
1716		for (i, out) in resized.iter().enumerate() {
1717			if i == 0 {
1718				encoder.cut().unwrap();
1719			}
1720			packets += encoder.encode_all(out).unwrap().len();
1721		}
1722		packets += encoder.flush_all().unwrap().len();
1723
1724		assert!(packets > 0, "re-encoding resized textures produced no packets");
1725	}
1726
1727	/// H.265 has no software encoder or decoder, so the HEVC round-trip rides the
1728	/// Media Foundation hardware path on both ends: NVENC/QSV/AMF encode through an
1729	/// HEVC encoder MFT, DXVA decode through an HEVC decoder MFT. Skips cleanly when
1730	/// either is absent (no GPU, or no HEVC Video Extensions installed).
1731	#[cfg(target_os = "windows")]
1732	#[test]
1733	fn mediafoundation_hevc_round_trip() {
1734		let encoder = Encoder::new(&EncodeConfig {
1735			backend: EncodeBackend::Named("mediafoundation".into()),
1736			codec: crate::encode::Codec::H265,
1737			..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1738		});
1739		let Ok(encoder) = encoder else {
1740			eprintln!("skipping: no Media Foundation H.265 hardware encoder available");
1741			return;
1742		};
1743		let Ok(decoder) = backend::open(
1744			&Codec::H265.into(),
1745			&decode_config(super::Backend::Named("mediafoundation".into())),
1746		) else {
1747			eprintln!("skipping: no Media Foundation H.265 hardware decoder available");
1748			return;
1749		};
1750		round_trip(encoder, decoder, "mediafoundation");
1751	}
1752}