Skip to main content

libobs_wrapper/
capabilities.rs

1//! Runtime capability discovery and compatibility planning for the loaded OBS installation.
2//!
3//! All enumeration and property inspection is executed on the OBS actor. Values returned from this
4//! module are owned Rust snapshots; no callback-borrowed or temporary libobs pointer escapes into
5//! safe downstream code.
6//!
7//! Use [`ObsCapabilities`] when the application cares about capabilities such as “H.264”, “AAC” or
8//! “RTMP” rather than a specific plugin ID. Selectors expose candidate lists, while
9//! [`ObsCapabilities::best_output_plan`] resolves a complete output/encoder choice and reports
10//! structured rejection reasons when no combination works.
11//!
12//! Each source/output/encoder/service descriptor also exposes runtime property schemas and
13//! form-ready settings snapshots through [`crate::settings`]. This is the plugin-generic path for
14//! third-party OBS settings UIs.
15
16use std::{
17    collections::{HashMap, HashSet},
18    ffi::CStr,
19    os::raw::{c_char, c_void},
20    ptr,
21};
22
23use crate::{
24    context::ObsContext,
25    data::{output::ObsOutputRef, ImmutableObsData, ObsData, ObsDataPointers},
26    encoders::{audio::ObsAudioEncoder, video::ObsVideoEncoder},
27    run_with_obs,
28    runtime::ObsRuntime,
29    scenes::{ObsSceneItemRef, ObsSceneRef},
30    services::ObsServiceRef,
31    settings::{SettingsSchema, SettingsSnapshot},
32    sources::{ObsFilterRef, ObsSourceRef},
33    unsafe_send::Sendable,
34    utils::{ObjectInfo, ObsError, ObsString},
35};
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub enum SourceKind {
39    Input,
40    Filter,
41    Transition,
42    Other,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46pub enum EncoderKind {
47    Audio,
48    Video,
49    Unknown(i64),
50}
51
52bitflags::bitflags! {
53    /// Capability flags reported by libobs for an encoder type.
54    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55    pub struct EncoderCapabilities: u32 {
56        const DEPRECATED = libobs::OBS_ENCODER_CAP_DEPRECATED;
57        const PASS_TEXTURE = libobs::OBS_ENCODER_CAP_PASS_TEXTURE;
58        const DYNAMIC_BITRATE = libobs::OBS_ENCODER_CAP_DYN_BITRATE;
59        const INTERNAL = libobs::OBS_ENCODER_CAP_INTERNAL;
60        const ROI = libobs::OBS_ENCODER_CAP_ROI;
61        const SCALING = libobs::OBS_ENCODER_CAP_SCALING;
62    }
63}
64
65bitflags::bitflags! {
66    /// Capability flags reported by libobs for an output type. Unknown future bits are retained.
67    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68    pub struct OutputCapabilities: u32 {
69        const VIDEO = libobs::OBS_OUTPUT_VIDEO;
70        const AUDIO = libobs::OBS_OUTPUT_AUDIO;
71        const ENCODED = libobs::OBS_OUTPUT_ENCODED;
72        const SERVICE = libobs::OBS_OUTPUT_SERVICE;
73        const MULTI_TRACK_AUDIO = libobs::OBS_OUTPUT_MULTI_TRACK_AUDIO;
74        const CAN_PAUSE = libobs::OBS_OUTPUT_CAN_PAUSE;
75        const MULTI_TRACK_VIDEO = libobs::OBS_OUTPUT_MULTI_TRACK_VIDEO;
76    }
77}
78
79#[derive(Clone, Debug)]
80pub struct SourceTypeInfo {
81    id: String,
82    display_name: Option<String>,
83    kind: SourceKind,
84    output_flags: u32,
85    runtime: ObsRuntime,
86}
87
88impl SourceTypeInfo {
89    pub fn id(&self) -> &str {
90        &self.id
91    }
92
93    pub fn display_name(&self) -> Option<&str> {
94        self.display_name.as_deref()
95    }
96
97    pub fn kind(&self) -> SourceKind {
98        self.kind
99    }
100
101    pub fn output_flags(&self) -> u32 {
102        self.output_flags
103    }
104
105    pub fn properties(&self) -> Result<Vec<PropertyMetadata>, ObsError> {
106        source_properties(&self.runtime, &self.id)
107    }
108
109    pub fn settings_schema(&self) -> Result<SettingsSchema, ObsError> {
110        Ok(SettingsSchema::new(self.properties()?))
111    }
112
113    /// Rebuilds the property tree after asking OBS to apply property-modified callbacks for
114    /// the supplied settings. This reflects dynamic visibility, enabled state, and list items.
115    pub fn settings_schema_for(&self, settings: &ObsData) -> Result<SettingsSchema, ObsError> {
116        self.runtime.ensure_same_runtime(settings.runtime())?;
117        Ok(SettingsSchema::new(source_properties_for_settings(
118            &self.runtime,
119            &self.id,
120            settings,
121        )?))
122    }
123
124    pub fn settings_snapshot_for(&self, settings: &ObsData) -> Result<SettingsSnapshot, ObsError> {
125        let schema = self.settings_schema_for(settings)?;
126        let defaults = self.default_settings()?;
127        schema.snapshot(settings, defaults.as_ref())
128    }
129
130    pub fn default_settings(&self) -> Result<Option<ImmutableObsData>, ObsError> {
131        default_settings(&self.runtime, &self.id, libobs::obs_get_source_defaults)
132    }
133
134    /// Returns an owned mutable copy of this type's defaults. If libobs reports no
135    /// defaults, an empty settings object for the same runtime is returned.
136    pub fn default_settings_mut(&self) -> Result<ObsData, ObsError> {
137        mutable_default_settings(&self.runtime, &self.id, libobs::obs_get_source_defaults)
138    }
139}
140
141#[derive(Clone, Debug)]
142pub struct OutputTypeInfo {
143    id: String,
144    display_name: Option<String>,
145    video_codecs: Vec<String>,
146    audio_codecs: Vec<String>,
147    protocols: Vec<String>,
148    flags: u32,
149    runtime: ObsRuntime,
150}
151
152impl OutputTypeInfo {
153    pub fn id(&self) -> &str {
154        &self.id
155    }
156
157    pub fn display_name(&self) -> Option<&str> {
158        self.display_name.as_deref()
159    }
160
161    pub fn video_codecs(&self) -> &[String] {
162        &self.video_codecs
163    }
164
165    pub fn audio_codecs(&self) -> &[String] {
166        &self.audio_codecs
167    }
168
169    pub fn protocols(&self) -> &[String] {
170        &self.protocols
171    }
172
173    pub fn flags(&self) -> u32 {
174        self.flags
175    }
176
177    pub(crate) fn runtime(&self) -> &ObsRuntime {
178        &self.runtime
179    }
180
181    pub fn capability_flags(&self) -> OutputCapabilities {
182        OutputCapabilities::from_bits_retain(self.flags)
183    }
184
185    pub fn supports_video_codec(&self, codec: &str) -> bool {
186        capability_list_supports(&self.video_codecs, codec)
187    }
188
189    pub fn supports_audio_codec(&self, codec: &str) -> bool {
190        capability_list_supports(&self.audio_codecs, codec)
191    }
192
193    pub fn supports_protocol(&self, protocol: &str) -> bool {
194        capability_list_supports(&self.protocols, protocol)
195    }
196
197    pub fn properties(&self) -> Result<Vec<PropertyMetadata>, ObsError> {
198        type_properties(&self.runtime, &self.id, libobs::obs_get_output_properties)
199    }
200
201    pub fn settings_schema(&self) -> Result<SettingsSchema, ObsError> {
202        Ok(SettingsSchema::new(self.properties()?))
203    }
204
205    pub fn settings_schema_for(&self, settings: &ObsData) -> Result<SettingsSchema, ObsError> {
206        self.runtime.ensure_same_runtime(settings.runtime())?;
207        Ok(SettingsSchema::new(type_properties_for_settings(
208            &self.runtime,
209            &self.id,
210            libobs::obs_get_output_properties,
211            settings,
212        )?))
213    }
214
215    pub fn settings_snapshot_for(&self, settings: &ObsData) -> Result<SettingsSnapshot, ObsError> {
216        let schema = self.settings_schema_for(settings)?;
217        let defaults = self.default_settings()?;
218        schema.snapshot(settings, defaults.as_ref())
219    }
220
221    pub fn default_settings(&self) -> Result<Option<ImmutableObsData>, ObsError> {
222        default_settings(&self.runtime, &self.id, libobs::obs_output_defaults)
223    }
224
225    /// Returns a mutable settings object initialized from this output type's defaults.
226    pub fn default_settings_mut(&self) -> Result<ObsData, ObsError> {
227        mutable_default_settings(&self.runtime, &self.id, libobs::obs_output_defaults)
228    }
229}
230
231#[derive(Clone, Debug)]
232pub struct EncoderTypeInfo {
233    id: String,
234    display_name: Option<String>,
235    kind: EncoderKind,
236    codec: Option<String>,
237    capabilities: u32,
238    runtime: ObsRuntime,
239}
240
241impl EncoderTypeInfo {
242    pub fn id(&self) -> &str {
243        &self.id
244    }
245
246    pub fn display_name(&self) -> Option<&str> {
247        self.display_name.as_deref()
248    }
249
250    pub fn kind(&self) -> EncoderKind {
251        self.kind
252    }
253
254    pub fn codec(&self) -> Option<&str> {
255        self.codec.as_deref()
256    }
257
258    pub fn capabilities(&self) -> u32 {
259        self.capabilities
260    }
261
262    pub fn capability_flags(&self) -> EncoderCapabilities {
263        EncoderCapabilities::from_bits_retain(self.capabilities)
264    }
265
266    pub fn is_deprecated(&self) -> bool {
267        self.capability_flags()
268            .contains(EncoderCapabilities::DEPRECATED)
269    }
270
271    pub fn is_internal(&self) -> bool {
272        self.capability_flags()
273            .contains(EncoderCapabilities::INTERNAL)
274    }
275
276    /// Returns whether this encoder is likely hardware-accelerated.
277    ///
278    /// libobs does not expose one universal hardware bit. Passing textures is a strong
279    /// signal for zero-copy hardware encoders; the fallback ID check covers common
280    /// hardware plugins that do not advertise that capability. This is a preference
281    /// heuristic only and is never used to exclude software fallbacks.
282    pub fn is_likely_hardware_accelerated(&self) -> bool {
283        if self
284            .capability_flags()
285            .contains(EncoderCapabilities::PASS_TEXTURE)
286        {
287            return true;
288        }
289        let id = self.id.to_ascii_lowercase();
290        ["nvenc", "qsv", "amf", "vaapi", "videotoolbox"]
291            .iter()
292            .any(|marker| id.contains(marker))
293    }
294
295    pub fn properties(&self) -> Result<Vec<PropertyMetadata>, ObsError> {
296        type_properties(&self.runtime, &self.id, libobs::obs_get_encoder_properties)
297    }
298
299    pub fn settings_schema(&self) -> Result<SettingsSchema, ObsError> {
300        Ok(SettingsSchema::new(self.properties()?))
301    }
302
303    pub fn settings_schema_for(&self, settings: &ObsData) -> Result<SettingsSchema, ObsError> {
304        self.runtime.ensure_same_runtime(settings.runtime())?;
305        Ok(SettingsSchema::new(type_properties_for_settings(
306            &self.runtime,
307            &self.id,
308            libobs::obs_get_encoder_properties,
309            settings,
310        )?))
311    }
312
313    pub fn settings_snapshot_for(&self, settings: &ObsData) -> Result<SettingsSnapshot, ObsError> {
314        let schema = self.settings_schema_for(settings)?;
315        let defaults = self.default_settings()?;
316        schema.snapshot(settings, defaults.as_ref())
317    }
318
319    pub fn default_settings(&self) -> Result<Option<ImmutableObsData>, ObsError> {
320        default_settings(&self.runtime, &self.id, libobs::obs_encoder_defaults)
321    }
322
323    /// Returns a mutable settings object initialized from this encoder type's defaults.
324    pub fn default_settings_mut(&self) -> Result<ObsData, ObsError> {
325        mutable_default_settings(&self.runtime, &self.id, libobs::obs_encoder_defaults)
326    }
327}
328
329#[derive(Clone, Debug)]
330pub struct ServiceTypeInfo {
331    id: String,
332    display_name: Option<String>,
333    runtime: ObsRuntime,
334}
335
336impl ServiceTypeInfo {
337    pub fn id(&self) -> &str {
338        &self.id
339    }
340
341    pub fn display_name(&self) -> Option<&str> {
342        self.display_name.as_deref()
343    }
344
345    pub fn properties(&self) -> Result<Vec<PropertyMetadata>, ObsError> {
346        type_properties(&self.runtime, &self.id, libobs::obs_get_service_properties)
347    }
348
349    pub fn settings_schema(&self) -> Result<SettingsSchema, ObsError> {
350        Ok(SettingsSchema::new(self.properties()?))
351    }
352
353    pub fn settings_schema_for(&self, settings: &ObsData) -> Result<SettingsSchema, ObsError> {
354        self.runtime.ensure_same_runtime(settings.runtime())?;
355        Ok(SettingsSchema::new(type_properties_for_settings(
356            &self.runtime,
357            &self.id,
358            libobs::obs_get_service_properties,
359            settings,
360        )?))
361    }
362
363    pub fn settings_snapshot_for(&self, settings: &ObsData) -> Result<SettingsSnapshot, ObsError> {
364        let schema = self.settings_schema_for(settings)?;
365        let defaults = self.default_settings()?;
366        schema.snapshot(settings, defaults.as_ref())
367    }
368
369    pub fn default_settings(&self) -> Result<Option<ImmutableObsData>, ObsError> {
370        default_settings(&self.runtime, &self.id, libobs::obs_service_defaults)
371    }
372
373    /// Returns a mutable settings object initialized from this service type's defaults.
374    pub fn default_settings_mut(&self) -> Result<ObsData, ObsError> {
375        mutable_default_settings(&self.runtime, &self.id, libobs::obs_service_defaults)
376    }
377}
378
379#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct ModuleInfo {
381    pub file_name: Option<String>,
382    pub name: Option<String>,
383    pub author: Option<String>,
384    pub description: Option<String>,
385    pub binary_path: Option<String>,
386    pub data_path: Option<String>,
387}
388
389#[derive(Clone, Debug)]
390pub struct ObsCapabilities {
391    source_types: Vec<SourceTypeInfo>,
392    input_types: Vec<SourceTypeInfo>,
393    filter_types: Vec<SourceTypeInfo>,
394    transition_types: Vec<SourceTypeInfo>,
395    outputs: Vec<OutputTypeInfo>,
396    encoders: Vec<EncoderTypeInfo>,
397    services: Vec<ServiceTypeInfo>,
398    protocols: Vec<String>,
399    modules: Vec<ModuleInfo>,
400}
401
402impl ObsCapabilities {
403    pub fn source_types(&self) -> &[SourceTypeInfo] {
404        &self.source_types
405    }
406    pub fn input_types(&self) -> &[SourceTypeInfo] {
407        &self.input_types
408    }
409    pub fn filter_types(&self) -> &[SourceTypeInfo] {
410        &self.filter_types
411    }
412    pub fn transition_types(&self) -> &[SourceTypeInfo] {
413        &self.transition_types
414    }
415    pub fn outputs(&self) -> &[OutputTypeInfo] {
416        &self.outputs
417    }
418    pub fn encoders(&self) -> &[EncoderTypeInfo] {
419        &self.encoders
420    }
421    pub fn services(&self) -> &[ServiceTypeInfo] {
422        &self.services
423    }
424    pub fn protocols(&self) -> &[String] {
425        &self.protocols
426    }
427    pub fn modules(&self) -> &[ModuleInfo] {
428        &self.modules
429    }
430
431    /// Starts a deterministic selection over discovered video encoders.
432    pub fn select_video_encoder(&self) -> EncoderSelector<'_> {
433        EncoderSelector::new(&self.encoders, EncoderKind::Video)
434    }
435
436    /// Starts a deterministic selection over discovered audio encoders.
437    pub fn select_audio_encoder(&self) -> EncoderSelector<'_> {
438        EncoderSelector::new(&self.encoders, EncoderKind::Audio)
439    }
440
441    /// Starts a deterministic selection over discovered outputs.
442    pub fn select_output(&self) -> OutputSelector<'_> {
443        OutputSelector::new(&self.outputs)
444    }
445
446    /// Resolves the best currently available output/encoder combination for a capability request.
447    /// The operation is pure over this owned capability snapshot and never creates native objects.
448    pub fn best_output_plan(
449        &self,
450        request: &OutputCompatibilityRequest,
451    ) -> Result<OutputCompatibilityPlan, OutputCompatibilityReport> {
452        let video_encoder = request.video_codec.as_deref().and_then(|codec| {
453            let selector = self.select_video_encoder().codec(codec);
454            if request.prefer_hardware_video {
455                selector.prefer_hardware().best_available().cloned()
456            } else {
457                selector.best_available().cloned()
458            }
459        });
460        let audio_encoder = request.audio_codec.as_deref().and_then(|codec| {
461            self.select_audio_encoder()
462                .codec(codec)
463                .best_available()
464                .cloned()
465        });
466
467        let mut issues = Vec::new();
468        if let Some(codec) = request.video_codec.as_deref() {
469            if video_encoder.is_none() {
470                issues.push(CompatibilityIssue::NoVideoEncoder {
471                    codec: codec.into(),
472                });
473            }
474        }
475        if let Some(codec) = request.audio_codec.as_deref() {
476            if audio_encoder.is_none() {
477                issues.push(CompatibilityIssue::NoAudioEncoder {
478                    codec: codec.into(),
479                });
480            }
481        }
482
483        let mut matching_outputs = Vec::new();
484        for output in &self.outputs {
485            let mut reasons = Vec::new();
486            if let Some(required_id) = request.output_id.as_deref() {
487                if output.id() != required_id {
488                    reasons.push(OutputRejectionReason::OutputId {
489                        required: required_id.into(),
490                    });
491                }
492            }
493            let flags = output.capability_flags();
494            if !flags.contains(request.required_output_capabilities) {
495                reasons.push(OutputRejectionReason::MissingCapabilities {
496                    required: request.required_output_capabilities,
497                    actual: flags,
498                });
499            }
500            if let Some(protocol) = request.protocol.as_deref() {
501                if !output.supports_protocol(protocol) {
502                    reasons.push(OutputRejectionReason::Protocol {
503                        required: protocol.into(),
504                    });
505                }
506            }
507            if let Some(codec) = request.video_codec.as_deref() {
508                if !output.supports_video_codec(codec) {
509                    reasons.push(OutputRejectionReason::VideoCodec {
510                        required: codec.into(),
511                    });
512                }
513            }
514            if let Some(codec) = request.audio_codec.as_deref() {
515                if !output.supports_audio_codec(codec) {
516                    reasons.push(OutputRejectionReason::AudioCodec {
517                        required: codec.into(),
518                    });
519                }
520            }
521            if reasons.is_empty() {
522                matching_outputs.push(output.clone());
523            } else {
524                issues.push(CompatibilityIssue::OutputRejected {
525                    output_id: output.id.clone(),
526                    reasons,
527                });
528            }
529        }
530
531        matching_outputs.sort_by(|a, b| a.id.cmp(&b.id));
532        let output = matching_outputs.into_iter().next();
533        if output.is_none() {
534            issues.push(CompatibilityIssue::NoCompatibleOutput);
535        }
536
537        let video_required = request.video_codec.is_some();
538        let audio_required = request.audio_codec.is_some();
539        match (
540            output,
541            video_required && video_encoder.is_none(),
542            audio_required && audio_encoder.is_none(),
543        ) {
544            (Some(output), false, false) => Ok(OutputCompatibilityPlan {
545                output,
546                video_encoder,
547                audio_encoder,
548                protocol: request.protocol.clone(),
549            }),
550            _ => Err(OutputCompatibilityReport { issues }),
551        }
552    }
553}
554
555/// Requirements used when resolving an output graph from runtime-discovered capabilities.
556#[derive(Clone, Debug, Default)]
557pub struct OutputCompatibilityRequest {
558    output_id: Option<String>,
559    protocol: Option<String>,
560    video_codec: Option<String>,
561    audio_codec: Option<String>,
562    required_output_capabilities: OutputCapabilities,
563    prefer_hardware_video: bool,
564}
565
566impl OutputCompatibilityRequest {
567    pub fn new() -> Self {
568        Self::default()
569    }
570
571    /// Restricts matching to one concrete output type while still validating codecs/flags.
572    pub fn output_id(mut self, output_id: impl Into<String>) -> Self {
573        self.output_id = Some(output_id.into());
574        self
575    }
576
577    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
578        self.protocol = Some(protocol.into());
579        self
580    }
581
582    pub fn video_codec(mut self, codec: impl Into<String>) -> Self {
583        self.video_codec = Some(codec.into());
584        self
585    }
586
587    pub fn audio_codec(mut self, codec: impl Into<String>) -> Self {
588        self.audio_codec = Some(codec.into());
589        self
590    }
591
592    pub fn require_output_capabilities(mut self, capabilities: OutputCapabilities) -> Self {
593        self.required_output_capabilities |= capabilities;
594        self
595    }
596
597    pub fn prefer_hardware_video(mut self, prefer: bool) -> Self {
598        self.prefer_hardware_video = prefer;
599        self
600    }
601}
602
603/// A concrete compatible choice of output and encoders from one capability snapshot.
604#[derive(Clone, Debug)]
605pub struct OutputCompatibilityPlan {
606    output: OutputTypeInfo,
607    video_encoder: Option<EncoderTypeInfo>,
608    audio_encoder: Option<EncoderTypeInfo>,
609    protocol: Option<String>,
610}
611
612impl OutputCompatibilityPlan {
613    pub fn output(&self) -> &OutputTypeInfo {
614        &self.output
615    }
616    pub fn video_encoder(&self) -> Option<&EncoderTypeInfo> {
617        self.video_encoder.as_ref()
618    }
619    pub fn audio_encoder(&self) -> Option<&EncoderTypeInfo> {
620        self.audio_encoder.as_ref()
621    }
622    pub fn protocol(&self) -> Option<&str> {
623        self.protocol.as_deref()
624    }
625}
626
627#[derive(Clone, Debug, PartialEq, Eq)]
628pub enum OutputRejectionReason {
629    OutputId {
630        required: String,
631    },
632    MissingCapabilities {
633        required: OutputCapabilities,
634        actual: OutputCapabilities,
635    },
636    Protocol {
637        required: String,
638    },
639    VideoCodec {
640        required: String,
641    },
642    AudioCodec {
643        required: String,
644    },
645}
646
647#[derive(Clone, Debug, PartialEq, Eq)]
648pub enum CompatibilityIssue {
649    NoVideoEncoder {
650        codec: String,
651    },
652    NoAudioEncoder {
653        codec: String,
654    },
655    OutputRejected {
656        output_id: String,
657        reasons: Vec<OutputRejectionReason>,
658    },
659    NoCompatibleOutput,
660}
661
662#[derive(Clone, Debug, PartialEq, Eq)]
663pub struct OutputCompatibilityReport {
664    issues: Vec<CompatibilityIssue>,
665}
666
667impl OutputCompatibilityReport {
668    pub fn issues(&self) -> &[CompatibilityIssue] {
669        &self.issues
670    }
671
672    pub fn summary(&self) -> String {
673        let encoder_issues = self
674            .issues
675            .iter()
676            .filter(|issue| {
677                matches!(
678                    issue,
679                    CompatibilityIssue::NoVideoEncoder { .. }
680                        | CompatibilityIssue::NoAudioEncoder { .. }
681                )
682            })
683            .count();
684        let rejected_outputs = self
685            .issues
686            .iter()
687            .filter(|issue| matches!(issue, CompatibilityIssue::OutputRejected { .. }))
688            .count();
689        format!(
690            "no compatible OBS output graph: {encoder_issues} encoder requirement(s) unavailable, {rejected_outputs} output type(s) rejected"
691        )
692    }
693}
694
695/// Filters and ranks discovered encoder descriptors without creating native objects.
696#[derive(Clone, Debug)]
697pub struct EncoderSelector<'a> {
698    encoders: &'a [EncoderTypeInfo],
699    kind: EncoderKind,
700    codec: Option<String>,
701    required_capabilities: EncoderCapabilities,
702    include_deprecated: bool,
703    include_internal: bool,
704    prefer_hardware: bool,
705    require_hardware: bool,
706}
707
708impl<'a> EncoderSelector<'a> {
709    fn new(encoders: &'a [EncoderTypeInfo], kind: EncoderKind) -> Self {
710        Self {
711            encoders,
712            kind,
713            codec: None,
714            required_capabilities: EncoderCapabilities::empty(),
715            include_deprecated: false,
716            include_internal: false,
717            prefer_hardware: false,
718            require_hardware: false,
719        }
720    }
721
722    pub fn codec(mut self, codec: impl Into<String>) -> Self {
723        self.codec = Some(codec.into());
724        self
725    }
726
727    pub fn require_capabilities(mut self, capabilities: EncoderCapabilities) -> Self {
728        self.required_capabilities |= capabilities;
729        self
730    }
731
732    pub fn include_deprecated(mut self, include: bool) -> Self {
733        self.include_deprecated = include;
734        self
735    }
736
737    pub fn include_internal(mut self, include: bool) -> Self {
738        self.include_internal = include;
739        self
740    }
741
742    /// Prefer likely hardware-accelerated encoders while retaining software fallback.
743    pub fn prefer_hardware(mut self) -> Self {
744        self.prefer_hardware = true;
745        self
746    }
747
748    /// Require a descriptor identified as hardware accelerated. Software candidates are excluded.
749    pub fn require_hardware(mut self) -> Self {
750        self.require_hardware = true;
751        self.prefer_hardware = true;
752        self
753    }
754
755    pub fn matches(&self) -> Vec<&'a EncoderTypeInfo> {
756        let mut candidates = self
757            .encoders
758            .iter()
759            .filter(|encoder| encoder.kind == self.kind)
760            .filter(|encoder| self.include_deprecated || !encoder.is_deprecated())
761            .filter(|encoder| self.include_internal || !encoder.is_internal())
762            .filter(|encoder| {
763                self.codec.as_ref().is_none_or(|codec| {
764                    encoder
765                        .codec
766                        .as_deref()
767                        .is_some_and(|actual| actual.eq_ignore_ascii_case(codec))
768                })
769            })
770            .filter(|encoder| {
771                encoder
772                    .capability_flags()
773                    .contains(self.required_capabilities)
774            })
775            .filter(|encoder| !self.require_hardware || encoder.is_likely_hardware_accelerated())
776            .collect::<Vec<_>>();
777
778        candidates.sort_by(|a, b| {
779            let a_hardware = self.prefer_hardware && a.is_likely_hardware_accelerated();
780            let b_hardware = self.prefer_hardware && b.is_likely_hardware_accelerated();
781            b_hardware.cmp(&a_hardware).then_with(|| a.id.cmp(&b.id))
782        });
783        candidates
784    }
785
786    pub fn best_available(&self) -> Option<&'a EncoderTypeInfo> {
787        self.matches().into_iter().next()
788    }
789}
790
791/// Filters discovered outputs by their libobs-declared protocols, codecs, and flags.
792#[derive(Clone, Debug)]
793pub struct OutputSelector<'a> {
794    outputs: &'a [OutputTypeInfo],
795    protocol: Option<String>,
796    video_codec: Option<String>,
797    audio_codec: Option<String>,
798    required_capabilities: OutputCapabilities,
799}
800
801impl<'a> OutputSelector<'a> {
802    fn new(outputs: &'a [OutputTypeInfo]) -> Self {
803        Self {
804            outputs,
805            protocol: None,
806            video_codec: None,
807            audio_codec: None,
808            required_capabilities: OutputCapabilities::empty(),
809        }
810    }
811
812    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
813        self.protocol = Some(protocol.into());
814        self
815    }
816
817    pub fn video_codec(mut self, codec: impl Into<String>) -> Self {
818        self.video_codec = Some(codec.into());
819        self
820    }
821
822    pub fn audio_codec(mut self, codec: impl Into<String>) -> Self {
823        self.audio_codec = Some(codec.into());
824        self
825    }
826
827    pub fn require_capabilities(mut self, capabilities: OutputCapabilities) -> Self {
828        self.required_capabilities |= capabilities;
829        self
830    }
831
832    pub fn matches(&self) -> Vec<&'a OutputTypeInfo> {
833        let mut candidates = self
834            .outputs
835            .iter()
836            .filter(|output| {
837                self.protocol
838                    .as_deref()
839                    .is_none_or(|protocol| output.supports_protocol(protocol))
840            })
841            .filter(|output| {
842                self.video_codec
843                    .as_deref()
844                    .is_none_or(|codec| output.supports_video_codec(codec))
845            })
846            .filter(|output| {
847                self.audio_codec
848                    .as_deref()
849                    .is_none_or(|codec| output.supports_audio_codec(codec))
850            })
851            .filter(|output| {
852                output
853                    .capability_flags()
854                    .contains(self.required_capabilities)
855            })
856            .collect::<Vec<_>>();
857        candidates.sort_by(|a, b| a.id.cmp(&b.id));
858        candidates
859    }
860
861    pub fn best_available(&self) -> Option<&'a OutputTypeInfo> {
862        self.matches().into_iter().next()
863    }
864}
865
866#[derive(Clone, Debug, PartialEq)]
867pub struct PropertyMetadata {
868    pub name: String,
869    pub description: Option<String>,
870    pub long_description: Option<String>,
871    pub enabled: bool,
872    pub visible: bool,
873    pub kind: PropertyKind,
874}
875
876#[derive(Clone, Debug, PartialEq)]
877pub enum PropertyKind {
878    Invalid,
879    Bool,
880    Integer {
881        min: i32,
882        max: i32,
883        step: i32,
884        suffix: Option<String>,
885        control: NumberControl,
886    },
887    Float {
888        min: f64,
889        max: f64,
890        step: f64,
891        suffix: Option<String>,
892        control: NumberControl,
893    },
894    Text {
895        text_type: TextType,
896        monospace: bool,
897        info_type: TextInfoType,
898        word_wrap: bool,
899    },
900    Path {
901        path_type: PathType,
902        filter: Option<String>,
903        default_path: Option<String>,
904    },
905    List {
906        list_type: ListType,
907        format: ListFormat,
908        items: Vec<ListItem>,
909    },
910    Color,
911    Button {
912        button_type: ButtonType,
913        url: Option<String>,
914    },
915    Font,
916    EditableList {
917        list_type: EditableListType,
918        filter: Option<String>,
919        default_path: Option<String>,
920    },
921    FrameRate {
922        options: Vec<FrameRateOption>,
923        ranges: Vec<FrameRateRange>,
924    },
925    Group {
926        group_type: GroupType,
927        properties: Vec<PropertyMetadata>,
928    },
929    ColorAlpha,
930    /// A property type introduced by a newer libobs than this crate knows about.
931    Unknown(i64),
932}
933
934macro_rules! raw_enum {
935    ($name:ident { $($variant:ident = $constant:path),+ $(,)? }) => {
936        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
937        pub enum $name {
938            $($variant,)+
939            Unknown(i64),
940        }
941        impl $name {
942            fn from_raw(raw: i64) -> Self {
943                $(if raw == $constant as i64 { return Self::$variant; })+
944                Self::Unknown(raw)
945            }
946        }
947    };
948}
949
950raw_enum!(NumberControl {
951    Scroller = libobs::obs_number_type_OBS_NUMBER_SCROLLER,
952    Slider = libobs::obs_number_type_OBS_NUMBER_SLIDER,
953});
954raw_enum!(TextType {
955    Default = libobs::obs_text_type_OBS_TEXT_DEFAULT,
956    Password = libobs::obs_text_type_OBS_TEXT_PASSWORD,
957    Multiline = libobs::obs_text_type_OBS_TEXT_MULTILINE,
958    Info = libobs::obs_text_type_OBS_TEXT_INFO,
959});
960raw_enum!(TextInfoType {
961    Normal = libobs::obs_text_info_type_OBS_TEXT_INFO_NORMAL,
962    Warning = libobs::obs_text_info_type_OBS_TEXT_INFO_WARNING,
963    Error = libobs::obs_text_info_type_OBS_TEXT_INFO_ERROR,
964});
965raw_enum!(PathType {
966    File = libobs::obs_path_type_OBS_PATH_FILE,
967    FileSave = libobs::obs_path_type_OBS_PATH_FILE_SAVE,
968    Directory = libobs::obs_path_type_OBS_PATH_DIRECTORY,
969});
970raw_enum!(ListType {
971    Invalid = libobs::obs_combo_type_OBS_COMBO_TYPE_INVALID,
972    Editable = libobs::obs_combo_type_OBS_COMBO_TYPE_EDITABLE,
973    List = libobs::obs_combo_type_OBS_COMBO_TYPE_LIST,
974    Radio = libobs::obs_combo_type_OBS_COMBO_TYPE_RADIO,
975});
976raw_enum!(ListFormat {
977    Invalid = libobs::obs_combo_format_OBS_COMBO_FORMAT_INVALID,
978    Int = libobs::obs_combo_format_OBS_COMBO_FORMAT_INT,
979    Float = libobs::obs_combo_format_OBS_COMBO_FORMAT_FLOAT,
980    String = libobs::obs_combo_format_OBS_COMBO_FORMAT_STRING,
981    Bool = libobs::obs_combo_format_OBS_COMBO_FORMAT_BOOL,
982});
983raw_enum!(ButtonType {
984    Default = libobs::obs_button_type_OBS_BUTTON_DEFAULT,
985    Url = libobs::obs_button_type_OBS_BUTTON_URL,
986});
987raw_enum!(EditableListType {
988    Strings = libobs::obs_editable_list_type_OBS_EDITABLE_LIST_TYPE_STRINGS,
989    Files = libobs::obs_editable_list_type_OBS_EDITABLE_LIST_TYPE_FILES,
990    FilesAndUrls = libobs::obs_editable_list_type_OBS_EDITABLE_LIST_TYPE_FILES_AND_URLS,
991});
992raw_enum!(GroupType {
993    Invalid = libobs::obs_group_type_OBS_COMBO_INVALID,
994    Normal = libobs::obs_group_type_OBS_GROUP_NORMAL,
995    Checkable = libobs::obs_group_type_OBS_GROUP_CHECKABLE,
996});
997
998#[derive(Clone, Debug, PartialEq)]
999pub struct ListItem {
1000    pub name: String,
1001    pub value: ListValue,
1002    pub disabled: bool,
1003}
1004
1005#[derive(Clone, Debug, PartialEq)]
1006pub enum ListValue {
1007    String(String),
1008    Int(i64),
1009    Float(f64),
1010    Bool(bool),
1011    UnknownFormat(i64),
1012}
1013
1014#[derive(Clone, Debug, PartialEq, Eq)]
1015pub struct FrameRateOption {
1016    pub name: Option<String>,
1017    pub description: Option<String>,
1018}
1019
1020#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1021pub struct FrameRate {
1022    pub numerator: u32,
1023    pub denominator: u32,
1024}
1025
1026#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1027pub struct FrameRateRange {
1028    pub min: FrameRate,
1029    pub max: FrameRate,
1030}
1031
1032impl ObsSceneRef {
1033    /// Creates a source from a discovered descriptor and adds it directly to this scene.
1034    pub fn add_discovered_source(
1035        &mut self,
1036        source_type: &SourceTypeInfo,
1037        name: impl Into<ObsString>,
1038        settings: Option<ObsData>,
1039    ) -> Result<ObsSceneItemRef<ObsSourceRef>, ObsError> {
1040        self.runtime().ensure_same_runtime(&source_type.runtime)?;
1041        if source_type.kind == SourceKind::Filter {
1042            return Err(capability_kind_mismatch(
1043                &source_type.id,
1044                "source/input/transition",
1045                "filter",
1046            ));
1047        }
1048        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1049        let source = ObsSourceRef::new_from_info(
1050            ObjectInfo::new(source_type.id.as_str(), name, settings, None),
1051            self.runtime().clone(),
1052        )?;
1053        self.add(source)
1054    }
1055}
1056
1057impl ObsContext {
1058    pub fn source_types(&self) -> Result<Vec<SourceTypeInfo>, ObsError> {
1059        discover_sources(self.runtime())
1060    }
1061
1062    pub fn input_types(&self) -> Result<Vec<SourceTypeInfo>, ObsError> {
1063        discover_source_category(
1064            self.runtime(),
1065            SourceKind::Input,
1066            libobs::obs_enum_input_types,
1067        )
1068    }
1069
1070    pub fn filter_types(&self) -> Result<Vec<SourceTypeInfo>, ObsError> {
1071        discover_source_category(
1072            self.runtime(),
1073            SourceKind::Filter,
1074            libobs::obs_enum_filter_types,
1075        )
1076    }
1077
1078    pub fn transition_types(&self) -> Result<Vec<SourceTypeInfo>, ObsError> {
1079        discover_source_category(
1080            self.runtime(),
1081            SourceKind::Transition,
1082            libobs::obs_enum_transition_types,
1083        )
1084    }
1085
1086    pub fn output_types(&self) -> Result<Vec<OutputTypeInfo>, ObsError> {
1087        discover_outputs(self.runtime())
1088    }
1089
1090    pub fn encoder_types(&self) -> Result<Vec<EncoderTypeInfo>, ObsError> {
1091        discover_encoders(self.runtime())
1092    }
1093
1094    pub fn service_types(&self) -> Result<Vec<ServiceTypeInfo>, ObsError> {
1095        discover_services(self.runtime())
1096    }
1097
1098    pub fn protocols(&self) -> Result<Vec<String>, ObsError> {
1099        discover_protocols(self.runtime())
1100    }
1101
1102    pub fn loaded_modules(&self) -> Result<Vec<ModuleInfo>, ObsError> {
1103        discover_modules(self.runtime())
1104    }
1105
1106    pub fn source_type(&self, id: &str) -> Result<Option<SourceTypeInfo>, ObsError> {
1107        Ok(self.source_types()?.into_iter().find(|info| info.id == id))
1108    }
1109
1110    pub fn output_type(&self, id: &str) -> Result<Option<OutputTypeInfo>, ObsError> {
1111        Ok(self.output_types()?.into_iter().find(|info| info.id == id))
1112    }
1113
1114    pub fn encoder_type(&self, id: &str) -> Result<Option<EncoderTypeInfo>, ObsError> {
1115        Ok(self.encoder_types()?.into_iter().find(|info| info.id == id))
1116    }
1117
1118    pub fn service_type(&self, id: &str) -> Result<Option<ServiceTypeInfo>, ObsError> {
1119        Ok(self.service_types()?.into_iter().find(|info| info.id == id))
1120    }
1121
1122    /// Creates a typed source from a discovered source descriptor. Filters use
1123    /// [`ObsContext::create_filter`] so callers cannot accidentally lose filter semantics.
1124    pub fn create_source(
1125        &self,
1126        source_type: &SourceTypeInfo,
1127        name: impl Into<ObsString>,
1128        settings: Option<ObsData>,
1129    ) -> Result<ObsSourceRef, ObsError> {
1130        self.runtime().ensure_same_runtime(&source_type.runtime)?;
1131        if source_type.kind == SourceKind::Filter {
1132            return Err(capability_kind_mismatch(
1133                &source_type.id,
1134                "source/input/transition",
1135                "filter",
1136            ));
1137        }
1138        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1139        ObsSourceRef::new_from_info(
1140            ObjectInfo::new(source_type.id.as_str(), name, settings, None),
1141            self.runtime().clone(),
1142        )
1143    }
1144
1145    /// Creates and registers a typed filter from a discovered filter descriptor.
1146    pub fn create_filter(
1147        &mut self,
1148        filter_type: &SourceTypeInfo,
1149        name: impl Into<ObsString>,
1150        settings: Option<ObsData>,
1151    ) -> Result<ObsFilterRef, ObsError> {
1152        self.runtime().ensure_same_runtime(&filter_type.runtime)?;
1153        if filter_type.kind != SourceKind::Filter {
1154            return Err(capability_kind_mismatch(
1155                &filter_type.id,
1156                "filter",
1157                &format!("{:?}", filter_type.kind),
1158            ));
1159        }
1160        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1161        self.obs_filter(ObjectInfo::new(
1162            filter_type.id.as_str(),
1163            name,
1164            settings,
1165            None,
1166        ))
1167    }
1168
1169    /// Creates and registers an output from a discovered output descriptor.
1170    pub fn create_output(
1171        &mut self,
1172        output_type: &OutputTypeInfo,
1173        name: impl Into<ObsString>,
1174        settings: Option<ObsData>,
1175    ) -> Result<ObsOutputRef, ObsError> {
1176        self.runtime().ensure_same_runtime(&output_type.runtime)?;
1177        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1178        self.output(ObjectInfo::new(
1179            output_type.id.as_str(),
1180            name,
1181            settings,
1182            None,
1183        ))
1184    }
1185
1186    /// Creates a video encoder from a discovered encoder descriptor.
1187    pub fn create_video_encoder(
1188        &self,
1189        encoder_type: &EncoderTypeInfo,
1190        name: impl Into<ObsString>,
1191        settings: Option<ObsData>,
1192    ) -> Result<std::sync::Arc<ObsVideoEncoder>, ObsError> {
1193        self.runtime().ensure_same_runtime(&encoder_type.runtime)?;
1194        if encoder_type.kind != EncoderKind::Video {
1195            return Err(capability_kind_mismatch(
1196                &encoder_type.id,
1197                "video encoder",
1198                &format!("{:?}", encoder_type.kind),
1199            ));
1200        }
1201        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1202        ObsVideoEncoder::new_from_info(
1203            ObjectInfo::new(encoder_type.id.as_str(), name, settings, None),
1204            self.runtime().clone(),
1205        )
1206    }
1207
1208    /// Creates an audio encoder from a discovered descriptor for a native OBS mix.
1209    ///
1210    /// The historical `mixer_index` parameter selects the encoder's input mix. Prefer
1211    /// [`Self::create_audio_encoder_for_mix`] in new code so it cannot be confused with an output
1212    /// encoder attachment slot.
1213    pub fn create_audio_encoder(
1214        &self,
1215        encoder_type: &EncoderTypeInfo,
1216        name: impl Into<ObsString>,
1217        settings: Option<ObsData>,
1218        mixer_index: usize,
1219    ) -> Result<std::sync::Arc<ObsAudioEncoder>, ObsError> {
1220        self.create_audio_encoder_for_mix(
1221            encoder_type,
1222            name,
1223            settings,
1224            crate::data::audio::AudioMixIndex::new(mixer_index)?,
1225        )
1226    }
1227
1228    /// Creates an audio encoder that reads from `mix`.
1229    pub fn create_audio_encoder_for_mix(
1230        &self,
1231        encoder_type: &EncoderTypeInfo,
1232        name: impl Into<ObsString>,
1233        settings: Option<ObsData>,
1234        mix: crate::data::audio::AudioMixIndex,
1235    ) -> Result<std::sync::Arc<ObsAudioEncoder>, ObsError> {
1236        self.runtime().ensure_same_runtime(&encoder_type.runtime)?;
1237        if encoder_type.kind != EncoderKind::Audio {
1238            return Err(capability_kind_mismatch(
1239                &encoder_type.id,
1240                "audio encoder",
1241                &format!("{:?}", encoder_type.kind),
1242            ));
1243        }
1244        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1245        ObsAudioEncoder::new_from_info_for_mix(
1246            ObjectInfo::new(encoder_type.id.as_str(), name, settings, None),
1247            mix,
1248            self.runtime().clone(),
1249        )
1250    }
1251
1252    /// Creates a managed streaming service from a discovered service descriptor.
1253    pub fn create_service(
1254        &self,
1255        service_type: &ServiceTypeInfo,
1256        name: impl Into<ObsString>,
1257        settings: Option<ObsData>,
1258    ) -> Result<std::sync::Arc<ObsServiceRef>, ObsError> {
1259        self.runtime().ensure_same_runtime(&service_type.runtime)?;
1260        ensure_settings_runtime(self.runtime(), settings.as_ref())?;
1261        ObsServiceRef::new_from_info(
1262            ObjectInfo::new(service_type.id.as_str(), name, settings, None),
1263            self.runtime().clone(),
1264        )
1265    }
1266
1267    pub fn capabilities(&self) -> Result<ObsCapabilities, ObsError> {
1268        Ok(ObsCapabilities {
1269            source_types: self.source_types()?,
1270            input_types: self.input_types()?,
1271            filter_types: self.filter_types()?,
1272            transition_types: self.transition_types()?,
1273            outputs: self.output_types()?,
1274            encoders: self.encoder_types()?,
1275            services: self.service_types()?,
1276            protocols: self.protocols()?,
1277            modules: self.loaded_modules()?,
1278        })
1279    }
1280}
1281
1282type EnumTypeFn = unsafe extern "C" fn(usize, *mut *const c_char) -> bool;
1283type PropertiesFn = unsafe extern "C" fn(*const c_char) -> *mut libobs::obs_properties_t;
1284type DefaultsFn = unsafe extern "C" fn(*const c_char) -> *mut libobs::obs_data_t;
1285
1286#[allow(unknown_lints)]
1287#[allow(ensure_obs_call_in_runtime)]
1288/// # Safety
1289/// Run on the OBS actor with an initialized registry. `enum_fn` must be a libobs type
1290/// enumerator returning null or registry-owned NUL-terminated IDs.
1291unsafe fn enum_ids_on_actor(enum_fn: EnumTypeFn) -> Vec<String> {
1292    let mut result = Vec::new();
1293    let mut index = 0;
1294    loop {
1295        let mut id = ptr::null();
1296        // SAFETY: The libobs enumerator runs on the actor; id is a live writable out pointer.
1297        if !unsafe { enum_fn(index, &mut id) } {
1298            break;
1299        }
1300        index += 1;
1301        // SAFETY: Enumeration returns a registry-owned NUL-terminated ID; copy it before leaving
1302        // the actor.
1303        if let Some(id) = unsafe { cstr_owned(id) } {
1304            result.push(id);
1305        }
1306    }
1307    result.sort();
1308    result.dedup();
1309    result
1310}
1311
1312fn discover_sources(runtime: &ObsRuntime) -> Result<Vec<SourceTypeInfo>, ObsError> {
1313    let runtime_for_result = runtime.clone();
1314    // SAFETY: run_with_obs retains the initialized runtime on its owner thread; local C IDs outlive
1315    // lookups and registry strings are copied before returning.
1316    let rows = run_with_obs!(runtime, move || unsafe {
1317        let inputs: HashSet<_> = enum_ids_on_actor(libobs::obs_enum_input_types)
1318            .into_iter()
1319            .collect();
1320        let filters: HashSet<_> = enum_ids_on_actor(libobs::obs_enum_filter_types)
1321            .into_iter()
1322            .collect();
1323        let transitions: HashSet<_> = enum_ids_on_actor(libobs::obs_enum_transition_types)
1324            .into_iter()
1325            .collect();
1326        enum_ids_on_actor(libobs::obs_enum_source_types)
1327            .into_iter()
1328            .map(|id| {
1329                let c_id = ObsString::new(&id);
1330                let display_name = cstr_owned(libobs::obs_source_get_display_name(c_id.as_ptr().0));
1331                let output_flags = libobs::obs_get_source_output_flags(c_id.as_ptr().0);
1332                let kind = if inputs.contains(&id) {
1333                    SourceKind::Input
1334                } else if filters.contains(&id) {
1335                    SourceKind::Filter
1336                } else if transitions.contains(&id) {
1337                    SourceKind::Transition
1338                } else {
1339                    SourceKind::Other
1340                };
1341                (id, display_name, kind, output_flags)
1342            })
1343            .collect::<Vec<_>>()
1344    })?;
1345    Ok(rows
1346        .into_iter()
1347        .map(|(id, display_name, kind, output_flags)| SourceTypeInfo {
1348            id,
1349            display_name,
1350            kind,
1351            output_flags,
1352            runtime: runtime_for_result.clone(),
1353        })
1354        .collect())
1355}
1356
1357fn discover_source_category(
1358    runtime: &ObsRuntime,
1359    kind: SourceKind,
1360    enum_fn: EnumTypeFn,
1361) -> Result<Vec<SourceTypeInfo>, ObsError> {
1362    let runtime_for_result = runtime.clone();
1363    // SAFETY: run_with_obs retains the initialized runtime on its owner thread; local C IDs outlive
1364    // lookups and registry strings are copied before returning.
1365    let rows = run_with_obs!(runtime, move || unsafe {
1366        enum_ids_on_actor(enum_fn)
1367            .into_iter()
1368            .map(|id| {
1369                let c_id = ObsString::new(&id);
1370                (
1371                    id,
1372                    cstr_owned(libobs::obs_source_get_display_name(c_id.as_ptr().0)),
1373                    libobs::obs_get_source_output_flags(c_id.as_ptr().0),
1374                )
1375            })
1376            .collect::<Vec<_>>()
1377    })?;
1378    Ok(rows
1379        .into_iter()
1380        .map(|(id, display_name, output_flags)| SourceTypeInfo {
1381            id,
1382            display_name,
1383            kind,
1384            output_flags,
1385            runtime: runtime_for_result.clone(),
1386        })
1387        .collect())
1388}
1389
1390fn discover_outputs(runtime: &ObsRuntime) -> Result<Vec<OutputTypeInfo>, ObsError> {
1391    let runtime_for_result = runtime.clone();
1392    // SAFETY: run_with_obs retains the initialized runtime on its owner thread; local C IDs outlive
1393    // lookups and registry strings are copied before returning.
1394    let rows = run_with_obs!(runtime, move || unsafe {
1395        let ids = enum_ids_on_actor(libobs::obs_enum_output_types);
1396        let mut protocols_by_output = HashMap::<String, Vec<String>>::new();
1397        let mut protocol_index = 0;
1398        loop {
1399            let mut protocol = ptr::null_mut();
1400            if !libobs::obs_enum_output_protocols(protocol_index, &mut protocol) {
1401                break;
1402            }
1403            protocol_index += 1;
1404            let Some(protocol_name) = cstr_owned(protocol.cast_const()) else {
1405                continue;
1406            };
1407            let mut matching_ids = HashSet::<String>::new();
1408            libobs::obs_enum_output_types_with_protocol(
1409                protocol.cast_const(),
1410                (&mut matching_ids as *mut HashSet<String>).cast::<c_void>(),
1411                Some(collect_output_type_id),
1412            );
1413            for id in matching_ids {
1414                protocols_by_output
1415                    .entry(id)
1416                    .or_default()
1417                    .push(protocol_name.clone());
1418            }
1419        }
1420
1421        ids.into_iter()
1422            .map(|id| {
1423                let c_id = ObsString::new(&id);
1424                let mut protocols = protocols_by_output.remove(&id).unwrap_or_default();
1425                protocols.sort();
1426                protocols.dedup();
1427                (
1428                    id,
1429                    cstr_owned(libobs::obs_output_get_display_name(c_id.as_ptr().0)),
1430                    split_capability_string(libobs::obs_get_output_supported_video_codecs(
1431                        c_id.as_ptr().0,
1432                    )),
1433                    split_capability_string(libobs::obs_get_output_supported_audio_codecs(
1434                        c_id.as_ptr().0,
1435                    )),
1436                    protocols,
1437                    libobs::obs_get_output_flags(c_id.as_ptr().0),
1438                )
1439            })
1440            .collect::<Vec<_>>()
1441    })?;
1442    Ok(rows
1443        .into_iter()
1444        .map(
1445            |(id, display_name, video_codecs, audio_codecs, protocols, flags)| OutputTypeInfo {
1446                id,
1447                display_name,
1448                video_codecs,
1449                audio_codecs,
1450                protocols,
1451                flags,
1452                runtime: runtime_for_result.clone(),
1453            },
1454        )
1455        .collect())
1456}
1457
1458/// # Safety
1459/// `data` must point to a live `HashSet<String>` for this synchronous libobs enumeration
1460/// and `id` must be null or a valid callback-borrowed C string for the duration of the call.
1461unsafe extern "C" fn collect_output_type_id(data: *mut c_void, id: *const c_char) -> bool {
1462    let Some(ids) = data.cast::<HashSet<String>>().as_mut() else {
1463        return false;
1464    };
1465    if let Some(id) = cstr_owned(id) {
1466        ids.insert(id);
1467    }
1468    true
1469}
1470
1471fn discover_encoders(runtime: &ObsRuntime) -> Result<Vec<EncoderTypeInfo>, ObsError> {
1472    let runtime_for_result = runtime.clone();
1473    // SAFETY: run_with_obs retains the initialized runtime on its owner thread; local C IDs outlive
1474    // lookups and registry strings are copied before returning.
1475    let rows = run_with_obs!(runtime, move || unsafe {
1476        enum_ids_on_actor(libobs::obs_enum_encoder_types)
1477            .into_iter()
1478            .map(|id| {
1479                let c_id = ObsString::new(&id);
1480                let raw_kind = libobs::obs_get_encoder_type(c_id.as_ptr().0) as i64;
1481                let kind = if raw_kind == libobs::obs_encoder_type_OBS_ENCODER_AUDIO as i64 {
1482                    EncoderKind::Audio
1483                } else if raw_kind == libobs::obs_encoder_type_OBS_ENCODER_VIDEO as i64 {
1484                    EncoderKind::Video
1485                } else {
1486                    EncoderKind::Unknown(raw_kind)
1487                };
1488                (
1489                    id,
1490                    cstr_owned(libobs::obs_encoder_get_display_name(c_id.as_ptr().0)),
1491                    kind,
1492                    cstr_owned(libobs::obs_get_encoder_codec(c_id.as_ptr().0)),
1493                    libobs::obs_get_encoder_caps(c_id.as_ptr().0),
1494                )
1495            })
1496            .collect::<Vec<_>>()
1497    })?;
1498    Ok(rows
1499        .into_iter()
1500        .map(
1501            |(id, display_name, kind, codec, capabilities)| EncoderTypeInfo {
1502                id,
1503                display_name,
1504                kind,
1505                codec,
1506                capabilities,
1507                runtime: runtime_for_result.clone(),
1508            },
1509        )
1510        .collect())
1511}
1512
1513fn discover_services(runtime: &ObsRuntime) -> Result<Vec<ServiceTypeInfo>, ObsError> {
1514    let runtime_for_result = runtime.clone();
1515    // SAFETY: run_with_obs retains the initialized runtime on its owner thread; local C IDs outlive
1516    // lookups and registry strings are copied before returning.
1517    let rows = run_with_obs!(runtime, move || unsafe {
1518        enum_ids_on_actor(libobs::obs_enum_service_types)
1519            .into_iter()
1520            .map(|id| {
1521                let c_id = ObsString::new(&id);
1522                (
1523                    id,
1524                    cstr_owned(libobs::obs_service_get_display_name(c_id.as_ptr().0)),
1525                )
1526            })
1527            .collect::<Vec<_>>()
1528    })?;
1529    Ok(rows
1530        .into_iter()
1531        .map(|(id, display_name)| ServiceTypeInfo {
1532            id,
1533            display_name,
1534            runtime: runtime_for_result.clone(),
1535        })
1536        .collect())
1537}
1538
1539fn discover_protocols(runtime: &ObsRuntime) -> Result<Vec<String>, ObsError> {
1540    // SAFETY: The actor retains the initialized output registry; protocol is a live
1541    // out pointer, and returned NUL-terminated protocol strings are copied immediately.
1542    run_with_obs!(runtime, move || unsafe {
1543        let mut result = Vec::new();
1544        let mut index = 0;
1545        loop {
1546            let mut protocol: *mut c_char = ptr::null_mut();
1547            if !libobs::obs_enum_output_protocols(index, &mut protocol) {
1548                break;
1549            }
1550            index += 1;
1551            if let Some(protocol) = cstr_owned(protocol.cast_const()) {
1552                result.push(protocol);
1553            }
1554        }
1555        result.sort();
1556        result.dedup();
1557        result
1558    })
1559}
1560
1561fn discover_modules(runtime: &ObsRuntime) -> Result<Vec<ModuleInfo>, ObsError> {
1562    #[allow(unknown_lints)]
1563    #[allow(ensure_obs_call_in_runtime)]
1564    /// # Safety
1565    /// Called synchronously by `obs_enum_modules` on the OBS actor. `param` points to the
1566    /// live `Vec<ModuleInfo>` owned by `discover_modules` for the complete enumeration.
1567    /// `module` must be the live module lent by libobs for this callback.
1568    unsafe extern "C" fn collect(param: *mut std::ffi::c_void, module: *mut libobs::obs_module_t) {
1569        // SAFETY: obs_enum_modules synchronously passes our exclusively borrowed Vec; no reference
1570        // escapes.
1571        let rows = unsafe { &mut *(param as *mut Vec<ModuleInfo>) };
1572        rows.push(ModuleInfo {
1573            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1574            // copied during this callback.
1575            file_name: unsafe { cstr_owned(libobs::obs_get_module_file_name(module)) },
1576            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1577            // copied during this callback.
1578            name: unsafe { cstr_owned(libobs::obs_get_module_name(module)) },
1579            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1580            // copied during this callback.
1581            author: unsafe { cstr_owned(libobs::obs_get_module_author(module)) },
1582            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1583            // copied during this callback.
1584            description: unsafe { cstr_owned(libobs::obs_get_module_description(module)) },
1585            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1586            // copied during this callback.
1587            binary_path: unsafe { cstr_owned(libobs::obs_get_module_binary_path(module)) },
1588            // SAFETY: obs_enum_modules lends a live module; its NUL-terminated metadata strings are
1589            // copied during this callback.
1590            data_path: unsafe { cstr_owned(libobs::obs_get_module_data_path(module)) },
1591        });
1592    }
1593
1594    // SAFETY: This actor command retains the initialized module registry while
1595    // synchronous enumeration passes the live local Vec to collect.
1596    run_with_obs!(runtime, move || unsafe {
1597        let mut rows: Vec<ModuleInfo> = Vec::new();
1598        // SAFETY: obs_enum_modules is synchronous; the Vec address remains valid for the
1599        // complete callback sequence and only owned strings are retained afterward.
1600        libobs::obs_enum_modules(Some(collect), (&mut rows as *mut Vec<ModuleInfo>).cast());
1601        rows.sort_by(|a, b| a.file_name.cmp(&b.file_name));
1602        rows
1603    })
1604}
1605
1606fn type_properties(
1607    runtime: &ObsRuntime,
1608    id: &str,
1609    getter: PropertiesFn,
1610) -> Result<Vec<PropertyMetadata>, ObsError> {
1611    let id = ObsString::new(id);
1612    // SAFETY: The id CString lives through the actor call; getter transfers an owned tree, which is
1613    // copied and destroyed by snapshot_owned_properties.
1614    run_with_obs!(runtime, (id), move || unsafe {
1615        // SAFETY: The property tree is created, fully copied, and destroyed on the actor.
1616        let properties = getter(id.as_ptr().0);
1617        snapshot_owned_properties(properties)
1618    })
1619}
1620
1621fn type_properties_for_settings(
1622    runtime: &ObsRuntime,
1623    id: &str,
1624    getter: PropertiesFn,
1625    settings: &ObsData,
1626) -> Result<Vec<PropertyMetadata>, ObsError> {
1627    runtime.ensure_same_runtime(settings.runtime())?;
1628    let id = ObsString::new(id);
1629    let settings_ptr = settings.as_ptr();
1630    run_with_obs!(runtime, (id, settings_ptr), move || unsafe {
1631        // Safety: the property tree and settings handle are live on the OBS actor. Applying
1632        // settings invokes plugin property-modified callbacks synchronously before snapshotting.
1633        let properties = getter(id.as_ptr().0);
1634        if properties.is_null() {
1635            return Vec::new();
1636        }
1637        libobs::obs_properties_apply_settings(properties, settings_ptr.get_ptr());
1638        snapshot_owned_properties(properties)
1639    })
1640}
1641
1642fn source_properties(runtime: &ObsRuntime, id: &str) -> Result<Vec<PropertyMetadata>, ObsError> {
1643    type_properties(runtime, id, libobs::obs_get_source_properties)
1644}
1645
1646fn source_properties_for_settings(
1647    runtime: &ObsRuntime,
1648    id: &str,
1649    settings: &ObsData,
1650) -> Result<Vec<PropertyMetadata>, ObsError> {
1651    type_properties_for_settings(runtime, id, libobs::obs_get_source_properties, settings)
1652}
1653
1654fn default_settings(
1655    runtime: &ObsRuntime,
1656    id: &str,
1657    getter: DefaultsFn,
1658) -> Result<Option<ImmutableObsData>, ObsError> {
1659    let id = ObsString::new(id);
1660    // SAFETY: The id CString lives through the actor call; getter transfers an owned data reference
1661    // into ImmutableObsData below.
1662    let ptr = run_with_obs!(runtime, (id), move || unsafe {
1663        // SAFETY: Type-default lookup runs on the OBS actor and returns an owned obs_data_t.
1664        Sendable(getter(id.as_ptr().0))
1665    })?;
1666    if ptr.0.is_null() {
1667        Ok(None)
1668    } else {
1669        Ok(Some(ImmutableObsData::from_raw_pointer(
1670            ptr,
1671            runtime.clone(),
1672        )))
1673    }
1674}
1675
1676fn mutable_default_settings(
1677    runtime: &ObsRuntime,
1678    id: &str,
1679    getter: DefaultsFn,
1680) -> Result<ObsData, ObsError> {
1681    let id = ObsString::new(id);
1682    // Safety: the defaults callback is invoked on the OBS actor and returns an owned
1683    // obs_data_t reference when non-null.
1684    let ptr = run_with_obs!(runtime, (id), move || unsafe {
1685        Sendable(getter(id.as_ptr().0))
1686    })?;
1687    if ptr.0.is_null() {
1688        ObsData::new(runtime.clone())
1689    } else {
1690        Ok(ObsData::from_raw_pointer(ptr, runtime.clone()))
1691    }
1692}
1693
1694fn ensure_settings_runtime(
1695    runtime: &ObsRuntime,
1696    settings: Option<&ObsData>,
1697) -> Result<(), ObsError> {
1698    if let Some(settings) = settings {
1699        runtime.ensure_same_runtime(settings.runtime())?;
1700    }
1701    Ok(())
1702}
1703
1704fn capability_kind_mismatch(id: &str, expected: &str, actual: &str) -> ObsError {
1705    ObsError::CapabilityKindMismatch {
1706        id: id.to_owned(),
1707        expected: expected.to_owned(),
1708        actual: actual.to_owned(),
1709    }
1710}
1711
1712#[allow(unknown_lints)]
1713#[allow(ensure_obs_call_in_runtime)]
1714/// # Safety
1715/// Run on the OBS actor. Transfer sole ownership of `properties` (or null) to this
1716/// helper, which destroys it. No other code may mutate or destroy it during copying.
1717pub(crate) unsafe fn snapshot_owned_properties(
1718    properties: *mut libobs::obs_properties_t,
1719) -> Vec<PropertyMetadata> {
1720    if properties.is_null() {
1721        return Vec::new();
1722    }
1723    // SAFETY: This helper owns the tree until copying finishes on the actor.
1724    let result = unsafe { snapshot_properties(properties) };
1725    // SAFETY: The tree was transferred here; copying is finished and no borrowed property or string
1726    // escapes.
1727    unsafe { libobs::obs_properties_destroy(properties) };
1728    result
1729}
1730
1731#[allow(unknown_lints)]
1732#[allow(ensure_obs_call_in_runtime)]
1733/// # Safety
1734/// Run on the OBS actor. Retain the live property tree without mutation or destruction
1735/// throughout this call, including recursive snapshots of its child groups.
1736unsafe fn snapshot_properties(properties: *mut libobs::obs_properties_t) -> Vec<PropertyMetadata> {
1737    let mut result = Vec::new();
1738    // SAFETY: The caller retains this property tree without mutation throughout the actor snapshot.
1739    let mut property = unsafe { libobs::obs_properties_first(properties) };
1740    while !property.is_null() {
1741        // SAFETY: property is borrowed from the retained tree on the actor; returned NUL-terminated
1742        // strings are copied before mutation or destruction.
1743        let name = unsafe { cstr_owned(libobs::obs_property_name(property)) }.unwrap_or_default();
1744        // SAFETY: property is borrowed from the retained tree on the actor; returned NUL-terminated
1745        // strings are copied before mutation or destruction.
1746        let description = unsafe { cstr_owned(libobs::obs_property_description(property)) };
1747        let long_description =
1748            // SAFETY: property is borrowed from the retained tree on the actor; returned
1749            // NUL-terminated strings are copied before mutation or destruction.
1750            unsafe { cstr_owned(libobs::obs_property_long_description(property)) };
1751        // SAFETY: property is an iterator borrow from the tree retained unchanged on the actor.
1752        let enabled = unsafe { libobs::obs_property_enabled(property) };
1753        // SAFETY: property is an iterator borrow from the tree retained unchanged on the actor.
1754        let visible = unsafe { libobs::obs_property_visible(property) };
1755        // SAFETY: property is an iterator borrow from the tree retained unchanged on the actor.
1756        let raw_type = unsafe { libobs::obs_property_get_type(property) } as i64;
1757        // SAFETY: property belongs to the retained tree and raw_type was queried from this same
1758        // property on the actor.
1759        let kind = unsafe { snapshot_property_kind(property, raw_type) };
1760        result.push(PropertyMetadata {
1761            name,
1762            description,
1763            long_description,
1764            enabled,
1765            visible,
1766            kind,
1767        });
1768        // SAFETY: property is borrowed from the retained tree; next writes the local cursor and
1769        // does not mutate the tree.
1770        if !unsafe { libobs::obs_property_next(&mut property) } {
1771            break;
1772        }
1773    }
1774    result
1775}
1776
1777#[allow(unknown_lints)]
1778#[allow(ensure_obs_call_in_runtime)]
1779/// # Safety
1780/// Run on the OBS actor. `property` must belong to a retained, unchanged tree, and
1781/// `raw_type` must be the type returned by obs_property_get_type for this property.
1782unsafe fn snapshot_property_kind(
1783    property: *mut libobs::obs_property_t,
1784    raw_type: i64,
1785) -> PropertyKind {
1786    if raw_type == libobs::obs_property_type_OBS_PROPERTY_INVALID as i64 {
1787        PropertyKind::Invalid
1788    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_BOOL as i64 {
1789        PropertyKind::Bool
1790    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_INT as i64 {
1791        PropertyKind::Integer {
1792            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1793            // the actor; borrowed strings are copied immediately.
1794            min: unsafe { libobs::obs_property_int_min(property) },
1795            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1796            // the actor; borrowed strings are copied immediately.
1797            max: unsafe { libobs::obs_property_int_max(property) },
1798            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1799            // the actor; borrowed strings are copied immediately.
1800            step: unsafe { libobs::obs_property_int_step(property) },
1801            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1802            // the actor; borrowed strings are copied immediately.
1803            suffix: unsafe { cstr_owned(libobs::obs_property_int_suffix(property)) },
1804            control: NumberControl::from_raw(
1805                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1806                // on the actor; borrowed strings are copied immediately.
1807                unsafe { libobs::obs_property_int_type(property) } as i64,
1808            ),
1809        }
1810    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_FLOAT as i64 {
1811        PropertyKind::Float {
1812            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1813            // the actor; borrowed strings are copied immediately.
1814            min: unsafe { libobs::obs_property_float_min(property) },
1815            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1816            // the actor; borrowed strings are copied immediately.
1817            max: unsafe { libobs::obs_property_float_max(property) },
1818            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1819            // the actor; borrowed strings are copied immediately.
1820            step: unsafe { libobs::obs_property_float_step(property) },
1821            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1822            // the actor; borrowed strings are copied immediately.
1823            suffix: unsafe { cstr_owned(libobs::obs_property_float_suffix(property)) },
1824            control: NumberControl::from_raw(
1825                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1826                // on the actor; borrowed strings are copied immediately.
1827                unsafe { libobs::obs_property_float_type(property) } as i64,
1828            ),
1829        }
1830    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_TEXT as i64 {
1831        PropertyKind::Text {
1832            text_type: TextType::from_raw(
1833                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1834                // on the actor; borrowed strings are copied immediately.
1835                unsafe { libobs::obs_property_text_type(property) } as i64,
1836            ),
1837            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1838            // the actor; borrowed strings are copied immediately.
1839            monospace: unsafe { libobs::obs_property_text_monospace(property) },
1840            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1841            // the actor; borrowed strings are copied immediately.
1842            info_type: TextInfoType::from_raw(unsafe {
1843                libobs::obs_property_text_info_type(property)
1844            } as i64),
1845            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1846            // the actor; borrowed strings are copied immediately.
1847            word_wrap: unsafe { libobs::obs_property_text_info_word_wrap(property) },
1848        }
1849    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_PATH as i64 {
1850        PropertyKind::Path {
1851            path_type: PathType::from_raw(
1852                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1853                // on the actor; borrowed strings are copied immediately.
1854                unsafe { libobs::obs_property_path_type(property) } as i64,
1855            ),
1856            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1857            // the actor; borrowed strings are copied immediately.
1858            filter: unsafe { cstr_owned(libobs::obs_property_path_filter(property)) },
1859            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1860            // the actor; borrowed strings are copied immediately.
1861            default_path: unsafe { cstr_owned(libobs::obs_property_path_default_path(property)) },
1862        }
1863    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_LIST as i64 {
1864        // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on the
1865        // actor; borrowed strings are copied immediately.
1866        let format_raw = unsafe { libobs::obs_property_list_format(property) } as i64;
1867        // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on the
1868        // actor; borrowed strings are copied immediately.
1869        let count = unsafe { libobs::obs_property_list_item_count(property) };
1870        let mut items = Vec::with_capacity(count);
1871        for index in 0..count {
1872            // SAFETY: The type/format branch matches this getter; index is below the queried count
1873            // and the tree is unchanged. Borrowed strings are copied immediately.
1874            let name = unsafe { cstr_owned(libobs::obs_property_list_item_name(property, index)) }
1875                .unwrap_or_default();
1876            let value = if format_raw == libobs::obs_combo_format_OBS_COMBO_FORMAT_STRING as i64 {
1877                ListValue::String(
1878                    // SAFETY: The type/format branch matches this getter; index is below the
1879                    // queried count and the tree is unchanged. Borrowed strings are copied
1880                    // immediately.
1881                    unsafe { cstr_owned(libobs::obs_property_list_item_string(property, index)) }
1882                        .unwrap_or_default(),
1883                )
1884            } else if format_raw == libobs::obs_combo_format_OBS_COMBO_FORMAT_INT as i64 {
1885                // SAFETY: The type/format branch matches this getter; index is below the queried
1886                // count and the tree is unchanged. Borrowed strings are copied immediately.
1887                ListValue::Int(unsafe { libobs::obs_property_list_item_int(property, index) })
1888            } else if format_raw == libobs::obs_combo_format_OBS_COMBO_FORMAT_FLOAT as i64 {
1889                // SAFETY: The type/format branch matches this getter; index is below the queried
1890                // count and the tree is unchanged. Borrowed strings are copied immediately.
1891                ListValue::Float(unsafe { libobs::obs_property_list_item_float(property, index) })
1892            } else if format_raw == libobs::obs_combo_format_OBS_COMBO_FORMAT_BOOL as i64 {
1893                // SAFETY: The type/format branch matches this getter; index is below the queried
1894                // count and the tree is unchanged. Borrowed strings are copied immediately.
1895                ListValue::Bool(unsafe { libobs::obs_property_list_item_bool(property, index) })
1896            } else {
1897                ListValue::UnknownFormat(format_raw)
1898            };
1899            items.push(ListItem {
1900                name,
1901                value,
1902                // SAFETY: The type/format branch matches this getter; index is below the queried
1903                // count and the tree is unchanged. Borrowed strings are copied immediately.
1904                disabled: unsafe { libobs::obs_property_list_item_disabled(property, index) },
1905            });
1906        }
1907        PropertyKind::List {
1908            list_type: ListType::from_raw(
1909                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1910                // on the actor; borrowed strings are copied immediately.
1911                unsafe { libobs::obs_property_list_type(property) } as i64,
1912            ),
1913            format: ListFormat::from_raw(format_raw),
1914            items,
1915        }
1916    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_COLOR as i64 {
1917        PropertyKind::Color
1918    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_BUTTON as i64 {
1919        PropertyKind::Button {
1920            button_type: ButtonType::from_raw(
1921                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1922                // on the actor; borrowed strings are copied immediately.
1923                unsafe { libobs::obs_property_button_type(property) } as i64,
1924            ),
1925            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1926            // the actor; borrowed strings are copied immediately.
1927            url: unsafe { cstr_owned(libobs::obs_property_button_url(property)) },
1928        }
1929    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_FONT as i64 {
1930        PropertyKind::Font
1931    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_EDITABLE_LIST as i64 {
1932        PropertyKind::EditableList {
1933            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1934            // the actor; borrowed strings are copied immediately.
1935            list_type: EditableListType::from_raw(unsafe {
1936                libobs::obs_property_editable_list_type(property)
1937            } as i64),
1938            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1939            // the actor; borrowed strings are copied immediately.
1940            filter: unsafe { cstr_owned(libobs::obs_property_editable_list_filter(property)) },
1941            // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on
1942            // the actor; borrowed strings are copied immediately.
1943            default_path: unsafe {
1944                cstr_owned(libobs::obs_property_editable_list_default_path(property))
1945            },
1946        }
1947    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_FRAME_RATE as i64 {
1948        // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on the
1949        // actor; borrowed strings are copied immediately.
1950        let option_count = unsafe { libobs::obs_property_frame_rate_options_count(property) };
1951        let mut options = Vec::with_capacity(option_count);
1952        for index in 0..option_count {
1953            options.push(FrameRateOption {
1954                // SAFETY: The type/format branch matches this getter; index is below the queried
1955                // count and the tree is unchanged. Borrowed strings are copied immediately.
1956                name: unsafe {
1957                    cstr_owned(libobs::obs_property_frame_rate_option_name(property, index))
1958                },
1959                // SAFETY: The type/format branch matches this getter; index is below the queried
1960                // count and the tree is unchanged. Borrowed strings are copied immediately.
1961                description: unsafe {
1962                    cstr_owned(libobs::obs_property_frame_rate_option_description(
1963                        property, index,
1964                    ))
1965                },
1966            });
1967        }
1968        // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on the
1969        // actor; borrowed strings are copied immediately.
1970        let range_count = unsafe { libobs::obs_property_frame_rate_fps_ranges_count(property) };
1971        let mut ranges = Vec::with_capacity(range_count);
1972        for index in 0..range_count {
1973            // SAFETY: The type/format branch matches this getter; index is below the queried count
1974            // and the tree is unchanged. Borrowed strings are copied immediately.
1975            let min = unsafe { libobs::obs_property_frame_rate_fps_range_min(property, index) };
1976            // SAFETY: The type/format branch matches this getter; index is below the queried count
1977            // and the tree is unchanged. Borrowed strings are copied immediately.
1978            let max = unsafe { libobs::obs_property_frame_rate_fps_range_max(property, index) };
1979            ranges.push(FrameRateRange {
1980                min: FrameRate {
1981                    numerator: min.numerator,
1982                    denominator: min.denominator,
1983                },
1984                max: FrameRate {
1985                    numerator: max.numerator,
1986                    denominator: max.denominator,
1987                },
1988            });
1989        }
1990        PropertyKind::FrameRate { options, ranges }
1991    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_GROUP as i64 {
1992        // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree on the
1993        // actor; borrowed strings are copied immediately.
1994        let content = unsafe { libobs::obs_property_group_content(property) };
1995        PropertyKind::Group {
1996            group_type: GroupType::from_raw(
1997                // SAFETY: raw_type selects matching typed getters on the retained, unchanged tree
1998                // on the actor; borrowed strings are copied immediately.
1999                unsafe { libobs::obs_property_group_type(property) } as i64,
2000            ),
2001            properties: if content.is_null() {
2002                Vec::new()
2003            } else {
2004                // SAFETY: content is a non-null child tree borrowed from the retained parent;
2005                // recursive copying does not destroy it.
2006                unsafe { snapshot_properties(content) }
2007            },
2008        }
2009    } else if raw_type == libobs::obs_property_type_OBS_PROPERTY_COLOR_ALPHA as i64 {
2010        PropertyKind::ColorAlpha
2011    } else {
2012        PropertyKind::Unknown(raw_type)
2013    }
2014}
2015
2016/// # Safety
2017/// A non-null `ptr` must address a NUL-terminated C string that is readable for this call.
2018unsafe fn cstr_owned(ptr: *const c_char) -> Option<String> {
2019    if ptr.is_null() {
2020        None
2021    } else {
2022        Some(
2023            // SAFETY: The unsafe caller guarantees readable storage through the terminating NUL;
2024            // the result is copied into owned Rust storage.
2025            unsafe { CStr::from_ptr(ptr) }
2026                .to_string_lossy()
2027                .into_owned(),
2028        )
2029    }
2030}
2031
2032fn capability_list_supports(values: &[String], requested: &str) -> bool {
2033    values.is_empty()
2034        || values
2035            .iter()
2036            .any(|value| value.eq_ignore_ascii_case(requested))
2037}
2038
2039/// # Safety
2040/// A non-null `ptr` must be readable through its terminating NUL for this call.
2041unsafe fn split_capability_string(ptr: *const c_char) -> Vec<String> {
2042    // SAFETY: The unsafe caller guarantees readable storage through the terminating NUL; the result
2043    // is copied into owned Rust storage.
2044    let Some(value) = (unsafe { cstr_owned(ptr) }) else {
2045        return Vec::new();
2046    };
2047    value
2048        .split(|c: char| c == ',' || c == ';' || c.is_ascii_whitespace())
2049        .filter(|part| !part.is_empty())
2050        .map(str::to_owned)
2051        .collect()
2052}
2053
2054#[cfg(test)]
2055mod tests {
2056    use super::*;
2057
2058    #[test]
2059    fn future_enum_values_are_preserved() {
2060        assert_eq!(
2061            NumberControl::from_raw(99_999),
2062            NumberControl::Unknown(99_999)
2063        );
2064        assert_eq!(ListFormat::from_raw(-7), ListFormat::Unknown(-7));
2065    }
2066
2067    #[test]
2068    fn capability_string_parser_is_owned_and_tolerant() {
2069        let text = std::ffi::CString::new("h264, hevc;av1").unwrap();
2070        // SAFETY: text owns a NUL-terminated CString that remains live throughout parsing.
2071        let parsed = unsafe { split_capability_string(text.as_ptr()) };
2072        assert_eq!(parsed, ["h264", "hevc", "av1"]);
2073    }
2074}