Skip to main content

libobs_wrapper\data\output/
mod.rs

1//! Managed OBS outputs and validated output composition.
2//!
3//! # Which level should I use?
4//!
5//! Prefer [`ObsOutputPipelineBuilder`] when creating a complete encoded output: it validates the
6//! selected output flags, codecs, protocol/service, audio mixer indices, and runtime affinity before
7//! native creation.
8//!
9//! Use [`ObsOutputComposition`] / [`ObsOutputTrait`] when an application intentionally needs to
10//! inspect or replace encoder/service attachments on an existing output. Attachment storage and
11//! lifecycle serialization are implementation details; public callers work through behavior only.
12//!
13//! Pair this module with [`crate::capabilities`] to choose concrete implementations from the OBS
14//! plugins available at runtime. For conventional recording or RTMP streaming, `libobs-simple`
15//! provides a shorter opinionated path.
16
17use libobs::obs_output;
18use std::collections::HashMap;
19use std::ptr;
20use std::sync::{Arc, Mutex, RwLock};
21
22use crate::data::object::{inner_fn_update_settings, ObsObjectTrait, ObsObjectTraitPrivate};
23use crate::data::ImmutableObsData;
24use crate::data::ObsDataPointers;
25use crate::runtime::ObsRuntime;
26use crate::unsafe_send::{Sendable, SmartPointerSendable};
27use crate::utils::{ObsDropGuard, OutputInfo};
28use crate::{impl_obs_drop, impl_signal_manager, run_with_obs};
29
30use crate::{
31    encoders::{audio::ObsAudioEncoder, video::ObsVideoEncoder},
32    services::ObsServiceRef,
33    utils::{ObsError, ObsString},
34};
35
36use super::ObsData;
37
38pub(crate) mod macros;
39mod traits;
40pub use traits::*;
41
42mod pipeline;
43pub use pipeline::*;
44
45mod replay_buffer;
46pub use replay_buffer::*;
47
48mod stats;
49pub use stats::*;
50
51#[derive(Debug)]
52struct _ObsOutputDropGuard {
53    output: Sendable<*mut obs_output>,
54    runtime: ObsRuntime,
55}
56
57impl ObsDropGuard for _ObsOutputDropGuard {}
58
59impl_obs_drop!(_ObsOutputDropGuard, (output), move || unsafe {
60    // SAFETY: This guard owns the reference returned by obs_output_create. The shared
61    // native lease drops it once, queuing this release on the OBS actor. The cleanup
62    // task retains the owned reference until this call completes.
63    libobs::obs_output_release(output.0);
64});
65
66#[derive(Debug, Clone)]
67/// A reference to an OBS output.
68///
69/// This struct represents an output in OBS, which is responsible for
70/// outputting encoded audio and video data to a destination such as:
71/// - A file (recording)
72/// - A streaming service (RTMP, etc.)
73/// - A replay buffer
74///
75/// The output is associated with video and audio encoders that convert
76/// raw media to the required format before sending/storing.
77///
78/// Attached encoders and services are retained internally for as long as the output owns them.
79/// They can be replaced or detached while the output is inactive, either individually or by
80/// applying a complete [`ObsOutputComposition`] desired state.
81pub struct ObsOutputRef {
82    /// Disconnect signals first
83    signal_manager: Arc<ObsOutputSignals>,
84
85    /// Settings for the output
86    settings: Arc<RwLock<ImmutableObsData>>,
87
88    /// Hotkey configuration data for the output
89    hotkey_data: Arc<RwLock<ImmutableObsData>>,
90
91    /// Video encoders attached to this output
92    curr_video_encoder: Arc<RwLock<Option<Arc<ObsVideoEncoder>>>>,
93
94    /// Audio encoders attached to this output
95    audio_encoders: Arc<RwLock<HashMap<usize, Arc<ObsAudioEncoder>>>>,
96
97    /// Streaming service attached to this output, if any.
98    service: Arc<RwLock<Option<Arc<ObsServiceRef>>>>,
99
100    /// Serializes output configuration with start/stop so encoder/service snapshots cannot race.
101    configuration_lock: Arc<Mutex<()>>,
102
103    /// Serializes lifecycle requests so concurrent pause/stop/start operations have deterministic
104    /// ordering and do not consume each other's completion signals.
105    lifecycle_lock: Arc<Mutex<()>>,
106
107    /// The type identifier of this output
108    id: ObsString,
109
110    /// The unique name of this output
111    name: ObsString,
112
113    runtime: ObsRuntime,
114
115    /// Pointer to the underlying OBS output
116    output: SmartPointerSendable<*mut obs_output>,
117}
118
119impl ObsOutputTraitSealed for ObsOutputRef {
120    fn new(output: OutputInfo, runtime: ObsRuntime) -> Result<Self, ObsError> {
121        let OutputInfo {
122            id,
123            name,
124            settings,
125            hotkey_data,
126        } = output;
127
128        let settings_ptr = settings.as_ref().map(|x| x.as_ptr());
129        let hotkey_data_ptr = hotkey_data.as_ref().map(|x| x.as_ptr());
130
131        let output = run_with_obs!(
132            runtime,
133            (id, name, settings_ptr, hotkey_data_ptr),
134            move || {
135                let settings_raw_ptr = match settings_ptr {
136                    Some(s) => s.get_ptr(),
137                    None => ptr::null_mut(),
138                };
139
140                let hotkey_data_raw_ptr = match hotkey_data_ptr {
141                    Some(h) => h.get_ptr(),
142                    None => ptr::null_mut(),
143                };
144
145                let id_ptr = id.as_ptr().0;
146                let name_ptr = name.as_ptr().0;
147
148                let output = unsafe {
149                    // Safety: All pointers are valid because we are keeping them in this scope and because we are using smart pointers for ObsData
150                    libobs::obs_output_create(
151                        id_ptr,
152                        name_ptr,
153                        settings_raw_ptr,
154                        hotkey_data_raw_ptr,
155                    )
156                };
157
158                if output.is_null() {
159                    return Err(ObsError::NullPointer(None));
160                }
161
162                Ok(Sendable(output))
163            }
164        )??;
165
166        let output = SmartPointerSendable::new(
167            output.0,
168            Arc::new(_ObsOutputDropGuard {
169                output: output.clone(),
170                runtime: runtime.clone(),
171            }),
172            runtime.native_registry(),
173        );
174
175        // We are getting the settings from OBS because OBS will have updated it with default values.
176        let new_settings_ptr = run_with_obs!(runtime, (output), move || {
177            let new_settings_ptr = unsafe {
178                // Safety: At this point, the output can't be released because we are using a SmartPointer.
179                libobs::obs_output_get_settings(output.get_ptr())
180            };
181
182            if new_settings_ptr.is_null() {
183                return Err(ObsError::NullPointer(None));
184            }
185
186            Ok(Sendable(new_settings_ptr))
187        })??;
188
189        let settings = ImmutableObsData::from_raw_pointer(new_settings_ptr, runtime.clone());
190
191        // We are creating the hotkey data here because even it is null, OBS would create it nonetheless.
192        // https://github.com/obsproject/obs-studio/blob/d97e5ad820abcccf826faf897df4c7f511857cd4/libobs/obs.c#L2629
193        let hotkey_data = match hotkey_data {
194            Some(h) => h,
195            None => ImmutableObsData::new(&runtime)?,
196        };
197
198        let signal_manager = ObsOutputSignals::new(&output, runtime.clone())?;
199        Ok(Self {
200            settings: Arc::new(RwLock::new(settings)),
201            hotkey_data: Arc::new(RwLock::new(hotkey_data)),
202
203            curr_video_encoder: Arc::new(RwLock::new(None)),
204            audio_encoders: Arc::new(RwLock::new(HashMap::new())),
205            service: Arc::new(RwLock::new(None)),
206            configuration_lock: Arc::new(Mutex::new(())),
207            lifecycle_lock: Arc::new(Mutex::new(())),
208
209            output: output.clone(),
210            id,
211            name,
212
213            runtime,
214            signal_manager: Arc::new(signal_manager),
215        })
216    }
217
218    fn video_encoder_slot(&self) -> &Arc<RwLock<Option<Arc<ObsVideoEncoder>>>> {
219        &self.curr_video_encoder
220    }
221
222    fn audio_encoder_slots(&self) -> &Arc<RwLock<HashMap<usize, Arc<ObsAudioEncoder>>>> {
223        &self.audio_encoders
224    }
225
226    fn service_slot(&self) -> &Arc<RwLock<Option<Arc<ObsServiceRef>>>> {
227        &self.service
228    }
229
230    fn configuration_lock(&self) -> &Arc<Mutex<()>> {
231        &self.configuration_lock
232    }
233
234    fn lifecycle_lock(&self) -> &Arc<Mutex<()>> {
235        &self.lifecycle_lock
236    }
237}
238
239impl ObsObjectTraitPrivate for ObsOutputRef {
240    fn __internal_replace_settings(&self, settings: ImmutableObsData) -> Result<(), ObsError> {
241        self.settings
242            .write()
243            .map_err(|_| ObsError::LockError("Failed to acquire write lock on settings".into()))
244            .map(|mut settings_lock| {
245                *settings_lock = settings;
246            })
247    }
248
249    fn __internal_replace_hotkey_data(
250        &self,
251        hotkey_data: ImmutableObsData,
252    ) -> Result<(), ObsError> {
253        self.hotkey_data
254            .write()
255            .map_err(|_| ObsError::LockError("Failed to acquire write lock on hotkey data".into()))
256            .map(|mut hotkey_lock| {
257                *hotkey_lock = hotkey_data;
258            })
259    }
260}
261
262impl ObsObjectTrait for ObsOutputRef {
263    type Native = *mut libobs::obs_output;
264
265    fn __native_handle(&self) -> SmartPointerSendable<Self::Native> {
266        self.output.clone()
267    }
268
269    fn name(&self) -> ObsString {
270        self.name.clone()
271    }
272
273    fn id(&self) -> ObsString {
274        self.id.clone()
275    }
276
277    fn runtime(&self) -> &ObsRuntime {
278        &self.runtime
279    }
280
281    fn settings(&self) -> Result<ImmutableObsData, ObsError> {
282        let r = self
283            .settings
284            .read()
285            .map_err(|_| ObsError::LockError("Failed to acquire read lock on settings".into()))?;
286
287        Ok(r.clone())
288    }
289
290    fn hotkey_data(&self) -> Result<ImmutableObsData, ObsError> {
291        let r = self.hotkey_data.read().map_err(|_| {
292            ObsError::LockError("Failed to acquire read lock on hotkey data".into())
293        })?;
294
295        Ok(r.clone())
296    }
297
298    fn update_settings(&self, settings: ObsData) -> Result<(), ObsError> {
299        let _configuration = self
300            .configuration_lock
301            .lock()
302            .map_err(|e| ObsError::LockError(e.to_string()))?;
303        if self.is_active()? {
304            return Err(ObsError::OutputAlreadyActive);
305        }
306
307        inner_fn_update_settings!(self, libobs::obs_output_update, settings)
308    }
309}
310
311impl ObsOutputTrait for ObsOutputRef {
312    fn signals(&self) -> &Arc<ObsOutputSignals> {
313        &self.signal_manager
314    }
315}
316
317impl_signal_manager!(|ptr: SmartPointerSendable<*mut libobs::obs_output>| unsafe {
318    // Safety: We are using a smart pointer, so it is fine
319    libobs::obs_output_get_signal_handler(ptr.get_ptr())
320}, ObsOutputSignals for *mut libobs::obs_output, [
321    "start": {},
322    "stop": {code: crate::enums::ObsOutputStopSignal},
323    "pause": {},
324    "unpause": {},
325    "starting": {},
326    "stopping": {},
327    "activate": {},
328    "deactivate": {},
329    "reconnect": {},
330    "reconnect_success": {}
331]);