Skip to main content

libobs_wrapper/
audio_monitoring.rs

1//! Global OBS audio-monitoring device discovery and selection.
2
3use std::{
4    ffi::{c_char, c_void, CStr},
5    ptr,
6};
7
8use crate::{
9    context::ObsContext,
10    run_with_obs,
11    utils::{ObsError, ObsString},
12};
13
14/// One monitoring output device reported by libobs.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct AudioMonitoringDevice {
17    name: String,
18    id: String,
19}
20
21impl AudioMonitoringDevice {
22    pub fn new(name: impl Into<String>, id: impl Into<String>) -> Self {
23        Self {
24            name: name.into(),
25            id: id.into(),
26        }
27    }
28
29    pub fn name(&self) -> &str {
30        &self.name
31    }
32
33    pub fn id(&self) -> &str {
34        &self.id
35    }
36}
37
38/// # Safety
39/// libobs must call this only during the synchronous enumeration performed by
40/// `audio_monitoring_devices`. `data` must point to that call's live device Vec, and non-null
41/// `name`/`id` values must be callback-borrowed NUL-terminated strings.
42unsafe extern "C" fn collect_monitoring_device(
43    data: *mut c_void,
44    name: *const c_char,
45    id: *const c_char,
46) -> bool {
47    // SAFETY: callback registration supplies `data` as a pointer to a live Vec for this call.
48    let Some(devices) = (unsafe { (data as *mut Vec<AudioMonitoringDevice>).as_mut() }) else {
49        return false;
50    };
51    if name.is_null() || id.is_null() {
52        return true;
53    }
54    // SAFETY: null was rejected above and libobs provides a C string for this callback.
55    let name = unsafe { CStr::from_ptr(name) }
56        .to_string_lossy()
57        .into_owned();
58    // SAFETY: null was rejected above and libobs provides a C string for this callback.
59    let id = unsafe { CStr::from_ptr(id) }.to_string_lossy().into_owned();
60    devices.push(AudioMonitoringDevice { name, id });
61    true
62}
63
64impl ObsContext {
65    /// Returns whether this libobs build/platform exposes an audio monitoring backend.
66    pub fn audio_monitoring_available(&self) -> Result<bool, ObsError> {
67        let runtime = self.runtime().clone();
68        run_with_obs!(runtime, (), move || unsafe {
69            // Safety: process-global query executed on the OBS actor.
70            libobs::obs_audio_monitoring_available()
71        })
72    }
73
74    /// Enumerates monitoring devices synchronously and copies native strings before returning.
75    pub fn audio_monitoring_devices(&self) -> Result<Vec<AudioMonitoringDevice>, ObsError> {
76        let runtime = self.runtime().clone();
77        run_with_obs!(runtime, (), move || {
78            let mut devices = Vec::new();
79            unsafe {
80                // Safety: libobs enumerates synchronously; the Vec lives for all callbacks.
81                libobs::obs_enum_audio_monitoring_devices(
82                    Some(collect_monitoring_device),
83                    &mut devices as *mut _ as *mut c_void,
84                );
85            }
86            devices
87        })
88    }
89
90    /// Returns the currently selected monitoring device, if libobs supplies one.
91    pub fn audio_monitoring_device(&self) -> Result<Option<AudioMonitoringDevice>, ObsError> {
92        let runtime = self.runtime().clone();
93        run_with_obs!(runtime, (), move || {
94            let mut name = ptr::null();
95            let mut id = ptr::null();
96            unsafe {
97                // Safety: libobs writes borrowed strings; they are copied before returning.
98                libobs::obs_get_audio_monitoring_device(&mut name, &mut id);
99            }
100            if name.is_null() || id.is_null() {
101                return None;
102            }
103            Some(AudioMonitoringDevice {
104                // SAFETY: both pointers were checked for null and remain valid for this actor call.
105                name: unsafe { CStr::from_ptr(name) }
106                    .to_string_lossy()
107                    .into_owned(),
108                // SAFETY: both pointers were checked for null and remain valid for this actor call.
109                id: unsafe { CStr::from_ptr(id) }.to_string_lossy().into_owned(),
110            })
111        })
112    }
113
114    /// Selects the global audio monitoring device used by sources in monitor modes.
115    pub fn set_audio_monitoring_device(
116        &self,
117        device: &AudioMonitoringDevice,
118    ) -> Result<(), ObsError> {
119        let name = ObsString::new(device.name());
120        let id = ObsString::new(device.id());
121        let runtime = self.runtime().clone();
122        let selected = run_with_obs!(runtime, (name, id), move || unsafe {
123            // Safety: strings are retained for the complete synchronous actor call.
124            libobs::obs_set_audio_monitoring_device(name.as_ptr().0, id.as_ptr().0)
125        })?;
126        if selected {
127            Ok(())
128        } else {
129            Err(ObsError::InvalidOperation(format!(
130                "OBS rejected audio monitoring device '{}' ({})",
131                device.name(),
132                device.id()
133            )))
134        }
135    }
136}