Skip to main content

libobs_wrapper\utils/
error.rs

1use std::fmt::Display;
2
3use crate::enums::ObsResetVideoStatus;
4
5/// Error type for OBS function calls.
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub enum ObsError {
8    /// The `obs_startup` function failed on libobs.
9    Failure,
10    /// This error is emitted if a dummy DLL was loaded instead of the real libobs DLL. Make sure you bootstrap properly with libobs-bootstrapper
11    InvalidDll,
12    /// Failed to lock mutex describing whether there is a
13    /// thread using libobs or not. Report to crate maintainer.
14    MutexFailure,
15    /// Some or no thread is already using libobs. This is a bug!
16    ThreadFailure,
17    /// Unable to initialize/reset the OBS audio subsystem.
18    ResetAudioFailure,
19    /// Unable to reset video.
20    ResetVideoFailure(ObsResetVideoStatus),
21    /// Unable to reset video because the program attempted to
22    /// change the graphics module. This is a bug!
23    ResetVideoFailureGraphicsModule,
24    /// Unable to reset video because some outputs were still active.
25    ResetVideoFailureOutputActive,
26    /// The function returned a null pointer, often indicating
27    /// an error with creating the object of the requested
28    /// pointer.
29    NullPointer(Option<String>),
30    OutputAlreadyActive,
31    OutputStartFailure(Option<String>),
32    OutputStopFailure(Option<String>),
33    OutputPauseFailure(Option<String>),
34    /// A bounded output/replay operation did not observe native completion before its deadline.
35    /// The native operation is not cancelled and may still complete after this error is returned.
36    OutputOperationTimeout {
37        operation: String,
38        timeout_ms: u64,
39    },
40    /// The signal subscription used to observe native completion was disconnected, usually because
41    /// the owning output/runtime was shut down while the caller was waiting.
42    OutputCompletionDisconnected {
43        operation: String,
44    },
45    OutputNotFound,
46    SourceNotFound,
47    SourceNotAvailable(String),
48    InvalidOperation(String),
49    /// Error converting a string between Rust and OBS
50    StringConversionError,
51
52    /// Native error from the Windows API when creating a display
53    DisplayCreationError(String),
54
55    OutputSaveBufferFailure(String),
56
57    /// The obs thread couldn't be called
58    InvocationError(String),
59
60    JsonParseError,
61    /// Couldn't get the sender of the signal
62    NoSenderError,
63    NoAvailableEncoders,
64    /// Error locking a mutex or RwLock. You should probably restart the application to avoid memory leaks.
65    LockError(String),
66    Unexpected(String),
67
68    /// Encoder is still active, stop the attached output before proceeding
69    EncoderActive,
70
71    /// Error during platform-specific initialization
72    PlatformInitError(String),
73
74    /// Error reading/writing to a file
75    IoError(String),
76
77    /// Failed to get data from signal calldata
78    SignalDataError(String),
79
80    /// Failed to convert an enum from a code
81    EnumConversionError(String),
82
83    /// The caller requested metadata using the wrong OBS property category.
84    PropertyTypeMismatch {
85        expected: String,
86    },
87
88    /// A runtime-discovered settings schema does not contain the requested property.
89    PropertyNotFound {
90        name: String,
91    },
92
93    /// A generic property value has the wrong scalar category for the discovered property.
94    PropertyValueTypeMismatch {
95        name: String,
96        expected: String,
97        actual: String,
98    },
99
100    /// A numeric generic property value is outside the range reported by libobs.
101    PropertyValueOutOfRange {
102        name: String,
103        value: String,
104        min: String,
105        max: String,
106    },
107
108    /// A generic value is correctly typed but not accepted by the discovered property metadata.
109    PropertyValueNotAllowed {
110        name: String,
111        value: String,
112    },
113
114    /// The discovered property category is structural/action-oriented and cannot be represented by a scalar setting value.
115    PropertyValueUnsupported {
116        name: String,
117        property_type: String,
118    },
119
120    /// Failed to send/receive on a runtime channel
121    RuntimeChannelError(String),
122
123    /// The bounded OBS actor queue is full.
124    RuntimeQueueFull {
125        capacity: usize,
126    },
127
128    /// The OBS actor panicked while executing a command or cleanup task.
129    RuntimePanicked,
130
131    /// An object from a different OBS runtime/context was passed to this operation.
132    RuntimeMismatch,
133
134    /// A discovered OBS type was used with an incompatible typed creation operation.
135    CapabilityKindMismatch {
136        id: String,
137        expected: String,
138        actual: String,
139    },
140
141    /// A required encoder/service was omitted from a high-level output pipeline.
142    OutputPipelineMissingComponent {
143        output_id: String,
144        component: String,
145    },
146
147    /// A component was supplied to an output that does not accept that component category.
148    OutputPipelineUnexpectedComponent {
149        output_id: String,
150        component: String,
151    },
152
153    /// An encoder codec is incompatible with the selected output type.
154    OutputPipelineUnsupportedCodec {
155        output_id: String,
156        media: String,
157        codec: String,
158    },
159
160    /// A service protocol is incompatible with the selected output type.
161    OutputPipelineUnsupportedProtocol {
162        output_id: String,
163        protocol: String,
164    },
165
166    /// No runtime-discovered output/encoder combination satisfies a high-level request.
167    NoCompatibleOutputGraph {
168        summary: String,
169    },
170
171    /// An audio encoder mixer index exceeded libobs's supported mixer range.
172    AudioMixerIndexOutOfBounds {
173        index: usize,
174        max: usize,
175    },
176
177    /// A blocking operation was requested recursively from the OBS actor thread.
178    RuntimeReentrantBlocking,
179
180    /// Attempted to call a OBS runtime function from outside the OBS thread.
181    /// This error should NEVER occur. If you are not using the runtime manually or have the "enable_runtime" feature enabled
182    /// then please report this to the crate maintainer as this indicates a bug in the crate.
183    RuntimeOutsideThread,
184
185    /// A filter was already applied to a source
186    FilterAlreadyApplied,
187}
188
189#[cfg_attr(coverage_nightly, coverage(off))]
190impl Display for ObsError {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        write!(f, "OBS Error: ")?;
193
194        match self {
195            ObsError::Failure => write!(f, "`obs-startup` function failed on libobs"),
196            ObsError::MutexFailure => write!(
197                f,
198                "Failed to lock mutex describing whether there is a thread using libobs or not. Report to crate maintainer."
199            ),
200            ObsError::ThreadFailure => write!(
201                f,
202                "Some or no thread is already using libobs. This is a bug!"
203            ),
204            ObsError::ResetAudioFailure => write!(f, "Could not initialize/reset OBS audio."),
205            ObsError::ResetVideoFailure(status) => {
206                write!(f, "Could not reset obs video. Status: {:?}", status)
207            }
208            ObsError::ResetVideoFailureGraphicsModule => write!(
209                f,
210                "Unable to reset video because the program attempted to change the graphics module. This is a bug!"
211            ),
212            ObsError::ResetVideoFailureOutputActive => write!(
213                f,
214                "Unable to reset video because some outputs were still active."
215            ),
216            ObsError::NullPointer(e) => write!(
217                f,
218                "The function returned a null pointer, often indicating an error with creating the object of the requested pointer. Details: {:?}",
219                e
220            ),
221            ObsError::OutputAlreadyActive => write!(f, "Output is already active."),
222            ObsError::OutputStartFailure(s) => {
223                write!(f, "Output failed to start. Error is {:?}", s)
224            }
225            ObsError::OutputStopFailure(s) => write!(f, "Output failed to stop. Error is {:?}", s),
226            ObsError::OutputNotFound => write!(f, "Output not found."),
227            ObsError::DisplayCreationError(e) => write!(
228                f,
229                "Native error from the Windows API when creating a display: {:?}",
230                e
231            ),
232            ObsError::OutputSaveBufferFailure(e) => {
233                write!(f, "Couldn't save output buffer: {:?}", e)
234            }
235            ObsError::SourceNotFound => write!(f, "Source not found."),
236            ObsError::SourceNotAvailable(source_name) => write!(
237                f,
238                "Source {} is not available. See logs or similar to check why.",
239                source_name
240            ),
241            ObsError::InvocationError(e) => write!(f, "The obs thread couldn't be called: {:?}", e),
242            ObsError::JsonParseError => write!(f, "Failed to parse JSON data."),
243            ObsError::NoSenderError => write!(f, "Couldn't get the sender of the signal."),
244            ObsError::NoAvailableEncoders => write!(f, "No available encoders found."),
245            ObsError::OutputPauseFailure(s) => {
246                write!(f, "Output failed to pause. Error is {:?}", s)
247            }
248            ObsError::OutputOperationTimeout {
249                operation,
250                timeout_ms,
251            } => write!(
252                f,
253                "Timed out after {timeout_ms} ms waiting for OBS operation '{operation}'. The native operation was not cancelled and may still complete; re-query output state before retrying or releasing resources."
254            ),
255            ObsError::OutputCompletionDisconnected { operation } => write!(
256                f,
257                "Lost the completion signal for OBS operation '{operation}', usually because the output/runtime is shutting down. Re-query state if the runtime is still available."
258            ),
259            ObsError::LockError(e) => write!(
260                f,
261                "Error locking a mutex or RwLock: {:?}. You should probably restart the application to avoid memory leaks.",
262                e
263            ),
264            ObsError::Unexpected(e) => write!(f, "Unexpected error: {:?}", e),
265            ObsError::EncoderActive => write!(
266                f,
267                "Encoder is still active, stop the attached output before proceeding"
268            ),
269            ObsError::StringConversionError => {
270                write!(f, "Error converting a string between Rust and OBS")
271            }
272            ObsError::PlatformInitError(e) => {
273                write!(f, "Error during platform-specific initialization: {}", e)
274            }
275            ObsError::InvalidOperation(e) => write!(f, "Invalid operation: {}", e),
276            ObsError::IoError(e) => write!(f, "I/O error: {}", e),
277            ObsError::SignalDataError(e) => write!(f, "Signal data error: {}", e),
278            ObsError::EnumConversionError(e) => write!(f, "Enum conversion error: {}", e),
279            ObsError::PropertyTypeMismatch { expected } => {
280                write!(f, "OBS property type mismatch; expected {expected}")
281            }
282            ObsError::PropertyNotFound { name } => {
283                write!(f, "OBS settings schema has no property named '{name}'.")
284            }
285            ObsError::PropertyValueTypeMismatch {
286                name,
287                expected,
288                actual,
289            } => write!(
290                f,
291                "OBS property '{name}' expects {expected}, but received {actual}."
292            ),
293            ObsError::PropertyValueOutOfRange {
294                name,
295                value,
296                min,
297                max,
298            } => write!(
299                f,
300                "OBS property '{name}' value {value} is outside the supported range {min}..={max}."
301            ),
302            ObsError::PropertyValueNotAllowed { name, value } => {
303                write!(f, "OBS property '{name}' does not accept value {value}.")
304            }
305            ObsError::PropertyValueUnsupported {
306                name,
307                property_type,
308            } => write!(
309                f,
310                "OBS property '{name}' ({property_type}) is not a scalar setting value."
311            ),
312            ObsError::RuntimeChannelError(e) => write!(f, "Runtime channel error: {}", e),
313            ObsError::RuntimeQueueFull { capacity } => write!(
314                f,
315                "OBS runtime queue is full (capacity: {}). Batch work or retry later.",
316                capacity
317            ),
318            ObsError::RuntimePanicked => {
319                write!(f, "The OBS actor panicked and has been shut down.")
320            }
321            ObsError::RuntimeMismatch => write!(
322                f,
323                "The operation mixed objects owned by different OBS runtimes."
324            ),
325            ObsError::CapabilityKindMismatch {
326                id,
327                expected,
328                actual,
329            } => write!(
330                f,
331                "Discovered OBS type '{id}' has kind '{actual}', but this operation requires '{expected}'."
332            ),
333            ObsError::OutputPipelineMissingComponent {
334                output_id,
335                component,
336            } => write!(f, "Output pipeline for '{output_id}' requires {component}."),
337            ObsError::OutputPipelineUnexpectedComponent {
338                output_id,
339                component,
340            } => write!(
341                f,
342                "Output pipeline for '{output_id}' does not accept {component}."
343            ),
344            ObsError::OutputPipelineUnsupportedCodec {
345                output_id,
346                media,
347                codec,
348            } => write!(
349                f,
350                "Output '{output_id}' does not support {media} codec '{codec}'."
351            ),
352            ObsError::OutputPipelineUnsupportedProtocol {
353                output_id,
354                protocol,
355            } => write!(
356                f,
357                "Output '{output_id}' does not support service protocol '{protocol}'."
358            ),
359            ObsError::NoCompatibleOutputGraph { summary } => {
360                write!(f, "No compatible OBS output graph: {summary}")
361            }
362            ObsError::AudioMixerIndexOutOfBounds { index, max } => {
363                write!(f, "Audio mixer index {index} is out of bounds (max {max}).")
364            }
365            ObsError::RuntimeReentrantBlocking => write!(
366                f,
367                "A blocking operation cannot wait for an OBS callback from the OBS actor thread."
368            ),
369            ObsError::InvalidDll => write!(
370                f,
371                "A dummy DLL was loaded instead of the real libobs DLL. Make sure you bootstrap properly with libobs-bootstrapper"
372            ),
373            #[cfg(feature = "enable_runtime")]
374            ObsError::RuntimeOutsideThread => write!(
375                f,
376                "Attempted to call a OBS runtime function from outside the OBS thread. This is a bug in the crate!"
377            ),
378            #[cfg(not(feature = "enable_runtime"))]
379            ObsError::RuntimeOutsideThread => write!(
380                f,
381                "Attempted to call a OBS runtime function from outside the OBS thread. Make sure that you do not use any OBS struct from a different thread than the one where the ObsContext was initialized. THIS BUG WILL CAUSE MEMORY CORRUPTION OR DEADLOCKS!"
382            ),
383            ObsError::FilterAlreadyApplied => write!(f, "Filter was applied already."),
384        }
385    }
386}
387
388impl std::error::Error for ObsError {}