Skip to main content

moq_video/encode/
encoder.rs

1//! Video encoder front end.
2//!
3//! Accepts raw [`Frame`]s and delegates the actual encode to a
4//! [`Backend`](super::backend::Backend). The resulting frames carry Annex-B in
5//! the framing the catalog importer for [`Config::codec`] expects: H.264
6//! (`moq_mux::codec::h264`) or H.265 (`moq_mux::codec::h265`).
7
8use std::marker::PhantomData;
9use std::rc::Rc;
10
11use super::Encoded;
12use super::backend;
13use crate::{Color, Device, Error, Frame, FrameRate, Size};
14
15/// Output video codec. `#[non_exhaustive]` so new codecs can be added without
16/// breaking external `match`es.
17///
18/// Not every codec has a backend on every platform: H.265 is hardware-only
19/// (VideoToolbox on macOS and iOS today). Building an [`Encoder`] returns
20/// [`Error::NoEncoder`](crate::Error::NoEncoder) when nothing can encode the
21/// requested codec on this machine.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23#[non_exhaustive]
24pub enum Codec {
25	/// H.264 / AVC, Annex-B with in-band SPS/PPS, published as avc3 with no
26	/// description. The widest
27	/// support and the default.
28	#[default]
29	H264,
30	/// H.265 / HEVC, Annex-B with in-band VPS/SPS/PPS, published as hev1
31	/// with no description.
32	H265,
33}
34
35impl Codec {
36	/// The codec's lowercase name, such as `h264`.
37	pub fn as_str(self) -> &'static str {
38		match self {
39			Self::H264 => "h264",
40			Self::H265 => "h265",
41		}
42	}
43
44	/// What this codec needs against H.264 for the same picture, which scales the default cap.
45	fn bitrate_scale(self) -> f64 {
46		match self {
47			Self::H264 => 1.0,
48			Self::H265 => 0.7,
49		}
50	}
51}
52
53/// Which encoder implementation to use. `#[non_exhaustive]` so new selection
54/// strategies can be added without breaking external `match`es.
55#[derive(Clone, Debug, Default, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum Backend {
58	/// Prefer a platform hardware encoder, falling back to OpenH264 when the
59	/// `openh264` feature is enabled.
60	#[default]
61	Auto,
62	/// Hardware only; error if none is available.
63	Hardware,
64	/// Software only (OpenH264 for H.264 when its feature is enabled).
65	Software,
66	/// A specific backend by name, e.g. `"videotoolbox"`, `"mediacodec"`,
67	/// `"nvenc"`, `"vaapi"`, `"v4l2"`, or `"openh264"`.
68	Named(String),
69}
70
71/// How an encoder trades latency for compression at the configured bitrate.
72///
73/// Bitrate is set separately, via [`Config::bitrate`]. Presets differ in the
74/// codec effort spent per frame and the buffering the backend allows. Each
75/// backend maps a preset onto the controls it actually has, so two presets can
76/// apply the same controls on one backend, and some backends cannot rule out
77/// frame reordering or queueing: V4L2 leaves both to the driver, and
78/// MediaCodec's no-B-frame setting is only a hint. The encoder logs the
79/// controls that took effect at debug level when it opens. A preset describes the encoder alone, not keyframe join time, transport delay,
80/// or viewer playout.
81///
82/// `#[non_exhaustive]` so a later policy can be added without breaking a
83/// `match`.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
85#[non_exhaustive]
86pub enum Preset {
87	/// The least per-frame encode time and buffering the backend supports.
88	#[default]
89	LowLatency,
90	/// More codec effort per frame for better compression.
91	Balanced,
92	/// The most codec effort the backend spends without queueing frames.
93	Quality,
94}
95
96/// The latency and compression controls a backend actually applied at open.
97///
98/// A report, not a request: a backend that has no distinct mapping for the
99/// requested [`Preset`] names the one whose controls it did apply, and one that
100/// could not confirm the controls a preset needs names none.
101#[derive(Clone, Debug, Default, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Applied {
104	/// The preset whose controls took effect, or `None` when the backend could
105	/// not confirm them (a refused or advisory low-latency setting).
106	pub preset: Option<Preset>,
107	/// The backend controls that took effect, for display, e.g.
108	/// `"p1, low-latency tuning, no B-frames, CQ 30 under the cap, 3-frame VBV"`. Not a parse target.
109	pub controls: String,
110	/// Whether [`Encoder::cut`] can force a group boundary; one that cannot (a V4L2
111	/// driver without the force-keyframe control) refuses every cut.
112	pub cut: bool,
113}
114
115impl Applied {
116	// A confirmed preset disables frame reordering even when the bitstream omits its bound.
117	fn reorder(&self, parsed: Option<u8>) -> Option<u8> {
118		self.preset.map(|_| 0).or(parsed)
119	}
120
121	// A confirmed preset neither reorders nor queues frames, so a frame trails the others by no more
122	// than its own encode, which the player's frame term already covers: the catalog `delay` is a
123	// known zero rather than one to measure. An unconfirmed one leaves it to measurement.
124	fn delay(&self) -> Option<std::time::Duration> {
125		self.preset.map(|_| std::time::Duration::ZERO)
126	}
127
128	/// A report that `preset` took effect through `controls`.
129	#[cfg_attr(
130		not(any(
131			feature = "openh264",
132			apple,
133			all(target_os = "linux", any(feature = "nvidia", feature = "vaapi"))
134		)),
135		allow(dead_code, reason = "only the encoder backends report a preset")
136	)]
137	pub(crate) fn new(preset: Preset, controls: impl Into<String>) -> Self {
138		Self {
139			preset: Some(preset),
140			controls: controls.into(),
141			// The encoder reports `cut` from the backend's `can_cut`.
142			cut: false,
143		}
144	}
145
146	/// A report of `controls` that were requested but that the backend cannot
147	/// confirm, so no preset is claimed.
148	#[cfg(any(
149		target_os = "windows",
150		all(target_os = "android", feature = "mediacodec"),
151		all(target_os = "linux", feature = "v4l2")
152	))]
153	pub(crate) fn unconfirmed(controls: impl Into<String>) -> Self {
154		Self {
155			preset: None,
156			controls: controls.into(),
157			cut: false,
158		}
159	}
160}
161
162/// Encoder configuration. `width` / `height` / `framerate` are the encoded
163/// output; external Vulkan frames are scaled by the backend on their GPU.
164///
165/// `#[non_exhaustive]`: build via [`Config::new`] and set the optional fields,
166/// so future knobs don't break callers.
167#[derive(Clone, Debug)]
168#[non_exhaustive]
169pub struct Config {
170	/// Encoded width in pixels.
171	pub width: u32,
172	/// Encoded height in pixels.
173	pub height: u32,
174	/// Encoded frame rate.
175	pub framerate: FrameRate,
176	/// The rendition's cap: the highest bitrate the encoder is configured for. `None` derives
177	/// [`resolved_bitrate`](Self::resolved_bitrate)'s default from the size, frame rate, and codec.
178	pub bitrate: Option<moq_net::bandwidth::Rate>,
179	/// The time between join points: a keyframe (an IDR with its parameter sets
180	/// in band) opens a group this often, so a subscriber joining mid-stream waits
181	/// at most this long for a picture it can decode. [`Encoder::cut`] opens one
182	/// sooner. Rounded to whole frames at `framerate`, never below one; see
183	/// [`effective_join`](Self::effective_join). Measured by the frames'
184	/// timestamps on a backend that can cut, so a source running slower than
185	/// `framerate` still opens a group this often, overshooting by less than one of
186	/// its frames. [`Encoder::new`] refuses zero. Defaults to two seconds.
187	pub join: std::time::Duration,
188	/// Output codec. Defaults to [`Codec::H264`].
189	pub codec: Codec,
190	/// Which encoder implementation to use. Defaults to [`Backend::Auto`].
191	pub backend: Backend,
192	/// How the encoder trades latency for compression. Defaults to
193	/// [`Preset::LowLatency`].
194	pub preset: Preset,
195	/// The finest quantizer (0-51, lower is finer) the rate control may pick.
196	/// `None` (the default) keeps the backend's own floor, which keeps quality
197	/// constant under the cap, so a calm scene spends less than it rather than
198	/// buying detail no one sees: 22 for openh264, 25 (H.264) or 23 (H.265) for
199	/// VideoToolbox.
200	///
201	/// Lower it to let the rate control code a picture finer when the cap
202	/// allows, or set `Some(0)` for no floor beyond the codec's own (openh264
203	/// never codes finer than 12). What that costs depends on the content: a
204	/// detailed calm scene spends more of the cap, while very simple content
205	/// can come out smaller and cheaper to encode and decode. Values above 51
206	/// act as 51. [`Applied`]'s controls name the floor that took effect.
207	///
208	/// openh264 and VideoToolbox read it; VideoToolbox before macOS 13 and iOS
209	/// 16 has no floor at all. The other backends keep their own quality
210	/// controls, tuned per device.
211	pub qp_floor: Option<u8>,
212	/// The color space of the input frames, written into the bitstream's VUI so a
213	/// decoder doesn't have to guess. `None` uses [`Color::infer`], which is both
214	/// what the crate's own RGB conversions produce and what a player falls back
215	/// to, so leaving it unset keeps the pixels and the label in agreement.
216	///
217	/// Set it to the first frame's [`Surface::color`](crate::Surface::color)
218	/// when that is known: a decoded or resized frame keeps its source's space,
219	/// which need not be the one this size infers. [`Encoder::encode`] refuses a
220	/// frame labelled differently with [`Error::ColorMismatch`] rather than
221	/// mislabel it.
222	pub color: Option<Color>,
223	/// Scale frames that arrive at another size to the encoded size, rather than
224	/// refusing them. `None` (the default) refuses them.
225	///
226	/// The scale runs wherever the encoder does, which for a
227	/// [`Sink`](super::Sink) is its own thread: a caller fanning one decoded
228	/// picture out to several encoders (a transcode ladder) hands each the
229	/// native frame and keeps the per-encoder pixel work off its own threads.
230	/// On Apple platforms a `Sink` encodes inline, so the scale runs on the
231	/// caller there. External Vulkan inputs the backend scales on the GPU are
232	/// left to it.
233	///
234	/// A scaled frame keeps its source's space, and an unlabelled one is labelled
235	/// with what [`Color::infer`] guesses for its original size. Set
236	/// [`color`](Self::color) to match, or a frame scaled across 576 lines is
237	/// refused with [`Error::ColorMismatch`].
238	pub resize: Option<crate::resize::Config>,
239	/// External Vulkan input device, required before opening a GPU-only encoder.
240	/// `None` retains selection for CPU and native decoder/capture surfaces.
241	#[cfg(target_os = "linux")]
242	pub input: Option<crate::frame::vulkan::Device>,
243	/// The hardware the encoder opens. [`Device::Auto`] (the default) picks
244	/// one: VA-API the first render node that encodes, decodes, and scales, so a
245	/// DMA-BUF moves between them without a copy; NVENC the first CUDA device, or
246	/// the one behind [`input`](Self::input); V4L2 the first node that encodes
247	/// H.264, which a driver whose format enumeration is wrong can defeat.
248	///
249	/// A render node an NVIDIA driver runs that is not the device behind
250	/// `input` is refused.
251	pub device: Device,
252}
253
254impl Config {
255	/// A config encoding `width` x `height` at `framerate`, with the default
256	/// codec, join, and bitrate.
257	pub fn new(width: u32, height: u32, framerate: FrameRate) -> Self {
258		Self {
259			width,
260			height,
261			framerate,
262			bitrate: None,
263			join: std::time::Duration::from_secs(2),
264			codec: Codec::default(),
265			backend: Backend::Auto,
266			preset: Preset::default(),
267			qp_floor: None,
268			color: None,
269			resize: None,
270			#[cfg(target_os = "linux")]
271			input: None,
272			device: Device::Auto,
273		}
274	}
275
276	/// The encoded resolution.
277	pub fn size(&self) -> Size {
278		Size::new(self.width, self.height)
279	}
280
281	/// The time between join points the encoder holds to: [`join`](Self::join)
282	/// rounded to whole frames at `framerate`, the value a catalog declares.
283	pub fn effective_join(&self) -> std::time::Duration {
284		// Rounded up, since a catalog declares it as the longest group.
285		let nanos = (u128::from(self.keyframe_interval()) * 1_000_000_000 * u128::from(self.framerate.denominator()))
286			.div_ceil(u128::from(self.framerate.numerator()));
287		std::time::Duration::from_nanos(nanos.try_into().unwrap_or(u64::MAX))
288	}
289
290	/// Frames between keyframes at `framerate`: [`join`](Self::join) rounded to
291	/// the nearest frame, and never below one, since a positive join shorter than
292	/// a frame still opens a group per frame. Each backend keys on this count, and
293	/// the encoder keys sooner when the timestamps reach it first.
294	pub(crate) fn keyframe_interval(&self) -> u32 {
295		self.framerate.frames(self.join).max(1)
296	}
297
298	/// The catalog rendition an encoder for this config produces.
299	///
300	/// Resolved by opening a throwaway encoder and encoding one frame, so the profile, level, and
301	/// constraints are the ones this machine writes into the bitstream rather than a guess. The
302	/// backend picks all three itself (VideoToolbox asks for High, openh264 leaves it at Baseline,
303	/// VAAPI writes Main) and its choice depends on the config it opened with, so reading them back
304	/// is the only way to know.
305	///
306	/// This is what lets a track be advertised before it carries anything: a subscriber can only
307	/// discover a track the catalog names, and an on-demand encoder only encodes once a subscriber
308	/// arrives. Publishing the probed rendition breaks that cycle without publishing a claim that
309	/// has to be corrected later, since it already says what the first keyframe will say.
310	///
311	/// Costs an encoder open and a single frame, so call it once per track. Call it *before*
312	/// opening the encoder you will actually use, so the two never hold a codec session at once.
313	///
314	/// # Errors
315	///
316	/// Fails when this machine cannot encode the config at all, which makes it a fail-fast check:
317	/// better here than on the first frame of a track that is already advertised.
318	pub async fn probe(&self) -> Result<hang::catalog::VideoConfig, Error> {
319		// Mid-gray, since the picture only has to make the encoder emit its parameter sets.
320		let size = self.size();
321		let i420 = crate::I420::new(size, vec![0x80u8; crate::I420::len(size)?])?;
322		let frame = Frame::new(moq_net::Timestamp::from_micros(0)?, crate::Surface::I420(i420));
323		Ok(self.probe_frame(frame).await?.0)
324	}
325
326	/// [`probe`](Self::probe), encoding `frame` rather than a CPU picture and handing back the
327	/// throwaway encoder, so the probe also proves the encoder reads that kind of surface.
328	pub(crate) async fn probe_frame(&self, frame: Frame) -> Result<(hang::catalog::VideoConfig, super::Sink), Error> {
329		// A `Sink` rather than an `Encoder`: this runs on whatever executor thread the caller is on,
330		// and the Windows backend's COM apartment has to be opened and closed on one thread.
331		let mut sink = super::Sink::open(self).await?;
332
333		// No cut: the first picture out of a fresh encoder is a keyframe on every backend, which
334		// is what carries the parameter sets, and a backend that cannot cut still probes.
335		sink.encode(frame).await?;
336		let mut annexb = Vec::new();
337		while let Some(encoded) = sink.receive()? {
338			annexb.extend_from_slice(&encoded.payload);
339		}
340		// A backend that pipelines holds the first frame, so drain it rather than reading nothing.
341		if annexb.is_empty() {
342			sink.flush().await?;
343			while let Some(encoded) = sink.receive()? {
344				annexb.extend_from_slice(&encoded.payload);
345			}
346		}
347
348		let parsed = match self.codec {
349			Codec::H264 => moq_mux::codec::h264::config(&annexb),
350			Codec::H265 => moq_mux::codec::h265::config(&annexb),
351		};
352		let mut rendition = parsed.map_err(|err| {
353			Error::codec(anyhow::anyhow!(
354				"{} emitted no usable parameter sets: {err}",
355				sink.name()
356			))
357		})?;
358
359		// Neither is in the bitstream: the target bitrate is nowhere in it, and the framerate only
360		// rides in an optional VUI. Fill them from the config that produced the rest.
361		rendition.bitrate.get_or_insert(self.resolved_bitrate().as_bps());
362		rendition.framerate.get_or_insert(self.framerate.as_f64());
363		rendition.reorder = sink.applied().reorder(rendition.reorder);
364		rendition.delay = sink.applied().delay();
365		Ok((rendition, sink))
366	}
367
368	/// Resolved input color space: explicit override, or the size-based guess
369	/// every player makes for an untagged stream. Backends write this into the
370	/// VUI; the crate's RGB conversions pick the same answer for the same size,
371	/// so the samples match what the bitstream claims.
372	pub(crate) fn resolved_color(&self) -> Color {
373		self.color.unwrap_or_else(|| Color::infer(self.size()))
374	}
375
376	/// The resize options, scaling on this encoder's device unless they name one.
377	fn resolved_resize(&self) -> Option<crate::resize::Config> {
378		let mut resize = self.resize.clone()?;
379		if resize.device == Device::Auto {
380			resize.device = self.device.clone();
381		}
382		Some(resize)
383	}
384
385	/// The rendition's cap: [`bitrate`](Self::bitrate), or the default for its size, frame rate, and
386	/// codec.
387	///
388	/// The default is `7.2 Mbps x Mpx / (1 + Mpx / 1.38)`, which levels off toward 10 Mbps, for
389	/// H.264 at 30 fps: 720p30 is 4 Mbps and 1080p30 is 6 Mbps. Frame rate scales it by
390	/// `(30 + (fps - 30) / 2) / 30`, since delta frames make it less than linear, and the codec by
391	/// its efficiency against H.264 (H.265 is 0.7). The JS publisher derives the same default.
392	pub fn resolved_bitrate(&self) -> moq_net::bandwidth::Rate {
393		self.bitrate
394			.unwrap_or_else(|| default_bitrate(self.size(), self.framerate, self.codec))
395	}
396}
397
398/// The cap an unconfigured encode resolves to; see [`Config::resolved_bitrate`].
399pub(crate) fn default_bitrate(size: Size, framerate: FrameRate, codec: Codec) -> moq_net::bandwidth::Rate {
400	let megapixels = size.pixels() as f64 / 1e6;
401	let frames = (30.0 + (framerate.as_f64() - 30.0) / 2.0) / 30.0;
402	let bps = 7.2e6 * megapixels / (1.0 + megapixels / 1.38) * frames * codec.bitrate_scale();
403	moq_net::bandwidth::Rate::from_bps(bps as u64)
404}
405
406/// Video encoder. Build one with [`Encoder::new`], submit raw [`Frame`]s via
407/// [`encode`](Self::encode), [`receive`](Self::receive) the resulting
408/// [`Encoded`] access units until it returns `None`, and publish them through a
409/// [`Publisher`](super::Publisher) built for the same [`Codec`].
410///
411/// An encoder is bound to the thread that opens it. Use [`Sink`](super::Sink)
412/// when the owner can move between threads.
413///
414/// ```compile_fail
415/// fn move_to_another_thread(encoder: moq_video::encode::Encoder) {
416///     std::thread::spawn(move || drop(encoder));
417/// }
418/// ```
419pub struct Encoder {
420	backend: Box<dyn backend::Backend>,
421	codec: Codec,
422	size: Size,
423	bitrate: moq_net::bandwidth::Rate,
424	/// What the backend wrote into the bitstream's VUI, kept so a frame declaring
425	/// a different space is caught rather than silently mislabeled.
426	color: Color,
427	/// A cut asked for by [`Encoder::cut`], applied to the next frame. Held
428	/// rather than applied immediately because the caller decides a group
429	/// boundary before it has the frame that opens it.
430	pending_cut: bool,
431	/// Where [`Config::join`] cuts a source slower than its frame rate.
432	join: Join,
433	/// How to scale a frame at another size, if at all; see [`Config::resize`].
434	resize: Option<crate::resize::Config>,
435	#[cfg(target_os = "linux")]
436	input: Option<crate::frame::vulkan::Device>,
437	/// Keeps direct use bound to the constructing thread, regardless of backend.
438	_thread_bound: PhantomData<Rc<()>>,
439}
440
441impl Encoder {
442	/// Open an encoder for `config`.
443	pub fn new(config: &Config) -> Result<Self, Error> {
444		// I420 chroma is subsampled 2x2, so the encoded resolution must be even.
445		let size = config.size();
446		size.validate("encoder")?;
447		size.validate_encodable("encoder", config.framerate)?;
448		if config.join.is_zero() {
449			return Err(Error::ZeroJoin);
450		}
451
452		let backend = backend::open(config)?;
453		let applied = backend.applied();
454		tracing::debug!(encoder = backend.name(), requested = ?config.preset, applied = ?applied.preset, controls = %applied.controls, "encoder preset");
455		Ok(Self {
456			backend,
457			codec: config.codec,
458			size,
459			bitrate: config.resolved_bitrate(),
460			color: config.resolved_color(),
461			pending_cut: false,
462			join: Join::new(config),
463			resize: config.resolved_resize(),
464			#[cfg(target_os = "linux")]
465			input: config.input,
466			_thread_bound: PhantomData,
467		})
468	}
469
470	/// The encoder name in use, e.g. `"videotoolbox"`.
471	pub fn name(&self) -> &str {
472		self.backend.name()
473	}
474
475	/// The latency and compression controls the backend applied for
476	/// [`Config::preset`], and whether it cuts, fixed for the session's lifetime.
477	pub fn applied(&self) -> Applied {
478		Applied {
479			cut: self.backend.can_cut(),
480			..self.backend.applied()
481		}
482	}
483
484	/// The resolution this encoder emits; external Vulkan inputs may be larger.
485	pub fn size(&self) -> Size {
486		self.size
487	}
488
489	/// The current target bitrate: what [`Config::bitrate`] resolved to at open, or
490	/// the last value [`set_bitrate`](Self::set_bitrate) accepted.
491	pub fn bitrate(&self) -> moq_net::bandwidth::Rate {
492		self.bitrate
493	}
494
495	/// Retune the live encoder to `bitrate`, taking effect from roughly the next frame. No IDR is forced, so this is cheap enough to
496	/// drive from a congestion controller: pair it with
497	/// [`moq_mux::rate::Control`], which decides *when* the target
498	/// is worth moving.
499	///
500	/// Setting the rate the encoder is already at does nothing and succeeds.
501	///
502	/// # Errors
503	///
504	/// Returns [`Error::BitrateUnsupported`] if this backend can't retune while
505	/// running. That's not fatal: the encoder keeps running at its current rate,
506	/// so a caller driving a control loop keeps encoding, and may try again later.
507	pub fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
508		if bitrate == self.bitrate {
509			return Ok(());
510		}
511		// The backends speak to codec APIs that want a plain integer, so the unit is
512		// unwrapped once here rather than in each of them.
513		self.backend.set_bitrate(bitrate.as_bps())?;
514		// Only after the backend accepts it, so a failed set doesn't leave the
515		// getter reporting a rate the encoder isn't using.
516		self.bitrate = bitrate;
517		Ok(())
518	}
519
520	/// The codec this encoder emits. A [`Publisher`](super::Publisher) must be
521	/// built for the same codec to publish its packets.
522	pub fn codec(&self) -> Codec {
523		self.codec
524	}
525
526	/// Cut a new group at the next frame, on top of the boundaries
527	/// [`Config::join`] places on its own. Today that means encoding it as a
528	/// keyframe (an IDR), so a subscriber can start decoding there.
529	///
530	/// Rarely needed: the encoder opens groups automatically, so reach for this
531	/// only when something outside the encoder needs a boundary at a specific
532	/// frame. A source group boundary (transcode mirrors the source's groups) is
533	/// the usual reason; a scene change, a source switch, or a subscriber joining
534	/// over [`track::Info::refresh`](moq_net::track::Info::refresh) are others.
535	/// Capture cuts for joiners itself.
536	///
537	/// The request waits for the next [`encode`](Self::encode) rather than applying
538	/// at once, so it is safe to call before the frame exists. Calling it repeatedly
539	/// before a frame arrives cuts once, not several times.
540	///
541	/// # Errors
542	///
543	/// Returns [`Error::CutUnsupported`] when this backend cannot force a group
544	/// boundary (a V4L2 driver without the force-keyframe control), in which case
545	/// nothing is queued: groups keep falling every [`Config::join`]'s worth of
546	/// frames at [`Config::framerate`], and the caller decides whether that layout
547	/// is acceptable rather than finding out from the stream.
548	pub fn cut(&mut self) -> Result<(), Error> {
549		self.check_cut()?;
550		self.pending_cut = true;
551		Ok(())
552	}
553
554	/// What [`cut`](Self::cut) would answer, without queueing anything.
555	pub(crate) fn check_cut(&self) -> Result<(), Error> {
556		match self.backend.can_cut() {
557			true => Ok(()),
558			false => Err(Error::CutUnsupported(self.backend.name())),
559		}
560	}
561
562	/// Submit one raw [`Frame`], whether it came from capture, a decoder (the
563	/// transcode input path), or your own pixels via
564	/// [`Surface::rgba`](crate::Surface::rgba).
565	///
566	/// Its access units come out of [`receive`](Self::receive), each carrying the
567	/// timestamp of the raw frame it came from: a backend that buffers readies an
568	/// earlier frame's output, so the two don't always line up.
569	///
570	/// A GPU surface feeds a hardware encoder on the same device directly
571	/// (NVDEC -> NVENC never leaves the GPU, a `CVPixelBuffer` goes straight to
572	/// VideoToolbox); anything else falls back to a CPU I420 upload. The frame must
573	/// already be at the encoder's resolution, except external Vulkan inputs
574	/// which the backend scales on the GPU. [`Config::resize`] scales the rest
575	/// here; without it, scale them with
576	/// [`Frame::resize`](crate::Frame::resize), which
577	/// [`decode::Config::scale_hint`](crate::decode::Config::scale_hint) lets a
578	/// hardware decoder make a no-op. An [unscaled](moq_net::Timestamp::unscaled)
579	/// frame has no time and fails with [`Error::TimeOverflow`].
580	pub fn encode(&mut self, frame: &Frame) -> Result<(), Error> {
581		// A transposed frame is why this compares the shape rather than a byte
582		// count: 240x320 and 320x240 hold the same number of bytes.
583		#[cfg(target_os = "linux")]
584		let external = if let crate::Surface::Vulkan(image) = &frame.surface {
585			let device = image.image().device;
586			if self.input != Some(device) {
587				return Err(Error::Unsupported(format!(
588					"external Vulkan {device} does not match encoder input {:?}",
589					self.input
590				)));
591			}
592			true
593		} else {
594			false
595		};
596		#[cfg(not(target_os = "linux"))]
597		let external = false;
598		// A backend that scales a GPU surface itself writes it straight into its
599		// own input, rather than into a scaled copy made here.
600		let scaled = external
601			|| self.resize.as_ref().is_some_and(|config| {
602				config.output.resolve(&frame.surface) == crate::Output::Native && self.backend.scales(&frame.surface)
603			});
604		let resized;
605		let frame = match &self.resize {
606			Some(config) if !scaled && frame.size() != self.size => {
607				resized = frame.resize(self.size, config)?;
608				&resized
609			}
610			_ => frame,
611		};
612		let size = frame.size();
613		if !scaled && size != self.size {
614			return Err(Error::codec(anyhow::anyhow!(
615				"frame {size} does not match encoder {}",
616				self.size
617			)));
618		}
619		// The VUI is fixed when the session opens, so a frame in a different space
620		// would be encoded under the wrong label. Reached by resizing across the
621		// standard-definition boundary, where the pixels keep their space but the
622		// encoder was sized into another one, and by a source whose space changes
623		// mid-stream.
624		// A frame the backend scales keeps its samples' space, and an unlabelled
625		// one means what `Color::infer` guesses for its own size, as
626		// `Frame::resize` would have labelled the copy.
627		let color = match frame.surface.color() {
628			None if scaled && !external && size != self.size => Some(Color::infer(size)),
629			color => color,
630		};
631		if let Some(color) = color
632			&& color != self.color
633		{
634			return Err(Error::ColorMismatch {
635				frame: color,
636				encoder: self.color,
637			});
638		}
639		// Video is timed: an unscaled frame has no time to space keyframes by.
640		let timestamp = std::time::Duration::try_from(frame.timestamp)?;
641		let cut = self.pending_cut || (self.backend.can_cut() && self.join.due(timestamp));
642		self.backend.encode(frame, cut)?;
643		// Cleared only once the frame is through: a failed encode produced no
644		// picture, so the request still belongs to whatever comes next rather than
645		// being swallowed. The size check above returns early for the same reason.
646		self.pending_cut = false;
647		self.join.encoded(timestamp, cut);
648		Ok(())
649	}
650
651	/// Pop the oldest ready access unit, or `None` while the codec holds the rest.
652	///
653	/// Call until it returns `None` after each [`encode`](Self::encode) and
654	/// [`flush`](Self::flush).
655	pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
656		let encoded = self.backend.receive()?;
657		if let Some(encoded) = &encoded {
658			self.join.observe(encoded);
659		}
660		Ok(encoded)
661	}
662
663	/// Mark the end of input, so [`receive`](Self::receive) returns every access
664	/// unit the codec is still holding. The encoder stays ready for the frames
665	/// that follow. Each keeps the timestamp of the raw frame it was encoded from,
666	/// so a drained tail stays in step with what came before it.
667	///
668	/// Call it before dropping the encoder, or its last frames are lost.
669	///
670	/// Reach for this at a boundary the output has to respect, which for a live
671	/// broadcast is a group: a hardware codec that pipelines holds the last frames
672	/// of a group past its end, and they would otherwise be published into the next
673	/// group ahead of its keyframe, where a consumer joining there cannot decode
674	/// them. Publishing frame-by-frame with no group structure needs none of this.
675	///
676	/// Not free: emptying the pipeline gives up the overlap between one frame's
677	/// encode and the next frame's submission, so flush at boundaries rather than
678	/// per frame.
679	pub fn flush(&mut self) -> Result<(), Error> {
680		self.backend.flush()
681	}
682
683	/// Submit `frame` and collect everything it readied.
684	#[cfg(test)]
685	pub(crate) fn encode_all(&mut self, frame: &Frame) -> Result<Vec<Encoded>, Error> {
686		self.encode(frame)?;
687		self.receive_all()
688	}
689
690	/// Flush and collect the tail.
691	#[cfg(test)]
692	pub(crate) fn flush_all(&mut self) -> Result<Vec<Encoded>, Error> {
693		self.flush()?;
694		self.receive_all()
695	}
696
697	#[cfg(test)]
698	fn receive_all(&mut self) -> Result<Vec<Encoded>, Error> {
699		let mut encoded = Vec::new();
700		while let Some(unit) = self.receive()? {
701			encoded.push(unit);
702		}
703		Ok(encoded)
704	}
705}
706
707/// The keyframes [`Config::join`] adds for a source slower than [`Config::framerate`].
708///
709/// Each backend keys every [`Config::keyframe_interval`] frames, which a slower
710/// source (a camera dropping to 20 fps in low light) stretches past the join the
711/// catalog declared. This keys the first frame whose distance from the last
712/// keyframe, counted in frames at the configured rate and rounded to the nearest,
713/// reaches that interval: a source at the configured rate keys on the same frame
714/// as the backend whatever its jitter, and a slower one overshoots the join by
715/// less than one of its frames. A faster source reaches the backend's count first.
716struct Join {
717	framerate: FrameRate,
718	interval: u32,
719	/// The last keyframe's timestamp, `None` before the first frame, which every
720	/// backend keys.
721	last: Option<std::time::Duration>,
722}
723
724impl Join {
725	fn new(config: &Config) -> Self {
726		Self {
727			framerate: config.framerate,
728			interval: config.keyframe_interval(),
729			last: None,
730		}
731	}
732
733	/// Whether the frame at `timestamp` is due a keyframe.
734	fn due(&self, timestamp: std::time::Duration) -> bool {
735		self.last
736			.and_then(|last| timestamp.checked_sub(last))
737			.is_some_and(|elapsed| self.framerate.frames(elapsed) >= self.interval)
738	}
739
740	/// The frame at `timestamp` went in, keyed when `cut`.
741	fn encoded(&mut self, timestamp: std::time::Duration, cut: bool) {
742		// A timestamp behind the last keyframe starts a new timeline, measured from
743		// here rather than held until it catches up with the old one.
744		if cut || self.last.is_none_or(|last| timestamp < last) {
745			self.last = Some(timestamp);
746		}
747	}
748
749	/// Count `encoded` if it is a keyframe, including one the backend placed on
750	/// its own count, so the next is measured from the latest.
751	fn observe(&mut self, encoded: &Encoded) {
752		if encoded.keyframe {
753			self.last = self.last.max(std::time::Duration::try_from(encoded.timestamp).ok());
754		}
755	}
756}
757
758#[cfg(test)]
759mod tests {
760	#![cfg_attr(
761		not(feature = "openh264"),
762		allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
763	)]
764
765	use std::collections::VecDeque;
766
767	use super::*;
768
769	use crate::{I420, Surface};
770
771	#[test]
772	fn reorder_is_declared_only_for_confirmed_controls() {
773		for preset in [Preset::LowLatency, Preset::Balanced, Preset::Quality] {
774			let applied = Applied {
775				preset: Some(preset),
776				..Applied::default()
777			};
778			assert_eq!(applied.reorder(None), Some(0));
779			assert_eq!(applied.reorder(Some(3)), Some(0));
780		}
781		let unconfirmed = Applied::default();
782		assert_eq!(unconfirmed.reorder(None), None);
783		assert_eq!(unconfirmed.reorder(Some(3)), Some(3));
784	}
785
786	#[test]
787	fn delay_is_a_known_zero_only_for_confirmed_controls() {
788		for preset in [Preset::LowLatency, Preset::Balanced, Preset::Quality] {
789			let applied = Applied {
790				preset: Some(preset),
791				..Applied::default()
792			};
793			assert_eq!(applied.delay(), Some(std::time::Duration::ZERO));
794		}
795		assert_eq!(Applied::default().delay(), None);
796	}
797
798	/// A mid-gray RGBA buffer: encodable without a camera.
799	fn gray_rgba(width: u32, height: u32) -> Vec<u8> {
800		vec![0x80u8; width as usize * height as usize * 4]
801	}
802
803	/// The `index`th frame of a mid-gray 30fps stream, so a round-tripped
804	/// timestamp identifies the frame it came from.
805	fn gray_frame(width: u32, height: u32, index: u64) -> Frame {
806		let surface = Surface::rgba(&gray_rgba(width, height), Size::new(width, height)).unwrap();
807		Frame::new(at(index), surface)
808	}
809
810	/// The presentation time of frame `index` at 30fps.
811	fn at(index: u64) -> moq_net::Timestamp {
812		moq_net::Timestamp::from_micros(index * 33_333).unwrap()
813	}
814
815	/// The payloads of some encoded frames, for the Annex-B assertions.
816	fn payloads(frames: &[Encoded]) -> Vec<bytes::Bytes> {
817		frames.iter().map(|f| f.payload.clone()).collect()
818	}
819
820	#[test]
821	#[cfg(feature = "openh264")]
822	fn software_encoder_emits_annexb() {
823		let config = Config {
824			backend: Backend::Software,
825			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
826		};
827		let mut encoder = Encoder::new(&config).expect("openh264 is vendored, always available");
828		assert_eq!(encoder.name(), "openh264");
829
830		let mut frames = Vec::new();
831		for i in 0..30 {
832			if i == 0 {
833				encoder.cut().unwrap();
834			}
835			frames.extend(encoder.encode_all(&gray_frame(320, 240, i)).unwrap());
836		}
837		frames.extend(encoder.flush_all().unwrap());
838
839		assert!(!frames.is_empty(), "encoder produced no packets");
840
841		// Every encoded frame carries the timestamp of the raw frame it came from,
842		// so the stream stays in step even if a backend buffers.
843		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
844		assert!(
845			micros.windows(2).all(|w| w[0] < w[1]),
846			"encoded timestamps not strictly increasing: {micros:?}"
847		);
848		assert!(
849			micros.iter().all(|&t| t % 33_333 == 0 && t < 30 * 33_333),
850			"encoded timestamp outside the fed set: {micros:?}"
851		);
852
853		// The first packet must start with an Annex-B start code so the Annex-B
854		// importer can find the inline SPS/PPS.
855		let packets = payloads(&frames);
856		let first = &packets[0];
857		let has_start_code = first.starts_with(&[0, 0, 0, 1]) || first.starts_with(&[0, 0, 1]);
858		assert!(
859			has_start_code,
860			"first packet is not Annex-B: {:02x?}",
861			&first[..first.len().min(8)]
862		);
863	}
864
865	/// The same path starting from planar I420 the caller already has.
866	#[test]
867	#[cfg(feature = "openh264")]
868	fn encode_i420_surface_emits_annexb() {
869		let config = Config {
870			backend: Backend::Software,
871			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
872		};
873		let mut encoder = Encoder::new(&config).unwrap();
874
875		// A mid-gray I420 frame: flat 0x80 across all three planes.
876		let size = Size::new(320, 240);
877		let i420 = I420::new(size, vec![0x80u8; I420::len(size).unwrap()]).unwrap();
878		let frame = Frame::new(at(0), Surface::I420(i420));
879		let mut frames = encoder.encode_all(&frame).unwrap();
880		frames.extend(encoder.flush_all().unwrap());
881		assert!(!frames.is_empty());
882		let packets = payloads(&frames);
883		assert!(packets[0].starts_with(&[0, 0, 0, 1]) || packets[0].starts_with(&[0, 0, 1]));
884	}
885
886	/// A frame that isn't the encoder's size must error rather than encode its
887	/// top-left corner.
888	#[test]
889	fn encode_rejects_dimension_mismatch() {
890		let Ok(mut encoder) = Encoder::new(&Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())) else {
891			return;
892		};
893		assert!(matches!(
894			encoder.encode_all(&gray_frame(640, 480, 0)),
895			Err(Error::Codec(_))
896		));
897	}
898
899	/// An encoder told to resize scales a frame at another size itself, so a
900	/// [`Sink`](super::super::Sink) does that work on its own thread.
901	#[test]
902	fn encode_resizes_when_configured() {
903		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
904		config.resize = Some(crate::resize::Config::default());
905		let Ok(mut encoder) = Encoder::new(&config) else {
906			return;
907		};
908		let mut frames = encoder.encode_all(&gray_frame(640, 480, 0)).unwrap();
909		frames.extend(encoder.flush_all().unwrap());
910		assert!(!frames.is_empty());
911	}
912
913	/// A transposed frame is why the encoder compares the shape rather than the
914	/// byte count: 240x320 and 320x240 hold the same number of bytes, so a length
915	/// check alone would accept this and encode garbage.
916	#[test]
917	fn encode_rejects_transposed_frame() {
918		let Ok(mut encoder) = Encoder::new(&Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())) else {
919			return;
920		};
921
922		let transposed = gray_frame(240, 320, 0);
923		assert_eq!(
924			gray_rgba(240, 320).len(),
925			gray_rgba(320, 240).len(),
926			"the byte counts must collide"
927		);
928		assert!(matches!(encoder.encode_all(&transposed), Err(Error::Codec(_))));
929	}
930
931	#[test]
932	fn unknown_named_encoder_errors() {
933		let config = Config {
934			backend: Backend::Named("definitely_not_a_codec".into()),
935			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
936		};
937		// Not `NoEncoder`: that reads "no usable video encoder found (tried: )"
938		// and describes a machine with no encoder rather than a name that is not
939		// one. The name asked for and the names available are both here.
940		let err = Encoder::new(&config).err().expect("an unknown name cannot open");
941		assert!(
942			matches!(&err, Error::UnknownEncoder { name, .. } if name == "definitely_not_a_codec"),
943			"unexpected error: {err:?}",
944		);
945	}
946
947	/// Exercises the hand-rolled VideoToolbox backend end to end on macOS:
948	/// synthetic frames through the real `VTCompressionSession`, asserting the
949	/// AVCC -> Annex-B conversion produces a self-contained IDR (SPS+PPS+slice).
950	#[cfg(apple)]
951	#[test]
952	fn videotoolbox_emits_annexb_keyframe() {
953		let config = Config {
954			backend: Backend::Named("videotoolbox".into()),
955			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
956		};
957		let mut encoder = Encoder::new(&config).expect("videotoolbox is available on macOS");
958		assert_eq!(encoder.name(), "videotoolbox");
959
960		let mut frames = Vec::new();
961		for i in 0..10 {
962			if i == 0 {
963				encoder.cut().unwrap();
964			}
965			frames.extend(encoder.encode_all(&gray_frame(320, 240, i)).unwrap());
966		}
967		frames.extend(encoder.flush_all().unwrap());
968
969		assert!(!frames.is_empty(), "encoder produced no packets");
970		// VideoToolbox completes each frame before returning, so the timestamps come
971		// back one per input frame, in order.
972		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
973		assert!(
974			micros.windows(2).all(|w| w[0] < w[1]),
975			"encoded timestamps not strictly increasing: {micros:?}"
976		);
977
978		let packets = payloads(&frames);
979		let first = &packets[0];
980		assert!(
981			first.starts_with(&[0, 0, 0, 1]) || first.starts_with(&[0, 0, 1]),
982			"first packet is not Annex-B"
983		);
984
985		// The first access unit must be a self-contained IDR: SPS (7), PPS (8),
986		// IDR slice (5), all spliced in-band by the AVCC -> Annex-B conversion.
987		let types = nal_types(first);
988		assert!(types.contains(&7), "no SPS in first packet: {types:?}");
989		assert!(types.contains(&8), "no PPS in first packet: {types:?}");
990		assert!(types.contains(&5), "first packet is not an IDR: {types:?}");
991	}
992
993	/// HEVC via VideoToolbox: synthetic frames through the real
994	/// `VTCompressionSession` with `kCMVideoCodecType_HEVC`, asserting the
995	/// HVCC -> Annex-B conversion produces a self-contained IRAP (VPS+SPS+PPS+IDR).
996	#[cfg(apple)]
997	#[test]
998	fn videotoolbox_emits_annexb_keyframe_h265() {
999		let config = Config {
1000			codec: Codec::H265,
1001			backend: Backend::Named("videotoolbox".into()),
1002			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1003		};
1004		let mut encoder = Encoder::new(&config).expect("videotoolbox HEVC is available on macOS");
1005		assert_eq!(encoder.name(), "videotoolbox");
1006		assert_eq!(encoder.codec(), Codec::H265);
1007
1008		let mut frames = Vec::new();
1009		for i in 0..10 {
1010			if i == 0 {
1011				encoder.cut().unwrap();
1012			}
1013			frames.extend(encoder.encode_all(&gray_frame(320, 240, i)).unwrap());
1014		}
1015		frames.extend(encoder.flush_all().unwrap());
1016
1017		assert!(!frames.is_empty(), "encoder produced no packets");
1018		let packets = payloads(&frames);
1019		let first = &packets[0];
1020		assert!(
1021			first.starts_with(&[0, 0, 0, 1]) || first.starts_with(&[0, 0, 1]),
1022			"first packet is not Annex-B"
1023		);
1024
1025		// The first access unit must be a self-contained IRAP: VPS (32), SPS (33),
1026		// PPS (34), and an IDR slice (16..=23), spliced in-band by the conversion.
1027		let types = hevc_nal_types(first);
1028		assert!(types.contains(&32), "no VPS in first packet: {types:?}");
1029		assert!(types.contains(&33), "no SPS in first packet: {types:?}");
1030		assert!(types.contains(&34), "no PPS in first packet: {types:?}");
1031		assert!(
1032			types.iter().any(|t| (16..=23).contains(t)),
1033			"first packet is not an IRAP: {types:?}"
1034		);
1035	}
1036
1037	/// HEVC NAL unit types in an Annex-B buffer (type = `(byte >> 1) & 0x3f`).
1038	#[cfg(apple)]
1039	fn hevc_nal_types(annexb: &[u8]) -> Vec<u8> {
1040		let mut types = Vec::new();
1041		let mut i = 0;
1042		while i + 3 < annexb.len() {
1043			if annexb[i..i + 3] == [0, 0, 1] {
1044				types.push((annexb[i + 3] >> 1) & 0x3f);
1045				i += 3;
1046			} else {
1047				i += 1;
1048			}
1049		}
1050		types
1051	}
1052
1053	/// Feed a GPU surface (NV12 `CVPixelBuffer`) straight into VideoToolbox:
1054	/// the zero-copy capture -> encode path, no I420 round-trip.
1055	#[cfg(apple)]
1056	#[test]
1057	fn videotoolbox_encodes_surface_zero_copy() {
1058		let config = Config {
1059			backend: Backend::Named("videotoolbox".into()),
1060			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1061		};
1062		let mut encoder = Encoder::new(&config).unwrap();
1063
1064		let mut frames = Vec::new();
1065		for i in 0..10 {
1066			if i == 0 {
1067				encoder.cut().unwrap();
1068			}
1069			let frame = Frame::new(at(i), Surface::PixelBuffer(nv12_surface(320, 240)));
1070			frames.extend(encoder.encode_all(&frame).unwrap());
1071		}
1072		frames.extend(encoder.flush_all().unwrap());
1073
1074		assert!(!frames.is_empty());
1075		let packets = payloads(&frames);
1076		let types = nal_types(&packets[0]);
1077		assert!(
1078			types.contains(&7) && types.contains(&8) && types.contains(&5),
1079			"no IDR: {types:?}"
1080		);
1081	}
1082
1083	/// A software encoder must download a GPU surface to I420 first. Exercises
1084	/// the NV12 -> I420 fallback path.
1085	#[cfg(all(apple, feature = "openh264"))]
1086	#[test]
1087	fn openh264_downloads_surface() {
1088		let config = Config {
1089			backend: Backend::Software,
1090			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1091		};
1092		let mut encoder = Encoder::new(&config).unwrap();
1093
1094		encoder.cut().unwrap();
1095		let frame = Frame::new(at(0), Surface::PixelBuffer(nv12_surface(320, 240)));
1096		let mut frames = encoder.encode_all(&frame).unwrap();
1097		frames.extend(encoder.flush_all().unwrap());
1098
1099		assert!(!frames.is_empty());
1100		let packets = payloads(&frames);
1101		assert!(packets[0].starts_with(&[0, 0, 0, 1]) || packets[0].starts_with(&[0, 0, 1]));
1102	}
1103
1104	/// A mid-gray NV12 `CVPixelBuffer`, the format AVFoundation/ScreenCaptureKit
1105	/// hand us. Y and interleaved UV planes filled with 128.
1106	#[cfg(apple)]
1107	fn nv12_surface(width: u32, height: u32) -> crate::frame::apple::PixelBuffer {
1108		use std::ptr::{self, NonNull};
1109
1110		use objc2_core_foundation::CFRetained;
1111		use objc2_core_video::{
1112			CVPixelBuffer, CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane, CVPixelBufferGetBytesPerRowOfPlane,
1113			CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags, CVPixelBufferUnlockBaseAddress,
1114			kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
1115		};
1116
1117		let mut raw: *mut CVPixelBuffer = ptr::null_mut();
1118		let status = unsafe {
1119			CVPixelBufferCreate(
1120				None,
1121				width as usize,
1122				height as usize,
1123				kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
1124				None,
1125				NonNull::new(&mut raw).unwrap(),
1126			)
1127		};
1128		assert_eq!(status, 0, "CVPixelBufferCreate failed");
1129		let buffer = unsafe { CFRetained::from_raw(NonNull::new(raw).unwrap()) };
1130
1131		let flags = CVPixelBufferLockFlags(0);
1132		assert_eq!(unsafe { CVPixelBufferLockBaseAddress(&buffer, flags) }, 0);
1133		for (plane, rows) in [(0usize, height as usize), (1usize, height as usize / 2)] {
1134			let base = CVPixelBufferGetBaseAddressOfPlane(&buffer, plane) as *mut u8;
1135			let stride = CVPixelBufferGetBytesPerRowOfPlane(&buffer, plane);
1136			unsafe { ptr::write_bytes(base, 128, stride * rows) };
1137		}
1138		unsafe { CVPixelBufferUnlockBaseAddress(&buffer, flags) };
1139
1140		crate::frame::apple::PixelBuffer::new(buffer, width, height)
1141	}
1142
1143	/// NAL unit types in an Annex-B buffer, found via 3-byte start codes (a
1144	/// 4-byte `00 00 00 01` code contains `00 00 01` too, so this catches both).
1145	fn nal_types(annexb: &[u8]) -> Vec<u8> {
1146		let mut types = Vec::new();
1147		let mut i = 0;
1148		while i + 3 < annexb.len() {
1149			if annexb[i..i + 3] == [0, 0, 1] {
1150				types.push(annexb[i + 3] & 0x1f);
1151				i += 3;
1152			} else {
1153				i += 1;
1154			}
1155		}
1156		types
1157	}
1158
1159	/// CPU path: synthetic RGBA through the Media Foundation hardware encoder
1160	/// (I420 -> system-memory NV12 upload). Ignored: needs a hardware encoder MFT,
1161	/// which GPU-less CI runners lack. Run with `--ignored`.
1162	#[cfg(target_os = "windows")]
1163	#[test]
1164	#[ignore = "needs a Media Foundation hardware encoder; see quest/m5/video-hardware.md"]
1165	fn mediafoundation_cpu_rgba() {
1166		let config = Config {
1167			backend: Backend::Named("mediafoundation".into()),
1168			..Config::new(640, 480, crate::FrameRate::new(30, 1).unwrap())
1169		};
1170		let mut encoder = Encoder::new(&config).expect("hardware H.264 encoder available");
1171		assert_eq!(encoder.name(), "mediafoundation");
1172
1173		let mut frames = Vec::new();
1174		for i in 0..30 {
1175			if i == 0 {
1176				encoder.cut().unwrap();
1177			}
1178			frames.extend(encoder.encode_all(&gray_frame(640, 480, i)).unwrap());
1179		}
1180		frames.extend(encoder.flush_all().unwrap());
1181
1182		assert!(!frames.is_empty(), "encoder produced no packets");
1183		// The MFT buffers, so packets come back stamped with the frame they were
1184		// encoded from rather than whichever frame was going in at the time.
1185		let micros: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
1186		assert!(
1187			micros.windows(2).all(|w| w[0] < w[1]),
1188			"encoded timestamps not strictly increasing: {micros:?}"
1189		);
1190		assert!(
1191			micros.iter().all(|&t| t % 33_333 == 0 && t < 30 * 33_333),
1192			"encoded timestamp outside the fed set: {micros:?}"
1193		);
1194
1195		let packets = payloads(&frames);
1196		let types = nal_types(&packets[0]);
1197		assert!(types.contains(&7), "no SPS in first packet: {types:?}");
1198		assert!(types.contains(&8), "no PPS in first packet: {types:?}");
1199		assert!(types.contains(&5), "first packet is not an IDR: {types:?}");
1200	}
1201
1202	/// Full zero-copy path: real camera -> D3D11 NV12 texture -> hardware encoder
1203	/// via the DXGI device manager, no CPU round-trip. Ignored: needs a camera and
1204	/// a GPU. Run with `--ignored`.
1205	#[cfg(all(target_os = "windows", feature = "capture"))]
1206	#[tokio::test]
1207	#[ignore = "needs a Windows camera and GPU; see quest/m5/video-hardware.md"]
1208	async fn mediafoundation_camera_texture() {
1209		let mut camera = crate::capture::open(&crate::capture::Config::default())
1210			.await
1211			.expect("open default camera");
1212		let (w, h) = (camera.width(), camera.height());
1213
1214		let config = Config {
1215			backend: Backend::Named("mediafoundation".into()),
1216			..Config::new(w, h, camera.framerate().unwrap_or(crate::FrameRate::integer(30)))
1217		};
1218		let mut encoder = Encoder::new(&config).expect("hardware H.264 encoder available");
1219
1220		let mut frames = Vec::new();
1221		let mut textures = 0;
1222		for i in 0..30 {
1223			let frame = camera
1224				.read()
1225				.await
1226				.expect("read camera frame")
1227				.expect("frame, not end of stream");
1228			if matches!(frame.surface, Surface::Texture(_)) {
1229				textures += 1;
1230			}
1231			if i == 0 {
1232				encoder.cut().unwrap();
1233			}
1234			frames.extend(encoder.encode_all(&frame).unwrap());
1235		}
1236		frames.extend(encoder.flush_all().unwrap());
1237
1238		// On a GPU this exercises the zero-copy texture path; the assert guards
1239		// against silently testing only the CPU fallback.
1240		assert!(textures > 0, "capture never produced a GPU texture");
1241		assert!(!frames.is_empty(), "encoder produced no packets");
1242		let packets = payloads(&frames);
1243		let types = nal_types(&packets[0]);
1244		assert!(
1245			types.contains(&7) && types.contains(&8) && types.contains(&5),
1246			"no IDR: {types:?}"
1247		);
1248	}
1249
1250	/// The openh264 retune goes through the raw `set_option` FFI, so this covers
1251	/// both that the call is accepted and that the encoder keeps producing after
1252	/// it. A wrong option id or a bad `SBitrateInfo` layout would fail here.
1253	#[test]
1254	#[cfg(feature = "openh264")]
1255	fn set_bitrate_retunes_software_encoder() {
1256		let config = Config {
1257			backend: Backend::Software,
1258			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1259		};
1260		let mut encoder = Encoder::new(&config).unwrap();
1261
1262		let opened = encoder.bitrate();
1263		assert_eq!(opened, config.resolved_bitrate());
1264
1265		// Encode first: this is the live-retune path, once the encoder exists.
1266		encoder.encode_all(&gray_frame(320, 240, 0)).unwrap();
1267
1268		let halved = opened.scaled(0.5);
1269		encoder.set_bitrate(halved).unwrap();
1270		assert_eq!(encoder.bitrate(), halved);
1271
1272		// The retuned encoder must still emit a decodable keyframe, not wedge.
1273		let frames = encoder.encode_all(&gray_frame(320, 240, 1)).unwrap();
1274		assert!(!frames.is_empty(), "encoder produced nothing after a retune");
1275		let packets = payloads(&frames);
1276		assert!(packets[0].starts_with(&[0, 0, 0, 1]) || packets[0].starts_with(&[0, 0, 1]));
1277	}
1278
1279	/// Regression: openh264 creates its encoder lazily on the first frame and
1280	/// rejects `SetOption` with `cmInitExpected` until then. A retune before any
1281	/// frame must be deferred to the first encode, not reported as a failure.
1282	#[test]
1283	#[cfg(feature = "openh264")]
1284	fn set_bitrate_before_the_first_frame_is_deferred() {
1285		let config = Config {
1286			backend: Backend::Software,
1287			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1288		};
1289		let mut encoder = Encoder::new(&config).unwrap();
1290
1291		let halved = encoder.bitrate().scaled(0.5);
1292		encoder.set_bitrate(halved).expect("a retune before the first frame");
1293		assert_eq!(encoder.bitrate(), halved);
1294
1295		// The deferred rate is applied during this encode, which must still work.
1296		let frames = encoder.encode_all(&gray_frame(320, 240, 0)).unwrap();
1297		assert!(!frames.is_empty());
1298
1299		// And the encoder is live now, so a further retune takes the direct path.
1300		encoder.set_bitrate(halved.scaled(0.5)).unwrap();
1301		assert!(encoder.encode_all(&gray_frame(320, 240, 1)).is_ok());
1302	}
1303
1304	#[test]
1305	fn default_bitrate_scales_with_resolution() {
1306		let small = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap()).resolved_bitrate();
1307		let large = Config::new(1920, 1080, crate::FrameRate::new(30, 1).unwrap()).resolved_bitrate();
1308		assert!(large > small);
1309		assert!(small > moq_net::bandwidth::Rate::ZERO);
1310	}
1311
1312	/// The anchors the formula was fit to (720p30 = 4 Mbps, 720p60 = 6 Mbps) and the 16:9 ladder it
1313	/// derives, in kbps at 30 fps H.264.
1314	#[test]
1315	fn default_bitrate_follows_the_formula() {
1316		let cap = |width, height, fps, codec| {
1317			let mut config = Config::new(width, height, crate::FrameRate::new(fps, 1).unwrap());
1318			config.codec = codec;
1319			config.resolved_bitrate().as_bps() as f64 / 1e6
1320		};
1321		let h264 = Codec::H264;
1322		for (width, height, mbps) in [
1323			(426, 240, 0.69),
1324			(640, 360, 1.4),
1325			(854, 480, 2.3),
1326			(1280, 720, 4.0),
1327			(1920, 1080, 6.0),
1328			(2560, 1440, 7.3),
1329			(3840, 2160, 8.6),
1330		] {
1331			let got = cap(width, height, 30, h264);
1332			assert!((got - mbps).abs() < 0.1, "{height}p30: {got} Mbps, want {mbps}");
1333		}
1334		assert!((cap(1280, 720, 60, h264) - 6.0).abs() < 0.05);
1335		// Half the frames still cost more than half: 15 fps is 3/4 of 30.
1336		assert!((cap(1280, 720, 15, h264) / cap(1280, 720, 30, h264) - 0.75).abs() < 1e-3);
1337		assert!((cap(1280, 720, 30, Codec::H265) / cap(1280, 720, 30, h264) - 0.7).abs() < 1e-3);
1338		// It levels off below 10 Mbps at 30 fps however large the picture.
1339		assert!(cap(16384, 8640, 30, h264) < 10.0);
1340	}
1341
1342	/// A backend that holds each frame back by one, like the Media Foundation MFT:
1343	/// `encode` readies the *previous* frame's access unit and `flush` the last.
1344	/// The payload is the frame's timestamp in microseconds, so a test can tell
1345	/// which frame a packet came from independently of what it's stamped with.
1346	#[derive(Default)]
1347	struct Delayed {
1348		held: Option<Encoded>,
1349		ready: VecDeque<Encoded>,
1350	}
1351
1352	impl backend::Backend for Delayed {
1353		fn encode(&mut self, frame: &Frame, cut: bool) -> Result<(), Error> {
1354			let payload = bytes::Bytes::from(frame.timestamp.as_micros().unwrap().to_string());
1355			self.ready
1356				.extend(self.held.replace(Encoded::new(frame.timestamp, payload, cut)));
1357			Ok(())
1358		}
1359
1360		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
1361			Ok(self.ready.pop_front())
1362		}
1363
1364		fn flush(&mut self) -> Result<(), Error> {
1365			self.ready.extend(self.held.take());
1366			Ok(())
1367		}
1368
1369		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
1370			Ok(())
1371		}
1372
1373		fn can_cut(&self) -> bool {
1374			true
1375		}
1376
1377		fn name(&self) -> &'static str {
1378			"delayed"
1379		}
1380	}
1381
1382	/// An encoder over a hand-built backend, so a test can pick the buffering
1383	/// behavior rather than take whatever this machine's hardware does.
1384	fn encoder_with(backend: Box<dyn backend::Backend>, config: &Config) -> Encoder {
1385		Encoder {
1386			backend,
1387			codec: config.codec,
1388			size: config.size(),
1389			bitrate: config.resolved_bitrate(),
1390			color: config.resolved_color(),
1391			pending_cut: false,
1392			join: Join::new(config),
1393			resize: config.resolved_resize(),
1394			#[cfg(target_os = "linux")]
1395			input: None,
1396			_thread_bound: PhantomData,
1397		}
1398	}
1399
1400	/// Scales every surface itself, the way NVENC scales CUDA frames into its
1401	/// input, and records the size each frame reached it at.
1402	struct Scaling {
1403		sizes: std::sync::Arc<std::sync::Mutex<Vec<Size>>>,
1404	}
1405
1406	impl backend::Backend for Scaling {
1407		fn encode(&mut self, frame: &Frame, _cut: bool) -> Result<(), Error> {
1408			self.sizes.lock().unwrap().push(frame.size());
1409			Ok(())
1410		}
1411
1412		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
1413			Ok(None)
1414		}
1415
1416		fn flush(&mut self) -> Result<(), Error> {
1417			Ok(())
1418		}
1419
1420		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
1421			Ok(())
1422		}
1423
1424		fn can_cut(&self) -> bool {
1425			true
1426		}
1427
1428		fn scales(&self, _surface: &crate::Surface) -> bool {
1429			true
1430		}
1431
1432		fn name(&self) -> &'static str {
1433			"scaling"
1434		}
1435	}
1436
1437	/// A backend that scales the frame itself is handed it at its own size, but
1438	/// the frame is held to the space it would have after `Frame::resize`: an
1439	/// unlabelled 720p frame is BT.709, which a 480p encoder would label BT.601.
1440	#[test]
1441	fn a_frame_the_backend_scales_keeps_its_implied_color() {
1442		use crate::Color;
1443
1444		let unlabelled = |size: Size| {
1445			let i420 = I420::new(size, vec![0x80; I420::len(size).unwrap()]).unwrap();
1446			Frame::new(moq_net::Timestamp::from_micros(0).unwrap(), Surface::I420(i420))
1447		};
1448		let mut config = Config::new(640, 480, crate::FrameRate::new(30, 1).unwrap());
1449		config.resize = Some(crate::resize::Config::default());
1450		let sizes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1451		let mut encoder = encoder_with(Box::new(Scaling { sizes: sizes.clone() }), &config);
1452
1453		let err = encoder
1454			.encode(&unlabelled(Size::new(1280, 720)))
1455			.expect_err("an implied BT.709 frame is refused");
1456		assert!(
1457			matches!(
1458				err,
1459				Error::ColorMismatch {
1460					frame: Color::BT709,
1461					encoder: Color::BT601
1462				}
1463			),
1464			"{err}"
1465		);
1466
1467		// Within the same space, the backend gets the frame unscaled.
1468		encoder.encode(&unlabelled(Size::new(704, 576))).unwrap();
1469		encoder.encode(&unlabelled(Size::new(640, 480))).unwrap();
1470		assert_eq!(*sizes.lock().unwrap(), [Size::new(704, 576), Size::new(640, 480)]);
1471	}
1472
1473	/// Records the cut flag each frame reached the codec with, so a test can
1474	/// check what the encoder actually asked for. `cuts` is whether it claims to
1475	/// honor one, the way a V4L2 driver without the force-keyframe control does
1476	/// not.
1477	struct Recorder {
1478		log: std::sync::Arc<std::sync::Mutex<Vec<bool>>>,
1479		cuts: bool,
1480	}
1481
1482	impl backend::Backend for Recorder {
1483		fn encode(&mut self, _frame: &Frame, cut: bool) -> Result<(), Error> {
1484			self.log.lock().unwrap().push(cut);
1485			Ok(())
1486		}
1487
1488		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
1489			Ok(None)
1490		}
1491
1492		fn flush(&mut self) -> Result<(), Error> {
1493			Ok(())
1494		}
1495
1496		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
1497			Ok(())
1498		}
1499
1500		fn can_cut(&self) -> bool {
1501			self.cuts
1502		}
1503
1504		fn name(&self) -> &'static str {
1505			"recorder"
1506		}
1507	}
1508
1509	/// Group boundaries are automatic, so an untouched encoder forces none. A cut
1510	/// is held until a frame arrives (callers decide a group boundary before they
1511	/// have the frame that opens it), collapses if made twice, and clears
1512	/// afterwards rather than cutting every frame from then on.
1513	#[test]
1514	fn a_cut_waits_for_the_next_frame_then_clears() {
1515		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1516		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1517		let backend = Recorder {
1518			log: log.clone(),
1519			cuts: true,
1520		};
1521		let mut encoder = encoder_with(Box::new(backend), &config);
1522
1523		// Nothing asked for: `Config::join` places the boundaries on its own.
1524		encoder.encode_all(&gray_frame(320, 240, 0)).unwrap();
1525
1526		// Asked twice before a frame exists: one cut, on the next frame.
1527		encoder.cut().unwrap();
1528		encoder.cut().unwrap();
1529		encoder.encode_all(&gray_frame(320, 240, 1)).unwrap();
1530
1531		// And it does not carry into the frame after.
1532		encoder.encode_all(&gray_frame(320, 240, 2)).unwrap();
1533
1534		assert_eq!(*log.lock().unwrap(), vec![false, true, false]);
1535	}
1536
1537	/// Repeated boundaries each reach the codec: a cut per group is what a
1538	/// transcode rung asks for, and a request that only worked once would leave
1539	/// every later group opening on a delta frame.
1540	#[test]
1541	fn every_cut_reaches_the_codec() {
1542		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1543		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1544		let backend = Recorder {
1545			log: log.clone(),
1546			cuts: true,
1547		};
1548		let mut encoder = encoder_with(Box::new(backend), &config);
1549
1550		for i in 0..6 {
1551			if i % 3 == 0 {
1552				encoder.cut().unwrap();
1553			}
1554			encoder.encode_all(&gray_frame(320, 240, i)).unwrap();
1555		}
1556
1557		assert_eq!(*log.lock().unwrap(), vec![true, false, false, true, false, false]);
1558	}
1559
1560	/// A backend that cannot force a boundary refuses the cut itself, up front,
1561	/// rather than queueing a request its codec would ignore. The V4L2 backend
1562	/// used to disable the request quietly and let groups fall on the driver's
1563	/// own interval, which only the subscriber could tell apart from a cut that
1564	/// worked.
1565	#[test]
1566	fn a_backend_that_cannot_cut_refuses_up_front() {
1567		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1568		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1569		let backend = Recorder {
1570			log: log.clone(),
1571			cuts: false,
1572		};
1573		let mut encoder = encoder_with(Box::new(backend), &config);
1574
1575		let err = encoder.cut().expect_err("the backend cannot cut");
1576		assert!(
1577			matches!(err, Error::CutUnsupported("recorder")),
1578			"unexpected error: {err:?}"
1579		);
1580		assert!(!encoder.pending_cut, "a refused cut must not be queued");
1581
1582		// The refusal names the backend, so a log line says which one to blame.
1583		assert!(err.to_string().contains("recorder"), "{err}");
1584
1585		// Encoding carries on at the backend's own boundaries; the refusal is the
1586		// caller's to act on, not a broken encoder.
1587		encoder.encode_all(&gray_frame(320, 240, 0)).unwrap();
1588		assert_eq!(*log.lock().unwrap(), vec![false]);
1589	}
1590
1591	/// A 320x240 gray frame at `micros`, for a source whose rate varies.
1592	fn gray_at(micros: u64) -> Frame {
1593		let surface = Surface::rgba(&gray_rgba(320, 240), Size::new(320, 240)).unwrap();
1594		Frame::new(moq_net::Timestamp::from_micros(micros).unwrap(), surface)
1595	}
1596
1597	/// A source slower than the configured rate (a camera dropping frames in low
1598	/// light) still opens a group every join, by its timestamps: no group holds a
1599	/// frame a join past its keyframe, so it overshoots by less than one of its
1600	/// frames, and none closes more than half a configured frame early. A backend
1601	/// that cannot cut is never asked to.
1602	#[test]
1603	fn a_slow_source_keys_by_time() {
1604		let config = Config {
1605			join: std::time::Duration::from_secs(1),
1606			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1607		};
1608		// 30 fps, then 20, then 12.5, then 24, the rates a camera drifts through as
1609		// the light changes.
1610		let mut times = Vec::new();
1611		let mut micros = 0u64;
1612		for (interval, count) in [(33_333, 45), (50_000, 50), (80_000, 30), (41_667, 60)] {
1613			for _ in 0..count {
1614				times.push(micros);
1615				micros += interval;
1616			}
1617		}
1618
1619		for cuts in [true, false] {
1620			let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1621			let backend = Recorder { log: log.clone(), cuts };
1622			let mut encoder = encoder_with(Box::new(backend), &config);
1623			for &micros in &times {
1624				encoder.encode_all(&gray_at(micros)).unwrap();
1625			}
1626			let log = log.lock().unwrap();
1627			if !cuts {
1628				assert!(log.iter().all(|cut| !cut), "a backend that cannot cut was asked to");
1629				continue;
1630			}
1631
1632			let mut key = times[0];
1633			for (&micros, &cut) in times.iter().zip(log.iter()).skip(1) {
1634				if cut {
1635					assert!(
1636						micros - key + 16_667 >= 1_000_000,
1637						"the group at {key}us closed at {micros}us"
1638					);
1639					key = micros;
1640				} else {
1641					assert!(
1642						micros - key < 1_000_000,
1643						"the group at {key}us holds a frame at {micros}us"
1644					);
1645				}
1646			}
1647		}
1648	}
1649
1650	/// A source at the configured rate keys on the same frames as the backend's
1651	/// own count, however its timestamps jitter, so measuring by time adds none.
1652	#[test]
1653	fn a_jittery_source_at_the_configured_rate_keys_on_the_count() {
1654		let config = Config {
1655			join: std::time::Duration::from_secs(1),
1656			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1657		};
1658		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1659		let backend = Recorder {
1660			log: log.clone(),
1661			cuts: true,
1662		};
1663		let mut encoder = encoder_with(Box::new(backend), &config);
1664
1665		// Up to a quarter frame either way, so neither end of a group can pull it
1666		// past half a frame.
1667		let jitter = [0, 8_000, -8_000, 5_000, -5_000];
1668		for i in 0..120u64 {
1669			let micros = (i * 33_333)
1670				.checked_add_signed(jitter[i as usize % jitter.len()])
1671				.unwrap();
1672			encoder.encode_all(&gray_at(micros)).unwrap();
1673		}
1674
1675		let log = log.lock().unwrap();
1676		let cuts: Vec<usize> = (0..log.len()).filter(|&i| log[i]).collect();
1677		assert_eq!(cuts, [30, 60, 90]);
1678	}
1679
1680	/// Keys on its own every `interval` frames, restarting the count at a cut the
1681	/// way a real codec's GOP does, and records the cut flag each frame came with.
1682	struct Counting {
1683		log: std::sync::Arc<std::sync::Mutex<Vec<bool>>>,
1684		interval: u32,
1685		count: u32,
1686		ready: VecDeque<Encoded>,
1687	}
1688
1689	impl backend::Backend for Counting {
1690		fn encode(&mut self, frame: &Frame, cut: bool) -> Result<(), Error> {
1691			self.log.lock().unwrap().push(cut);
1692			let keyframe = cut || self.count.is_multiple_of(self.interval);
1693			self.count = if keyframe { 1 } else { self.count + 1 };
1694			self.ready
1695				.push_back(Encoded::new(frame.timestamp, bytes::Bytes::new(), keyframe));
1696			Ok(())
1697		}
1698
1699		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
1700			Ok(self.ready.pop_front())
1701		}
1702
1703		fn flush(&mut self) -> Result<(), Error> {
1704			Ok(())
1705		}
1706
1707		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
1708			Ok(())
1709		}
1710
1711		fn can_cut(&self) -> bool {
1712			true
1713		}
1714
1715		fn name(&self) -> &'static str {
1716			"counting"
1717		}
1718	}
1719
1720	/// A source faster than the configured rate reaches the backend's count before
1721	/// the join, and each keyframe the backend places restarts the clock, so the
1722	/// encoder forces none between them.
1723	#[test]
1724	fn a_fast_source_keys_on_the_backend_count() {
1725		let config = Config {
1726			join: std::time::Duration::from_secs(1),
1727			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1728		};
1729		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1730		let backend = Counting {
1731			log: log.clone(),
1732			interval: config.keyframe_interval(),
1733			count: 0,
1734			ready: VecDeque::new(),
1735		};
1736		let mut encoder = encoder_with(Box::new(backend), &config);
1737
1738		// Three seconds at 60 fps: the backend keys every half second.
1739		for i in 0..180 {
1740			encoder.encode_all(&gray_at(i * 16_667)).unwrap();
1741		}
1742		assert!(log.lock().unwrap().iter().all(|cut| !cut));
1743	}
1744
1745	/// A timestamp behind the last keyframe starts a new timeline: the next
1746	/// keyframe comes a join after the jump, not once the source catches up with
1747	/// where it was.
1748	#[test]
1749	fn a_jump_back_restarts_the_join() {
1750		let config = Config {
1751			join: std::time::Duration::from_secs(1),
1752			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1753		};
1754		let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1755		let backend = Recorder {
1756			log: log.clone(),
1757			cuts: true,
1758		};
1759		let mut encoder = encoder_with(Box::new(backend), &config);
1760
1761		for i in 0..20 {
1762			encoder.encode_all(&gray_at(10_000_000 + i * 33_333)).unwrap();
1763		}
1764		for i in 0..40 {
1765			encoder.encode_all(&gray_at(i * 33_333)).unwrap();
1766		}
1767
1768		let log = log.lock().unwrap();
1769		let cuts: Vec<usize> = (0..log.len()).filter(|&i| log[i]).collect();
1770		assert_eq!(cuts, [50], "a join after the jump at frame 20");
1771	}
1772
1773	/// openh264 keys where the join asks and restarts its own count there, so a
1774	/// 20 fps source on a 30 fps config keys every 20 frames, with no stray IDR
1775	/// on the 30-frame count in between.
1776	#[test]
1777	#[cfg(feature = "openh264")]
1778	fn openh264_keys_a_slow_source_by_time() {
1779		let config = Config {
1780			backend: Backend::Software,
1781			join: std::time::Duration::from_secs(1),
1782			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1783		};
1784		let mut encoder = Encoder::new(&config).unwrap();
1785
1786		let mut keys = Vec::new();
1787		for i in 0..70 {
1788			for encoded in encoder.encode_all(&gray_at(i * 50_000)).unwrap() {
1789				if encoded.keyframe {
1790					keys.push(encoded.timestamp.as_micros().unwrap() / 50_000);
1791				}
1792			}
1793		}
1794		assert_eq!(keys, [0, 20, 40, 60]);
1795	}
1796
1797	/// A join of zero opens no group, so it is refused at open rather than
1798	/// handed to a backend, each of which would do something different with it
1799	/// (openh264 keys every frame, V4L2 rejects the control, VideoToolbox reads
1800	/// it as unlimited).
1801	#[test]
1802	fn a_zero_join_is_refused() {
1803		let config = Config {
1804			join: std::time::Duration::ZERO,
1805			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1806		};
1807		let Err(err) = Encoder::new(&config) else {
1808			panic!("an empty group cannot open");
1809		};
1810		assert!(matches!(err, Error::ZeroJoin), "unexpected error: {err:?}");
1811	}
1812
1813	/// The catalog declares the join after rounding to whole frames, since that
1814	/// is the spacing the stream actually has: a fractional frame rate stretches
1815	/// the default two seconds, and a positive join shorter than a frame rounds
1816	/// up to one frame rather than down to none. Nanoseconds round up too, so
1817	/// the declaration never undercuts the stream.
1818	#[test]
1819	fn the_effective_join_is_whole_frames() {
1820		let join = |ms, framerate| {
1821			let config = Config {
1822				join: std::time::Duration::from_millis(ms),
1823				..Config::new(320, 240, framerate)
1824			};
1825			(config.keyframe_interval(), config.effective_join())
1826		};
1827		let ntsc = crate::FrameRate::new(30_000, 1001).unwrap();
1828		let thirty = crate::FrameRate::new(30, 1).unwrap();
1829		assert_eq!(join(2000, ntsc), (60, std::time::Duration::from_millis(2002)));
1830		assert_eq!(join(2000, thirty), (60, std::time::Duration::from_secs(2)));
1831		assert_eq!(join(1, thirty), (1, std::time::Duration::from_nanos(33_333_334)));
1832	}
1833
1834	/// `cut()` has to reach the codec on a *warm* encoder, which is the case that
1835	/// matters: a fresh one emits an IDR on its first frame regardless, so only a
1836	/// mid-stream request proves the plumbing works. Runs on openh264, so this
1837	/// holds on every platform rather than only where hardware exists.
1838	#[test]
1839	#[cfg(feature = "openh264")]
1840	fn a_mid_stream_cut_emits_an_idr() {
1841		let config = Config {
1842			backend: Backend::Software,
1843			..Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1844		};
1845		// A join far longer than the run, so any IDR here was asked for rather than
1846		// inserted on schedule.
1847		let mut encoder = Encoder::new(&Config {
1848			join: std::time::Duration::from_secs(60),
1849			..config
1850		})
1851		.unwrap();
1852
1853		let mut per_frame = Vec::new();
1854		for i in 0..6 {
1855			// Frame 0 opens the stream; ask again at frame 3, mid-stream.
1856			if i == 3 {
1857				encoder.cut().unwrap();
1858			}
1859			let encoded = encoder.encode_all(&gray_frame(320, 240, i)).unwrap();
1860			let joined: Vec<u8> = encoded.iter().flat_map(|f| f.payload.iter()).copied().collect();
1861			per_frame.push(nal_types(&joined));
1862		}
1863
1864		// The requested frame is a self-contained IDR: SPS (7) and PPS (8) inline
1865		// ahead of an IDR slice (5), which is what avc3 promises a joining subscriber.
1866		let asked = &per_frame[3];
1867		assert!(asked.contains(&5), "the requested frame is not an IDR: {asked:?}");
1868		assert!(asked.contains(&7), "no SPS with the requested IDR: {asked:?}");
1869		assert!(asked.contains(&8), "no PPS with the requested IDR: {asked:?}");
1870
1871		// And the frames around it stay delta frames, so the request keyed exactly
1872		// one: keying every frame would pass the assertions above while destroying
1873		// the bitrate.
1874		for i in [1, 2, 4, 5] {
1875			assert!(
1876				!per_frame[i].contains(&5),
1877				"frame {i} was keyed without being asked: {:?}",
1878				per_frame[i]
1879			);
1880		}
1881	}
1882
1883	/// A backend whose every encode fails, to pin what survives one.
1884	struct Failing;
1885
1886	impl backend::Backend for Failing {
1887		fn encode(&mut self, _frame: &Frame, _cut: bool) -> Result<(), Error> {
1888			Err(Error::codec(anyhow::anyhow!("no")))
1889		}
1890
1891		fn receive(&mut self) -> Result<Option<Encoded>, Error> {
1892			Ok(None)
1893		}
1894
1895		fn flush(&mut self) -> Result<(), Error> {
1896			Ok(())
1897		}
1898
1899		fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
1900			Ok(())
1901		}
1902
1903		fn can_cut(&self) -> bool {
1904			true
1905		}
1906
1907		fn name(&self) -> &'static str {
1908			"failing"
1909		}
1910	}
1911
1912	/// A cut outlives an encode that produced no picture, whether it was rejected
1913	/// up front (wrong size) or failed in the backend. Dropping it would leave the
1914	/// next frame unkeyed, so a subscriber waits out a whole GOP for a starting
1915	/// point the caller already asked for.
1916	#[test]
1917	fn a_failed_encode_keeps_the_cut() {
1918		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1919
1920		let mut encoder = encoder_with(Box::new(Failing), &config);
1921		encoder.cut().unwrap();
1922		assert!(encoder.encode_all(&gray_frame(320, 240, 0)).is_err());
1923		assert!(encoder.pending_cut, "the backend error swallowed the request");
1924
1925		// Rejected before the backend ever sees it, for the same reason.
1926		let mut encoder = encoder_with(Box::new(Delayed::default()), &config);
1927		encoder.cut().unwrap();
1928		assert!(encoder.encode_all(&gray_frame(640, 480, 0)).is_err());
1929		assert!(encoder.pending_cut, "the size check swallowed the request");
1930
1931		// ...and the next frame that does go through claims it.
1932		encoder.encode_all(&gray_frame(320, 240, 1)).unwrap();
1933		assert!(!encoder.pending_cut);
1934	}
1935
1936	/// Regression: a backend that buffers hands back an earlier frame's access
1937	/// unit, so the timestamp has to ride through the encoder with the picture.
1938	/// Stamping output with whatever frame is going in at the time (or the tail
1939	/// with one arbitrary time) shifts every packet by the encoder delay and
1940	/// collapses the drained tail onto a single instant.
1941	#[test]
1942	fn a_buffering_backend_keeps_each_frames_timestamp() {
1943		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1944		let mut encoder = encoder_with(Box::new(Delayed::default()), &config);
1945
1946		// The packet handed back while frame `i` goes in belongs to frame `i - 1`, so
1947		// it has to be stamped one frame back. Stamping at the call site (the only
1948		// option when encode just returned bytes) would shift the whole stream.
1949		for i in 0..5 {
1950			let encoded = encoder.encode_all(&gray_frame(320, 240, i)).unwrap();
1951			if i == 0 {
1952				assert!(encoded.is_empty(), "the first frame is still buffered");
1953				continue;
1954			}
1955			assert_eq!(encoded.len(), 1);
1956			assert_eq!(encoded[0].timestamp, at(i - 1));
1957			// And the packet really is the earlier frame's, not a mis-stamped copy of
1958			// the one going in.
1959			assert_eq!(
1960				&encoded[0].payload[..],
1961				at(i - 1).as_micros().unwrap().to_string().as_bytes()
1962			);
1963		}
1964
1965		// The tail: frame 4 never came back from an encode call, so `flush` drains
1966		// it, still carrying its own time rather than one the caller picks.
1967		let tail = encoder.flush_all().unwrap();
1968		assert_eq!(tail.len(), 1);
1969		assert_eq!(tail[0].timestamp, at(4));
1970		assert!(
1971			encoder_with(Box::new(Delayed::default()), &config)
1972				.flush_all()
1973				.unwrap()
1974				.is_empty()
1975		);
1976	}
1977
1978	/// A group has to contain its own frames. A codec that pipelines is still
1979	/// holding the last of them when the group ends, so the boundary flushes it;
1980	/// without that they surface in the *next* group, ahead of its keyframe, where
1981	/// a subscriber joining there cannot decode them.
1982	///
1983	/// The encoder stays usable afterwards: a live track flushes at every group
1984	/// and keeps going.
1985	#[test]
1986	fn a_flush_empties_a_pipelined_backend_and_leaves_it_running() {
1987		let config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
1988		let mut encoder = encoder_with(Box::new(Delayed::default()), &config);
1989
1990		let mut group = Vec::new();
1991		for i in 0..3 {
1992			group.extend(encoder.encode_all(&gray_frame(320, 240, i)).unwrap());
1993		}
1994		group.extend(encoder.flush_all().unwrap());
1995
1996		// All three frames land in the group they belong to, in order.
1997		let times: Vec<_> = group.iter().map(|packet| packet.timestamp).collect();
1998		assert_eq!(times, vec![at(0), at(1), at(2)], "the group lost or reordered frames");
1999
2000		// The next group starts clean: nothing carried over, and the encoder still
2001		// takes frames.
2002		let mut next = encoder.encode_all(&gray_frame(320, 240, 3)).unwrap();
2003		assert!(next.is_empty(), "frame 3 is buffered, so nothing comes back yet");
2004		next.extend(encoder.flush_all().unwrap());
2005		let times: Vec<_> = next.iter().map(|packet| packet.timestamp).collect();
2006		assert_eq!(times, vec![at(3)], "the flush left something behind");
2007	}
2008
2009	/// The hardware encoder states the color space too, and states the one the
2010	/// pixels were actually converted into. VideoToolbox takes the three
2011	/// properties as a request, so read the SPS back rather than trusting that it
2012	/// honored them.
2013	#[cfg(apple)]
2014	#[test]
2015	fn videotoolbox_sps_declares_the_color_space() {
2016		use super::backend::test_util::{BT601_DESCRIBED, BT709_DESCRIBED, declared_color};
2017
2018		for (size, described) in [
2019			(Size::new(640, 480), BT601_DESCRIBED),
2020			(Size::new(1920, 1080), BT709_DESCRIBED),
2021		] {
2022			let config = Config {
2023				backend: Backend::Named("videotoolbox".into()),
2024				..Config::new(size.width, size.height, crate::FrameRate::new(30, 1).unwrap())
2025			};
2026			let mut encoder = Encoder::new(&config).expect("videotoolbox is available on macOS");
2027
2028			let rgba = [255u8, 0, 0, 255].repeat(size.pixels() as usize);
2029			let surface = crate::frame::Surface::rgba(&rgba, size).unwrap();
2030			encoder.cut().unwrap();
2031			let frames = encoder
2032				.encode_all(&Frame::new(moq_net::Timestamp::from_micros(0).unwrap(), surface))
2033				.unwrap();
2034
2035			let keyframe = frames.first().expect("a keyframe");
2036			assert_eq!(declared_color(&keyframe.payload), Some(described), "{size} SPS");
2037		}
2038	}
2039
2040	/// Resizing across the standard-definition boundary keeps the pixels' color
2041	/// space but moves the encoder into another one, which would emit BT.709
2042	/// pixels under a BT.601 label. The encoder refuses that frame, and
2043	/// `Config::color` pins the real space so the bitstream says so.
2044	#[test]
2045	#[cfg(feature = "openh264")]
2046	fn config_color_pins_the_space_a_resize_carried() {
2047		use super::backend::test_util::{BT709_DESCRIBED, declared_color};
2048		use crate::Color;
2049
2050		let big = Size::new(1280, 720);
2051		let small = Size::new(640, 480);
2052
2053		// Converted at 720p, so the samples are BT.709.
2054		let rgba = vec![0x80u8; big.pixels() as usize * 4];
2055		let frame = Frame::new(
2056			moq_net::Timestamp::from_micros(0).unwrap(),
2057			crate::frame::Surface::rgba(&rgba, big).unwrap(),
2058		);
2059		let scaled = frame.resize(small, &crate::resize::Config::default()).unwrap();
2060		assert_eq!(scaled.surface.color(), Some(Color::BT709), "resize keeps the space");
2061
2062		// Left to infer, a 480p encoder would write BT.601 over those BT.709
2063		// samples, so it refuses them instead.
2064		let config = Config {
2065			backend: Backend::Software,
2066			..Config::new(small.width, small.height, crate::FrameRate::new(30, 1).unwrap())
2067		};
2068		let mut encoder = Encoder::new(&config).unwrap();
2069		encoder.cut().unwrap();
2070		let err = encoder.encode_all(&scaled).expect_err("a mismatched frame is refused");
2071		assert!(
2072			matches!(
2073				err,
2074				Error::ColorMismatch {
2075					frame: Color::BT709,
2076					encoder: Color::BT601
2077				}
2078			),
2079			"{err}"
2080		);
2081
2082		// Declaring the real space fixes the label.
2083		let config = Config {
2084			backend: Backend::Software,
2085			color: Some(Color::BT709),
2086			..Config::new(small.width, small.height, crate::FrameRate::new(30, 1).unwrap())
2087		};
2088		let mut encoder = Encoder::new(&config).unwrap();
2089		encoder.cut().unwrap();
2090		let frames = encoder.encode_all(&scaled).expect("a declared space encodes");
2091
2092		let keyframe = frames.first().expect("a keyframe");
2093		assert_eq!(declared_color(&keyframe.payload), Some(BT709_DESCRIBED));
2094	}
2095
2096	/// A transcode takes the space from the source's SPS, not from either size.
2097	/// The decoder (openh264, which reports none) labels its pictures with the
2098	/// signalled space, even where the source's size would guess another: they
2099	/// convert back to the red they started as. A rung whose size guesses a
2100	/// different space re-signals the source's, or refuses to mislabel it,
2101	/// BT.2020 PQ and HLG included.
2102	#[test]
2103	#[cfg(feature = "openh264")]
2104	fn transcode_keeps_the_space_the_source_signalled() {
2105		use super::backend::test_util::{Described, declared_color};
2106		use crate::Color;
2107		use crate::color::{Matrix, Primaries, Range, Transfer};
2108
2109		let hdr = |transfer| Color {
2110			matrix: Matrix::Bt2020,
2111			range: Range::Limited,
2112			primaries: Primaries::Bt2020,
2113			transfer,
2114		};
2115		let rate = crate::FrameRate::new(30, 1).unwrap();
2116		let red = [255u8, 0, 0];
2117		// Only the height picks the guess, so the frames are narrow to keep the codec and the
2118		// scaler cheap.
2119		for (source, rung, color) in [
2120			// The source's own guess, scaled across 576 lines.
2121			(Size::new(160, 720), Size::new(80, 480), Color::BT709),
2122			// Spaces neither size would guess.
2123			(Size::new(160, 720), Size::new(240, 1080), Color::BT601),
2124			(
2125				Size::new(80, 480),
2126				Size::new(160, 720),
2127				Color::BT709.with_range(Range::Full),
2128			),
2129			// HDR survives the round trip with its primaries and curve.
2130			(Size::new(160, 720), Size::new(80, 480), hdr(Transfer::Pq)),
2131			(
2132				Size::new(80, 480),
2133				Size::new(160, 720),
2134				hdr(Transfer::Hlg).with_range(Range::Full),
2135			),
2136		] {
2137			let codes = color.code_points();
2138			let described = || Described {
2139				primaries: codes.primaries,
2140				transfer: codes.transfer,
2141				matrix: codes.matrix,
2142				full_range: color.range == Range::Full,
2143			};
2144
2145			// Solid red, converted in `color` rather than in the size guess.
2146			let [y, u, v] = color.coefficients().apply(red);
2147			let luma = source.pixels() as usize;
2148			let mut data = vec![y; luma];
2149			data.extend(std::iter::repeat_n(u, luma / 4));
2150			data.extend(std::iter::repeat_n(v, luma / 4));
2151			let frame = Frame::new(at(0), Surface::I420(I420::new(source, data).unwrap().with_color(color)));
2152
2153			let config = Config {
2154				backend: Backend::Software,
2155				color: Some(color),
2156				..Config::new(source.width, source.height, rate)
2157			};
2158			let mut encoder = Encoder::new(&config).unwrap();
2159			encoder.cut().unwrap();
2160			let mut encoded = encoder.encode_all(&frame).unwrap();
2161			encoded.extend(encoder.flush_all().unwrap());
2162			assert_eq!(
2163				declared_color(&encoded[0].payload),
2164				Some(described()),
2165				"{source} source SPS"
2166			);
2167
2168			let catalog = hang::catalog::VideoConfig::new(hang::catalog::H264 {
2169				inline: true,
2170				profile: 0x42,
2171				constraints: 0xc0,
2172				level: 0x1f,
2173			});
2174			let mut decode = crate::decode::Config::new();
2175			decode.backend = crate::decode::Backend::Software;
2176			let mut decoder = crate::decode::Decoder::new(&catalog, &decode).unwrap();
2177			let mut decoded = Vec::new();
2178			for unit in &encoded {
2179				decoded.extend(
2180					decoder
2181						.decode_all(&unit.payload, unit.timestamp, unit.keyframe)
2182						.unwrap(),
2183				);
2184			}
2185			decoded.extend(decoder.flush_all().unwrap());
2186			let picture = decoded.first().expect("a decoded picture");
2187			assert_eq!(picture.surface.color(), Some(color), "{source} decoded label");
2188
2189			// The label is the one the samples were made in, so they read back as red.
2190			let rgba = picture.surface.to_rgba(&crate::convert::Config::default()).unwrap();
2191			let center = (rgba.stride() * source.height as usize / 2) + source.width as usize / 2 * 4;
2192			for (channel, expected) in red.iter().enumerate() {
2193				let actual = rgba.data()[center + channel];
2194				assert!(
2195					actual.abs_diff(*expected) <= 8,
2196					"{source} {color:?} channel {channel}: {actual}, expected {expected}"
2197				);
2198			}
2199
2200			let scaled = picture.resize(rung, &crate::resize::Config::default()).unwrap();
2201			assert_eq!(scaled.surface.color(), Some(color), "{rung} rung label");
2202
2203			// Left to the rung's size guess, the encoder refuses rather than mislabel.
2204			let mut guessed = Encoder::new(&Config {
2205				backend: Backend::Software,
2206				..Config::new(rung.width, rung.height, rate)
2207			})
2208			.unwrap();
2209			assert!(matches!(
2210				guessed.encode_all(&scaled),
2211				Err(Error::ColorMismatch { frame, .. }) if frame == color
2212			));
2213
2214			// Opened from the frame's label, the rung signals the source's space.
2215			let mut encoder = Encoder::new(&Config {
2216				backend: Backend::Software,
2217				color: scaled.surface.color(),
2218				..Config::new(rung.width, rung.height, rate)
2219			})
2220			.unwrap();
2221			encoder.cut().unwrap();
2222			let encoded = encoder.encode_all(&scaled).unwrap();
2223			assert_eq!(
2224				declared_color(&encoded[0].payload),
2225				Some(described()),
2226				"{rung} rung SPS"
2227			);
2228		}
2229	}
2230
2231	#[cfg(all(target_os = "windows", feature = "capture", feature = "openh264"))]
2232	#[test]
2233	#[ignore = "requires Windows WGC video processing and a Media Foundation hardware H.264 encoder"]
2234	fn wgc_nv12_encodes_with_matching_color_on_gpu_and_software() {
2235		use super::backend::test_util::{BT601_DESCRIBED, BT709_DESCRIBED, declared_color};
2236		use crate::frame::d3d11;
2237
2238		let device = d3d11::create_device(None).expect("D3D11 hardware device");
2239		for (size, declared) in [
2240			(Size::new(640, 480), BT601_DESCRIBED),
2241			(Size::new(1280, 720), BT709_DESCRIBED),
2242		] {
2243			let pixels = [0, 0, 255, 255].repeat(size.pixels() as usize);
2244			let source = d3d11::upload_bgra(&device, size, &pixels);
2245			for backend in ["mediafoundation", "openh264"] {
2246				let texture = d3d11::Texture::capture(&device, &source, size).expect("BGRA to NV12");
2247				let frame = Frame::new(moq_net::Timestamp::from_micros(0).unwrap(), Surface::Texture(texture));
2248				let config = Config {
2249					backend: Backend::Named(backend.into()),
2250					color: frame.surface.color(),
2251					..Config::new(size.width, size.height, crate::FrameRate::new(30, 1).unwrap())
2252				};
2253				let mut encoder = Encoder::new(&config).expect("requested encoder must be available");
2254				assert_eq!(encoder.name(), backend);
2255				let mut encoded = encoder.encode_all(&frame).expect("encode WGC texture");
2256				encoded.extend(encoder.flush_all().unwrap());
2257				assert!(!encoded.is_empty(), "{backend} must produce a frame");
2258				assert!(
2259					encoded
2260						.iter()
2261						.any(|frame| declared_color(&frame.payload).as_ref() == Some(&declared)),
2262					"{backend} {size} SPS color"
2263				);
2264			}
2265		}
2266	}
2267}
2268
2269#[cfg(all(test, target_os = "linux"))]
2270mod external_tests {
2271	use super::*;
2272	use crate::frame::vulkan::{Device, Format, Handles, Image, Memory, Slot, Timeline};
2273	use std::os::unix::net::UnixStream;
2274
2275	fn device() -> Device {
2276		Device {
2277			device_uuid: [0xaa; 16],
2278			driver_uuid: [0xbb; 16],
2279			render_node: None,
2280		}
2281	}
2282
2283	#[tokio::test]
2284	async fn unknown_external_device_is_refused_at_open_and_probe() {
2285		let mut config = Config::new(320, 240, FrameRate::new(30, 1).unwrap());
2286		config.input = Some(device());
2287		let error = match Encoder::new(&config) {
2288			Ok(_) => panic!("opened an unrelated device"),
2289			Err(error) => error,
2290		};
2291		assert!(error.to_string().contains(&device().to_string()), "{error}");
2292		let error = config.probe().await.unwrap_err();
2293		assert!(error.to_string().contains(&device().to_string()), "{error}");
2294		config.backend = Backend::Software;
2295		assert!(matches!(Encoder::new(&config), Err(Error::NoEncoder(_))));
2296	}
2297
2298	#[test]
2299	fn refuses_external_frame_on_an_encoder_without_that_device() {
2300		let config = {
2301			let mut config = Config::new(320, 240, FrameRate::new(30, 1).unwrap());
2302			config.backend = Backend::Named("probe".into());
2303			config
2304		};
2305		let mut encoder = Encoder::new(&config).unwrap();
2306		let (memory, timeline) = UnixStream::pair().unwrap();
2307		let slot = Slot::new(
2308			Handles {
2309				memory: memory.into(),
2310				timeline: timeline.into(),
2311			},
2312			Image {
2313				device: device(),
2314				memory: Memory::OpaqueFd { memory_type: 0 },
2315				size: config.size(),
2316				allocation_size: 4096,
2317				format: Format::Rgba8,
2318			},
2319			(),
2320		)
2321		.unwrap();
2322		let (image, _) = slot.publish(Timeline::new(1, 2).unwrap()).unwrap();
2323		let frame = Frame::new(
2324			moq_net::Timestamp::from_micros(0).unwrap(),
2325			crate::Surface::Vulkan(image),
2326		);
2327		let error = encoder.encode_all(&frame).unwrap_err();
2328		assert!(error.to_string().contains(&device().to_string()), "{error}");
2329		assert!(frame.surface.to_i420().is_err());
2330	}
2331}