Skip to main content

alpha2_native/openh264/
library.rs

1//! Finding, verifying and loading the `OpenH264` library.
2//!
3//! alpha2 ships no H.264 encoder. The user downloads Cisco's binary on request
4//! (`npx @alpha2-sh/node install --openh264`, `python -m alpha2 install --openh264`) into the
5//! shared host cache; nothing downloads it implicitly.
6//!
7//! Lookup order:
8//! 1. `ALPHA2_OPENH264_LIBRARY`, a path whose SHA-256 must be Cisco's unless
9//!    `ALPHA2_OPENH264_UNVERIFIED=1`. A set path that fails is an error, not a fallthrough.
10//! 2. The shared cache, `<cache>/openh264-<version>-<target>/<library>`, hash-verified.
11//! 3. A system package (provider `system`): `libopenh264.so.8` via the Linux loader, or on macOS
12//!    only absolute Homebrew/`MacPorts` paths ([`MACOS_SYSTEM_CANDIDATES`]), since `dlopen` of a
13//!    leaf name there also searches the working directory. None on Windows.
14//!
15//! An unverified library must still report a supported API version. `ALPHA2_OPENH264=0` disables it
16//! all, as Cisco's licence requires.
17
18use std::fmt::Write as _;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, OnceLock};
21
22use sha2::{Digest, Sha256};
23
24use super::ffi;
25
26/// The `OpenH264` release `release/openh264/manifest.toml` pins (`version`).
27pub const OPENH264_VERSION: &str = "2.7.0";
28
29/// The text Cisco's licence requires wherever the user controls the codec (manifest `notice`).
30pub const OPENH264_NOTICE: &str = "OpenH264 Video Codec provided by Cisco Systems, Inc.";
31
32/// What a user runs to install Cisco's binary.
33pub const OPENH264_INSTALL_COMMAND: &str =
34    "python -m alpha2 install --openh264, or npx @alpha2-sh/node install --openh264";
35
36/// API versions (major, minor) the FFI is written against; v2.6.0 and v2.7.0 headers are identical
37/// and both are the `.8` ABI.
38const COMPATIBLE_API: &[(u32, u32)] = &[(2, 6), (2, 7)];
39
40/// A target's manifest entry: cached library name, SHA-256, and system loader names.
41#[derive(Clone, Copy)]
42pub(super) struct PinnedLibrary {
43    pub(super) target: &'static str,
44    pub(super) library: &'static str,
45    pub(super) sha256: &'static str,
46    pub(super) system_candidates: &'static [&'static str],
47}
48
49/// Where macOS packages put the `.8` library (Homebrew on Apple silicon and Intel,
50/// `MacPorts`). Absolute paths only.
51pub(crate) const MACOS_SYSTEM_CANDIDATES: &[&str] = &[
52    "/opt/homebrew/lib/libopenh264.8.dylib",
53    "/usr/local/lib/libopenh264.8.dylib",
54    "/opt/local/lib/libopenh264.8.dylib",
55];
56
57/// Every target of `release/openh264/manifest.toml`, in its order.
58pub(super) const PINS: [PinnedLibrary; 4] = [
59    PinnedLibrary {
60        target: "linux-x64",
61        library: "libopenh264-2.7.0-linux64.8.so",
62        sha256: "1522f873a482923c5ec018a4415e1866898197528828c50f90fd300c94620df3",
63        system_candidates: &["libopenh264.so.8"],
64    },
65    PinnedLibrary {
66        target: "linux-arm64",
67        library: "libopenh264-2.7.0-linux-arm64.8.so",
68        sha256: "9ac664b0154fd0868491c2a904397b8a05779874c0603b8b1f16ad15de1ffd82",
69        system_candidates: &["libopenh264.so.8"],
70    },
71    PinnedLibrary {
72        target: "macos-arm64",
73        library: "libopenh264-2.7.0-mac-arm64.dylib",
74        sha256: "2e1ae3cd10c08328ca03a1f304fd2a1a2a7e5658c6d5a8582101a963f7995ef0",
75        system_candidates: MACOS_SYSTEM_CANDIDATES,
76    },
77    PinnedLibrary {
78        target: "win-x64",
79        library: "openh264-2.7.0-win64.dll",
80        sha256: "0ef5e7f3b38753b15c13afa0418d4d7805fa228e6adfd3e425bbf758cff1c288",
81        system_candidates: &[],
82    },
83];
84
85#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
86const PINNED: Option<PinnedLibrary> = Some(PINS[0]);
87#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
88const PINNED: Option<PinnedLibrary> = Some(PINS[1]);
89#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
90const PINNED: Option<PinnedLibrary> = Some(PINS[2]);
91#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
92const PINNED: Option<PinnedLibrary> = Some(PINS[3]);
93#[cfg(not(any(
94    all(
95        target_os = "linux",
96        any(target_arch = "x86_64", target_arch = "aarch64")
97    ),
98    all(target_os = "macos", target_arch = "aarch64"),
99    all(target_os = "windows", target_arch = "x86_64"),
100)))]
101const PINNED: Option<PinnedLibrary> = None;
102
103/// Who provided the library that loaded.
104#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
105#[non_exhaustive]
106pub enum OpenH264Provider {
107    /// Cisco's binary, verified by its SHA-256.
108    Cisco,
109    /// A library the system loader found, or one named with verification off; version-checked only.
110    System,
111}
112
113impl OpenH264Provider {
114    /// Stable identifier for `capabilities` and the export result.
115    #[must_use]
116    pub const fn as_str(self) -> &'static str {
117        match self {
118            Self::Cisco => "cisco-openh264",
119            Self::System => "system",
120        }
121    }
122}
123
124/// An `OpenH264` library that loaded and passed its checks.
125pub struct OpenH264Library {
126    pub(crate) api: Arc<ffi::Api>,
127    provider: OpenH264Provider,
128    version: String,
129    path: String,
130}
131
132impl std::fmt::Debug for OpenH264Library {
133    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        formatter
135            .debug_struct("OpenH264Library")
136            .field("provider", &self.provider)
137            .field("version", &self.version)
138            .field("path", &self.path)
139            .finish_non_exhaustive()
140    }
141}
142
143impl OpenH264Library {
144    /// Who provided it.
145    #[must_use]
146    pub const fn provider(&self) -> OpenH264Provider {
147        self.provider
148    }
149
150    /// The version it reports, `major.minor.revision`.
151    #[must_use]
152    pub fn version(&self) -> &str {
153        &self.version
154    }
155
156    /// Where it was loaded from: a path, or the name given to the system loader.
157    #[must_use]
158    pub fn path(&self) -> &str {
159        &self.path
160    }
161}
162
163/// Whether `OpenH264` can encode in this process, and if not, why.
164#[derive(Clone, Debug)]
165#[non_exhaustive]
166pub enum OpenH264Status {
167    /// Loaded and checked.
168    Available(Arc<OpenH264Library>),
169    /// `ALPHA2_OPENH264=0`.
170    Disabled,
171    /// No library anywhere the host looks; the string says where it looked.
172    NotInstalled(String),
173    /// A library was found and refused: the reason names it and why.
174    Unusable(String),
175}
176
177impl OpenH264Status {
178    /// Stable identifier for `capabilities`.
179    #[must_use]
180    pub const fn as_str(&self) -> &'static str {
181        match self {
182            Self::Available(_) => "available",
183            Self::Disabled => "disabled",
184            Self::NotInstalled(_) => "not-installed",
185            Self::Unusable(_) => "unusable",
186        }
187    }
188
189    /// The library, when one loaded.
190    #[must_use]
191    pub fn library(&self) -> Option<&Arc<OpenH264Library>> {
192        match self {
193            Self::Available(library) => Some(library),
194            _ => None,
195        }
196    }
197
198    /// Why it cannot encode, or `None` when it can.
199    #[must_use]
200    pub fn reason(&self) -> Option<String> {
201        match self {
202            Self::Available(_) => None,
203            Self::Disabled => Some("ALPHA2_OPENH264=0 turned OpenH264 off".to_owned()),
204            Self::NotInstalled(reason) | Self::Unusable(reason) => Some(reason.clone()),
205        }
206    }
207
208    /// What the user can do about it, or `None` when it can encode or the user disabled it.
209    #[must_use]
210    pub fn remedy(&self) -> Option<String> {
211        match self {
212            Self::Available(_) | Self::Disabled => None,
213            Self::NotInstalled(_) | Self::Unusable(_) if PINNED.is_none() => None,
214            Self::NotInstalled(_) => Some(format!(
215                "install Cisco's OpenH264 binary: {OPENH264_INSTALL_COMMAND}"
216            )),
217            Self::Unusable(_) => Some(format!(
218                "reinstall Cisco's OpenH264 binary with --force ({OPENH264_INSTALL_COMMAND} \
219                 --force), or fix ALPHA2_OPENH264_LIBRARY"
220            )),
221        }
222    }
223}
224
225/// `OpenH264` for this process, looked up once on first use.
226#[must_use]
227pub fn openh264_status() -> &'static OpenH264Status {
228    static STATUS: OnceLock<OpenH264Status> = OnceLock::new();
229    STATUS.get_or_init(|| {
230        let status = resolve(&Lookup::from_environment());
231        if let OpenH264Status::Unusable(reason) = &status {
232            alpha2_os::diagnostic!("alpha2 native: OpenH264 is not used: {reason}");
233        }
234        status
235    })
236}
237
238/// Everything a lookup reads from the environment, so tests can supply their own.
239pub(crate) struct Lookup {
240    /// `ALPHA2_OPENH264`.
241    pub(crate) enabled: Option<String>,
242    /// `ALPHA2_OPENH264_LIBRARY`.
243    pub(crate) library: Option<PathBuf>,
244    /// `ALPHA2_OPENH264_UNVERIFIED`.
245    pub(crate) unverified: bool,
246    /// The host cache directory, when one can be named.
247    pub(crate) cache: Option<PathBuf>,
248    /// System libraries to try in order: leaf names go to the loader, absolute paths
249    /// load only if they are files.
250    pub(crate) system: &'static [&'static str],
251}
252
253/// This target's system libraries ([`PinnedLibrary::system_candidates`]).
254pub(crate) fn system_candidates() -> &'static [&'static str] {
255    PINNED
256        .as_ref()
257        .map_or(&[], |pinned| pinned.system_candidates)
258}
259
260impl Lookup {
261    fn from_environment() -> Self {
262        let set = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
263        Self {
264            enabled: set("ALPHA2_OPENH264").map(|value| value.to_string_lossy().into_owned()),
265            library: set("ALPHA2_OPENH264_LIBRARY").map(PathBuf::from),
266            unverified: set("ALPHA2_OPENH264_UNVERIFIED").is_some_and(|value| value == "1"),
267            cache: alpha2_os::host_cache_directory(),
268            system: system_candidates(),
269        }
270    }
271}
272
273/// Where the install puts this target's library under `cache`.
274pub(crate) fn cached_library_path(cache: &Path) -> Option<PathBuf> {
275    let pinned = PINNED.as_ref()?;
276    Some(
277        cache
278            .join(format!("openh264-{OPENH264_VERSION}-{}", pinned.target))
279            .join(pinned.library),
280    )
281}
282
283/// Looks for `OpenH264` as [the module](self) describes.
284pub(crate) fn resolve(lookup: &Lookup) -> OpenH264Status {
285    if lookup.enabled.as_deref() == Some("0") {
286        return OpenH264Status::Disabled;
287    }
288    if let Some(path) = &lookup.library {
289        return if lookup.unverified {
290            load(path, OpenH264Provider::System, None)
291        } else {
292            match PINNED.as_ref() {
293                Some(pinned) => load(path, OpenH264Provider::Cisco, Some(pinned.sha256)),
294                None => OpenH264Status::Unusable(format!(
295                    "ALPHA2_OPENH264_LIBRARY={}: Cisco publishes no binary alpha2 knows the \
296                     SHA-256 of for this platform; set ALPHA2_OPENH264_UNVERIFIED=1 to load it \
297                     anyway",
298                    path.display()
299                )),
300            }
301        };
302    }
303    let mut looked = Vec::new();
304    if let (Some(cache), Some(pinned)) = (&lookup.cache, PINNED.as_ref())
305        && let Some(path) = cached_library_path(cache)
306    {
307        if path.is_file() {
308            return load(&path, OpenH264Provider::Cisco, Some(pinned.sha256));
309        }
310        looked.push(path.display().to_string());
311    }
312    for name in lookup.system {
313        let path = Path::new(name);
314        let shown = if path.is_absolute() {
315            (*name).to_owned()
316        } else {
317            format!("{name} on the loader path")
318        };
319        if path.is_absolute() && !path.is_file() {
320            looked.push(shown);
321            continue;
322        }
323        match ffi::Api::load(path) {
324            Ok(api) => return checked(api, OpenH264Provider::System, name),
325            Err(ffi::LoadError::Open(_)) => looked.push(shown),
326            Err(error) => return OpenH264Status::Unusable(refusal(name, &error)),
327        }
328    }
329    OpenH264Status::NotInstalled(if PINNED.is_none() {
330        "Cisco publishes no OpenH264 binary for this platform".to_owned()
331    } else if looked.is_empty() {
332        "no OpenH264 library was found".to_owned()
333    } else {
334        format!("no OpenH264 library at {}", looked.join(" or "))
335    })
336}
337
338/// Loads `path` after checking its SHA-256 against `sha256`, when given.
339fn load(path: &Path, provider: OpenH264Provider, sha256: Option<&str>) -> OpenH264Status {
340    let shown = path.display().to_string();
341    if let Some(expected) = sha256 {
342        let actual = match file_sha256(path) {
343            Ok(actual) => actual,
344            Err(error) => {
345                return OpenH264Status::Unusable(format!("{shown} cannot be read: {error}"));
346            }
347        };
348        if actual != expected {
349            return OpenH264Status::Unusable(format!(
350                "{shown} is not Cisco's OpenH264 {OPENH264_VERSION} binary for this platform \
351                 (SHA-256 {actual}, expected {expected})"
352            ));
353        }
354    }
355    match ffi::Api::load(path) {
356        Ok(api) => checked(api, provider, &shown),
357        Err(error) => OpenH264Status::Unusable(refusal(&shown, &error) + &quarantine_note(path)),
358    }
359}
360
361/// For a quarantined library on macOS (Gatekeeper refuses unnotarized ones), how to remove the
362/// attribute. Empty elsewhere.
363fn quarantine_note(path: &Path) -> String {
364    if !alpha2_os::quarantined(path) {
365        return String::new();
366    }
367    format!(
368        "; macOS quarantined it (a browser download), and Gatekeeper refuses an unnotarized \
369         library: remove the attribute (xattr -d com.apple.quarantine '{}') or install it with \
370         python -m alpha2 install --openh264 or npx @alpha2-sh/node install --openh264",
371        path.display()
372    )
373}
374
375/// Accepts a loaded library whose API version the FFI was written against.
376fn checked(api: ffi::Api, provider: OpenH264Provider, shown: &str) -> OpenH264Status {
377    let version = api.version();
378    if !COMPATIBLE_API.contains(&(version.major, version.minor)) {
379        return OpenH264Status::Unusable(format!(
380            "{shown} is OpenH264 {}.{}.{}, and alpha2 is built against the 2.6/2.7 API",
381            version.major, version.minor, version.revision
382        ));
383    }
384    OpenH264Status::Available(Arc::new(OpenH264Library {
385        api: Arc::new(api),
386        provider,
387        version: format!("{}.{}.{}", version.major, version.minor, version.revision),
388        path: shown.to_owned(),
389    }))
390}
391
392fn refusal(shown: &str, error: &ffi::LoadError) -> String {
393    match error {
394        ffi::LoadError::Open(message) => {
395            format!("{shown} was found but is not loadable: {message}")
396        }
397        ffi::LoadError::Symbol(symbol, message) => {
398            format!("{shown} is not an OpenH264 encoder library (no {symbol}: {message})")
399        }
400    }
401}
402
403/// The SHA-256 of the file at `path`, in lower-case hex.
404pub(crate) fn file_sha256(path: &Path) -> std::io::Result<String> {
405    use std::io::Read;
406    let mut file = std::fs::File::open(path)?;
407    let mut hasher = Sha256::new();
408    let mut buffer = vec![0_u8; 1 << 16];
409    loop {
410        let read = file.read(&mut buffer)?;
411        if read == 0 {
412            break;
413        }
414        hasher.update(&buffer[..read]);
415    }
416    Ok(hasher
417        .finalize()
418        .iter()
419        .fold(String::with_capacity(64), |mut hex, byte| {
420            let _ = write!(hex, "{byte:02x}");
421            hex
422        }))
423}