Skip to main content

alpha2_host_core/
probe_cache.rs

1//! What this process learned from encoder probe opens, so failures that cannot change are asked
2//! once.
3
4use std::collections::HashMap;
5use std::sync::Mutex;
6
7use alpha2_media::{EncoderRefusal, OpenFailureKind};
8
9/// A probe answer that cannot change while the process runs.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum ProbeVerdict {
12    /// The encoder encoded a frame.
13    Runs,
14    /// The encoder failed in a way asking again would repeat, with the failure kind and reason.
15    Refused(OpenFailureKind, String),
16}
17
18/// Unclassified probe failures in a row after which the last one is kept as the verdict.
19///
20/// Some transforms leak resources on every failed open, so a long-lived host must stop asking.
21pub const UNCLASSIFIED_FAILURES_KEPT: u8 = 3;
22
23/// What this process knows about one encoder and way it runs.
24#[derive(Debug, Default)]
25pub struct ProbeEntry {
26    /// The kept verdict, if any.
27    verdict: Option<ProbeVerdict>,
28    unclassified_failures: u8,
29}
30
31/// The probe outcomes kept for this process, by encoder name and way it runs.
32pub type ProbeCache = Mutex<HashMap<(String, bool), ProbeEntry>>;
33
34/// The cached verdict for `name` and mode, else `probe`'s answer (cached when it cannot change, or
35/// after [`UNCLASSIFIED_FAILURES_KEPT`] unclassified failures in a row); `None` when nothing is
36/// cached and there is no `probe`.
37///
38/// The cache lock is held across the probe, so two exports asking at once probe once.
39pub fn cached_probe(
40    cache: &ProbeCache,
41    name: &str,
42    on_hardware: bool,
43    probe: Option<impl FnOnce() -> Result<(), (OpenFailureKind, String)>>,
44) -> Option<Result<(), EncoderRefusal>> {
45    let refusal = |kind, reason| EncoderRefusal {
46        encoder: name.to_owned(),
47        hardware_accelerated: on_hardware,
48        kind,
49        reason,
50    };
51    let mut entries = cache
52        .lock()
53        .unwrap_or_else(std::sync::PoisonError::into_inner);
54    let entry = entries.entry((name.to_owned(), on_hardware)).or_default();
55    match &entry.verdict {
56        Some(ProbeVerdict::Runs) => return Some(Ok(())),
57        Some(ProbeVerdict::Refused(kind, reason)) => {
58            return Some(Err(refusal(*kind, reason.clone())));
59        }
60        None => {}
61    }
62    let outcome = probe?();
63    entry.unclassified_failures = match &outcome {
64        Err((OpenFailureKind::Unknown, _)) => entry.unclassified_failures.saturating_add(1),
65        _ => 0,
66    };
67    entry.verdict = match &outcome {
68        Ok(()) => Some(ProbeVerdict::Runs),
69        Err((kind @ (OpenFailureKind::Absent | OpenFailureKind::Unsuitable), reason)) => {
70            Some(ProbeVerdict::Refused(*kind, reason.clone()))
71        }
72        Err((OpenFailureKind::Unknown, reason))
73            if entry.unclassified_failures >= UNCLASSIFIED_FAILURES_KEPT =>
74        {
75            Some(ProbeVerdict::Refused(
76                OpenFailureKind::Unknown,
77                reason.clone(),
78            ))
79        }
80        Err(_) => None,
81    };
82    if let Err((kind, error)) = &outcome {
83        alpha2_os::diagnostic!(
84            "alpha2 native: video encoder {name} {} is registered but did not encode a frame on \
85             this machine, so it is not offered that way ({}{}): {error}",
86            mode_label(on_hardware),
87            kind.as_str(),
88            if entry.verdict.is_some() {
89                ""
90            } else {
91                "; asked again at the next export"
92            }
93        );
94    }
95    Some(outcome.map_err(|(kind, reason)| refusal(kind, reason)))
96}
97
98/// How long a hardware encoder probe answer is kept for this process.
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub enum Keep {
101    /// Until the process exits. For a success, a refusal by the device, or a timed-out probe, whose
102    /// thread or child may never return.
103    Process,
104    /// Not kept, so a busy, unstarted or lost probe is asked again next time.
105    Never,
106    /// Kept after [`UNCLASSIFIED_FAILURES_KEPT`] unclassified failures in a row.
107    AfterRepeats,
108}
109
110impl Keep {
111    /// The rule for a classified open failure, or for success when `kind` is `None`.
112    #[must_use]
113    pub const fn of_failure(kind: Option<OpenFailureKind>) -> Self {
114        match kind {
115            None | Some(OpenFailureKind::Absent | OpenFailureKind::Unsuitable) => Self::Process,
116            Some(OpenFailureKind::Busy) => Self::Never,
117            Some(_) => Self::AfterRepeats,
118        }
119    }
120}
121
122/// How a probe that runs in a child process ended.
123#[derive(Clone, Copy, Debug, Eq, PartialEq)]
124pub enum ChildProbeEnd {
125    /// The child answered; `busy` when the answer says the device was busy.
126    Answered {
127        /// The device was busy.
128        busy: bool,
129    },
130    /// The child did not start.
131    NotStarted,
132    /// Waiting for the child failed.
133    Lost,
134    /// The child did not finish in time and was killed.
135    TimedOut,
136    /// The child crashed or exited without an answer.
137    NoAnswer,
138}
139
140impl ChildProbeEnd {
141    /// How long the answer of a probe that ended this way is kept.
142    #[must_use]
143    pub const fn keep(self) -> Keep {
144        match self {
145            Self::Answered { busy: false } | Self::TimedOut => Keep::Process,
146            Self::Answered { busy: true } | Self::NotStarted | Self::Lost => Keep::Never,
147            Self::NoAnswer => Keep::AfterRepeats,
148        }
149    }
150}
151
152/// Probe answers by key, kept under [`Keep`]; the first kept answer for a key stays.
153#[derive(Debug)]
154pub struct KeptAnswers<K, V> {
155    entries: Vec<(K, Option<V>, u8)>,
156}
157
158impl<K, V> Default for KeptAnswers<K, V> {
159    fn default() -> Self {
160        Self::new()
161    }
162}
163
164impl<K, V> KeptAnswers<K, V> {
165    /// No answers.
166    #[must_use]
167    pub const fn new() -> Self {
168        Self {
169            entries: Vec::new(),
170        }
171    }
172}
173
174impl<K: PartialEq, V: Clone> KeptAnswers<K, V> {
175    /// The kept answer for `key`.
176    #[must_use]
177    pub fn get(&self, key: &K) -> Option<V> {
178        self.entries
179            .iter()
180            .find(|(known, _, _)| known == key)
181            .and_then(|(_, answer, _)| answer.clone())
182    }
183
184    /// Records `answer` for `key` as `keep` says, unless an answer is already kept.
185    pub fn record(&mut self, key: K, answer: &V, keep: Keep) {
186        let index = if let Some(index) = self.entries.iter().position(|(known, _, _)| *known == key)
187        {
188            index
189        } else {
190            self.entries.push((key, None, 0));
191            self.entries.len() - 1
192        };
193        let (_, kept, repeats) = &mut self.entries[index];
194        if kept.is_some() {
195            return;
196        }
197        match keep {
198            Keep::Process => *kept = Some(answer.clone()),
199            Keep::Never => *repeats = 0,
200            Keep::AfterRepeats => {
201                *repeats = repeats.saturating_add(1);
202                if *repeats >= UNCLASSIFIED_FAILURES_KEPT {
203                    *kept = Some(answer.clone());
204                }
205            }
206        }
207    }
208}
209
210/// The kept answer of `answers`, else `probe` on its own thread, bounded by `timeout` and kept as
211/// the [`Keep`] it returns says.
212///
213/// A probe still running at `timeout` is kept as a refusal for the process, so at most one probe
214/// thread is ever stuck. The lock is held across the wait, so concurrent callers probe once.
215///
216/// # Errors
217/// The probe's refusal, or why it did not answer.
218pub fn bounded_kept_probe<V: Clone + Send + 'static>(
219    answers: &Mutex<KeptAnswers<(), Result<V, String>>>,
220    name: &str,
221    timeout: std::time::Duration,
222    probe: impl FnOnce() -> (Result<V, String>, Keep) + Send + 'static,
223) -> Result<V, String> {
224    let mut answers = answers
225        .lock()
226        .unwrap_or_else(std::sync::PoisonError::into_inner);
227    if let Some(answer) = answers.get(&()) {
228        return answer;
229    }
230    let (sender, receiver) = std::sync::mpsc::channel();
231    let spawned = std::thread::Builder::new()
232        .name(format!("alpha2 {name} probe"))
233        .spawn(move || {
234            let _ = sender.send(probe());
235        });
236    let (answer, keep) = match spawned {
237        Err(error) => (
238            Err(format!("{name}: the probe did not start: {error}")),
239            Keep::Never,
240        ),
241        Ok(_) => match receiver.recv_timeout(timeout) {
242            Ok(answered) => answered,
243            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => (
244                Err(format!(
245                    "{name}'s probe session did not finish within {timeout:?}, so the path is \
246                     off for this process"
247                )),
248                Keep::Process,
249            ),
250            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => (
251                Err(format!("{name}'s probe ended without an answer")),
252                Keep::AfterRepeats,
253            ),
254        },
255    };
256    answers.record((), &answer, keep);
257    answer
258}
259
260/// How an encoder runs, for diagnostics.
261#[must_use]
262pub const fn mode_label(on_hardware: bool) -> &'static str {
263    if on_hardware { "on GPU" } else { "on CPU" }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn a_busy_or_lost_probe_is_asked_again_and_a_timeout_or_refusal_is_kept() {
272        let mut answers = KeptAnswers::new();
273        answers.record(
274            "h264",
275            &"busy",
276            ChildProbeEnd::Answered { busy: true }.keep(),
277        );
278        assert_eq!(answers.get(&"h264"), None);
279        answers.record("h264", &"not started", ChildProbeEnd::NotStarted.keep());
280        answers.record("h264", &"lost", ChildProbeEnd::Lost.keep());
281        assert_eq!(answers.get(&"h264"), None);
282        answers.record("h264", &"timed out", ChildProbeEnd::TimedOut.keep());
283        assert_eq!(answers.get(&"h264"), Some("timed out"));
284        answers.record(
285            "h264",
286            &"later",
287            ChildProbeEnd::Answered { busy: false }.keep(),
288        );
289        assert_eq!(
290            answers.get(&"h264"),
291            Some("timed out"),
292            "the first kept answer stays"
293        );
294
295        answers.record(
296            "hevc",
297            &"refused",
298            ChildProbeEnd::Answered { busy: false }.keep(),
299        );
300        assert_eq!(answers.get(&"hevc"), Some("refused"));
301
302        for crash in 1..=UNCLASSIFIED_FAILURES_KEPT {
303            assert_eq!(answers.get(&"av1"), None, "after {} crashes", crash - 1);
304            answers.record("av1", &"crashed", ChildProbeEnd::NoAnswer.keep());
305        }
306        assert_eq!(answers.get(&"av1"), Some("crashed"));
307        assert_eq!(Keep::of_failure(None), Keep::Process);
308        assert_eq!(
309            Keep::of_failure(Some(OpenFailureKind::Unsuitable)),
310            Keep::Process
311        );
312        assert_eq!(Keep::of_failure(Some(OpenFailureKind::Busy)), Keep::Never);
313        assert_eq!(
314            Keep::of_failure(Some(OpenFailureKind::Unknown)),
315            Keep::AfterRepeats
316        );
317    }
318
319    #[test]
320    fn a_probe_that_outlives_its_timeout_runs_once_for_every_later_question() {
321        let answers = Mutex::new(KeptAnswers::new());
322        let runs = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
323        for _ in 0..3 {
324            let counted = std::sync::Arc::clone(&runs);
325            let answer = bounded_kept_probe(
326                &answers,
327                "h264_videotoolbox",
328                std::time::Duration::from_millis(20),
329                move || {
330                    counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
331                    std::thread::sleep(std::time::Duration::from_millis(500));
332                    (Ok(()), Keep::Process)
333                },
334            );
335            assert!(answer.expect_err("timed out").contains("did not finish"));
336        }
337        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
338
339        let busy = Mutex::new(KeptAnswers::new());
340        let runs = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
341        for _ in 0..2 {
342            let counted = std::sync::Arc::clone(&runs);
343            let _ = bounded_kept_probe(
344                &busy,
345                "h264_videotoolbox",
346                std::time::Duration::from_secs(5),
347                move || {
348                    counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
349                    (Err::<(), _>("busy".to_owned()), Keep::Never)
350                },
351            );
352        }
353        assert_eq!(
354            runs.load(std::sync::atomic::Ordering::SeqCst),
355            2,
356            "busy is asked again"
357        );
358    }
359
360    #[test]
361    fn unclassified_probe_failures_are_kept_after_a_run_of_them() {
362        let cache = ProbeCache::default();
363        let probes = std::cell::Cell::new(0);
364        let ask = |kind| {
365            cached_probe(
366                &cache,
367                "hevc_mf",
368                false,
369                Some(|| {
370                    probes.set(probes.get() + 1);
371                    Err((kind, format!("failure {}", probes.get())))
372                }),
373            )
374        };
375        // A busy answer between unclassified ones restarts the run.
376        ask(OpenFailureKind::Unknown);
377        ask(OpenFailureKind::Busy);
378        for _ in 0..UNCLASSIFIED_FAILURES_KEPT {
379            ask(OpenFailureKind::Unknown);
380        }
381        let asked = probes.get();
382        assert_eq!(asked, usize::from(UNCLASSIFIED_FAILURES_KEPT) + 2);
383        let kept = ask(OpenFailureKind::Unknown);
384        assert_eq!(probes.get(), asked, "probed after the run was kept");
385        let Some(Err(refusal)) = kept else {
386            panic!("{kept:?}");
387        };
388        assert_eq!(refusal.kind, OpenFailureKind::Unknown);
389        assert_eq!(refusal.reason, format!("failure {asked}"));
390    }
391}