libobs_wrapper/
audio_monitoring.rs1use 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#[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
38unsafe extern "C" fn collect_monitoring_device(
43 data: *mut c_void,
44 name: *const c_char,
45 id: *const c_char,
46) -> bool {
47 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 let name = unsafe { CStr::from_ptr(name) }
56 .to_string_lossy()
57 .into_owned();
58 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 pub fn audio_monitoring_available(&self) -> Result<bool, ObsError> {
67 let runtime = self.runtime().clone();
68 run_with_obs!(runtime, (), move || unsafe {
69 libobs::obs_audio_monitoring_available()
71 })
72 }
73
74 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 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 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 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 name: unsafe { CStr::from_ptr(name) }
106 .to_string_lossy()
107 .into_owned(),
108 id: unsafe { CStr::from_ptr(id) }.to_string_lossy().into_owned(),
110 })
111 })
112 }
113
114 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 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}