Skip to main content

libobs_wrapper\signals/
mod.rs

1//! Per-object OBS signal subscriptions.
2//!
3//! Signal state used to live in process-global maps keyed by native pointer addresses.
4//! Besides unnecessary global locking, that let callback-only raw pointers escape
5//! through async channels.  A signal manager now owns its own hubs and passes stable
6//! hub addresses directly to libobs as callback data.
7
8mod handler;
9mod traits;
10
11pub use traits::*;
12
13use crossbeam_channel::{
14    bounded, Receiver, RecvError, RecvTimeoutError, Sender, TryRecvError, TrySendError,
15};
16use std::{sync::Mutex, time::Duration};
17
18const SIGNAL_QUEUE_CAPACITY: usize = 32;
19
20/// Opaque identity of an object mentioned by an OBS callback.
21///
22/// This is deliberately not a raw pointer and cannot be dereferenced. Callback data is
23/// often borrowed only for the duration of the C callback; exposing that pointer as a
24/// sendable Rust value allowed use-after-free in otherwise safe code.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub struct SignalObjectId(usize);
27
28impl SignalObjectId {
29    /// Construct an opaque callback identity from a callback-borrowed native pointer.
30    ///
31    /// # Safety
32    /// `ptr` must be a pointer supplied by libobs for the current callback. The returned
33    /// identity is never dereferenceable and does not extend the native object's lifetime.
34    #[doc(hidden)]
35    pub unsafe fn from_raw<T>(ptr: *mut T) -> Self {
36        Self(ptr as usize)
37    }
38
39    pub fn is_null(self) -> bool {
40        self.0 == 0
41    }
42}
43
44/// Synchronous receiver for an OBS signal subscription.
45///
46/// Each subscriber has a bounded queue. If it falls behind, new callback events are
47/// dropped for that subscriber rather than blocking the OBS callback thread.
48#[derive(Debug)]
49pub struct SignalReceiver<T> {
50    receiver: Receiver<T>,
51}
52
53impl<T> SignalReceiver<T> {
54    pub fn recv(&self) -> Result<T, RecvError> {
55        self.receiver.recv()
56    }
57
58    /// Compatibility alias for the old Tokio broadcast receiver call sites.
59    pub fn blocking_recv(&self) -> Result<T, RecvError> {
60        self.recv()
61    }
62
63    /// Waits for a signal for at most `timeout`.
64    ///
65    /// Native OBS callbacks are not cancelled when this deadline expires. Callers that use a
66    /// signal as completion for a native operation must therefore treat a timeout as an unknown
67    /// completion state and re-query native state before retrying or tearing resources down.
68    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
69        self.receiver.recv_timeout(timeout)
70    }
71
72    pub fn try_recv(&self) -> Result<T, TryRecvError> {
73        self.receiver.try_recv()
74    }
75}
76
77/// A small per-object fan-out hub used by generated signal managers.
78#[doc(hidden)]
79#[derive(Debug)]
80pub struct SignalHub<T> {
81    subscribers: Mutex<Vec<Sender<T>>>,
82}
83
84impl<T> Default for SignalHub<T> {
85    fn default() -> Self {
86        Self {
87            subscribers: Mutex::new(Vec::new()),
88        }
89    }
90}
91
92impl<T> SignalHub<T> {
93    #[doc(hidden)]
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    #[doc(hidden)]
99    pub fn subscribe(&self) -> SignalReceiver<T> {
100        let (tx, rx) = bounded(SIGNAL_QUEUE_CAPACITY);
101        match self.subscribers.lock() {
102            Ok(mut subscribers) => subscribers.push(tx),
103            Err(poisoned) => poisoned.into_inner().push(tx),
104        }
105        SignalReceiver { receiver: rx }
106    }
107}
108
109impl<T: Clone> SignalHub<T> {
110    #[doc(hidden)]
111    pub fn publish(&self, value: T) {
112        let mut subscribers = match self.subscribers.lock() {
113            Ok(subscribers) => subscribers,
114            Err(poisoned) => poisoned.into_inner(),
115        };
116        subscribers.retain(|subscriber| match subscriber.try_send(value.clone()) {
117            Ok(()) | Err(TrySendError::Full(_)) => true,
118            Err(TrySendError::Disconnected(_)) => false,
119        });
120    }
121}
122
123/// Generate a signal manager whose subscription state is owned by that manager.
124#[macro_export]
125macro_rules! impl_signal_manager {
126    ($handler_getter: expr, $name: ident for $ptr: ty, [
127        $($(#[$attr:meta])* $signal_name: literal: { $($inner_def:tt)* }),* $(,)*
128    ]) => {
129        paste::paste! {
130            $($crate::__signals_impl_signal!($ptr, $signal_name, $($inner_def)*);)*
131
132            $(
133                extern "C" fn [<$signal_name:snake _handler>](
134                    hub_ptr: *mut std::ffi::c_void,
135                    __internal_calldata: *mut libobs::calldata_t,
136                ) {
137                    let Some(hub) = (unsafe {
138                        // Safety: libobs receives this address from Arc::as_ptr during
139                        // connect and the manager keeps the Arc alive until disconnect.
140                        (hub_ptr as *const $crate::signals::SignalHub<
141                            [<__Private $signal_name:camel Type>]
142                        >).as_ref()
143                    }) else {
144                        log::warn!("Null signal hub for {}", $signal_name);
145                        return;
146                    };
147
148                    let value = unsafe {
149                        // Safety: libobs invokes the callback with valid calldata for
150                        // the duration of this call.
151                        [<$signal_name:snake _handler_inner>](__internal_calldata)
152                    };
153                    match value {
154                        Ok(value) => hub.publish(value),
155                        Err(err) => log::warn!("Error processing signal {}: {:?}", $signal_name, err),
156                    }
157                }
158            )*
159
160            #[derive(Debug)]
161            pub struct $name {
162                runtime: $crate::runtime::ObsRuntime,
163                pointer: $crate::unsafe_send::SmartPointerSendable<$ptr>,
164                $([<$signal_name:snake _hub>]: std::sync::Arc<
165                    $crate::signals::SignalHub<[<__Private $signal_name:camel Type>]>
166                >,)*
167            }
168
169            impl $name {
170                pub(crate) fn new(
171                    smart_ptr: &$crate::unsafe_send::SmartPointerSendable<$ptr>,
172                    runtime: $crate::runtime::ObsRuntime,
173                ) -> Result<Self, $crate::utils::ObsError> {
174                    use $crate::utils::ObsString;
175                    let smart_ptr = smart_ptr.clone();
176                    $(
177                        let [<$signal_name:snake _hub>] = std::sync::Arc::new(
178                            $crate::signals::SignalHub::<[<__Private $signal_name:camel Type>]>::new()
179                        );
180                    )*
181
182                    // Connect the complete manager in one actor command. A queue/shutdown
183                    // failure therefore happens before any callback userdata is registered,
184                    // eliminating partially-constructed managers with dangling C userdata.
185                    let connect_ptr = smart_ptr.clone();
186                    $(let [<$signal_name:snake _connect_hub>] = [<$signal_name:snake _hub>].clone();)*
187                    $crate::run_with_obs!(
188                        runtime,
189                        (connect_ptr, $([<$signal_name:snake _connect_hub>],)*),
190                        move || {
191                            $(
192                                let handler = ($handler_getter)(connect_ptr.clone());
193                                let signal = ObsString::new($signal_name);
194                                unsafe {
195                                    // SAFETY: handler and signal are valid on the OBS actor;
196                                    // each Arc allocation has a stable address until disconnect.
197                                    libobs::signal_handler_connect(
198                                        handler,
199                                        signal.as_c_str().as_ptr(),
200                                        Some([<$signal_name:snake _handler>]),
201                                        std::sync::Arc::as_ptr(&[<$signal_name:snake _connect_hub>])
202                                            as *mut std::ffi::c_void,
203                                    );
204                                }
205                            )*
206                        }
207                    )?;
208
209                    Ok(Self {
210                        pointer: smart_ptr,
211                        runtime,
212                        $([<$signal_name:snake _hub>],)*
213                    })
214                }
215
216                $(
217                    $(#[$attr])*
218                    pub fn [<on_ $signal_name:snake>](&self) -> Result<
219                        $crate::signals::SignalReceiver<[<__Private $signal_name:camel Type>]>,
220                        $crate::utils::ObsError,
221                    > {
222                        Ok(self.[<$signal_name:snake _hub>].subscribe())
223                    }
224                )*
225            }
226
227            // Deferred cleanup always executes on the OBS owner thread.
228            #[allow(unknown_lints)]
229            #[allow(ensure_obs_call_in_runtime)]
230            impl Drop for $name {
231                fn drop(&mut self) {
232                    log::trace!("Dropping signal manager {}...", stringify!($name));
233                    let ptr = self.pointer.clone();
234                    $(let [<$signal_name:snake _hub>] = self.[<$signal_name:snake _hub>].clone();)*
235
236                    // Deferred cleanup runs on the OBS owner thread; capturing a runtime clone
237                    // would let the final runtime handle drop on the actor during shutdown.
238                    self.runtime.defer_obs_cleanup(move || {
239                        let handler = ($handler_getter)(ptr.clone());
240                        $(
241                            let signal = $crate::utils::ObsString::new($signal_name);
242                            unsafe {
243                                // SAFETY: Deferred cleanup executes on the OBS owner thread;
244                                // the signal string and captured hub Arc remain alive for disconnect.
245                                libobs::signal_handler_disconnect(
246                                    handler,
247                                    signal.as_c_str().as_ptr(),
248                                    Some([<$signal_name:snake _handler>]),
249                                    std::sync::Arc::as_ptr(&[<$signal_name:snake _hub>])
250                                        as *mut std::ffi::c_void,
251                                );
252                            }
253                        )*
254                    });
255                }
256            }
257        }
258    };
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn slow_signal_subscriber_drops_new_events_without_blocking() {
267        let hub = SignalHub::new();
268        let receiver = hub.subscribe();
269        for value in 0..(SIGNAL_QUEUE_CAPACITY + 5) {
270            hub.publish(value);
271        }
272
273        let drained: Vec<_> = (0..SIGNAL_QUEUE_CAPACITY)
274            .map(|_| receiver.try_recv().expect("queued signal"))
275            .collect();
276        assert_eq!(drained, (0..SIGNAL_QUEUE_CAPACITY).collect::<Vec<_>>());
277        assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty)));
278    }
279
280    #[test]
281    fn disconnected_signal_subscribers_are_removed() {
282        let hub = SignalHub::new();
283        let receiver = hub.subscribe();
284        drop(receiver);
285        hub.publish(1_u8);
286        let subscribers = hub
287            .subscribers
288            .lock()
289            .unwrap_or_else(|poisoned| poisoned.into_inner());
290        assert!(subscribers.is_empty());
291    }
292
293    #[test]
294    fn timeout_receiver_observes_completion_published_before_wait() {
295        let hub = SignalHub::new();
296        let receiver = hub.subscribe();
297        hub.publish(42_u8);
298
299        assert_eq!(receiver.recv_timeout(Duration::from_millis(1)).unwrap(), 42);
300    }
301
302    #[test]
303    fn timeout_receiver_reports_missing_completion() {
304        let hub = SignalHub::<u8>::new();
305        let receiver = hub.subscribe();
306
307        assert!(matches!(
308            receiver.recv_timeout(Duration::from_millis(1)),
309            Err(RecvTimeoutError::Timeout)
310        ));
311    }
312}