Skip to main content

libobs_wrapper\data\output/
pipeline.rs

1//! High-level validated output-pipeline construction.
2//!
3//! The builder validates the complete encoder/service graph against the selected output
4//! descriptor before it creates or mutates an OBS output. Low-level attachment remains
5//! available through [`super::ObsOutputTrait`] for callers that intentionally need it.
6
7use std::sync::Arc;
8
9use crate::{
10    capabilities::{OutputCapabilities, OutputTypeInfo},
11    context::ObsContext,
12    data::{audio::AudioEncoderSlot, object::ObsObjectTrait, ObsData, ObsDataPointers},
13    encoders::{audio::ObsAudioEncoder, video::ObsVideoEncoder, ObsEncoderTrait},
14    services::ObsServiceRef,
15    utils::{ObsError, ObsString},
16};
17
18use super::{ObsOutputComposition, ObsOutputRef, ObsOutputTrait};
19
20/// Builder for one validated OBS output graph.
21#[derive(Debug)]
22pub struct ObsOutputPipelineBuilder {
23    context: ObsContext,
24    output_type: OutputTypeInfo,
25    name: ObsString,
26    settings: Option<ObsData>,
27    composition: ObsOutputComposition,
28}
29
30impl ObsOutputPipelineBuilder {
31    pub(crate) fn new(
32        context: ObsContext,
33        output_type: OutputTypeInfo,
34        name: ObsString,
35        settings: Option<ObsData>,
36    ) -> Self {
37        Self {
38            context,
39            output_type,
40            name,
41            settings,
42            composition: ObsOutputComposition::new(),
43        }
44    }
45
46    pub fn video_encoder(mut self, encoder: Arc<ObsVideoEncoder>) -> Self {
47        self.composition = self.composition.with_video_encoder(encoder);
48        self
49    }
50
51    /// Compatibility helper: `slot` is an output encoder attachment slot.
52    pub fn audio_encoder(mut self, slot: usize, encoder: Arc<ObsAudioEncoder>) -> Self {
53        self.composition = self.composition.with_audio_encoder(slot, encoder);
54        self
55    }
56
57    pub fn audio_encoder_at_slot(
58        mut self,
59        slot: AudioEncoderSlot,
60        encoder: Arc<ObsAudioEncoder>,
61    ) -> Self {
62        self.composition = self.composition.with_audio_encoder_at_slot(slot, encoder);
63        self
64    }
65
66    pub fn service(mut self, service: Arc<ObsServiceRef>) -> Self {
67        self.composition = self.composition.with_service(service);
68        self
69    }
70
71    /// Validates the complete graph without creating an output.
72    pub fn validate(&self) -> Result<(), ObsError> {
73        self.context
74            .runtime()
75            .ensure_same_runtime(self.output_type.runtime())?;
76
77        if let Some(settings) = self.settings.as_ref() {
78            self.context
79                .runtime()
80                .ensure_same_runtime(settings.runtime())?;
81        }
82
83        let flags = self.output_type.capability_flags();
84        let encoded = flags.contains(OutputCapabilities::ENCODED);
85        let needs_video = encoded && flags.contains(OutputCapabilities::VIDEO);
86        let needs_audio = encoded && flags.contains(OutputCapabilities::AUDIO);
87        let needs_service = flags.contains(OutputCapabilities::SERVICE);
88
89        let video_encoder = self.composition.video_encoder();
90        if needs_video && video_encoder.is_none() {
91            return Err(missing_component(&self.output_type, "a video encoder"));
92        }
93        if video_encoder.is_some() && !needs_video {
94            return Err(unexpected_component(&self.output_type, "a video encoder"));
95        }
96
97        let audio_encoders = self.composition.audio_encoders();
98        if needs_audio && audio_encoders.is_empty() {
99            return Err(missing_component(
100                &self.output_type,
101                "at least one audio encoder",
102            ));
103        }
104        if !audio_encoders.is_empty() && !needs_audio {
105            return Err(unexpected_component(&self.output_type, "audio encoders"));
106        }
107        for (mixer_idx, encoder) in audio_encoders {
108            if *mixer_idx >= libobs::MAX_AUDIO_MIXES as usize {
109                return Err(ObsError::AudioMixerIndexOutOfBounds {
110                    index: *mixer_idx,
111                    max: (libobs::MAX_AUDIO_MIXES - 1) as usize,
112                });
113            }
114            self.context
115                .runtime()
116                .ensure_same_runtime(encoder.runtime())?;
117        }
118
119        let service = self.composition.service();
120        if needs_service && service.is_none() {
121            return Err(missing_component(&self.output_type, "a service"));
122        }
123        if service.is_some() && !needs_service {
124            return Err(unexpected_component(&self.output_type, "a service"));
125        }
126
127        if let Some(encoder) = video_encoder {
128            self.context
129                .runtime()
130                .ensure_same_runtime(encoder.runtime())?;
131            if let Some(codec) = encoder.codec()? {
132                if !self.output_type.video_codecs().is_empty()
133                    && !self.output_type.supports_video_codec(&codec)
134                {
135                    return Err(ObsError::OutputPipelineUnsupportedCodec {
136                        output_id: self.output_type.id().to_owned(),
137                        media: "video".to_owned(),
138                        codec,
139                    });
140                }
141            }
142        }
143
144        for encoder in audio_encoders.values() {
145            if let Some(codec) = encoder.codec()? {
146                if !self.output_type.audio_codecs().is_empty()
147                    && !self.output_type.supports_audio_codec(&codec)
148                {
149                    return Err(ObsError::OutputPipelineUnsupportedCodec {
150                        output_id: self.output_type.id().to_owned(),
151                        media: "audio".to_owned(),
152                        codec,
153                    });
154                }
155            }
156        }
157
158        if let Some(service) = service {
159            self.context
160                .runtime()
161                .ensure_same_runtime(service.runtime())?;
162            if let Some(protocol) = service.protocol()? {
163                if !self.output_type.protocols().is_empty()
164                    && !self.output_type.supports_protocol(&protocol)
165                {
166                    return Err(ObsError::OutputPipelineUnsupportedProtocol {
167                        output_id: self.output_type.id().to_owned(),
168                        protocol,
169                    });
170                }
171            }
172        }
173
174        Ok(())
175    }
176
177    /// Validates the complete graph, creates the output, then applies the desired state.
178    /// No output is created when validation fails.
179    pub fn build(mut self) -> Result<ObsOutputPipeline, ObsError> {
180        self.validate()?;
181        let output =
182            self.context
183                .create_output(&self.output_type, self.name, self.settings.take())?;
184        output.apply_composition(self.composition)?;
185        Ok(ObsOutputPipeline { output })
186    }
187}
188
189/// A fully validated and wired output ready for lifecycle operations.
190#[derive(Clone, Debug)]
191pub struct ObsOutputPipeline {
192    output: ObsOutputRef,
193}
194
195impl ObsOutputPipeline {
196    pub fn output(&self) -> &ObsOutputRef {
197        &self.output
198    }
199
200    pub fn start(&self) -> Result<(), ObsError> {
201        self.output.start()
202    }
203
204    pub fn stop(&self) -> Result<(), ObsError> {
205        self.output.stop()
206    }
207
208    pub fn is_active(&self) -> Result<bool, ObsError> {
209        self.output.is_active()
210    }
211
212    pub fn into_output(self) -> ObsOutputRef {
213        self.output
214    }
215}
216
217impl ObsContext {
218    /// Starts a high-level pipeline builder for a discovered output type.
219    pub fn output_pipeline(
220        &self,
221        output_type: &OutputTypeInfo,
222        name: impl Into<ObsString>,
223        settings: Option<ObsData>,
224    ) -> ObsOutputPipelineBuilder {
225        ObsOutputPipelineBuilder::new(self.clone(), output_type.clone(), name.into(), settings)
226    }
227}
228
229fn missing_component(output_type: &OutputTypeInfo, component: &str) -> ObsError {
230    ObsError::OutputPipelineMissingComponent {
231        output_id: output_type.id().to_owned(),
232        component: component.to_owned(),
233    }
234}
235
236fn unexpected_component(output_type: &OutputTypeInfo, component: &str) -> ObsError {
237    ObsError::OutputPipelineUnexpectedComponent {
238        output_id: output_type.id().to_owned(),
239        component: component.to_owned(),
240    }
241}