Skip to main content

moq_video/encode/backend/
mod.rs

1//! Pluggable video encoder backends.
2//!
3//! [`Backend`] is the seam between frame input prep (capture + color conversion,
4//! owned by [`Encoder`](super::Encoder)) and the codec itself. Every backend
5//! takes a raw [`Frame`] and emits Annex-B with in-band parameter sets (SPS/PPS,
6//! plus VPS for H.265), the framing the matching catalog importer expects. Each
7//! backend produces exactly one codec, so the producer can route its packets to
8//! the right importer.
9//!
10//! Output is stamped with the timestamp of the frame it was encoded from, not
11//! whichever frame happened to be going in. A backend that readies each frame's
12//! output as it is submitted just echoes the input timestamp; one that buffers
13//! (Media Foundation, MediaCodec) correlates through the codec's own sample clock.
14//!
15//! [`open`] picks the best backend for a [`Codec`](super::Codec) +
16//! [`Backend`](super::Backend): only candidates that support the requested codec are
17//! considered, hardware (platform-gated) before the OpenH264 software fallback
18//! when this build enables it.
19
20use super::encoder::{Applied, Backend as Choice, Codec, Config};
21use crate::device::Drives;
22use crate::encode::Encoded;
23use crate::{Error, Frame};
24
25#[cfg(feature = "openh264")]
26mod openh264;
27
28#[cfg(test)]
29pub(crate) mod probe;
30
31#[cfg(apple)]
32mod videotoolbox;
33
34#[cfg(target_os = "windows")]
35mod mediafoundation;
36
37#[cfg(all(target_os = "android", feature = "mediacodec"))]
38mod mediacodec;
39
40#[cfg(all(target_os = "linux", feature = "nvidia"))]
41mod nvenc;
42
43#[cfg(all(target_os = "linux", feature = "v4l2"))]
44mod v4l2;
45
46#[cfg(all(target_os = "linux", feature = "vaapi"))]
47mod vaapi;
48
49/// An opened video encoder. Submit frames at the configured resolution, then
50/// receive zero or more access units in the codec's wire framing, each stamped
51/// with the timestamp of the frame it came from and marked when it is a
52/// keyframe, whether forced by `cut` or placed by the backend's own GOP cadence.
53///
54/// A backend that readies output synchronously holds it in a reused queue, so
55/// no call allocates to hand it back.
56pub(crate) trait Backend {
57	/// Submit one frame, opening a group at it (an IDR) when `cut` is set.
58	/// Backends place group boundaries on their own every
59	/// [`Config::keyframe_interval`] frames, so this is only the encoder's extra
60	/// request: a caller's [`Encoder::cut`](super::Encoder::cut), or a
61	/// [`Config::join`] that a source slower than its frame rate reached first. It
62	/// arrives only on a backend whose [`can_cut`](Self::can_cut) said yes. A
63	/// backend that drops the frame carries the cut to the next one it encodes,
64	/// or the group waits a whole join for its keyframe.
65	fn encode(&mut self, frame: &Frame, cut: bool) -> Result<(), Error>;
66
67	/// Pop the oldest ready access unit, or `None` while the codec holds the rest.
68	fn receive(&mut self) -> Result<Option<Encoded>, Error>;
69
70	/// Mark the end of input, so [`receive`](Self::receive) returns every access
71	/// unit the codec still holds. The next frame submitted starts new input.
72	///
73	/// The caller reaches for this at a boundary the output has to respect, which
74	/// on a live track is a group: a codec that pipelines would otherwise carry the
75	/// last frames of one group into the next, ahead of its keyframe, where a
76	/// consumer joining there cannot decode them.
77	///
78	/// No default, even though most backends have nothing to hold: a pipelined one
79	/// that inherited an empty implementation would drop frames at every boundary
80	/// and look like it worked.
81	fn flush(&mut self) -> Result<(), Error>;
82
83	/// Submit one frame and collect everything it readied.
84	#[cfg(all(
85		test,
86		any(
87			feature = "openh264",
88			apple,
89			all(target_os = "android", feature = "mediacodec"),
90			all(target_os = "linux", feature = "vaapi"),
91		)
92	))]
93	fn encode_all(&mut self, frame: &Frame, cut: bool) -> Result<Vec<Encoded>, Error> {
94		self.encode(frame, cut)?;
95		self.receive_all()
96	}
97
98	/// Flush and collect the tail.
99	#[cfg(test)]
100	#[allow(dead_code, reason = "only the platform backends' tests use it")]
101	fn flush_all(&mut self) -> Result<Vec<Encoded>, Error> {
102		self.flush()?;
103		self.receive_all()
104	}
105
106	/// Collect everything ready.
107	#[cfg(test)]
108	fn receive_all(&mut self) -> Result<Vec<Encoded>, Error> {
109		let mut encoded = Vec::new();
110		while let Some(unit) = self.receive()? {
111			encoded.push(unit);
112		}
113		Ok(encoded)
114	}
115
116	/// Retune the live encoder to `bitrate` bits per second, taking effect from
117	/// roughly the next frame. Called as the congestion controller's estimate
118	/// moves, so it must not force an IDR or rebuild the session: a keyframe on
119	/// every bandwidth change is exactly the burst a closing uplink can't take.
120	///
121	/// No default: a backend that can't retune has to say so with
122	/// [`Error::BitrateUnsupported`](crate::Error::BitrateUnsupported) rather
123	/// than inherit a silent no-op and quietly ignore congestion.
124	fn set_bitrate(&mut self, bitrate: u64) -> Result<(), Error>;
125
126	/// Whether [`encode`](Self::encode) honors `cut`.
127	///
128	/// Known at open: a V4L2 driver either has the force-keyframe control or
129	/// does not, and the encoder refuses a cut up front on one that does not
130	/// rather than queue a request the codec ignores. No default, for the same
131	/// reason as `set_bitrate`: a backend that cannot cut has to say so, not
132	/// inherit a yes and let the refusal surface as a mislaid group boundary.
133	fn can_cut(&self) -> bool;
134
135	/// Whether [`encode`](Self::encode) scales `surface` to the session size
136	/// itself, on the surface's device, so a resizing encoder hands the frame
137	/// over at its own size. The default leaves scaling to the encoder.
138	fn scales(&self, _surface: &crate::Surface) -> bool {
139		false
140	}
141
142	/// The encoder name in use, e.g. `"videotoolbox"` (for logging and errors).
143	fn name(&self) -> &'static str;
144
145	/// The latency and compression controls this backend applied at open for
146	/// [`Config::preset`](super::Config::preset).
147	///
148	/// The default claims nothing, which is the honest answer for a backend that
149	/// has not confirmed its controls took effect.
150	fn applied(&self) -> Applied {
151		Applied::default()
152	}
153}
154
155/// Whether one NAL unit (header first, no start code) is a keyframe slice: an
156/// H.264 IDR (type 5), or an H.265 IRAP picture (BLA/IDR/CRA, types 16..=23).
157#[cfg(any(
158	apple,
159	target_os = "windows",
160	all(target_os = "linux", any(feature = "nvidia", feature = "vaapi", feature = "v4l2")),
161	test
162))]
163fn keyframe_nal(codec: Codec, nal: &[u8]) -> bool {
164	let Some(&header) = nal.first() else {
165		return false;
166	};
167	match codec {
168		Codec::H264 => header & 0x1f == 5,
169		Codec::H265 => (16..=23).contains(&((header >> 1) & 0x3f)),
170	}
171}
172
173/// Whether an Annex-B access unit is a keyframe, for a backend whose codec API
174/// hands back only the bytes. Decided by the first slice, since every slice of a
175/// picture shares its type; the parameter sets and SEI ahead of it are skipped.
176#[cfg(any(
177	target_os = "windows",
178	all(target_os = "linux", any(feature = "nvidia", feature = "vaapi", feature = "v4l2")),
179	test
180))]
181fn keyframe_annexb(codec: Codec, mut annexb: &[u8]) -> bool {
182	while let Some((at, len)) = moq_mux::codec::annexb::find_start_code(annexb) {
183		annexb = &annexb[at + len..];
184		let Some(&header) = annexb.first() else { break };
185		let slice = match codec {
186			Codec::H264 => (1..=5).contains(&(header & 0x1f)),
187			Codec::H265 => (header >> 1) & 0x3f < 32,
188		};
189		if slice {
190			return keyframe_nal(codec, annexb);
191		}
192	}
193	false
194}
195
196/// Every encoder backend this crate has a name for, on any platform.
197///
198/// Platform-complete on purpose, where the candidate lists this module selects
199/// from are gated to what this build compiled. A caller offering
200/// [`Backend::Named`](super::Backend) as a choice needs the whole vocabulary, because
201/// a name it does not offer is a name nobody can ask for, and whether a given
202/// machine has that backend is answered by trying it rather than by the list.
203///
204/// The test below asserts every candidate compiled into this build appears
205/// here, so a rename fails on the platform that renamed it rather than
206/// silently leaving a name nothing answers to.
207pub const NAMES: &[&str] = &[
208	"videotoolbox",
209	"mediafoundation",
210	"mediacodec",
211	"nvenc",
212	"vaapi",
213	"v4l2",
214	"openh264",
215];
216
217/// Whether the backend called `name` reads, in place, the GPU surface this
218/// platform's render export hands over: a Vulkan image on Linux, a pixel buffer
219/// on Apple platforms, a Direct3D11 texture on Windows.
220#[cfg_attr(not(feature = "render"), allow(dead_code, reason = "only the render export asks"))]
221pub(crate) fn reads_export(name: &str) -> bool {
222	HARDWARE.iter().any(|candidate| {
223		#[cfg(target_os = "linux")]
224		let reads = candidate.vulkan;
225		// Every hardware encoder on these takes the platform's surface.
226		#[cfg(not(target_os = "linux"))]
227		let reads = cfg!(any(apple, target_os = "windows"));
228		candidate.name == name && reads
229	})
230}
231
232/// A backend constructor: name, the codecs it can emit, an opener, and whether it can always cut.
233struct Candidate {
234	name: &'static str,
235	codecs: &'static [Codec],
236	open: fn(&Config) -> Result<Box<dyn Backend>, Error>,
237	/// Whether every encoder this opens honors a cut ([`Backend::can_cut`]), known before
238	/// opening one. V4L2 learns it from the driver at open, so it cannot promise.
239	#[cfg_attr(
240		not(feature = "capture"),
241		allow(dead_code, reason = "only the `capture` feature uses it")
242	)]
243	cuts: bool,
244	/// The kind of [`Device`](crate::Device) it opens, which a named one steers selection by.
245	drives: Drives,
246	#[cfg(target_os = "linux")]
247	vulkan: bool,
248}
249
250/// Hardware backends, in priority order. Platform-gated so only the ones that
251/// could plausibly work on this target are even listed.
252const HARDWARE: &[Candidate] = &[
253	#[cfg(apple)]
254	Candidate {
255		name: videotoolbox::NAME,
256		codecs: &[Codec::H264, Codec::H265],
257		open: videotoolbox::VideoToolbox::open,
258		cuts: true,
259		drives: Drives::Own,
260		#[cfg(target_os = "linux")]
261		vulkan: false,
262	},
263	#[cfg(target_os = "windows")]
264	Candidate {
265		name: mediafoundation::NAME,
266		codecs: &[Codec::H264, Codec::H265],
267		open: mediafoundation::MediaFoundation::open,
268		cuts: true,
269		drives: Drives::Own,
270		#[cfg(target_os = "linux")]
271		vulkan: false,
272	},
273	#[cfg(all(target_os = "android", feature = "mediacodec"))]
274	Candidate {
275		name: mediacodec::NAME,
276		codecs: &[Codec::H264, Codec::H265],
277		open: mediacodec::MediaCodec::open,
278		cuts: true,
279		drives: Drives::Own,
280		#[cfg(target_os = "linux")]
281		vulkan: false,
282	},
283	#[cfg(all(target_os = "linux", feature = "nvidia"))]
284	Candidate {
285		name: nvenc::NAME,
286		codecs: &[Codec::H264, Codec::H265],
287		open: nvenc::Nvenc::open,
288		cuts: true,
289		drives: Drives::Nvidia,
290		#[cfg(target_os = "linux")]
291		vulkan: true,
292	},
293	#[cfg(all(target_os = "linux", feature = "vaapi"))]
294	Candidate {
295		name: vaapi::NAME,
296		codecs: &[Codec::H264, Codec::H265],
297		open: vaapi::Vaapi::open,
298		cuts: true,
299		drives: Drives::Render,
300		#[cfg(target_os = "linux")]
301		vulkan: false,
302	},
303	// Last of the Linux hardware encoders: the SoC blocks it drives are the only
304	// hardware on a board that has neither an NVIDIA GPU nor a VAAPI stack, so it
305	// is never the one being chosen over a faster peer.
306	#[cfg(all(target_os = "linux", feature = "v4l2"))]
307	Candidate {
308		name: v4l2::NAME,
309		codecs: &[Codec::H264],
310		open: v4l2::V4l2::open,
311		cuts: false,
312		drives: Drives::Video,
313		#[cfg(target_os = "linux")]
314		vulkan: false,
315	},
316];
317
318/// Software fallbacks compiled into this build. Only H.264 (OpenH264) has one;
319/// H.265 is hardware-only. A slice so a build can omit it entirely and future
320/// software codecs can slot in.
321const SOFTWARE: &[Candidate] = &[
322	#[cfg(feature = "openh264")]
323	Candidate {
324		name: openh264::NAME,
325		codecs: &[Codec::H264],
326		open: openh264::Openh264::open,
327		cuts: true,
328		drives: Drives::Own,
329		#[cfg(target_os = "linux")]
330		vulkan: false,
331	},
332];
333
334/// Test-only backends. Deliberately in neither list above, so `Auto` /
335/// `Hardware` / `Software` can never select one: they exist to be asked for by
336/// name.
337#[cfg(test)]
338const NAMED_ONLY: &[Candidate] = &[
339	Candidate {
340		name: probe::NAME,
341		codecs: &[Codec::H264],
342		open: probe::Probe::open,
343		cuts: true,
344		drives: Drives::Own,
345		#[cfg(target_os = "linux")]
346		vulkan: false,
347	},
348	Candidate {
349		name: probe::NO_CUT,
350		codecs: &[Codec::H264],
351		open: probe::Probe::open_no_cut,
352		cuts: false,
353		drives: Drives::Own,
354		#[cfg(target_os = "linux")]
355		vulkan: false,
356	},
357	#[cfg(feature = "openh264")]
358	Candidate {
359		name: probe::PIPELINED,
360		codecs: &[Codec::H264],
361		open: probe::Pipelined::open,
362		cuts: true,
363		drives: Drives::Own,
364		#[cfg(target_os = "linux")]
365		vulkan: false,
366	},
367];
368
369#[cfg(not(test))]
370const NAMED_ONLY: &[Candidate] = &[];
371
372/// A candidate paired with the tier it came from, so [`select`] can tell a
373/// software encoder that was asked for from one reached by falling past
374/// hardware that refused to open.
375struct Attempt<'a> {
376	candidate: &'a Candidate,
377	hardware: bool,
378}
379
380impl<'a> Attempt<'a> {
381	fn hardware(candidate: &'a Candidate) -> Self {
382		Self {
383			candidate,
384			hardware: true,
385		}
386	}
387
388	fn software(candidate: &'a Candidate) -> Self {
389		Self {
390			candidate,
391			hardware: false,
392		}
393	}
394}
395
396/// Open the best encoder for `config.codec` + `config.kind`, trying candidates
397/// in priority order and falling back until one succeeds.
398pub(crate) fn open(config: &Config) -> Result<Box<dyn Backend>, Error> {
399	select(attempts(config.codec, &config.backend), config)
400}
401
402/// Whether whichever backend [`open`] picks for `codec` + `kind` honors a cut, answered
403/// before opening one: every candidate it may fall to must promise it.
404#[cfg_attr(
405	not(feature = "capture"),
406	allow(dead_code, reason = "only the `capture` feature uses it")
407)]
408pub(crate) fn always_cuts(codec: Codec, kind: &Choice) -> bool {
409	let attempts = attempts(codec, kind);
410	!attempts.is_empty() && attempts.iter().all(|attempt| attempt.candidate.cuts)
411}
412
413/// The encoders [`open`] tries for `codec` + `kind`, in order: each name, and
414/// whether it is hardware.
415#[cfg_attr(not(feature = "render"), allow(dead_code, reason = "only the render export asks"))]
416pub(crate) fn candidates(codec: Codec, kind: &Choice) -> Vec<(&'static str, bool)> {
417	attempts(codec, kind)
418		.iter()
419		.map(|attempt| (attempt.candidate.name, attempt.hardware))
420		.collect()
421}
422
423/// The candidates [`open`] tries for `codec` + `kind`, in order.
424fn attempts(codec: Codec, kind: &Choice) -> Vec<Attempt<'static>> {
425	let supports = move |c: &Candidate| c.codecs.contains(&codec);
426	let hardware = HARDWARE.iter().filter(|c| supports(c)).map(Attempt::hardware);
427	let software = SOFTWARE.iter().filter(|c| supports(c)).map(Attempt::software);
428
429	match kind {
430		Choice::Auto => hardware.chain(software).collect(),
431		Choice::Hardware => hardware.collect(),
432		Choice::Software => software.collect(),
433		Choice::Named(name) => HARDWARE
434			.iter()
435			.map(Attempt::hardware)
436			.chain(SOFTWARE.iter().chain(NAMED_ONLY.iter()).map(Attempt::software))
437			.filter(|a| supports(a.candidate) && a.candidate.name == name)
438			.collect(),
439	}
440}
441
442/// Try `attempts` in order and return the first encoder that opens, warning when
443/// that means falling past hardware.
444///
445/// Split out from [`open`] because the candidate lists are platform-gated
446/// consts: what `Auto` has to fall back *from* depends on the machine, so a test
447/// supplies its own attempts instead of hoping the host has the right GPU.
448fn select(attempts: Vec<Attempt>, config: &Config) -> Result<Box<dyn Backend>, Error> {
449	// Each entry is "name: why it refused". The names alone say which backends
450	// exist, which is what a reader already knows; the reasons say why this
451	// machine has none, which is the question being asked.
452	let mut tried: Vec<String> = Vec::new();
453	let mut refused = Vec::new();
454
455	for attempt in attempts {
456		let name = attempt.candidate.name;
457
458		#[cfg(target_os = "linux")]
459		if let Some(device) = config.input
460			&& (!attempt.hardware || !attempt.candidate.vulkan)
461		{
462			let reason = format!("{name}: cannot import external Vulkan {device}");
463			if attempt.hardware {
464				refused.push(reason.clone());
465			}
466			tried.push(reason);
467			continue;
468		}
469		match config.device.takes(attempt.candidate.drives) {
470			Ok(true) => {}
471			Ok(false) => {
472				let reason = format!("{name}: does not open {}", config.device);
473				if attempt.hardware {
474					refused.push(reason.clone());
475				}
476				tried.push(reason);
477				continue;
478			}
479			// Telling whether this backend drives the named node failed, which
480			// counts against this candidate alone, as a failed open would.
481			Err(e) => {
482				tracing::debug!(encoder = name, error = %e, "encoder unavailable, trying next");
483				tried.push(format!("{name}: {e}"));
484				if attempt.hardware {
485					refused.push(format!("{name}: {e}"));
486				}
487				continue;
488			}
489		}
490		match (attempt.candidate.open)(config) {
491			Ok(backend) => {
492				// `Auto` returning a software encoder is otherwise invisible except for
493				// its CPU cost, so name each hardware candidate it fell past and why.
494				if !attempt.hardware && matches!(&config.backend, Choice::Auto) {
495					let refused = match refused.is_empty() {
496						true => "none in this build".to_owned(),
497						false => refused.join(", "),
498					};
499					tracing::warn!(
500						encoder = name,
501						%refused,
502						"no hardware encoder available, falling back to software"
503					);
504				}
505				return Ok(backend);
506			}
507			Err(e) => {
508				tracing::debug!(encoder = name, error = %e, "encoder unavailable, trying next");
509				tried.push(format!("{name}: {e}"));
510				if attempt.hardware {
511					refused.push(format!("{name}: {e}"));
512				}
513			}
514		}
515	}
516
517	// Nothing was tried at all, so no candidate matched. For a named request
518	// that is a name this build does not have: a typo, a feature that is off,
519	// or a backend that does not take this codec. Reporting it as "no usable
520	// encoder (tried: )" tells the caller nothing, and naming what is here is
521	// most of the answer.
522	#[cfg(target_os = "linux")]
523	if let Some(device) = config.input {
524		return Err(Error::NoEncoder(format!(
525			"no backend can import external Vulkan {device} (tried: {})",
526			tried.join(", ")
527		)));
528	}
529	if tried.is_empty() {
530		return Err(missing(config.codec, &config.backend));
531	}
532
533	Err(Error::NoEncoder(tried.join(", ")))
534}
535
536/// Why no encoder this build has answers `codec` + `kind`, naming those it has.
537pub(crate) fn missing(codec: Codec, kind: &Choice) -> Error {
538	let available = available_names(codec).join(", ");
539	match kind {
540		Choice::Named(name) => Error::UnknownEncoder {
541			name: name.clone(),
542			codec,
543			available,
544		},
545		kind => Error::NoEncoder(format!(
546			"nothing compiled in for {codec:?} at {kind:?} (this build has: {available})"
547		)),
548	}
549}
550
551/// Returns the encoders this build has for `codec`, in priority order.
552///
553/// Only the ones a user could ask for: the test-only list is left out, since it
554/// exists to be named by a test rather than offered to anybody.
555fn available_names(codec: Codec) -> Vec<&'static str> {
556	HARDWARE
557		.iter()
558		.chain(SOFTWARE.iter())
559		.filter(|candidate| candidate.codecs.contains(&codec))
560		.map(|candidate| candidate.name)
561		.collect()
562}
563
564#[cfg(test)]
565#[cfg_attr(
566	not(feature = "openh264"),
567	allow(dead_code, reason = "only the `openh264` feature uses it")
568)]
569pub(crate) mod test_util {
570	use h264_reader::nal::sps::SeqParameterSet;
571	use h264_reader::nal::{Nal, RefNal, UnitType};
572
573	/// What a scene cost an encoder held to `config.bitrate`, its cap.
574	#[derive(Debug)]
575	pub(crate) struct Spent {
576		/// The mean bitrate after the first second, once rate control has settled.
577		pub mean: u64,
578		/// The most any one second carried after the first.
579		#[cfg_attr(
580			all(
581				feature = "openh264",
582				not(any(
583					apple,
584					target_os = "windows",
585					all(target_os = "linux", any(feature = "nvidia", feature = "vaapi"))
586				))
587			),
588			expect(dead_code, reason = "only the hardware encoders' tests bound the peak")
589		)]
590		pub peak: u64,
591	}
592
593	/// What [`spend`] encodes.
594	#[derive(Clone, Copy, Debug, PartialEq, Eq)]
595	pub(crate) enum Scene {
596		/// A detailed picture drifting a pixel a frame.
597		Calm,
598		/// Fresh noise every frame, which no quantizer below the coarsest codes
599		/// under any cap.
600		Busy,
601		/// The calm picture held still for half the run, then noise: a rate
602		/// controller that banked what the still picture left unspent can pour
603		/// it into the first busy frames.
604		Waking,
605	}
606
607	/// Encode three seconds of `scene` and report what it spent, retuning the cap
608	/// to `retune` half a second in. `None` when the backend `config` names
609	/// cannot open on this machine; once it opens, any failure panics, so an
610	/// encoder that opens but cannot encode fails the test instead of skipping it.
611	pub(crate) fn spend(config: &crate::encode::Config, scene: Scene, retune: Option<u64>) -> Option<Spent> {
612		let mut encoder = crate::encode::Encoder::new(config).ok()?;
613		let size = crate::Size::new(config.width, config.height);
614		let fps = config.framerate.rounded() as usize;
615		let mut sizes = Vec::new();
616		let mut noise = 0x2545_f491_4f6c_dd1du64;
617		for index in 0..3 * fps {
618			if let Some(bps) = retune.filter(|_| index == fps / 2) {
619				encoder
620					.set_bitrate(moq_net::bandwidth::Rate::from_bps(bps))
621					.expect("retune the cap");
622			}
623			let (w, h) = (size.width as usize, size.height as usize);
624			let busy = match scene {
625				Scene::Calm => false,
626				Scene::Busy => true,
627				Scene::Waking => index >= 3 * fps / 2,
628			};
629			// The still picture is the calm one's first frame.
630			let shift = if scene == Scene::Waking { 0 } else { index };
631			let mut rgba = vec![255u8; w * h * 4];
632			for y in 0..h {
633				for x in 0..w {
634					let i = (y * w + x) * 4;
635					let value = if busy {
636						noise ^= noise << 13;
637						noise ^= noise >> 7;
638						noise ^= noise << 17;
639						noise as u8
640					} else {
641						let sx = x + shift;
642						(((sx * 7) ^ (y * 13)) & 0xff) as u8 / 2 + ((sx / 9 + y / 5) % 2) as u8 * 64
643					};
644					rgba[i..i + 3].fill(value);
645				}
646			}
647			let surface = crate::Surface::rgba(&rgba, size).expect("wrap the frame");
648			let timestamp =
649				moq_net::Timestamp::from_micros(index as u64 * 1_000_000 / fps as u64).expect("frame timestamp");
650			let bytes: usize = encoder
651				.encode_all(&crate::Frame::new(timestamp, surface))
652				.expect("encode a frame")
653				.iter()
654				.map(|unit| unit.payload.len())
655				.sum();
656			sizes.push(bytes);
657		}
658		let settled = &sizes[fps..];
659		let bits = |frames: &[usize]| frames.iter().sum::<usize>() as u64 * 8;
660		Some(Spent {
661			mean: bits(settled) * fps as u64 / settled.len() as u64,
662			peak: settled.windows(fps).map(bits).max().unwrap_or(0),
663		})
664	}
665
666	/// A stream's VUI color description, as the raw code points ISO/IEC 23091-2
667	/// assigns them plus the range flag.
668	///
669	/// Deliberately not mapped onto [`Color`](crate::Color): the mapping is lossy
670	/// (several code points share a matrix, and BT.709 and SMPTE 170M define the
671	/// same transfer curve under different numbers), so a test that compared
672	/// `Color`s could not see a backend drift on the fields `Color` folds away.
673	#[derive(Debug, PartialEq, Eq)]
674	pub(crate) struct Described {
675		pub primaries: u8,
676		pub transfer: u8,
677		pub matrix: u8,
678		pub full_range: bool,
679	}
680
681	/// The description we emit for BT.601 and BT.709 limited range, shared by the
682	/// backend tests so a backend drifting from the others fails rather than
683	/// quietly encoding its own dialect.
684	///
685	/// BT.601 goes out as SMPTE 170M primaries and matrix (code point 6) with the
686	/// BT.709 transfer curve (1). The two curves are defined identically, and
687	/// CoreVideo's SMPTE 170M transfer constant is deprecated while Media
688	/// Foundation has none at all, so 1 is the only value all five backends can
689	/// actually emit.
690	pub(crate) const BT601_DESCRIBED: Described = Described {
691		primaries: 6,
692		transfer: 1,
693		matrix: 6,
694		full_range: false,
695	};
696
697	pub(crate) const BT709_DESCRIBED: Described = Described {
698		primaries: 1,
699		transfer: 1,
700		matrix: 1,
701		full_range: false,
702	};
703
704	/// The color description an H.264 Annex-B stream carries in its SPS, or `None`
705	/// if it carries none and a decoder would have to guess.
706	///
707	/// Reads the bitstream rather than the encoder's config, so a backend that
708	/// quietly drops the VUI (or a driver that ignores it) fails the test instead
709	/// of passing on our own bookkeeping.
710	pub(crate) fn declared_color(annexb: &[u8]) -> Option<Described> {
711		// Every 4-byte start code contains a 3-byte one at offset 1, so scanning
712		// for the short form finds both.
713		let starts: Vec<usize> = (0..annexb.len().saturating_sub(2))
714			.filter(|&i| annexb[i..i + 3] == [0, 0, 1])
715			.map(|i| i + 3)
716			.collect();
717
718		let sps = starts.iter().enumerate().find_map(|(n, &start)| {
719			// Bound the NAL at the next start code: a trailing slice would
720			// leave the SPS parser reading into the following NAL.
721			let end = starts.get(n + 1).map_or(annexb.len(), |&next| next - 3);
722			let nal = RefNal::new(&annexb[start..end], &[], true);
723			match nal.header().ok()?.nal_unit_type() {
724				UnitType::SeqParameterSet => SeqParameterSet::from_bits(nal.rbsp_bits()).ok(),
725				_ => None,
726			}
727		})?;
728
729		let signal = sps.vui_parameters.as_ref()?.video_signal_type.as_ref()?;
730		let description = signal.colour_description.as_ref()?;
731		Some(Described {
732			primaries: description.colour_primaries,
733			transfer: description.transfer_characteristics,
734			matrix: description.matrix_coefficients,
735			full_range: signal.video_full_range_flag,
736		})
737	}
738}
739
740#[cfg(test)]
741mod tests {
742	#![cfg_attr(
743		not(feature = "openh264"),
744		allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
745	)]
746
747	use super::*;
748
749	/// A backend that opens and encodes nothing. Stands in for a real candidate so
750	/// a selection test doesn't disturb [`probe`]'s process-wide log.
751	struct Stub;
752
753	impl Stub {
754		fn open(_config: &Config) -> Result<Box<dyn Backend>, Error> {
755			Ok(Box::new(Self))
756		}
757	}
758
759	impl Backend for Stub {
760		fn encode(&mut self, _frame: &Frame, _cut: bool) -> Result<(), Error> {
761			Ok(())
762		}
763
764		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
765			Ok(None)
766		}
767
768		fn flush(&mut self) -> Result<(), Error> {
769			Ok(())
770		}
771
772		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
773			Ok(())
774		}
775
776		fn can_cut(&self) -> bool {
777			true
778		}
779
780		fn name(&self) -> &'static str {
781			"stub"
782		}
783	}
784
785	const WORKING: Candidate = Candidate {
786		name: "stub",
787		codecs: &[Codec::H264],
788		open: Stub::open,
789		cuts: true,
790		drives: Drives::Own,
791		#[cfg(target_os = "linux")]
792		vulkan: false,
793	};
794
795	/// Compiled in but refusing at runtime, the way NVENC does on a host whose
796	/// driver libraries aren't on the loader path.
797	const REFUSING: Candidate = Candidate {
798		name: "driverless",
799		codecs: &[Codec::H264],
800		open: |_| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
801		cuts: true,
802		drives: Drives::Own,
803		#[cfg(target_os = "linux")]
804		vulkan: false,
805	};
806
807	fn config() -> Config {
808		Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
809	}
810
811	/// Only a selection whose every candidate promises cuts may advertise them, and a
812	/// candidate's promise holds for the encoder it opens.
813	#[test]
814	fn always_cuts_needs_every_candidate_to_promise() {
815		let named = |name: &str| Choice::Named(name.to_owned());
816		assert!(always_cuts(Codec::H264, &named(probe::NAME)));
817		assert!(!always_cuts(Codec::H264, &named(probe::NO_CUT)));
818		assert!(!always_cuts(Codec::H264, &named("v4l2")), "V4L2 learns it at open");
819		assert!(!always_cuts(Codec::H264, &named("nonexistent")), "nothing to open");
820
821		let _probe = probe::exclusive();
822		for candidate in NAMED_ONLY {
823			let backend = (candidate.open)(&config()).unwrap();
824			assert_eq!(backend.can_cut(), candidate.cuts, "{}", candidate.name);
825		}
826	}
827
828	/// A named node passes over the hardware that drives another kind of device
829	/// without opening it, and says so when nothing else opens.
830	#[test]
831	fn a_named_device_passes_over_other_hardware() {
832		const RENDER: Candidate = Candidate {
833			name: "render",
834			open: |_| panic!("opened a render backend for a codec node"),
835			drives: Drives::Render,
836			..WORKING
837		};
838		const VIDEO: Candidate = Candidate {
839			name: "video",
840			drives: Drives::Video,
841			..WORKING
842		};
843
844		let mut config = config();
845		config.device = crate::Device::Video("/dev/video11".into());
846		let opened = select(vec![Attempt::hardware(&RENDER), Attempt::hardware(&VIDEO)], &config).unwrap();
847		assert_eq!(opened.name(), "stub");
848
849		match select(vec![Attempt::hardware(&RENDER)], &config) {
850			Err(Error::NoEncoder(reason)) => assert!(
851				reason.contains("render: does not open codec node /dev/video11"),
852				"{reason}"
853			),
854			Err(other) => panic!("expected NoEncoder, got {other:?}"),
855			Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
856		}
857	}
858
859	/// A driver check that cannot read the named node counts against the NVIDIA
860	/// candidate alone: selection goes on, and the reason reaches the error.
861	#[cfg(target_os = "linux")]
862	#[test]
863	fn a_failed_driver_check_moves_on() {
864		const NVIDIA: Candidate = Candidate {
865			name: "nvidia",
866			open: |_| panic!("opened NVIDIA for an unreadable node"),
867			drives: Drives::Nvidia,
868			..WORKING
869		};
870		const RENDER: Candidate = Candidate {
871			name: "render",
872			drives: Drives::Render,
873			..WORKING
874		};
875
876		let mut config = config();
877		config.device = crate::Device::Render("/dev/dri/renderD199-absent".into());
878		let opened = select(vec![Attempt::hardware(&NVIDIA), Attempt::hardware(&RENDER)], &config).unwrap();
879		assert_eq!(opened.name(), "stub");
880
881		match select(vec![Attempt::hardware(&NVIDIA)], &config) {
882			Err(Error::NoEncoder(reason)) => assert!(
883				reason.contains("nvidia: ") && reason.contains("renderD199-absent"),
884				"{reason}"
885			),
886			Err(other) => panic!("expected NoEncoder, got {other:?}"),
887			Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
888		}
889	}
890
891	#[tracing_test::traced_test]
892	#[test]
893	fn falling_past_hardware_warns() {
894		let backend = select(
895			vec![Attempt::hardware(&REFUSING), Attempt::software(&WORKING)],
896			&config(),
897		)
898		.unwrap();
899		assert_eq!(backend.name(), "stub");
900
901		// The warning has to name what refused and why, or it says no more than the
902		// DEBUG line a user already has to know to go looking for.
903		logs_assert(
904			|lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
905				Some(warning) if warning.contains("driverless") && warning.contains("driver libraries not found") => {
906					Ok(())
907				}
908				Some(warning) => Err(format!("warning does not name the refusal: {warning}")),
909				None => Err("no fallback warning".to_owned()),
910			},
911		);
912	}
913
914	/// Hardware passed over for driving another device than the named one is
915	/// hardware the software pick fell past, so the warning names it too.
916	#[tracing_test::traced_test]
917	#[test]
918	fn falling_past_hardware_for_another_device_warns() {
919		const RENDER: Candidate = Candidate {
920			name: "render",
921			open: |_| panic!("opened a render backend for a codec node"),
922			drives: Drives::Render,
923			..WORKING
924		};
925
926		let mut config = config();
927		config.device = crate::Device::Video("/dev/video11".into());
928		select(vec![Attempt::hardware(&RENDER), Attempt::software(&WORKING)], &config).unwrap();
929		logs_assert(
930			|lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
931				Some(warning) if warning.contains("render: does not open codec node /dev/video11") => Ok(()),
932				Some(warning) => Err(format!("warning does not name the passed-over hardware: {warning}")),
933				None => Err("no fallback warning".to_owned()),
934			},
935		);
936	}
937
938	#[tracing_test::traced_test]
939	#[test]
940	fn auto_without_hardware_warns() {
941		let backend = select(vec![Attempt::software(&WORKING)], &config()).unwrap();
942		assert_eq!(backend.name(), "stub");
943		assert!(logs_contain("falling back to software"));
944		assert!(logs_contain("none in this build"));
945	}
946
947	#[tracing_test::traced_test]
948	#[test]
949	fn asking_for_software_is_not_a_fallback() {
950		let mut config = config();
951		config.backend = Choice::Software;
952		select(vec![Attempt::software(&WORKING)], &config).unwrap();
953		assert!(!logs_contain("falling back to software"));
954	}
955
956	/// A name no candidate answers to has to say so. It used to come back as
957	/// `NoEncoder("")`, which names neither the mistake nor the alternatives.
958	#[test]
959	fn an_unknown_name_names_itself_and_the_alternatives() {
960		let mut config = config();
961		config.backend = Choice::Named("vappi".to_owned());
962
963		match open(&config) {
964			Err(Error::UnknownEncoder { name, codec, available }) => {
965				assert_eq!(name, "vappi");
966				assert_eq!(codec, config.codec);
967				#[cfg(feature = "openh264")]
968				assert!(available.contains(openh264::NAME), "nothing offered: {available}");
969				#[cfg(not(feature = "openh264"))]
970				assert!(!available.contains("openh264"), "disabled backend offered: {available}");
971			}
972			Err(other) => panic!("expected UnknownEncoder, got {other:?}"),
973			Ok(backend) => panic!("expected UnknownEncoder, opened {}", backend.name()),
974		}
975	}
976
977	#[cfg(not(feature = "openh264"))]
978	#[test]
979	fn disabled_software_backend_is_not_selected() {
980		let mut config = config();
981		config.backend = Choice::Software;
982		assert!(matches!(open(&config), Err(Error::NoEncoder(_))));
983
984		config.backend = Choice::Named("openh264".to_owned());
985		assert!(matches!(open(&config), Err(Error::UnknownEncoder { .. })));
986	}
987
988	/// The reason each candidate refused belongs in the error. Only the DEBUG
989	/// line used to carry it, which is no use to a caller holding the `Err`.
990	#[test]
991	fn every_candidate_refusing_reports_why() {
992		let mut config = config();
993		config.backend = Choice::Named("driverless".to_owned());
994
995		match select(vec![Attempt::hardware(&REFUSING)], &config) {
996			Err(Error::NoEncoder(tried)) => {
997				assert!(tried.contains("driverless"), "does not name the backend: {tried}");
998				assert!(
999					tried.contains("driver libraries not found"),
1000					"does not carry the reason: {tried}"
1001				);
1002			}
1003			Err(other) => panic!("expected NoEncoder, got {other:?}"),
1004			Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
1005		}
1006	}
1007
1008	#[tracing_test::traced_test]
1009	#[test]
1010	fn hardware_that_opens_is_not_a_fallback() {
1011		select(
1012			vec![Attempt::hardware(&WORKING), Attempt::software(&WORKING)],
1013			&config(),
1014		)
1015		.unwrap();
1016		assert!(!logs_contain("falling back to software"));
1017	}
1018
1019	/// Every backend this build compiled has to be in the public name list, or
1020	/// a caller offering the list as a choice offers a name nothing answers to.
1021	#[test]
1022	fn every_compiled_backend_is_named_publicly() {
1023		for candidate in HARDWARE.iter().chain(SOFTWARE.iter()) {
1024			assert!(
1025				NAMES.contains(&candidate.name),
1026				"{} is compiled in but missing from NAMES",
1027				candidate.name,
1028			);
1029		}
1030	}
1031
1032	/// The keyframe is decided by the first slice, past the parameter sets and SEI
1033	/// that lead an H.264 IDR, and by either start code length.
1034	#[test]
1035	fn an_h264_keyframe_is_its_idr_slice() {
1036		let idr = [
1037			0, 0, 0, 1, 0x67, 0x42, 0, 0, 1, 0x68, 0xce, 0, 0, 1, 0x06, 0x05, 0, 0, 1, 0x65, 0x88,
1038		];
1039		assert!(keyframe_annexb(Codec::H264, &idr));
1040
1041		let delta = [0, 0, 0, 1, 0x09, 0xf0, 0, 0, 0, 1, 0x41, 0x9a];
1042		assert!(!keyframe_annexb(Codec::H264, &delta));
1043
1044		// Parameter sets with no slice are not a picture at all.
1045		assert!(!keyframe_annexb(
1046			Codec::H264,
1047			&[0, 0, 1, 0x67, 0x42, 0, 0, 1, 0x68, 0xce]
1048		));
1049		assert!(!keyframe_annexb(Codec::H264, &[]));
1050	}
1051
1052	/// Every H.265 IRAP type (BLA, IDR, CRA) is a keyframe; a trailing picture is not.
1053	#[test]
1054	fn an_h265_keyframe_is_any_irap_slice() {
1055		// VPS (32), SPS (33), PPS (34), then the slice, each with a two-byte header.
1056		let with_slice = |nal_type: u8| {
1057			let mut annexb = Vec::new();
1058			for header in [32, 33, 34, nal_type] {
1059				annexb.extend_from_slice(&[0, 0, 0, 1, header << 1, 0x01, 0xaf]);
1060			}
1061			annexb
1062		};
1063		for irap in 16..=23 {
1064			assert!(keyframe_annexb(Codec::H265, &with_slice(irap)), "type {irap}");
1065		}
1066		for trailing in [0, 1] {
1067			assert!(!keyframe_annexb(Codec::H265, &with_slice(trailing)), "type {trailing}");
1068		}
1069	}
1070}