Skip to main content

libobs_wrapper\utils\info/
startup.rs

1use crate::{
2    context::ObsContext,
3    data::{audio::ObsAudioInfo, video::ObsVideoInfo},
4    logger::{ConsoleLogger, ObsLogger},
5    utils::{initialization::NixDisplay, ObsError, ObsPath, ObsString},
6};
7
8/// Contains information to start a libobs context.
9/// This is passed to the creation of `ObsContext`.
10///
11/// ## Platform Notes
12/// On Linux platforms, if your application uses a GUI
13/// framework (like GTK, Qt, etc.), it is crucial to set
14/// the appropriate `NixDisplay` in the `StartupInfo` **if you want to create a preview window**.
15/// This ensures that libobs can correctly interface with
16/// the display server (X11 or Wayland) used by your application.
17/// If this is not set, libobs will not be able to create a preview window and the application will crash.
18#[derive(Debug)]
19pub struct StartupInfo {
20    pub(crate) startup_paths: StartupPaths,
21    pub(crate) obs_video_info: ObsVideoInfo,
22    pub(crate) obs_audio_info: ObsAudioInfo,
23    pub(crate) module_config_path: Option<ObsString>,
24    // Option because logger is taken when creating
25    pub(crate) logger: Option<Box<dyn ObsLogger + Sync + Send>>,
26    pub(crate) start_glib_loop: bool,
27    pub(crate) nix_display: Option<NixDisplay>,
28}
29
30impl StartupInfo {
31    pub fn new() -> StartupInfo {
32        Self::default()
33    }
34
35    #[cfg_attr(coverage_nightly, coverage(off))]
36    pub fn set_startup_paths(mut self, paths: StartupPaths) -> Self {
37        self.startup_paths = paths;
38        self
39    }
40
41    pub fn set_video_info(mut self, ovi: ObsVideoInfo) -> Self {
42        self.obs_video_info = ovi;
43        self
44    }
45
46    /// Configures the audio subsystem used during normal [`StartupInfo::start`].
47    ///
48    /// The default is 44.1 kHz stereo with libobs-managed buffering. Use
49    /// [`ObsAudioInfo::new_low_latency`] only when lower latency is worth reduced buffering headroom.
50    pub fn set_audio_info(mut self, audio: ObsAudioInfo) -> Self {
51        self.obs_audio_info = audio;
52        self
53    }
54
55    /// Sets the root directory used by OBS modules for persistent configuration.
56    ///
57    /// libobs passes this value to modules through `obs_module_config_path`.
58    /// Callers embedding libobs should set an application-owned writable directory;
59    /// leaving it unset preserves libobs's `NULL` behavior, which can cause modules
60    /// that construct config paths to resolve relative to the process working directory.
61    pub fn set_module_config_path(mut self, path: ObsPath) -> Self {
62        self.module_config_path = Some(path.build());
63        self
64    }
65
66    #[cfg_attr(coverage_nightly, coverage(off))]
67    pub fn get_video_info(&self) -> &ObsVideoInfo {
68        &self.obs_video_info
69    }
70
71    /// Returns the audio configuration that will be passed to `obs_reset_audio2` at startup.
72    pub fn get_audio_info(&self) -> &ObsAudioInfo {
73        &self.obs_audio_info
74    }
75
76    #[cfg_attr(coverage_nightly, coverage(off))]
77    pub fn set_logger(mut self, logger: Box<dyn ObsLogger + Sync + Send>) -> Self {
78        self.logger = Some(logger);
79        self
80    }
81
82    #[cfg_attr(coverage_nightly, coverage(off))]
83    pub fn set_start_glib_loop(mut self, start: bool) -> Self {
84        self.start_glib_loop = start;
85        self
86    }
87
88    /// This sets the Nix display (X11 or Wayland) to use when starting libobs.
89    ///
90    /// This is **important** if your application creates any preview windows using libobs on Linux.
91    /// Otherwise if you don't plan to use preview windows **AND** are not using a GUI framework, you can skip this.
92    ///
93    /// Wayland requires this display to be the same as the one used by the GUI application (if you have one).
94    /// Failing to set this may result in libobs being unable to create preview windows,
95    ///
96    /// X11 however works without setting this display, in fact your window may become unresponsive if a display is set.
97    ///
98    /// # Safety
99    /// Make sure that the display is closed AFTER the whole OBS context has been dropped!
100    pub unsafe fn set_nix_display(mut self, display: NixDisplay) -> Self {
101        self.nix_display = Some(display);
102        self
103    }
104
105    #[cfg_attr(coverage_nightly, coverage(off))]
106    pub fn start(self) -> Result<ObsContext, ObsError> {
107        ObsContext::new(self)
108    }
109}
110
111impl Default for StartupInfo {
112    fn default() -> StartupInfo {
113        Self {
114            startup_paths: StartupPaths::default(),
115            obs_video_info: ObsVideoInfo::default(),
116            obs_audio_info: ObsAudioInfo::default(),
117            module_config_path: None,
118            logger: Some(Box::new(ConsoleLogger::new())),
119            start_glib_loop: true,
120            nix_display: None,
121        }
122    }
123}
124
125/// Contains the necessary paths for starting the
126/// libobs context built from `ObsPath`.
127///
128/// Note that these strings are copied when parsed,
129/// meaning that these can be freed immediately
130/// after all three strings have been used.
131#[derive(Clone, Debug)]
132pub struct StartupPaths {
133    libobs_data_path: ObsString,
134    plugin_bin_path: ObsString,
135    plugin_data_path: ObsString,
136}
137
138impl StartupPaths {
139    #[cfg_attr(coverage_nightly, coverage(off))]
140    pub fn new(
141        libobs_data_path: ObsPath,
142        plugin_bin_path: ObsPath,
143        plugin_data_path: ObsPath,
144    ) -> StartupPaths {
145        Self {
146            libobs_data_path: libobs_data_path.build(),
147            plugin_bin_path: plugin_bin_path.build(),
148            plugin_data_path: plugin_data_path.build(),
149        }
150    }
151
152    pub fn libobs_data_path(&self) -> &ObsString {
153        &(self.libobs_data_path)
154    }
155
156    pub fn plugin_bin_path(&self) -> &ObsString {
157        &(self.plugin_bin_path)
158    }
159
160    pub fn plugin_data_path(&self) -> &ObsString {
161        &(self.plugin_data_path)
162    }
163}
164
165impl Default for StartupPaths {
166    fn default() -> Self {
167        StartupPathsBuilder::new().build()
168    }
169}
170
171#[derive(Clone, Debug)]
172pub struct StartupPathsBuilder {
173    libobs_data_path: ObsPath,
174    plugin_bin_path: ObsPath,
175    plugin_data_path: ObsPath,
176}
177
178impl StartupPathsBuilder {
179    fn new() -> Self {
180        #[cfg(target_os = "windows")]
181        return Self {
182            libobs_data_path: ObsPath::from_relative("data/libobs"),
183            plugin_bin_path: ObsPath::from_relative("obs-plugins/64bit"),
184            plugin_data_path: ObsPath::from_relative("data/obs-plugins/%module%"),
185        };
186
187        #[cfg(target_os = "macos")]
188        return Self {
189            libobs_data_path: ObsPath::from_relative("data/libobs"),
190            plugin_bin_path: ObsPath::from_relative("obs-plugins/%module%.plugin/Contents/MacOS"),
191            plugin_data_path: ObsPath::from_relative("data/obs-plugins/%module%"),
192        };
193
194        #[cfg(target_os = "linux")]
195        {
196            let lib_path = match std::env::consts::ARCH {
197                "x86_64" => "/usr/lib/x86_64-linux-gnu",
198                "aarch64" => "/usr/lib/aarch64-linux-gnu",
199                "arm" => "/usr/lib/arm-linux-gnueabihf",
200                _ => "/usr/lib",
201            };
202
203            Self {
204                libobs_data_path: ObsPath::new("/usr/share/obs/libobs"),
205                plugin_bin_path: ObsPath::new(&(lib_path.to_string() + "/obs-plugins/%module%")),
206                plugin_data_path: ObsPath::new("/usr/share/obs/obs-plugins/%module%"),
207            }
208        }
209
210        #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
211        Self {
212            libobs_data_path: ObsPath::from_relative("data/libobs"),
213            plugin_bin_path: ObsPath::from_relative("obs-plugins/%module%"),
214            plugin_data_path: ObsPath::from_relative("data/obs-plugins/%module%"),
215        }
216    }
217
218    pub fn build(self) -> StartupPaths {
219        StartupPaths {
220            libobs_data_path: self.libobs_data_path.build(),
221            plugin_bin_path: self.plugin_bin_path.build(),
222            plugin_data_path: self.plugin_data_path.build(),
223        }
224    }
225
226    #[cfg_attr(coverage_nightly, coverage(off))]
227    pub fn libobs_data_path(mut self, value: ObsPath) -> Self {
228        self.libobs_data_path = value;
229        self
230    }
231
232    #[cfg_attr(coverage_nightly, coverage(off))]
233    pub fn plugin_bin_path(mut self, value: ObsPath) -> Self {
234        self.plugin_bin_path = value;
235        self
236    }
237
238    #[cfg_attr(coverage_nightly, coverage(off))]
239    pub fn plugin_data_path(mut self, value: ObsPath) -> Self {
240        self.plugin_data_path = value;
241        self
242    }
243}
244
245#[cfg_attr(coverage_nightly, coverage(off))]
246impl Default for StartupPathsBuilder {
247    fn default() -> StartupPathsBuilder {
248        Self::new()
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use crate::enums::{ObsSamplesPerSecond, ObsSpeakerLayout};
256
257    #[test]
258    fn startup_audio_configuration_is_retained_for_initialization() {
259        let audio = ObsAudioInfo::new(
260            ObsSamplesPerSecond::F48000,
261            ObsSpeakerLayout::Stereo,
262            35,
263            true,
264        );
265        let startup = StartupInfo::new().set_audio_info(audio.clone());
266
267        assert_eq!(startup.get_audio_info(), &audio);
268        assert_eq!(startup.obs_audio_info, audio);
269    }
270
271    #[test]
272    fn module_config_path_is_explicitly_configurable() {
273        let info =
274            StartupInfo::new().set_module_config_path(ObsPath::new("/tmp/clipture-obs-config"));
275        let configured = info
276            .module_config_path
277            .as_ref()
278            .expect("module config path should be retained");
279        assert_eq!(configured.to_string(), "/tmp/clipture-obs-config");
280    }
281}