moqros 0.7.0

Stream ROS 2 topics (images as video, any message as data) over Media over QUIC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Video encoding/decoding.
//!
//! - **VP8** (feature `vp8`, default): royalty-free, via the system libvpx.
//! - **AV1** (feature `av1`): royalty-free, via the system libaom.
//! - **H.264** (feature `h264`): via Cisco's prebuilt OpenH264 binary, loaded at
//!   runtime so Cisco's patent license applies. See [`set_openh264_library`].
//!
//! With the `hw` feature, encoders run on the GPU through GStreamer when one is available
//! (see [`Hardware`]); decoding always runs in software.

use std::time::Duration;

use bytes::Bytes;
use hang::catalog::VideoCodec;

use crate::clock::StreamClock;
use crate::convert::{I420, Planes, yuv_to_packed};
use crate::{Error, Image, PixelFormat, Result};

mod annexb;
#[cfg(feature = "av1")]
mod av1;
#[cfg(feature = "hw")]
mod gst;
#[cfg(feature = "h264")]
mod h264;
mod obu;
#[cfg(feature = "vp8")]
mod vp8;
mod vp8_header;

#[cfg(feature = "h264")]
pub use h264::set_openh264_library;

/// Video codecs moqros can produce and consume.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Codec {
	/// VP8 (feature `vp8`, on by default).
	Vp8,
	/// H.264 (feature `h264`).
	H264,
	/// AV1 (feature `av1`).
	Av1,
}

impl Codec {
	/// Every codec moqros knows, compiled in or not.
	#[cfg(test)]
	pub(crate) const ALL: &[Codec] = &[Codec::Vp8, Codec::H264, Codec::Av1];

	/// Codecs compiled into this build, preferred first.
	pub const fn available() -> &'static [Codec] {
		&[
			#[cfg(feature = "vp8")]
			Codec::Vp8,
			#[cfg(feature = "av1")]
			Codec::Av1,
			#[cfg(feature = "h264")]
			Codec::H264,
		]
	}

	/// Whether this build can encode and decode the codec.
	pub fn is_available(self) -> bool {
		Self::available().contains(&self)
	}

	/// Map a catalog codec onto a moqros codec.
	pub fn from_catalog(codec: &VideoCodec) -> Option<Self> {
		match codec {
			VideoCodec::VP8 => Some(Self::Vp8),
			VideoCodec::H264(_) => Some(Self::H264),
			VideoCodec::AV1(_) => Some(Self::Av1),
			_ => None,
		}
	}

	/// Whether `data` (one encoded frame) is a keyframe.
	pub fn is_keyframe(self, data: &[u8]) -> bool {
		match self {
			Self::Vp8 => vp8_header::is_keyframe(data),
			Self::H264 => annexb::is_keyframe(data),
			Self::Av1 => obu::is_keyframe(data),
		}
	}

	/// Catalog codec description for an encoded keyframe (for H.264 read from its SPS, for
	/// AV1 from its sequence header).
	pub(crate) fn catalog_codec(self, keyframe: &[u8]) -> VideoCodec {
		match self {
			Self::Vp8 => VideoCodec::VP8,
			Self::H264 => annexb::catalog_codec(keyframe),
			Self::Av1 => obu::catalog_codec(keyframe),
		}
	}
}

crate::names::named_enum!(Codec, "codec", {
	Vp8 => "vp8",
	H264 => "h264" | "avc",
	Av1 => "av1" | "av01",
});

impl Default for Codec {
	fn default() -> Self {
		Self::available().first().copied().unwrap_or(Self::Vp8)
	}
}

/// Whether [`Encoder`] encodes on a hardware encoder (feature `hw`).
///
/// Hardware encoders are reached through GStreamer: VA-API (`va` and `vaapi` plugins) on
/// Intel/AMD GPUs and NVENC (`nvcodec` plugin) on NVIDIA GPUs. Software encoding stays the
/// fallback, so the codec's own feature is still needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Hardware {
	/// Always encode in software.
	Off,
	/// Use a hardware encoder when one works, otherwise encode in software.
	#[default]
	Auto,
	/// Fail unless a hardware encoder works.
	Require,
}

crate::names::named_enum!(Hardware, "hardware mode", {
	Off => "off",
	Auto => "auto",
	Require => "require",
});

/// Tuning knobs for [`Encoder`].
#[derive(Debug, Clone)]
pub struct EncoderSettings {
	/// Codec to encode with.
	pub codec: Codec,
	/// Target bitrate in bits per second.
	pub bitrate: u32,
	/// Upper bound on the input frame rate, used by rate control.
	pub max_fps: f32,
	/// Maximum time between keyframes. Each keyframe starts a new MoQ group,
	/// so this bounds how long a late joiner waits for the first picture. A group
	/// nearing moq-net's limits (8192 frames or 32 MB) gets an earlier keyframe.
	pub keyframe_interval: Duration,
	/// Encoder worker threads; 0 picks a sensible default.
	pub threads: u16,
	/// Whether to encode on a hardware encoder.
	pub hardware: Hardware,
}

impl Default for EncoderSettings {
	fn default() -> Self {
		Self {
			codec: Codec::default(),
			bitrate: 2_000_000,
			max_fps: 30.0,
			keyframe_interval: Duration::from_secs(2),
			threads: 0,
			hardware: Hardware::default(),
		}
	}
}

impl EncoderSettings {
	pub(crate) fn threads(&self) -> u32 {
		match self.threads {
			0 => default_threads(),
			n => u32::from(n),
		}
	}

	/// Encoder-internal GOP length, kept longer than our time-based interval so the
	/// forced keyframe is what normally starts a group.
	#[expect(
		clippy::cast_possible_truncation,
		clippy::cast_sign_loss,
		reason = "float casts saturate"
	)]
	pub(crate) fn gop_frames(&self) -> u32 {
		(self.max_fps * self.keyframe_interval.as_secs_f32() * 2.0)
			.ceil()
			.max(1.0) as u32
	}

	/// Duration of one frame at `max_fps`, in microseconds.
	#[expect(
		clippy::cast_possible_truncation,
		clippy::cast_sign_loss,
		reason = "float casts saturate"
	)]
	pub(crate) fn frame_duration_micros(&self) -> u64 {
		(1_000_000.0 / self.max_fps.max(1.0)) as u64
	}
}

/// Codec worker threads when none are configured: one per core, at most 4.
pub(crate) fn default_threads() -> u32 {
	std::thread::available_parallelism().map_or(1, |n| u32::try_from(n.get()).unwrap_or(4).min(4))
}

/// One encoded frame.
#[derive(Debug, Clone)]
pub struct EncodedFrame {
	/// VP8 frame, Annex-B H.264 access unit, or AV1 temporal unit (low-overhead OBUs).
	pub data: Bytes,
	/// Whether the frame decodes on its own.
	pub keyframe: bool,
	/// Picture width in pixels.
	pub width: u32,
	/// Picture height in pixels.
	pub height: u32,
	/// Timestamp of the encoded [`Image`].
	pub timestamp: Duration,
	/// Catalog codec description (for H.264 parsed from the keyframe's SPS, for AV1 from its
	/// sequence header).
	pub codec: VideoCodec,
}

/// What an [`EncoderBackend`] produced for one input frame.
pub(crate) struct EncodedChunk {
	pub data: Bytes,
	pub keyframe: bool,
}

/// A codec implementation behind [`Encoder`].
pub(crate) trait EncoderBackend: Send {
	/// Encode one frame at `pts` microseconds. Returns `None` if the encoder dropped it.
	fn encode(&mut self, frame: &I420, pts: u64, force_keyframe: bool) -> Result<Option<EncodedChunk>>;

	/// Aim for `bitrate` bit/s from the next frame on. Returns `false` if the backend can't change
	/// it while running, so it has to be recreated.
	fn set_bitrate(&mut self, bitrate: u32) -> Result<bool> {
		let _ = bitrate;
		Ok(false)
	}
}

/// A codec implementation behind [`Decoder`].
pub(crate) trait DecoderBackend: Send {
	/// Decode one frame into packed `format` `(width, height, pixels)` (see [`packed_picture`]),
	/// failing with [`Error::TooLarge`] for pictures above `max_pixels`.
	fn decode(&mut self, data: &[u8], max_pixels: u64, format: PixelFormat) -> Result<Option<(u32, u32, Vec<u8>)>>;
}

/// A decoder's output picture as packed `format` `(width, height, pixels)`, failing with
/// [`Error::TooLarge`] before converting a picture above `max_pixels`.
pub(crate) fn packed_picture(planes: &Planes<'_>, max_pixels: u64, format: PixelFormat) -> Result<(u32, u32, Vec<u8>)> {
	// A picture too large for `u32` saturates, and then fails the size check.
	let dim = |n: usize| u32::try_from(n).unwrap_or(u32::MAX);
	let (width, height) = (dim(planes.width), dim(planes.height));
	check_size(width, height, max_pixels)?;
	Ok((width, height, yuv_to_packed(planes, format)?))
}

/// Default for [`Decoder::set_max_pixels`]: 8K UHD (7680x4320).
pub const DEFAULT_MAX_PIXELS: u64 = 7680 * 4320;

/// Fail with [`Error::TooLarge`] if a `width`x`height` picture is above `max` pixels.
pub(crate) fn check_size(width: u32, height: u32, max: u64) -> Result<()> {
	if u64::from(width) * u64::from(height) > max {
		return Err(Error::TooLarge { width, height, max });
	}
	Ok(())
}

/// Stateful encoder that accepts [`Image`]s of any supported pixel format.
///
/// The codec is (re)created lazily whenever the input resolution changes.
pub struct Encoder {
	settings: EncoderSettings,
	active: Option<ActiveBackend>,
	/// Hardware encoder in use, if any. Outlives a backend that's recreated, so the same
	/// element is tried first for the new one.
	hardware: Option<&'static str>,
	/// Stream time (pts) of the last keyframe.
	last_keyframe: Option<u64>,
	clock: StreamClock,
	/// The converted input, reused from frame to frame.
	yuv: I420,
}

/// The backend an [`Encoder`] currently encodes with, and what it has produced so far.
struct ActiveBackend {
	backend: Box<dyn EncoderBackend>,
	dims: (usize, usize),
	/// Catalog codec of the last keyframe, reused for the delta frames that follow it.
	codec: Option<VideoCodec>,
}

impl ActiveBackend {
	fn new(backend: Box<dyn EncoderBackend>, dims: (usize, usize)) -> Self {
		Self {
			backend,
			dims,
			codec: None,
		}
	}
}

impl Encoder {
	/// Fails if `settings.codec` isn't compiled into this build, or if `settings.hardware` is
	/// [`Hardware::Require`] without the `hw` feature.
	pub fn new(settings: EncoderSettings) -> Result<Self> {
		if !settings.codec.is_available() {
			return Err(unavailable(settings.codec));
		}
		if settings.hardware == Hardware::Require && !cfg!(feature = "hw") {
			return Err(Error::CodecUnavailable(
				"hardware encoding is not compiled in (enable the `hw` feature)".into(),
			));
		}
		Ok(Self {
			settings,
			active: None,
			hardware: None,
			last_keyframe: None,
			clock: StreamClock::default(),
			yuv: I420::default(),
		})
	}

	/// The settings this encoder was created with.
	pub fn settings(&self) -> &EncoderSettings {
		&self.settings
	}

	/// Name of the GStreamer element encoding on hardware, once the first frame picked one.
	/// `None` while encoding in software.
	pub fn hardware_encoder(&self) -> Option<&'static str> {
		self.hardware
	}

	/// Aim for `bitrate` bit/s from the next frame on.
	///
	/// VP8 and AV1 software encoders adjust in place. Other encoders (H.264, hardware) are
	/// recreated, so the next frame is a keyframe.
	pub fn set_bitrate(&mut self, bitrate: u32) {
		if bitrate == self.settings.bitrate {
			return;
		}
		self.settings.bitrate = bitrate;
		let Some(active) = self.active.as_mut() else {
			return;
		};
		match active.backend.set_bitrate(bitrate) {
			Ok(true) => tracing::debug!(codec = %self.settings.codec, bitrate, "changed the bitrate"),
			Ok(false) => {
				tracing::debug!(codec = %self.settings.codec, bitrate, "recreating the encoder for the new bitrate");
				self.active = None;
			}
			Err(err) => {
				tracing::warn!(codec = %self.settings.codec, bitrate, %err, "changing the bitrate failed; recreating the encoder");
				self.active = None;
			}
		}
	}

	/// Request that the next frame is encoded as a keyframe.
	pub fn force_keyframe(&mut self) {
		self.last_keyframe = None;
	}

	/// Encode one image. Returns `None` when the encoder dropped the frame.
	pub fn encode(&mut self, image: &Image) -> Result<Option<EncodedFrame>> {
		self.yuv.fill_from_image(image)?;
		// Taken out for the call, which borrows the encoder.
		let yuv = std::mem::take(&mut self.yuv);
		let frame = self.encode_yuv(&yuv, image.timestamp);
		self.yuv = yuv;
		frame
	}

	/// Encode one converted picture captured at `timestamp`.
	#[expect(
		clippy::cast_possible_truncation,
		reason = "I420 dimensions come from `u32` image dimensions"
	)]
	pub(crate) fn encode_yuv(&mut self, yuv: &I420, timestamp: Duration) -> Result<Option<EncodedFrame>> {
		let dims = (yuv.width(), yuv.height());

		if self.active.as_ref().is_none_or(|active| active.dims != dims) {
			tracing::debug!(codec = %self.settings.codec, width = dims.0, height = dims.1, "creating encoder");
			// Drop the old encoder first: a hardware encoder may only allow one session.
			self.active = None;
			self.active = Some(ActiveBackend::new(self.create_backend(dims)?, dims));
			self.last_keyframe = None;
		}

		// Codecs want strictly increasing presentation times. Keyframes are scheduled on
		// the same timeline, so capture clock jumps can't stall or flood them.
		let pts = self.clock.micros(timestamp);
		let interval = u64::try_from(self.settings.keyframe_interval.as_micros()).unwrap_or(u64::MAX);
		let force = self
			.last_keyframe
			.is_none_or(|last| pts.saturating_sub(last) >= interval);

		let Some(EncodedChunk { data, keyframe }) = self.encode_with_fallback(yuv, pts, force)? else {
			return Ok(None);
		};
		if keyframe {
			self.last_keyframe = Some(pts);
		}
		let active = self.active.as_mut().expect("backend created above");
		let codec = match &active.codec {
			Some(codec) if !keyframe => codec.clone(),
			_ => active.codec.insert(self.settings.codec.catalog_codec(&data)).clone(),
		};

		Ok(Some(EncodedFrame {
			data,
			keyframe,
			width: dims.0 as u32,
			height: dims.1 as u32,
			timestamp,
			codec,
		}))
	}

	/// Encode on the active backend.
	///
	/// A hardware encoder that fails mid-stream (e.g. a GPU reset) is replaced by a software
	/// one in auto mode, and the frame is encoded again as a keyframe.
	fn encode_with_fallback(&mut self, yuv: &I420, pts: u64, force: bool) -> Result<Option<EncodedChunk>> {
		let active = self.active.as_mut().expect("backend created before encoding");
		let dims = active.dims;
		match active.backend.encode(yuv, pts, force) {
			Ok(chunk) => Ok(chunk),
			Err(err) if self.hardware.is_some() && self.settings.hardware == Hardware::Auto => {
				tracing::warn!(codec = %self.settings.codec, element = self.hardware, %err, "hardware encoder failed; encoding in software");
				self.hardware = None;
				self.active = None;
				let backend = create_software_encoder(&self.settings, dims)?;
				let active = self.active.insert(ActiveBackend::new(backend, dims));
				active.backend.encode(yuv, pts, true)
			}
			Err(err) => {
				// Recreate the encoder on the next frame rather than reuse a broken one.
				if self.hardware.is_some() {
					self.active = None;
				}
				Err(err)
			}
		}
	}

	/// A hardware encoder if one works (and is wanted), otherwise a software one.
	///
	/// Hardware encoders may only reject some sizes, so they're tried again for a new
	/// resolution; ones that failed at a size aren't (see [`gst::GstEncoder::new`]).
	fn create_backend(&mut self, dims: (usize, usize)) -> Result<Box<dyn EncoderBackend>> {
		#[cfg(feature = "hw")]
		if self.settings.hardware != Hardware::Off {
			let first_attempt = gst::first_attempt(self.settings.codec, dims);
			match gst::GstEncoder::new(&self.settings, dims, self.hardware) {
				Ok(encoder) => {
					if self.hardware != Some(encoder.element()) {
						tracing::info!(codec = %self.settings.codec, element = encoder.element(), "using hardware encoder");
					}
					self.hardware = Some(encoder.element());
					return Ok(Box::new(encoder));
				}
				Err(err) if self.settings.hardware == Hardware::Require => return Err(err),
				Err(err) => {
					// Warn once per codec and size, not for every topic.
					if first_attempt {
						tracing::warn!(codec = %self.settings.codec, %err, "no usable hardware encoder; encoding in software");
					} else {
						tracing::debug!(codec = %self.settings.codec, %err, "no usable hardware encoder; encoding in software");
					}
					self.hardware = None;
				}
			}
		}
		create_software_encoder(&self.settings, dims)
	}
}

/// Decoder producing `rgb8` [`Image`]s.
///
/// A bitstream can declare a huge picture in a few bytes, so pictures above
/// [`Decoder::max_pixels`] are rejected rather than allocated.
pub struct Decoder {
	codec: Codec,
	inner: Box<dyn DecoderBackend>,
	max_pixels: u64,
	output: PixelFormat,
}

impl Decoder {
	/// A decoder for `codec`. Fails if the codec isn't compiled in or can't be loaded.
	pub fn new(codec: Codec) -> Result<Self> {
		let inner: Box<dyn DecoderBackend> = match codec {
			#[cfg(feature = "vp8")]
			Codec::Vp8 => Box::new(vp8::Vp8Decoder::new()?),
			#[cfg(feature = "h264")]
			Codec::H264 => Box::new(h264::H264Decoder::new()?),
			#[cfg(feature = "av1")]
			Codec::Av1 => Box::new(av1::Av1Decoder::new()?),
			#[allow(unreachable_patterns)]
			other => return Err(unavailable(other)),
		};
		Ok(Self {
			codec,
			inner,
			max_pixels: DEFAULT_MAX_PIXELS,
			output: PixelFormat::Rgb8,
		})
	}

	/// The codec this decoder reads.
	pub fn codec(&self) -> Codec {
		self.codec
	}

	/// Largest picture, in pixels, [`Decoder::decode`] accepts.
	pub fn max_pixels(&self) -> u64 {
		self.max_pixels
	}

	/// Accept pictures of up to `max_pixels` (default [`DEFAULT_MAX_PIXELS`]).
	pub fn set_max_pixels(&mut self, max_pixels: u64) {
		self.max_pixels = max_pixels;
	}

	/// The pixel format of decoded images.
	pub fn output_format(&self) -> PixelFormat {
		self.output
	}

	/// Decode into `format` images (`rgb8` by default): `rgb8`, `bgr8`, `rgba8`, `bgra8` or
	/// `mono8` (the luma only). Fails with [`Error::InvalidSettings`] for the 4:2:2 formats.
	pub fn set_output_format(&mut self, format: PixelFormat) -> Result<()> {
		if matches!(format, PixelFormat::Uyvy | PixelFormat::Yuyv) {
			return Err(Error::InvalidSettings(format!("can't decode into {format}")));
		}
		self.output = format;
		Ok(())
	}

	/// Decode one frame. Returns `None` if no picture is ready yet (e.g. while waiting for a keyframe).
	///
	/// Fails with [`Error::TooLarge`] for a picture above [`Decoder::max_pixels`].
	pub fn decode(&mut self, data: &[u8], timestamp: Duration) -> Result<Option<Image>> {
		let Some((width, height, pixels)) = self.inner.decode(data, self.max_pixels, self.output)? else {
			return Ok(None);
		};
		Ok(Some(Image::new(width, height, self.output, pixels, timestamp)?))
	}
}

#[expect(
	clippy::cast_possible_truncation,
	reason = "I420 dimensions come from `u32` image dimensions"
)]
fn create_software_encoder(
	settings: &EncoderSettings,
	(width, height): (usize, usize),
) -> Result<Box<dyn EncoderBackend>> {
	Ok(match settings.codec {
		#[cfg(feature = "vp8")]
		Codec::Vp8 => Box::new(vp8::Vp8Encoder::new(settings, width as u32, height as u32)?),
		#[cfg(feature = "h264")]
		Codec::H264 => Box::new(h264::H264Encoder::new(settings)?),
		#[cfg(feature = "av1")]
		Codec::Av1 => Box::new(av1::Av1Encoder::new(settings, width as u32, height as u32)?),
		#[allow(unreachable_patterns)]
		other => {
			let _ = (width, height);
			return Err(unavailable(other));
		}
	})
}

fn unavailable(codec: Codec) -> Error {
	Error::CodecUnavailable(format!(
		"{codec} support is not compiled in (enable the `{codec}` feature)"
	))
}

#[cfg(test)]
pub(crate) mod tests {
	use super::*;

	#[expect(clippy::cast_possible_truncation, reason = "the pattern wraps around")]
	pub(crate) fn test_pattern(w: u32, h: u32, t: u32) -> Image {
		let rgb: Vec<u8> = (0..h)
			.flat_map(|y| (0..w).flat_map(move |x| [((x + t * 4) % 256) as u8, (y % 256) as u8, 100]))
			.collect();
		Image::new(w, h, PixelFormat::Rgb8, rgb, Duration::from_millis(u64::from(t) * 33)).unwrap()
	}

	/// Shared checks run against every available codec.
	pub(crate) fn round_trip(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			bitrate: 4_000_000,
			..Default::default()
		})
		.unwrap();
		let mut decoder = Decoder::new(codec).unwrap();

		let mut decoded = 0;
		let mut keyframe_codec = None;
		for t in 0..10 {
			let image = test_pattern(64, 48, t);
			let Some(frame) = encoder.encode(&image).unwrap() else {
				continue;
			};
			assert_eq!(Codec::from_catalog(&frame.codec), Some(codec));
			// Delta frames carry the description of the keyframe they depend on.
			let keyframe_codec = keyframe_codec.get_or_insert_with(|| frame.codec.clone());
			assert_eq!(&frame.codec, keyframe_codec);
			assert_eq!(codec.is_keyframe(&frame.data), frame.keyframe);
			if t == 0 {
				assert!(frame.keyframe, "first frame must be a keyframe");
			}
			if let Some(out) = decoder.decode(&frame.data, frame.timestamp).unwrap() {
				assert_eq!((out.width, out.height), (64, 48));
				assert_eq!(out.timestamp, image.timestamp);
				let err = out
					.data
					.iter()
					.zip(image.data.iter())
					.map(|(a, b)| u64::from(a.abs_diff(*b)))
					.sum::<u64>() / out.data.len() as u64;
				assert!(err < 12, "{codec}: mean abs error {err}");
				decoded += 1;
			}
		}
		assert!(decoded >= 9, "{codec}: decoded {decoded} frames");
	}

	pub(crate) fn keyframes(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			keyframe_interval: Duration::from_millis(100),
			..Default::default()
		})
		.unwrap();
		let keyframes: Vec<bool> = (0..8)
			.filter_map(|t| encoder.encode(&test_pattern(32, 32, t)).unwrap())
			.map(|f| f.keyframe)
			.collect();
		assert!(keyframes[0]);
		assert!(keyframes.iter().filter(|k| **k).count() >= 2, "{keyframes:?}");

		let frame = encoder.encode(&test_pattern(48, 32, 9)).unwrap().unwrap();
		assert!(frame.keyframe, "resolution change restarts with a keyframe");
		assert_eq!((frame.width, frame.height), (48, 32));
	}

	/// Every input pixel format encodes; odd sizes are cropped to even ones.
	pub(crate) fn pixel_formats(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			..Default::default()
		})
		.unwrap();
		let mut decoder = Decoder::new(codec).unwrap();
		for (t, format) in [
			PixelFormat::Rgb8,
			PixelFormat::Bgr8,
			PixelFormat::Rgba8,
			PixelFormat::Bgra8,
			PixelFormat::Mono8,
			PixelFormat::Uyvy,
			PixelFormat::Yuyv,
		]
		.into_iter()
		.enumerate()
		{
			let (width, height) = (33u32, 25u32);
			let data = vec![128u8; (width * height) as usize * format.bytes_per_pixel()];
			let timestamp = Duration::from_millis(t as u64 * 33);
			let image = Image::new(width, height, format, data, timestamp).unwrap();
			encoder.force_keyframe();
			let frame = encoder
				.encode(&image)
				.unwrap()
				.expect("forced keyframes aren't dropped");
			assert!(frame.keyframe, "{codec} {format}");
			assert_eq!((frame.width, frame.height), (32, 24), "{codec} {format}");
			let out = decoder
				.decode(&frame.data, timestamp)
				.unwrap()
				.expect("keyframe decodes");
			assert_eq!((out.width, out.height, out.format), (32, 24, PixelFormat::Rgb8));
		}
	}

	/// Repeated or backwards capture times still encode, and keep their timestamps.
	pub(crate) fn irregular_timestamps(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			..Default::default()
		})
		.unwrap();
		for millis in [1000, 1000, 500, 1033] {
			let mut image = test_pattern(32, 32, 0);
			image.timestamp = Duration::from_millis(millis);
			if let Some(frame) = encoder.encode(&image).unwrap() {
				assert_eq!(frame.timestamp, image.timestamp);
			}
		}
	}

	pub(crate) fn forced_keyframe(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			keyframe_interval: Duration::from_secs(60),
			..Default::default()
		})
		.unwrap();
		// Rate control may drop unforced frames, but never turns them into keyframes.
		for t in 0..4 {
			if t == 2 {
				encoder.force_keyframe();
			}
			let frame = encoder.encode(&test_pattern(32, 32, t)).unwrap();
			match t {
				0 | 2 => assert!(frame.expect("forced keyframes aren't dropped").keyframe, "frame {t}"),
				_ => assert!(frame.is_none_or(|frame| !frame.keyframe), "frame {t}"),
			}
		}
	}

	/// A rejected image leaves a running encoder untouched.
	pub(crate) fn rejects_invalid_images(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			keyframe_interval: Duration::from_secs(60),
			..Default::default()
		})
		.unwrap();
		assert!(encoder.encode(&test_pattern(32, 32, 0)).unwrap().unwrap().keyframe);
		let tiny = Image::new(1, 1, PixelFormat::Rgb8, vec![0u8; 3], Duration::from_millis(33)).unwrap();
		assert!(matches!(encoder.encode(&tiny), Err(Error::InvalidImage(_))));
		// Same resolution as before, so the encoder carries on without a new keyframe.
		if let Some(frame) = encoder.encode(&test_pattern(32, 32, 2)).unwrap() {
			assert!(!frame.keyframe);
			assert_eq!((frame.width, frame.height), (32, 32));
		}
	}

	/// A noisy picture, so the encoded size follows the bitrate.
	#[expect(clippy::cast_possible_truncation, reason = "the noise wraps around")]
	fn noise(w: u32, h: u32, t: u32) -> Image {
		let mut state = 0x9e37_79b9_u32 ^ t.wrapping_mul(0x85eb_ca6b);
		let rgb: Vec<u8> = (0..w * h * 3)
			.map(|_| {
				state ^= state << 13;
				state ^= state >> 17;
				state ^= state << 5;
				state as u8
			})
			.collect();
		Image::new(w, h, PixelFormat::Rgb8, rgb, Duration::from_millis(u64::from(t) * 33)).unwrap()
	}

	/// Lowering the bitrate mid-stream shrinks the frames that follow.
	pub(crate) fn bitrate_changes(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			bitrate: 2_000_000,
			keyframe_interval: Duration::from_secs(60),
			hardware: Hardware::Off,
			..Default::default()
		})
		.unwrap();
		let size = |encoder: &mut Encoder, frames: std::ops::Range<u32>| -> usize {
			frames
				.filter_map(|t| encoder.encode(&noise(128, 96, t)).unwrap())
				.filter(|frame| !frame.keyframe)
				.map(|frame| frame.data.len())
				.sum()
		};
		let high = size(&mut encoder, 0..30);
		encoder.set_bitrate(200_000);
		assert_eq!(encoder.settings().bitrate, 200_000);
		// Let rate control settle before measuring.
		size(&mut encoder, 30..40);
		let low = size(&mut encoder, 40..70);
		assert!(low * 2 < high, "{codec}: {high} bytes at 2 Mbit/s, {low} at 200 kbit/s");
	}

	/// Pictures above the decoder's limit fail without being converted.
	pub(crate) fn rejects_oversized_pictures(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			..Default::default()
		})
		.unwrap();
		let frame = encoder.encode(&test_pattern(64, 48, 0)).unwrap().unwrap();

		let mut decoder = Decoder::new(codec).unwrap();
		assert_eq!(decoder.max_pixels(), DEFAULT_MAX_PIXELS);
		decoder.set_max_pixels(64 * 48 - 1);
		assert!(matches!(
			decoder.decode(&frame.data, frame.timestamp),
			Err(Error::TooLarge {
				width: 64,
				height: 48,
				..
			})
		));

		let mut decoder = Decoder::new(codec).unwrap();
		decoder.set_max_pixels(64 * 48);
		assert!(decoder.decode(&frame.data, frame.timestamp).unwrap().is_some());
	}

	/// Keyframes keep their interval when the capture clock jumps backwards (e.g. a
	/// looping rosbag) or jitters.
	pub(crate) fn keyframe_after_clock_jump(codec: Codec) {
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			keyframe_interval: Duration::from_secs(1),
			..Default::default()
		})
		.unwrap();
		let mut encode = |millis: u64| {
			let mut image = test_pattern(32, 32, 0);
			image.timestamp = Duration::from_millis(millis);
			encoder.encode(&image).unwrap()
		};
		assert!(encode(100_000).expect("first frame is a keyframe").keyframe);
		// Neither a small step back nor a restarted clock is due for a keyframe yet.
		for millis in [100_033, 100_032, 0, 500] {
			assert!(encode(millis).is_none_or(|frame| !frame.keyframe), "{millis}ms");
		}
		let frame = encode(1_000).expect("forced keyframes aren't dropped");
		assert!(frame.keyframe, "a second passed since the first keyframe");
	}

	/// Decoders produce every packed format, and refuse the 4:2:2 ones.
	#[test]
	fn decodes_into_each_output_format() {
		let Some(&codec) = Codec::available().first() else {
			return;
		};
		if codec == Codec::H264 && std::env::var_os("OPENH264_LIBRARY").is_none() {
			return;
		}
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			hardware: Hardware::Off,
			..Default::default()
		})
		.unwrap();
		let frame = encoder.encode(&test_pattern(64, 48, 0)).unwrap().unwrap();
		let rgb = Decoder::new(codec)
			.unwrap()
			.decode(&frame.data, frame.timestamp)
			.unwrap()
			.unwrap();
		for format in [
			PixelFormat::Bgr8,
			PixelFormat::Rgba8,
			PixelFormat::Bgra8,
			PixelFormat::Mono8,
		] {
			let mut decoder = Decoder::new(codec).unwrap();
			decoder.set_output_format(format).unwrap();
			assert_eq!(decoder.output_format(), format);
			let image = decoder.decode(&frame.data, frame.timestamp).unwrap().unwrap();
			assert_eq!((image.width, image.height, image.format), (64, 48, format));
			if format == PixelFormat::Bgr8 {
				assert_eq!((image.data[0], image.data[2]), (rgb.data[2], rgb.data[0]));
			}
		}
		let mut decoder = Decoder::new(codec).unwrap();
		assert!(matches!(
			decoder.set_output_format(PixelFormat::Uyvy),
			Err(Error::InvalidSettings(_))
		));
		assert_eq!(decoder.output_format(), PixelFormat::Rgb8);
	}

	#[test]
	fn codec_names() {
		assert_eq!("vp8".parse::<Codec>().unwrap(), Codec::Vp8);
		assert_eq!("H264".parse::<Codec>().unwrap(), Codec::H264);
		assert_eq!("AV1".parse::<Codec>().unwrap(), Codec::Av1);
		assert!("vp9".parse::<Codec>().is_err());
		assert!(Codec::Vp8.is_keyframe(&[0x10, 0x02, 0x00]));
		assert!(!Codec::Vp8.is_keyframe(&[0x11, 0x02, 0x00]));
	}

	#[test]
	fn codec_names_round_trip() {
		for &codec in Codec::ALL {
			assert_eq!(codec.to_string().parse::<Codec>().unwrap(), codec);
		}
		assert_eq!("AVC".parse::<Codec>().unwrap(), Codec::H264);
		assert_eq!("av01".parse::<Codec>().unwrap(), Codec::Av1);
		assert!(matches!("".parse::<Codec>(), Err(Error::InvalidSettings(_))));
	}

	#[test]
	fn codecs_from_catalog() {
		assert_eq!(Codec::from_catalog(&VideoCodec::VP8), Some(Codec::Vp8));
		let avc: VideoCodec = "avc3.42001f".parse().unwrap();
		assert_eq!(Codec::from_catalog(&avc), Some(Codec::H264));
		let av1: VideoCodec = "av01.0.04M.08".parse().unwrap();
		assert_eq!(Codec::from_catalog(&av1), Some(Codec::Av1));
		assert_eq!(Codec::from_catalog(&VideoCodec::Unknown("hev2".into())), None);
	}

	#[test]
	fn detects_h264_keyframes_by_idr_nal() {
		let sps_pps_idr = [0, 0, 0, 1, 0x67, 1, 0, 0, 1, 0x68, 2, 0, 0, 1, 0x65, 3];
		assert!(Codec::H264.is_keyframe(&sps_pps_idr));
		assert!(!Codec::H264.is_keyframe(&[0, 0, 0, 1, 0x41, 3]));
		assert!(!Codec::H264.is_keyframe(&[0, 0, 0, 1, 0x67, 1]));
		assert!(!Codec::H264.is_keyframe(&[]));
		assert!(!Codec::Vp8.is_keyframe(&[]));
	}

	#[test]
	fn default_codec_is_compiled_in() {
		if !Codec::available().is_empty() {
			assert!(Codec::default().is_available());
			assert_eq!(Codec::default(), Codec::available()[0]);
		}
	}

	#[test]
	fn missing_codecs_are_reported() {
		for &codec in Codec::ALL {
			if !codec.is_available() {
				let settings = EncoderSettings {
					codec,
					..Default::default()
				};
				assert!(matches!(Encoder::new(settings), Err(Error::CodecUnavailable(_))));
				assert!(matches!(Decoder::new(codec), Err(Error::CodecUnavailable(_))));
			}
		}
	}

	#[test]
	fn hardware_modes() {
		for mode in [Hardware::Off, Hardware::Auto, Hardware::Require] {
			assert_eq!(mode.to_string().parse::<Hardware>().unwrap(), mode);
		}
		assert_eq!("AUTO".parse::<Hardware>().unwrap(), Hardware::Auto);
		assert!(matches!("on".parse::<Hardware>(), Err(Error::InvalidSettings(_))));
		assert_eq!(EncoderSettings::default().hardware, Hardware::Auto);
	}

	#[test]
	fn hardware_off_encodes_in_software() {
		let Some(&codec) = Codec::available().first() else {
			return;
		};
		let mut encoder = Encoder::new(EncoderSettings {
			codec,
			hardware: Hardware::Off,
			..Default::default()
		})
		.unwrap();
		if codec == Codec::H264 && std::env::var_os("OPENH264_LIBRARY").is_none() {
			return;
		}
		assert!(encoder.encode(&test_pattern(32, 32, 0)).unwrap().unwrap().keyframe);
		assert_eq!(encoder.hardware_encoder(), None);
	}

	#[cfg(not(feature = "hw"))]
	#[test]
	fn required_hardware_needs_the_hw_feature() {
		let settings = EncoderSettings {
			hardware: Hardware::Require,
			..Default::default()
		};
		if settings.codec.is_available() {
			assert!(matches!(Encoder::new(settings), Err(Error::CodecUnavailable(_))));
		}
	}

	#[test]
	fn encoder_settings_derived_values() {
		let settings = EncoderSettings::default();
		assert_eq!(settings.gop_frames(), 120);
		assert!((1..=4).contains(&settings.threads()));

		let settings = EncoderSettings {
			max_fps: 29.97,
			keyframe_interval: Duration::from_secs(1),
			threads: 8,
			..Default::default()
		};
		assert_eq!(settings.gop_frames(), 60);
		assert_eq!(settings.threads(), 8);

		let settings = EncoderSettings {
			keyframe_interval: Duration::ZERO,
			..Default::default()
		};
		assert_eq!(settings.gop_frames(), 1);
	}
}