1use bytes::Bytes;
25use moq_net::Timestamp;
26
27use super::decoder::{Backend as Choice, Config};
28use crate::device::Drives;
29use crate::{Error, Frame, Size};
30
31#[cfg(feature = "openh264")]
32mod openh264;
33
34#[cfg(test)]
35pub(crate) mod probe;
36
37#[cfg(feature = "vpx")]
38mod vpx;
39
40#[cfg(apple)]
41mod videotoolbox;
42
43#[cfg(target_os = "windows")]
44mod mediafoundation;
45
46#[cfg(all(target_os = "android", feature = "mediacodec"))]
47mod mediacodec;
48
49#[cfg(any(
50 all(target_os = "android", feature = "mediacodec"),
51 all(target_os = "linux", any(feature = "nvidia", feature = "v4l2", feature = "vaapi")),
52))]
53mod submitted;
54
55#[cfg(all(target_os = "linux", feature = "nvidia"))]
56mod nvdec;
57
58#[cfg(all(target_os = "linux", feature = "vaapi"))]
61pub(crate) mod vaapi;
62
63#[cfg(all(target_os = "linux", feature = "v4l2"))]
64mod v4l2;
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum Codec {
70 H264,
72 H265,
74 Av1,
76 Vp8,
78 Vp9,
80}
81
82impl Codec {
83 fn label(self) -> &'static str {
84 match self {
85 Codec::H264 => "H.264",
86 Codec::H265 => "H.265",
87 Codec::Av1 => "AV1",
88 Codec::Vp8 => "VP8",
89 Codec::Vp9 => "VP9",
90 }
91 }
92}
93
94#[derive(Clone, Debug)]
101pub(crate) struct Stream {
102 pub codec: Codec,
103 #[cfg_attr(
105 not(all(target_os = "linux", feature = "vaapi")),
106 allow(dead_code, reason = "only VA-API asks its driver by profile")
107 )]
108 pub h264_profile: Option<u8>,
109 #[cfg_attr(
115 not(all(target_os = "linux", feature = "nvidia")),
116 allow(dead_code, reason = "only NVDEC checks a size before the first keyframe")
117 )]
118 pub size: Option<Size>,
119 #[cfg_attr(
122 not(apple),
123 allow(dead_code, reason = "only VideoToolbox builds its session from them")
124 )]
125 pub parameter_sets: Option<Bytes>,
126}
127
128impl From<Codec> for Stream {
129 fn from(codec: Codec) -> Self {
131 Self {
132 codec,
133 h264_profile: None,
134 size: None,
135 parameter_sets: None,
136 }
137 }
138}
139
140pub(crate) trait Backend {
147 fn decode(&mut self, access_unit: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error>;
154
155 fn receive(&mut self) -> Result<Option<Frame>, Error>;
157
158 fn flush(&mut self) -> Result<(), Error>;
164
165 #[cfg(test)]
167 fn decode_all(&mut self, access_unit: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<Vec<Frame>, Error> {
168 self.decode(access_unit, timestamp, keyframe)?;
169 self.receive_all()
170 }
171
172 #[cfg(test)]
174 #[allow(dead_code, reason = "only the platform backends' tests use it")]
175 fn flush_all(&mut self) -> Result<Vec<Frame>, Error> {
176 self.flush()?;
177 self.receive_all()
178 }
179
180 #[cfg(test)]
182 fn receive_all(&mut self) -> Result<Vec<Frame>, Error> {
183 let mut frames = Vec::new();
184 while let Some(frame) = self.receive()? {
185 frames.push(frame);
186 }
187 Ok(frames)
188 }
189
190 fn name(&self) -> &str;
192}
193
194pub const NAMES: &[&str] = &[
199 "videotoolbox",
200 "mediafoundation",
201 "mediacodec",
202 "nvdec",
203 "vaapi",
204 "v4l2",
205 "openh264",
206 "vpx",
207];
208
209type Open = fn(&Stream, &Config) -> Result<Box<dyn Backend>, Error>;
212
213struct Candidate {
215 name: &'static str,
216 supports: fn(Codec) -> bool,
217 open: Open,
218 drives: Drives,
220}
221
222const HARDWARE: &[Candidate] = &[
225 #[cfg(apple)]
226 Candidate {
227 name: videotoolbox::NAME,
228 supports: |c| matches!(c, Codec::H264 | Codec::H265),
229 open: videotoolbox::VideoToolbox::open,
230 drives: Drives::Own,
231 },
232 #[cfg(target_os = "windows")]
233 Candidate {
234 name: mediafoundation::NAME,
235 supports: |c| matches!(c, Codec::H264 | Codec::H265),
236 open: mediafoundation::MediaFoundation::open,
237 drives: Drives::Own,
238 },
239 #[cfg(all(target_os = "android", feature = "mediacodec"))]
240 Candidate {
241 name: mediacodec::NAME,
242 supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Av1),
243 open: mediacodec::MediaCodec::open,
244 drives: Drives::Own,
245 },
246 #[cfg(all(target_os = "linux", feature = "nvidia"))]
247 Candidate {
248 name: nvdec::NAME,
249 supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Av1),
250 open: nvdec::Nvdec::open,
251 drives: Drives::Nvidia,
252 },
253 #[cfg(all(target_os = "linux", feature = "vaapi"))]
254 Candidate {
255 name: vaapi::NAME,
256 supports: |c| matches!(c, Codec::H264 | Codec::H265),
257 open: vaapi::Vaapi::open,
258 drives: Drives::Render,
259 },
260 #[cfg(all(target_os = "linux", feature = "v4l2"))]
264 Candidate {
265 name: v4l2::NAME,
266 supports: |c| matches!(c, Codec::H264),
267 open: v4l2::V4l2::open,
268 drives: Drives::Video,
269 },
270];
271
272const SOFTWARE: &[Candidate] = &[
273 #[cfg(feature = "openh264")]
274 Candidate {
275 name: openh264::NAME,
276 supports: |c| matches!(c, Codec::H264),
277 open: openh264::Openh264::open,
278 drives: Drives::Own,
279 },
280 #[cfg(feature = "vpx")]
281 Candidate {
282 name: vpx::NAME,
283 supports: |c| matches!(c, Codec::Vp8 | Codec::Vp9),
284 open: vpx::Vpx::open,
285 drives: Drives::Own,
286 },
287];
288
289#[cfg(test)]
293const NAMED_ONLY: &[Candidate] = &[
294 Candidate {
295 name: probe::NAME,
296 supports: |c| matches!(c, Codec::H264),
297 open: probe::Probe::open,
298 drives: Drives::Own,
299 },
300 Candidate {
301 name: probe::BUFFERED_NAME,
302 supports: |c| matches!(c, Codec::H264 | Codec::H265 | Codec::Vp9),
303 open: probe::Buffered::open,
304 drives: Drives::Own,
305 },
306 Candidate {
307 name: probe::FAILING_FLUSH_NAME,
308 supports: |c| matches!(c, Codec::H264),
309 open: probe::Buffered::open_failing_flush,
310 drives: Drives::Own,
311 },
312 Candidate {
313 name: probe::REORDER_NAME,
314 supports: |c| matches!(c, Codec::H264),
315 open: probe::Reorder::open,
316 drives: Drives::Own,
317 },
318 Candidate {
319 name: probe::HOLDING_NAME,
320 supports: |c| matches!(c, Codec::H264 | Codec::H265),
321 open: probe::Reorder::open_holding,
322 drives: Drives::Own,
323 },
324 Candidate {
325 name: probe::IMMEDIATE_NAME,
326 supports: |c| matches!(c, Codec::H264),
327 open: probe::Immediate::open,
328 drives: Drives::Own,
329 },
330 Candidate {
331 name: probe::NATIVE_NAME,
332 supports: |c| matches!(c, Codec::H264),
333 open: probe::Native::open,
334 drives: Drives::Own,
335 },
336 Candidate {
337 name: probe::REFUSING_NAME,
338 supports: |c| matches!(c, Codec::H264),
339 open: probe::Refusing::open,
340 drives: Drives::Own,
341 },
342 #[cfg(not(apple))]
343 Candidate {
344 name: probe::BLOCKING_FLUSH_NAME,
345 supports: |c| matches!(c, Codec::H264),
346 open: probe::BlockingFlush::open,
347 drives: Drives::Own,
348 },
349];
350
351#[cfg(not(test))]
352const NAMED_ONLY: &[Candidate] = &[];
353
354struct Attempt<'a> {
358 candidate: &'a Candidate,
359 hardware: bool,
360}
361
362impl<'a> Attempt<'a> {
363 fn hardware(candidate: &'a Candidate) -> Self {
364 Self {
365 candidate,
366 hardware: true,
367 }
368 }
369
370 fn software(candidate: &'a Candidate) -> Self {
371 Self {
372 candidate,
373 hardware: false,
374 }
375 }
376}
377
378pub(crate) fn open(stream: &Stream, config: &Config) -> Result<Box<dyn Backend>, Error> {
382 let attempts: Vec<Attempt> = match &config.backend {
383 Choice::Auto => HARDWARE
384 .iter()
385 .map(Attempt::hardware)
386 .chain(SOFTWARE.iter().map(Attempt::software))
387 .collect(),
388 Choice::Hardware => HARDWARE.iter().map(Attempt::hardware).collect(),
389 Choice::Software => SOFTWARE.iter().map(Attempt::software).collect(),
390 Choice::Named(name) => HARDWARE
391 .iter()
392 .map(Attempt::hardware)
393 .chain(SOFTWARE.iter().chain(NAMED_ONLY.iter()).map(Attempt::software))
394 .filter(|a| a.candidate.name == name)
395 .collect(),
396 };
397
398 select(stream, attempts, config)
399}
400
401fn select(stream: &Stream, attempts: Vec<Attempt>, config: &Config) -> Result<Box<dyn Backend>, Error> {
412 let codec = stream.codec;
413 let mut tried: Vec<String> = Vec::new();
417 let mut skipped = Vec::new();
418 let mut passed = Vec::new();
421 let mut faulted = false;
422
423 for attempt in attempts {
424 if !(attempt.candidate.supports)(codec) {
425 continue;
426 }
427
428 let name = attempt.candidate.name;
429 match config.device.takes(attempt.candidate.drives) {
430 Ok(true) => {}
431 Ok(false) => {
432 passed.push(format!("{name}: does not open {}", config.device));
433 continue;
434 }
435 Err(e) => {
438 tracing::debug!(decoder = name, error = %e, "decoder unavailable, trying next");
439 faulted = true;
440 tried.push(format!("{name}: {e}"));
441 if attempt.hardware {
442 skipped.push(format!("{name}: {e}"));
443 }
444 continue;
445 }
446 }
447
448 match (attempt.candidate.open)(stream, config) {
449 Ok(backend) => {
450 if !attempt.hardware && !(skipped.is_empty() && passed.is_empty()) {
455 let skipped: Vec<&str> = skipped.iter().chain(&passed).map(String::as_str).collect();
456 tracing::warn!(
457 decoder = name,
458 skipped = %skipped.join(", "),
459 "no hardware decoder available, falling back to software"
460 );
461 }
462 return Ok(backend);
463 }
464 Err(e) => {
465 tracing::debug!(decoder = name, error = %e, "decoder unavailable, trying next");
466 faulted |= !matches!(e, Error::UnsupportedCodec(_));
468 let reason = match e {
469 Error::UnsupportedCodec(reason) => reason,
470 e => e.to_string(),
471 };
472 tried.push(format!("{name}: {reason}"));
473 if attempt.hardware {
474 skipped.push(format!("{name}: {reason}"));
475 }
476 }
477 }
478 }
479
480 if tried.is_empty() && !passed.is_empty() {
486 return Err(Error::NoDecoder(passed.join(", ")));
487 }
488 tried.append(&mut passed);
489 if tried.is_empty() {
490 let available = available_names(codec);
491 return match &config.backend {
492 Choice::Named(name) => Err(Error::UnknownDecoder {
493 name: name.clone(),
494 codec,
495 available: available.join(", "),
496 }),
497 kind => Err(Error::UnsupportedCodec(format!(
498 "nothing compiled in for {} at {kind:?} (this build has: {})",
499 codec.label(),
500 available.join(", "),
501 ))),
502 };
503 }
504 if !faulted {
505 return Err(Error::UnsupportedCodec(format!(
506 "no decoder here takes this {} stream ({})",
507 codec.label(),
508 tried.join(", ")
509 )));
510 }
511 Err(Error::NoDecoder(tried.join(", ")))
513}
514
515fn available_names(codec: Codec) -> Vec<&'static str> {
520 HARDWARE
521 .iter()
522 .chain(SOFTWARE.iter())
523 .filter(|candidate| (candidate.supports)(codec))
524 .map(|candidate| candidate.name)
525 .collect()
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 struct Stub;
535
536 impl Stub {
537 fn open(_stream: &Stream, _config: &Config) -> Result<Box<dyn Backend>, Error> {
538 Ok(Box::new(Self))
539 }
540 }
541
542 impl Backend for Stub {
543 fn decode(&mut self, _access_unit: Bytes, _timestamp: Timestamp, _keyframe: bool) -> Result<(), Error> {
544 Ok(())
545 }
546
547 fn receive(&mut self) -> Result<Option<Frame>, Error> {
548 Ok(None)
549 }
550
551 fn flush(&mut self) -> Result<(), Error> {
552 Ok(())
553 }
554
555 fn name(&self) -> &str {
556 "stub"
557 }
558 }
559
560 const WORKING: Candidate = Candidate {
561 name: "stub",
562 supports: |c| matches!(c, Codec::H264),
563 open: Stub::open,
564 drives: Drives::Own,
565 };
566
567 const DRIVERLESS: Candidate = Candidate {
570 name: "driverless",
571 supports: |c| matches!(c, Codec::H264),
572 open: |_, _| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
573 drives: Drives::Own,
574 };
575
576 #[tracing_test::traced_test]
577 #[test]
578 fn falling_past_hardware_warns() {
579 let config = Config::new();
580 let attempts = vec![Attempt::hardware(&DRIVERLESS), Attempt::software(&WORKING)];
581 let backend = select(&Codec::H264.into(), attempts, &config).unwrap();
582 assert_eq!(backend.name(), "stub");
583
584 logs_assert(
585 |lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
586 Some(warning) if warning.contains("driverless") && warning.contains("driver libraries not found") => {
587 Ok(())
588 }
589 Some(warning) => Err(format!("warning does not name the refusal: {warning}")),
590 None => Err("no fallback warning".to_owned()),
591 },
592 );
593 }
594
595 #[tracing_test::traced_test]
598 #[test]
599 fn falling_past_hardware_for_another_device_warns() {
600 const RENDER: Candidate = Candidate {
601 name: "render",
602 open: |_, _| panic!("opened a render backend for a codec node"),
603 drives: Drives::Render,
604 ..WORKING
605 };
606
607 let mut config = Config::new();
608 config.device = crate::Device::Video("/dev/video11".into());
609 let attempts = vec![Attempt::hardware(&RENDER), Attempt::software(&WORKING)];
610 select(&Codec::H264.into(), attempts, &config).unwrap();
611 logs_assert(
612 |lines: &[&str]| match lines.iter().find(|line| line.contains("falling back to software")) {
613 Some(warning) if warning.contains("render: does not open codec node /dev/video11") => Ok(()),
614 Some(warning) => Err(format!("warning does not name the passed-over hardware: {warning}")),
615 None => Err("no fallback warning".to_owned()),
616 },
617 );
618 }
619
620 #[tracing_test::traced_test]
624 #[test]
625 fn hardware_that_cannot_decode_the_codec_is_not_a_fallback() {
626 const H265_ONLY: Candidate = Candidate {
627 name: "driverless",
628 supports: |c| matches!(c, Codec::H265),
629 open: |_, _| Err(Error::codec(anyhow::anyhow!("driver libraries not found"))),
630 drives: Drives::Own,
631 };
632
633 let attempts = vec![Attempt::hardware(&H265_ONLY), Attempt::software(&WORKING)];
634 select(&Codec::H264.into(), attempts, &Config::new()).unwrap();
635 assert!(!logs_contain("no hardware decoder available"));
636 }
637
638 #[cfg(target_os = "linux")]
642 #[test]
643 fn a_failed_driver_check_moves_on() {
644 const NVIDIA: Candidate = Candidate {
645 name: "nvidia",
646 supports: |c| matches!(c, Codec::H264),
647 open: |_, _| panic!("opened NVIDIA for an unreadable node"),
648 drives: Drives::Nvidia,
649 };
650 const RENDER: Candidate = Candidate {
651 drives: Drives::Render,
652 ..WORKING
653 };
654
655 let mut config = Config::new();
656 config.device = crate::Device::Render("/dev/dri/renderD199-absent".into());
657 let attempts = vec![Attempt::hardware(&NVIDIA), Attempt::hardware(&RENDER)];
658 assert_eq!(select(&Codec::H264.into(), attempts, &config).unwrap().name(), "stub");
659
660 match select(&Codec::H264.into(), vec![Attempt::hardware(&NVIDIA)], &config) {
661 Err(Error::NoDecoder(reason)) => assert!(
662 reason.contains("nvidia: ") && reason.contains("renderD199-absent"),
663 "{reason}"
664 ),
665 Err(other) => panic!("expected NoDecoder, got {other:?}"),
666 Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
667 }
668 }
669
670 #[test]
673 fn a_named_device_steers_selection_to_its_backend() {
674 const RENDER: Candidate = Candidate {
675 name: "render",
676 supports: |c| matches!(c, Codec::H264),
677 open: |_, _| panic!("opened a render backend for a codec node"),
678 drives: Drives::Render,
679 };
680 const VIDEO: Candidate = Candidate {
681 drives: Drives::Video,
682 ..WORKING
683 };
684
685 let mut config = Config::new();
686 config.device = crate::Device::Video("/dev/video10".into());
687 let attempts = vec![Attempt::hardware(&RENDER), Attempt::hardware(&VIDEO)];
688 assert_eq!(select(&Codec::H264.into(), attempts, &config).unwrap().name(), "stub");
689
690 let attempts = vec![Attempt::hardware(&RENDER)];
693 match select(&Codec::H264.into(), attempts, &config) {
694 Err(Error::NoDecoder(reason)) => assert!(reason.contains("/dev/video10"), "{reason}"),
695 Err(other) => panic!("expected NoDecoder, got {other:?}"),
696 Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
697 }
698 }
699
700 #[test]
703 fn the_named_devices_refusal_is_the_streams() {
704 const RENDER: Candidate = Candidate {
705 name: "render",
706 supports: |c| matches!(c, Codec::H264),
707 open: |_, _| Err(Error::UnsupportedCodec("too large".into())),
708 drives: Drives::Render,
709 };
710 const VIDEO: Candidate = Candidate {
711 drives: Drives::Video,
712 ..WORKING
713 };
714
715 let mut config = Config::new();
716 config.device = crate::Device::Render("/dev/dri/renderD129".into());
717 let attempts = vec![Attempt::hardware(&VIDEO), Attempt::hardware(&RENDER)];
718 assert!(matches!(
719 select(&Codec::H264.into(), attempts, &config),
720 Err(Error::UnsupportedCodec(_))
721 ));
722 }
723
724 #[test]
727 fn an_unknown_name_names_itself_and_the_alternatives() {
728 let mut config = Config::new();
729 config.backend = Choice::Named("vappi".to_owned());
730
731 match open(&Codec::H264.into(), &config) {
732 Err(Error::UnknownDecoder { name, codec, available }) => {
733 assert_eq!(name, "vappi");
734 assert_eq!(codec, crate::decode::Codec::H264);
735 #[cfg(feature = "openh264")]
736 assert!(available.contains(openh264::NAME), "nothing offered: {available}");
737 #[cfg(not(feature = "openh264"))]
738 assert!(!available.contains("openh264"), "disabled backend offered: {available}");
739 }
740 Err(other) => panic!("expected UnknownDecoder, got {other:?}"),
741 Ok(backend) => panic!("expected UnknownDecoder, opened {}", backend.name()),
742 }
743 }
744
745 #[cfg(not(feature = "openh264"))]
746 #[test]
747 fn disabled_software_backend_is_not_selected() {
748 let mut config = Config::new();
749 config.backend = Choice::Software;
750 assert!(matches!(
751 open(&Codec::H264.into(), &config),
752 Err(Error::UnsupportedCodec(_))
753 ));
754
755 config.backend = Choice::Named("openh264".to_owned());
756 assert!(matches!(
757 open(&Codec::H264.into(), &config),
758 Err(Error::UnknownDecoder { .. })
759 ));
760 }
761
762 #[test]
765 fn every_candidate_faulting_reports_why() {
766 let mut config = Config::new();
767 config.backend = Choice::Named("driverless".to_owned());
768
769 match select(&Codec::H264.into(), vec![Attempt::hardware(&DRIVERLESS)], &config) {
770 Err(Error::NoDecoder(tried)) => {
771 assert!(tried.contains("driverless"), "does not name the backend: {tried}");
772 assert!(
773 tried.contains("driver libraries not found"),
774 "does not carry the reason: {tried}"
775 );
776 }
777 Err(other) => panic!("expected NoDecoder, got {other:?}"),
778 Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
779 }
780 }
781
782 fn named(name: &str) -> &'static Candidate {
784 NAMED_ONLY
785 .iter()
786 .find(|candidate| candidate.name == name)
787 .expect("a test-only candidate")
788 }
789
790 #[test]
794 fn every_candidate_refusing_is_unsupported() {
795 let refusing = named(probe::REFUSING_NAME);
796 let attempts = vec![Attempt::hardware(refusing), Attempt::hardware(refusing)];
797 match select(&Codec::H264.into(), attempts, &Config::new()) {
798 Err(Error::UnsupportedCodec(reason)) => {
799 assert!(
800 reason.contains(probe::REFUSING_NAME),
801 "does not name the backend: {reason}"
802 );
803 assert!(reason.contains("cannot decode"), "does not carry the reason: {reason}");
804 }
805 Err(other) => panic!("expected UnsupportedCodec, got {other:?}"),
806 Ok(backend) => panic!("expected UnsupportedCodec, opened {}", backend.name()),
807 }
808 }
809
810 #[test]
813 fn a_fault_among_refusals_is_a_fault() {
814 let refusing = named(probe::REFUSING_NAME);
815 for attempts in [
816 vec![Attempt::hardware(refusing), Attempt::hardware(&DRIVERLESS)],
817 vec![Attempt::hardware(&DRIVERLESS), Attempt::software(refusing)],
818 ] {
819 match select(&Codec::H264.into(), attempts, &Config::new()) {
820 Err(Error::NoDecoder(tried)) => {
821 assert!(tried.contains(probe::REFUSING_NAME), "drops the refusal: {tried}");
822 assert!(tried.contains("driverless"), "drops the fault: {tried}");
823 }
824 Err(other) => panic!("expected NoDecoder, got {other:?}"),
825 Ok(backend) => panic!("expected NoDecoder, opened {}", backend.name()),
826 }
827 }
828 }
829
830 #[test]
833 fn a_refusal_falls_through_to_the_next_candidate() {
834 let attempts = vec![
835 Attempt::hardware(named(probe::REFUSING_NAME)),
836 Attempt::software(&WORKING),
837 ];
838 let backend = select(&Codec::H264.into(), attempts, &Config::new()).unwrap();
839 assert_eq!(backend.name(), "stub");
840 }
841
842 #[test]
844 fn every_compiled_backend_is_named_publicly() {
845 for candidate in HARDWARE.iter().chain(SOFTWARE.iter()) {
846 assert!(
847 NAMES.contains(&candidate.name),
848 "{} is compiled in but missing from NAMES",
849 candidate.name,
850 );
851 }
852 }
853}