Skip to main content

libobs_wrapper\sources/
transition.rs

1//! Managed transition control with retained source lifetimes.
2
3use std::{sync::Mutex, time::Duration};
4
5use crate::{
6    data::object::ObsObjectTrait,
7    run_with_obs,
8    signals::SignalReceiver,
9    sources::{ObsSourceRef, ObsSourceTrait},
10    utils::ObsError,
11};
12
13pub const DEFAULT_TRANSITION_COMPLETION_TIMEOUT: Duration = Duration::from_secs(10);
14
15#[derive(Debug)]
16struct TransitionState {
17    current: Option<ObsSourceRef>,
18    in_flight: Option<ObsSourceRef>,
19    completion: Option<SignalReceiver<()>>,
20}
21
22/// Managed controller around an OBS transition source.
23///
24/// The destination is retained while native transition work is active. [`Self::begin_to`] is the
25/// non-blocking form for editor/event-loop integrations: initiate a transition, optionally interrupt
26/// it with [`Self::force_stop`], and call [`Self::wait_for_completion`] when a bounded synchronous
27/// wait is appropriate. [`Self::start_to_with_timeout`] combines begin + wait for simpler workflows.
28///
29/// If a bounded wait times out, the destination remains retained in `in_flight` until a later wait,
30/// [`Self::reconcile`], or [`Self::force_stop`] resolves native state. Timeout therefore never claims
31/// to cancel libobs work or releases the destination prematurely.
32#[derive(Debug)]
33pub struct ManagedTransition {
34    transition: ObsSourceRef,
35    state: Mutex<TransitionState>,
36    operation: Mutex<()>,
37}
38
39impl ManagedTransition {
40    pub fn new(transition: ObsSourceRef) -> Result<Self, ObsError> {
41        let ptr = transition.__native_handle();
42        let runtime = transition.runtime().clone();
43        let source_type = run_with_obs!(runtime, (ptr), move || unsafe {
44            // Safety: transition is retained for the actor call.
45            libobs::obs_source_get_type(ptr.get_ptr())
46        })?;
47        if source_type != libobs::obs_source_type_OBS_SOURCE_TYPE_TRANSITION {
48            return Err(ObsError::InvalidOperation(format!(
49                "source '{}' is not an OBS transition",
50                transition.name()
51            )));
52        }
53        Ok(Self {
54            transition,
55            state: Mutex::new(TransitionState {
56                current: None,
57                in_flight: None,
58                completion: None,
59            }),
60            operation: Mutex::new(()),
61        })
62    }
63
64    pub fn source(&self) -> &ObsSourceRef {
65        &self.transition
66    }
67
68    pub fn current_source(&self) -> Result<Option<ObsSourceRef>, ObsError> {
69        self.state
70            .lock()
71            .map(|state| state.current.clone())
72            .map_err(|e| ObsError::LockError(e.to_string()))
73    }
74
75    pub fn set_current_source(&self, source: ObsSourceRef) -> Result<(), ObsError> {
76        self.transition
77            .runtime()
78            .ensure_same_runtime(source.runtime())?;
79        let _operation = self
80            .operation
81            .lock()
82            .map_err(|e| ObsError::LockError(e.to_string()))?;
83        if self.is_active()? {
84            return Err(ObsError::InvalidOperation(
85                "cannot replace transition source while a transition is active".into(),
86            ));
87        }
88        let transition = self.transition.__native_handle();
89        let source_ptr = source.__native_handle();
90        let runtime = self.transition.runtime().clone();
91        run_with_obs!(runtime, (transition, source_ptr), move || unsafe {
92            // Safety: both managed source leases are retained for the actor call.
93            libobs::obs_transition_set(transition.get_ptr(), source_ptr.get_ptr());
94        })?;
95        let mut state = self
96            .state
97            .lock()
98            .map_err(|e| ObsError::LockError(e.to_string()))?;
99        state.current = Some(source);
100        state.in_flight = None;
101        state.completion = None;
102        Ok(())
103    }
104
105    pub fn is_active(&self) -> Result<bool, ObsError> {
106        let transition = self.transition.__native_handle();
107        let runtime = self.transition.runtime().clone();
108        run_with_obs!(runtime, (transition), move || unsafe {
109            // Safety: transition is retained for the actor call.
110            libobs::obs_transition_is_active(transition.get_ptr())
111        })
112    }
113
114    pub fn start_to(&self, destination: ObsSourceRef, duration: Duration) -> Result<(), ObsError> {
115        self.start_to_with_timeout(destination, duration, DEFAULT_TRANSITION_COMPLETION_TIMEOUT)
116    }
117
118    /// Starts an automatic transition without blocking the caller.
119    ///
120    /// Active transitions are rejected rather than implicitly interrupted. This form is intended
121    /// for GUI/event-loop code that needs to remain responsive and possibly call [`Self::force_stop`]
122    /// before later waiting or reconciling.
123    pub fn begin_to(&self, destination: ObsSourceRef, duration: Duration) -> Result<(), ObsError> {
124        self.transition
125            .runtime()
126            .ensure_same_runtime(destination.runtime())?;
127        let _operation = self
128            .operation
129            .lock()
130            .map_err(|e| ObsError::LockError(e.to_string()))?;
131        self.reconcile_locked()?;
132        if self.is_active()? {
133            return Err(ObsError::InvalidOperation(
134                "transition already active; force-stop it explicitly before interrupting".into(),
135            ));
136        }
137
138        let duration_ms = u32::try_from(duration.as_millis()).map_err(|_| {
139            ObsError::InvalidOperation("transition duration exceeds u32 milliseconds".into())
140        })?;
141        let completion = self.transition.signals().on_transition_stop()?;
142        {
143            let mut state = self
144                .state
145                .lock()
146                .map_err(|e| ObsError::LockError(e.to_string()))?;
147            state.in_flight = Some(destination.clone());
148            state.completion = Some(completion);
149        }
150
151        let transition = self.transition.__native_handle();
152        let destination_ptr = destination.__native_handle();
153        let runtime = self.transition.runtime().clone();
154        let started = run_with_obs!(runtime, (transition, destination_ptr), move || unsafe {
155            // Safety: both source handles are retained and state retains destination beyond call.
156            libobs::obs_transition_start(
157                transition.get_ptr(),
158                libobs::obs_transition_mode_OBS_TRANSITION_MODE_AUTO,
159                duration_ms,
160                destination_ptr.get_ptr(),
161            )
162        })?;
163        if !started {
164            let mut state = self
165                .state
166                .lock()
167                .map_err(|e| ObsError::LockError(e.to_string()))?;
168            state.in_flight = None;
169            state.completion = None;
170            return Err(ObsError::InvalidOperation(
171                "libobs rejected transition start".into(),
172            ));
173        }
174        Ok(())
175    }
176
177    /// Waits for the transition initiated by [`Self::begin_to`].
178    ///
179    /// A timeout leaves both destination and completion subscription retained so callers can retry
180    /// the wait or reconcile native state later. Calling this on the OBS actor thread is rejected
181    /// because it would prevent libobs from making progress.
182    pub fn wait_for_completion(&self, timeout: Duration) -> Result<(), ObsError> {
183        if self.transition.runtime().is_actor_thread() {
184            return Err(ObsError::RuntimeReentrantBlocking);
185        }
186        let completion = {
187            let mut state = self
188                .state
189                .lock()
190                .map_err(|e| ObsError::LockError(e.to_string()))?;
191            state.completion.take().ok_or_else(|| {
192                ObsError::InvalidOperation("no managed transition completion is pending".into())
193            })?
194        };
195
196        match completion.recv_timeout(timeout) {
197            Ok(()) => {
198                let mut state = self
199                    .state
200                    .lock()
201                    .map_err(|e| ObsError::LockError(e.to_string()))?;
202                if let Some(completed) = state.in_flight.take() {
203                    state.current = Some(completed);
204                }
205                Ok(())
206            }
207            Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
208                self.state
209                    .lock()
210                    .map_err(|e| ObsError::LockError(e.to_string()))?
211                    .completion = Some(completion);
212                Err(ObsError::OutputOperationTimeout {
213                    operation: "transition".into(),
214                    timeout_ms: timeout.as_millis().min(u64::MAX as u128) as u64,
215                })
216            }
217            Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
218                Err(ObsError::OutputCompletionDisconnected {
219                    operation: "transition".into(),
220                })
221            }
222        }
223    }
224
225    /// Starts an automatic transition and waits for `transition_stop`.
226    pub fn start_to_with_timeout(
227        &self,
228        destination: ObsSourceRef,
229        duration: Duration,
230        timeout: Duration,
231    ) -> Result<(), ObsError> {
232        self.begin_to(destination, duration)?;
233        self.wait_for_completion(timeout)
234    }
235
236    /// Interrupts a managed transition and deterministically snaps to its requested destination.
237    ///
238    /// libobs's `obs_transition_force_stop` invokes plugin-specific stop hooks/signals but does not
239    /// by itself reset generic transition source state. We therefore follow it with
240    /// `obs_transition_set`, retaining the destination through the actor call and making the native
241    /// transition inactive before returning.
242    pub fn force_stop(&self) -> Result<(), ObsError> {
243        let _operation = self
244            .operation
245            .lock()
246            .map_err(|e| ObsError::LockError(e.to_string()))?;
247        let destination = {
248            let state = self
249                .state
250                .lock()
251                .map_err(|e| ObsError::LockError(e.to_string()))?;
252            state.in_flight.clone().or_else(|| state.current.clone())
253        };
254        let transition = self.transition.__native_handle();
255        let destination_ptr = destination.as_ref().map(|source| source.__native_handle());
256        let runtime = self.transition.runtime().clone();
257        run_with_obs!(runtime, (transition, destination_ptr), move || unsafe {
258            // Safety: transition and optional destination are retained for the actor call.
259            libobs::obs_transition_force_stop(transition.get_ptr());
260            libobs::obs_transition_set(
261                transition.get_ptr(),
262                destination_ptr
263                    .as_ref()
264                    .map_or(std::ptr::null_mut(), |source| source.get_ptr()),
265            );
266        })?;
267
268        let mut state = self
269            .state
270            .lock()
271            .map_err(|e| ObsError::LockError(e.to_string()))?;
272        state.current = destination;
273        state.in_flight = None;
274        state.completion = None;
275        Ok(())
276    }
277
278    /// Reconciles retained in-flight state after a timeout/late completion.
279    pub fn reconcile(&self) -> Result<(), ObsError> {
280        let _operation = self
281            .operation
282            .lock()
283            .map_err(|e| ObsError::LockError(e.to_string()))?;
284        self.reconcile_locked()
285    }
286
287    fn reconcile_locked(&self) -> Result<(), ObsError> {
288        if self.is_active()? {
289            return Ok(());
290        }
291        let mut state = self
292            .state
293            .lock()
294            .map_err(|e| ObsError::LockError(e.to_string()))?;
295        if let Some(completed) = state.in_flight.take() {
296            state.current = Some(completed);
297        }
298        state.completion = None;
299        Ok(())
300    }
301}