Skip to main content

libobs_wrapper\data\output/
traits.rs

1use std::{
2    collections::{HashMap, HashSet},
3    ffi::CStr,
4    fmt::Debug,
5    sync::{Arc, Mutex, MutexGuard, RwLock, TryLockError},
6    thread,
7    time::{Duration, Instant},
8};
9
10use crossbeam_channel::RecvTimeoutError;
11
12use crate::{
13    data::{
14        audio::{AudioEncoderSlot, AudioMixIndex},
15        object::ObsObjectTrait,
16    },
17    encoders::{audio::ObsAudioEncoder, video::ObsVideoEncoder},
18    enums::ObsOutputStopSignal,
19    macros::trait_with_optional_send_sync,
20    run_with_obs,
21    runtime::ObsRuntime,
22    services::ObsServiceRef,
23    utils::{AudioEncoderInfo, ObsError, OutputInfo, VideoEncoderInfo},
24};
25
26use super::ObsOutputSignals;
27
28#[derive(Clone, Debug, Default)]
29/// Desired encoder/service wiring for an OBS output.
30///
31/// Applying a composition replaces the complete managed wiring in one actor command: an
32/// omitted video encoder or service is detached, and audio mixer slots not present in
33/// `audio_encoders` are cleared. All handles are validated for runtime affinity before any
34/// native state is changed.
35pub struct ObsOutputComposition {
36    video_encoder: Option<Arc<ObsVideoEncoder>>,
37    audio_encoders: HashMap<usize, Arc<ObsAudioEncoder>>,
38    service: Option<Arc<ObsServiceRef>>,
39}
40
41impl ObsOutputComposition {
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    pub fn with_video_encoder(mut self, encoder: Arc<ObsVideoEncoder>) -> Self {
47        self.video_encoder = Some(encoder);
48        self
49    }
50
51    /// Compatibility helper: the index here is an output encoder slot, not the encoder's source mix.
52    pub fn with_audio_encoder(mut self, slot: usize, encoder: Arc<ObsAudioEncoder>) -> Self {
53        self.audio_encoders.insert(slot, encoder);
54        self
55    }
56
57    pub fn with_audio_encoder_at_slot(
58        mut self,
59        slot: AudioEncoderSlot,
60        encoder: Arc<ObsAudioEncoder>,
61    ) -> Self {
62        self.audio_encoders.insert(slot.index(), encoder);
63        self
64    }
65
66    pub fn with_service(mut self, service: Arc<ObsServiceRef>) -> Self {
67        self.service = Some(service);
68        self
69    }
70
71    pub fn without_video_encoder(mut self) -> Self {
72        self.video_encoder = None;
73        self
74    }
75
76    pub fn without_audio_encoder(mut self, slot: usize) -> Self {
77        self.audio_encoders.remove(&slot);
78        self
79    }
80
81    pub fn without_audio_encoder_at_slot(mut self, slot: AudioEncoderSlot) -> Self {
82        self.audio_encoders.remove(&slot.index());
83        self
84    }
85
86    pub fn without_service(mut self) -> Self {
87        self.service = None;
88        self
89    }
90
91    pub fn video_encoder(&self) -> Option<&Arc<ObsVideoEncoder>> {
92        self.video_encoder.as_ref()
93    }
94
95    pub fn audio_encoders(&self) -> &HashMap<usize, Arc<ObsAudioEncoder>> {
96        &self.audio_encoders
97    }
98
99    pub fn service(&self) -> Option<&Arc<ObsServiceRef>> {
100        self.service.as_ref()
101    }
102}
103
104trait_with_optional_send_sync! {
105    pub(crate) trait ObsOutputTraitSealed: Debug {
106        /// Creates a new output reference from the given output info and runtime.
107        fn new(output: OutputInfo, runtime: ObsRuntime) -> Result<Self, ObsError>
108        where
109            Self: Sized;
110
111        fn video_encoder_slot(&self) -> &Arc<RwLock<Option<Arc<ObsVideoEncoder>>>>;
112        fn audio_encoder_slots(&self) -> &Arc<RwLock<HashMap<usize, Arc<ObsAudioEncoder>>>>;
113        fn service_slot(&self) -> &Arc<RwLock<Option<Arc<ObsServiceRef>>>>;
114        fn configuration_lock(&self) -> &Arc<Mutex<()>>;
115        fn lifecycle_lock(&self) -> &Arc<Mutex<()>>;
116    }
117}
118
119/// Default deadline used by blocking lifecycle operations.
120///
121/// A timeout only stops the Rust caller from waiting; libobs does not provide cancellation for
122/// these requests and native completion may still arrive later.
123pub const DEFAULT_OUTPUT_OPERATION_TIMEOUT: Duration = Duration::from_secs(30);
124
125pub(crate) fn operation_timeout(operation: &str, timeout: Duration) -> ObsError {
126    ObsError::OutputOperationTimeout {
127        operation: operation.to_owned(),
128        timeout_ms: timeout.as_millis().min(u64::MAX as u128) as u64,
129    }
130}
131
132pub(crate) fn remaining(
133    deadline: Instant,
134    operation: &str,
135    timeout: Duration,
136) -> Result<Duration, ObsError> {
137    deadline
138        .checked_duration_since(Instant::now())
139        .filter(|remaining| !remaining.is_zero())
140        .ok_or_else(|| operation_timeout(operation, timeout))
141}
142
143pub(crate) fn lock_until<'a>(
144    lock: &'a Mutex<()>,
145    deadline: Instant,
146    operation: &str,
147    timeout: Duration,
148) -> Result<MutexGuard<'a, ()>, ObsError> {
149    loop {
150        match lock.try_lock() {
151            Ok(guard) => return Ok(guard),
152            Err(TryLockError::Poisoned(err)) => {
153                return Err(ObsError::LockError(err.to_string()));
154            }
155            Err(TryLockError::WouldBlock) => {
156                let wait = remaining(deadline, operation, timeout)?;
157                thread::sleep(wait.min(Duration::from_millis(1)));
158            }
159        }
160    }
161}
162
163pub(crate) fn wait_for_completion<T>(
164    receiver: &crate::signals::SignalReceiver<T>,
165    deadline: Instant,
166    operation: &str,
167    timeout: Duration,
168) -> Result<T, ObsError> {
169    let wait = remaining(deadline, operation, timeout)?;
170    receiver.recv_timeout(wait).map_err(|err| match err {
171        RecvTimeoutError::Timeout => operation_timeout(operation, timeout),
172        RecvTimeoutError::Disconnected => ObsError::OutputCompletionDisconnected {
173            operation: operation.to_owned(),
174        },
175    })
176}
177
178#[allow(private_bounds)]
179pub trait ObsOutputTrait:
180    ObsOutputTraitSealed + ObsObjectTrait<Native = *mut libobs::obs_output_t>
181{
182    fn signals(&self) -> &Arc<ObsOutputSignals>;
183
184    #[doc(hidden)]
185    fn native_output_flags(&self) -> Result<u32, ObsError> {
186        let output_ptr = self.__native_handle();
187        let runtime = self.runtime().clone();
188        run_with_obs!(runtime, (output_ptr), move || {
189            // Safety: the managed output handle remains alive for the actor call.
190            unsafe { libobs::obs_output_get_flags(output_ptr.get_ptr()) }
191        })
192    }
193
194    /// Returns the video encoder currently attached to this output, if any.
195    fn attached_video_encoder(&self) -> Result<Option<Arc<ObsVideoEncoder>>, ObsError> {
196        let curr = self
197            .video_encoder_slot()
198            .read()
199            .map_err(|e| ObsError::LockError(e.to_string()))?;
200
201        Ok(curr.clone())
202    }
203
204    /// Returns the audio encoder attached at the requested mixer index, if any.
205    /// Compatibility helper: `slot` is the output attachment slot, not an audio mix.
206    fn attached_audio_encoder(
207        &self,
208        slot: usize,
209    ) -> Result<Option<Arc<ObsAudioEncoder>>, ObsError> {
210        self.audio_encoder_slots()
211            .read()
212            .map_err(|e| ObsError::LockError(e.to_string()))
213            .map(|encoders| encoders.get(&slot).cloned())
214    }
215
216    fn attached_audio_encoder_at_slot(
217        &self,
218        slot: AudioEncoderSlot,
219    ) -> Result<Option<Arc<ObsAudioEncoder>>, ObsError> {
220        self.attached_audio_encoder(slot.index())
221    }
222
223    /// Returns a snapshot of all managed audio encoder attachments keyed by mixer index.
224    fn attached_audio_encoders(&self) -> Result<HashMap<usize, Arc<ObsAudioEncoder>>, ObsError> {
225        self.audio_encoder_slots()
226            .read()
227            .map_err(|e| ObsError::LockError(e.to_string()))
228            .map(|encoders| encoders.clone())
229    }
230
231    /// Returns the streaming service attached to this output, if any.
232    fn attached_service(&self) -> Result<Option<Arc<ObsServiceRef>>, ObsError> {
233        self.service_slot()
234            .read()
235            .map_err(|e| ObsError::LockError(e.to_string()))
236            .map(|service| service.clone())
237    }
238
239    #[deprecated = "Use attached_video_encoder"]
240    fn get_current_video_encoder(&self) -> Result<Option<Arc<ObsVideoEncoder>>, ObsError> {
241        self.attached_video_encoder()
242    }
243
244    #[deprecated = "Use attached_audio_encoder"]
245    fn get_current_audio_encoder(
246        &self,
247        mixer_idx: usize,
248    ) -> Result<Option<Arc<ObsAudioEncoder>>, ObsError> {
249        self.attached_audio_encoder(mixer_idx)
250    }
251
252    #[deprecated = "Use attached_audio_encoders"]
253    fn get_current_audio_encoders(&self) -> Result<HashMap<usize, Arc<ObsAudioEncoder>>, ObsError> {
254        self.attached_audio_encoders()
255    }
256
257    #[deprecated = "Use attached_service"]
258    fn get_current_service(&self) -> Result<Option<Arc<ObsServiceRef>>, ObsError> {
259        self.attached_service()
260    }
261
262    /// Returns an owned, coherent snapshot of the currently managed encoder/service wiring.
263    fn current_composition(&self) -> Result<ObsOutputComposition, ObsError> {
264        let _configuration = self
265            .configuration_lock()
266            .lock()
267            .map_err(|e| ObsError::LockError(e.to_string()))?;
268        Ok(ObsOutputComposition {
269            video_encoder: self.attached_video_encoder()?,
270            audio_encoders: self.attached_audio_encoders()?,
271            service: self.attached_service()?,
272        })
273    }
274
275    /// Attaches a streaming service to this output. Fails while the output is active.
276    fn set_service(&self, service: Arc<ObsServiceRef>) -> Result<(), ObsError> {
277        let _configuration = self
278            .configuration_lock()
279            .lock()
280            .map_err(|e| ObsError::LockError(e.to_string()))?;
281        if self.is_active()? {
282            return Err(ObsError::OutputAlreadyActive);
283        }
284        let flags = self.native_output_flags()?;
285        ensure_output_supports_service(self, flags)?;
286        self.runtime().ensure_same_runtime(service.runtime())?;
287
288        let mut slot = self
289            .service_slot()
290            .write()
291            .map_err(|e| ObsError::LockError(e.to_string()))?;
292        let output_ptr = self.__native_handle();
293        let service_ptr = service.__native_handle();
294        let runtime = self.runtime().clone();
295        run_with_obs!(runtime, (output_ptr, service_ptr), move || {
296            // Safety: both managed handles retain their native objects for the actor call.
297            unsafe { libobs::obs_output_set_service(output_ptr.get_ptr(), service_ptr.get_ptr()) };
298        })?;
299
300        slot.replace(service);
301        Ok(())
302    }
303
304    /// Replaces the complete managed output wiring in one actor command.
305    ///
306    /// This is the preferred API when constructing an output from discovered capabilities: it
307    /// validates all runtime affinities before touching libobs, detaches omitted components, and
308    /// updates the Rust-side ownership graph only after the native calls complete.
309    fn apply_composition(&self, composition: ObsOutputComposition) -> Result<(), ObsError> {
310        let _configuration = self
311            .configuration_lock()
312            .lock()
313            .map_err(|e| ObsError::LockError(e.to_string()))?;
314        if self.is_active()? {
315            return Err(ObsError::OutputAlreadyActive);
316        }
317        let flags = self.native_output_flags()?;
318        if composition.video_encoder.is_some() {
319            ensure_output_supports_video_encoder(self, flags)?;
320        }
321        if !composition.audio_encoders.is_empty() {
322            ensure_output_supports_audio_encoder(self, flags)?;
323        }
324        if composition.service.is_some() {
325            ensure_output_supports_service(self, flags)?;
326        }
327
328        for mixer_idx in composition.audio_encoders.keys() {
329            validate_audio_mixer(*mixer_idx)?;
330        }
331        if let Some(encoder) = composition.video_encoder.as_ref() {
332            self.runtime().ensure_same_runtime(encoder.runtime())?;
333        }
334        for encoder in composition.audio_encoders.values() {
335            self.runtime().ensure_same_runtime(encoder.runtime())?;
336        }
337        if let Some(service) = composition.service.as_ref() {
338            self.runtime().ensure_same_runtime(service.runtime())?;
339        }
340
341        // Take all locks before changing native state so poisoned Rust-side state cannot leave
342        // libobs and the managed ownership graph out of sync.
343        let mut video_slot = self
344            .video_encoder_slot()
345            .write()
346            .map_err(|e| ObsError::LockError(e.to_string()))?;
347        let mut audio_slots = self
348            .audio_encoder_slots()
349            .write()
350            .map_err(|e| ObsError::LockError(e.to_string()))?;
351        let mut service_slot = self
352            .service_slot()
353            .write()
354            .map_err(|e| ObsError::LockError(e.to_string()))?;
355
356        let output_ptr = self.__native_handle();
357        let video_ptr = composition
358            .video_encoder
359            .as_ref()
360            .map(|encoder| encoder.__native_handle());
361        let service_ptr = composition
362            .service
363            .as_ref()
364            .map(|service| service.__native_handle());
365        let audio_ptrs = composition
366            .audio_encoders
367            .iter()
368            .map(|(mixer_idx, encoder)| (*mixer_idx, encoder.__native_handle()))
369            .collect::<HashMap<_, _>>();
370        let mixer_indices = audio_slots
371            .keys()
372            .copied()
373            .chain(audio_ptrs.keys().copied())
374            .collect::<HashSet<_>>();
375        let runtime = self.runtime().clone();
376
377        run_with_obs!(
378            runtime,
379            (
380                output_ptr,
381                video_ptr,
382                service_ptr,
383                audio_ptrs,
384                mixer_indices,
385                flags
386            ),
387            move || unsafe {
388                // Safety: every non-null pointer is retained by a managed handle captured for the
389                // actor call. Null is the documented libobs detach value for these setters.
390                // Only call setters supported by the concrete output: libobs warns (and third-party
391                // plugins may do worse) when service/encoder setters are used on the wrong category.
392                if output_supports_video_encoder(flags) {
393                    libobs::obs_output_set_video_encoder(
394                        output_ptr.get_ptr(),
395                        video_ptr
396                            .as_ref()
397                            .map_or(std::ptr::null_mut(), |encoder| encoder.get_ptr()),
398                    );
399                }
400                if output_supports_audio_encoder(flags) {
401                    for mixer_idx in mixer_indices {
402                        libobs::obs_output_set_audio_encoder(
403                            output_ptr.get_ptr(),
404                            audio_ptrs
405                                .get(&mixer_idx)
406                                .map_or(std::ptr::null_mut(), |encoder| encoder.get_ptr()),
407                            mixer_idx,
408                        );
409                    }
410                }
411                if output_supports_service(flags) {
412                    libobs::obs_output_set_service(
413                        output_ptr.get_ptr(),
414                        service_ptr
415                            .as_ref()
416                            .map_or(std::ptr::null_mut(), |service| service.get_ptr()),
417                    );
418                }
419            }
420        )?;
421
422        *video_slot = composition.video_encoder;
423        *audio_slots = composition.audio_encoders;
424        *service_slot = composition.service;
425        Ok(())
426    }
427
428    /// Detaches the current video encoder while the output is inactive.
429    fn clear_video_encoder(&self) -> Result<(), ObsError> {
430        let _configuration = self
431            .configuration_lock()
432            .lock()
433            .map_err(|e| ObsError::LockError(e.to_string()))?;
434        if self.is_active()? {
435            return Err(ObsError::OutputAlreadyActive);
436        }
437        let flags = self.native_output_flags()?;
438        let output_ptr = self.__native_handle();
439        let runtime = self.runtime().clone();
440        let mut slot = self
441            .video_encoder_slot()
442            .write()
443            .map_err(|e| ObsError::LockError(e.to_string()))?;
444        if output_supports_video_encoder(flags) {
445            run_with_obs!(runtime, (output_ptr), move || unsafe {
446                // Safety: the managed output handle remains valid for the actor call; null detaches.
447                libobs::obs_output_set_video_encoder(output_ptr.get_ptr(), std::ptr::null_mut());
448            })?;
449        }
450        *slot = None;
451        Ok(())
452    }
453
454    /// Detaches the audio encoder at an output attachment slot while inactive.
455    /// The historical parameter name was "mixer index"; it never selected the encoder's source mix.
456    fn clear_audio_encoder(&self, mixer_idx: usize) -> Result<(), ObsError> {
457        let _configuration = self
458            .configuration_lock()
459            .lock()
460            .map_err(|e| ObsError::LockError(e.to_string()))?;
461        validate_audio_mixer(mixer_idx)?;
462        if self.is_active()? {
463            return Err(ObsError::OutputAlreadyActive);
464        }
465        let flags = self.native_output_flags()?;
466        let output_ptr = self.__native_handle();
467        let runtime = self.runtime().clone();
468        let mut slots = self
469            .audio_encoder_slots()
470            .write()
471            .map_err(|e| ObsError::LockError(e.to_string()))?;
472        if output_supports_audio_encoder(flags) {
473            run_with_obs!(runtime, (output_ptr), move || unsafe {
474                // Safety: the managed output handle remains valid for the actor call; null detaches.
475                libobs::obs_output_set_audio_encoder(
476                    output_ptr.get_ptr(),
477                    std::ptr::null_mut(),
478                    mixer_idx,
479                );
480            })?;
481        }
482        slots.remove(&mixer_idx);
483        Ok(())
484    }
485
486    fn clear_audio_encoder_at_slot(&self, slot: AudioEncoderSlot) -> Result<(), ObsError> {
487        self.clear_audio_encoder(slot.index())
488    }
489
490    /// Detaches the current streaming service while the output is inactive.
491    fn clear_service(&self) -> Result<(), ObsError> {
492        let _configuration = self
493            .configuration_lock()
494            .lock()
495            .map_err(|e| ObsError::LockError(e.to_string()))?;
496        if self.is_active()? {
497            return Err(ObsError::OutputAlreadyActive);
498        }
499        let flags = self.native_output_flags()?;
500        let output_ptr = self.__native_handle();
501        let runtime = self.runtime().clone();
502        let mut slot = self
503            .service_slot()
504            .write()
505            .map_err(|e| ObsError::LockError(e.to_string()))?;
506        if output_supports_service(flags) {
507            run_with_obs!(runtime, (output_ptr), move || unsafe {
508                // Safety: the managed output handle remains valid for the actor call; null detaches.
509                libobs::obs_output_set_service(output_ptr.get_ptr(), std::ptr::null_mut());
510            })?;
511        }
512        *slot = None;
513        Ok(())
514    }
515
516    /// Creates and attaches a new video encoder to this output.
517    ///
518    /// Fails if the output is active.
519    fn create_and_set_video_encoder(
520        &self,
521        info: VideoEncoderInfo,
522    ) -> Result<Arc<ObsVideoEncoder>, ObsError> {
523        if self.is_active()? {
524            return Err(ObsError::OutputAlreadyActive);
525        }
526        ensure_output_supports_video_encoder(self, self.native_output_flags()?)?;
527
528        let video_enc = ObsVideoEncoder::new_from_info(info, self.runtime().clone())?;
529
530        self.set_video_encoder(video_enc.clone())?;
531        Ok(video_enc)
532    }
533
534    /// Attaches an existing video encoder to this output.
535    ///
536    /// Fails if the output is active.
537    fn set_video_encoder(&self, encoder: Arc<ObsVideoEncoder>) -> Result<(), ObsError> {
538        let _configuration = self
539            .configuration_lock()
540            .lock()
541            .map_err(|e| ObsError::LockError(e.to_string()))?;
542        if self.is_active()? {
543            return Err(ObsError::OutputAlreadyActive);
544        }
545        ensure_output_supports_video_encoder(self, self.native_output_flags()?)?;
546        self.runtime().ensure_same_runtime(encoder.runtime())?;
547
548        let mut slot = self
549            .video_encoder_slot()
550            .write()
551            .map_err(|e| ObsError::LockError(e.to_string()))?;
552        let output_ptr = self.__native_handle();
553        let encoder_ptr = encoder.__native_handle();
554        let runtime = self.runtime().clone();
555
556        run_with_obs!(runtime, (output_ptr, encoder_ptr), move || {
557            unsafe {
558                // SAFETY: This actor command captures both output and encoder leases; each
559                // retains its native reference until libobs finishes updating the attachment.
560                libobs::obs_output_set_video_encoder(output_ptr.get_ptr(), encoder_ptr.get_ptr());
561            }
562        })?;
563
564        slot.replace(encoder);
565
566        Ok(())
567    }
568
569    /// Compatibility helper that historically used one integer for both concepts.
570    ///
571    /// It creates an encoder reading native mix `index` and also attaches it at output slot
572    /// `index`. New code should use [`Self::create_and_set_audio_encoder_for_mix_at_slot`].
573    fn create_and_set_audio_encoder(
574        &self,
575        info: AudioEncoderInfo,
576        index: usize,
577    ) -> Result<Arc<ObsAudioEncoder>, ObsError> {
578        let mix = AudioMixIndex::new(index)?;
579        let slot = AudioEncoderSlot::new(index)?;
580        self.create_and_set_audio_encoder_for_mix_at_slot(info, mix, slot)
581    }
582
583    /// Creates an encoder for `mix` and attaches it independently at output `slot`.
584    fn create_and_set_audio_encoder_for_mix_at_slot(
585        &self,
586        info: AudioEncoderInfo,
587        mix: AudioMixIndex,
588        slot: AudioEncoderSlot,
589    ) -> Result<Arc<ObsAudioEncoder>, ObsError> {
590        if self.is_active()? {
591            return Err(ObsError::OutputAlreadyActive);
592        }
593        ensure_output_supports_audio_encoder(self, self.native_output_flags()?)?;
594        let audio_enc = ObsAudioEncoder::new_from_info_for_mix(info, mix, self.runtime().clone())?;
595        self.set_audio_encoder_at_slot(audio_enc.clone(), slot)?;
596        Ok(audio_enc)
597    }
598
599    /// Compatibility helper: `mixer_idx` is actually an output attachment slot.
600    fn set_audio_encoder(
601        &self,
602        encoder: Arc<ObsAudioEncoder>,
603        mixer_idx: usize,
604    ) -> Result<(), ObsError> {
605        self.set_audio_encoder_at_slot(encoder, AudioEncoderSlot::new(mixer_idx)?)
606    }
607
608    /// Attaches an existing audio encoder at an output slot. The encoder retains its own,
609    /// independently selected [`AudioMixIndex`].
610    fn set_audio_encoder_at_slot(
611        &self,
612        encoder: Arc<ObsAudioEncoder>,
613        slot: AudioEncoderSlot,
614    ) -> Result<(), ObsError> {
615        let _configuration = self
616            .configuration_lock()
617            .lock()
618            .map_err(|e| ObsError::LockError(e.to_string()))?;
619        if self.is_active()? {
620            return Err(ObsError::OutputAlreadyActive);
621        }
622        ensure_output_supports_audio_encoder(self, self.native_output_flags()?)?;
623        self.runtime().ensure_same_runtime(encoder.runtime())?;
624
625        let mut slots = self
626            .audio_encoder_slots()
627            .write()
628            .map_err(|e| ObsError::LockError(e.to_string()))?;
629        let encoder_ptr = encoder.__native_handle();
630        let output_ptr = self.__native_handle();
631        let runtime = self.runtime().clone();
632        let slot_index = slot.index();
633        run_with_obs!(runtime, (output_ptr, encoder_ptr), move || unsafe {
634            // Safety: managed handles retain both objects and AudioEncoderSlot is range checked.
635            libobs::obs_output_set_audio_encoder(
636                output_ptr.get_ptr(),
637                encoder_ptr.get_ptr(),
638                slot_index,
639            );
640        })?;
641        slots.insert(slot_index, encoder);
642        Ok(())
643    }
644
645    /// Starts the output, wiring encoders to global contexts and invoking `obs_output_start`.
646    ///
647    /// Lifecycle requests are serialized per output. Starting an already-active output keeps the
648    /// historical `OutputAlreadyActive` error so accidental duplicate starts remain visible.
649    fn start(&self) -> Result<(), ObsError> {
650        let _lifecycle = self
651            .lifecycle_lock()
652            .lock()
653            .map_err(|e| ObsError::LockError(e.to_string()))?;
654        let _configuration = self
655            .configuration_lock()
656            .lock()
657            .map_err(|e| ObsError::LockError(e.to_string()))?;
658        if self.is_active()? {
659            return Err(ObsError::OutputAlreadyActive);
660        }
661
662        let vid_encoder_ptr = self
663            .video_encoder_slot()
664            .read()
665            .map_err(|e| ObsError::LockError(e.to_string()))?
666            .as_ref()
667            .map(|enc| enc.__native_handle());
668
669        let audio_encoder_pointers = self
670            .audio_encoder_slots()
671            .read()
672            .map_err(|e| ObsError::LockError(e.to_string()))?
673            .values()
674            .map(|enc| enc.__native_handle())
675            .collect::<Vec<_>>();
676
677        let output_ptr = self.__native_handle();
678        let runtime = self.runtime().clone();
679        let res = run_with_obs!(
680            runtime,
681            (output_ptr, vid_encoder_ptr, audio_encoder_pointers),
682            move || {
683                if let Some(vid_encoder_ptr) = vid_encoder_ptr {
684                    unsafe {
685                        // Safety: vid_encoder_ptr is retained by the managed encoder handle.
686                        libobs::obs_encoder_set_video(
687                            vid_encoder_ptr.get_ptr(),
688                            libobs::obs_get_video(),
689                        );
690                    }
691                }
692                for audio_encoder_ptr in audio_encoder_pointers {
693                    unsafe {
694                        // Safety: audio_encoder_ptr is retained by the managed encoder handle.
695                        libobs::obs_encoder_set_audio(
696                            audio_encoder_ptr.get_ptr(),
697                            libobs::obs_get_audio(),
698                        );
699                    }
700                }
701
702                unsafe {
703                    // Safety: output_ptr is retained by the managed output handle.
704                    libobs::obs_output_start(output_ptr.get_ptr())
705                }
706            }
707        )?;
708
709        if res {
710            return Ok(());
711        }
712
713        let runtime = self.runtime().clone();
714        let err = run_with_obs!(runtime, (output_ptr), move || {
715            let err = unsafe {
716                // Safety: output_ptr is retained by the managed output handle.
717                libobs::obs_output_get_last_error(output_ptr.get_ptr())
718            };
719
720            if err.is_null() {
721                return "Unknown error".to_string();
722            }
723
724            unsafe { CStr::from_ptr(err) }.to_string_lossy().to_string()
725        })?;
726
727        Err(ObsError::OutputStartFailure(Some(err)))
728    }
729
730    /// Pauses/resumes with an explicit completion deadline.
731    ///
732    /// Repeating the state already in effect is idempotent and returns immediately. Concurrent
733    /// lifecycle requests are serialized so one request cannot consume another request's signal.
734    /// A timeout does **not** cancel the native pause request; query [`Self::is_paused`] before
735    /// retrying.
736    fn set_paused_with_timeout(
737        &self,
738        should_pause: bool,
739        timeout: Duration,
740    ) -> Result<(), ObsError> {
741        if self.runtime().is_actor_thread() {
742            return Err(ObsError::RuntimeReentrantBlocking);
743        }
744        let operation = if should_pause { "pause" } else { "unpause" };
745        let started = Instant::now();
746        let deadline = started.checked_add(timeout).unwrap_or(started);
747        let _lifecycle = lock_until(self.lifecycle_lock(), deadline, operation, timeout)?;
748
749        if !self.is_active()? {
750            return Err(ObsError::OutputPauseFailure(Some(
751                "Output is not active.".to_string(),
752            )));
753        }
754        if self.is_paused()? == should_pause {
755            return Ok(());
756        }
757
758        // Subscribe before initiating the operation so a synchronous/very-fast callback cannot be
759        // lost between the native call and subscription setup.
760        let receiver = if should_pause {
761            self.signals().on_pause()?
762        } else {
763            self.signals().on_unpause()?
764        };
765
766        let output_ptr = self.__native_handle();
767        let runtime = self.runtime().clone();
768        let res = run_with_obs!(runtime, (output_ptr), move || unsafe {
769            // Safety: output_ptr is retained by the managed output handle.
770            libobs::obs_output_pause(output_ptr.get_ptr(), should_pause)
771        })?;
772
773        if !res {
774            let runtime = self.runtime().clone();
775            let err = run_with_obs!(runtime, (output_ptr), move || {
776                let err = unsafe {
777                    // Safety: output_ptr is retained by the managed output handle.
778                    libobs::obs_output_get_last_error(output_ptr.get_ptr())
779                };
780                if err.is_null() {
781                    None
782                } else {
783                    Some(unsafe { CStr::from_ptr(err) }.to_string_lossy().to_string())
784                }
785            })?;
786            return Err(ObsError::OutputPauseFailure(err));
787        }
788
789        wait_for_completion(&receiver, deadline, operation, timeout)?;
790        Ok(())
791    }
792
793    /// Pauses the output with [`DEFAULT_OUTPUT_OPERATION_TIMEOUT`].
794    fn pause(&self) -> Result<(), ObsError> {
795        self.pause_with_timeout(DEFAULT_OUTPUT_OPERATION_TIMEOUT)
796    }
797
798    /// Pauses the output and waits at most `timeout` for native completion.
799    fn pause_with_timeout(&self, timeout: Duration) -> Result<(), ObsError> {
800        self.set_paused_with_timeout(true, timeout)
801    }
802
803    /// Resumes the output with [`DEFAULT_OUTPUT_OPERATION_TIMEOUT`].
804    fn unpause(&self) -> Result<(), ObsError> {
805        self.unpause_with_timeout(DEFAULT_OUTPUT_OPERATION_TIMEOUT)
806    }
807
808    /// Resumes the output and waits at most `timeout` for native completion.
809    fn unpause_with_timeout(&self, timeout: Duration) -> Result<(), ObsError> {
810        self.set_paused_with_timeout(false, timeout)
811    }
812
813    /// Stops the output with [`DEFAULT_OUTPUT_OPERATION_TIMEOUT`].
814    ///
815    /// Stop is idempotent: if the output is already inactive and not reconnecting, this returns
816    /// `Ok(())`. A timeout only bounds this caller's wait; libobs may complete later. The managed
817    /// output continues retaining its encoder/service graph. Re-query [`Self::is_active`] and
818    /// [`Self::is_reconnecting`] before changing or releasing that graph.
819    fn stop(&self) -> Result<(), ObsError> {
820        self.stop_with_timeout(DEFAULT_OUTPUT_OPERATION_TIMEOUT)
821    }
822
823    /// Requests a graceful stop and waits at most one overall `timeout` for both the `stop` and
824    /// `deactivate` completion signals. Time spent waiting behind another lifecycle/configuration
825    /// operation consumes the same deadline.
826    fn stop_with_timeout(&self, timeout: Duration) -> Result<(), ObsError> {
827        self.stop_impl(timeout, false)
828    }
829
830    /// Requests libobs's force-stop recovery path and waits for normal stop/deactivate completion.
831    ///
832    /// `obs_output_force_stop` asks the output to stop immediately without waiting for queued data;
833    /// it is appropriate after a graceful stop deadline when data loss is preferable to waiting.
834    /// It is not cancellation and still uses the same bounded completion semantics here.
835    fn force_stop(&self) -> Result<(), ObsError> {
836        self.force_stop_with_timeout(DEFAULT_OUTPUT_OPERATION_TIMEOUT)
837    }
838
839    /// Force-stop variant with an explicit overall deadline.
840    fn force_stop_with_timeout(&self, timeout: Duration) -> Result<(), ObsError> {
841        self.stop_impl(timeout, true)
842    }
843
844    #[doc(hidden)]
845    fn stop_impl(&self, timeout: Duration, force: bool) -> Result<(), ObsError> {
846        if self.runtime().is_actor_thread() {
847            return Err(ObsError::RuntimeReentrantBlocking);
848        }
849        let operation = if force { "force-stop" } else { "stop" };
850        let started = Instant::now();
851        let deadline = started.checked_add(timeout).unwrap_or(started);
852        let _lifecycle = lock_until(self.lifecycle_lock(), deadline, operation, timeout)?;
853        let _configuration = lock_until(self.configuration_lock(), deadline, operation, timeout)?;
854
855        let output_ptr = self.__native_handle();
856        let runtime = self.runtime().clone();
857        let (active, reconnecting) = run_with_obs!(runtime, (output_ptr), move || unsafe {
858            // Safety: output_ptr is retained by the managed output handle.
859            (
860                libobs::obs_output_active(output_ptr.get_ptr()),
861                libobs::obs_output_reconnecting(output_ptr.get_ptr()),
862            )
863        })?;
864
865        if !active && !reconnecting {
866            return Ok(());
867        }
868
869        // Both subscriptions are established before the request. This also covers outputs whose
870        // stop/deactivate callbacks are emitted during the initiating actor call.
871        let stop_receiver = self.signals().on_stop()?;
872        let deactivate_receiver = self.signals().on_deactivate()?;
873
874        let runtime = self.runtime().clone();
875        run_with_obs!(runtime, (output_ptr), move || unsafe {
876            // Safety: output_ptr is retained by the managed output handle.
877            if force {
878                libobs::obs_output_force_stop(output_ptr.get_ptr());
879            } else {
880                libobs::obs_output_stop(output_ptr.get_ptr());
881            }
882        })?;
883
884        let signal = wait_for_completion(&stop_receiver, deadline, operation, timeout)?;
885        log::trace!("Received {operation} signal: {signal:?}");
886        if signal != ObsOutputStopSignal::Success {
887            return Err(ObsError::OutputStopFailure(Some(signal.to_string())));
888        }
889
890        wait_for_completion(&deactivate_receiver, deadline, operation, timeout)?;
891        Ok(())
892    }
893
894    /// Returns whether the output is currently active.
895    fn is_active(&self) -> Result<bool, ObsError> {
896        let output_ptr = self.__native_handle();
897        let runtime = self.runtime().clone();
898        run_with_obs!(runtime, (output_ptr), move || unsafe {
899            // Safety: output_ptr is retained by the managed output handle.
900            libobs::obs_output_active(output_ptr.get_ptr())
901        })
902    }
903
904    /// Returns whether the output is currently paused.
905    fn is_paused(&self) -> Result<bool, ObsError> {
906        let output_ptr = self.__native_handle();
907        let runtime = self.runtime().clone();
908        run_with_obs!(runtime, (output_ptr), move || unsafe {
909            // Safety: output_ptr is retained by the managed output handle.
910            libobs::obs_output_paused(output_ptr.get_ptr())
911        })
912    }
913
914    /// Returns whether the output is currently reconnecting.
915    fn is_reconnecting(&self) -> Result<bool, ObsError> {
916        let output_ptr = self.__native_handle();
917        let runtime = self.runtime().clone();
918        run_with_obs!(runtime, (output_ptr), move || unsafe {
919            // Safety: output_ptr is retained by the managed output handle.
920            libobs::obs_output_reconnecting(output_ptr.get_ptr())
921        })
922    }
923}
924
925fn output_supports_video_encoder(flags: u32) -> bool {
926    flags & libobs::OBS_OUTPUT_ENCODED != 0 && flags & libobs::OBS_OUTPUT_VIDEO != 0
927}
928
929fn output_supports_audio_encoder(flags: u32) -> bool {
930    flags & libobs::OBS_OUTPUT_ENCODED != 0 && flags & libobs::OBS_OUTPUT_AUDIO != 0
931}
932
933fn output_supports_service(flags: u32) -> bool {
934    flags & libobs::OBS_OUTPUT_SERVICE != 0
935}
936
937fn unsupported_component<T: ObsOutputTrait + ?Sized>(output: &T, component: &str) -> ObsError {
938    ObsError::OutputPipelineUnexpectedComponent {
939        output_id: output.id().to_string(),
940        component: component.to_owned(),
941    }
942}
943
944fn ensure_output_supports_video_encoder<T: ObsOutputTrait + ?Sized>(
945    output: &T,
946    flags: u32,
947) -> Result<(), ObsError> {
948    output_supports_video_encoder(flags)
949        .then_some(())
950        .ok_or_else(|| unsupported_component(output, "a video encoder"))
951}
952
953fn ensure_output_supports_audio_encoder<T: ObsOutputTrait + ?Sized>(
954    output: &T,
955    flags: u32,
956) -> Result<(), ObsError> {
957    output_supports_audio_encoder(flags)
958        .then_some(())
959        .ok_or_else(|| unsupported_component(output, "audio encoders"))
960}
961
962fn ensure_output_supports_service<T: ObsOutputTrait + ?Sized>(
963    output: &T,
964    flags: u32,
965) -> Result<(), ObsError> {
966    output_supports_service(flags)
967        .then_some(())
968        .ok_or_else(|| unsupported_component(output, "a service"))
969}
970
971fn validate_audio_mixer(mixer_idx: usize) -> Result<(), ObsError> {
972    if mixer_idx >= libobs::MAX_AUDIO_MIXES as usize {
973        return Err(ObsError::AudioMixerIndexOutOfBounds {
974            index: mixer_idx,
975            max: (libobs::MAX_AUDIO_MIXES - 1) as usize,
976        });
977    }
978    Ok(())
979}
980
981#[cfg(test)]
982mod tests {
983    use super::validate_audio_mixer;
984
985    #[test]
986    fn audio_mixer_indices_are_bounded_before_ffi() {
987        assert!(validate_audio_mixer(0).is_ok());
988        assert!(validate_audio_mixer((libobs::MAX_AUDIO_MIXES - 1) as usize).is_ok());
989        assert!(validate_audio_mixer(libobs::MAX_AUDIO_MIXES as usize).is_err());
990    }
991}