Skip to main content

moq_ext_sources/
backend.rs

1//! A choice of video encoder or decoder backend, as a flag or a config file names it.
2//!
3//! A choice is a strategy (`auto`, `hardware`, `software`) or one backend by
4//! name, from moq-video's [`encode::NAMES`] or [`decode::NAMES`]. An unknown
5//! name fails to parse. A known name this build lacks, such as `vaapi`
6//! without moq-video's `vaapi` feature, fails when the encoder or decoder
7//! opens.
8
9use crate::video::{decode, encode};
10
11/// A choice of encoder or decoder backend: a strategy, or one backend by name.
12///
13/// Converts into moq-video's [`encode::Backend`] and [`decode::Backend`]. It
14/// displays as the name it parses from.
15///
16/// # Examples
17///
18/// ```
19/// use moq_ext_sources::Backend;
20///
21/// assert_eq!(Backend::parse_encoder("hw"), Ok(Backend::Hardware));
22/// let backend: moq_video::encode::Backend = Backend::Software.into();
23/// assert_eq!(backend, moq_video::encode::Backend::Software);
24/// ```
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, derive_more::Display)]
26#[display("{}", self.name())]
27pub enum Backend {
28    /// Tries the hardware backends in turn, then software.
29    #[default]
30    Auto,
31    /// Hardware only, with no fallback to software.
32    Hardware,
33    /// Software only.
34    Software,
35    /// Only the backend of this name, one of moq-video's backend names.
36    Named(&'static str),
37}
38
39/// An error from parsing a backend name that is no strategy and no known backend.
40#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
41#[display("unknown backend '{_0}': expected auto, hardware, software, or one of [{}]", _1.join(", "))]
42pub struct UnknownBackend(String, &'static [&'static str]);
43
44impl std::error::Error for UnknownBackend {}
45
46impl Backend {
47    /// Returns every encoder choice: the strategies, then each encoder backend by name.
48    pub fn encoders() -> impl Iterator<Item = Self> {
49        Self::choices(encode::NAMES)
50    }
51
52    /// Returns every decoder choice: the strategies, then each decoder backend by name.
53    pub fn decoders() -> impl Iterator<Item = Self> {
54        Self::choices(decode::NAMES)
55    }
56
57    /// Parses an encoder choice, ignoring case.
58    ///
59    /// Takes `auto`, `hardware` or `hw`, `software` or `sw`, or a name from
60    /// [`encode::NAMES`].
61    ///
62    /// # Errors
63    ///
64    /// Fails for any other value, with a message that lists the names.
65    pub fn parse_encoder(value: &str) -> Result<Self, UnknownBackend> {
66        Self::parse(value, encode::NAMES)
67    }
68
69    /// Parses a decoder choice, ignoring case.
70    ///
71    /// Takes the strategies as [`parse_encoder`](Self::parse_encoder) does, or
72    /// a name from [`decode::NAMES`].
73    ///
74    /// # Errors
75    ///
76    /// Fails for any other value, with a message that lists the names.
77    pub fn parse_decoder(value: &str) -> Result<Self, UnknownBackend> {
78        Self::parse(value, decode::NAMES)
79    }
80
81    /// Returns the name the choice parses from and displays as.
82    #[must_use]
83    pub fn name(self) -> &'static str {
84        match self {
85            Self::Auto => "auto",
86            Self::Hardware => "hardware",
87            Self::Software => "software",
88            Self::Named(name) => name,
89        }
90    }
91
92    /// Returns the short alias the choice also parses from, such as `hw`.
93    #[must_use]
94    pub fn alias(self) -> Option<&'static str> {
95        match self {
96            Self::Hardware => Some("hw"),
97            Self::Software => Some("sw"),
98            Self::Auto | Self::Named(_) => None,
99        }
100    }
101
102    /// Returns the strategies followed by one choice per name in `names`.
103    fn choices(names: &'static [&'static str]) -> impl Iterator<Item = Self> {
104        [Self::Auto, Self::Hardware, Self::Software]
105            .into_iter()
106            .chain(names.iter().map(|name| Self::Named(name)))
107    }
108
109    /// Parses a strategy, its short alias, or a name in `names`, ignoring case.
110    fn parse(value: &str, names: &'static [&'static str]) -> Result<Self, UnknownBackend> {
111        match value.to_lowercase().as_str() {
112            "auto" => Ok(Self::Auto),
113            "hardware" | "hw" => Ok(Self::Hardware),
114            "software" | "sw" => Ok(Self::Software),
115            other => names
116                .iter()
117                .find(|name| **name == other)
118                .map(|name| Self::Named(name))
119                .ok_or_else(|| UnknownBackend(value.to_string(), names)),
120        }
121    }
122}
123
124impl From<Backend> for encode::Backend {
125    fn from(backend: Backend) -> Self {
126        match backend {
127            Backend::Auto => Self::Auto,
128            Backend::Hardware => Self::Hardware,
129            Backend::Software => Self::Software,
130            Backend::Named(name) => Self::Named(name.to_string()),
131        }
132    }
133}
134
135impl From<Backend> for decode::Backend {
136    fn from(backend: Backend) -> Self {
137        match backend {
138            Backend::Auto => Self::Auto,
139            Backend::Hardware => Self::Hardware,
140            Backend::Software => Self::Software,
141            Backend::Named(name) => Self::Named(name.to_string()),
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn strategies_aliases_and_names_parse() {
152        assert_eq!(Backend::parse_encoder("HW"), Ok(Backend::Hardware));
153        assert_eq!(Backend::parse_decoder("sw"), Ok(Backend::Software));
154        assert_eq!(Backend::parse_decoder("nvdec"), Ok(Backend::Named("nvdec")));
155        assert_eq!(
156            encode::Backend::from(Backend::Named("vaapi")),
157            encode::Backend::Named("vaapi".to_string())
158        );
159    }
160
161    /// An encoder name is no decoder, and the error lists what would parse.
162    #[test]
163    fn a_name_of_the_other_kind_is_rejected() {
164        assert!(Backend::parse_encoder("nvdec").is_err());
165        assert!(Backend::parse_decoder("nvenc").is_err());
166        let err = Backend::parse_encoder("x264").unwrap_err();
167        assert!(err.to_string().contains("openh264"), "{err}");
168    }
169
170    #[test]
171    fn every_choice_parses_back_from_its_name() {
172        for choice in Backend::encoders() {
173            assert_eq!(Backend::parse_encoder(&choice.to_string()), Ok(choice));
174        }
175        for choice in Backend::decoders() {
176            assert_eq!(Backend::parse_decoder(&choice.to_string()), Ok(choice));
177            if let Some(alias) = choice.alias() {
178                assert_eq!(Backend::parse_decoder(alias), Ok(choice));
179            }
180        }
181    }
182}