Skip to main content

libobs_simple\output/
replay.rs

1//! Replay buffer builder for OBS.
2//!
3//! This module provides a simplified interface for configuring OBS replay buffers.
4//! A replay buffer continuously records the last N seconds of content, allowing
5//! on-demand saving of recent footage.
6//!
7//! # Example
8//!
9//! ```no_run
10//! use libobs_simple::output::replay::ReplayBufferBuilder;
11//! use libobs_wrapper::{data::video::ObsVideoInfoBuilder, utils::{ObsPath, StartupInfo}};
12//!
13//! fn main() -> Result<(), Box<dyn std::error::Error>> {
14//!     let context = StartupInfo::new()
15//!         .set_video_info(ObsVideoInfoBuilder::new().build())
16//!         .start()?;
17//!
18//!     let _replay = ReplayBufferBuilder::new(context, "my_replay", ObsPath::new("."))
19//!         .max_time_sec(30)
20//!         .max_size_mb(1000)
21//!         .format("%CCYY-%MM-%DD %hh-%mm-%ss")
22//!         .extension("mp4")
23//!         .build()?;
24//!
25//!     Ok(())
26//! }
27//! ```
28
29use libobs_wrapper::{
30    context::ObsContext,
31    data::{
32        output::{ObsOutputTrait, ObsReplayBufferOutputRef},
33        ObsData, ObsDataGetters, ObsDataSetters,
34    },
35    encoders::{ObsAudioEncoderType, ObsVideoEncoderType},
36    utils::{AudioEncoderInfo, ObsError, ObsPath, ObsString, OutputInfo, VideoEncoderInfo},
37};
38
39use super::simple::{
40    select_video_encoder_type, AudioEncoder, HardwareCodec, HardwarePreset, VideoEncoder,
41    X264Preset,
42};
43
44/// Settings for replay buffer output
45#[derive(Debug)]
46pub struct ReplayBufferSettings {
47    name: ObsString,
48    /// Maximum duration to keep in buffer (seconds)
49    max_time_sec: i64,
50    /// Maximum buffer size (megabytes)
51    max_size_mb: i64,
52    /// Filename format string (e.g., "%CCYY-%MM-%DD %hh-%mm-%ss")
53    format: ObsString,
54    /// File extension (e.g., "mp4", "mkv")
55    extension: ObsString,
56    /// Allow spaces in filenames
57    allow_spaces: bool,
58    video_encoder: VideoEncoder,
59    audio_encoder: AudioEncoder,
60    video_bitrate: u32,
61    audio_bitrate: u32,
62    directory: ObsPath,
63    custom_encoder_settings: Option<String>,
64}
65
66impl ReplayBufferSettings {
67    /// Sets the maximum time to keep in buffer (seconds).
68    pub fn with_max_time_sec(mut self, seconds: i64) -> Self {
69        self.max_time_sec = seconds;
70        self
71    }
72
73    /// Sets the maximum buffer size (megabytes).
74    pub fn with_max_size_mb(mut self, megabytes: i64) -> Self {
75        self.max_size_mb = megabytes;
76        self
77    }
78
79    /// Sets the filename format string.
80    pub fn with_format<S: Into<ObsString>>(mut self, format: S) -> Self {
81        self.format = format.into();
82        self
83    }
84
85    /// Sets the file extension.
86    pub fn with_extension<S: Into<ObsString>>(mut self, extension: S) -> Self {
87        self.extension = extension.into();
88        self
89    }
90
91    /// Sets whether to allow spaces in filenames.
92    pub fn with_allow_spaces(mut self, allow: bool) -> Self {
93        self.allow_spaces = allow;
94        self
95    }
96
97    /// Sets the video bitrate in Kbps.
98    pub fn with_video_bitrate(mut self, bitrate: u32) -> Self {
99        self.video_bitrate = bitrate;
100        self
101    }
102
103    /// Sets the audio bitrate in Kbps.
104    pub fn with_audio_bitrate(mut self, bitrate: u32) -> Self {
105        self.audio_bitrate = bitrate;
106        self
107    }
108
109    /// Sets the video encoder to use x264 software encoding.
110    pub fn with_x264_encoder(mut self, preset: X264Preset) -> Self {
111        self.video_encoder = VideoEncoder::X264(preset);
112        self
113    }
114
115    /// Sets the video encoder to use a generic hardware encoder for the given codec.
116    pub fn with_hardware_encoder(mut self, codec: HardwareCodec, preset: HardwarePreset) -> Self {
117        self.video_encoder = VideoEncoder::Hardware { codec, preset };
118        self
119    }
120
121    /// Sets a custom video encoder.
122    pub fn with_custom_video_encoder(mut self, encoder: ObsVideoEncoderType) -> Self {
123        self.video_encoder = VideoEncoder::Custom(encoder);
124        self
125    }
126
127    /// Sets custom encoder settings.
128    pub fn with_custom_encoder_settings<S: Into<String>>(mut self, settings: S) -> Self {
129        self.custom_encoder_settings = Some(settings.into());
130        self
131    }
132
133    /// Sets the audio encoder.
134    pub fn with_audio_encoder(mut self, encoder: AudioEncoder) -> Self {
135        self.audio_encoder = encoder;
136        self
137    }
138}
139
140/// Builder for replay buffer outputs
141#[derive(Debug)]
142pub struct ReplayBufferBuilder {
143    settings: ReplayBufferSettings,
144    context: ObsContext,
145}
146
147/// Extension trait for ObsContext to create replay buffer builders
148pub trait ObsContextReplayExt {
149    fn replay_buffer_builder<T: Into<ObsString>, K: Into<ObsPath>>(
150        &self,
151        name: T,
152        directory_path: K,
153    ) -> ReplayBufferBuilder;
154}
155
156impl ObsContextReplayExt for ObsContext {
157    fn replay_buffer_builder<T: Into<ObsString>, K: Into<ObsPath>>(
158        &self,
159        name: T,
160        directory_path: K,
161    ) -> ReplayBufferBuilder {
162        ReplayBufferBuilder::new(self.clone(), name, directory_path)
163    }
164}
165
166impl ReplayBufferBuilder {
167    /// Creates a new ReplayBufferBuilder with default settings.
168    pub fn new<T: Into<ObsString>, K: Into<ObsPath>>(
169        context: ObsContext,
170        name: T,
171        directory_path: K,
172    ) -> Self {
173        ReplayBufferBuilder {
174            settings: ReplayBufferSettings {
175                name: name.into(),
176                max_time_sec: 15,
177                max_size_mb: 500,
178                format: "%CCYY-%MM-%DD %hh-%mm-%ss".into(),
179                extension: "mp4".into(),
180                directory: directory_path.into(),
181                allow_spaces: true,
182                video_bitrate: 6000,
183                audio_bitrate: 160,
184                video_encoder: VideoEncoder::X264(X264Preset::VeryFast),
185                audio_encoder: AudioEncoder::AAC,
186                custom_encoder_settings: None,
187            },
188            context,
189        }
190    }
191
192    /// Sets the replay buffer settings.
193    pub fn settings(mut self, settings: ReplayBufferSettings) -> Self {
194        self.settings = settings;
195        self
196    }
197
198    /// Sets the maximum time to keep in buffer (seconds).
199    pub fn max_time_sec(mut self, seconds: i64) -> Self {
200        self.settings.max_time_sec = seconds;
201        self
202    }
203
204    /// Sets the maximum buffer size (megabytes).
205    pub fn max_size_mb(mut self, megabytes: i64) -> Self {
206        self.settings.max_size_mb = megabytes;
207        self
208    }
209
210    /// Sets the filename format string.
211    pub fn format<S: Into<ObsString>>(mut self, format: S) -> Self {
212        self.settings.format = format.into();
213        self
214    }
215
216    /// Sets the file extension.
217    pub fn extension<S: Into<ObsString>>(mut self, extension: S) -> Self {
218        self.settings.extension = extension.into();
219        self
220    }
221
222    /// Sets whether to allow spaces in filenames.
223    pub fn allow_spaces(mut self, allow: bool) -> Self {
224        self.settings.allow_spaces = allow;
225        self
226    }
227
228    /// Sets the video bitrate in Kbps.
229    pub fn video_bitrate(mut self, bitrate: u32) -> Self {
230        self.settings.video_bitrate = bitrate;
231        self
232    }
233
234    /// Sets the audio bitrate in Kbps.
235    pub fn audio_bitrate(mut self, bitrate: u32) -> Self {
236        self.settings.audio_bitrate = bitrate;
237        self
238    }
239
240    /// Sets the video encoder to x264.
241    pub fn x264_encoder(mut self, preset: X264Preset) -> Self {
242        self.settings.video_encoder = VideoEncoder::X264(preset);
243        self
244    }
245
246    /// Sets the video encoder to a generic hardware encoder.
247    pub fn hardware_encoder(mut self, codec: HardwareCodec, preset: HardwarePreset) -> Self {
248        self.settings.video_encoder = VideoEncoder::Hardware { codec, preset };
249        self
250    }
251
252    /// Builds and returns the configured replay buffer output.
253    pub fn build(mut self) -> Result<ObsReplayBufferOutputRef, ObsError> {
254        if self.settings.max_size_mb <= 0 {
255            return Err(ObsError::InvalidOperation(
256                "max_size_mb must be greater than 0".into(),
257            ));
258        }
259
260        if self.settings.max_time_sec <= 0 {
261            return Err(ObsError::InvalidOperation(
262                "max_time_sec must be greater than 0".into(),
263            ));
264        }
265
266        // Create replay buffer settings
267        let mut output_settings = self.context.data()?;
268        output_settings.set_int("max_time_sec", self.settings.max_time_sec)?;
269        output_settings.set_int("max_size_mb", self.settings.max_size_mb)?;
270        output_settings.set_string("format", self.settings.format.clone())?;
271        output_settings.set_string("extension", self.settings.extension.clone())?;
272        output_settings.set_string("directory", self.settings.directory.clone().build())?;
273        output_settings.set_bool("allow_spaces", self.settings.allow_spaces)?;
274
275        log::trace!(
276            "Replay buffer output settings: {:?}",
277            output_settings.get_json()
278        );
279
280        // Create the replay buffer output
281        let output_info = OutputInfo::new(
282            "replay_buffer",
283            self.settings.name.clone(),
284            Some(output_settings),
285            None,
286        );
287
288        let output = self.context.replay_buffer(output_info)?;
289
290        // Create and configure video encoder (with hardware fallback)
291        let video_encoder_type =
292            select_video_encoder_type(&self.context, &self.settings.video_encoder)?;
293        let mut video_settings = self.context.data()?;
294
295        self.configure_video_encoder(&mut video_settings)?;
296
297        let video_encoder_info = VideoEncoderInfo::new(
298            video_encoder_type,
299            format!("{}_video_encoder", self.settings.name),
300            Some(video_settings),
301            None,
302        );
303
304        output.create_and_set_video_encoder(video_encoder_info)?;
305
306        // Create and configure audio encoder
307        let audio_encoder_type = match &self.settings.audio_encoder {
308            AudioEncoder::AAC => ObsAudioEncoderType::FFMPEG_AAC,
309            AudioEncoder::Opus => ObsAudioEncoderType::FFMPEG_OPUS,
310            AudioEncoder::Custom(encoder_type) => encoder_type.clone(),
311        };
312
313        log::trace!("Selected audio encoder: {:?}", audio_encoder_type);
314        let mut audio_settings = self.context.data()?;
315        audio_settings.set_string("rate_control", "CBR")?;
316        audio_settings.set_int("bitrate", self.settings.audio_bitrate as i64)?;
317
318        let audio_encoder_info = AudioEncoderInfo::new(
319            audio_encoder_type,
320            format!("{}_audio_encoder", self.settings.name),
321            Some(audio_settings),
322            None,
323        );
324
325        log::trace!("Creating audio encoder with info: {:?}", audio_encoder_info);
326        output.create_and_set_audio_encoder(audio_encoder_info, 0)?;
327
328        Ok(output)
329    }
330
331    fn get_encoder_preset(&self, encoder: &VideoEncoder) -> Option<&str> {
332        match encoder {
333            VideoEncoder::Auto(_) => None,
334            VideoEncoder::X264(preset) => Some(preset.as_str()),
335            VideoEncoder::Hardware { preset, .. } => Some(preset.as_str()),
336            VideoEncoder::Custom(_) => None,
337        }
338    }
339
340    fn configure_video_encoder(&self, settings: &mut ObsData) -> Result<(), ObsError> {
341        // Set rate control to CBR
342        settings.set_string("rate_control", "CBR")?;
343        settings.set_int("bitrate", self.settings.video_bitrate as i64)?;
344
345        // Set preset if available
346        if let Some(preset) = self.get_encoder_preset(&self.settings.video_encoder) {
347            settings.set_string("preset", preset)?;
348        }
349
350        // Apply custom encoder settings if provided
351        if let Some(ref custom) = self.settings.custom_encoder_settings {
352            settings.set_string("x264opts", custom.as_str())?;
353        }
354
355        Ok(())
356    }
357}