Skip to main content

libobs_simple\output/
streaming.rs

1//! Dead-simple capability-driven RTMP streaming.
2//!
3//! This module intentionally chooses the common OBS pieces for the caller: an RTMP output,
4//! H.264 video, AAC audio, and the standard `rtmp_custom` service. Concrete encoder backends are
5//! selected from the loaded OBS installation, preferring hardware while retaining software fallback.
6
7use libobs_wrapper::{
8    capabilities::{OutputCapabilities, OutputCompatibilityRequest},
9    context::ObsContext,
10    data::output::ObsOutputRef,
11    settings::PropertyValue,
12    utils::{ObsError, ObsString},
13};
14
15use super::configure::set_if_supported;
16
17/// Builder for a conventional H.264/AAC RTMP stream.
18#[derive(Debug)]
19pub struct SimpleRtmpStreamingBuilder {
20    context: ObsContext,
21    name: ObsString,
22    server: String,
23    stream_key: String,
24    video_bitrate: u32,
25    audio_bitrate: u32,
26    prefer_hardware_video: bool,
27}
28
29/// Adds the common RTMP streaming workflow to [`ObsContext`].
30pub trait ObsContextStreamingExt {
31    /// Creates a simple RTMP builder using H.264/AAC and runtime capability selection.
32    fn simple_rtmp_stream(
33        &self,
34        name: impl Into<ObsString>,
35        server: impl Into<String>,
36        stream_key: impl Into<String>,
37    ) -> SimpleRtmpStreamingBuilder;
38}
39
40impl ObsContextStreamingExt for ObsContext {
41    fn simple_rtmp_stream(
42        &self,
43        name: impl Into<ObsString>,
44        server: impl Into<String>,
45        stream_key: impl Into<String>,
46    ) -> SimpleRtmpStreamingBuilder {
47        SimpleRtmpStreamingBuilder::new(self.clone(), name, server, stream_key)
48    }
49}
50
51impl SimpleRtmpStreamingBuilder {
52    pub fn new(
53        context: ObsContext,
54        name: impl Into<ObsString>,
55        server: impl Into<String>,
56        stream_key: impl Into<String>,
57    ) -> Self {
58        Self {
59            context,
60            name: name.into(),
61            server: server.into(),
62            stream_key: stream_key.into(),
63            video_bitrate: 6_000,
64            audio_bitrate: 160,
65            prefer_hardware_video: true,
66        }
67    }
68
69    pub fn video_bitrate(mut self, bitrate_kbps: u32) -> Self {
70        self.video_bitrate = bitrate_kbps;
71        self
72    }
73
74    pub fn audio_bitrate(mut self, bitrate_kbps: u32) -> Self {
75        self.audio_bitrate = bitrate_kbps;
76        self
77    }
78
79    /// Controls whether hardware H.264 encoders are ranked ahead of software encoders.
80    /// Software remains available as a fallback either way.
81    pub fn prefer_hardware_video(mut self, prefer: bool) -> Self {
82        self.prefer_hardware_video = prefer;
83        self
84    }
85
86    /// Discovers, configures, validates, and creates the complete RTMP output graph.
87    /// Calling this does not start network I/O; use [`libobs_wrapper::data::output::ObsOutputTrait::start`]
88    /// when the application is ready to stream.
89    pub fn build(self) -> Result<ObsOutputRef, ObsError> {
90        let capabilities = self.context.capabilities()?;
91        let request = OutputCompatibilityRequest::new()
92            .protocol("RTMP")
93            .video_codec("h264")
94            .audio_codec("aac")
95            .prefer_hardware_video(self.prefer_hardware_video)
96            .require_output_capabilities(
97                OutputCapabilities::ENCODED
98                    | OutputCapabilities::VIDEO
99                    | OutputCapabilities::AUDIO
100                    | OutputCapabilities::SERVICE,
101            );
102        let plan = capabilities.best_output_plan(&request).map_err(|report| {
103            ObsError::NoCompatibleOutputGraph {
104                summary: report.summary(),
105            }
106        })?;
107        let video_type = plan
108            .video_encoder()
109            .ok_or_else(|| ObsError::NoCompatibleOutputGraph {
110                summary: "no H.264 video encoder was selected".into(),
111            })?;
112        let audio_type = plan
113            .audio_encoder()
114            .ok_or_else(|| ObsError::NoCompatibleOutputGraph {
115                summary: "no AAC audio encoder was selected".into(),
116            })?;
117
118        let mut video_settings = video_type.default_settings_mut()?;
119        let video_schema = video_type.settings_schema_for(&video_settings)?;
120        set_if_supported(
121            &video_schema,
122            &mut video_settings,
123            "rate_control",
124            PropertyValue::String("CBR".into()),
125        )?;
126        set_if_supported(
127            &video_schema,
128            &mut video_settings,
129            "bitrate",
130            PropertyValue::Integer(i64::from(self.video_bitrate)),
131        )?;
132        let video_encoder = self.context.create_video_encoder(
133            video_type,
134            format!("{}_video", self.name),
135            Some(video_settings),
136        )?;
137
138        let mut audio_settings = audio_type.default_settings_mut()?;
139        let audio_schema = audio_type.settings_schema_for(&audio_settings)?;
140        set_if_supported(
141            &audio_schema,
142            &mut audio_settings,
143            "bitrate",
144            PropertyValue::Integer(i64::from(self.audio_bitrate)),
145        )?;
146        let audio_encoder = self.context.create_audio_encoder(
147            audio_type,
148            format!("{}_audio", self.name),
149            Some(audio_settings),
150            0,
151        )?;
152
153        let service_type = self
154            .context
155            .service_type("rtmp_custom")?
156            .ok_or_else(|| ObsError::SourceNotAvailable("rtmp_custom service".into()))?;
157        let mut service_settings = service_type.default_settings_mut()?;
158        let service_schema = service_type.settings_schema_for(&service_settings)?;
159        service_schema.set(
160            &mut service_settings,
161            "server",
162            PropertyValue::String(self.server),
163        )?;
164        service_schema.set(
165            &mut service_settings,
166            "key",
167            PropertyValue::String(self.stream_key),
168        )?;
169        let service = self.context.create_service(
170            &service_type,
171            format!("{}_service", self.name),
172            Some(service_settings),
173        )?;
174
175        let output_settings = plan.output().default_settings_mut()?;
176        Ok(self
177            .context
178            .output_pipeline(plan.output(), self.name, Some(output_settings))
179            .video_encoder(video_encoder)
180            .audio_encoder(0, audio_encoder)
181            .service(service)
182            .build()?
183            .into_output())
184    }
185}