1use std::collections::HashMap;
5use std::sync::Mutex;
6
7use alpha2_media::{EncoderRefusal, OpenFailureKind};
8
9#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum ProbeVerdict {
12 Runs,
14 Refused(OpenFailureKind, String),
16}
17
18pub const UNCLASSIFIED_FAILURES_KEPT: u8 = 3;
22
23#[derive(Debug, Default)]
25pub struct ProbeEntry {
26 verdict: Option<ProbeVerdict>,
28 unclassified_failures: u8,
29}
30
31pub type ProbeCache = Mutex<HashMap<(String, bool), ProbeEntry>>;
33
34pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub enum Keep {
101 Process,
104 Never,
106 AfterRepeats,
108}
109
110impl Keep {
111 #[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
124pub enum ChildProbeEnd {
125 Answered {
127 busy: bool,
129 },
130 NotStarted,
132 Lost,
134 TimedOut,
136 NoAnswer,
138}
139
140impl ChildProbeEnd {
141 #[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#[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 #[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 #[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 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
210pub 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#[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 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}