Skip to main content

libobs_wrapper\utils/
modules.rs

1use std::{
2    ffi::{CStr, CString},
3    fmt::Debug,
4};
5
6use crate::{
7    context::ObsContext, enums::ObsLogLevel, logger::internal_log_global, runtime::ObsRuntime,
8    utils::StartupPaths,
9};
10use libobs::obs_module_failure_info;
11
12pub struct ObsModules {
13    paths: StartupPaths,
14
15    /// Module names copied out of OBS-owned failure data during initialization.
16    failed_modules: Vec<String>,
17    pub(crate) runtime: Option<ObsRuntime>,
18}
19
20impl Debug for ObsModules {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        f.debug_struct("ObsModules")
23            .field("paths", &self.paths)
24            .field("failed_modules", &self.failed_modules)
25            .finish()
26    }
27}
28
29// List of all modules, this is for compatibility for obs versions below 32.0.0
30static SAFE_MODULES: &str = "decklink|image-source|linux-alsa|linux-capture|linux-pipewire|linux-pulseaudio|linux-v4l2|obs-ffmpeg|obs-filters|obs-nvenc|obs-outputs|obs-qsv11|obs-transitions|obs-vst|obs-websocket|obs-x264|rtmp-services|text-freetype2|vlc-video|decklink-captions|decklink-output-ui|obslua|obspython|frontend-tools";
31
32impl ObsModules {
33    /// Safety: ALWAYS CALL THIS IN THE OBS RUNTIME CONTEXT
34    #[allow(unknown_lints)]
35    #[allow(ensure_obs_call_in_runtime)]
36    pub(crate) unsafe fn add_paths(paths: &StartupPaths) -> Self {
37        internal_log_global(
38            ObsLogLevel::Info,
39            "[libobs-wrapper]: Adding module paths:".to_string(),
40        );
41        internal_log_global(
42            ObsLogLevel::Info,
43            format!(
44                "[libobs-wrapper]:   libobs data path: {}",
45                paths.libobs_data_path()
46            ),
47        );
48        internal_log_global(
49            ObsLogLevel::Info,
50            format!(
51                "[libobs-wrapper]:   plugin bin path: {}",
52                paths.plugin_bin_path()
53            ),
54        );
55        internal_log_global(
56            ObsLogLevel::Info,
57            format!(
58                "[libobs-wrapper]:   plugin data path: {}",
59                paths.plugin_data_path()
60            ),
61        );
62
63        libobs::obs_add_data_path(paths.libobs_data_path().as_ptr().0);
64        libobs::obs_add_module_path(
65            paths.plugin_bin_path().as_ptr().0,
66            paths.plugin_data_path().as_ptr().0,
67        );
68
69        #[allow(unused_mut)]
70        let mut disabled_plugins = vec!["obs-websocket", "frontend-tools"];
71
72        #[cfg(feature = "__test_environment")]
73        {
74            disabled_plugins.extend(&["decklink-output-ui", "decklink-captions", "decklink"]);
75        }
76
77        let version = ObsContext::get_version_global().unwrap_or_default();
78        let version_parts: Vec<&str> = version.split('.').collect();
79        let major = version_parts
80            .first()
81            .and_then(|s| s.parse::<u32>().ok())
82            .unwrap_or(0);
83
84        // Check if obs_add_disabled_module exists at runtime
85        #[cfg(target_os = "linux")]
86        let has_disabled_module_fn = {
87            // Try to find symbol in already loaded libraries
88            let symbol_name = CString::new("obs_add_disabled_module").unwrap();
89            let sym = libc::dlsym(libc::RTLD_DEFAULT, symbol_name.as_ptr());
90            let found = !sym.is_null();
91
92            if !found && major >= 32 {
93                log::warn!(
94                    "OBS version >= 32 but obs_add_disabled_module symbol not found, falling back to safe modules"
95                );
96            }
97
98            found
99        };
100        #[cfg(not(target_os = "linux"))]
101        let has_disabled_module_fn = major >= 32;
102
103        if major >= 32 && has_disabled_module_fn {
104            for plugin in disabled_plugins {
105                let c_str = CString::new(plugin).unwrap();
106                #[cfg(target_os = "linux")]
107                {
108                    let symbol_name = CString::new("obs_add_disabled_module").unwrap();
109                    let func = libc::dlsym(libc::RTLD_DEFAULT, symbol_name.as_ptr());
110                    if !func.is_null() {
111                        // SAFETY: dlsym found obs_add_disabled_module in the loaded libobs.
112                        // obs.h declares it as void(const char *), using the C ABI; POSIX
113                        // permits converting this symbol address to its function pointer type.
114                        // libobs remains loaded throughout this initialization call.
115                        let add_disabled: extern "C" fn(*const std::os::raw::c_char) =
116                            std::mem::transmute(func);
117                        add_disabled(c_str.as_ptr());
118                    }
119                }
120                #[cfg(not(target_os = "linux"))]
121                {
122                    libobs::obs_add_disabled_module(c_str.as_ptr());
123                }
124            }
125        } else {
126            for plugin in SAFE_MODULES.split('|') {
127                if disabled_plugins.contains(&plugin) {
128                    continue;
129                }
130                let c_str = CString::new(plugin).unwrap();
131                libobs::obs_add_safe_module(c_str.as_ptr());
132            }
133        }
134
135        Self {
136            paths: paths.clone(),
137            failed_modules: Vec::new(),
138            runtime: None,
139        }
140    }
141
142    /// Safety: ALWAYS CALL THIS IN THE OBS RUNTIME CONTEXT
143    #[allow(unknown_lints)]
144    #[allow(ensure_obs_call_in_runtime)]
145    pub(crate) unsafe fn load_modules(&mut self) {
146        let mut failure_info: obs_module_failure_info = std::mem::zeroed();
147        internal_log_global(
148            ObsLogLevel::Info,
149            "---------------------------------".to_string(),
150        );
151        libobs::obs_load_all_modules2(&mut failure_info);
152        internal_log_global(
153            ObsLogLevel::Info,
154            "---------------------------------".to_string(),
155        );
156        libobs::obs_log_loaded_modules();
157        internal_log_global(
158            ObsLogLevel::Info,
159            "---------------------------------".to_string(),
160        );
161        libobs::obs_post_load_modules();
162        self.failed_modules.clear();
163        for i in 0..failure_info.count {
164            let module = failure_info.failed_modules.add(i);
165            if !module.is_null() && !(*module).is_null() {
166                self.failed_modules
167                    .push(CStr::from_ptr(*module).to_string_lossy().into_owned());
168            }
169        }
170        libobs::obs_module_failure_info_free(&mut failure_info);
171
172        self.log_if_failed();
173    }
174
175    #[cfg_attr(coverage_nightly, coverage(off))]
176    #[allow(unknown_lints)]
177    #[allow(ensure_obs_call_in_runtime)]
178    unsafe fn log_if_failed(&self) {
179        if self.failed_modules.is_empty() {
180            return;
181        }
182
183        internal_log_global(
184            ObsLogLevel::Warning,
185            format!("Failed to load modules: {}", self.failed_modules.join(", ")),
186        );
187    }
188}
189
190// Deferred cleanup always executes on the OBS owner thread.
191#[allow(unknown_lints)]
192#[allow(ensure_obs_call_in_runtime)]
193impl Drop for ObsModules {
194    fn drop(&mut self) {
195        log::trace!("Dropping ObsModules and removing module paths...");
196        let Some(runtime) = self.runtime.take() else {
197            return;
198        };
199        let data_path = self.paths.libobs_data_path().clone();
200        // Deferred cleanup runs on the OBS owner thread. Do not move `runtime` into it: the
201        // final runtime handle must not drop on the actor, where shutdown cannot be awaited.
202        runtime.defer_obs_cleanup(move || unsafe {
203            // SAFETY: Deferred cleanup executes on the OBS owner thread.
204            libobs::obs_remove_data_path(data_path.as_ptr().0);
205        });
206    }
207}