Skip to main content

libobs_wrapper/
runtime.rs

1//! Runtime management for serialized OBS access.
2//!
3//! libobs has process-global state and a number of thread-affine operations.  The
4//! default runtime therefore treats OBS as an actor: callers submit bounded work to
5//! one dedicated thread while native resource destruction uses a separate cleanup
6//! queue.  The cleanup queue is intentionally unbounded because Rust destructors must
7//! never deadlock behind normal application work.
8
9use std::ffi::CStr;
10use std::fmt::Debug;
11use std::ptr;
12use std::rc::Rc;
13use std::sync::Arc;
14use std::thread;
15#[cfg(feature = "enable_runtime")]
16use std::thread::JoinHandle;
17
18#[cfg(feature = "enable_runtime")]
19use crossbeam_channel::{bounded, select, unbounded, Sender, TrySendError};
20#[cfg(feature = "enable_runtime")]
21use std::{
22    panic::{catch_unwind, AssertUnwindSafe},
23    sync::{
24        atomic::{AtomicU8, Ordering},
25        Mutex,
26    },
27};
28
29use crate::context::ObsContext;
30use crate::crash_handler::main_crash_handler;
31use crate::enums::{ObsLogLevel, ObsResetVideoStatus};
32use crate::logger::{extern_log_callback, internal_log_global, LOGGER};
33#[cfg(target_os = "linux")]
34use crate::run_with_obs;
35use crate::unsafe_send::NativeObjectRegistry;
36use crate::utils::initialization::{platform_specific_setup, PlatformSpecificGuard};
37use crate::utils::{ObsError, ObsModules, ObsString};
38use crate::{
39    context::{
40        activate_runtime_slot, begin_runtime_shutdown, cancel_runtime_start, release_runtime_slot,
41        reserve_runtime_slot,
42    },
43    utils::StartupInfo,
44};
45
46#[cfg(feature = "enable_runtime")]
47const RUNTIME_QUEUE_CAPACITY: usize = 128;
48#[cfg(feature = "enable_runtime")]
49const RUNTIME_RUNNING: u8 = 0;
50#[cfg(feature = "enable_runtime")]
51const RUNTIME_SHUTTING_DOWN: u8 = 1;
52#[cfg(feature = "enable_runtime")]
53const RUNTIME_PANICKED: u8 = 2;
54#[cfg(feature = "enable_runtime")]
55const RUNTIME_STOPPED: u8 = 3;
56
57#[cfg(feature = "enable_runtime")]
58type RuntimeTask = Box<dyn FnOnce() + Send + 'static>;
59
60#[cfg(feature = "enable_runtime")]
61enum ObsCommand {
62    Execute(RuntimeTask),
63}
64
65#[cfg(feature = "enable_runtime")]
66fn execute_command(command: ObsCommand) {
67    match command {
68        ObsCommand::Execute(task) => task(),
69    }
70}
71
72#[cfg(feature = "enable_runtime")]
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74enum QueueSubmitError {
75    Full,
76    Disconnected,
77}
78
79#[cfg(feature = "enable_runtime")]
80fn try_submit_command(
81    sender: &Sender<ObsCommand>,
82    command: ObsCommand,
83) -> Result<(), QueueSubmitError> {
84    match sender.try_send(command) {
85        Ok(()) => Ok(()),
86        Err(TrySendError::Full(_)) => Err(QueueSubmitError::Full),
87        Err(TrySendError::Disconnected(_)) => Err(QueueSubmitError::Disconnected),
88    }
89}
90
91#[cfg(feature = "enable_runtime")]
92fn run_actor_work<F>(work: F) -> bool
93where
94    F: FnOnce(),
95{
96    catch_unwind(AssertUnwindSafe(work)).is_ok()
97}
98
99struct InitializationRollback {
100    armed: bool,
101    obs_started: bool,
102}
103
104impl InitializationRollback {
105    fn new() -> Self {
106        Self {
107            armed: true,
108            obs_started: false,
109        }
110    }
111
112    fn disarm(&mut self) {
113        self.armed = false;
114    }
115}
116
117#[allow(unknown_lints)]
118#[allow(ensure_obs_call_in_runtime)]
119impl Drop for InitializationRollback {
120    fn drop(&mut self) {
121        if !self.armed {
122            return;
123        }
124
125        log::warn!("Rolling back incomplete OBS initialization");
126        if self.obs_started {
127            unsafe {
128                // SAFETY: Initialization and rollback occur on the owning OBS thread.
129                libobs::obs_shutdown();
130            }
131        }
132        unsafe {
133            // SAFETY: These process-global handlers were installed by initialize_inner.
134            libobs::base_set_crash_handler(None, std::ptr::null_mut());
135            libobs::base_set_log_handler(None, std::ptr::null_mut());
136        }
137        let _ = release_runtime_slot();
138    }
139}
140
141/// Core runtime that serializes access to libobs.
142#[derive(Clone)]
143pub struct ObsRuntime {
144    #[cfg(feature = "enable_runtime")]
145    command_sender: Arc<Sender<ObsCommand>>,
146    #[cfg(feature = "enable_runtime")]
147    cleanup_sender: Arc<Sender<RuntimeTask>>,
148    #[cfg(feature = "enable_runtime")]
149    health: Arc<AtomicU8>,
150    native_registry: Arc<NativeObjectRegistry>,
151    thread_id: std::thread::ThreadId,
152    _guard: Arc<_ObsRuntimeGuard>,
153
154    #[cfg(not(feature = "enable_runtime"))]
155    _platform_specific: Option<Rc<PlatformSpecificGuard>>,
156}
157
158/// Test environment only: see `context::test_shutdown`. While no `ObsContext` is alive,
159/// flush deferred cleanup before releasing this handle so that the final runtime handle is
160/// dropped here (and joins shutdown) rather than inside a queued closure on the actor.
161#[cfg(all(feature = "enable_runtime", any(test, feature = "__test_environment")))]
162impl Drop for ObsRuntime {
163    fn drop(&mut self) {
164        const FLUSH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
165        if self.is_actor_thread() || !crate::context::test_shutdown::no_live_contexts() {
166            return;
167        }
168        let (flushed_tx, flushed_rx) = bounded::<()>(1);
169        let marker: RuntimeTask = Box::new(move || {
170            let _ = flushed_tx.send(());
171        });
172        if self.cleanup_sender.send(marker).is_ok()
173            && flushed_rx.recv_timeout(FLUSH_TIMEOUT).is_err()
174        {
175            // Disconnected means the actor stopped; only a timeout is worth reporting.
176            log::warn!("Deferred OBS cleanup did not drain within {FLUSH_TIMEOUT:?}");
177        }
178    }
179}
180
181impl Debug for ObsRuntime {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        f.debug_struct("ObsRuntime")
184            .field("thread_id", &self.thread_id)
185            .field("native_objects", &self.native_registry.len())
186            .finish_non_exhaustive()
187    }
188}
189
190impl ObsRuntime {
191    pub(crate) fn startup(
192        options: StartupInfo,
193    ) -> Result<(ObsRuntime, ObsModules, StartupInfo), ObsError> {
194        reserve_runtime_slot()?;
195        log::trace!("Initializing OBS context");
196        match Self::init(options) {
197            Ok(initialized) => Ok(initialized),
198            Err(err) => {
199                // Only undo a reservation that never became active. initialize_inner
200                // owns rollback after it activates the process-global slot.
201                cancel_runtime_start();
202                Err(err)
203            }
204        }
205    }
206
207    #[cfg(not(feature = "enable_runtime"))]
208    fn init(info: StartupInfo) -> Result<(ObsRuntime, ObsModules, StartupInfo), ObsError> {
209        let (startup, mut modules, platform_specific) = unsafe { Self::initialize_inner(info)? };
210        let runtime = Self {
211            native_registry: Arc::new(NativeObjectRegistry::default()),
212            thread_id: thread::current().id(),
213            _guard: Arc::new(_ObsRuntimeGuard {}),
214            _platform_specific: platform_specific,
215        };
216        modules.runtime = Some(runtime.clone());
217        Ok((runtime, modules, startup))
218    }
219
220    #[cfg(feature = "enable_runtime")]
221    #[allow(unknown_lints)]
222    #[allow(ensure_obs_call_in_runtime)]
223    fn init(info: StartupInfo) -> Result<(ObsRuntime, ObsModules, StartupInfo), ObsError> {
224        static RUNTIME_THREAD_NAME: &str = "libobs-wrapper-obs-runtime";
225
226        let health = Arc::new(AtomicU8::new(RUNTIME_RUNNING));
227        let actor_health = health.clone();
228        let (command_sender, command_receiver) = bounded(RUNTIME_QUEUE_CAPACITY);
229        let (cleanup_sender, cleanup_receiver) = unbounded::<RuntimeTask>();
230        let (shutdown_sender, shutdown_receiver) = unbounded::<()>();
231        let (init_tx, init_rx) = bounded(1);
232
233        let handle = std::thread::Builder::new()
234            .name(RUNTIME_THREAD_NAME.to_string())
235            .spawn(move || {
236                log::trace!("Starting OBS actor thread");
237                // SAFETY: This closure is the dedicated OBS actor thread and owns the
238                // complete initialize/use/shutdown sequence for libobs. Catch Rust panics
239                // as well as typed initialization failures so the process-global slot
240                // cannot be stranded in Starting/Active.
241                let initialized = catch_unwind(AssertUnwindSafe(|| {
242                    // SAFETY: This closure is executing on the dedicated OBS actor that
243                    // owns initialization for the complete process-global OBS lifetime.
244                    unsafe { Self::initialize_inner(info) }
245                }));
246
247                let (info, modules, platform_specific_guard) = match initialized {
248                    Ok(Ok(value)) => value,
249                    Ok(Err(err)) => {
250                        let _ = init_tx.send(Err(err));
251                        return;
252                    }
253                    Err(_) => {
254                        actor_health.store(RUNTIME_PANICKED, Ordering::Release);
255                        // SAFETY: We are still on the owning OBS actor and initialization
256                        // panicked before control could be returned to another thread.
257                        // SAFETY: Shutdown recovery runs on the owning OBS actor after
258                        // normal work has stopped; clearing process-global callbacks is safe.
259                        unsafe {
260                            libobs::base_set_crash_handler(None, std::ptr::null_mut());
261                            libobs::base_set_log_handler(None, std::ptr::null_mut());
262                        }
263                        let _ = release_runtime_slot();
264                        let _ = init_tx.send(Err(ObsError::RuntimePanicked));
265                        return;
266                    }
267                };
268
269                if init_tx.send(Ok((modules, info))).is_err() {
270                    log::error!("OBS runtime initializer was dropped before startup completed");
271                    // SAFETY: Initialization and this cleanup both run on the same OBS actor thread.
272                    let _ = unsafe { Self::shutdown_inner() };
273                    return;
274                }
275
276                // Keep platform-specific thread-affine state alive for the complete OBS lifetime.
277                let _platform_specific_guard = platform_specific_guard;
278
279                let actor_survived = run_actor_work(|| {
280                    'runtime: loop {
281                        select! {
282                            recv(cleanup_receiver) -> cleanup => match cleanup {
283                                Ok(task) => task(),
284                                Err(_) => break 'runtime,
285                            },
286                            recv(command_receiver) -> command => match command {
287                                Ok(command) => execute_command(command),
288                                Err(_) => break 'runtime,
289                            },
290                            recv(shutdown_receiver) -> _ => break 'runtime,
291                        }
292                    }
293
294                    // A normal last-runtime drop may leave fire-and-forget work and deferred
295                    // destruction. Preserve FIFO ordering before obs_shutdown().
296                    while let Ok(command) = command_receiver.try_recv() {
297                        execute_command(command);
298                    }
299                    while let Ok(cleanup) = cleanup_receiver.try_recv() {
300                        cleanup();
301                    }
302                });
303
304                if !actor_survived {
305                    actor_health.store(RUNTIME_PANICKED, Ordering::Release);
306                    log::error!("OBS actor command panicked; rejecting pending work and shutting down safely");
307
308                    // Pending normal commands must not execute after an arbitrary command panic.
309                    // Dropping them disconnects any synchronous result channels. Native cleanup
310                    // is still attempted before shutdown so owned OBS references are released.
311                    while command_receiver.try_recv().is_ok() {}
312                    while let Ok(cleanup) = cleanup_receiver.try_recv() {
313                        if !run_actor_work(cleanup) {
314                            log::error!("A deferred OBS cleanup task also panicked during actor recovery");
315                        }
316                    }
317                }
318
319                let shutdown_result = catch_unwind(AssertUnwindSafe(|| unsafe {
320                    // SAFETY: The actor owns the complete libobs lifetime and shutdown
321                    // runs on the same thread that initialized it.
322                    Self::shutdown_inner()
323                }));
324                match shutdown_result {
325                    Ok(Ok(())) => {}
326                    Ok(Err(err)) => log::error!("Failed to shut down OBS context: {err:?}"),
327                    Err(_) => {
328                        log::error!("OBS shutdown panicked; clearing handlers and force-releasing the global runtime slot");
329                        // SAFETY: This recovery branch still executes on the owning OBS actor
330                        // after normal work has stopped; clearing global callbacks is safe here.
331                        unsafe {
332                            libobs::base_set_crash_handler(None, std::ptr::null_mut());
333                            libobs::base_set_log_handler(None, std::ptr::null_mut());
334                        }
335                        let _ = release_runtime_slot();
336                    }
337                }
338                if actor_health.load(Ordering::Acquire) != RUNTIME_PANICKED {
339                    actor_health.store(RUNTIME_STOPPED, Ordering::Release);
340                }
341            })
342            .map_err(|_| ObsError::ThreadFailure)?;
343
344        let (mut modules, info) = init_rx.recv().map_err(|_| {
345            ObsError::RuntimeChannelError("OBS actor exited during initialization".to_string())
346        })??;
347
348        let thread_id = handle.thread().id();
349        let command_sender = Arc::new(command_sender);
350        let cleanup_sender = Arc::new(cleanup_sender);
351        let shutdown_sender = Arc::new(shutdown_sender);
352        let runtime = Self {
353            command_sender: command_sender.clone(),
354            cleanup_sender: cleanup_sender.clone(),
355            health: health.clone(),
356            native_registry: Arc::new(NativeObjectRegistry::default()),
357            thread_id,
358            _guard: Arc::new(_ObsRuntimeGuard {
359                handle: Mutex::new(Some(handle)),
360                shutdown_sender,
361                health,
362            }),
363        };
364
365        modules.runtime = Some(runtime.clone());
366        Ok((runtime, modules, info))
367    }
368
369    /// Returns true when called from the dedicated OBS actor thread.
370    ///
371    /// With `enable_runtime` disabled there is no dedicated actor: libobs is intentionally
372    /// caller-thread-affine instead, so blocking native-completion waits on that owning thread are
373    /// not actor reentrancy and must not be rejected as such.
374    pub fn is_actor_thread(&self) -> bool {
375        #[cfg(feature = "enable_runtime")]
376        {
377            std::thread::current().id() == self.thread_id
378        }
379        #[cfg(not(feature = "enable_runtime"))]
380        {
381            false
382        }
383    }
384
385    /// Returns true when both values belong to the same process-global OBS runtime.
386    pub fn same_instance(&self, other: &Self) -> bool {
387        self.native_registry.runtime_id() == other.native_registry.runtime_id()
388    }
389
390    pub(crate) fn ensure_same_runtime(&self, other: &Self) -> Result<(), ObsError> {
391        if self.same_instance(other) {
392            Ok(())
393        } else {
394            Err(ObsError::RuntimeMismatch)
395        }
396    }
397
398    #[cfg(feature = "enable_runtime")]
399    fn unavailable_error(&self) -> ObsError {
400        match self.health.load(Ordering::Acquire) {
401            RUNTIME_PANICKED => ObsError::RuntimePanicked,
402            _ => ObsError::RuntimeChannelError("OBS actor is shutting down or stopped".to_string()),
403        }
404    }
405
406    /// Dispatches work without waiting for completion.
407    ///
408    /// The regular actor queue is bounded.  If it is full this returns
409    /// [`ObsError::RuntimeQueueFull`] instead of growing memory without bound.
410    #[cfg(feature = "enable_runtime")]
411    pub fn run_with_obs_no_block<F>(&self, operation: F) -> Result<(), ObsError>
412    where
413        F: FnOnce() + Send + 'static,
414    {
415        if self.is_actor_thread() {
416            operation();
417            return Ok(());
418        }
419        if self.health.load(Ordering::Acquire) != RUNTIME_RUNNING {
420            return Err(self.unavailable_error());
421        }
422
423        match try_submit_command(
424            &self.command_sender,
425            ObsCommand::Execute(Box::new(operation)),
426        ) {
427            Ok(()) => Ok(()),
428            Err(QueueSubmitError::Full) => Err(ObsError::RuntimeQueueFull {
429                capacity: RUNTIME_QUEUE_CAPACITY,
430            }),
431            Err(QueueSubmitError::Disconnected) => Err(self.unavailable_error()),
432        }
433    }
434
435    #[cfg(not(feature = "enable_runtime"))]
436    pub fn run_with_obs_no_block<F>(&self, operation: F) -> Result<(), ObsError>
437    where
438        F: FnOnce() + 'static,
439    {
440        self.run_with_obs_result(operation)
441    }
442
443    /// Runs work on the OBS actor and returns its typed result.
444    ///
445    /// Unlike the old implementation this does not erase the result into `Any`, so
446    /// there is no runtime downcast or corresponding impossible error path.
447    #[cfg(feature = "enable_runtime")]
448    pub fn run_with_obs_result<F, T>(&self, operation: F) -> Result<T, ObsError>
449    where
450        F: FnOnce() -> T + Send + 'static,
451        T: Send + 'static,
452    {
453        if self.is_actor_thread() {
454            return Ok(operation());
455        }
456        if self.health.load(Ordering::Acquire) != RUNTIME_RUNNING {
457            return Err(self.unavailable_error());
458        }
459
460        let (result_tx, result_rx) = bounded(1);
461        let task = move || {
462            let result = operation();
463            let _ = result_tx.send(result);
464        };
465
466        match try_submit_command(&self.command_sender, ObsCommand::Execute(Box::new(task))) {
467            Ok(()) => {}
468            Err(QueueSubmitError::Full) => {
469                return Err(ObsError::RuntimeQueueFull {
470                    capacity: RUNTIME_QUEUE_CAPACITY,
471                });
472            }
473            Err(QueueSubmitError::Disconnected) => return Err(self.unavailable_error()),
474        }
475
476        result_rx.recv().map_err(|_| self.unavailable_error())
477    }
478
479    #[cfg(not(feature = "enable_runtime"))]
480    pub fn run_with_obs_result<F, T>(&self, operation: F) -> Result<T, ObsError>
481    where
482        F: FnOnce() -> T,
483    {
484        if std::thread::current().id() != self.thread_id {
485            return Err(ObsError::RuntimeOutsideThread);
486        }
487        Ok(operation())
488    }
489
490    pub(crate) fn native_registry(&self) -> Arc<NativeObjectRegistry> {
491        self.native_registry.clone()
492    }
493
494    /// Queue native destruction without making a Rust `Drop` implementation wait for
495    /// the normal actor queue.  This is public only so exported wrapper macros can use
496    /// it from companion crates; application code normally has no reason to call it.
497    #[doc(hidden)]
498    #[cfg(feature = "enable_runtime")]
499    pub fn defer_obs_cleanup<F>(&self, cleanup: F)
500    where
501        F: FnOnce() + Send + 'static,
502    {
503        if std::thread::current().id() == self.thread_id {
504            cleanup();
505            return;
506        }
507
508        if self.cleanup_sender.send(Box::new(cleanup)).is_err() {
509            // We must never panic from Drop.  At this point the actor is gone, so the
510            // only safe option is to report the leak rather than call libobs off-thread.
511            log::error!("OBS actor stopped before deferred native cleanup could be queued");
512        }
513    }
514
515    #[doc(hidden)]
516    #[cfg(not(feature = "enable_runtime"))]
517    pub fn defer_obs_cleanup<F>(&self, cleanup: F)
518    where
519        F: FnOnce() + 'static,
520    {
521        if std::thread::current().id() == self.thread_id {
522            cleanup();
523        } else {
524            log::error!("Native OBS cleanup requested from outside the owning thread");
525        }
526    }
527
528    #[allow(unknown_lints)]
529    #[allow(ensure_obs_call_in_runtime)]
530    unsafe fn initialize_inner(
531        mut info: StartupInfo,
532    ) -> Result<(StartupInfo, ObsModules, Option<Rc<PlatformSpecificGuard>>), ObsError> {
533        // `startup` reserved the process-global slot before spawning this actor.
534        // Transition that reservation to the concrete owning thread.
535        activate_runtime_slot(thread::current().id())?;
536
537        // Install DLL blocklist hook here
538
539        #[cfg(windows)]
540        unsafe {
541            // Safety: We are in the OBS thread, so it's safe to call this here.
542            libobs::obs_init_win32_crash_handler();
543        }
544
545        // Set logger, load debug privileges and crash handler
546        unsafe {
547            // Safety: We are in the OBS thread, so it's safe to call this here.
548            libobs::base_set_crash_handler(Some(main_crash_handler), std::ptr::null_mut());
549        }
550
551        let native = match unsafe {
552            // Safety: We are in the OBS thread and the nix_display can only be set here.
553            platform_specific_setup(info.nix_display.clone())
554        } {
555            Ok(native) => native,
556            Err(err) => {
557                unsafe {
558                    libobs::base_set_crash_handler(None, std::ptr::null_mut());
559                }
560                let _ = release_runtime_slot();
561                return Err(err);
562            }
563        };
564        let mut rollback = InitializationRollback::new();
565        unsafe {
566            // Safety: We are in the OBS thread, so it's safe to call this here.
567            libobs::base_set_log_handler(Some(extern_log_callback), std::ptr::null_mut());
568        }
569
570        let mut log_callback = LOGGER.lock().map_err(|_e| ObsError::MutexFailure)?;
571
572        *log_callback = info.logger.take().ok_or_else(|| {
573            ObsError::InvalidOperation("startup logger was already consumed".to_string())
574        })?;
575        drop(log_callback);
576
577        // Locale will only be used internally by
578        // libobs for logging purposes, making it
579        // unnecessary to support other languages.
580        let locale_str = ObsString::new("en-US");
581        let module_config_path = info
582            .module_config_path
583            .as_ref()
584            .map_or(ptr::null(), |path| path.as_ptr().0);
585        internal_log_global(
586            ObsLogLevel::Info,
587            format!(
588                "[libobs-wrapper]: Module config path: {}",
589                info.module_config_path
590                    .as_ref()
591                    .map(ToString::to_string)
592                    .unwrap_or_else(|| "<unset>".to_string())
593            ),
594        );
595        let startup_status = unsafe {
596            // Safety: Both strings are owned by this startup frame and remain valid
597            // for the duration of obs_startup. A null module config path preserves
598            // libobs's documented "no configuration directory" behavior.
599            libobs::obs_startup(locale_str.as_ptr().0, module_config_path, ptr::null_mut())
600        };
601        if !startup_status {
602            return Err(ObsError::Failure);
603        }
604        // From this exact point onward any Rust error/panic must run obs_shutdown().
605        rollback.obs_started = true;
606
607        // SAFETY: libobs startup succeeded on this actor; the returned pointer is either
608        // null or a libobs-owned NUL-terminated version string.
609        let version = unsafe { libobs::obs_get_version_string() };
610        let version_str = if version.is_null() {
611            "unknown".to_string()
612        } else {
613            // SAFETY: `version` was checked non-null immediately above and libobs owns
614            // the NUL-terminated string for the process lifetime.
615            let version_cstr = unsafe { CStr::from_ptr(version) };
616            version_cstr.to_string_lossy().into_owned()
617        };
618
619        internal_log_global(ObsLogLevel::Info, format!("OBS {}", version_str));
620
621        // Check version compatibility
622        if !ObsContext::check_version_compatibility() {
623            internal_log_global(
624                ObsLogLevel::Warning,
625                "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string(),
626            );
627            internal_log_global(
628                ObsLogLevel::Warning,
629                format!(
630                    "OBS major version mismatch: installed version is {}, but expected major version {}. Expect crashes or bugs!!",
631                    version_str,
632                    libobs::LIBOBS_API_MAJOR_VER
633                ),
634            );
635            internal_log_global(
636                ObsLogLevel::Warning,
637                "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".to_string(),
638            );
639        }
640
641        internal_log_global(
642            ObsLogLevel::Info,
643            "---------------------------------".to_string(),
644        );
645
646        let mut obs_modules = unsafe {
647            // Safety: This is running in the OBS thread, so it's safe to call this here.
648            ObsModules::add_paths(&info.startup_paths)
649        };
650
651        // Note that audio is meant to only be reset
652        // once. See the link below for information.
653        //
654        // https://docs.obsproject.com/frontends
655        let audio_ready = unsafe {
656            // Safety: The audio_info pointer is valid here.
657            libobs::obs_reset_audio2(info.obs_audio_info.as_ptr().0)
658        };
659        if !audio_ready {
660            return Err(ObsError::ResetAudioFailure);
661        }
662
663        // Resets the video context. Note that this
664        // is similar to Self::reset_video, but it
665        // does not call that function because the
666        // ObsContext struct is not created yet,
667        // and also because there is no need to free
668        // anything tied to the OBS context.
669        let reset_video_status = num_traits::FromPrimitive::from_i32(unsafe {
670            // Safety: The video_info pointer is valid here.
671            libobs::obs_reset_video(info.obs_video_info.as_ptr())
672        });
673
674        let reset_video_status = match reset_video_status {
675            Some(x) => x,
676            None => ObsResetVideoStatus::Failure,
677        };
678
679        if reset_video_status != ObsResetVideoStatus::Success {
680            return Err(ObsError::ResetVideoFailure(reset_video_status));
681        }
682
683        let sdr_info = info.obs_video_info.get_sdr_info();
684        unsafe {
685            // Safety: These are just numbers, so it's safe to call this here. Also graphics are initialized, so we can call this.
686            libobs::obs_set_video_levels(sdr_info.sdr_white_level, sdr_info.hdr_nominal_peak_level);
687        }
688
689        unsafe {
690            obs_modules.load_modules();
691        }
692
693        internal_log_global(
694            ObsLogLevel::Info,
695            "==== Startup complete ===============================================".to_string(),
696        );
697
698        rollback.disarm();
699        Ok((info, obs_modules, native))
700    }
701
702    /// Shuts down the OBS context and cleans up resources
703    ///
704    /// This method performs a clean shutdown of OBS, including:
705    /// - Removing sources from output channels
706    /// - Calling `obs_shutdown` to clean up OBS resources
707    /// - Removing log and crash handlers
708    /// - Checking for memory leaks
709    ///
710    /// Safety: Always run this in the OBS runtime context.
711    #[allow(unknown_lints)]
712    #[allow(ensure_obs_call_in_runtime)]
713    unsafe fn shutdown_inner() -> Result<(), ObsError> {
714        // Clean up sources
715        for i in 0..libobs::MAX_CHANNELS {
716            unsafe { libobs::obs_set_output_source(i, ptr::null_mut()) };
717        }
718
719        unsafe {
720            // SAFETY: Shutdown runs on the initializing thread after command processing stops
721            // and deferred cleanup is drained. Managed owners retain ObsRuntime until their
722            // releases are queued; global output references were cleared above. Panic recovery
723            // rejects pending work and drains cleanup before reaching here.
724            libobs::obs_shutdown()
725        }
726
727        let r = LOGGER.lock();
728        match r {
729            Ok(mut logger) => {
730                logger.log(ObsLogLevel::Info, "OBS context shutdown.".to_string());
731                let allocs = unsafe {
732                    // Safety: Can always be called because it just returns a number.
733                    libobs::bnum_allocs()
734                };
735
736                // Increasing this to 1 because of whats described below
737                let mut notice = "";
738                let level = if allocs > 1 {
739                    ObsLogLevel::Error
740                } else {
741                    notice = " (this is an issue in the OBS source code that cannot be fixed)";
742                    ObsLogLevel::Info
743                };
744                // One memory leak is expected here because OBS does not free array elements of the obs_data_path when calling obs_add_data_path
745                // even when obs_remove_data_path is called. This is a bug in OBS.
746                logger.log(
747                    level,
748                    format!("Number of memory leaks: {}{}", allocs, notice),
749                );
750
751                #[cfg(any(feature = "__test_environment", test))]
752                if allocs != 1 {
753                    log::error!("OBS leak check expected 1 allocation, observed {allocs}");
754                }
755            }
756            Err(_) => {
757                println!("OBS context shutdown. (but couldn't lock logger)");
758            }
759        }
760
761        unsafe {
762            // Safety: We are in the OBS thread, so it's safe to call this here.
763            // Clean up log and crash handler
764            libobs::base_set_crash_handler(None, std::ptr::null_mut());
765            libobs::base_set_log_handler(None, std::ptr::null_mut());
766        }
767
768        release_runtime_slot()?;
769        Ok(())
770    }
771
772    #[cfg(target_os = "linux")]
773    pub fn get_platform(&self) -> Result<crate::utils::initialization::PlatformType, ObsError> {
774        run_with_obs!(self, || {
775            let raw_platform = unsafe {
776                // Safety: This is safe to call as long as OBS is initialized.
777                libobs::obs_get_nix_platform()
778            };
779
780            match raw_platform {
781                libobs::obs_nix_platform_type_OBS_NIX_PLATFORM_X11_EGL => {
782                    crate::utils::initialization::PlatformType::X11
783                }
784                libobs::obs_nix_platform_type_OBS_NIX_PLATFORM_WAYLAND => {
785                    crate::utils::initialization::PlatformType::Wayland
786                }
787                _ => crate::utils::initialization::PlatformType::Invalid,
788            }
789        })
790    }
791}
792
793/// Guard for the process-global actor lifetime.
794#[derive(Debug)]
795pub struct _ObsRuntimeGuard {
796    #[cfg(feature = "enable_runtime")]
797    handle: Mutex<Option<JoinHandle<()>>>,
798    #[cfg(feature = "enable_runtime")]
799    shutdown_sender: Arc<Sender<()>>,
800    #[cfg(feature = "enable_runtime")]
801    health: Arc<AtomicU8>,
802}
803
804#[cfg(feature = "enable_runtime")]
805impl Drop for _ObsRuntimeGuard {
806    fn drop(&mut self) {
807        log::trace!("Last ObsRuntime dropped; requesting actor shutdown");
808        begin_runtime_shutdown();
809        self.health.store(RUNTIME_SHUTTING_DOWN, Ordering::Release);
810        if self.shutdown_sender.send(()).is_err() {
811            let _ = release_runtime_slot();
812        }
813
814        // Never wait for native execution from a production destructor.  Dropping a
815        // JoinHandle detaches the worker, which owns everything it needs to finish the
816        // queued cleanup and call obs_shutdown safely.
817        let handle = match self.handle.get_mut() {
818            Ok(handle) => handle.take(),
819            Err(poisoned) => poisoned.into_inner().take(),
820        };
821
822        #[cfg(any(test, feature = "__test_environment"))]
823        if let Some(handle) = handle {
824            // Integration tests need deterministic shutdown before the next test starts.
825            if handle.thread().id() != std::thread::current().id() && handle.join().is_err() {
826                log::error!("OBS actor panicked during test shutdown");
827            }
828        }
829
830        #[cfg(not(any(test, feature = "__test_environment")))]
831        drop(handle);
832    }
833}
834
835#[cfg(not(feature = "enable_runtime"))]
836impl Drop for _ObsRuntimeGuard {
837    fn drop(&mut self) {
838        log::trace!("Last local ObsRuntime dropped; shutting down OBS");
839        begin_runtime_shutdown();
840        if let Err(err) = unsafe { ObsRuntime::shutdown_inner() } {
841            log::error!("Failed to shut down OBS context: {err:?}");
842        }
843    }
844}
845
846#[cfg(all(test, feature = "enable_runtime"))]
847mod tests {
848    use super::*;
849
850    #[test]
851    fn bounded_submission_reports_full_without_blocking() {
852        let (sender, _receiver) = bounded(1);
853        try_submit_command(&sender, ObsCommand::Execute(Box::new(|| {})))
854            .expect("first command fits");
855        assert_eq!(
856            try_submit_command(&sender, ObsCommand::Execute(Box::new(|| {}))),
857            Err(QueueSubmitError::Full)
858        );
859    }
860
861    #[test]
862    fn bounded_submission_reports_disconnect() {
863        let (sender, receiver) = bounded(1);
864        drop(receiver);
865        assert_eq!(
866            try_submit_command(&sender, ObsCommand::Execute(Box::new(|| {}))),
867            Err(QueueSubmitError::Disconnected)
868        );
869    }
870
871    #[test]
872    fn actor_work_contains_command_panics() {
873        assert!(!run_actor_work(|| panic!("synthetic actor command panic")));
874        assert!(run_actor_work(|| {}));
875    }
876}