Skip to main content

libobs_wrapper\encoders/
audio.rs

1use libobs::audio_output;
2use std::{
3    ptr,
4    sync::{Arc, RwLock},
5};
6
7use crate::{
8    data::{
9        audio::AudioMixIndex,
10        object::{inner_fn_update_settings, ObsObjectTrait, ObsObjectTraitPrivate},
11        ImmutableObsData, ObsDataPointers,
12    },
13    encoders::{_ObsEncoderDropGuard, ObsEncoderTrait},
14    run_with_obs,
15    runtime::ObsRuntime,
16    unsafe_send::{Sendable, SmartPointerSendable},
17    utils::{AudioEncoderInfo, ObsError, ObsString},
18};
19
20#[derive(Clone, Debug)]
21#[allow(dead_code)]
22/// Represents a audio encoder. If this struct is not referenced anywhere anymore,
23/// this Audio Encoder will get removed. Note: The output internally stores the ObsAudioEncoder, once it was
24/// added to the output
25pub struct ObsAudioEncoder {
26    pub(crate) id: ObsString,
27    pub(crate) name: ObsString,
28    pub(crate) settings: Arc<RwLock<ImmutableObsData>>,
29    pub(crate) hotkey_data: Arc<RwLock<ImmutableObsData>>,
30    pub(crate) runtime: ObsRuntime,
31    pub(crate) encoder: SmartPointerSendable<*mut libobs::obs_encoder_t>,
32    mix_index: AudioMixIndex,
33}
34
35impl ObsAudioEncoder {
36    /// Creates an audio encoder for a native OBS mix.
37    ///
38    /// The historical `mixer_idx` argument identifies the **source mix the encoder reads from**;
39    /// it is not an output attachment slot. Prefer [`Self::new_from_info_for_mix`] in new code.
40    pub fn new_from_info(
41        info: AudioEncoderInfo,
42        mixer_idx: usize,
43        runtime: ObsRuntime,
44    ) -> Result<Arc<Self>, ObsError> {
45        Self::new_from_info_for_mix(info, AudioMixIndex::new(mixer_idx)?, runtime)
46    }
47
48    /// Creates an audio encoder that reads from the selected native OBS audio mix.
49    pub fn new_from_info_for_mix(
50        info: AudioEncoderInfo,
51        mix_index: AudioMixIndex,
52        runtime: ObsRuntime,
53    ) -> Result<Arc<Self>, ObsError> {
54        let AudioEncoderInfo {
55            id,
56            name,
57            settings,
58            hotkey_data,
59        } = info;
60
61        let settings_ptr = settings.as_ref().map(|s| s.as_ptr());
62        let hotkey_data_ptr = hotkey_data.as_ref().map(|h| h.as_ptr());
63
64        let encoder = run_with_obs!(
65            runtime,
66            (id, name, settings_ptr, hotkey_data_ptr),
67            move || {
68                let settings_ptr_raw = match settings_ptr {
69                    Some(s) => s.get_ptr(),
70                    None => ptr::null_mut(),
71                };
72
73                let hotkey_data_ptr_raw = match hotkey_data_ptr {
74                    Some(h) => h.get_ptr(),
75                    None => ptr::null_mut(),
76                };
77
78                let ptr = unsafe {
79                    // Safety: All pointers are in the current scope and therefore valid.
80                    libobs::obs_audio_encoder_create(
81                        id.as_ptr().0,
82                        name.as_ptr().0,
83                        settings_ptr_raw,
84                        mix_index.index(),
85                        hotkey_data_ptr_raw,
86                    )
87                };
88
89                if ptr.is_null() {
90                    Err(ObsError::NullPointer(None))
91                } else {
92                    Ok(Sendable(ptr))
93                }
94            }
95        )??;
96
97        let encoder = SmartPointerSendable::new(
98            encoder.0,
99            Arc::new(_ObsEncoderDropGuard {
100                encoder,
101                runtime: runtime.clone(),
102            }),
103            runtime.native_registry(),
104        );
105
106        let settings = {
107            let settings_ptr = run_with_obs!(runtime, (encoder), move || unsafe {
108                // Safety: We are using a smart pointer to ensure that the encoder pointer is valid
109                Sendable(libobs::obs_encoder_get_settings(encoder.get_ptr()))
110            })?;
111
112            ImmutableObsData::from_raw_pointer(settings_ptr, runtime.clone())
113        };
114
115        let hotkey_data = match hotkey_data {
116            Some(h) => h,
117            None => ImmutableObsData::new(&runtime)?,
118        };
119
120        Ok(Arc::new(Self {
121            encoder,
122            id,
123            name,
124            settings: Arc::new(RwLock::new(settings)),
125            hotkey_data: Arc::new(RwLock::new(hotkey_data)),
126            runtime,
127            mix_index,
128        }))
129    }
130
131    /// Native OBS audio mix this encoder reads from.
132    pub fn mix_index(&self) -> AudioMixIndex {
133        self.mix_index
134    }
135
136    /// This is only needed once for global audio context
137    /// # Safety
138    /// You must ensure that the `handler` pointer is valid and lives as long as this function call.
139    pub unsafe fn set_audio_context(&self, handler: *mut audio_output) -> Result<(), ObsError> {
140        let handler = Sendable(handler);
141        let encoder_ptr = self.encoder.clone();
142
143        run_with_obs!(self.runtime, (handler, encoder_ptr), move || {
144            unsafe {
145                // Safety: Caller made sure that handler is valid and encoder_ptr is valid because of a SmartPointer
146                libobs::obs_encoder_set_audio(encoder_ptr.get_ptr(), handler.0)
147            }
148        })
149    }
150}
151
152impl ObsObjectTraitPrivate for ObsAudioEncoder {
153    fn __internal_replace_settings(&self, settings: ImmutableObsData) -> Result<(), ObsError> {
154        self.settings
155            .write()
156            .map_err(|_| {
157                ObsError::LockError(
158                    "Failed to acquire lock for replacing settings in the audio encoder".into(),
159                )
160            })
161            .map(|mut guard| {
162                *guard = settings;
163            })
164    }
165
166    fn __internal_replace_hotkey_data(
167        &self,
168        hotkey_data: ImmutableObsData,
169    ) -> Result<(), ObsError> {
170        self.hotkey_data
171            .write()
172            .map_err(|_| {
173                ObsError::LockError(
174                    "Failed to acquire lock for replacing hotkey data in the audio encoder".into(),
175                )
176            })
177            .map(|mut guard| {
178                *guard = hotkey_data;
179            })
180    }
181}
182
183impl ObsObjectTrait for ObsAudioEncoder {
184    type Native = *mut libobs::obs_encoder;
185
186    fn __native_handle(&self) -> SmartPointerSendable<Self::Native> {
187        self.encoder.clone()
188    }
189
190    fn runtime(&self) -> &ObsRuntime {
191        &self.runtime
192    }
193
194    fn settings(&self) -> Result<ImmutableObsData, ObsError> {
195        self.settings
196            .read()
197            .map_err(|_| {
198                ObsError::LockError("Failed to acquire read lock on audio encoder settings".into())
199            })
200            .map(|s| s.clone())
201    }
202
203    fn hotkey_data(&self) -> Result<ImmutableObsData, ObsError> {
204        self.hotkey_data
205            .read()
206            .map_err(|_| {
207                ObsError::LockError(
208                    "Failed to acquire read lock on audio encoder hotkey data".into(),
209                )
210            })
211            .map(|h| h.clone())
212    }
213
214    fn id(&self) -> ObsString {
215        self.id.clone()
216    }
217
218    fn name(&self) -> ObsString {
219        self.name.clone()
220    }
221
222    fn update_settings(&self, settings: crate::data::ObsData) -> Result<(), ObsError> {
223        if self.is_active()? {
224            return Err(ObsError::EncoderActive);
225        }
226
227        inner_fn_update_settings!(self, libobs::obs_encoder_update, settings)
228    }
229}
230
231impl ObsEncoderTrait for ObsAudioEncoder {}