1use super::encoder::{Applied, Backend as Choice, Codec, Config};
21use crate::device::Drives;
22use crate::encode::Encoded;
23use crate::{Error, Frame};
24
25#[cfg(feature = "openh264")]
26mod openh264;
27
28#[cfg(test)]
29pub(crate) mod probe;
30
31#[cfg(apple)]
32mod videotoolbox;
33
34#[cfg(target_os = "windows")]
35mod mediafoundation;
36
37#[cfg(all(target_os = "android", feature = "mediacodec"))]
38mod mediacodec;
39
40#[cfg(all(target_os = "linux", feature = "nvidia"))]
41mod nvenc;
42
43#[cfg(all(target_os = "linux", feature = "v4l2"))]
44mod v4l2;
45
46#[cfg(all(target_os = "linux", feature = "vaapi"))]
47mod vaapi;
48
49pub(crate) trait Backend {
57 fn encode(&mut self, frame: &Frame, cut: bool) -> Result<(), Error>;
66
67 fn receive(&mut self) -> Result<Option<Encoded>, Error>;
69
70 fn flush(&mut self) -> Result<(), Error>;
82
83 #[cfg(all(
85 test,
86 any(
87 feature = "openh264",
88 apple,
89 all(target_os = "android", feature = "mediacodec"),
90 all(target_os = "linux", feature = "vaapi"),
91 )
92 ))]
93 fn encode_all(&mut self, frame: &Frame, cut: bool) -> Result<Vec<Encoded>, Error> {
94 self.encode(frame, cut)?;
95 self.receive_all()
96 }
97
98 #[cfg(test)]
100 #[allow(dead_code, reason = "only the platform backends' tests use it")]
101 fn flush_all(&mut self) -> Result<Vec<Encoded>, Error> {
102 self.flush()?;
103 self.receive_all()
104 }
105
106 #[cfg(test)]
108 fn receive_all(&mut self) -> Result<Vec<Encoded>, Error> {
109 let mut encoded = Vec::new();
110 while let Some(unit) = self.receive()? {
111 encoded.push(unit);
112 }
113 Ok(encoded)
114 }
115
116 fn set_bitrate(&mut self, bitrate: u64) -> Result<(), Error>;
125
126 fn can_cut(&self) -> bool;
134
135 fn scales(&self, _surface: &crate::Surface) -> bool {
139 false
140 }
141
142 fn name(&self) -> &'static str;
144
145 fn applied(&self) -> Applied {
151 Applied::default()
152 }
153}
154
155#[cfg(any(
158 apple,
159 target_os = "windows",
160 all(target_os = "linux", any(feature = "nvidia", feature = "vaapi", feature = "v4l2")),
161 test
162))]
163fn keyframe_nal(codec: Codec, nal: &[u8]) -> bool {
164 let Some(&header) = nal.first() else {
165 return false;
166 };
167 match codec {
168 Codec::H264 => header & 0x1f == 5,
169 Codec::H265 => (16..=23).contains(&((header >> 1) & 0x3f)),
170 }
171}
172
173#[cfg(any(
177 target_os = "windows",
178 all(target_os = "linux", any(feature = "nvidia", feature = "vaapi", feature = "v4l2")),
179 test
180))]
181fn keyframe_annexb(codec: Codec, mut annexb: &[u8]) -> bool {
182 while let Some((at, len)) = moq_mux::codec::annexb::find_start_code(annexb) {
183 annexb = &annexb[at + len..];
184 let Some(&header) = annexb.first() else { break };
185 let slice = match codec {
186 Codec::H264 => (1..=5).contains(&(header & 0x1f)),
187 Codec::H265 => (header >> 1) & 0x3f < 32,
188 };
189 if slice {
190 return keyframe_nal(codec, annexb);
191 }
192 }
193 false
194}
195
196pub const NAMES: &[&str] = &[
208 "videotoolbox",
209 "mediafoundation",
210 "mediacodec",
211 "nvenc",
212 "vaapi",
213 "v4l2",
214 "openh264",
215];
216
217#[cfg_attr(not(feature = "render"), allow(dead_code, reason = "only the render export asks"))]
221pub(crate) fn reads_export(name: &str) -> bool {
222 HARDWARE.iter().any(|candidate| {
223 #[cfg(target_os = "linux")]
224 let reads = candidate.vulkan;
225 #[cfg(not(target_os = "linux"))]
227 let reads = cfg!(any(apple, target_os = "windows"));
228 candidate.name == name && reads
229 })
230}
231
232struct Candidate {
234 name: &'static str,
235 codecs: &'static [Codec],
236 open: fn(&Config) -> Result<Box<dyn Backend>, Error>,
237 #[cfg_attr(
240 not(feature = "capture"),
241 allow(dead_code, reason = "only the `capture` feature uses it")
242 )]
243 cuts: bool,
244 drives: Drives,
246 #[cfg(target_os = "linux")]
247 vulkan: bool,
248}
249
250const HARDWARE: &[Candidate] = &[
253 #[cfg(apple)]
254 Candidate {
255 name: videotoolbox::NAME,
256 codecs: &[Codec::H264, Codec::H265],
257 open: videotoolbox::VideoToolbox::open,
258 cuts: true,
259 drives: Drives::Own,
260 #[cfg(target_os = "linux")]
261 vulkan: false,
262 },
263 #[cfg(target_os = "windows")]
264 Candidate {
265 name: mediafoundation::NAME,
266 codecs: &[Codec::H264, Codec::H265],
267 open: mediafoundation::MediaFoundation::open,
268 cuts: true,
269 drives: Drives::Own,
270 #[cfg(target_os = "linux")]
271 vulkan: false,
272 },
273 #[cfg(all(target_os = "android", feature = "mediacodec"))]
274 Candidate {
275 name: mediacodec::NAME,
276 codecs: &[Codec::H264, Codec::H265],
277 open: mediacodec::MediaCodec::open,
278 cuts: true,
279 drives: Drives::Own,
280 #[cfg(target_os = "linux")]
281 vulkan: false,
282 },
283 #[cfg(all(target_os = "linux", feature = "nvidia"))]
284 Candidate {
285 name: nvenc::NAME,
286 codecs: &[Codec::H264, Codec::H265],
287 open: nvenc::Nvenc::open,
288 cuts: true,
289 drives: Drives::Nvidia,
290 #[cfg(target_os = "linux")]
291 vulkan: true,
292 },
293 #[cfg(all(target_os = "linux", feature = "vaapi"))]
294 Candidate {
295 name: vaapi::NAME,
296 codecs: &[Codec::H264, Codec::H265],
297 open: vaapi::Vaapi::open,
298 cuts: true,
299 drives: Drives::Render,
300 #[cfg(target_os = "linux")]
301 vulkan: false,
302 },
303 #[cfg(all(target_os = "linux", feature = "v4l2"))]
307 Candidate {
308 name: v4l2::NAME,
309 codecs: &[Codec::H264],
310 open: v4l2::V4l2::open,
311 cuts: false,
312 drives: Drives::Video,
313 #[cfg(target_os = "linux")]
314 vulkan: false,
315 },
316];
317
318const SOFTWARE: &[Candidate] = &[
322 #[cfg(feature = "openh264")]
323 Candidate {
324 name: openh264::NAME,
325 codecs: &[Codec::H264],
326 open: openh264::Openh264::open,
327 cuts: true,
328 drives: Drives::Own,
329 #[cfg(target_os = "linux")]
330 vulkan: false,
331 },
332];
333
334#[cfg(test)]
338const NAMED_ONLY: &[Candidate] = &[
339 Candidate {
340 name: probe::NAME,
341 codecs: &[Codec::H264],
342 open: probe::Probe::open,
343 cuts: true,
344 drives: Drives::Own,
345 #[cfg(target_os = "linux")]
346 vulkan: false,
347 },
348 Candidate {
349 name: probe::NO_CUT,
350 codecs: &[Codec::H264],
351 open: probe::Probe::open_no_cut,
352 cuts: false,
353 drives: Drives::Own,
354 #[cfg(target_os = "linux")]
355 vulkan: false,
356 },
357 #[cfg(feature = "openh264")]
358 Candidate {
359 name: probe::PIPELINED,
360 codecs: &[Codec::H264],
361 open: probe::Pipelined::open,
362 cuts: true,
363 drives: Drives::Own,
364 #[cfg(target_os = "linux")]
365 vulkan: false,
366 },
367];
368
369#[cfg(not(test))]
370const NAMED_ONLY: &[Candidate] = &[];
371
372struct Attempt<'a> {
376 candidate: &'a Candidate,
377 hardware: bool,
378}
379
380impl<'a> Attempt<'a> {
381 fn hardware(candidate: &'a Candidate) -> Self {
382 Self {
383 candidate,
384 hardware: true,
385 }
386 }
387
388 fn software(candidate: &'a Candidate) -> Self {
389 Self {
390 candidate,
391 hardware: false,
392 }
393 }
394}
395
396pub(crate) fn open(config: &Config) -> Result<Box<dyn Backend>, Error> {
399 select(attempts(config.codec, &config.backend), config)
400}
401
402#[cfg_attr(
405 not(feature = "capture"),
406 allow(dead_code, reason = "only the `capture` feature uses it")
407)]
408pub(crate) fn always_cuts(codec: Codec, kind: &Choice) -> bool {
409 let attempts = attempts(codec, kind);
410 !attempts.is_empty() && attempts.iter().all(|attempt| attempt.candidate.cuts)
411}
412
413#[cfg_attr(not(feature = "render"), allow(dead_code, reason = "only the render export asks"))]
416pub(crate) fn candidates(codec: Codec, kind: &Choice) -> Vec<(&'static str, bool)> {
417 attempts(codec, kind)
418 .iter()
419 .map(|attempt| (attempt.candidate.name, attempt.hardware))
420 .collect()
421}
422
423fn attempts(codec: Codec, kind: &Choice) -> Vec<Attempt<'static>> {
425 let supports = move |c: &Candidate| c.codecs.contains(&codec);
426 let hardware = HARDWARE.iter().filter(|c| supports(c)).map(Attempt::hardware);
427 let software = SOFTWARE.iter().filter(|c| supports(c)).map(Attempt::software);
428
429 match kind {
430 Choice::Auto => hardware.chain(software).collect(),
431 Choice::Hardware => hardware.collect(),
432 Choice::Software => software.collect(),
433 Choice::Named(name) => HARDWARE
434 .iter()
435 .map(Attempt::hardware)
436 .chain(SOFTWARE.iter().chain(NAMED_ONLY.iter()).map(Attempt::software))
437 .filter(|a| supports(a.candidate) && a.candidate.name == name)
438 .collect(),
439 }
440}
441
442fn select(attempts: Vec<Attempt>, config: &Config) -> Result<Box<dyn Backend>, Error> {
449 let mut tried: Vec<String> = Vec::new();
453 let mut refused = Vec::new();
454
455 for attempt in attempts {
456 let name = attempt.candidate.name;
457
458 #[cfg(target_os = "linux")]
459 if let Some(device) = config.input
460 && (!attempt.hardware || !attempt.candidate.vulkan)
461 {
462 let reason = format!("{name}: cannot import external Vulkan {device}");
463 if attempt.hardware {
464 refused.push(reason.clone());
465 }
466 tried.push(reason);
467 continue;
468 }
469 match config.device.takes(attempt.candidate.drives) {
470 Ok(true) => {}
471 Ok(false) => {
472 let reason = format!("{name}: does not open {}", config.device);
473 if attempt.hardware {
474 refused.push(reason.clone());
475 }
476 tried.push(reason);
477 continue;
478 }
479 Err(e) => {
482 tracing::debug!(encoder = name, error = %e, "encoder unavailable, trying next");
483 tried.push(format!("{name}: {e}"));
484 if attempt.hardware {
485 refused.push(format!("{name}: {e}"));
486 }
487 continue;
488 }
489 }
490 match (attempt.candidate.open)(config) {
491 Ok(backend) => {
492 if !attempt.hardware && matches!(&config.backend, Choice::Auto) {
495 let refused = match refused.is_empty() {
496 true => "none in this build".to_owned(),
497 false => refused.join(", "),
498 };
499 tracing::warn!(
500 encoder = name,
501 %refused,
502 "no hardware encoder available, falling back to software"
503 );
504 }
505 return Ok(backend);
506 }
507 Err(e) => {
508 tracing::debug!(encoder = name, error = %e, "encoder unavailable, trying next");
509 tried.push(format!("{name}: {e}"));
510 if attempt.hardware {
511 refused.push(format!("{name}: {e}"));
512 }
513 }
514 }
515 }
516
517 #[cfg(target_os = "linux")]
523 if let Some(device) = config.input {
524 return Err(Error::NoEncoder(format!(
525 "no backend can import external Vulkan {device} (tried: {})",
526 tried.join(", ")
527 )));
528 }
529 if tried.is_empty() {
530 return Err(missing(config.codec, &config.backend));
531 }
532
533 Err(Error::NoEncoder(tried.join(", ")))
534}
535
536pub(crate) fn missing(codec: Codec, kind: &Choice) -> Error {
538 let available = available_names(codec).join(", ");
539 match kind {
540 Choice::Named(name) => Error::UnknownEncoder {
541 name: name.clone(),
542 codec,
543 available,
544 },
545 kind => Error::NoEncoder(format!(
546 "nothing compiled in for {codec:?} at {kind:?} (this build has: {available})"
547 )),
548 }
549}
550
551fn available_names(codec: Codec) -> Vec<&'static str> {
556 HARDWARE
557 .iter()
558 .chain(SOFTWARE.iter())
559 .filter(|candidate| candidate.codecs.contains(&codec))
560 .map(|candidate| candidate.name)
561 .collect()
562}
563
564#[cfg(test)]
565#[cfg_attr(
566 not(feature = "openh264"),
567 allow(dead_code, reason = "only the `openh264` feature uses it")
568)]
569pub(crate) mod test_util {
570 use h264_reader::nal::sps::SeqParameterSet;
571 use h264_reader::nal::{Nal, RefNal, UnitType};
572
573 #[derive(Debug)]
575 pub(crate) struct Spent {
576 pub mean: u64,
578 #[cfg_attr(
580 all(
581 feature = "openh264",
582 not(any(
583 apple,
584 target_os = "windows",
585 all(target_os = "linux", any(feature = "nvidia", feature = "vaapi"))
586 ))
587 ),
588 expect(dead_code, reason = "only the hardware encoders' tests bound the peak")
589 )]
590 pub peak: u64,
591 }
592
593 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
595 pub(crate) enum Scene {
596 Calm,
598 Busy,
601 Waking,
605 }
606
607 pub(crate) fn spend(config: &crate::encode::Config, scene: Scene, retune: Option<u64>) -> Option<Spent> {
612 let mut encoder = crate::encode::Encoder::new(config).ok()?;
613 let size = crate::Size::new(config.width, config.height);
614 let fps = config.framerate.rounded() as usize;
615 let mut sizes = Vec::new();
616 let mut noise = 0x2545_f491_4f6c_dd1du64;
617 for index in 0..3 * fps {
618 if let Some(bps) = retune.filter(|_| index == fps / 2) {
619 encoder
620 .set_bitrate(moq_net::bandwidth::Rate::from_bps(bps))
621 .expect("retune the cap");
622 }
623 let (w, h) = (size.width as usize, size.height as usize);
624 let busy = match scene {
625 Scene::Calm => false,
626 Scene::Busy => true,
627 Scene::Waking => index >= 3 * fps / 2,
628 };
629 let shift = if scene == Scene::Waking { 0 } else { index };
631 let mut rgba = vec![255u8; w * h * 4];
632 for y in 0..h {
633 for x in 0..w {
634 let i = (y * w + x) * 4;
635 let value = if busy {
636 noise ^= noise << 13;
637 noise ^= noise >> 7;
638 noise ^= noise << 17;
639 noise as u8
640 } else {
641 let sx = x + shift;
642 (((sx * 7) ^ (y * 13)) & 0xff) as u8 / 2 + ((sx / 9 + y / 5) % 2) as u8 * 64
643 };
644 rgba[i..i + 3].fill(value);
645 }
646 }
647 let surface = crate::Surface::rgba(&rgba, size).expect("wrap the frame");
648 let timestamp =
649 moq_net::Timestamp::from_micros(index as u64 * 1_000_000 / fps as u64).expect("frame timestamp");
650 let bytes: usize = encoder
651 .encode_all(&crate::Frame::new(timestamp, surface))
652 .expect("encode a frame")
653 .iter()
654 .map(|unit| unit.payload.len())
655 .sum();
656 sizes.push(bytes);
657 }
658 let settled = &sizes[fps..];
659 let bits = |frames: &[usize]| frames.iter().sum::<usize>() as u64 * 8;
660 Some(Spent {
661 mean: bits(settled) * fps as u64 / settled.len() as u64,
662 peak: settled.windows(fps).map(bits).max().unwrap_or(0),
663 })
664 }
665
666 #[derive(Debug, PartialEq, Eq)]
674 pub(crate) struct Described {
675 pub primaries: u8,
676 pub transfer: u8,
677 pub matrix: u8,
678 pub full_range: bool,
679 }
680
681 pub(crate) const BT601_DESCRIBED: Described = Described {
691 primaries: 6,
692 transfer: 1,
693 matrix: 6,
694 full_range: false,
695 };
696
697 pub(crate) const BT709_DESCRIBED: Described = Described {
698 primaries: 1,
699 transfer: 1,
700 matrix: 1,
701 full_range: false,
702 };
703
704 pub(crate) fn declared_color(annexb: &[u8]) -> Option<Described> {
711 let starts: Vec<usize> = (0..annexb.len().saturating_sub(2))
714 .filter(|&i| annexb[i..i + 3] == [0, 0, 1])
715 .map(|i| i + 3)
716 .collect();
717
718 let sps = starts.iter().enumerate().find_map(|(n, &start)| {
719 let end = starts.get(n + 1).map_or(annexb.len(), |&next| next - 3);
722 let nal = RefNal::new(&annexb[start..end], &[], true);
723 match nal.header().ok()?.nal_unit_type() {
724 UnitType::SeqParameterSet => SeqParameterSet::from_bits(nal.rbsp_bits()).ok(),
725 _ => None,
726 }
727 })?;
728
729 let signal = sps.vui_parameters.as_ref()?.video_signal_type.as_ref()?;
730 let description = signal.colour_description.as_ref()?;
731 Some(Described {
732 primaries: description.colour_primaries,
733 transfer: description.transfer_characteristics,
734 matrix: description.matrix_coefficients,
735 full_range: signal.video_full_range_flag,
736 })
737 }
738}
739
740#[cfg(test)]
741mod tests {
742 #![cfg_attr(
743 not(feature = "openh264"),
744 allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
745 )]
746
747 use super::*;
748
749 struct Stub;
752
753 impl Stub {
754 fn open(_config: &Config) -> Result<Box<dyn Backend>, Error> {
755 Ok(Box::new(Self))
756 }
757 }
758
759 impl Backend for Stub {
760 fn encode(&mut self, _frame: &Frame, _cut: bool) -> Result<(), Error> {
761 Ok(())
762 }
763
764 fn receive(&mut self) -> Result<Option<Encoded>, Error> {
765 Ok(None)
766 }
767
768 fn flush(&mut self) -> Result<(), Error> {
769 Ok(())
770 }
771
772 fn set_bitrate(&mut self, _bitrate: u64) -> Result<(), Error> {
773 Ok(())
774 }
775
776 fn can_cut(&self) -> bool {
777 true
778 }
779
780 fn name(&self) -> &'static str {
781 "stub"
782 }
783 }
784
785 const WORKING: Candidate = Candidate {
786 name: "stub",
787 codecs: &[Codec::H264],
788 open: Stub::open,
789 cuts: true,
790 drives: Drives::Own,
791 #[cfg(target_os = "linux")]
792 vulkan: false,
793 };
794
795 const REFUSING: Candidate = Candidate {
798 name: "driverless",
799 codecs: &[Codec::H264],
800 open: |_| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
801 cuts: true,
802 drives: Drives::Own,
803 #[cfg(target_os = "linux")]
804 vulkan: false,
805 };
806
807 fn config() -> Config {
808 Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
809 }
810
811 #[test]
814 fn always_cuts_needs_every_candidate_to_promise() {
815 let named = |name: &str| Choice::Named(name.to_owned());
816 assert!(always_cuts(Codec::H264, &named(probe::NAME)));
817 assert!(!always_cuts(Codec::H264, &named(probe::NO_CUT)));
818 assert!(!always_cuts(Codec::H264, &named("v4l2")), "V4L2 learns it at open");
819 assert!(!always_cuts(Codec::H264, &named("nonexistent")), "nothing to open");
820
821 let _probe = probe::exclusive();
822 for candidate in NAMED_ONLY {
823 let backend = (candidate.open)(&config()).unwrap();
824 assert_eq!(backend.can_cut(), candidate.cuts, "{}", candidate.name);
825 }
826 }
827
828 #[test]
831 fn a_named_device_passes_over_other_hardware() {
832 const RENDER: Candidate = Candidate {
833 name: "render",
834 open: |_| panic!("opened a render backend for a codec node"),
835 drives: Drives::Render,
836 ..WORKING
837 };
838 const VIDEO: Candidate = Candidate {
839 name: "video",
840 drives: Drives::Video,
841 ..WORKING
842 };
843
844 let mut config = config();
845 config.device = crate::Device::Video("/dev/video11".into());
846 let opened = select(vec![Attempt::hardware(&RENDER), Attempt::hardware(&VIDEO)], &config).unwrap();
847 assert_eq!(opened.name(), "stub");
848
849 match select(vec![Attempt::hardware(&RENDER)], &config) {
850 Err(Error::NoEncoder(reason)) => assert!(
851 reason.contains("render: does not open codec node /dev/video11"),
852 "{reason}"
853 ),
854 Err(other) => panic!("expected NoEncoder, got {other:?}"),
855 Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
856 }
857 }
858
859 #[cfg(target_os = "linux")]
862 #[test]
863 fn a_failed_driver_check_moves_on() {
864 const NVIDIA: Candidate = Candidate {
865 name: "nvidia",
866 open: |_| panic!("opened NVIDIA for an unreadable node"),
867 drives: Drives::Nvidia,
868 ..WORKING
869 };
870 const RENDER: Candidate = Candidate {
871 name: "render",
872 drives: Drives::Render,
873 ..WORKING
874 };
875
876 let mut config = config();
877 config.device = crate::Device::Render("/dev/dri/renderD199-absent".into());
878 let opened = select(vec![Attempt::hardware(&NVIDIA), Attempt::hardware(&RENDER)], &config).unwrap();
879 assert_eq!(opened.name(), "stub");
880
881 match select(vec![Attempt::hardware(&NVIDIA)], &config) {
882 Err(Error::NoEncoder(reason)) => assert!(
883 reason.contains("nvidia: ") && reason.contains("renderD199-absent"),
884 "{reason}"
885 ),
886 Err(other) => panic!("expected NoEncoder, got {other:?}"),
887 Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
888 }
889 }
890
891 #[tracing_test::traced_test]
892 #[test]
893 fn falling_past_hardware_warns() {
894 let backend = select(
895 vec![Attempt::hardware(&REFUSING), Attempt::software(&WORKING)],
896 &config(),
897 )
898 .unwrap();
899 assert_eq!(backend.name(), "stub");
900
901 logs_assert(
904 |lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
905 Some(warning) if warning.contains("driverless") && warning.contains("driver libraries not found") => {
906 Ok(())
907 }
908 Some(warning) => Err(format!("warning does not name the refusal: {warning}")),
909 None => Err("no fallback warning".to_owned()),
910 },
911 );
912 }
913
914 #[tracing_test::traced_test]
917 #[test]
918 fn falling_past_hardware_for_another_device_warns() {
919 const RENDER: Candidate = Candidate {
920 name: "render",
921 open: |_| panic!("opened a render backend for a codec node"),
922 drives: Drives::Render,
923 ..WORKING
924 };
925
926 let mut config = config();
927 config.device = crate::Device::Video("/dev/video11".into());
928 select(vec![Attempt::hardware(&RENDER), Attempt::software(&WORKING)], &config).unwrap();
929 logs_assert(
930 |lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
931 Some(warning) if warning.contains("render: does not open codec node /dev/video11") => Ok(()),
932 Some(warning) => Err(format!("warning does not name the passed-over hardware: {warning}")),
933 None => Err("no fallback warning".to_owned()),
934 },
935 );
936 }
937
938 #[tracing_test::traced_test]
939 #[test]
940 fn auto_without_hardware_warns() {
941 let backend = select(vec![Attempt::software(&WORKING)], &config()).unwrap();
942 assert_eq!(backend.name(), "stub");
943 assert!(logs_contain("falling back to software"));
944 assert!(logs_contain("none in this build"));
945 }
946
947 #[tracing_test::traced_test]
948 #[test]
949 fn asking_for_software_is_not_a_fallback() {
950 let mut config = config();
951 config.backend = Choice::Software;
952 select(vec![Attempt::software(&WORKING)], &config).unwrap();
953 assert!(!logs_contain("falling back to software"));
954 }
955
956 #[test]
959 fn an_unknown_name_names_itself_and_the_alternatives() {
960 let mut config = config();
961 config.backend = Choice::Named("vappi".to_owned());
962
963 match open(&config) {
964 Err(Error::UnknownEncoder { name, codec, available }) => {
965 assert_eq!(name, "vappi");
966 assert_eq!(codec, config.codec);
967 #[cfg(feature = "openh264")]
968 assert!(available.contains(openh264::NAME), "nothing offered: {available}");
969 #[cfg(not(feature = "openh264"))]
970 assert!(!available.contains("openh264"), "disabled backend offered: {available}");
971 }
972 Err(other) => panic!("expected UnknownEncoder, got {other:?}"),
973 Ok(backend) => panic!("expected UnknownEncoder, opened {}", backend.name()),
974 }
975 }
976
977 #[cfg(not(feature = "openh264"))]
978 #[test]
979 fn disabled_software_backend_is_not_selected() {
980 let mut config = config();
981 config.backend = Choice::Software;
982 assert!(matches!(open(&config), Err(Error::NoEncoder(_))));
983
984 config.backend = Choice::Named("openh264".to_owned());
985 assert!(matches!(open(&config), Err(Error::UnknownEncoder { .. })));
986 }
987
988 #[test]
991 fn every_candidate_refusing_reports_why() {
992 let mut config = config();
993 config.backend = Choice::Named("driverless".to_owned());
994
995 match select(vec![Attempt::hardware(&REFUSING)], &config) {
996 Err(Error::NoEncoder(tried)) => {
997 assert!(tried.contains("driverless"), "does not name the backend: {tried}");
998 assert!(
999 tried.contains("driver libraries not found"),
1000 "does not carry the reason: {tried}"
1001 );
1002 }
1003 Err(other) => panic!("expected NoEncoder, got {other:?}"),
1004 Ok(backend) => panic!("expected NoEncoder, opened {}", backend.name()),
1005 }
1006 }
1007
1008 #[tracing_test::traced_test]
1009 #[test]
1010 fn hardware_that_opens_is_not_a_fallback() {
1011 select(
1012 vec![Attempt::hardware(&WORKING), Attempt::software(&WORKING)],
1013 &config(),
1014 )
1015 .unwrap();
1016 assert!(!logs_contain("falling back to software"));
1017 }
1018
1019 #[test]
1022 fn every_compiled_backend_is_named_publicly() {
1023 for candidate in HARDWARE.iter().chain(SOFTWARE.iter()) {
1024 assert!(
1025 NAMES.contains(&candidate.name),
1026 "{} is compiled in but missing from NAMES",
1027 candidate.name,
1028 );
1029 }
1030 }
1031
1032 #[test]
1035 fn an_h264_keyframe_is_its_idr_slice() {
1036 let idr = [
1037 0, 0, 0, 1, 0x67, 0x42, 0, 0, 1, 0x68, 0xce, 0, 0, 1, 0x06, 0x05, 0, 0, 1, 0x65, 0x88,
1038 ];
1039 assert!(keyframe_annexb(Codec::H264, &idr));
1040
1041 let delta = [0, 0, 0, 1, 0x09, 0xf0, 0, 0, 0, 1, 0x41, 0x9a];
1042 assert!(!keyframe_annexb(Codec::H264, &delta));
1043
1044 assert!(!keyframe_annexb(
1046 Codec::H264,
1047 &[0, 0, 1, 0x67, 0x42, 0, 0, 1, 0x68, 0xce]
1048 ));
1049 assert!(!keyframe_annexb(Codec::H264, &[]));
1050 }
1051
1052 #[test]
1054 fn an_h265_keyframe_is_any_irap_slice() {
1055 let with_slice = |nal_type: u8| {
1057 let mut annexb = Vec::new();
1058 for header in [32, 33, 34, nal_type] {
1059 annexb.extend_from_slice(&[0, 0, 0, 1, header << 1, 0x01, 0xaf]);
1060 }
1061 annexb
1062 };
1063 for irap in 16..=23 {
1064 assert!(keyframe_annexb(Codec::H265, &with_slice(irap)), "type {irap}");
1065 }
1066 for trailing in [0, 1] {
1067 assert!(!keyframe_annexb(Codec::H265, &with_slice(trailing)), "type {trailing}");
1068 }
1069 }
1070}