Skip to main content

libobs_wrapper/
context.rs

1//! OBS Context Management
2//!
3//! This module provides the core functionality for interacting with libobs.
4//! The primary type is [`ObsContext`], which serves as the main entry point for
5//! all OBS operations.
6//!
7//! # Overview
8//!
9//! The `ObsContext` represents an initialized OBS environment and provides methods to:
10//! - Initialize the OBS runtime
11//! - Create and manage scenes
12//! - Create and manage outputs (recording, streaming)
13//! - Access and configure video/audio settings
14//! - Work with OBS runtimes prepared at build time or explicitly provisioned before initialization
15//!
16//! # Thread Safety
17//!
18//! OBS operations must be performed on a single thread. The `ObsContext` handles
19//! this requirement by creating a dedicated thread for OBS operations and providing
20//! a thread-safe interface to interact with it.
21//!
22//! # Examples
23//!
24//! Creating a basic OBS context:
25//!
26//! ```no_run
27//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
28//! use libobs_wrapper::context::ObsContext;
29//! use libobs_wrapper::utils::StartupInfo;
30//!
31//! let info = StartupInfo::default();
32//! let context = ObsContext::new(info)?;
33//! # Ok(())
34//! # }
35//! ```
36//!
37//! For more examples refer to the [examples](https://github.com/libobs-rs/libobs-rs/tree/main/examples) directory in the repository.
38
39mod registry;
40
41use std::{
42    ffi::CStr,
43    sync::{Arc, Condvar, Mutex, RwLock},
44    thread::ThreadId,
45};
46
47#[cfg(target_os = "linux")]
48use crate::utils::initialization::PlatformType;
49use crate::{
50    data::output::{ObsOutputTrait, ObsOutputTraitSealed, ObsReplayBufferOutputRef},
51    display::{ObsDisplayCreationData, ObsDisplayRef},
52};
53use crate::{
54    data::{audio::ObsAudioInfo, output::ObsOutputRef, video::ObsVideoInfo, ObsData},
55    enums::{ObsLogLevel, ObsResetVideoStatus, ObsSamplesPerSecond},
56    logger::LOGGER,
57    run_with_obs,
58    runtime::ObsRuntime,
59    scenes::ObsSceneRef,
60    sources::{ObsFilterRef, ObsSourceBuilder},
61    unsafe_send::Sendable,
62    utils::{FilterInfo, ObsError, ObsModules, ObsString, OutputInfo, StartupInfo},
63};
64use getters0::Getters;
65use libobs::{audio_output, video_output};
66use registry::ObjectRegistry;
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub(crate) enum ObsRuntimeState {
70    Idle,
71    Starting,
72    Active(ThreadId),
73    ShuttingDown,
74}
75
76lazy_static::lazy_static! {
77    static ref OBS_RUNTIME_STATE: (Mutex<ObsRuntimeState>, Condvar) =
78        (Mutex::new(ObsRuntimeState::Idle), Condvar::new());
79}
80
81pub(crate) fn reserve_runtime_slot() -> Result<(), ObsError> {
82    let (lock, changed) = &*OBS_RUNTIME_STATE;
83    let mut state = lock.lock().map_err(|_| ObsError::MutexFailure)?;
84    loop {
85        match *state {
86            ObsRuntimeState::Idle => {
87                *state = ObsRuntimeState::Starting;
88                return Ok(());
89            }
90            ObsRuntimeState::ShuttingDown => {
91                state = changed.wait(state).map_err(|_| ObsError::MutexFailure)?;
92            }
93            ObsRuntimeState::Starting | ObsRuntimeState::Active(_) => {
94                return Err(ObsError::ThreadFailure);
95            }
96        }
97    }
98}
99
100pub(crate) fn cancel_runtime_start() {
101    let (lock, changed) = &*OBS_RUNTIME_STATE;
102    let mut state = match lock.lock() {
103        Ok(state) => state,
104        Err(poisoned) => poisoned.into_inner(),
105    };
106    if *state == ObsRuntimeState::Starting {
107        *state = ObsRuntimeState::Idle;
108        changed.notify_all();
109    }
110}
111
112pub(crate) fn activate_runtime_slot(thread_id: ThreadId) -> Result<(), ObsError> {
113    let (lock, _) = &*OBS_RUNTIME_STATE;
114    let mut state = lock.lock().map_err(|_| ObsError::MutexFailure)?;
115    if *state != ObsRuntimeState::Starting {
116        return Err(ObsError::ThreadFailure);
117    }
118    *state = ObsRuntimeState::Active(thread_id);
119    Ok(())
120}
121
122pub(crate) fn begin_runtime_shutdown() {
123    let (lock, _) = &*OBS_RUNTIME_STATE;
124    match lock.lock() {
125        Ok(mut state) => {
126            if matches!(*state, ObsRuntimeState::Active(_)) {
127                *state = ObsRuntimeState::ShuttingDown;
128            }
129        }
130        Err(poisoned) => {
131            let mut state = poisoned.into_inner();
132            *state = ObsRuntimeState::ShuttingDown;
133        }
134    }
135}
136
137pub(crate) fn release_runtime_slot() -> Result<(), ObsError> {
138    let (lock, changed) = &*OBS_RUNTIME_STATE;
139    let mut state = lock.lock().map_err(|_| ObsError::MutexFailure)?;
140    *state = ObsRuntimeState::Idle;
141    changed.notify_all();
142    Ok(())
143}
144
145/// Interface to the process-global OBS context.
146///
147/// Context-level native objects are owned by an internal registry. Each native handle
148/// retains the runtime independently, so correctness does not depend on Rust struct
149/// field declaration order.
150#[derive(Debug, Getters, Clone)]
151#[skip_new]
152pub struct ObsContext {
153    /// Test-environment bookkeeping of live contexts; see [`test_shutdown`]. Declared first so
154    /// it is released before this context's runtime handles drop.
155    #[cfg(all(feature = "enable_runtime", any(test, feature = "__test_environment")))]
156    #[skip_getter]
157    _live_context: Arc<test_shutdown::LiveContextToken>,
158
159    /// Keeps C-referenced startup configuration alive for the OBS lifetime.
160    startup_info: Arc<RwLock<StartupInfo>>,
161
162    #[skip_getter]
163    objects: Arc<ObjectRegistry>,
164
165    #[skip_getter]
166    _obs_modules: Arc<ObsModules>,
167
168    runtime: ObsRuntime,
169
170    #[cfg(target_os = "linux")]
171    glib_loop: Arc<RwLock<Option<crate::utils::linux::LinuxGlibLoop>>>,
172}
173
174/// Test-environment-only shutdown synchronization.
175///
176/// The final runtime handle may otherwise be released on the OBS actor (by queued deferred
177/// cleanup that owns another wrapper object), where shutdown cannot be joined. Then nothing
178/// waits for `obs_shutdown`: a test can return and the process run its exit handlers while
179/// OBS threads are still alive (crashing in OpenSSL, EGL or Mesa teardown), and a context
180/// created right after can still find the slot `Active`.
181///
182/// To prevent that, dropping a runtime handle off the actor while no `ObsContext` is alive
183/// first flushes the deferred-cleanup queue (see `ObsRuntime`'s test-environment `Drop`).
184/// Queued closures then release their handles before this one, so the final handle drops
185/// on a regular thread, which joins the actor through shutdown.
186#[cfg(all(feature = "enable_runtime", any(test, feature = "__test_environment")))]
187pub(crate) mod test_shutdown {
188    use std::sync::atomic::{AtomicUsize, Ordering};
189
190    static LIVE_CONTEXTS: AtomicUsize = AtomicUsize::new(0);
191
192    pub(crate) fn no_live_contexts() -> bool {
193        LIVE_CONTEXTS.load(Ordering::Acquire) == 0
194    }
195
196    /// Held (behind an `Arc`) by every `ObsContext` clone family.
197    #[derive(Debug)]
198    pub(crate) struct LiveContextToken(());
199
200    impl LiveContextToken {
201        pub(crate) fn new() -> Self {
202            LIVE_CONTEXTS.fetch_add(1, Ordering::AcqRel);
203            Self(())
204        }
205    }
206
207    impl Drop for LiveContextToken {
208        fn drop(&mut self) {
209            LIVE_CONTEXTS.fetch_sub(1, Ordering::AcqRel);
210        }
211    }
212}
213
214impl ObsContext {
215    /// Checks if the installed OBS version matches the expected version.
216    /// Returns true if the major version matches, false otherwise.
217    pub fn check_version_compatibility() -> bool {
218        // SAFETY: libobs returns a static NUL-terminated version string independent of
219        // initialization. The loaded library retains it; the null check precedes CStr access.
220        unsafe {
221            #[allow(unknown_lints)]
222            #[allow(ensure_obs_call_in_runtime)]
223            let version = libobs::obs_get_version_string();
224            if version.is_null() {
225                return false;
226            }
227
228            let version_str = match CStr::from_ptr(version).to_str() {
229                Ok(s) => s,
230                Err(_) => return false,
231            };
232
233            let version_parts: Vec<&str> = version_str.split('.').collect();
234            if version_parts.len() != 3 {
235                return false;
236            }
237
238            let major = match version_parts[0].parse::<u64>() {
239                Ok(v) => v,
240                Err(_) => return false,
241            };
242
243            major == libobs::LIBOBS_API_MAJOR_VER as u64
244        }
245    }
246
247    pub fn builder() -> StartupInfo {
248        StartupInfo::new()
249    }
250
251    /// Initializes libobs on the current thread.
252    ///
253    /// Note that there can be only one ObsContext
254    /// initialized at a time. This is because
255    /// libobs is not completely thread-safe.
256    ///
257    /// Also note that this might leak a very tiny
258    /// amount of memory. As a result, it is
259    /// probably a good idea not to restart the
260    /// OBS context repeatedly over a very long
261    /// period of time. Unfortunately the memory
262    /// leak is caused by a bug in libobs itself.
263    ///
264    /// On Linux, make sure to call `ObsContext::check_version_compatibility` before
265    /// initializing the context. If that method returns false, it may be possible for the binary to crash.
266    ///
267    /// If initialization fails, an `ObsError` is returned.
268    pub fn new(info: StartupInfo) -> Result<ObsContext, ObsError> {
269        log::trace!("Getting version number...");
270
271        #[allow(unknown_lints)]
272        #[allow(ensure_obs_call_in_runtime)]
273        // Safety: This is fine, we are just getting a version number, which does not require
274        // to be on the OBS thread.
275        let version_numb = unsafe { libobs::obs_get_version() };
276        if version_numb == 0 {
277            return Err(ObsError::InvalidDll);
278        }
279
280        // Spawning runtime, I'll keep this as function for now
281        let (runtime, obs_modules, info) = ObsRuntime::startup(info)?;
282        #[cfg(target_os = "linux")]
283        let linux_opt = if info.start_glib_loop {
284            Some(crate::utils::linux::LinuxGlibLoop::new())
285        } else {
286            None
287        };
288
289        Ok(Self {
290            _obs_modules: Arc::new(obs_modules),
291            objects: Arc::new(ObjectRegistry::default()),
292            runtime: runtime.clone(),
293            startup_info: Arc::new(RwLock::new(info)),
294            #[cfg(target_os = "linux")]
295            glib_loop: Arc::new(RwLock::new(linux_opt)),
296            #[cfg(all(feature = "enable_runtime", any(test, feature = "__test_environment")))]
297            _live_context: Arc::new(test_shutdown::LiveContextToken::new()),
298        })
299    }
300
301    #[cfg(target_os = "linux")]
302    pub fn get_platform(&self) -> Result<PlatformType, ObsError> {
303        self.runtime.get_platform()
304    }
305
306    pub fn get_version(&self) -> Result<String, ObsError> {
307        Self::get_version_global()
308    }
309
310    pub fn get_version_global() -> Result<String, ObsError> {
311        unsafe {
312            #[allow(unknown_lints)]
313            #[allow(ensure_obs_call_in_runtime)]
314            // Safety: This is fine, it just returns a globally allocated variable
315            let version = libobs::obs_get_version_string();
316            if version.is_null() {
317                return Err(ObsError::NullPointer(Some(
318                    "OBS version string".to_string(),
319                )));
320            }
321            let version_cstr = CStr::from_ptr(version);
322            Ok(version_cstr.to_string_lossy().into_owned())
323        }
324    }
325
326    pub fn log(&self, level: ObsLogLevel, msg: &str) {
327        let mut log = LOGGER
328            .lock()
329            .unwrap_or_else(|poisoned| poisoned.into_inner());
330        log.log(level, msg.to_string());
331    }
332
333    /// Resets the OBS video context. This is often called
334    /// when one wants to change a setting related to the
335    /// OBS video info sent on startup.
336    ///
337    /// It is important to register your video encoders to
338    /// a video handle after you reset the video context
339    /// if you are using a video handle other than the
340    /// main video handle. For convenience, this function
341    /// sets all video encoder back to the main video handler
342    /// by default.
343    ///
344    /// Note that you cannot reset the graphics module
345    /// without destroying the entire OBS context. Trying
346    /// so will result in an error.
347    pub fn reset_video(&mut self, ovi: ObsVideoInfo) -> Result<(), ObsError> {
348        // You cannot change the graphics module without
349        // completely destroying the entire OBS context.
350        if self
351            .startup_info
352            .read()
353            .map_err(|_| {
354                ObsError::LockError("Failed to acquire read lock on startup info".to_string())
355            })?
356            .obs_video_info
357            .graphics_module()
358            != ovi.graphics_module()
359        {
360            return Err(ObsError::ResetVideoFailureGraphicsModule);
361        }
362
363        if self.objects.any_output_active()? {
364            return Err(ObsError::ResetVideoFailureOutputActive);
365        }
366
367        // Resets the video context. Note that this
368        // is similar to Self::reset_video, but it
369        // does not call that function because the
370        // ObsContext struct is not created yet,
371        // and also because there is no need to free
372        // anything tied to the OBS context.
373        let vid_ptr = Sendable(ovi.as_ptr());
374        let reset_video_status = run_with_obs!(self.runtime, (vid_ptr), move || unsafe {
375            // Safety: OVI is still in scope, so the pointer is valid as well.
376            libobs::obs_reset_video(vid_ptr.0)
377        })?;
378
379        let reset_video_status = num_traits::FromPrimitive::from_i32(reset_video_status);
380
381        let reset_video_status = match reset_video_status {
382            Some(x) => x,
383            None => ObsResetVideoStatus::Failure,
384        };
385
386        if reset_video_status == ObsResetVideoStatus::Success {
387            self.startup_info
388                .write()
389                .map_err(|_| {
390                    ObsError::LockError("Failed to acquire write lock on startup info".to_string())
391                })?
392                .obs_video_info = ovi;
393
394            Ok(())
395        } else {
396            Err(ObsError::ResetVideoFailure(reset_video_status))
397        }
398    }
399
400    /// Returns a pointer to the video output.
401    ///
402    /// # Safety
403    /// This function is unsafe because it returns a raw pointer that must be handled carefully. Only use this pointer if you REALLY know what you are doing.
404    pub unsafe fn get_video_ptr(&self) -> Result<*mut video_output, ObsError> {
405        // Removed safeguards here because ptr are not sendable and this OBS context should never be used across threads
406        run_with_obs!(self.runtime, || unsafe {
407            // Safety: This can be called as long as OBS hasn't shutdown, which it hasn't.
408            Sendable(libobs::obs_get_video())
409        })
410        .map(|ptr| ptr.0)
411    }
412
413    /// Returns a pointer to the audio output.
414    ///
415    /// # Safety
416    /// This function is unsafe because it returns a raw pointer that must be handled carefully. Only use this pointer if you REALLY know what you are doing.
417    pub unsafe fn get_audio_ptr(&self) -> Result<*mut audio_output, ObsError> {
418        // Removed safeguards here because ptr are not sendable and this OBS context should never be used across threads
419        run_with_obs!(self.runtime, || unsafe {
420            // Safety: This can be called as long as OBS hasn't shutdown, which it hasn't.
421            Sendable(libobs::obs_get_audio())
422        })
423        .map(|ptr| ptr.0)
424    }
425
426    pub fn data(&self) -> Result<ObsData, ObsError> {
427        ObsData::new(self.runtime.clone())
428    }
429
430    pub fn replay_buffer(
431        &mut self,
432        info: OutputInfo,
433    ) -> Result<ObsReplayBufferOutputRef, ObsError> {
434        let output = ObsReplayBufferOutputRef::new(info, self.runtime.clone());
435
436        match output {
437            Ok(x) => {
438                let tmp = x.clone();
439                self.objects.add_output(x)?;
440                Ok(tmp)
441            }
442
443            Err(x) => Err(x),
444        }
445    }
446
447    pub fn output(&mut self, info: OutputInfo) -> Result<ObsOutputRef, ObsError> {
448        let output = ObsOutputRef::new(info, self.runtime.clone());
449
450        match output {
451            Ok(x) => {
452                let tmp = x.clone();
453                self.objects.add_output(x)?;
454                Ok(tmp)
455            }
456
457            Err(x) => Err(x),
458        }
459    }
460
461    pub fn obs_filter(&mut self, info: FilterInfo) -> Result<ObsFilterRef, ObsError> {
462        let filter = ObsFilterRef::new(
463            info.id,
464            info.name,
465            info.settings,
466            info.hotkey_data,
467            self.runtime.clone(),
468        );
469
470        match filter {
471            Ok(x) => {
472                let tmp = x.clone();
473                self.objects.add_filter(x)?;
474                Ok(tmp)
475            }
476
477            Err(x) => Err(x),
478        }
479    }
480
481    /// Returns the audio configuration currently active inside libobs.
482    ///
483    /// This queries `obs_get_audio_info2` rather than merely returning the startup builder value,
484    /// so callers can verify the sample rate, speaker layout and buffering policy that libobs
485    /// accepted during startup.
486    pub fn audio_info(&self) -> Result<ObsAudioInfo, ObsError> {
487        let runtime = self.runtime.clone();
488        run_with_obs!(runtime, (), move || unsafe {
489            // Safety: the output struct is local and initialized by libobs on the owning runtime.
490            let mut native: libobs::obs_audio_info2 = std::mem::zeroed();
491            if !libobs::obs_get_audio_info2(&mut native) {
492                return Err(ObsError::InvalidOperation(
493                    "libobs has no active audio configuration".into(),
494                ));
495            }
496
497            let samples = match native.samples_per_sec {
498                44_100 => ObsSamplesPerSecond::F44100,
499                48_000 => ObsSamplesPerSecond::F48000,
500                other => {
501                    return Err(ObsError::EnumConversionError(format!(
502                        "unsupported active OBS sample rate {other}"
503                    )));
504                }
505            };
506            // C enums are `i32` in the MSVC bindings and `u32` elsewhere.
507            #[allow(clippy::unnecessary_cast)]
508            let speakers =
509                num_traits::FromPrimitive::from_u32(native.speakers as u32).ok_or_else(|| {
510                    ObsError::EnumConversionError(format!(
511                        "unknown active OBS speaker layout {}",
512                        native.speakers
513                    ))
514                })?;
515            Ok(ObsAudioInfo::new(
516                samples,
517                speakers,
518                native.max_buffering_ms,
519                native.fixed_buffering,
520            ))
521        })?
522    }
523
524    /// Creates a new display and returns its ID.
525    ///
526    /// You must call `update_color_space` on the display when the window is moved, resized or the display settings change.
527    ///
528    /// Note: When calling `set_size` or `set_pos`, `update_color_space` is called automatically.
529    ///
530    /// Another note: On Linux, this method is unsafe because you must ensure that every display reference is dropped before your window exits.
531    #[cfg(not(target_os = "linux"))]
532    pub fn display(&mut self, data: ObsDisplayCreationData) -> Result<ObsDisplayRef, ObsError> {
533        self.inner_display_fn(data)
534    }
535
536    /// Creates a new display and returns its ID.
537    ///
538    /// You must call `update_color_space` on the display when the window is moved, resized or the display settings change.
539    ///
540    /// # Safety
541    /// All references of the `ObsDisplayRef` **MUST** be dropped before your window closes, otherwise you **will** have crashes.
542    /// This includes calling `remove_display` or `remove_display_by_id` to remove the display from the context.
543    ///
544    /// Also on X11, make sure that the provided window handle was created using the same display as the one provided in the `NixDisplay` in the `StartupInfo`.
545    ///
546    /// Note: When calling `set_size` or `set_pos`, `update_color_space` is called automatically.
547    #[cfg(target_os = "linux")]
548    pub unsafe fn display(
549        &mut self,
550        data: ObsDisplayCreationData,
551    ) -> Result<ObsDisplayRef, ObsError> {
552        self.inner_display_fn(data)
553    }
554
555    /// This function is used internally to create displays.
556    fn inner_display_fn(
557        &mut self,
558        data: ObsDisplayCreationData,
559    ) -> Result<ObsDisplayRef, ObsError> {
560        #[cfg(target_os = "linux")]
561        {
562            // We'll need to check if a custom display was provided because libobs will crash if the display didn't create the window the user is giving us
563            // X11 allows having a separate display however.
564            let nix_display = self
565                .startup_info
566                .read()
567                .map_err(|_| {
568                    ObsError::LockError("Failed to acquire read lock on startup info".to_string())
569                })?
570                .nix_display
571                .clone();
572
573            let is_wayland_handle = data.window_handle.is_wayland;
574            if is_wayland_handle && nix_display.is_none() {
575                return Err(ObsError::DisplayCreationError(
576                    "Wayland window handle provided but no NixDisplay was set in StartupInfo."
577                        .to_string(),
578                ));
579            }
580
581            if let Some(nix_display) = &nix_display {
582                if is_wayland_handle {
583                    match nix_display {
584                        crate::utils::NixDisplay::X11(_display) => {
585                            return Err(ObsError::DisplayCreationError(
586                                "Provided NixDisplay is X11, but the window handle is Wayland."
587                                    .to_string(),
588                            ));
589                        }
590                        crate::utils::NixDisplay::Wayland(display) => {
591                            use crate::utils::linux::wl_proxy_get_display;
592                            if !data.window_handle.is_wayland {
593                                return Err(ObsError::DisplayCreationError(
594                            "Provided window handle is not a Wayland handle, but the NixDisplay is Wayland.".to_string(),
595                        ));
596                            }
597
598                            let surface_handle = data.window_handle.window.0.display;
599                            let display_from_surface = unsafe {
600                                // Safety: The display handle is valid as long as the surface is valid.
601                                wl_proxy_get_display(surface_handle)
602                            };
603                            if let Err(e) = display_from_surface {
604                                log::warn!(
605                                    "Could not get display from surface handle on wayland. Make sure your wayland client is at least version 1.23. Error: {:?}",
606                                    e
607                                );
608                            } else if let Ok(display_from_surface) = display_from_surface {
609                                if display_from_surface != display.as_ptr() {
610                                    return Err(ObsError::DisplayCreationError(
611                            "Provided surface handle's Wayland display does not match the NixDisplay's Wayland display.".to_string(),
612                        ));
613                                }
614                            }
615                        }
616                    }
617                }
618            }
619        }
620
621        let display = ObsDisplayRef::new(data, self.runtime.clone())
622            .map_err(|e| ObsError::DisplayCreationError(e.to_string()))?;
623
624        self.objects.add_display(display.clone())?;
625        Ok(display)
626    }
627
628    pub fn remove_display(&mut self, display: &ObsDisplayRef) -> Result<(), ObsError> {
629        self.remove_display_by_id(display.id())
630    }
631
632    pub fn remove_display_by_id(&mut self, id: usize) -> Result<(), ObsError> {
633        self.objects.remove_display(id)
634    }
635
636    pub fn get_display_by_id(&self, id: usize) -> Result<Option<ObsDisplayRef>, ObsError> {
637        self.objects.display(id)
638    }
639
640    pub fn get_output(&self, name: &str) -> Result<Option<Arc<dyn ObsOutputTrait>>, ObsError> {
641        self.objects.output(name)
642    }
643
644    pub fn update_output(&self, name: &str, settings: ObsData) -> Result<(), ObsError> {
645        self.objects
646            .output(name)?
647            .ok_or(ObsError::OutputNotFound)?
648            .update_settings(settings)
649    }
650
651    pub fn get_filter(&self, name: &str) -> Result<Option<ObsFilterRef>, ObsError> {
652        self.objects.filter(name)
653    }
654
655    /// Creates a new scene
656    ///
657    /// If the channel is provided, the scene will be set to that output channel.
658    ///
659    /// There are 64 channels that you can assign scenes to,
660    /// which will draw on top of each other in ascending index order
661    /// when a output is rendered.
662    ///
663    /// # Arguments
664    /// * `name` - The name of the scene. This must be unique.
665    /// * `channel` - Optional channel to bind the scene to. If provided, the scene will be set as active for that channel.
666    ///
667    /// # Returns
668    /// A Result containing the new ObsSceneRef or an error
669    pub fn scene<T: Into<ObsString> + Send + Sync>(
670        &mut self,
671        name: T,
672        channel: Option<u32>,
673    ) -> Result<ObsSceneRef, ObsError> {
674        let scene = ObsSceneRef::new(name.into(), self.runtime.clone())?;
675
676        let tmp = scene.clone();
677        self.objects.add_scene(scene)?;
678
679        if let Some(channel) = channel {
680            tmp.set_to_channel(channel)?;
681        }
682        Ok(tmp)
683    }
684
685    pub fn get_scene(&self, name: &str) -> Result<Option<ObsSceneRef>, ObsError> {
686        self.objects.scene(name)
687    }
688
689    /// Returns a snapshot of all scenes currently managed by this context.
690    pub fn scenes(&self) -> Result<Vec<ObsSceneRef>, ObsError> {
691        self.objects.scenes()
692    }
693
694    pub fn source_builder<T: ObsSourceBuilder, K: Into<ObsString> + Send + Sync>(
695        &self,
696        name: K,
697    ) -> Result<T, ObsError> {
698        T::new(name.into(), self.runtime.clone())
699    }
700}