Skip to main content

libobs_wrapper\data\output/
replay_buffer.rs

1//! Provides functionality for working with OBS replay buffers.
2//!
3//! This module extends the ObsOutputRef to provide replay buffer capabilities.
4//! A replay buffer is a special type of output that continuously records
5//! the last N seconds of content, allowing the user to save this buffer on demand. This must be configured. More documentation soon.
6use std::{
7    path::{Path, PathBuf},
8    sync::{Arc, Mutex},
9    time::{Duration, Instant},
10};
11
12use crate::{
13    data::{
14        object::ObsObjectTrait,
15        output::{
16            traits::{lock_until, wait_for_completion},
17            ObsOutputRef, ObsOutputTrait, ObsOutputTraitSealed,
18        },
19    },
20    forward_obs_object_impl, forward_obs_output_impl, impl_signal_manager, run_with_obs,
21    runtime::ObsRuntime,
22    unsafe_send::{Sendable, SmartPointerSendable},
23    utils::{ObsCalldataExt, ObsError, ObsString, OutputInfo},
24};
25
26#[derive(Debug, Clone)]
27/// A reference to an OBS output.
28///
29/// This struct is used specifically for the replay buffer to manage saving the buffer to a file
30/// and configuring special settings, which are specific to the replay buffer
31///
32/// The output is associated with video and audio encoders that convert
33/// raw media to the required format before sending/storing.
34pub struct ObsReplayBufferOutputRef {
35    /// Disconnect signals first
36    replay_signal_manager: Arc<ObsReplayOutputSignals>,
37
38    /// libobs exposes one replay `saved` signal and one `get_last_replay` value with no request
39    /// identity. Serializing saves is therefore required to correlate a completion/path with the
40    /// request that initiated it.
41    save_lock: Arc<Mutex<()>>,
42
43    output: ObsOutputRef,
44}
45
46/// Default maximum time [`ObsReplayBufferOutputRef::save_buffer`] waits for native completion.
47pub const DEFAULT_REPLAY_SAVE_TIMEOUT: Duration = Duration::from_secs(30);
48
49impl ObsOutputTraitSealed for ObsReplayBufferOutputRef {
50    fn new(mut output: OutputInfo, runtime: ObsRuntime) -> Result<Self, ObsError> {
51        output.id = ObsString::new("replay_buffer");
52        let output = ObsOutputRef::new(output, runtime.clone())?;
53
54        let replay_signal_manager =
55            ObsReplayOutputSignals::new(&output.__native_handle(), runtime)?;
56        Ok(Self {
57            replay_signal_manager: Arc::new(replay_signal_manager),
58            save_lock: Arc::new(Mutex::new(())),
59            output,
60        })
61    }
62
63    fn video_encoder_slot(
64        &self,
65    ) -> &std::sync::Arc<
66        std::sync::RwLock<Option<std::sync::Arc<crate::encoders::video::ObsVideoEncoder>>>,
67    > {
68        self.output.video_encoder_slot()
69    }
70
71    fn audio_encoder_slots(
72        &self,
73    ) -> &std::sync::Arc<
74        std::sync::RwLock<
75            std::collections::HashMap<
76                usize,
77                std::sync::Arc<crate::encoders::audio::ObsAudioEncoder>,
78            >,
79        >,
80    > {
81        self.output.audio_encoder_slots()
82    }
83
84    fn service_slot(
85        &self,
86    ) -> &std::sync::Arc<std::sync::RwLock<Option<std::sync::Arc<crate::services::ObsServiceRef>>>>
87    {
88        self.output.service_slot()
89    }
90
91    fn configuration_lock(&self) -> &std::sync::Arc<std::sync::Mutex<()>> {
92        self.output.configuration_lock()
93    }
94
95    fn lifecycle_lock(&self) -> &std::sync::Arc<std::sync::Mutex<()>> {
96        self.output.lifecycle_lock()
97    }
98}
99
100forward_obs_object_impl!(ObsReplayBufferOutputRef, output, *mut libobs::obs_output);
101forward_obs_output_impl!(ObsReplayBufferOutputRef, output);
102
103impl_signal_manager!(|ptr: SmartPointerSendable<*mut libobs::obs_output>| {
104    unsafe {
105        // SAFETY: ptr retains the output reference through this actor call. The signal
106        // manager keeps that lease through disconnect; the handler is output-owned.
107        libobs::obs_output_get_signal_handler(ptr.get_ptr())
108    }
109}, ObsReplayOutputSignals for *mut libobs::obs_output, [
110    "saved": {}
111]);
112
113impl ObsReplayBufferOutputRef {
114    pub fn replay_signals(&self) -> &Arc<ObsReplayOutputSignals> {
115        &self.replay_signal_manager
116    }
117    /// Saves the current replay buffer content to disk using a bounded completion wait.
118    ///
119    /// Save requests are serialized because the OBS replay-buffer procedure exposes only a single
120    /// `saved` signal and global `get_last_replay` path. The subscription is established before
121    /// invoking `save`, so even a completion emitted during the initiating actor call is observed.
122    ///
123    /// If the deadline expires, this returns [`ObsError::OutputOperationTimeout`]. The native save
124    /// is not cancelled and may still finish later; wait for/re-query replay state before assuming
125    /// that no file was produced.
126    pub fn save_buffer(&self) -> Result<Box<Path>, ObsError> {
127        self.save_buffer_with_timeout(DEFAULT_REPLAY_SAVE_TIMEOUT)
128    }
129
130    /// Saves the replay buffer while waiting at most one overall `timeout`, including time spent
131    /// behind another save request.
132    pub fn save_buffer_with_timeout(&self, timeout: Duration) -> Result<Box<Path>, ObsError> {
133        if self.runtime().is_actor_thread() {
134            return Err(ObsError::RuntimeReentrantBlocking);
135        }
136
137        let operation = "replay-save";
138        let started = Instant::now();
139        let deadline = started.checked_add(timeout).unwrap_or(started);
140        let _save = lock_until(&self.save_lock, deadline, operation, timeout)?;
141
142        if !self.is_active()? {
143            return Err(ObsError::OutputSaveBufferFailure(
144                "Replay buffer output is not active.".to_string(),
145            ));
146        }
147
148        log::trace!("Saving replay buffer...");
149        let output_ptr = self.__native_handle();
150
151        log::trace!("Getting procedure handler for replay buffer output...");
152        let proc_handler = run_with_obs!(self.runtime().clone(), (output_ptr), move || {
153            // Safety: output_ptr is retained by the managed output handle.
154            let ph = unsafe { libobs::obs_output_get_proc_handler(output_ptr.get_ptr()) };
155            if ph.is_null() {
156                return Err(ObsError::OutputSaveBufferFailure(
157                    "Failed to get replay-buffer procedure handler.".to_string(),
158                ));
159            }
160            Ok(Sendable(ph))
161        })??;
162
163        // Critical ordering: observe completion before calling `save`.
164        let saved = self.replay_signals().on_saved()?;
165
166        log::trace!("Calling 'save' procedure on replay buffer output...");
167        // Safety: proc_handler belongs to this still-live output.
168        unsafe {
169            self.runtime().call_proc_handler(&proc_handler, "save")?;
170        }
171
172        log::trace!("Waiting for 'saved' signal from replay buffer output...");
173        wait_for_completion(&saved, deadline, operation, timeout)?;
174
175        log::trace!("Retrieving last replay path from replay buffer output...");
176        // Safety: proc_handler belongs to this still-live output.
177        let mut calldata = unsafe {
178            self.runtime()
179                .call_proc_handler(&proc_handler, "get_last_replay")?
180        };
181
182        log::trace!("Extracting path from calldata...");
183        let path = PathBuf::from(calldata.get_string("path")?);
184        if path.as_os_str().is_empty() {
185            return Err(ObsError::OutputSaveBufferFailure(
186                "Replay save completed but OBS returned an empty last-replay path.".to_string(),
187            ));
188        }
189
190        Ok(path.into_boxed_path())
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use crate::signals::SignalHub;
198    use std::sync::{mpsc, Barrier};
199    use std::thread;
200
201    #[test]
202    fn completion_published_during_initiation_is_not_lost() {
203        let hub = SignalHub::new();
204        let receiver = hub.subscribe();
205        let timeout = Duration::from_millis(100);
206        let started = Instant::now();
207        let deadline = started.checked_add(timeout).unwrap();
208
209        // Models a native `save` procedure that emits `saved` before returning.
210        hub.publish(());
211
212        wait_for_completion(&receiver, deadline, "replay-save", timeout).unwrap();
213    }
214
215    #[test]
216    fn overlapping_save_lock_is_bounded() {
217        let save_lock = Arc::new(Mutex::new(()));
218        let held = save_lock.lock().unwrap();
219        let lock_for_thread = save_lock.clone();
220        let barrier = Arc::new(Barrier::new(2));
221        let thread_barrier = barrier.clone();
222
223        let waiter = thread::spawn(move || {
224            thread_barrier.wait();
225            let timeout = Duration::from_millis(20);
226            let started = Instant::now();
227            let deadline = started.checked_add(timeout).unwrap();
228            lock_until(&lock_for_thread, deadline, "replay-save", timeout).map(|_| ())
229        });
230
231        barrier.wait();
232        let result = waiter.join().unwrap();
233        drop(held);
234        assert!(matches!(
235            result,
236            Err(ObsError::OutputOperationTimeout { operation, .. }) if operation == "replay-save"
237        ));
238    }
239
240    #[test]
241    fn overlapping_save_requests_serialize_when_deadline_allows() {
242        let save_lock = Arc::new(Mutex::new(()));
243        let (first_acquired_tx, first_acquired_rx) = mpsc::channel();
244        let (release_first_tx, release_first_rx) = mpsc::channel();
245
246        let first_lock = save_lock.clone();
247        let first = thread::spawn(move || {
248            let timeout = Duration::from_secs(1);
249            let started = Instant::now();
250            let deadline = started.checked_add(timeout).unwrap();
251            let _guard = lock_until(&first_lock, deadline, "replay-save", timeout).unwrap();
252            first_acquired_tx.send(()).unwrap();
253            release_first_rx.recv().unwrap();
254        });
255
256        first_acquired_rx.recv().unwrap();
257        let second_lock = save_lock.clone();
258        let second = thread::spawn(move || {
259            let timeout = Duration::from_secs(1);
260            let started = Instant::now();
261            let deadline = started.checked_add(timeout).unwrap();
262            lock_until(&second_lock, deadline, "replay-save", timeout).map(|_| ())
263        });
264
265        release_first_tx.send(()).unwrap();
266        first.join().unwrap();
267        second.join().unwrap().unwrap();
268    }
269
270    #[test]
271    fn missing_replay_completion_times_out() {
272        let hub = SignalHub::<()>::new();
273        let receiver = hub.subscribe();
274        let timeout = Duration::from_millis(1);
275        let started = Instant::now();
276        let deadline = started.checked_add(timeout).unwrap();
277
278        assert!(matches!(
279            wait_for_completion(&receiver, deadline, "replay-save", timeout),
280            Err(ObsError::OutputOperationTimeout { operation, .. }) if operation == "replay-save"
281        ));
282    }
283}