Skip to main content

grafton_ndi/advanced/
finder.rs

1//! The metadata sources advertise to a finder.
2
3#[cfg(any(test, ndi_has_advanced_source_metadata))]
4use std::ffi::c_char;
5
6use crate::{
7    sys::advanced::{native, SourceMetadata},
8    Finder, Result, Source,
9};
10
11#[cfg(any(test, ndi_has_advanced_source_metadata))]
12use crate::finder::{decode_source, SnapshotBudget};
13
14/// A discovered source together with the metadata it advertises.
15///
16/// A sender advertises metadata by naming it in the `send.metadata` property
17/// of its configuration, and a finder is told it by a Discovery Server.
18///
19/// Returned by [`Finder::current_sources_with_metadata`].
20#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21pub struct ExtendedSource {
22    source: Source,
23    metadata: Option<String>,
24}
25
26impl ExtendedSource {
27    /// The source, usable wherever a discovered [`Source`] is.
28    pub fn source(&self) -> &Source {
29        &self.source
30    }
31
32    /// The metadata the source advertises, or `None` when it advertises
33    /// none. Bytes that are not valid UTF-8 are replaced.
34    pub fn metadata(&self) -> Option<&str> {
35        self.metadata.as_deref()
36    }
37
38    /// Take the source, discarding the metadata.
39    pub fn into_source(self) -> Source {
40        self.source
41    }
42}
43
44/// Copy one descriptor of a metadata snapshot. A descriptor the plain
45/// snapshot would leave out is skipped, as is one whose metadata is longer
46/// than the 4 MiB one SDK string may be.
47///
48/// # Safety
49///
50/// Every non-null argument is a NUL-terminated string that stays readable
51/// until this returns.
52#[cfg(any(test, ndi_has_advanced_source_metadata))]
53unsafe fn extended_source(
54    name: *const c_char,
55    address: *const c_char,
56    metadata: *const c_char,
57    budget: &mut SnapshotBudget,
58) -> Result<Option<ExtendedSource>> {
59    // SAFETY: the caller keeps the strings readable while the snapshot policy
60    // copies them, omitting malformed entries without losing their scan charges.
61    let Some(source) = (unsafe { decode_source(name, address, budget, |_| true)? }) else {
62        return Ok(None);
63    };
64    let metadata = if metadata.is_null() {
65        None
66    } else {
67        // SAFETY: non-null was checked; the caller guarantees the terminator.
68        let Some(text) = (unsafe { budget.metadata_text(metadata)? }) else {
69            return Ok(None);
70        };
71        // The SDK gives a source that advertises nothing an empty string.
72        (!text.is_empty()).then_some(text)
73    };
74    Ok(Some(ExtendedSource { source, metadata }))
75}
76
77#[cfg(ndi_has_advanced_source_metadata)]
78impl crate::finder::snapshot_sealed::Sealed for SourceMetadata {}
79
80// SAFETY: the SDK's v2 snapshot obeys the same descriptor/string lifetime
81// contract as v1. The copier includes metadata in the shared byte budget.
82#[cfg(ndi_has_advanced_source_metadata)]
83unsafe impl crate::finder::FinderSnapshot for SourceMetadata {
84    type Descriptor = crate::sys::advanced_bindings::NDIlib_source_v2_t;
85    type Item = ExtendedSource;
86
87    unsafe fn fetch(
88        &self,
89        instance: crate::sys::bindings::NDIlib_find_instance_t,
90        count: &mut u32,
91    ) -> *const Self::Descriptor {
92        // SAFETY: the private snapshot guard supplies a live serialized finder.
93        unsafe { self.NDIlib_find_get_current_sources_v2(instance, count) }
94    }
95
96    unsafe fn copy(
97        &self,
98        source: &Self::Descriptor,
99        budget: &mut SnapshotBudget,
100    ) -> Result<Option<ExtendedSource>> {
101        // SAFETY: the guard keeps this snapshot and all its strings live.
102        unsafe {
103            extended_source(
104                source.p_ndi_name,
105                source.p_url_address,
106                source.p_metadata,
107                budget,
108            )
109        }
110    }
111}
112
113impl Finder {
114    /// The sources currently known, each with the metadata it advertises.
115    ///
116    /// This is [`current_sources`](Self::current_sources) with metadata: a
117    /// snapshot, copied before the SDK can replace it.
118    ///
119    /// # Errors
120    ///
121    /// [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
122    /// without an Advanced runtime.
123    /// [`crate::Error::ResourceLimit`] when the descriptor count or total work
124    /// exceeds the limits of [`Self::current_sources`]. Advertised metadata
125    /// is included in that same byte budget, including lossy UTF-8 expansion.
126    /// [`crate::Error::UnexpectedSdkResult`] with
127    /// [`crate::SdkResultDefect::MalformedDiscoveryData`] for a malformed top-level
128    /// descriptor array, or [`crate::Error::AllocationFailed`] for failed result
129    /// or text reservations. See [`Self::current_sources`] for allocation behavior
130    /// of shared source owners. An isolated malformed descriptor is skipped.
131    #[doc(alias = "NDIlib_find_get_current_sources_v2")]
132    pub fn current_sources_with_metadata(&self) -> Result<Vec<ExtendedSource>> {
133        let table = self.runtime().table::<SourceMetadata>()?;
134        native!(SourceMetadata, table => {
135            self.snapshot(table)
136        })
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use std::ffi::CStr;
143
144    use super::*;
145    use crate::sdk_copy::MAX_SDK_STRING_BYTES;
146
147    #[test]
148    fn plain_and_metadata_snapshots_charge_the_same_source_text() {
149        let name = c"HOST (Camera)".as_ptr();
150        let address = c"192.0.2.7:5961".as_ptr();
151        for (name, address) in [
152            (std::ptr::null(), address),
153            (name, std::ptr::null()),
154            (name, address),
155            (std::ptr::null(), std::ptr::null()),
156        ] {
157            let mut plain_budget = SnapshotBudget::new();
158            let mut metadata_budget = SnapshotBudget::new();
159            // SAFETY: both pointer pairs are null or live terminated literals.
160            let plain =
161                unsafe { crate::finder::decode_source(name, address, &mut plain_budget, |_| true) }
162                    .unwrap();
163            let metadata =
164                unsafe { extended_source(name, address, std::ptr::null(), &mut metadata_budget) }
165                    .unwrap();
166            assert_eq!(
167                plain.as_ref(),
168                metadata.as_ref().map(ExtendedSource::source)
169            );
170            assert_eq!(plain_budget.spent(), metadata_budget.spent());
171        }
172    }
173
174    #[test]
175    fn one_unusable_descriptor_does_not_hide_the_others() {
176        let name = c"HOST (Camera)";
177        let address = c"192.0.2.7:5961";
178        let invalid_utf8 = c"<ndi \xff/>";
179        let copy = |name: Option<&CStr>, address: Option<&CStr>, metadata: Option<&CStr>| {
180            let pointer = |text: Option<&CStr>| text.map_or(std::ptr::null(), CStr::as_ptr);
181            // SAFETY: every pointer is null or a live C string literal.
182            unsafe {
183                extended_source(
184                    pointer(name),
185                    pointer(address),
186                    pointer(metadata),
187                    &mut SnapshotBudget::new(),
188                )
189            }
190            .unwrap()
191        };
192
193        // A source without metadata, as a null pointer and as the empty
194        // string the SDK gives.
195        for nothing in [None, Some(c"")] {
196            let plain = copy(Some(name), Some(address), nothing).unwrap();
197            assert_eq!(plain.source().name(), "HOST (Camera)");
198            assert_eq!(plain.metadata(), None);
199        }
200
201        let lossy = copy(Some(name), Some(address), Some(invalid_utf8)).unwrap();
202        assert_eq!(lossy.metadata(), Some("<ndi \u{fffd}/>"));
203        assert_eq!(lossy.into_source().name(), "HOST (Camera)");
204
205        assert!(copy(Some(invalid_utf8), Some(address), None).is_none());
206        assert!(copy(Some(name), Some(invalid_utf8), None).is_none());
207
208        // Neither a name nor an address: there is nothing to connect to.
209        assert!(copy(None, None, Some(invalid_utf8)).is_none());
210
211        // A name, address or metadata whose terminator lies past the string limit.
212        let mut too_long = vec![b'x'; MAX_SDK_STRING_BYTES + 1];
213        too_long[MAX_SDK_STRING_BYTES] = 0;
214        let too_long = CStr::from_bytes_with_nul(&too_long).unwrap();
215        assert!(copy(Some(too_long), Some(address), None).is_none());
216        assert!(copy(Some(name), Some(too_long), None).is_none());
217        assert!(copy(Some(name), Some(address), Some(too_long)).is_none());
218    }
219}