Skip to main content

moq_video/decode/backend/
mod.rs

1//! Pluggable video decoder backends.
2//!
3//! The mirror of [`encode::backend`](crate::encode). [`Backend`] is the seam
4//! between the access-unit prep (keyframe gating plus any codec-specific payload
5//! conversion, owned by [`Decoder`](super::Decoder)) and the codec itself. H.264
6//! / H.265 backends take Annex-B access units with parameter sets inline ahead
7//! of each keyframe; AV1 backends take OBU temporal units directly.
8//!
9//! [`open`] picks the best backend for a [`Codec`] and [`Config`], trying
10//! hardware candidates (platform-gated: VideoToolbox on macOS and iOS, Media Foundation
11//! / DXVA on Windows, MediaCodec on Android, NVDEC, VAAPI, then V4L2 on Linux) before
12//! the software decoders this build enables (OpenH264 for H.264, libvpx for VP8
13//! and VP9), exactly like the encode side. Only backends that support the
14//! requested codec are considered: there is no software H.265 or AV1 decoder, so
15//! those tracks have no fallback below the hardware path. VP8 / VP9 backends
16//! take one coded frame per call.
17//!
18//! A backend that fails to open either refuses the [`Stream`] or faults. A
19//! refusal is [`Error::UnsupportedCodec`]: the device answered that it cannot
20//! decode this stream, so no retry on this machine helps but another rendition
21//! may. Anything else is a fault: missing drivers, no device, or a library
22//! error. A backend that cannot tell the two apart reports a fault.
23
24use bytes::Bytes;
25use moq_net::Timestamp;
26
27use super::decoder::{Backend as Choice, Config};
28use crate::device::Drives;
29use crate::{Error, Frame, Size};
30
31#[cfg(feature = "openh264")]
32mod openh264;
33
34#[cfg(test)]
35pub(crate) mod probe;
36
37#[cfg(feature = "vpx")]
38mod vpx;
39
40#[cfg(apple)]
41mod videotoolbox;
42
43#[cfg(target_os = "windows")]
44mod mediafoundation;
45
46#[cfg(all(target_os = "android", feature = "mediacodec"))]
47mod mediacodec;
48
49#[cfg(any(
50	all(target_os = "android", feature = "mediacodec"),
51	all(target_os = "linux", any(feature = "nvidia", feature = "v4l2", feature = "vaapi")),
52))]
53mod submitted;
54
55#[cfg(all(target_os = "linux", feature = "nvidia"))]
56mod nvdec;
57
58// Crate-visible so `decode::Consumer`'s end-of-track test can name the one
59// backend that holds pictures back; nothing outside the tests reaches for it.
60#[cfg(all(target_os = "linux", feature = "vaapi"))]
61pub(crate) mod vaapi;
62
63#[cfg(all(target_os = "linux", feature = "v4l2"))]
64mod v4l2;
65
66/// The video codec a decoder handles, derived from the catalog.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum Codec {
70	/// H.264 / AVC video.
71	H264,
72	/// H.265 / HEVC video.
73	H265,
74	/// AV1 video.
75	Av1,
76	/// VP8 video.
77	Vp8,
78	/// VP9 video.
79	Vp9,
80}
81
82impl Codec {
83	fn label(self) -> &'static str {
84		match self {
85			Codec::H264 => "H.264",
86			Codec::H265 => "H.265",
87			Codec::Av1 => "AV1",
88			Codec::Vp8 => "VP8",
89			Codec::Vp9 => "VP9",
90		}
91	}
92}
93
94/// The stream a decoder opens for, as far as the catalog describes it before
95/// the first picture arrives.
96///
97/// What a backend needs to ask its device whether it decodes the stream at
98/// all. The catalog is the peer's claim, so a stream that turns out otherwise
99/// still fails at its first keyframe.
100#[derive(Clone, Debug)]
101pub(crate) struct Stream {
102	pub codec: Codec,
103	/// The H.264 `profile_idc` the codec string declares.
104	#[cfg_attr(
105		not(all(target_os = "linux", feature = "vaapi")),
106		allow(dead_code, reason = "only VA-API asks its driver by profile")
107	)]
108	pub h264_profile: Option<u8>,
109	/// The catalog's coded size, when the description's SPS pins it. It may be
110	/// the cropped picture size, so the macroblock-aligned size a decoder
111	/// allocates can be larger. Without an SPS the catalog's size is only a
112	/// ceiling the picture resizes below in band, so it says nothing a device
113	/// could refuse.
114	#[cfg_attr(
115		not(all(target_os = "linux", feature = "nvidia")),
116		allow(dead_code, reason = "only NVDEC checks a size before the first keyframe")
117	)]
118	pub size: Option<Size>,
119	/// Annex-B parameter sets from the description, for a track that carries
120	/// them out of band.
121	#[cfg_attr(
122		not(apple),
123		allow(dead_code, reason = "only VideoToolbox builds its session from them")
124	)]
125	pub parameter_sets: Option<Bytes>,
126}
127
128impl From<Codec> for Stream {
129	/// A stream of `codec` the catalog says nothing more about.
130	fn from(codec: Codec) -> Self {
131		Self {
132			codec,
133			h264_profile: None,
134			size: None,
135			parameter_sets: None,
136		}
137	}
138}
139
140/// An opened decoder. Submit prepared access units in decode order, then
141/// receive zero or more decoded frames (zero while the decoder is still
142/// buffering, e.g. before the first keyframe's parameter sets).
143///
144/// A backend that readies pictures synchronously holds them in a reused queue,
145/// so no call allocates to hand them back.
146pub(crate) trait Backend {
147	/// Submit one access unit stamped with its presentation `timestamp`.
148	/// `keyframe` marks a random-access frame. Takes an owned [`Bytes`] so a
149	/// backend can split codec units without copying.
150	/// Backends that decode one-in one-out echo the input timestamp; NVDEC and
151	/// MediaCodec thread timestamps through the codec, so they survive decoder
152	/// delay and frame reordering.
153	fn decode(&mut self, access_unit: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error>;
154
155	/// Pop the oldest ready picture, or `None` while the codec holds the rest.
156	fn receive(&mut self) -> Result<Option<Frame>, Error>;
157
158	/// Mark the end of input, so [`receive`](Self::receive) returns every picture
159	/// the codec still holds. The next access unit submitted starts new input.
160	///
161	/// Backends configured for zero delay hold nothing. A backend that reorders
162	/// pictures queues its tail here so the end of a track does not drop it.
163	fn flush(&mut self) -> Result<(), Error>;
164
165	/// Submit one access unit and collect everything it readied.
166	#[cfg(test)]
167	fn decode_all(&mut self, access_unit: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<Vec<Frame>, Error> {
168		self.decode(access_unit, timestamp, keyframe)?;
169		self.receive_all()
170	}
171
172	/// Flush and collect the tail.
173	#[cfg(test)]
174	#[allow(dead_code, reason = "only the platform backends' tests use it")]
175	fn flush_all(&mut self) -> Result<Vec<Frame>, Error> {
176		self.flush()?;
177		self.receive_all()
178	}
179
180	/// Collect everything ready.
181	#[cfg(test)]
182	fn receive_all(&mut self) -> Result<Vec<Frame>, Error> {
183		let mut frames = Vec::new();
184		while let Some(frame) = self.receive()? {
185			frames.push(frame);
186		}
187		Ok(frames)
188	}
189
190	/// The decoder name in use, e.g. `"videotoolbox"` (for logging).
191	fn name(&self) -> &str;
192}
193
194/// Every decoder backend this crate has a name for, on any platform.
195///
196/// The decode counterpart of [`encode::backend::NAMES`](crate::encode::NAMES),
197/// and platform-complete for the same reason.
198pub const NAMES: &[&str] = &[
199	"videotoolbox",
200	"mediafoundation",
201	"mediacodec",
202	"nvdec",
203	"vaapi",
204	"v4l2",
205	"openh264",
206	"vpx",
207];
208
209/// A backend opener: builds a decoder for a stream and config, refusing a
210/// stream its device cannot decode with [`Error::UnsupportedCodec`].
211type Open = fn(&Stream, &Config) -> Result<Box<dyn Backend>, Error>;
212
213/// A backend constructor: name, the codecs it can decode, and an opener.
214struct Candidate {
215	name: &'static str,
216	supports: fn(Codec) -> bool,
217	open: Open,
218	/// The kind of [`Device`](crate::Device) it opens, which a named one steers selection by.
219	drives: Drives,
220}
221
222/// Hardware backends, in priority order. Platform-gated so only the ones that
223/// could plausibly work on this target are even listed.
224const HARDWARE: &[Candidate] = &[
225	#[cfg(apple)]
226	Candidate {
227		name: videotoolbox::NAME,
228		supports: |c| matches!(c, Codec::H264 | Codec::H265),
229		open: videotoolbox::VideoToolbox::open,
230		drives: Drives::Own,
231	},
232	#[cfg(target_os = "windows")]
233	Candidate {
234		name: mediafoundation::NAME,
235		supports: |c| matches!(c, Codec::H264 | Codec::H265),
236		open: mediafoundation::MediaFoundation::open,
237		drives: Drives::Own,
238	},
239	#[cfg(all(target_os = "android", feature = "mediacodec"))]
240	Candidate {
241		name: mediacodec::NAME,
242		supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Av1),
243		open: mediacodec::MediaCodec::open,
244		drives: Drives::Own,
245	},
246	#[cfg(all(target_os = "linux", feature = "nvidia"))]
247	Candidate {
248		name: nvdec::NAME,
249		supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Av1),
250		open: nvdec::Nvdec::open,
251		drives: Drives::Nvidia,
252	},
253	#[cfg(all(target_os = "linux", feature = "vaapi"))]
254	Candidate {
255		name: vaapi::NAME,
256		supports: |c| matches!(c, Codec::H264 | Codec::H265),
257		open: vaapi::Vaapi::open,
258		drives: Drives::Render,
259	},
260	// Last of the Linux hardware decoders, for the same reason as its encode
261	// counterpart: the SoC blocks it drives are the only hardware on a board that
262	// has no NVIDIA GPU.
263	#[cfg(all(target_os = "linux", feature = "v4l2"))]
264	Candidate {
265		name: v4l2::NAME,
266		supports: |c| matches!(c, Codec::H264),
267		open: v4l2::V4l2::open,
268		drives: Drives::Video,
269	},
270];
271
272const SOFTWARE: &[Candidate] = &[
273	#[cfg(feature = "openh264")]
274	Candidate {
275		name: openh264::NAME,
276		supports: |c| matches!(c, Codec::H264),
277		open: openh264::Openh264::open,
278		drives: Drives::Own,
279	},
280	#[cfg(feature = "vpx")]
281	Candidate {
282		name: vpx::NAME,
283		supports: |c| matches!(c, Codec::Vp8 | Codec::Vp9),
284		open: vpx::Vpx::open,
285		drives: Drives::Own,
286	},
287];
288
289/// Test-only backends. Deliberately in neither list above, so `Auto` /
290/// `Hardware` / `Software` can never select one: they exist to be asked for by
291/// name.
292#[cfg(test)]
293const NAMED_ONLY: &[Candidate] = &[
294	Candidate {
295		name: probe::NAME,
296		supports: |c| matches!(c, Codec::H264),
297		open: probe::Probe::open,
298		drives: Drives::Own,
299	},
300	Candidate {
301		name: probe::BUFFERED_NAME,
302		supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Vp9),
303		open: probe::Buffered::open,
304		drives: Drives::Own,
305	},
306	Candidate {
307		name: probe::FAILING_FLUSH_NAME,
308		supports: |c| matches!(c, Codec::H264),
309		open: probe::Buffered::open_failing_flush,
310		drives: Drives::Own,
311	},
312	Candidate {
313		name: probe::REORDER_NAME,
314		supports: |c| matches!(c, Codec::H264),
315		open: probe::Reorder::open,
316		drives: Drives::Own,
317	},
318	Candidate {
319		name: probe::HOLDING_NAME,
320		supports: |c| matches!(c, Codec::H264 | Codec::H265),
321		open: probe::Reorder::open_holding,
322		drives: Drives::Own,
323	},
324	Candidate {
325		name: probe::IMMEDIATE_NAME,
326		supports: |c| matches!(c, Codec::H264),
327		open: probe::Immediate::open,
328		drives: Drives::Own,
329	},
330	Candidate {
331		name: probe::NATIVE_NAME,
332		supports: |c| matches!(c, Codec::H264),
333		open: probe::Native::open,
334		drives: Drives::Own,
335	},
336	Candidate {
337		name: probe::REFUSING_NAME,
338		supports: |c| matches!(c, Codec::H264),
339		open: probe::Refusing::open,
340		drives: Drives::Own,
341	},
342	#[cfg(not(apple))]
343	Candidate {
344		name: probe::BLOCKING_FLUSH_NAME,
345		supports: |c| matches!(c, Codec::H264),
346		open: probe::BlockingFlush::open,
347		drives: Drives::Own,
348	},
349];
350
351#[cfg(not(test))]
352const NAMED_ONLY: &[Candidate] = &[];
353
354/// A candidate paired with the tier it came from, so [`select`] can tell a
355/// software decoder that was asked for from one reached by falling past
356/// hardware that failed to open.
357struct Attempt<'a> {
358	candidate: &'a Candidate,
359	hardware: bool,
360}
361
362impl<'a> Attempt<'a> {
363	fn hardware(candidate: &'a Candidate) -> Self {
364		Self {
365			candidate,
366			hardware: true,
367		}
368	}
369
370	fn software(candidate: &'a Candidate) -> Self {
371		Self {
372			candidate,
373			hardware: false,
374		}
375	}
376}
377
378/// Open the best decoder for `codec` and `config`, trying candidates in priority
379/// order and falling back until one succeeds. Candidates that don't support the
380/// codec are skipped before they're even tried.
381pub(crate) fn open(stream: &Stream, config: &Config) -> Result<Box<dyn Backend>, Error> {
382	let attempts: Vec<Attempt> = match &config.backend {
383		Choice::Auto => HARDWARE
384			.iter()
385			.map(Attempt::hardware)
386			.chain(SOFTWARE.iter().map(Attempt::software))
387			.collect(),
388		Choice::Hardware => HARDWARE.iter().map(Attempt::hardware).collect(),
389		Choice::Software => SOFTWARE.iter().map(Attempt::software).collect(),
390		Choice::Named(name) => HARDWARE
391			.iter()
392			.map(Attempt::hardware)
393			.chain(SOFTWARE.iter().chain(NAMED_ONLY.iter()).map(Attempt::software))
394			.filter(|a| a.candidate.name == name)
395			.collect(),
396	};
397
398	select(stream, attempts, config)
399}
400
401/// Try `attempts` in order and return the first decoder that opens, warning when
402/// that means falling past hardware.
403///
404/// Fails with [`Error::UnsupportedCodec`] only when every candidate that takes
405/// the codec refused the stream: one fault among them could be what stopped a
406/// decoder that would have worked, so the whole is a fault.
407///
408/// Split out from [`open`] for the same reason as its encode counterpart: the
409/// candidate lists are platform-gated consts, so a test supplies its own
410/// attempts rather than depending on what the host GPU can do.
411fn select(stream: &Stream, attempts: Vec<Attempt>, config: &Config) -> Result<Box<dyn Backend>, Error> {
412	let codec = stream.codec;
413	// Each entry is "name: why it failed". The names alone say which backends
414	// exist, which is what a reader already knows; the reasons say why this
415	// machine has none, which is the question being asked.
416	let mut tried: Vec<String> = Vec::new();
417	let mut skipped = Vec::new();
418	// Passed over unopened for driving another device than the named one, which
419	// says nothing about the stream, so neither a refusal nor a fault.
420	let mut passed = Vec::new();
421	let mut faulted = false;
422
423	for attempt in attempts {
424		if !(attempt.candidate.supports)(codec) {
425			continue;
426		}
427
428		let name = attempt.candidate.name;
429		match config.device.takes(attempt.candidate.drives) {
430			Ok(true) => {}
431			Ok(false) => {
432				passed.push(format!("{name}: does not open {}", config.device));
433				continue;
434			}
435			// Telling whether this backend drives the named node failed, which
436			// counts against this candidate alone, as a failed open would.
437			Err(e) => {
438				tracing::debug!(decoder = name, error = %e, "decoder unavailable, trying next");
439				faulted = true;
440				tried.push(format!("{name}: {e}"));
441				if attempt.hardware {
442					skipped.push(format!("{name}: {e}"));
443				}
444				continue;
445			}
446		}
447
448		match (attempt.candidate.open)(stream, config) {
449			Ok(backend) => {
450				// Same reasoning as the encode side: a compiled-in hardware decoder that
451				// fails to open, or is passed over for another device, is otherwise
452				// invisible, since `Auto` hands back a working software decoder and says
453				// nothing above DEBUG.
454				if !attempt.hardware && !(skipped.is_empty() && passed.is_empty()) {
455					let skipped: Vec<&str> = skipped.iter().chain(&passed).map(String::as_str).collect();
456					tracing::warn!(
457						decoder = name,
458						skipped = %skipped.join(", "),
459						"no hardware decoder available, falling back to software"
460					);
461				}
462				return Ok(backend);
463			}
464			Err(e) => {
465				tracing::debug!(decoder = name, error = %e, "decoder unavailable, trying next");
466				// The one variant a backend opens with to say its device answered.
467				faulted |= !matches!(e, Error::UnsupportedCodec(_));
468				let reason = match e {
469					Error::UnsupportedCodec(reason) => reason,
470					e => e.to_string(),
471				};
472				tried.push(format!("{name}: {reason}"));
473				if attempt.hardware {
474					skipped.push(format!("{name}: {reason}"));
475				}
476			}
477		}
478	}
479
480	// Nothing was tried at all, so no candidate both matched and takes this
481	// codec. For a named request that is a name this build does not have: a
482	// typo, a feature that is off, or a backend that does not decode this
483	// codec. Naming what is here is most of the answer. Otherwise this build
484	// cannot decode the codec at all, which is known before opening anything.
485	if tried.is_empty() && !passed.is_empty() {
486		return Err(Error::NoDecoder(passed.join(", ")));
487	}
488	tried.append(&mut passed);
489	if tried.is_empty() {
490		let available = available_names(codec);
491		return match &config.backend {
492			Choice::Named(name) => Err(Error::UnknownDecoder {
493				name: name.clone(),
494				codec,
495				available: available.join(", "),
496			}),
497			kind => Err(Error::UnsupportedCodec(format!(
498				"nothing compiled in for {} at {kind:?} (this build has: {})",
499				codec.label(),
500				available.join(", "),
501			))),
502		};
503	}
504	if !faulted {
505		return Err(Error::UnsupportedCodec(format!(
506			"no decoder here takes this {} stream ({})",
507			codec.label(),
508			tried.join(", ")
509		)));
510	}
511	// Missing drivers, no device, or a library fault: not a property of the track.
512	Err(Error::NoDecoder(tried.join(", ")))
513}
514
515/// Returns the decoders this build has for `codec`, in priority order.
516///
517/// Only the ones a user could ask for: the test-only list is left out, since it
518/// exists to be named by a test rather than offered to anybody.
519fn available_names(codec: Codec) -> Vec<&'static str> {
520	HARDWARE
521		.iter()
522		.chain(SOFTWARE.iter())
523		.filter(|candidate| (candidate.supports)(codec))
524		.map(|candidate| candidate.name)
525		.collect()
526}
527
528#[cfg(test)]
529mod tests {
530	use super::*;
531
532	/// A backend that opens and decodes nothing, the decode mirror of the encode
533	/// side's stub.
534	struct Stub;
535
536	impl Stub {
537		fn open(_stream: &Stream, _config: &Config) -> Result<Box<dyn Backend>, Error> {
538			Ok(Box::new(Self))
539		}
540	}
541
542	impl Backend for Stub {
543		fn decode(&mut self, _access_unit: Bytes, _timestamp: Timestamp, _keyframe: bool) -> Result<(), Error> {
544			Ok(())
545		}
546
547		fn receive(&mut self) -> Result<Option<Frame>, Error> {
548			Ok(None)
549		}
550
551		fn flush(&mut self) -> Result<(), Error> {
552			Ok(())
553		}
554
555		fn name(&self) -> &str {
556			"stub"
557		}
558	}
559
560	const WORKING: Candidate = Candidate {
561		name: "stub",
562		supports: |c| matches!(c, Codec::H264),
563		open: Stub::open,
564		drives: Drives::Own,
565	};
566
567	/// Compiled in but faulting at runtime, the way NVDEC does on a host whose
568	/// driver libraries aren't on the loader path.
569	const DRIVERLESS: Candidate = Candidate {
570		name: "driverless",
571		supports: |c| matches!(c, Codec::H264),
572		open: |_, _| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
573		drives: Drives::Own,
574	};
575
576	#[tracing_test::traced_test]
577	#[test]
578	fn falling_past_hardware_warns() {
579		let config = Config::new();
580		let attempts = vec![Attempt::hardware(&DRIVERLESS), Attempt::software(&WORKING)];
581		let backend = select(&Codec::H264.into(), attempts, &config).unwrap();
582		assert_eq!(backend.name(), "stub");
583
584		logs_assert(
585			|lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
586				Some(warning) if warning.contains("driverless") && warning.contains("driver libraries not found") => {
587					Ok(())
588				}
589				Some(warning) => Err(format!("warning does not name the refusal: {warning}")),
590				None => Err("no fallback warning".to_owned()),
591			},
592		);
593	}
594
595	/// Hardware passed over for driving another device than the named one is
596	/// hardware the software pick fell past, so the warning names it too.
597	#[tracing_test::traced_test]
598	#[test]
599	fn falling_past_hardware_for_another_device_warns() {
600		const RENDER: Candidate = Candidate {
601			name: "render",
602			open: |_, _| panic!("opened a render backend for a codec node"),
603			drives: Drives::Render,
604			..WORKING
605		};
606
607		let mut config = Config::new();
608		config.device = crate::Device::Video("/dev/video11".into());
609		let attempts = vec![Attempt::hardware(&RENDER), Attempt::software(&WORKING)];
610		select(&Codec::H264.into(), attempts, &config).unwrap();
611		logs_assert(
612			|lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
613				Some(warning) if warning.contains("render: does not open codec node /dev/video11") => Ok(()),
614				Some(warning) => Err(format!("warning does not name the passed-over hardware: {warning}")),
615				None => Err("no fallback warning".to_owned()),
616			},
617		);
618	}
619
620	/// A hardware candidate skipped for not supporting the codec never ran, so it
621	/// refused nothing and the software pick isn't a fallback. Only the decode side
622	/// can hit this: it filters by codec inside the loop rather than up front.
623	#[tracing_test::traced_test]
624	#[test]
625	fn hardware_that_cannot_decode_the_codec_is_not_a_fallback() {
626		const H265_ONLY: Candidate = Candidate {
627			name: "driverless",
628			supports: |c| matches!(c, Codec::H265),
629			open: |_, _| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
630			drives: Drives::Own,
631		};
632
633		let attempts = vec![Attempt::hardware(&H265_ONLY), Attempt::software(&WORKING)];
634		select(&Codec::H264.into(), attempts, &Config::new()).unwrap();
635		assert!(!logs_contain("no hardware decoder available"));
636	}
637
638	/// A driver check that cannot read the named node counts against the NVIDIA
639	/// candidate alone: selection goes on to the next, and with none left the
640	/// failure is a fault that names the node, not a refusal of the stream.
641	#[cfg(target_os = "linux")]
642	#[test]
643	fn a_failed_driver_check_moves_on() {
644		const NVIDIA: Candidate = Candidate {
645			name: "nvidia",
646			supports: |c| matches!(c, Codec::H264),
647			open: |_, _| panic!("opened NVIDIA for an unreadable node"),
648			drives: Drives::Nvidia,
649		};
650		const RENDER: Candidate = Candidate {
651			drives: Drives::Render,
652			..WORKING
653		};
654
655		let mut config = Config::new();
656		config.device = crate::Device::Render("/dev/dri/renderD199-absent".into());
657		let attempts = vec![Attempt::hardware(&NVIDIA), Attempt::hardware(&RENDER)];
658		assert_eq!(select(&Codec::H264.into(), attempts, &config).unwrap().name(), "stub");
659
660		match select(&Codec::H264.into(), vec![Attempt::hardware(&NVIDIA)], &config) {
661			Err(Error::NoDecoder(reason)) => assert!(
662				reason.contains("nvidia: ") && reason.contains("renderD199-absent"),
663				"{reason}"
664			),
665			Err(other) => panic!("expected NoDecoder, got {other:?}"),
666			Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
667		}
668	}
669
670	/// A named node passes over the backends that drive another kind of device
671	/// without opening them, and opens the one that drives it.
672	#[test]
673	fn a_named_device_steers_selection_to_its_backend() {
674		const RENDER: Candidate = Candidate {
675			name: "render",
676			supports: |c| matches!(c, Codec::H264),
677			open: |_, _| panic!("opened a render backend for a codec node"),
678			drives: Drives::Render,
679		};
680		const VIDEO: Candidate = Candidate {
681			drives: Drives::Video,
682			..WORKING
683		};
684
685		let mut config = Config::new();
686		config.device = crate::Device::Video("/dev/video10".into());
687		let attempts = vec![Attempt::hardware(&RENDER), Attempt::hardware(&VIDEO)];
688		assert_eq!(select(&Codec::H264.into(), attempts, &config).unwrap().name(), "stub");
689
690		// Passed over is not a refusal of the stream: with no backend left for
691		// the device, the error is a missing decoder that names the device.
692		let attempts = vec![Attempt::hardware(&RENDER)];
693		match select(&Codec::H264.into(), attempts, &config) {
694			Err(Error::NoDecoder(reason)) => assert!(reason.contains("/dev/video10"), "{reason}"),
695			Err(other) => panic!("expected NoDecoder, got {other:?}"),
696			Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
697		}
698	}
699
700	/// The backend that drives the named device refusing the stream is a refusal,
701	/// even beside backends passed over for driving another device.
702	#[test]
703	fn the_named_devices_refusal_is_the_streams() {
704		const RENDER: Candidate = Candidate {
705			name: "render",
706			supports: |c| matches!(c, Codec::H264),
707			open: |_, _| Err(Error::UnsupportedCodec("too large".into())),
708			drives: Drives::Render,
709		};
710		const VIDEO: Candidate = Candidate {
711			drives: Drives::Video,
712			..WORKING
713		};
714
715		let mut config = Config::new();
716		config.device = crate::Device::Render("/dev/dri/renderD129".into());
717		let attempts = vec![Attempt::hardware(&VIDEO), Attempt::hardware(&RENDER)];
718		assert!(matches!(
719			select(&Codec::H264.into(), attempts, &config),
720			Err(Error::UnsupportedCodec(_))
721		));
722	}
723
724	/// A name no candidate answers to has to say so, and say what it could have
725	/// been asked for instead.
726	#[test]
727	fn an_unknown_name_names_itself_and_the_alternatives() {
728		let mut config = Config::new();
729		config.backend = Choice::Named("vappi".to_owned());
730
731		match open(&Codec::H264.into(), &config) {
732			Err(Error::UnknownDecoder { name, codec, available }) => {
733				assert_eq!(name, "vappi");
734				assert_eq!(codec, crate::decode::Codec::H264);
735				#[cfg(feature = "openh264")]
736				assert!(available.contains(openh264::NAME), "nothing offered: {available}");
737				#[cfg(not(feature = "openh264"))]
738				assert!(!available.contains("openh264"), "disabled backend offered: {available}");
739			}
740			Err(other) => panic!("expected UnknownDecoder, got {other:?}"),
741			Ok(backend) => panic!("expected UnknownDecoder, opened {}", backend.name()),
742		}
743	}
744
745	#[cfg(not(feature = "openh264"))]
746	#[test]
747	fn disabled_software_backend_is_not_selected() {
748		let mut config = Config::new();
749		config.backend = Choice::Software;
750		assert!(matches!(
751			open(&Codec::H264.into(), &config),
752			Err(Error::UnsupportedCodec(_))
753		));
754
755		config.backend = Choice::Named("openh264".to_owned());
756		assert!(matches!(
757			open(&Codec::H264.into(), &config),
758			Err(Error::UnknownDecoder { .. })
759		));
760	}
761
762	/// The reason each candidate faulted belongs in the error. Only the DEBUG
763	/// line used to carry it, which is no use to a caller holding the `Err`.
764	#[test]
765	fn every_candidate_faulting_reports_why() {
766		let mut config = Config::new();
767		config.backend = Choice::Named("driverless".to_owned());
768
769		match select(&Codec::H264.into(), vec![Attempt::hardware(&DRIVERLESS)], &config) {
770			Err(Error::NoDecoder(tried)) => {
771				assert!(tried.contains("driverless"), "does not name the backend: {tried}");
772				assert!(
773					tried.contains("driver libraries not found"),
774					"does not carry the reason: {tried}"
775				);
776			}
777			Err(other) => panic!("expected NoDecoder, got {other:?}"),
778			Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
779		}
780	}
781
782	/// The test-only candidate answering to `name`.
783	fn named(name: &str) -> &'static Candidate {
784		NAMED_ONLY
785			.iter()
786			.find(|candidate| candidate.name == name)
787			.expect("a test-only candidate")
788	}
789
790	/// Every candidate's device saying it cannot decode the stream is a property
791	/// of the stream on this machine, which a caller can answer with another
792	/// rendition.
793	#[test]
794	fn every_candidate_refusing_is_unsupported() {
795		let refusing = named(probe::REFUSING_NAME);
796		let attempts = vec![Attempt::hardware(refusing), Attempt::hardware(refusing)];
797		match select(&Codec::H264.into(), attempts, &Config::new()) {
798			Err(Error::UnsupportedCodec(reason)) => {
799				assert!(
800					reason.contains(probe::REFUSING_NAME),
801					"does not name the backend: {reason}"
802				);
803				assert!(reason.contains("cannot decode"), "does not carry the reason: {reason}");
804			}
805			Err(other) => panic!("expected UnsupportedCodec, got {other:?}"),
806			Ok(backend) => panic!("expected UnsupportedCodec, opened {}", backend.name()),
807		}
808	}
809
810	/// A fault among the refusals could be what stopped a decoder that would have
811	/// taken the stream, so in either order the whole stays a fault.
812	#[test]
813	fn a_fault_among_refusals_is_a_fault() {
814		let refusing = named(probe::REFUSING_NAME);
815		for attempts in [
816			vec![Attempt::hardware(refusing), Attempt::hardware(&DRIVERLESS)],
817			vec![Attempt::hardware(&DRIVERLESS), Attempt::software(refusing)],
818		] {
819			match select(&Codec::H264.into(), attempts, &Config::new()) {
820				Err(Error::NoDecoder(tried)) => {
821					assert!(tried.contains(probe::REFUSING_NAME), "drops the refusal: {tried}");
822					assert!(tried.contains("driverless"), "drops the fault: {tried}");
823				}
824				Err(other) => panic!("expected NoDecoder, got {other:?}"),
825				Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
826			}
827		}
828	}
829
830	/// A refusal is no different from any other failure when a later candidate
831	/// opens: `Auto` still lands on it.
832	#[test]
833	fn a_refusal_falls_through_to_the_next_candidate() {
834		let attempts = vec![
835			Attempt::hardware(named(probe::REFUSING_NAME)),
836			Attempt::software(&WORKING),
837		];
838		let backend = select(&Codec::H264.into(), attempts, &Config::new()).unwrap();
839		assert_eq!(backend.name(), "stub");
840	}
841
842	/// The decode half of the same guarantee the encode side keeps.
843	#[test]
844	fn every_compiled_backend_is_named_publicly() {
845		for candidate in HARDWARE.iter().chain(SOFTWARE.iter()) {
846			assert!(
847				NAMES.contains(&candidate.name),
848				"{} is compiled in but missing from NAMES",
849				candidate.name,
850			);
851		}
852	}
853}