Skip to main content

alpha2_host_core/
encode_watch.rs

1//! A heartbeat before each encoder and muxer call, for an outside stall watcher.
2
3thread_local! {
4    /// What this thread calls before each encoder and muxer call ([`watch_encode_calls`]).
5    static ENCODE_CALL_WATCH: std::cell::RefCell<Option<Box<dyn Fn()>>> =
6        const { std::cell::RefCell::new(None) };
7}
8
9/// Calls `beat` on this thread before every encoder and muxer call a sink
10/// makes, until the guard drops.
11///
12/// Some calls wait forever (`h264_vulkan` waits on fences with `UINT64_MAX`; `write(2)` to a stuck
13/// hard-mounted share retries forever) and cannot be interrupted, so the driving thread reports
14/// where it is and its owner decides when a call is stuck. The audio encoder's thread is covered by
15/// the call that waits on it.
16#[must_use = "the watch ends when the guard drops"]
17pub fn watch_encode_calls(beat: impl Fn() + 'static) -> EncodeCallWatch {
18    let previous = ENCODE_CALL_WATCH.with(|watch| watch.replace(Some(Box::new(beat))));
19    EncodeCallWatch {
20        previous,
21        thread: std::marker::PhantomData,
22    }
23}
24
25/// Ends a [`watch_encode_calls`] watch, restoring the one before it.
26pub struct EncodeCallWatch {
27    previous: Option<Box<dyn Fn()>>,
28    thread: std::marker::PhantomData<*const ()>,
29}
30
31impl Drop for EncodeCallWatch {
32    fn drop(&mut self) {
33        let previous = self.previous.take();
34        ENCODE_CALL_WATCH.with(|watch| {
35            watch.replace(previous);
36        });
37    }
38}
39
40/// Tells this thread's [`watch_encode_calls`] watch, if any, that an encoder or muxer call
41/// starts.
42pub fn beat_encode_call() {
43    ENCODE_CALL_WATCH.with(|watch| {
44        if let Some(beat) = watch.borrow().as_ref() {
45            beat();
46        }
47    });
48}