Skip to main content

grafton_ndi/
finder.rs

1//! NDI source discovery and network browsing.
2
3mod budget;
4
5#[cfg(test)]
6mod cache_retirement_tests;
7
8#[cfg(ndi_test_finder_snapshot_guard)]
9#[path = "../tests/ui/internal/finder_snapshot_guard.rs"]
10mod snapshot_guard_contract;
11
12pub(crate) use budget::SnapshotBudget;
13
14use std::{
15    borrow::Borrow,
16    cell::Cell,
17    collections::{HashMap, HashSet},
18    convert::Infallible,
19    ffi::{c_char, CStr, CString},
20    fmt::{self, Display, Formatter},
21    hash::{Hash, Hasher},
22    net::IpAddr,
23    num::NonZeroU16,
24    ptr,
25    sync::{Arc, Mutex},
26    time::Duration,
27};
28
29use crate::{
30    change_feed::ChangeFeed,
31    list_setting::list_cstring,
32    sys::{self, bindings::*},
33    timeout::{Deadline, NeverStop, Stop, StopResult, POLL_INTERVAL},
34    Error, Ndi, ResourceKind, Result,
35};
36
37/// Configuration for NDI source discovery.
38///
39/// The defaults find the sources of the groups the NDI configuration names,
40/// including those of this machine, and query the configured `networks.ips`.
41///
42/// # Examples
43///
44/// ```
45/// use grafton_ndi::FinderOptions;
46///
47/// // Find sources in specific groups, other machines only
48/// let options = FinderOptions::new()
49///     .show_local_sources(false)
50///     .groups(["Public", "Studio"]);
51///
52/// // Also query hosts that discovery does not reach
53/// let options = FinderOptions::new().extra_ips(["192.168.1.100", "10.0.0.100"]);
54/// ```
55#[derive(Debug, Clone, PartialEq, Eq, Hash)]
56pub struct FinderOptions {
57    show_local_sources: bool,
58    groups: Option<Vec<String>>,
59    extra_ips: Option<Vec<String>>,
60    #[cfg(feature = "advanced")]
61    config: Option<crate::advanced::AdvancedConfig>,
62}
63
64impl Default for FinderOptions {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl FinderOptions {
71    /// Inherit discovery groups from the NDI configuration.
72    #[must_use]
73    pub fn clear_groups(mut self) -> Self {
74        self.groups = None;
75        self
76    }
77
78    /// Inherit direct IP addresses from the NDI configuration.
79    #[must_use]
80    pub fn clear_extra_ips(mut self) -> Self {
81        self.extra_ips = None;
82        self
83    }
84
85    /// Remove the per-instance Advanced configuration override.
86    #[cfg(feature = "advanced")]
87    #[must_use]
88    pub fn clear_config(mut self) -> Self {
89        self.config = None;
90        self
91    }
92
93    /// Whether local sources were requested.
94    #[must_use]
95    pub fn configured_show_local_sources(&self) -> bool {
96        self.show_local_sources
97    }
98
99    /// Requested discovery groups, or `None` to inherit the NDI configuration.
100    #[must_use]
101    pub fn configured_groups(&self) -> Option<&[String]> {
102        self.groups.as_deref()
103    }
104
105    /// Requested direct IP addresses, in their stored order, if any.
106    #[must_use]
107    pub fn configured_extra_ips(&self) -> Option<&[String]> {
108        self.extra_ips.as_deref()
109    }
110
111    /// The stored Advanced configuration handle, if any.
112    #[cfg(feature = "advanced")]
113    #[must_use]
114    pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
115        self.config.as_ref()
116    }
117
118    /// The default options: local sources included, the groups of the NDI
119    /// configuration, and the direct addresses in its `networks.ips`.
120    pub fn new() -> Self {
121        Self {
122            show_local_sources: true,
123            groups: None,
124            extra_ips: None,
125            #[cfg(feature = "advanced")]
126            config: None,
127        }
128    }
129
130    /// Set whether sources on this machine are found.
131    #[must_use]
132    pub fn show_local_sources(mut self, show: bool) -> Self {
133        self.show_local_sources = show;
134        self
135    }
136
137    /// Set a non-empty list of groups to search in place of the NDI configuration.
138    /// Use [`Self::clear_groups`] to inherit the configuration.
139    /// Creation refuses empty elements and elements containing a comma or NUL.
140    #[must_use]
141    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
142        self.groups = Some(groups.into_iter().map(Into::into).collect());
143        self
144    }
145
146    /// Set a non-empty list of individual IP addresses to query directly.
147    /// This replaces `networks.ips` from the NDI configuration. Use
148    /// [`Self::clear_extra_ips`] to inherit the configuration. Creation
149    /// refuses empty elements and elements containing a comma or NUL.
150    #[must_use]
151    pub fn extra_ips(mut self, ips: impl IntoIterator<Item = impl Into<String>>) -> Self {
152        self.extra_ips = Some(ips.into_iter().map(Into::into).collect());
153        self
154    }
155
156    /// Create the finder with this per-instance Advanced SDK configuration,
157    /// which it keeps for as long as it lives.
158    ///
159    /// [`Finder::new`] then needs an Advanced runtime, and a build with the
160    /// Advanced SDK.
161    #[cfg(feature = "advanced")]
162    #[must_use]
163    pub fn config(mut self, config: crate::advanced::AdvancedConfig) -> Self {
164        self.config = Some(config);
165        self
166    }
167}
168
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170struct FindInstance(NDIlib_find_instance_t);
171
172// SAFETY: Processing.NDI.Find.h forbids overlapping current-source snapshots
173// on one instance. Finder's snapshot lock covers every fetch and copy before
174// another snapshot can invalidate its buffers; its change feed permits only one
175// native waiter. Beyond that header contract, we rely on no thread affinity for
176// creation, use and destruction, and on a native wait beside snapshots. Real
177// runtime tests in tests/change_notifications.rs exercise cross-thread use and
178// concurrent waits/snapshots; tests/finder_deadlines.rs pins snapshot contention.
179// The surrounding Rust fields determine Finder's remaining traits.
180unsafe impl Send for FindInstance {}
181// SAFETY: the same snapshot and waiter serialization applies to shared uses.
182unsafe impl Sync for FindInstance {}
183
184/// Discovers NDI sources on the network.
185///
186/// `Finder` provides methods to discover and monitor NDI sources. It maintains
187/// a background thread that continuously updates the list of available sources.
188/// Concurrent lookups share native change reports: every waiting lookup is
189/// notified when the source list changes, then takes its own owned snapshot.
190///
191/// # Examples
192///
193/// ```no_run
194/// # use grafton_ndi::{Ndi, FinderOptions, Finder};
195/// # use std::time::Duration;
196/// # fn main() -> Result<(), grafton_ndi::Error> {
197/// let ndi = Ndi::new()?;
198/// let finder = Finder::new(&ndi, &FinderOptions::new())?;
199///
200/// // Wait for initial discovery
201/// let mut watch = finder.watch();
202/// if watch.wait_for_change(Duration::from_secs(5))? {
203///     let sources = watch.current_sources()?;
204///     for source in sources {
205///         println!("Found: {}", source);
206///     }
207/// }
208/// # Ok(())
209/// # }
210/// ```
211pub struct Finder {
212    instance: FindInstance,
213    // SDK snapshots and their strings expire on the next snapshot call.
214    sources_lock: parking_lot::Mutex<FindInstance>,
215    changes: ChangeFeed,
216    _groups: Option<CString>,    // Hold ownership of CStrings
217    _extra_ips: Option<CString>, // to ensure they outlive SDK usage
218    #[cfg(feature = "advanced")]
219    _config: crate::advanced::RetainedConfig,
220    sdk: crate::runtime::Bound<sys::Core>,
221}
222
223impl fmt::Debug for Finder {
224    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
225        f.debug_struct("Finder")
226            .field("groups", &self._groups)
227            .field("extra_ips", &self._extra_ips)
228            .finish_non_exhaustive()
229    }
230}
231
232// The mutex guards a native snapshot's lifetime, not mutable Rust state. A
233// panic releases it without poisoning, and a later snapshot replaces all SDK
234// buffers before reading them. No partially updated Rust invariant survives.
235impl std::panic::RefUnwindSafe for Finder {}
236
237pub(crate) mod snapshot_sealed {
238    pub trait Sealed {}
239}
240
241/// One SDK snapshot entry point and its bounded descriptor copier.
242///
243/// # Safety
244///
245/// For a live finder, `fetch` returns null or the initialized descriptor array
246/// whose length it writes. The descriptors and their non-null strings remain
247/// readable through their NUL or the SDK string bound until the next snapshot
248/// call on that finder. `copy` reads only those descriptor fields and returns
249/// owned values; it neither replaces nor retains the native snapshot.
250pub(crate) unsafe trait FinderSnapshot: snapshot_sealed::Sealed {
251    type Descriptor;
252    type Item;
253
254    /// # Safety
255    /// `instance` is live and no snapshot call can overlap the fetch and copy.
256    unsafe fn fetch(
257        &self,
258        instance: NDIlib_find_instance_t,
259        count: &mut u32,
260    ) -> *const Self::Descriptor;
261
262    /// # Safety
263    /// `source` comes from this entry point's still-live snapshot.
264    unsafe fn copy(
265        &self,
266        source: &Self::Descriptor,
267        budget: &mut SnapshotBudget,
268    ) -> Result<Option<Self::Item>>;
269}
270
271/// The standard source snapshot entry point.
272struct SourceSnapshot<'a>(&'a sys::Core);
273
274impl snapshot_sealed::Sealed for SourceSnapshot<'_> {}
275
276// SAFETY: this delegates fetch to Core and copies accepted descriptors into
277// owned sources before the guard ends the native snapshot's lifetime.
278unsafe impl FinderSnapshot for SourceSnapshot<'_> {
279    type Descriptor = NDIlib_source_t;
280    type Item = Source;
281
282    unsafe fn fetch(
283        &self,
284        instance: NDIlib_find_instance_t,
285        count: &mut u32,
286    ) -> *const Self::Descriptor {
287        // SAFETY: forwarded to the serialized live-instance obligation.
288        unsafe { self.0.NDIlib_find_get_current_sources(instance, count) }
289    }
290
291    unsafe fn copy(
292        &self,
293        source: &Self::Descriptor,
294        budget: &mut SnapshotBudget,
295    ) -> Result<Option<Source>> {
296        // SAFETY: the snapshot guard keeps both native strings readable.
297        unsafe { copy_source(source, budget, |_| true) }
298    }
299}
300
301/// An acquired snapshot lock and the exact native handle it guards. Fetching
302/// gets its instance from this guard, never from a separate Finder argument.
303struct SnapshotGuard<'finder> {
304    instance: parking_lot::MutexGuard<'finder, FindInstance>,
305}
306
307/// A snapshot wait's expiry is part of its type: an unbounded wait cannot
308/// expire, while a lookup deadline can. Both use the same cancellation kernel.
309trait SnapshotWait: Copy {
310    type Expired;
311
312    fn remaining(self) -> Duration;
313    fn expiration(self) -> Option<Self::Expired>;
314    fn lock(
315        self,
316        mutex: &parking_lot::Mutex<FindInstance>,
317    ) -> std::result::Result<parking_lot::MutexGuard<'_, FindInstance>, Self::Expired>;
318}
319
320#[derive(Clone, Copy)]
321struct UnboundedSnapshot;
322
323impl SnapshotWait for UnboundedSnapshot {
324    type Expired = std::convert::Infallible;
325
326    fn remaining(self) -> Duration {
327        POLL_INTERVAL
328    }
329
330    fn expiration(self) -> Option<Self::Expired> {
331        None
332    }
333
334    fn lock(
335        self,
336        mutex: &parking_lot::Mutex<FindInstance>,
337    ) -> std::result::Result<parking_lot::MutexGuard<'_, FindInstance>, Self::Expired> {
338        Ok(mutex.lock())
339    }
340}
341
342impl SnapshotWait for Deadline {
343    type Expired = ();
344
345    fn remaining(self) -> Duration {
346        Deadline::remaining(self).min(POLL_INTERVAL)
347    }
348
349    fn expiration(self) -> Option<Self::Expired> {
350        self.is_expired().then_some(())
351    }
352
353    fn lock(
354        self,
355        mutex: &parking_lot::Mutex<FindInstance>,
356    ) -> std::result::Result<parking_lot::MutexGuard<'_, FindInstance>, Self::Expired> {
357        mutex.try_lock_until(self.end()).ok_or(())
358    }
359}
360
361impl SnapshotGuard<'_> {
362    fn snapshot<S: FinderSnapshot>(&self, snapshot: &S) -> Result<Vec<S::Item>> {
363        let mut copied = Vec::new();
364        self.scan(snapshot, |source, budget, remaining| {
365            // SAFETY: scan keeps this entry point's descriptors readable.
366            let item = unsafe { snapshot.copy(source, budget) }?;
367            budget::push_snapshot_item(&mut copied, item, remaining)
368        })?;
369        Ok(copied)
370    }
371
372    fn first_named(
373        &self,
374        snapshot: &impl FinderSnapshot<Descriptor = NDIlib_source_t, Item = Source>,
375        name: &str,
376    ) -> Result<Option<Source>> {
377        let mut first = None;
378        self.scan(snapshot, |entry, budget, _| {
379            // SAFETY: scan keeps the source descriptor and its strings live.
380            if let Some(source) = unsafe {
381                copy_source(entry, budget, |source| {
382                    first.is_none() && source.name.as_str() == name
383                })
384            }? {
385                first = Some(source);
386            }
387            Ok(())
388        })?;
389        Ok(first)
390    }
391
392    fn discover(
393        &self,
394        snapshot: &impl FinderSnapshot<Descriptor = NDIlib_source_t, Item = Source>,
395        staged: &mut DiscoveryWindow,
396        query: Option<HostQuery<'_>>,
397    ) -> Result<()> {
398        let mut retained = Ok(());
399        self.scan(snapshot, |entry, budget, _| {
400            // SAFETY: scan keeps the source descriptor and its strings live.
401            if let Some(source) = unsafe {
402                copy_source(entry, budget, |source| {
403                    // Keep scanning after a retention error so snapshot
404                    // errors still take precedence.
405                    retained.is_ok() && source.selected_by(query, &staged.seen)
406                })
407            }? {
408                retained = staged.push(source);
409            }
410            Ok(())
411        })?;
412        retained
413    }
414
415    fn scan<S: FinderSnapshot>(
416        &self,
417        snapshot: &S,
418        visit: impl FnMut(&S::Descriptor, &mut SnapshotBudget, usize) -> Result<()>,
419    ) -> Result<()> {
420        let mut count = 0;
421        // SAFETY: this private guard keeps its own finder's handle serialized
422        // until the scan completes. The sealed entry point supplies the array
423        // and string lifetimes required by the bounded scan kernel.
424        unsafe {
425            let descriptors = snapshot.fetch(self.instance.0, &mut count);
426            budget::scan_snapshot::<_, S::Item>(descriptors, count, visit)
427        }
428    }
429}
430
431/// The shared two-step cursor protocol. Workers observe; only the owner commits.
432/// A Cell keeps each cursor Send but not Sync, matching its single consumer.
433pub(crate) struct SourceCursor {
434    observed: Cell<u64>,
435}
436
437/// Evidence that one worker completed an observation. Only the protocol below
438/// can construct it; dropping it leaves the owner's cursor unchanged.
439pub(crate) struct SourceObservation(u64);
440
441impl SourceCursor {
442    pub(crate) fn new(generation: u64) -> Self {
443        Self {
444            observed: Cell::new(generation),
445        }
446    }
447
448    pub(crate) fn observed(&self) -> u64 {
449        self.observed.get()
450    }
451
452    pub(crate) fn commit(&self, observation: Option<SourceObservation>) {
453        if let Some(SourceObservation(generation)) = observation {
454            self.observed.set(generation);
455        }
456    }
457
458    pub(crate) fn snapshot<T>(
459        finder: &Finder,
460        snapshot: impl FnOnce(&Finder) -> Result<T>,
461        completed: impl FnOnce(&T) -> bool,
462    ) -> Result<(T, Option<SourceObservation>)> {
463        Self::observe_snapshot(
464            || finder.changes.generation(),
465            || snapshot(finder),
466            completed,
467        )
468    }
469
470    // Read before copying, but acknowledge only after the owner receives the
471    // result. Reports during copying remain outstanding; failure or an
472    // incomplete internal snapshot creates no observation to commit.
473    fn observe_snapshot<T>(
474        generation: impl FnOnce() -> u64,
475        snapshot: impl FnOnce() -> Result<T>,
476        completed: impl FnOnce(&T) -> bool,
477    ) -> Result<(T, Option<SourceObservation>)> {
478        let observed = generation();
479        let value = snapshot()?;
480        let observation = completed(&value).then_some(SourceObservation(observed));
481        Ok((value, observation))
482    }
483
484    pub(crate) fn wait(
485        finder: &Finder,
486        observed: u64,
487        deadline: Deadline,
488        stop: impl Stop,
489    ) -> (bool, Option<SourceObservation>) {
490        Self::observe_wait(
491            || finder.changes.generation(),
492            || finder.wait_for_sources_since(observed, deadline, stop),
493        )
494    }
495
496    // A successful wait acknowledges the generation read after its report.
497    fn observe_wait(
498        generation: impl FnOnce() -> u64,
499        wait: impl FnOnce() -> bool,
500    ) -> (bool, Option<SourceObservation>) {
501        let changed = wait();
502        let observation = changed.then(|| SourceObservation(generation()));
503        (changed, observation)
504    }
505}
506
507/// One consumer's cursor over a finder's source-list changes.
508///
509/// Take snapshots and wait through the same watch, so reports published by
510/// concurrent lookups between those operations cannot be missed. A report
511/// during a snapshot remains visible to the next wait. Each consumer must
512/// create its own watch; a watch can move between threads but is not `Sync`.
513///
514/// ```no_run
515/// # use grafton_ndi::{Finder, FinderOptions, Ndi};
516/// # use std::time::Duration;
517/// # fn main() -> grafton_ndi::Result<()> {
518/// # let ndi = Ndi::new()?;
519/// # let finder = Finder::new(&ndi, &FinderOptions::new())?;
520/// let mut watch = finder.watch();
521/// println!("{:?}", watch.current_sources()?);
522/// while watch.wait_for_change(Duration::from_secs(5))? {
523///     println!("{:?}", watch.current_sources()?);
524/// }
525/// # Ok(())
526/// # }
527/// ```
528pub struct SourceWatch<'finder> {
529    finder: &'finder Finder,
530    cursor: SourceCursor,
531}
532
533impl fmt::Debug for SourceWatch<'_> {
534    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
535        f.debug_struct("SourceWatch")
536            .field("finder", &self.finder)
537            .finish_non_exhaustive()
538    }
539}
540
541impl SourceWatch<'_> {
542    /// Copy the currently known sources and record the generation before
543    /// copying, preserving any report that arrives during the snapshot.
544    /// A failed snapshot leaves the cursor unchanged.
545    ///
546    /// # Errors
547    ///
548    /// Returns the snapshot errors of [`Finder::current_sources`]:
549    /// [`Error::UnexpectedSdkResult`] for a malformed top-level descriptor array,
550    /// [`Error::AllocationFailed`] for failed result or text reservations,
551    /// or [`Error::ResourceLimit`] when a snapshot exceeds its copy budgets.
552    #[doc(alias = "NDIlib_find_get_current_sources")]
553    pub fn current_sources(&mut self) -> Result<Vec<Source>> {
554        self.snapshot(Finder::current_sources, |_| true)
555    }
556
557    /// Wait for a report newer than this consumer's last snapshot or wait.
558    ///
559    /// Returns `true` immediately if another lookup already published a report.
560    /// A zero timeout reads such reports even while another native waiter is
561    /// active; otherwise it makes one nonblocking native query. Returns `false`
562    /// when the timeout expires without a report.
563    ///
564    /// # Errors
565    ///
566    /// Returns [`Error::InvalidInput`] if `timeout` exceeds [`crate::MAX_TIMEOUT`].
567    #[doc(alias = "NDIlib_find_wait_for_sources")]
568    pub fn wait_for_change(&mut self, timeout: Duration) -> Result<bool> {
569        Ok(self.wait_until(Deadline::after(timeout)?, NeverStop))
570    }
571
572    fn snapshot_until<S: Stop, T>(
573        &mut self,
574        deadline: Deadline,
575        stop: S,
576        copy: impl FnOnce(SnapshotGuard<'_>) -> Result<T>,
577    ) -> StopResult<Option<T>, S> {
578        self.snapshot(
579            |finder| match finder.lock_snapshots_until(deadline, stop) {
580                Ok(Some(guard)) => copy(guard).map(|sources| Ok(Some(sources))),
581                Ok(None) => Ok(Ok(None)),
582                Err(stopped) => Ok(Err(stopped)),
583            },
584            |sources| matches!(sources, Ok(Some(_))),
585        )
586    }
587
588    fn snapshot<T>(
589        &mut self,
590        snapshot: impl FnOnce(&Finder) -> Result<T>,
591        completed: impl FnOnce(&T) -> bool,
592    ) -> Result<T> {
593        let (value, observation) = SourceCursor::snapshot(self.finder, snapshot, completed)?;
594        self.cursor.commit(observation);
595        Ok(value)
596    }
597
598    fn wait_until(&mut self, deadline: Deadline, stop: impl Stop) -> bool {
599        let (changed, observation) =
600            SourceCursor::wait(self.finder, self.cursor.observed(), deadline, stop);
601        self.cursor.commit(observation);
602        changed
603    }
604}
605
606pub(crate) struct BorrowedSource<'a> {
607    name: SourceTextView<'a>,
608    address: Option<SourceTextView<'a>>,
609}
610
611impl BorrowedSource<'_> {
612    fn selected_by(&self, query: Option<HostQuery<'_>>, seen: &HashSet<SeenSource>) -> bool {
613        let name = self.name.as_str();
614        let address = self.address.map(SourceTextView::as_str);
615        if query.is_some_and(|query| !source_matches_query(name, address, query)) {
616            return false;
617        }
618        let key = (name, address);
619        !seen.contains(&key as &dyn SourceIdentity)
620    }
621}
622
623mod descriptor_sealed {
624    pub trait Sealed {}
625}
626
627/// A descriptor's bounded-text policy. The decoder alone owns null handling,
628/// selection order and source construction.
629pub(crate) trait DescriptorText: descriptor_sealed::Sealed {
630    const ALLOCATION_KIND: crate::AllocationKind;
631    const SKIP_INVALID_UTF8: bool;
632
633    fn empty_source_name(&mut self) -> Result<()>;
634
635    /// # Safety
636    /// The non-null pointer remains readable through its first NUL or the SDK
637    /// string bound, for the returned lifetime.
638    unsafe fn view<'a>(&mut self, pointer: *const c_char) -> Result<Option<&'a CStr>>;
639}
640
641impl descriptor_sealed::Sealed for SnapshotBudget {}
642impl DescriptorText for SnapshotBudget {
643    const ALLOCATION_KIND: crate::AllocationKind = crate::AllocationKind::DiscoveryResults;
644    const SKIP_INVALID_UTF8: bool = true;
645
646    fn empty_source_name(&mut self) -> Result<()> {
647        self.charge_empty_source_name()
648    }
649
650    unsafe fn view<'a>(&mut self, pointer: *const c_char) -> Result<Option<&'a CStr>> {
651        // SAFETY: forwarded to the decoder's bounded string obligation.
652        unsafe { self.source_c_str(pointer) }
653    }
654}
655
656struct SingleSourceText(sys::table::Called<()>);
657impl descriptor_sealed::Sealed for SingleSourceText {}
658impl DescriptorText for SingleSourceText {
659    const ALLOCATION_KIND: crate::AllocationKind = crate::AllocationKind::SourceDescriptor;
660    const SKIP_INVALID_UTF8: bool = false;
661
662    fn empty_source_name(&mut self) -> Result<()> {
663        Ok(())
664    }
665
666    unsafe fn view<'a>(&mut self, pointer: *const c_char) -> Result<Option<&'a CStr>> {
667        // SAFETY: the descriptor caller keeps each non-null string readable.
668        unsafe { crate::sdk_copy::sdk_text(self.0.map(|()| pointer)) }.map(Some)
669    }
670}
671
672/// Decode a source through one view-then-build policy. Both null pointers name
673/// no source; a null name beside an address becomes the shared empty name.
674/// Rejected entries retain all text charges but allocate no source storage.
675///
676/// # Safety
677/// Each non-null pointer remains readable through its first NUL or
678/// `MAX_SDK_STRING_BYTES`, whichever comes first, until selection and copying
679/// finish. The policy must preserve that lifetime.
680pub(crate) unsafe fn decode_source<T: DescriptorText>(
681    name: *const c_char,
682    address: *const c_char,
683    text: &mut T,
684    select: impl FnOnce(&BorrowedSource<'_>) -> bool,
685) -> Result<Option<Source>> {
686    if name.is_null() && address.is_null() {
687        return Ok(None);
688    }
689    let name = if name.is_null() {
690        text.empty_source_name()?;
691        c""
692    } else {
693        // SAFETY: forwarded to the caller's bounded string obligation.
694        let Some(name) = (unsafe { text.view(name) })? else {
695            return Ok(None);
696        };
697        name
698    };
699    let address = if address.is_null() {
700        None
701    } else {
702        // SAFETY: forwarded to the caller's bounded string obligation.
703        let Some(address) = (unsafe { text.view(address) })? else {
704            return Ok(None);
705        };
706        Some(address)
707    };
708    // Both bounded reads have already been charged, even when one field is
709    // malformed and the descriptor won't be available for selection.
710    let validated = SourceTextView::new(name).and_then(|name| {
711        Ok(BorrowedSource {
712            name,
713            address: address.map(SourceTextView::new).transpose()?,
714        })
715    });
716    let source = match validated {
717        Ok(source) => source,
718        Err(_) if T::SKIP_INVALID_UTF8 => return Ok(None),
719        Err(error) => return Err(Error::InvalidUtf8(error)),
720    };
721    if !select(&source) {
722        return Ok(None);
723    }
724    Ok(Some(Source::from_text(
725        SourceText::from_sdk(source.name, T::ALLOCATION_KIND)?,
726        source
727            .address
728            .map(|address| SourceText::from_sdk(address, T::ALLOCATION_KIND).map(SourceAddress))
729            .transpose()?,
730    )))
731}
732
733/// The descriptor's address is one pointer, whether the SDK calls it an IP
734/// address or a URL. Decoding classifies the copied text by its scheme.
735fn source_pointers(source: &NDIlib_source_t) -> (*const c_char, *const c_char) {
736    // SAFETY: both union fields are pointers of the same type.
737    let address = unsafe { source.__bindgen_anon_1.p_url_address };
738    (source.p_ndi_name, address)
739}
740
741/// Copy one entry after checking the operation's selector. A skipped entry
742/// still consumes the same snapshot budget as a retained one.
743/// # Safety
744/// The snapshot must keep the descriptor's strings readable through their NUL
745/// terminator or through the applicable limit until this returns.
746unsafe fn copy_source(
747    source: &NDIlib_source_t,
748    budget: &mut SnapshotBudget,
749    select: impl FnOnce(&BorrowedSource<'_>) -> bool,
750) -> Result<Option<Source>> {
751    let (name, address) = source_pointers(source);
752    // SAFETY: forwarded to the caller's bounded string obligation.
753    unsafe { decode_source(name, address, budget, select) }
754}
755
756impl Finder {
757    /// Creates a new source finder with the specified settings.
758    ///
759    /// # Arguments
760    ///
761    /// * `ndi` - The NDI instance (cloned internally to keep the runtime alive)
762    /// * `options` - Configuration for source discovery
763    ///
764    /// # Errors
765    ///
766    /// Returns [`Error::InvalidInput`] when either list is empty or a group or
767    /// extra address is empty or contains a comma or NUL, [`Error::UnsupportedCapability`] when the options
768    /// carry an Advanced configuration that the runtime or this build cannot
769    /// take, and [`Error::NativeOperationFailed`] when the SDK creates no
770    /// finder.
771    #[doc(alias = "NDIlib_find_create_v2")]
772    #[doc(alias = "NDIlib_find_create_v3")]
773    pub fn new(ndi: &Ndi, options: &FinderOptions) -> Result<Self> {
774        #[cfg(feature = "advanced")]
775        {
776            <Self as crate::advanced::Configurable>::create_from_options(ndi, options)
777        }
778        #[cfg(not(feature = "advanced"))]
779        {
780            Self::create_plain(ndi, options)
781        }
782    }
783
784    pub(crate) fn create_plain(ndi: &Ndi, options: &FinderOptions) -> Result<Self> {
785        // SAFETY: the SDK's finder creation returns null or a fresh finder
786        // that nothing else owns, and the settings outlive the call.
787        unsafe {
788            Self::create(ndi, options, |core, raw| {
789                crate::runtime::NativeCreation::plain(core.named().NDIlib_find_create_v2(raw))
790            })
791        }
792    }
793
794    /// The one creation path: create a finder through `create`, which is handed the core table and the native
795    /// settings for `settings`, and keep `config` for as long as the finder
796    /// lives.
797    ///
798    /// # Safety
799    ///
800    /// `create` returns null or a live finder of `ndi`'s runtime, made from
801    /// the settings it was handed, that nothing else owns.
802    pub(crate) unsafe fn create(
803        ndi: &Ndi,
804        settings: &FinderOptions,
805        create: impl FnOnce(
806            &sys::Core,
807            &NDIlib_find_create_t,
808        ) -> crate::runtime::NativeCreation<NDIlib_find_instance_t>,
809    ) -> Result<Self> {
810        let groups = list_cstring(settings.groups.as_deref(), "groups")?;
811        let extra_ips = list_cstring(settings.extra_ips.as_deref(), "extra_ips")?;
812        let sdk = ndi.bind_core();
813        let created = create(
814            &sdk,
815            &NDIlib_find_create_t {
816                show_local_sources: settings.show_local_sources,
817                p_groups: groups.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
818                p_extra_ips: extra_ips.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
819            },
820        );
821        let instance = created.call.created()?.as_ptr();
822        let finder = Self {
823            instance: FindInstance(instance),
824            sources_lock: parking_lot::Mutex::new(FindInstance(instance)),
825            changes: ChangeFeed::default(),
826            _groups: groups,
827            _extra_ips: extra_ips,
828            #[cfg(feature = "advanced")]
829            _config: created.config,
830            sdk,
831        };
832        // Some standard-library mutexes allocate their native backing on the
833        // first lock. Initialize before exposure, while Finder already owns
834        // the native instance so Drop also cleans it up if initialization panics.
835        let _ = finder.changes.generation();
836        Ok(finder)
837    }
838
839    /// Copy one snapshot through the entry point's shared lifetime contract.
840    /// The guard carries the handle it protects, so fetching cannot pair a
841    /// different finder's instance with this lock.
842    #[cfg(any(test, all(feature = "advanced", ndi_has_advanced_source_metadata)))]
843    pub(crate) fn snapshot<S: FinderSnapshot>(&self, snapshot: &S) -> Result<Vec<S::Item>> {
844        let Ok(guard) = self.lock_snapshots(NeverStop);
845        guard.snapshot(snapshot)
846    }
847
848    fn lock_snapshots<S: Stop>(
849        &self,
850        stop: S,
851    ) -> std::result::Result<SnapshotGuard<'_>, S::Stopped> {
852        let Ok(guard) = self.lock_snapshots_with(UnboundedSnapshot, stop, |remaining| {
853            self.sources_lock.try_lock_for(remaining)
854        })?;
855        Ok(guard)
856    }
857
858    fn lock_snapshots_until<S: Stop>(
859        &self,
860        deadline: Deadline,
861        stop: S,
862    ) -> std::result::Result<Option<SnapshotGuard<'_>>, S::Stopped> {
863        self.lock_snapshots_with(deadline, stop, |remaining| {
864            self.sources_lock.try_lock_for(remaining)
865        })
866        .map(std::result::Result::ok)
867    }
868
869    // The acquisition is injectable so cancellation can be tested exactly
870    // when a contended lock becomes available, without scheduler timing.
871    fn lock_snapshots_with<'finder, W: SnapshotWait, S: Stop>(
872        &'finder self,
873        wait: W,
874        stop: S,
875        mut acquire: impl FnMut(Duration) -> Option<parking_lot::MutexGuard<'finder, FindInstance>>,
876    ) -> std::result::Result<std::result::Result<SnapshotGuard<'finder>, W::Expired>, S::Stopped>
877    {
878        let instance = if S::CAN_STOP {
879            loop {
880                stop.check()?;
881                if let Some(instance) = acquire(wait.remaining()) {
882                    // Cancellation may arrive while the lock is waiting. Do
883                    // not start a new native snapshot after that wait succeeds.
884                    stop.check()?;
885                    break instance;
886                }
887                stop.check()?;
888                if let Some(expired) = wait.expiration() {
889                    return Ok(Err(expired));
890                }
891            }
892        } else {
893            match wait.lock(&self.sources_lock) {
894                Ok(instance) => instance,
895                Err(expired) => return Ok(Err(expired)),
896            }
897        };
898        Ok(Ok(SnapshotGuard { instance }))
899    }
900
901    #[cfg(any(feature = "tokio", feature = "smol"))]
902    pub(crate) fn generation(&self) -> u64 {
903        self.changes.generation()
904    }
905
906    pub(crate) fn current_sources_stoppable<S: Stop>(&self, stop: S) -> StopResult<Vec<Source>, S> {
907        match self.lock_snapshots(stop) {
908            Ok(guard) => guard.snapshot(&SourceSnapshot(&self.sdk)).map(Ok),
909            Err(stopped) => Ok(Err(stopped)),
910        }
911    }
912
913    /// The runtime this finder was created through.
914    #[cfg(feature = "advanced")]
915    pub(crate) fn runtime(&self) -> &Ndi {
916        self.sdk.ndi()
917    }
918
919    /// Monitor this finder's source list with a cursor for one consumer.
920    ///
921    /// Every consumer needs its own watch. Reports observed by a concurrent
922    /// lookup remain visible to this watch until it snapshots or waits again.
923    /// Creating a watch records the current generation without allocating.
924    #[must_use]
925    pub fn watch(&self) -> SourceWatch<'_> {
926        SourceWatch {
927            finder: self,
928            cursor: SourceCursor::new(self.changes.generation()),
929        }
930    }
931
932    /// Share one native report with every observer of the earlier generation.
933    pub(crate) fn wait_for_sources_since(
934        &self,
935        generation: u64,
936        deadline: Deadline,
937        stop: impl Stop,
938    ) -> bool {
939        // SAFETY: the finder instance is live for this borrow.
940        self.changes
941            .wait_since(generation, deadline, stop, |timeout_ms| unsafe {
942                self.sdk
943                    .NDIlib_find_wait_for_sources(self.instance.0, timeout_ms)
944            })
945    }
946
947    /// Returns the current list of discovered sources (snapshot).
948    ///
949    /// This method uses `NDIlib_find_get_current_sources` which provides a snapshot
950    /// of the current source list without any additional network discovery.
951    /// Concurrent snapshots on this finder are serialized until all source names
952    /// and addresses have been copied into owned Rust values.
953    ///
954    ///
955    /// Each snapshot permits at most 16,384 descriptors and 16 MiB total
956    /// native descriptors, result storage, scanned string bytes (including
957    /// rejected entries) and owned source text with its shared storage overhead.
958    /// Exceeding either budget returns [`Error::ResourceLimit`]. Each SDK string
959    /// is also limited to 4 MiB including its terminator. An isolated malformed
960    /// descriptor within the snapshot budgets is skipped, including one
961    /// whose name or address fails UTF-8 validation.
962    ///
963    /// # Allocation behavior
964    ///
965    /// Failed reservations for the result vector or copied text return
966    /// [`Error::AllocationFailed`]. The same applies to the result and
967    /// deduplication containers in [`Self::find_sources`]. Creating a shared
968    /// owner for copied source text uses the global allocator's allocation
969    /// failure handler, which can terminate the process. This also applies to
970    /// single-source getters that copy an SDK descriptor, such as
971    /// [`crate::Sender::source`].
972    ///
973    /// # Returns
974    ///
975    /// A vector of currently known sources. May be empty if no sources are found.
976    ///
977    /// # Errors
978    ///
979    /// Returns [`Error::UnexpectedSdkResult`] with
980    /// [`crate::SdkResultDefect::MalformedDiscoveryData`] for a malformed top-level
981    /// descriptor array, [`Error::AllocationFailed`] for failed result or text
982    /// reservations, or [`Error::ResourceLimit`] when a snapshot exceeds
983    /// its copy budgets. An isolated malformed descriptor is skipped.
984    ///
985    /// # Examples
986    ///
987    /// ```no_run
988    /// # use grafton_ndi::{Ndi, FinderOptions, Finder};
989    /// # fn main() -> Result<(), grafton_ndi::Error> {
990    /// # let ndi = Ndi::new()?;
991    /// # let finder = Finder::new(&ndi, &FinderOptions::default())?;
992    /// // Get current snapshot of sources
993    /// let sources = finder.current_sources()?;
994    ///
995    /// for source in sources {
996    ///     println!("Current source: {}", source);
997    /// }
998    /// # Ok(())
999    /// # }
1000    /// ```
1001    #[doc(alias = "NDIlib_find_get_current_sources")]
1002    pub fn current_sources(&self) -> Result<Vec<Source>> {
1003        let Ok(sources) = self.current_sources_stoppable(NeverStop)?;
1004        Ok(sources)
1005    }
1006
1007    /// Poll discovery until `accept` selects a value or `timeout` elapses.
1008    ///
1009    /// After each source-list snapshot, `accept` may select a value, observe
1010    /// cancellation, or continue waiting for a source-list change until the
1011    /// deadline. A single
1012    /// [`SourceWatch::wait_for_change`] returns on the *first*
1013    /// change, yielding only a partial snapshot when discovery is staggered
1014    /// (unicast / IP-hint-only networks where responders trickle in across
1015    /// several notifications); polling to the deadline makes resolution robust
1016    /// against that while still returning the instant `accept` is satisfied.
1017    ///
1018    /// Distinguishes a completed final snapshot from a busy snapshot lock
1019    /// so callers can decide whether the result is eligible for caching.
1020    fn poll_until_deadline<T, S: Stop, R>(
1021        &self,
1022        deadline: Deadline,
1023        stop: S,
1024        mut copy: impl FnMut(SnapshotGuard<'_>) -> Result<R>,
1025        mut accept: impl FnMut(R) -> StopResult<Option<T>, S>,
1026    ) -> StopResult<DiscoveryPoll<T>, S> {
1027        let mut watch = self.watch();
1028        loop {
1029            if let Err(stopped) = stop.check() {
1030                return Ok(Err(stopped));
1031            }
1032            let sources = match watch.snapshot_until(deadline, stop, &mut copy)? {
1033                Ok(Some(sources)) => sources,
1034                Ok(None) => return Ok(Ok(DiscoveryPoll::SnapshotBusy)),
1035                Err(stopped) => return Ok(Err(stopped)),
1036            };
1037            match accept(sources)? {
1038                Ok(Some(selected)) => return Ok(Ok(DiscoveryPoll::Selected(selected))),
1039                Ok(None) => {}
1040                Err(stopped) => return Ok(Err(stopped)),
1041            }
1042            if deadline.is_expired() {
1043                return Ok(Ok(DiscoveryPoll::Complete));
1044            }
1045            // Block until the source list changes or the window ends; either
1046            // way the next iteration re-snapshots. The wait is rounded up, so
1047            // the last one lasts until the deadline rather than polling.
1048            watch.wait_until(deadline, stop);
1049        }
1050    }
1051
1052    /// Wait until a source satisfies `select`, using this finder's discovery scope.
1053    ///
1054    /// Attempts a current snapshot immediately, then waits for source-list changes
1055    /// within one total wait budget, including snapshot-lock contention.
1056    /// `Duration::ZERO` makes one non-waiting snapshot attempt; a busy snapshot lock
1057    /// returns `None`. Returns the first matching complete descriptor in a snapshot,
1058    /// or `None` when the budget expires without a match. Predicates run after
1059    /// releasing the snapshot lock, may inspect name and address together, and may
1060    /// call this finder's snapshot APIs. No source's
1061    /// continued availability is guaranteed.
1062    ///
1063    /// This blocks the calling thread and allocates bounded owned snapshots as
1064    /// [`Self::current_sources`] describes. It retains this finder's groups, IP
1065    /// hints, local-source policy, configuration and runtime; it creates no finder.
1066    /// Concurrent selection operations can use the same finder. Native snapshot
1067    /// execution, bounded descriptor copies, and caller predicates cannot be
1068    /// interrupted and may finish after the wait budget; `current_sources` itself
1069    /// keeps its ordinary blocking snapshot-lock behavior.
1070    ///
1071    /// # Errors
1072    ///
1073    /// Returns [`Error::InvalidInput`] for a timeout above [`crate::MAX_TIMEOUT`],
1074    /// including immediate matches, and snapshot errors such as
1075    /// [`Error::ResourceLimit`]. A panic in `select` propagates outside SDK locks.
1076    #[doc(alias = "NDIlib_find_get_current_sources")]
1077    #[doc(alias = "NDIlib_find_wait_for_sources")]
1078    pub fn find_source(
1079        &self,
1080        timeout: Duration,
1081        select: impl FnMut(&Source) -> bool,
1082    ) -> Result<Option<Source>> {
1083        let Ok(source) = self.find_source_until(Deadline::after(timeout)?, NeverStop, select)?;
1084        Ok(source)
1085    }
1086
1087    pub(crate) fn find_source_until<S: Stop>(
1088        &self,
1089        deadline: Deadline,
1090        stop: S,
1091        mut select: impl FnMut(&Source) -> bool,
1092    ) -> StopResult<Option<Source>, S> {
1093        self.poll_until_deadline(
1094            deadline,
1095            stop,
1096            |guard| guard.snapshot(&SourceSnapshot(&self.sdk)),
1097            |sources| Ok(select_owned_source(sources, stop, &mut select)),
1098        )
1099        .map(|outcome| outcome.map(DiscoveryPoll::into_selection))
1100    }
1101
1102    /// Wait for an exact, case-sensitive complete NDI source name.
1103    ///
1104    /// Names normally look like `"STUDIO (Camera 2)"`. Duplicate names at different
1105    /// addresses select the first match in the current snapshot; use
1106    /// [`Self::find_source`] with an address predicate to disambiguate them.
1107    /// Timeout, concurrency and error behavior match that method. Only the
1108    /// first matching descriptor is copied from each bounded snapshot.
1109    ///
1110    /// # Errors
1111    ///
1112    /// An empty name returns [`Error::InvalidInput`]. A name containing a NUL
1113    /// returns [`Error::InvalidCString`], whose
1114    /// [`NulError::into_vec`](std::ffi::NulError::into_vec) returns the bytes
1115    /// through the first NUL. The name is checked before the timeout,
1116    /// including in async lookups. Other errors match [`Self::find_source`].
1117    #[doc(alias = "NDIlib_find_get_current_sources")]
1118    #[doc(alias = "NDIlib_find_wait_for_sources")]
1119    pub fn find_source_by_name(&self, name: &str, timeout: Duration) -> Result<Option<Source>> {
1120        let (name, deadline) = checked_name_lookup(name, timeout)?;
1121        let Ok(source) = self.find_source_by_name_until(name.as_str(), deadline, NeverStop)?;
1122        Ok(source)
1123    }
1124
1125    pub(crate) fn find_source_by_name_until<S: Stop>(
1126        &self,
1127        name: &str,
1128        deadline: Deadline,
1129        stop: S,
1130    ) -> StopResult<Option<Source>, S> {
1131        self.poll_until_deadline(
1132            deadline,
1133            stop,
1134            |guard| guard.first_named(&SourceSnapshot(&self.sdk), name),
1135            |source| Ok(Ok(source)),
1136        )
1137        .map(|outcome| outcome.map(DiscoveryPoll::into_selection))
1138    }
1139
1140    /// Discovers sources for up to `timeout`, returning the complete set.
1141    ///
1142    /// This honors the full `timeout` window and returns every source observed
1143    /// within it. Unlike a single [`SourceWatch::wait_for_change`]
1144    /// followed by a snapshot — which returns on the *first* source-list change
1145    /// and so can miss responders that announce late on staggered or unicast
1146    /// (IP-hint-only) networks — enumeration here retains each source observed
1147    /// during the window.
1148    ///
1149    /// For an immediate, non-blocking snapshot of already-known sources use
1150    /// [`current_sources`](Self::current_sources); to resolve a single specific
1151    /// feed use [`Self::find_source`] or [`Self::find_source_by_name`].
1152    ///
1153    /// # Arguments
1154    ///
1155    /// * `timeout` - Discovery window, including waits for the snapshot lock.
1156    ///   [`Duration::ZERO`] makes one non-waiting snapshot attempt, returning no
1157    ///   sources if the lock is busy. Must not exceed [`crate::MAX_TIMEOUT`]
1158    ///   (~49.7 days). Native snapshot execution and descriptor copies can finish
1159    ///   after the wait budget; lock contention returns the results observed so far.
1160    ///
1161    /// # Returns
1162    ///
1163    /// Every source observed within the window, in first-observed order.
1164    /// Identity includes the name and the complete address text;
1165    /// a changed descriptor is returned as a distinct source. Network discovery
1166    /// cannot guarantee observation of every source. May be empty if none appear.
1167    ///
1168    /// # Errors
1169    ///
1170    /// Returns [`Error::InvalidInput`] if `timeout` exceeds [`crate::MAX_TIMEOUT`].
1171    /// Returns [`Error::ResourceLimit`] if a snapshot exceeds the limits of
1172    /// [`Self::current_sources`], or distinct results retained across the
1173    /// whole window exceed 16,384 entries or 16 MiB. The retained byte budget
1174    /// counts shared source strings once, plus the storage of both the result
1175    /// vector and the deduplication set, including container capacity.
1176    /// Returns [`Error::UnexpectedSdkResult`] for a malformed top-level snapshot
1177    /// array, or [`Error::AllocationFailed`] for failed result, deduplication or
1178    /// text reservations. See [`Self::current_sources`] for allocation behavior
1179    /// of shared source owners. An isolated malformed descriptor is skipped.
1180    ///
1181    /// # Examples
1182    ///
1183    /// ```no_run
1184    /// # use grafton_ndi::{Ndi, FinderOptions, Finder};
1185    /// # use std::time::Duration;
1186    /// # fn main() -> Result<(), grafton_ndi::Error> {
1187    /// # let ndi = Ndi::new()?;
1188    /// # let finder = Finder::new(&ndi, &FinderOptions::default())?;
1189    /// // Discover for up to 5 seconds, then list everything found
1190    /// let sources = finder.find_sources(Duration::from_secs(5))?;
1191    ///
1192    /// for source in sources {
1193    ///     println!("Found: {}", source);
1194    /// }
1195    /// # Ok(())
1196    /// # }
1197    /// ```
1198    #[doc(alias = "NDIlib_find_get_current_sources")]
1199    #[doc(alias = "NDIlib_find_wait_for_sources")]
1200    pub fn find_sources(&self, timeout: Duration) -> Result<Vec<Source>> {
1201        let Ok(sources) = self.find_sources_until(Deadline::after(timeout)?, NeverStop)?;
1202        Ok(sources)
1203    }
1204
1205    pub(crate) fn find_sources_until<S: Stop>(
1206        &self,
1207        deadline: Deadline,
1208        stop: S,
1209    ) -> StopResult<Vec<Source>, S> {
1210        self.find_selected_sources_until(deadline, stop, None)
1211            .map(|outcome| outcome.map(DiscoveryOutcome::into_sources))
1212    }
1213
1214    fn find_selected_sources_until<S: Stop>(
1215        &self,
1216        deadline: Deadline,
1217        stop: S,
1218        query: Option<HostQuery<'_>>,
1219    ) -> StopResult<DiscoveryOutcome, S> {
1220        let mut window = DiscoveryWindow::default();
1221        let outcome = self.poll_until_deadline(
1222            deadline,
1223            stop,
1224            |guard| {
1225                // The committed window becomes private staging for this
1226                // attempt. An invalid snapshot drops the staged results.
1227                let mut staged = std::mem::take(&mut window);
1228                let result = guard.discover(&SourceSnapshot(&self.sdk), &mut staged, query);
1229                drop(guard);
1230                result?;
1231                window = staged;
1232                Ok(())
1233            },
1234            |()| Ok(Ok(None::<Infallible>)),
1235        )?;
1236        Ok(outcome.map(|end| match end {
1237            DiscoveryPoll::Complete => DiscoveryOutcome::Complete(window.sources),
1238            DiscoveryPoll::SnapshotBusy => DiscoveryOutcome::SnapshotBusy(window.sources),
1239            DiscoveryPoll::Selected(never) => match never {},
1240        }))
1241    }
1242}
1243
1244enum DiscoveryPoll<T> {
1245    Selected(T),
1246    Complete,
1247    SnapshotBusy,
1248}
1249
1250impl<T> DiscoveryPoll<T> {
1251    fn into_selection(self) -> Option<T> {
1252        match self {
1253            Self::Selected(selected) => Some(selected),
1254            Self::Complete | Self::SnapshotBusy => None,
1255        }
1256    }
1257}
1258
1259enum DiscoveryOutcome {
1260    Complete(Vec<Source>),
1261    SnapshotBusy(Vec<Source>),
1262}
1263
1264impl DiscoveryOutcome {
1265    fn into_sources(self) -> Vec<Source> {
1266        match self {
1267            Self::Complete(sources) | Self::SnapshotBusy(sources) => sources,
1268        }
1269    }
1270}
1271
1272fn select_owned_source<S: Stop>(
1273    sources: Vec<Source>,
1274    stop: S,
1275    select: &mut impl FnMut(&Source) -> bool,
1276) -> std::result::Result<Option<Source>, S::Stopped> {
1277    for source in sources {
1278        // A callback may finish even if it cancels, but the next callback
1279        // must observe that stop before invoking user code.
1280        stop.check()?;
1281        if select(&source) {
1282            return Ok(Some(source));
1283        }
1284    }
1285    Ok(None)
1286}
1287
1288impl Drop for Finder {
1289    fn drop(&mut self) {
1290        // SAFETY: the instance belongs to this runtime and is destroyed once.
1291        unsafe { self.sdk.NDIlib_find_destroy(self.instance.0) };
1292    }
1293}
1294
1295const_assert!({
1296    const fn assert_send_sync<T: Send + Sync>() {}
1297    assert_send_sync::<Finder>();
1298});
1299
1300/// An exact, nonempty NDI source name with no interior NUL. Ownership can
1301/// change without checking the same text again.
1302#[derive(Debug, Clone)]
1303pub(crate) struct SourceName<'a>(&'a str);
1304
1305impl<'a> SourceName<'a> {
1306    pub(crate) fn checked(name: &'a str) -> Result<Self> {
1307        if name.is_empty() {
1308            return Err(Error::InvalidInput(crate::InputDefect::Empty {
1309                what: "source name",
1310            }));
1311        }
1312        if let Some(error) = crate::error::nul_error_with_prefix(name) {
1313            return Err(error.into());
1314        }
1315        Ok(Self(name))
1316    }
1317
1318    pub(crate) fn as_str(&self) -> &str {
1319        self.0
1320    }
1321
1322    #[cfg(any(feature = "tokio", feature = "smol"))]
1323    pub(crate) fn into_owned(self) -> OwnedSourceName {
1324        OwnedSourceName(self.0.to_owned())
1325    }
1326
1327    pub(crate) fn into_c_string(self) -> CString {
1328        // Reserve the terminator as well so converting a borrowed name needs
1329        // one allocation, just as CString::new does.
1330        let mut bytes = Vec::with_capacity(self.0.len() + 1);
1331        bytes.extend_from_slice(self.0.as_bytes());
1332        // SAFETY: checked excludes every NUL, and ownership changes preserve
1333        // those exact bytes. CString appends the only, terminating NUL.
1334        unsafe { CString::from_vec_unchecked(bytes) }
1335    }
1336}
1337
1338/// The checked name crossing async dispatch has no borrowed representation or
1339/// lifetime parameter. Rust 1.88 can prove its worker future is Send directly.
1340#[cfg(any(feature = "tokio", feature = "smol"))]
1341#[derive(Debug, Clone)]
1342pub(crate) struct OwnedSourceName(String);
1343
1344#[cfg(any(feature = "tokio", feature = "smol"))]
1345impl OwnedSourceName {
1346    pub(crate) fn as_str(&self) -> &str {
1347        &self.0
1348    }
1349}
1350
1351/// Check lookup arguments in their public argument order, before any snapshot,
1352/// cache access or async dispatch.
1353pub(crate) fn checked_name_lookup(
1354    name: &str,
1355    timeout: Duration,
1356) -> Result<(SourceName<'_>, Deadline)> {
1357    let name = SourceName::checked(name)?;
1358    Ok((name, Deadline::after(timeout)?))
1359}
1360
1361pub(crate) fn checked_host_lookup(
1362    host: &str,
1363    timeout: Duration,
1364) -> Result<(HostQuery<'_>, Deadline)> {
1365    let host = HostQuery::checked(host)?;
1366    Ok((host, Deadline::after(timeout)?))
1367}
1368
1369/// An ordered discovery window and its borrowed-lookup index. Their source
1370/// values share the same text storage.
1371#[derive(Default)]
1372struct DiscoveryWindow {
1373    sources: Vec<Source>,
1374    seen: HashSet<SeenSource>,
1375    retained_bytes: usize,
1376}
1377
1378impl DiscoveryWindow {
1379    /// Retain a source after the snapshot selector has checked its identity.
1380    fn push(&mut self, source: Source) -> Result<()> {
1381        if self.sources.len() == budget::MAX_SOURCES {
1382            return Err(budget::limit(
1383                ResourceKind::FinderDiscoverySources,
1384                budget::MAX_SOURCES,
1385            ));
1386        }
1387        let text_bytes = source.name.storage_bytes()
1388            + source
1389                .address
1390                .as_ref()
1391                .map_or(0, |address| address.0.storage_bytes());
1392        let bytes = self
1393            .retained_bytes
1394            .checked_add(text_bytes)
1395            .ok_or_else(|| budget::limit(ResourceKind::FinderDiscoveryBytes, budget::MAX_BYTES))?;
1396        // Check before growing either container. Round
1397        // up for vector growth, hash buckets and control bytes; the actual
1398        // capacities are checked as well before retaining the source.
1399        let next_capacity = (self.sources.len() + 1).max(4).next_power_of_two();
1400        let growth_bound = next_capacity * 4 * (std::mem::size_of::<Source>() + 1);
1401        if bytes + growth_bound > budget::MAX_BYTES {
1402            return Err(budget::limit(
1403                ResourceKind::FinderDiscoveryBytes,
1404                budget::MAX_BYTES,
1405            ));
1406        }
1407        self.sources
1408            .try_reserve(1)
1409            .map_err(|_| budget::allocation_failed())?;
1410        self.seen
1411            .try_reserve(1)
1412            .map_err(|_| budget::allocation_failed())?;
1413        // HashSet capacity excludes unused buckets. Charging twice its
1414        // capacity covers bucket rounding and control bytes conservatively.
1415        let containers = self.sources.capacity() * std::mem::size_of::<Source>()
1416            + self.seen.capacity() * 2 * (std::mem::size_of::<Source>() + 1);
1417        if bytes + containers > budget::MAX_BYTES {
1418            return Err(budget::limit(
1419                ResourceKind::FinderDiscoveryBytes,
1420                budget::MAX_BYTES,
1421            ));
1422        }
1423        self.seen.insert(SeenSource(source.clone()));
1424        self.sources.push(source);
1425        self.retained_bytes = bytes;
1426        Ok(())
1427    }
1428}
1429
1430struct Authority<'a> {
1431    host: &'a str,
1432    port: Option<u16>,
1433}
1434
1435/// Strip an initial scheme of the form `ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`
1436/// followed by `://`.
1437fn strip_url_scheme(address: &str) -> Option<&str> {
1438    let mut bytes = address.bytes();
1439    if !bytes.next()?.is_ascii_alphabetic() {
1440        return None;
1441    }
1442    let end = 1 + bytes
1443        .position(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')))?;
1444    address.get(end..)?.strip_prefix("://")
1445}
1446
1447// An outer None rejects the authority, while Some(None) accepts an empty port.
1448fn parse_port(text: &str, allow_empty: bool) -> Option<Option<u16>> {
1449    match text.as_bytes().first() {
1450        None => allow_empty.then_some(None),
1451        // The integer parser checks the remaining digits and the range. The
1452        // first byte must be a digit to rule out its optional leading '+'.
1453        Some(b'0'..=b'9') => text.parse().ok().map(Some),
1454        _ => None,
1455    }
1456}
1457
1458fn parse_authority(address: &str) -> Option<Authority<'_>> {
1459    let url = strip_url_scheme(address);
1460    let allow_empty_port = url.is_some();
1461    let authority = url.unwrap_or(address).split(['/', '?', '#']).next()?;
1462    let authority = authority.rsplit('@').next()?;
1463    if authority.is_empty() {
1464        return None;
1465    }
1466    if let Some(rest) = authority.strip_prefix('[') {
1467        let (host, suffix) = rest.split_once(']')?;
1468        if host.parse::<std::net::Ipv6Addr>().is_err() {
1469            return None;
1470        }
1471        let port = if suffix.is_empty() {
1472            None
1473        } else {
1474            parse_port(suffix.strip_prefix(':')?, allow_empty_port)?
1475        };
1476        return Some(Authority { host, port });
1477    }
1478    if authority.matches(':').count() > 1 {
1479        authority.parse::<std::net::Ipv6Addr>().ok()?;
1480        return Some(Authority {
1481            host: authority,
1482            port: None,
1483        });
1484    }
1485    let (host, port) = match authority.split_once(':') {
1486        Some((host, port)) => (host, parse_port(port, allow_empty_port)?),
1487        None => (authority, None),
1488    };
1489    if host.is_empty() {
1490        return None;
1491    }
1492    Some(Authority { host, port })
1493}
1494
1495#[derive(Clone, Copy)]
1496pub(crate) enum HostQuery<'a> {
1497    Ip(IpAddr),
1498    Host(&'a str),
1499    Machine(&'a str),
1500}
1501
1502impl<'a> HostQuery<'a> {
1503    pub(crate) fn checked(host: &'a str) -> Result<Self> {
1504        Self::parse(host).ok_or(Error::InvalidInput(crate::InputDefect::InvalidHostQuery))
1505    }
1506
1507    #[cfg(any(feature = "tokio", feature = "smol"))]
1508    pub(crate) fn into_owned(self) -> OwnedHostQuery {
1509        match self {
1510            Self::Ip(ip) => OwnedHostQuery::Ip(ip),
1511            Self::Host(name) => OwnedHostQuery::Host(name.to_owned()),
1512            Self::Machine(name) => OwnedHostQuery::Machine(name.to_owned()),
1513        }
1514    }
1515
1516    fn parse(host: &'a str) -> Option<Self> {
1517        let ip_text = if host.starts_with('[') {
1518            host.strip_prefix('[')?.strip_suffix(']')?
1519        } else {
1520            host
1521        };
1522        if let Ok(ip) = ip_text.parse::<IpAddr>() {
1523            return Some(Self::Ip(ip));
1524        }
1525        if host != ip_text {
1526            return None;
1527        }
1528        let name = host.strip_suffix('.').unwrap_or(host);
1529        if name.is_empty()
1530            || name.len() > 253
1531            || name.trim() != name
1532            || name.chars().any(char::is_control)
1533            || name.contains([':', '/', '?', '#', '@', '[', ']', '(', ')'])
1534            || (name.contains('.') && name.bytes().all(|c| c.is_ascii_digit() || c == b'.'))
1535        {
1536            return None;
1537        }
1538        if name.split('.').all(|label| {
1539            !label.is_empty()
1540                && label.len() <= 63
1541                && label.as_bytes()[0].is_ascii_alphanumeric()
1542                && label.as_bytes()[label.len() - 1].is_ascii_alphanumeric()
1543                && label
1544                    .bytes()
1545                    .all(|c| c.is_ascii_alphanumeric() || c == b'-')
1546        }) {
1547            Some(Self::Host(name))
1548        } else {
1549            Some(Self::Machine(name))
1550        }
1551    }
1552
1553    fn matches(self, candidate: &str) -> bool {
1554        match self {
1555            Self::Ip(ip) => candidate.parse::<IpAddr>() == Ok(ip),
1556            Self::Host(name) | Self::Machine(name) => candidate
1557                .strip_suffix('.')
1558                .unwrap_or(candidate)
1559                .eq_ignore_ascii_case(name),
1560        }
1561    }
1562}
1563
1564fn address_matches_query(address: &str, query: HostQuery<'_>) -> bool {
1565    !matches!(query, HostQuery::Machine(_))
1566        && parse_authority(address).is_some_and(|authority| query.matches(authority.host))
1567}
1568
1569fn source_name_matches_query(name: &str, query: HostQuery<'_>) -> bool {
1570    name.split_once(" (")
1571        .filter(|(_, source)| source.ends_with(')'))
1572        .is_some_and(|(machine, _)| query.matches(machine))
1573}
1574
1575fn source_matches_query(name: &str, address: Option<&str>, query: HostQuery<'_>) -> bool {
1576    if address.is_some_and(|address| address_matches_query(address, query)) {
1577        return true;
1578    }
1579    match query {
1580        HostQuery::Ip(_) => false,
1581        HostQuery::Host(_) | HostQuery::Machine(_) => source_name_matches_query(name, query),
1582    }
1583}
1584
1585/// A parsed query that can cross a blocking-pool dispatch without reparsing
1586/// text or borrowing the async caller's string.
1587#[cfg(any(feature = "tokio", feature = "smol"))]
1588pub(crate) enum OwnedHostQuery {
1589    Ip(IpAddr),
1590    Host(String),
1591    Machine(String),
1592}
1593
1594#[cfg(any(feature = "tokio", feature = "smol"))]
1595impl OwnedHostQuery {
1596    pub(crate) fn as_query(&self) -> HostQuery<'_> {
1597        match self {
1598            Self::Ip(ip) => HostQuery::Ip(*ip),
1599            Self::Host(name) => HostQuery::Host(name),
1600            Self::Machine(name) => HostQuery::Machine(name),
1601        }
1602    }
1603}
1604
1605/// A retained cache identity keeps numeric addresses separate from names.
1606#[derive(Debug, PartialEq, Eq)]
1607enum HostKey {
1608    Ip(IpAddr),
1609    Name(Box<str>),
1610}
1611
1612/// Owned keys and borrowed queries share identity without allocating a key.
1613pub(crate) trait HostIdentity {
1614    fn identity(&self) -> HostQuery<'_>;
1615}
1616
1617impl HostIdentity for HostQuery<'_> {
1618    fn identity(&self) -> HostQuery<'_> {
1619        *self
1620    }
1621}
1622
1623impl HostIdentity for HostKey {
1624    fn identity(&self) -> HostQuery<'_> {
1625        match self {
1626            Self::Ip(ip) => HostQuery::Ip(*ip),
1627            Self::Name(name) => HostQuery::Host(name),
1628        }
1629    }
1630}
1631
1632impl Hash for dyn HostIdentity + '_ {
1633    fn hash<H: Hasher>(&self, state: &mut H) {
1634        match self.identity() {
1635            HostQuery::Ip(ip) => {
1636                0u8.hash(state);
1637                ip.hash(state);
1638            }
1639            HostQuery::Host(name) | HostQuery::Machine(name) => {
1640                1u8.hash(state);
1641                name.len().hash(state);
1642                for byte in name.bytes() {
1643                    byte.to_ascii_lowercase().hash(state);
1644                }
1645            }
1646        }
1647    }
1648}
1649
1650impl PartialEq for dyn HostIdentity + '_ {
1651    fn eq(&self, other: &Self) -> bool {
1652        match (self.identity(), other.identity()) {
1653            (HostQuery::Ip(a), HostQuery::Ip(b)) => a == b,
1654            (
1655                HostQuery::Host(a) | HostQuery::Machine(a),
1656                HostQuery::Host(b) | HostQuery::Machine(b),
1657            ) => a.eq_ignore_ascii_case(b),
1658            _ => false,
1659        }
1660    }
1661}
1662impl Eq for dyn HostIdentity + '_ {}
1663
1664impl Hash for HostKey {
1665    fn hash<H: Hasher>(&self, state: &mut H) {
1666        (self as &dyn HostIdentity).hash(state);
1667    }
1668}
1669
1670impl<'a> Borrow<dyn HostIdentity + 'a> for HostKey {
1671    fn borrow(&self) -> &(dyn HostIdentity + 'a) {
1672        self
1673    }
1674}
1675
1676impl TryFrom<HostQuery<'_>> for HostKey {
1677    type Error = Error;
1678
1679    fn try_from(query: HostQuery<'_>) -> Result<Self> {
1680        Ok(match query {
1681            HostQuery::Ip(ip) => Self::Ip(ip),
1682            HostQuery::Host(name) | HostQuery::Machine(name) => {
1683                let mut name = budget::copy_string(name)?;
1684                name.make_ascii_lowercase();
1685                Self::Name(name.into_boxed_str())
1686            }
1687        })
1688    }
1689}
1690
1691/// Opaque network address text of an NDI source.
1692///
1693/// Construction refuses NUL bytes and keeps the native representation ready
1694/// for connection requests. Equality and hashing compare the exact text the SDK
1695/// receives. URL classification does not establish the codec or NDI|HX use.
1696#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1697pub struct SourceAddress(SourceText);
1698
1699/// A borrowed SDK string checked for UTF-8 and free of interior NULs.
1700#[derive(Clone, Copy)]
1701pub(crate) struct SourceTextView<'a>(&'a str);
1702
1703impl<'a> SourceTextView<'a> {
1704    pub(crate) fn new(source: &'a CStr) -> std::result::Result<Self, std::str::Utf8Error> {
1705        source.to_str().map(Self)
1706    }
1707
1708    pub(crate) fn as_str(self) -> &'a str {
1709        self.0
1710    }
1711}
1712
1713/// Validated UTF-8 with exactly one trailing NUL, shared by descriptors and
1714/// their native borrowers. All SDK pointers lead into this immutable storage.
1715#[derive(Clone, PartialEq, Eq, Hash)]
1716pub(crate) struct SourceText(Arc<CString>);
1717
1718impl SourceText {
1719    // Shared CString storage adds its Arc header, the CString and one NUL.
1720    pub(crate) const STORAGE_OVERHEAD: usize =
1721        2 * std::mem::size_of::<usize>() + std::mem::size_of::<CString>() + 1;
1722
1723    /// Copy classified SDK text directly into its final shared native storage.
1724    pub(crate) fn from_sdk(
1725        source: SourceTextView<'_>,
1726        kind: crate::AllocationKind,
1727    ) -> Result<Self> {
1728        let source = source.as_str();
1729        let mut text = String::new();
1730        let bytes = source.len() + 1;
1731        text.try_reserve_exact(bytes)
1732            .map_err(|_| crate::error::allocation_failed(kind, Some(bytes)))?;
1733        text.push_str(source);
1734        // SAFETY: SourceTextView borrows text from a CStr.
1735        Ok(unsafe { Self::from_nul_free_string(text) })
1736    }
1737
1738    /// Keep generated text whose NUL-free invariant is already established.
1739    ///
1740    /// # Safety
1741    /// `text` must contain no NUL.
1742    unsafe fn from_nul_free_string(text: String) -> Self {
1743        let mut bytes = text.into_bytes();
1744        bytes.push(0);
1745        // SAFETY: the caller excludes interior NUL and we appended the sole NUL.
1746        Self(Arc::new(unsafe {
1747            CString::from_vec_with_nul_unchecked(bytes)
1748        }))
1749    }
1750
1751    pub(crate) fn new(text: String) -> Result<Self> {
1752        Ok(Self(Arc::new(CString::new(text)?)))
1753    }
1754
1755    pub(crate) fn as_str(&self) -> &str {
1756        // SAFETY: the CString was constructed from a String, and its immutable
1757        // shared backing cannot change after construction.
1758        unsafe { std::str::from_utf8_unchecked(self.0.as_bytes()) }
1759    }
1760
1761    fn as_c_str(&self) -> &CStr {
1762        self.0.as_c_str()
1763    }
1764
1765    fn storage_bytes(&self) -> usize {
1766        self.0.as_bytes().len() + Self::STORAGE_OVERHEAD
1767    }
1768}
1769
1770impl fmt::Debug for SourceText {
1771    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1772        fmt::Debug::fmt(self.as_str(), f)
1773    }
1774}
1775
1776impl SourceAddress {
1777    pub(crate) fn from_advertised_host(text: &str, port: NonZeroU16) -> Option<Self> {
1778        let host = HostQuery::parse(text)?;
1779        let endpoint = match host {
1780            HostQuery::Ip(IpAddr::V6(_)) => {
1781                let literal = text
1782                    .strip_prefix('[')
1783                    .and_then(|s| s.strip_suffix(']'))
1784                    .unwrap_or(text);
1785                format!("[{literal}]:{port}")
1786            }
1787            HostQuery::Ip(IpAddr::V4(ip)) => format!("{ip}:{port}"),
1788            // Preserve a final DNS dot, which marks an absolute host name.
1789            HostQuery::Host(_) => format!("{text}:{port}"),
1790            HostQuery::Machine(_) => return None,
1791        };
1792        let authority = parse_authority(&endpoint)?;
1793        if authority.port != Some(port.get()) || !host.matches(authority.host) {
1794            return None;
1795        }
1796        // SAFETY: an IP literal or DNS host name contains no NUL, and
1797        // formatting adds only brackets, a colon and decimal digits.
1798        Some(Self(unsafe { SourceText::from_nul_free_string(endpoint) }))
1799    }
1800
1801    /// Keep the opaque address text unchanged after checking its native form.
1802    ///
1803    /// # Errors
1804    ///
1805    /// Returns [`Error::InvalidCString`] when the address contains a NUL byte.
1806    pub fn new(text: impl Into<String>) -> Result<Self> {
1807        SourceText::new(text.into()).map(Self)
1808    }
1809
1810    /// The exact address text, whether it names a host, IP address or URL.
1811    pub fn as_str(&self) -> &str {
1812        self.0.as_str()
1813    }
1814
1815    pub(crate) fn as_c_str(&self) -> &CStr {
1816        self.0.as_c_str()
1817    }
1818
1819    /// Whether the address starts with a valid URL scheme followed by `://`.
1820    ///
1821    /// The scheme starts with an ASCII letter and can contain ASCII letters,
1822    /// digits, `+`, `-` and `.`. Use `as_str().contains("://")` to search for
1823    /// the separator anywhere in the address text.
1824    pub fn is_url(&self) -> bool {
1825        strip_url_scheme(self.as_str()).is_some()
1826    }
1827
1828    /// Check whether this address has the exact host or IP.
1829    ///
1830    /// Hostnames compare without ASCII case or a final DNS dot. The query
1831    /// grammar is defined by [`Source::matches_host`]. Machine-name queries
1832    /// and invalid queries return false because an address has no machine label.
1833    ///
1834    /// # Arguments
1835    ///
1836    /// * `host` - The hostname or IP address to search for
1837    ///
1838    /// # Examples
1839    ///
1840    /// ```
1841    /// use grafton_ndi::SourceAddress;
1842    ///
1843    /// let addr = SourceAddress::new("192.168.1.100:5960".to_string()).unwrap();
1844    /// assert!(addr.matches_host("192.168.1.100"));
1845    /// assert!(!addr.matches_host("192.168.1"));
1846    ///
1847    /// let url = SourceAddress::new("http://camera.local:8080".to_string()).unwrap();
1848    /// assert!(url.matches_host("camera.local"));
1849    /// ```
1850    pub fn matches_host(&self, host: &str) -> bool {
1851        HostQuery::parse(host).is_some_and(|query| self.matches_query(query))
1852    }
1853
1854    fn matches_query(&self, query: HostQuery<'_>) -> bool {
1855        address_matches_query(self.as_str(), query)
1856    }
1857
1858    /// Extract an explicit port from conventional host/port or URL syntax.
1859    ///
1860    /// Reads the authority before any path, query or fragment. Ports use
1861    /// ASCII decimal digits and must fit in a `u16`. An empty port field is
1862    /// recognized in a URL and returns `None`. Unrecognized syntax returns `None`.
1863    ///
1864    /// # Returns
1865    ///
1866    /// `Some(port)` if a valid port is found, `None` otherwise.
1867    ///
1868    /// # Examples
1869    ///
1870    /// ```
1871    /// use grafton_ndi::SourceAddress;
1872    ///
1873    /// let addr = SourceAddress::new("192.168.1.100:5960".to_string()).unwrap();
1874    /// assert_eq!(addr.port(), Some(5960));
1875    ///
1876    /// let no_port = SourceAddress::new("192.168.1.100".to_string()).unwrap();
1877    /// assert_eq!(no_port.port(), None);
1878    ///
1879    /// let url = SourceAddress::new("http://camera.local:8080".to_string()).unwrap();
1880    /// assert_eq!(url.port(), Some(8080));
1881    /// ```
1882    pub fn port(&self) -> Option<u16> {
1883        self.authority().and_then(|authority| authority.port)
1884    }
1885
1886    // SDK addresses are opaque. Only interpret conventional URL authorities and
1887    // host[:port] forms; never inspect their path, query, or fragment as a port.
1888    fn authority(&self) -> Option<Authority<'_>> {
1889        parse_authority(self.as_str())
1890    }
1891}
1892
1893/// An NDI source: its name and, when known, its network address.
1894///
1895/// Equality and hashing compare the complete name and address text; they do
1896/// not imply persistent device identity.
1897///
1898/// The name typically includes the machine name and source name (e.g.,
1899/// "MACHINE (Source)"). A source found by a [`Finder`] has the address it
1900/// advertises; a receiver given a source without one looks it up by name.
1901///
1902/// # Examples
1903///
1904/// ```
1905/// use grafton_ndi::{Source, SourceAddress};
1906///
1907/// let source = Source::new("LAPTOP (Camera 1)").unwrap()
1908///     .with_address(SourceAddress::new("192.168.1.100:5960".to_string()).unwrap());
1909/// assert_eq!(source.name(), "LAPTOP (Camera 1)");
1910/// assert_eq!(source.to_string(), "LAPTOP (Camera 1)@192.168.1.100:5960");
1911/// assert!(Source::new("LAPTOP (Camera 1)").unwrap().address().is_none());
1912/// ```
1913#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1914pub struct Source {
1915    name: SourceText,
1916    address: Option<SourceAddress>,
1917}
1918
1919/// Only discovery's private deduplication set needs borrowed textual keys.
1920/// Keep its custom Borrow and hashing separate from the public source value.
1921#[repr(transparent)]
1922#[derive(Clone, PartialEq, Eq)]
1923struct SeenSource(Source);
1924
1925const_assert!(std::mem::size_of::<SeenSource>() == std::mem::size_of::<Source>());
1926
1927/// Owned and borrowed source keys use the same complete textual identity.
1928/// Trait-object borrowing permits a HashSet lookup without allocating a Source.
1929trait SourceIdentity {
1930    fn key(&self) -> (&str, Option<&str>);
1931}
1932
1933impl SourceIdentity for Source {
1934    fn key(&self) -> (&str, Option<&str>) {
1935        (
1936            self.name(),
1937            self.address.as_ref().map(SourceAddress::as_str),
1938        )
1939    }
1940}
1941
1942impl SourceIdentity for (&str, Option<&str>) {
1943    fn key(&self) -> (&str, Option<&str>) {
1944        *self
1945    }
1946}
1947
1948impl SourceIdentity for SeenSource {
1949    fn key(&self) -> (&str, Option<&str>) {
1950        self.0.key()
1951    }
1952}
1953
1954impl Hash for SeenSource {
1955    fn hash<H: Hasher>(&self, state: &mut H) {
1956        self.key().hash(state);
1957    }
1958}
1959
1960impl Hash for dyn SourceIdentity + '_ {
1961    fn hash<H: Hasher>(&self, state: &mut H) {
1962        self.key().hash(state);
1963    }
1964}
1965
1966impl PartialEq for dyn SourceIdentity + '_ {
1967    fn eq(&self, other: &Self) -> bool {
1968        self.key() == other.key()
1969    }
1970}
1971
1972impl Eq for dyn SourceIdentity + '_ {}
1973
1974impl<'a> Borrow<dyn SourceIdentity + 'a> for SeenSource {
1975    fn borrow(&self) -> &(dyn SourceIdentity + 'a) {
1976        self
1977    }
1978}
1979
1980impl Source {
1981    pub(crate) fn from_text(name: SourceText, address: Option<SourceAddress>) -> Self {
1982        Self { name, address }
1983    }
1984
1985    /// The source named `name`, without an address.
1986    ///
1987    /// # Errors
1988    ///
1989    /// Returns [`Error::InvalidCString`] when the name contains a NUL byte.
1990    pub fn new(name: impl Into<String>) -> Result<Self> {
1991        Ok(Self {
1992            name: SourceText::new(name.into())?,
1993            address: None,
1994        })
1995    }
1996
1997    /// This source, at `address`.
1998    #[must_use]
1999    pub fn with_address(self, address: SourceAddress) -> Self {
2000        Self {
2001            address: Some(address),
2002            ..self
2003        }
2004    }
2005
2006    /// The NDI source name (e.g., "MACHINE (Source Name)"). A source the SDK
2007    /// described by its address alone has an empty name.
2008    pub fn name(&self) -> &str {
2009        self.name.as_str()
2010    }
2011
2012    pub(crate) fn name_c_str(&self) -> &CStr {
2013        self.name.as_c_str()
2014    }
2015
2016    /// The network address for connecting to this source, when known.
2017    pub fn address(&self) -> Option<&SourceAddress> {
2018        self.address.as_ref()
2019    }
2020
2021    /// Check if this source matches a hostname, IP address or NDI machine name.
2022    ///
2023    /// An IP query checks the complete address host numerically; IP literals may
2024    /// have enclosing square brackets. A DNS hostname checks both the address
2025    /// host and the machine component of an SDK
2026    /// `MACHINE (Source Name)` label. Other machine-name queries check only that
2027    /// machine component, never the label's source name or an address.
2028    ///
2029    /// Names are nonempty and at most 253 bytes after an optional final dot is
2030    /// removed. They have no control characters, leading or trailing whitespace,
2031    /// endpoint/URI delimiters (`: / ? # @ [ ]`), or label delimiters (`( )`).
2032    /// Dotted-numeric text must be a complete IP address. DNS hostnames use
2033    /// ASCII letters, digits and interior hyphens in labels of at most 63 bytes;
2034    /// other accepted names, including spaces and underscores, are machine names.
2035    /// Both name cases ignore a final dot and fold only ASCII letters: other
2036    /// Unicode characters compare exactly. Invalid queries return false.
2037    ///
2038    /// # Arguments
2039    ///
2040    /// * `host` - The hostname, IP address or machine name to match against
2041    ///
2042    /// # Examples
2043    ///
2044    /// ```
2045    /// use grafton_ndi::{Source, SourceAddress};
2046    ///
2047    /// let source = Source::new("CAMERA1 (Chan1, 192.168.0.107)").unwrap()
2048    ///     .with_address(SourceAddress::new("192.168.0.107:5960".to_string()).unwrap());
2049    ///
2050    /// assert!(source.matches_host("192.168.0.107"));
2051    /// assert!(source.matches_host("CAMERA1"));
2052    /// assert!(!source.matches_host("192.168.1.1"));
2053    /// ```
2054    pub fn matches_host(&self, host: &str) -> bool {
2055        HostQuery::parse(host).is_some_and(|query| self.matches_query(query))
2056    }
2057
2058    fn matches_query(&self, query: HostQuery<'_>) -> bool {
2059        source_matches_query(
2060            self.name(),
2061            self.address.as_ref().map(SourceAddress::as_str),
2062            query,
2063        )
2064    }
2065
2066    /// Extract the host from conventional host/port or URL syntax.
2067    ///
2068    /// Reads the authority before any path, query or fragment and removes
2069    /// brackets around IPv6 literals. A URL with an empty port field still
2070    /// has a host. SDK addresses are opaque and unrecognized syntax returns
2071    /// `None`.
2072    ///
2073    /// For IP-based sources, this returns the IP portion without the port.
2074    /// For URL-based sources, this extracts the hostname portion, which may be
2075    /// a name such as `camera.local` rather than an IP address.
2076    ///
2077    /// # Returns
2078    ///
2079    /// `Some(host)` if an IP or hostname is found, `None` otherwise.
2080    ///
2081    /// # Examples
2082    ///
2083    /// ```
2084    /// use grafton_ndi::{Source, SourceAddress};
2085    ///
2086    /// let source = Source::new("CAMERA1").unwrap()
2087    ///     .with_address(SourceAddress::new("192.168.1.100:5960".to_string()).unwrap());
2088    ///
2089    /// assert_eq!(source.host(), Some("192.168.1.100"));
2090    /// ```
2091    pub fn host(&self) -> Option<&str> {
2092        self.address
2093            .as_ref()?
2094            .authority()
2095            .map(|authority| authority.host)
2096    }
2097
2098    /// Copy a source descriptor that the SDK call `source` returned
2099    /// into owned strings after null and UTF-8 checks.
2100    ///
2101    /// Null checks cannot validate dangling or otherwise invalid pointers. The
2102    /// SDK must provide a live descriptor and readable NUL-terminated strings.
2103    ///
2104    /// # Errors
2105    ///
2106    /// Returns [`Error::NativeOperationFailed`] naming the call's function when the
2107    /// descriptor is null, or names neither a source nor an address, and
2108    /// [`Error::UnexpectedSdkResult`] when its name or address is longer than
2109    /// the 4 MiB available for one SDK string, including its terminator.
2110    /// [`Error::InvalidUtf8`] reports an invalid name or address.
2111    /// [`Error::AllocationFailed`] reports a failed text buffer reservation.
2112    /// See [`Finder::current_sources`] for allocation behavior of shared source owners.
2113    ///
2114    /// # Safety
2115    ///
2116    /// The non-null pointer in `source` must point to a live `NDIlib_source_t`. Its
2117    /// non-null string pointers must remain readable through their NUL
2118    /// terminators, or for 4 MiB, until copying finishes.
2119    pub(crate) unsafe fn try_from_raw(
2120        source: sys::table::Called<*const NDIlib_source_t>,
2121    ) -> Result<Self> {
2122        let failed = || source.failed();
2123        let source_ptr = *source.value();
2124        if source_ptr.is_null() {
2125            return Err(failed());
2126        }
2127
2128        // SAFETY: the caller guarantees a non-null descriptor is live.
2129        let ndi_source = unsafe { &*source_ptr };
2130        let (name, address) = source_pointers(ndi_source);
2131        // SAFETY: the caller keeps both strings readable through their
2132        // terminator or the SDK string bound. The decoder passes only non-null
2133        // pointers to this strict policy, which reports malformed SDK text.
2134        unsafe {
2135            decode_source(
2136                name,
2137                address,
2138                &mut SingleSourceText(source.map(|_| ())),
2139                |_| true,
2140            )
2141        }?
2142        .ok_or_else(failed)
2143    }
2144}
2145
2146impl Display for Source {
2147    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2148        match &self.address {
2149            Some(address) => write!(
2150                f,
2151                "{name}@{address}",
2152                name = self.name(),
2153                address = address.as_str()
2154            ),
2155            None => write!(f, "{name}", name = self.name()),
2156        }
2157    }
2158}
2159
2160/// A thread-safe cache of complete host result sets in one finder's scope.
2161///
2162/// A host can publish several feeds. [`Self::find_sources_by_host`] retains every
2163/// distinct matching descriptor observed over its discovery window, rather than
2164/// choosing a feed by arrival order. Use [`Finder::find_source`] for a selection
2165/// that should return as soon as a particular feed appears.
2166///
2167/// The cache owns its configured finder, keeping it and the NDI runtime alive.
2168/// Configure groups, IP hints and Advanced settings before constructing the
2169/// cache: a lookup never creates another finder or changes its configuration.
2170/// Store it directly in server state, or share it through [`std::sync::Arc`].
2171/// [`finder`](Self::finder) lends the configured finder for uncached selection.
2172///
2173/// Entries remain until [`Self::invalidate`] or [`Self::clear`]; they can contain
2174/// offline endpoints and omit feeds announced after the original window. Empty
2175/// results are not cached. A miss with a busy final snapshot returns the feeds
2176/// observed so far without filling the cache, so the next miss tries discovery
2177/// again. A failed cache reservation returns the discovered result uncached.
2178/// See [`Self::find_sources_by_host`] for allocation behavior during publication.
2179/// The accepted grammar is [`Source::matches_host`]'s.
2180/// Equivalent hostname or machine-name ASCII case/final-dot and numeric IP
2181/// spellings share an entry. Other spellings, including DNS aliases, remain
2182/// distinct identities.
2183///
2184/// The cache is `Send + Sync`. Discovery, descriptor copies and retired entry
2185/// destruction run outside its mutex so unrelated lookups and invalidation
2186/// remain available; SDK snapshots retain their normal
2187/// per-finder serialization. Returned vectors own copies of the descriptors.
2188/// Concurrent discovery waits share change reports through that finder, so
2189/// one lookup cannot consume another lookup's notification.
2190/// Dropping the cache destroys its native finder and releases its runtime
2191/// handle synchronously on the dropping thread.
2192///
2193/// ```no_run
2194/// # use grafton_ndi::{Ndi, Finder, FinderOptions, SourceCache};
2195/// # use std::time::Duration;
2196/// # fn main() -> grafton_ndi::Result<()> {
2197/// let ndi = Ndi::new()?;
2198/// let finder = Finder::new(&ndi, &FinderOptions::new().groups(["Studio"])
2199///     .extra_ips(["192.168.0.107"]))?;
2200/// let cache = SourceCache::new(finder);
2201/// let feeds = cache.find_sources_by_host("192.168.0.107", Duration::from_secs(5))?;
2202/// for feed in feeds { println!("{feed}"); }
2203/// # Ok(())
2204/// # }
2205/// ```
2206pub struct SourceCache {
2207    finder: Finder,
2208    entries: CachedSources,
2209}
2210
2211impl fmt::Debug for SourceCache {
2212    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2213        f.debug_struct("SourceCache")
2214            .field("finder", &self.finder)
2215            .finish_non_exhaustive()
2216    }
2217}
2218
2219#[derive(Default)]
2220struct CachedSources {
2221    cache: Mutex<CacheState>,
2222}
2223
2224struct CacheState {
2225    entries: HashMap<HostKey, Arc<Vec<Source>>>,
2226    generation: Option<u64>,
2227}
2228
2229impl Default for CacheState {
2230    fn default() -> Self {
2231        Self {
2232            entries: HashMap::new(),
2233            generation: Some(0),
2234        }
2235    }
2236}
2237
2238impl CacheState {
2239    fn invalidate_pending(&mut self) {
2240        self.generation = self.generation.and_then(|value| value.checked_add(1));
2241    }
2242}
2243
2244/// Publication eligibility observed under the cache lock when a lookup missed.
2245pub(crate) struct CacheMiss(Option<u64>);
2246
2247pub(crate) enum CacheProbe {
2248    Hit(Vec<Source>),
2249    Miss(CacheMiss),
2250}
2251
2252impl SourceCache {
2253    #[cfg(any(feature = "tokio", feature = "smol"))]
2254    pub(crate) fn probe_host(&self, query: HostQuery<'_>) -> Result<CacheProbe> {
2255        self.entries.probe(query, copy_sources)
2256    }
2257
2258    #[cfg(all(test, any(feature = "tokio", feature = "smol")))]
2259    pub(crate) fn seed_for_test(&self, host: &str, sources: Vec<Source>) {
2260        let key = HostKey::try_from(HostQuery::checked(host).unwrap()).unwrap();
2261        self.entries.publish(Some(0), key, Arc::new(sources));
2262    }
2263
2264    /// Create an empty cache owning `finder` and its discovery configuration.
2265    ///
2266    /// This moves the finder without allocating, cloning or making an SDK call.
2267    /// It keeps the finder alive and NDI initialized until the cache is dropped.
2268    /// Share the cache through [`std::sync::Arc`] for long-lived server workers;
2269    /// [`finder`](Self::finder) reaches the same finder for uncached lookups.
2270    ///
2271    /// ```no_run
2272    /// use grafton_ndi::{Finder, FinderOptions, Ndi, Result, SourceCache};
2273    /// use std::sync::Arc;
2274    ///
2275    /// struct ServerState {
2276    ///     sources: SourceCache,
2277    /// }
2278    ///
2279    /// fn server_state(ndi: &Ndi) -> Result<Arc<ServerState>> {
2280    ///     let options = FinderOptions::new().groups(["Studio"]);
2281    ///     let finder = Finder::new(ndi, &options)?;
2282    ///     Ok(Arc::new(ServerState {
2283    ///         sources: SourceCache::new(finder),
2284    ///     }))
2285    /// }
2286    /// ```
2287    pub fn new(finder: Finder) -> Self {
2288        Self {
2289            finder,
2290            entries: CachedSources::default(),
2291        }
2292    }
2293
2294    /// The configured finder, borrowed for uncached discovery and selection.
2295    ///
2296    /// This allocates nothing and makes no SDK call. The finder cannot be
2297    /// replaced through this borrow, so cached entries retain their scope.
2298    #[must_use]
2299    pub fn finder(&self) -> &Finder {
2300        &self.finder
2301    }
2302
2303    /// All feeds observed for a hostname, IP or NDI machine name within `timeout`.
2304    ///
2305    /// A cache hit returns owned descriptor copies without an SDK call. On a
2306    /// miss, observes the full window using the configured finder; zero makes
2307    /// one non-waiting snapshot attempt. Results keep first-observed order, and
2308    /// sources that differ in name or full address text are distinct. Select the
2309    /// desired feed explicitly.
2310    /// Empty results return an empty vector and are not retained. If the final
2311    /// snapshot lock stays busy until the budget expires, the feeds observed
2312    /// so far are returned uncached and a later miss retries discovery.
2313    ///
2314    /// Discovery runs outside the cache lock; its window includes snapshot-lock
2315    /// contention. Access to cached descriptor copies can briefly serialize on the
2316    /// cache mutex. Copying and native snapshot execution can finish after the
2317    /// discovery wait budget. [`Finder::find_sources`] describes the bounded
2318    /// discovery work and its allocation errors. Copying a cache hit can return
2319    /// [`Error::AllocationFailed`] if the result vector cannot be reserved.
2320    /// On a miss, reservations to copy the result, prepare a host key or grow
2321    /// the cache map are best-effort. Creating the shared snapshot owner uses
2322    /// the global allocator's allocation failure handler, as does creating
2323    /// shared source owners during [`Finder::current_sources`].
2324    /// Entries have the explicit stale-data policy described on [`SourceCache`].
2325    ///
2326    /// # Errors
2327    ///
2328    /// [`Error::InvalidInput`] for a query outside [`Source::matches_host`]'s
2329    /// grammar or a timeout above [`crate::MAX_TIMEOUT`], even on a cache hit.
2330    /// The host is checked before the timeout, including in async lookups;
2331    /// discovery/resource errors propagate without filling an entry. A failed
2332    /// publication reservation returns the discovered result uncached. IP hints
2333    /// must already be configured on the finder.
2334    #[doc(alias = "NDIlib_find_get_current_sources")]
2335    #[doc(alias = "NDIlib_find_wait_for_sources")]
2336    pub fn find_sources_by_host(&self, host: &str, timeout: Duration) -> Result<Vec<Source>> {
2337        let (query, deadline) = checked_host_lookup(host, timeout)?;
2338        let Ok(sources) = self.find_sources_by_host_until(query, deadline, None, NeverStop)?;
2339        Ok(sources)
2340    }
2341
2342    pub(crate) fn find_sources_by_host_until<S: Stop>(
2343        &self,
2344        query: HostQuery<'_>,
2345        deadline: Deadline,
2346        previous_miss: Option<CacheMiss>,
2347        stop: S,
2348    ) -> StopResult<Vec<Source>, S> {
2349        self.entries.find_sources_by_host_with::<S>(
2350            query,
2351            deadline,
2352            previous_miss,
2353            |query, deadline| self.discover_host_until(query, deadline, stop),
2354        )
2355    }
2356
2357    fn discover_host_until<S: Stop>(
2358        &self,
2359        query: HostQuery<'_>,
2360        deadline: Deadline,
2361        stop: S,
2362    ) -> StopResult<DiscoveryOutcome, S> {
2363        self.finder()
2364            .find_selected_sources_until(deadline, stop, Some(query))
2365    }
2366
2367    /// Remove a host's complete result set and suppress pending fills.
2368    /// Equivalent spellings remove the same entry. An invalid host removes no
2369    /// entry but still suppresses publication from every pending discovery.
2370    pub fn invalidate(&self, host: &str) {
2371        self.entries.invalidate(host);
2372    }
2373
2374    /// Remove every result set and suppress publication from pending discovery.
2375    pub fn clear(&self) {
2376        self.entries.clear();
2377    }
2378
2379    /// Number of cached host result sets; each holds every feed observed for its host.
2380    pub fn len(&self) -> usize {
2381        self.entries.len()
2382    }
2383
2384    /// Whether no host result sets are cached.
2385    pub fn is_empty(&self) -> bool {
2386        self.entries.is_empty()
2387    }
2388}
2389
2390/// Fallibly reserve descriptor copies while sharing their immutable, validated
2391/// source strings. Discovery has already bounded the string storage.
2392fn copy_sources(sources: &[Source]) -> Result<Vec<Source>> {
2393    let mut copy = Vec::new();
2394    copy.try_reserve_exact(sources.len())
2395        .map_err(|_| budget::allocation_failed())?;
2396    for source in sources {
2397        copy.push(source.clone());
2398    }
2399    Ok(copy)
2400}
2401
2402impl CachedSources {
2403    /// Clone the map entry under the short lock, then copy descriptors outside it.
2404    /// The miss generation belongs to the same lookup used for publication.
2405    fn probe(
2406        &self,
2407        query: HostQuery<'_>,
2408        copy: impl FnOnce(&[Source]) -> Result<Vec<Source>>,
2409    ) -> Result<CacheProbe> {
2410        let (snapshot, generation) = {
2411            let cache = self
2412                .cache
2413                .lock()
2414                .unwrap_or_else(|poisoned| poisoned.into_inner());
2415            (
2416                cache.entries.get(&query as &dyn HostIdentity).cloned(),
2417                cache.generation,
2418            )
2419        };
2420        match snapshot {
2421            Some(snapshot) => copy(&snapshot).map(CacheProbe::Hit),
2422            None => Ok(CacheProbe::Miss(CacheMiss(generation))),
2423        }
2424    }
2425
2426    fn find_sources_by_host_with<S: Stop>(
2427        &self,
2428        query: HostQuery<'_>,
2429        deadline: Deadline,
2430        previous_miss: Option<CacheMiss>,
2431        discover: impl FnOnce(HostQuery<'_>, Deadline) -> StopResult<DiscoveryOutcome, S>,
2432    ) -> StopResult<Vec<Source>, S> {
2433        self.find_sources_by_host_with_copy::<S>(
2434            query,
2435            deadline,
2436            previous_miss,
2437            discover,
2438            copy_sources,
2439        )
2440    }
2441
2442    fn find_sources_by_host_with_copy<S: Stop>(
2443        &self,
2444        query: HostQuery<'_>,
2445        deadline: Deadline,
2446        previous_miss: Option<CacheMiss>,
2447        discover: impl FnOnce(HostQuery<'_>, Deadline) -> StopResult<DiscoveryOutcome, S>,
2448        mut copy: impl FnMut(&[Source]) -> Result<Vec<Source>>,
2449    ) -> StopResult<Vec<Source>, S> {
2450        // A queued lookup can use a hit published before its worker starts.
2451        // It keeps the original generation if discovery is still needed.
2452        let CacheMiss(generation) = match self.probe(query, &mut copy)? {
2453            CacheProbe::Hit(sources) => return Ok(Ok(sources)),
2454            CacheProbe::Miss(miss) => previous_miss.unwrap_or(miss),
2455        };
2456        // SDK waits and user discovery run outside the cache mutex. Invalidation
2457        // changes the generation, so an old result cannot repopulate the cache.
2458        let sources = match discover(query, deadline)? {
2459            Ok(DiscoveryOutcome::Complete(sources)) => sources,
2460            Ok(DiscoveryOutcome::SnapshotBusy(sources)) => return Ok(Ok(sources)),
2461            Err(stopped) => return Ok(Err(stopped)),
2462        };
2463        if !sources.is_empty() {
2464            {
2465                let cache = self
2466                    .cache
2467                    .lock()
2468                    .unwrap_or_else(|poisoned| poisoned.into_inner());
2469                if generation.is_none()
2470                    || cache.generation != generation
2471                    || cache.entries.contains_key(&query as &dyn HostIdentity)
2472                {
2473                    return Ok(Ok(sources));
2474                }
2475            }
2476            // The bounded, fallible descriptor copy happens outside the mutex.
2477            // Publication must still recheck both generation and key: another
2478            // discovery or invalidation may have completed during this copy.
2479            let Ok(snapshot) = copy(&sources) else {
2480                return Ok(Ok(sources));
2481            };
2482            let Ok(key) = HostKey::try_from(query) else {
2483                return Ok(Ok(sources));
2484            };
2485            self.publish(generation, key, Arc::new(snapshot));
2486        }
2487        Ok(Ok(sources))
2488    }
2489
2490    // Admission cannot change the caller's discovered result. Prepare copies
2491    // outside the lock, then recheck ownership before reserving and inserting.
2492    fn publish(&self, generation: Option<u64>, key: HostKey, snapshot: Arc<Vec<Source>>) {
2493        let mut cache = self
2494            .cache
2495            .lock()
2496            .unwrap_or_else(|poisoned| poisoned.into_inner());
2497        if generation.is_some()
2498            && cache.generation == generation
2499            && !cache.entries.contains_key(&key)
2500            && cache.entries.try_reserve(1).is_ok()
2501        {
2502            cache.entries.insert(key, snapshot);
2503        }
2504    }
2505
2506    fn invalidate(&self, host: &str) {
2507        let retired = {
2508            let mut cache = self
2509                .cache
2510                .lock()
2511                .unwrap_or_else(|poisoned| poisoned.into_inner());
2512            cache.invalidate_pending();
2513            HostQuery::parse(host)
2514                .and_then(|query| cache.entries.remove_entry(&query as &dyn HostIdentity))
2515        };
2516        // Transfer the complete entry, including its key, before reclaiming
2517        // strings or the final snapshot owner. Readers only wait for removal.
2518        drop(retired);
2519    }
2520
2521    fn clear(&self) {
2522        let retired = {
2523            let mut cache = self
2524                .cache
2525                .lock()
2526                .unwrap_or_else(|poisoned| poisoned.into_inner());
2527            cache.invalidate_pending();
2528            std::mem::take(&mut cache.entries)
2529        };
2530        // Detaching the map is constant-sized and allocation-free. Reclaim its
2531        // entries and high-water bucket storage after releasing the mutex.
2532        drop(retired);
2533    }
2534
2535    fn len(&self) -> usize {
2536        self.cache
2537            .lock()
2538            .unwrap_or_else(|poisoned| poisoned.into_inner())
2539            .entries
2540            .len()
2541    }
2542
2543    fn is_empty(&self) -> bool {
2544        self.len() == 0
2545    }
2546}
2547
2548#[cfg(test)]
2549mod tests {
2550    // Exercise the cache with the same checked inputs as the synchronous
2551    // boundary, while letting individual tests supply discovery and copying.
2552    impl CachedSources {
2553        fn lookup(
2554            &self,
2555            host: &str,
2556            timeout: Duration,
2557            discover: impl FnOnce(HostQuery<'_>) -> Result<Vec<Source>>,
2558        ) -> Result<Vec<Source>> {
2559            self.lookup_with_copy(host, timeout, discover, copy_sources)
2560        }
2561
2562        fn lookup_with_copy(
2563            &self,
2564            host: &str,
2565            timeout: Duration,
2566            discover: impl FnOnce(HostQuery<'_>) -> Result<Vec<Source>>,
2567            copy: impl FnMut(&[Source]) -> Result<Vec<Source>>,
2568        ) -> Result<Vec<Source>> {
2569            let (query, deadline) = checked_host_lookup(host, timeout)?;
2570            let Ok(sources) = self.find_sources_by_host_with_copy::<NeverStop>(
2571                query,
2572                deadline,
2573                None,
2574                |query, _| discover(query).map(|sources| Ok(DiscoveryOutcome::Complete(sources))),
2575                copy,
2576            )?;
2577            Ok(sources)
2578        }
2579    }
2580
2581    unsafe fn source_from_raw(
2582        source: *const NDIlib_source_t,
2583        function: &'static std::ffi::CStr,
2584    ) -> Result<Source> {
2585        // SAFETY: forwarded to the test caller's live-descriptor obligation.
2586        unsafe { Source::try_from_raw(sys::table::for_test(source, function)) }
2587    }
2588
2589    use super::*;
2590
2591    const MALFORMED_SOURCE_NAMES: [(&str, &str); 5] = [
2592        ("\0leading", "\0"),
2593        ("bad\0name", "bad\0"),
2594        ("trailing\0", "trailing\0"),
2595        ("multiple\0names\0", "multiple\0"),
2596        ("é映\0later", "é映\0"),
2597    ];
2598
2599    fn assert_same_name_error(actual: Error, expected: &Error) {
2600        match (actual, expected) {
2601            (Error::InvalidInput(actual), Error::InvalidInput(expected)) => {
2602                assert_eq!(&actual, expected)
2603            }
2604            (Error::InvalidCString(actual), Error::InvalidCString(expected)) => {
2605                assert_eq!(&actual, expected)
2606            }
2607            (actual, expected) => panic!("different errors: {actual:?}, {expected:?}"),
2608        }
2609    }
2610
2611    #[test]
2612    fn source_names_preserve_checked_text_and_distinguish_empty_from_nul() {
2613        assert_same_name_error(
2614            SourceName::checked("").unwrap_err(),
2615            &Error::InvalidInput(crate::InputDefect::Empty {
2616                what: "source name",
2617            }),
2618        );
2619        for (name, prefix) in MALFORMED_SOURCE_NAMES {
2620            let Error::InvalidCString(error) = SourceName::checked(name).unwrap_err() else {
2621                panic!("expected a NUL error for {name:?}");
2622            };
2623            assert_eq!(error.nul_position(), prefix.len() - 1);
2624            #[cfg(feature = "file-io")]
2625            assert_same_name_error(
2626                crate::file::SourceSpec::new(name).unwrap_err(),
2627                &Error::InvalidCString(error.clone()),
2628            );
2629            assert_eq!(error.into_vec(), prefix.as_bytes());
2630        }
2631        let longest = "x".repeat(if cfg!(miri) {
2632            64
2633        } else {
2634            crate::sdk_copy::MAX_SDK_STRING_BYTES - 1
2635        });
2636        for name in ["STUDIO (Camera 1)", "Caméra (映像)", longest.as_str()] {
2637            let (checked, allocations) =
2638                crate::test_alloc::allocation_count(|| SourceName::checked(name).unwrap());
2639            assert_eq!(allocations, 0);
2640            assert_eq!(checked.as_str(), name);
2641            let (native, allocations) =
2642                crate::test_alloc::allocation_count(|| checked.clone().into_c_string());
2643            assert_eq!(allocations, 1);
2644            assert_eq!(native.to_str().unwrap(), name);
2645            #[cfg(any(feature = "tokio", feature = "smol"))]
2646            assert_eq!(checked.into_owned().as_str(), name);
2647            #[cfg(feature = "file-io")]
2648            assert_eq!(
2649                crate::file::SourceSpec::new(name).unwrap().name(),
2650                Some(name)
2651            );
2652        }
2653        // Address-only Source values intentionally do not use this name rule.
2654        assert_eq!(Source::new("").unwrap().name(), "");
2655    }
2656
2657    #[test]
2658    fn invalid_source_name_allocation_depends_only_on_the_prefix() {
2659        for prefix in ["\0", "é映\0"] {
2660            let (_, prefix_peak) =
2661                crate::test_alloc::peak_bytes(|| SourceName::checked(prefix).unwrap_err());
2662            assert!(prefix_peak <= 64);
2663            let max_suffix = if cfg!(miri) { 64 } else { 1 << 20 };
2664            for suffix_len in [1, 32, max_suffix] {
2665                let name = format!("{prefix}{}", "x".repeat(suffix_len));
2666                let (error, peak) =
2667                    crate::test_alloc::peak_bytes(|| SourceName::checked(&name).unwrap_err());
2668                let Error::InvalidCString(error) = error else {
2669                    panic!("expected a NUL error");
2670                };
2671                assert_eq!(error.nul_position(), prefix.len() - 1);
2672                assert_eq!(error.into_vec(), prefix.as_bytes());
2673                assert_eq!(peak, prefix_peak, "suffix length {suffix_len}");
2674            }
2675        }
2676    }
2677
2678    #[test]
2679    fn discovery_lookup_checks_inputs_before_timeouts_without_a_runtime() {
2680        let excessive = crate::MAX_TIMEOUT + Duration::from_nanos(1);
2681        for timeout in [Duration::ZERO, excessive] {
2682            for name in ["", "bad\0name", "trailing\0"] {
2683                assert_same_name_error(
2684                    checked_name_lookup(name, timeout).err().unwrap(),
2685                    &SourceName::checked(name).unwrap_err(),
2686                );
2687            }
2688            for host in ["", "bad\0host", "http://camera"] {
2689                assert_same_name_error(
2690                    checked_host_lookup(host, timeout).err().unwrap(),
2691                    &Error::InvalidInput(crate::InputDefect::InvalidHostQuery),
2692                );
2693            }
2694        }
2695        for result in [
2696            checked_name_lookup("camera", excessive).err(),
2697            checked_host_lookup("camera", excessive).err(),
2698        ] {
2699            assert!(matches!(
2700                result,
2701                Some(Error::InvalidInput(
2702                    crate::InputDefect::TimeoutTooLong { .. }
2703                ))
2704            ));
2705        }
2706    }
2707
2708    #[test]
2709    fn exact_source_name_entry_points_share_errors_before_native_lookup() {
2710        let Some(ndi) = crate::test_support::ndi() else {
2711            return;
2712        };
2713        let finder = Finder::new(&ndi, &FinderOptions::new().show_local_sources(false)).unwrap();
2714        let mut listener = crate::test_support::require_feature(
2715            ndi.require_feature(crate::RuntimeFeature::ReceiverDiscovery),
2716        )
2717        .then(|| {
2718            crate::discovery_server::RecvListener::new(
2719                &ndi,
2720                &crate::discovery_server::ListenerOptions::new().server("127.0.0.1:1"),
2721            )
2722            .unwrap()
2723        });
2724        let id = crate::discovery_server::ReceiverId::new("not-advertised").unwrap();
2725        for name in std::iter::once("").chain(MALFORMED_SOURCE_NAMES.map(|(name, _)| name)) {
2726            let expected = SourceName::checked(name).unwrap_err();
2727            assert_same_name_error(
2728                finder
2729                    .find_source_by_name(name, Duration::ZERO)
2730                    .unwrap_err(),
2731                &expected,
2732            );
2733            #[cfg(feature = "file-io")]
2734            assert_same_name_error(crate::file::SourceSpec::new(name).unwrap_err(), &expected);
2735            if let Some(listener) = &mut listener {
2736                // This ID has no membership; invalid text must win before it is read.
2737                assert_same_name_error(listener.request_connect(&id, name).unwrap_err(), &expected);
2738            }
2739        }
2740    }
2741
2742    #[test]
2743    fn source_cursor_commits_only_completed_observations_in_protocol_order() {
2744        let cursor = SourceCursor::new(1);
2745        let generation = Cell::new(10);
2746        let (_, observation) = SourceCursor::observe_snapshot(
2747            || generation.get(),
2748            || {
2749                generation.set(11);
2750                Ok(())
2751            },
2752            |_| true,
2753        )
2754        .unwrap();
2755        assert_eq!(cursor.observed(), 1, "a worker cannot commit its result");
2756        cursor.commit(observation);
2757        assert_eq!(cursor.observed(), 10, "snapshot observes before copying");
2758
2759        let failed = SourceCursor::observe_snapshot(
2760            || generation.get(),
2761            || Err::<(), _>(Error::InvalidInput(crate::InputDefect::InvalidHostQuery)),
2762            |_| true,
2763        );
2764        assert!(failed.is_err());
2765        assert_eq!(
2766            cursor.observed(),
2767            10,
2768            "failure does not acknowledge a report"
2769        );
2770        let (_, incomplete) =
2771            SourceCursor::observe_snapshot(|| generation.get(), || Ok(None::<()>), Option::is_some)
2772                .unwrap();
2773        cursor.commit(incomplete);
2774        assert_eq!(
2775            cursor.observed(),
2776            10,
2777            "an incomplete internal copy is not success"
2778        );
2779
2780        let (changed, observation) = SourceCursor::observe_wait(
2781            || generation.get(),
2782            || {
2783                generation.set(12);
2784                true
2785            },
2786        );
2787        assert!(changed);
2788        assert_eq!(cursor.observed(), 10);
2789        cursor.commit(observation);
2790        assert_eq!(cursor.observed(), 12, "wait observes after its report");
2791        let (changed, observation) = SourceCursor::observe_wait(
2792            || panic!("an unchanged wait has no generation to acknowledge"),
2793            || false,
2794        );
2795        assert!(!changed);
2796        cursor.commit(observation);
2797        assert_eq!(cursor.observed(), 12);
2798        let (_, abandoned) = SourceCursor::observe_snapshot(|| 13, || Ok(()), |_| true).unwrap();
2799        let _ = abandoned; // A dropped async future never calls commit.
2800        assert_eq!(cursor.observed(), 12);
2801    }
2802
2803    #[test]
2804    fn discovery_window_charges_shared_source_strings_once() {
2805        let entry = source_entry(c"HOST (Camera)".as_ptr(), c"192.0.2.7:5961".as_ptr());
2806        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
2807        let guard = SnapshotGuard {
2808            instance: mutex.lock(),
2809        };
2810        let mut window = DiscoveryWindow::default();
2811        let entries = [entry, entry];
2812        let snapshot = SliceSnapshot(&entries);
2813        guard.discover(&snapshot, &mut window, None).unwrap();
2814        let source = &window.sources[0];
2815        let expected =
2816            source.name.storage_bytes() + source.address.as_ref().unwrap().0.storage_bytes();
2817        assert_eq!(window.retained_bytes, expected);
2818        assert!(Arc::ptr_eq(
2819            &source.name.0,
2820            &window
2821                .seen
2822                .get(source as &dyn SourceIdentity)
2823                .unwrap()
2824                .0
2825                .name
2826                .0
2827        ));
2828        guard.discover(&snapshot, &mut window, None).unwrap();
2829        assert_eq!(window.retained_bytes, expected, "duplicates add no storage");
2830    }
2831
2832    #[test]
2833    fn a_typed_stop_does_not_publish_an_incomplete_host_window() {
2834        use std::sync::atomic::AtomicBool;
2835        let cache = CachedSources::default();
2836        let outcome = cache
2837            .find_sources_by_host_with::<&AtomicBool>(
2838                HostQuery::checked("camera").unwrap(),
2839                Deadline::after(Duration::ZERO).unwrap(),
2840                None,
2841                |_, _| Ok(Err(crate::timeout::Stopped)),
2842            )
2843            .unwrap();
2844        assert!(matches!(outcome, Err(crate::timeout::Stopped)));
2845        assert!(cache.is_empty());
2846    }
2847
2848    #[test]
2849    fn cache_discovery_retains_the_deadline_that_precedes_the_lookup() {
2850        let cache = CachedSources::default();
2851        let deadline = Deadline::starting(
2852            std::time::Instant::now() - Duration::from_secs(1),
2853            crate::timeout::Timeout::new(Duration::from_millis(1)).unwrap(),
2854        )
2855        .unwrap();
2856        let sources = cache
2857            .find_sources_by_host_with::<NeverStop>(
2858                HostQuery::checked("camera").unwrap(),
2859                deadline,
2860                None,
2861                |query, remaining| {
2862                    assert!(matches!(query, HostQuery::Host("camera")));
2863                    assert_eq!(remaining.end(), deadline.end());
2864                    assert!(remaining.is_expired());
2865                    Ok(Ok(DiscoveryOutcome::Complete(Vec::new())))
2866                },
2867            )
2868            .unwrap()
2869            .unwrap();
2870        assert!(sources.is_empty());
2871    }
2872
2873    #[cfg(any(feature = "tokio", feature = "smol"))]
2874    #[test]
2875    fn owned_host_queries_keep_the_parsed_kind_and_normalized_text() {
2876        for (host, kind) in [
2877            ("192.0.2.1", 0),
2878            ("[2001:db8::1]", 0),
2879            ("Camera.LOCAL.", 1),
2880            ("Studio A.", 2),
2881        ] {
2882            let text = host.to_owned();
2883            let parsed = HostQuery::checked(&text).unwrap();
2884            let expected = HostKey::try_from(parsed).unwrap();
2885            let owned = parsed.into_owned();
2886            drop(text);
2887            let query = owned.as_query();
2888            assert!(matches!(
2889                (kind, query),
2890                (0, HostQuery::Ip(_)) | (1, HostQuery::Host(_)) | (2, HostQuery::Machine(_)),
2891            ));
2892            assert_eq!(HostKey::try_from(query).unwrap(), expected);
2893        }
2894    }
2895
2896    #[test]
2897    fn advertised_hosts_round_trip_through_authority() {
2898        for host in [
2899            "192.0.2.10",
2900            "[192.0.2.10]",
2901            "::1",
2902            "2001:db8:0000::0010",
2903            "[2001:db8:0000::0010]",
2904            "::ffff:192.0.2.10",
2905            "a",
2906            "camera-1.local",
2907            "CAMERA.Local.",
2908        ] {
2909            let query = HostQuery::parse(host).unwrap();
2910            for port in [
2911                NonZeroU16::MIN,
2912                NonZeroU16::new(5960).unwrap(),
2913                NonZeroU16::MAX,
2914            ] {
2915                let endpoint = SourceAddress::from_advertised_host(host, port).unwrap();
2916                let authority = parse_authority(endpoint.as_str()).unwrap();
2917                assert!(query.matches(authority.host), "{host}: {endpoint:?}");
2918                assert_eq!(authority.port, Some(port.get()));
2919            }
2920        }
2921    }
2922
2923    #[test]
2924    fn source_values_refuse_nul_before_any_native_use() {
2925        assert!(matches!(
2926            Source::new("Camera\0other"),
2927            Err(Error::InvalidCString(_))
2928        ));
2929        assert!(matches!(
2930            SourceAddress::new("camera\0other"),
2931            Err(Error::InvalidCString(_))
2932        ));
2933        assert_eq!(Source::new("").unwrap().name(), "");
2934        assert_eq!(SourceAddress::new("").unwrap().as_str(), "");
2935    }
2936
2937    #[test]
2938    fn configured_lists_preserve_elements_and_validate_at_owner_creation() {
2939        let options = FinderOptions::new()
2940            .groups(["Public", "Studio"])
2941            .extra_ips(["192.0.2.1", "192.0.2.2"]);
2942        assert_eq!(options.configured_groups().unwrap(), ["Public", "Studio"]);
2943        assert_eq!(
2944            list_cstring(options.configured_groups(), "groups")
2945                .unwrap()
2946                .as_deref(),
2947            Some(c"Public,Studio")
2948        );
2949        assert_eq!(list_cstring(None, "groups").unwrap(), None);
2950        assert!(matches!(
2951            list_cstring(Some(&[]), "groups"),
2952            Err(Error::InvalidInput(crate::InputDefect::Empty {
2953                what: "groups"
2954            }))
2955        ));
2956        for invalid in ["", "Studio,Public", "Studio\0Public"] {
2957            let options = FinderOptions::new().groups(["valid", invalid]);
2958            assert_eq!(options.configured_groups().unwrap()[1], invalid);
2959            assert!(matches!(
2960                list_cstring(options.configured_groups(), "groups"),
2961                Err(Error::InvalidInput(crate::InputDefect::ListElement {
2962                    setting: "groups",
2963                    index: 1
2964                }))
2965            ));
2966        }
2967    }
2968
2969    #[test]
2970    fn configured_lists_report_the_first_invalid_element_across_checks() {
2971        for (values, expected) in [
2972            (["first\0nul", "", "last,comma"], 0),
2973            (["first,comma", "second\0nul", ""], 0),
2974            (["", "second\0nul", "last,comma"], 0),
2975            (["valid", "second\0nul", "last,comma"], 1),
2976            (["valid", "second,comma", "last\0nul"], 1),
2977            (["valid", "", "last\0nul"], 1),
2978            (["non-ASCII café", "second\0nul", "last,comma"], 1),
2979            (["valid", "second", "last\0nul"], 2),
2980        ] {
2981            let values = values.map(str::to_owned);
2982            assert!(matches!(
2983                list_cstring(Some(&values), "servers"),
2984                Err(Error::InvalidInput(crate::InputDefect::ListElement {
2985                    setting: "servers",
2986                    index,
2987                })) if index == expected
2988            ));
2989        }
2990    }
2991
2992    #[test]
2993    fn cache_descriptor_copies_release_the_global_mutex_and_recheck_publication() {
2994        let cache = CachedSources::default();
2995        let sources = vec![Source::new("camera (Program)").unwrap()];
2996        for hit in [false, true] {
2997            let result = cache
2998                .lookup_with_copy(
2999                    "camera",
3000                    Duration::ZERO,
3001                    |_| {
3002                        assert!(!hit);
3003                        Ok(sources.clone())
3004                    },
3005                    |snapshot| {
3006                        assert!(
3007                            cache.cache.try_lock().is_ok(),
3008                            "descriptor copies must not hold the cache mutex"
3009                        );
3010                        copy_sources(snapshot)
3011                    },
3012                )
3013                .unwrap();
3014            assert_eq!(result, sources);
3015        }
3016        cache.clear();
3017        let result = cache
3018            .lookup_with_copy(
3019                "camera",
3020                Duration::ZERO,
3021                |_| Ok(sources.clone()),
3022                |snapshot| {
3023                    cache.invalidate("camera");
3024                    copy_sources(snapshot)
3025                },
3026            )
3027            .unwrap();
3028        assert_eq!(result, sources);
3029        assert!(
3030            cache.is_empty(),
3031            "invalidation during snapshot preparation suppresses publication"
3032        );
3033        cache
3034            .lookup_with_copy(
3035                "camera",
3036                Duration::ZERO,
3037                |_| {
3038                    cache.clear();
3039                    Ok(sources.clone())
3040                },
3041                |_| panic!("stale discovery must not allocate a publication copy"),
3042            )
3043            .unwrap();
3044    }
3045
3046    #[test]
3047    fn publication_failure_returns_discovery_but_hit_failure_is_reported() {
3048        let cache = CachedSources::default();
3049        let sources = vec![Source::new("camera (Program)").unwrap()];
3050        for invalidate in [false, true] {
3051            let result = cache
3052                .lookup_with_copy(
3053                    "camera",
3054                    Duration::ZERO,
3055                    |_| Ok(sources.clone()),
3056                    |_| {
3057                        if invalidate {
3058                            cache.invalidate("camera");
3059                        }
3060                        Err(budget::allocation_failed())
3061                    },
3062                )
3063                .unwrap();
3064            assert_eq!(result, sources);
3065            assert!(cache.is_empty());
3066        }
3067        cache
3068            .lookup("camera", Duration::ZERO, |_| Ok(sources.clone()))
3069            .unwrap();
3070        let result = cache.lookup_with_copy(
3071            "camera",
3072            Duration::ZERO,
3073            |_| panic!("a hit must not run discovery"),
3074            |_| Err(budget::allocation_failed()),
3075        );
3076        assert!(matches!(
3077            result,
3078            Err(Error::AllocationFailed(crate::AllocationFailure {
3079                kind: crate::AllocationKind::DiscoveryResults,
3080                ..
3081            }))
3082        ));
3083        assert_eq!(cache.len(), 1);
3084    }
3085
3086    #[test]
3087    fn successful_cache_publication_keeps_its_allocation_count() {
3088        for (host, expected) in [("camera", 4), ("192.0.2.1", 3)] {
3089            let cache = CachedSources::default();
3090            // Initialize native mutex storage before measuring publication.
3091            assert!(cache.is_empty());
3092            let sources = vec![Source::new("camera (Program)").unwrap()];
3093            let (result, allocations) = crate::test_alloc::allocation_count(|| {
3094                cache.lookup(host, Duration::ZERO, |_| Ok(sources))
3095            });
3096            assert_eq!(result.unwrap().len(), 1);
3097            // One vector, its Arc header and map storage; only names need an
3098            // allocated key. Source strings remain shared with the caller.
3099            assert_eq!(allocations, expected, "{host}");
3100            assert_eq!(cache.len(), 1);
3101        }
3102    }
3103
3104    #[test]
3105    fn owned_source_selection_checks_cancellation_between_candidates() {
3106        use std::sync::atomic::{AtomicBool, Ordering};
3107
3108        let names = ["first", "second", "third", "fourth"];
3109        let sources: Vec<_> = names
3110            .into_iter()
3111            .map(|name| Source::new(name).unwrap())
3112            .collect();
3113        for prefix in 0..names.len() {
3114            let stop = AtomicBool::new(prefix == 0);
3115            let mut visited = Vec::new();
3116            let result = select_owned_source(sources.clone(), &stop, &mut |source| {
3117                visited.push(source.name().to_owned());
3118                if visited.len() == prefix {
3119                    stop.store(true, Ordering::Release);
3120                }
3121                false
3122            });
3123            assert_eq!(result, Err(crate::timeout::Stopped));
3124            assert_eq!(visited, names[..prefix]);
3125        }
3126        for (target, expected) in [(Some("third"), 3), (None, 4)] {
3127            let stop = AtomicBool::new(false);
3128            let mut visited = Vec::new();
3129            let result = select_owned_source(sources.clone(), &stop, &mut |source| {
3130                visited.push(source.name().to_owned());
3131                Some(source.name()) == target
3132            });
3133            assert_eq!(result.unwrap().as_ref().map(Source::name), target);
3134            assert_eq!(visited, names[..expected]);
3135        }
3136    }
3137
3138    #[cfg(any(feature = "tokio", feature = "smol"))]
3139    #[test]
3140    fn cancellation_during_successful_snapshot_lock_acquisition_skips_the_snapshot() {
3141        use std::sync::atomic::{AtomicBool, Ordering};
3142        let Some(ndi) = crate::test_support::ndi() else {
3143            return;
3144        };
3145        let finder = Finder::new(&ndi, &FinderOptions::new()).unwrap();
3146        fn check<W: SnapshotWait>(finder: &Finder, wait: W) {
3147            let stop = AtomicBool::new(false);
3148            let mut held = Some(finder.sources_lock.lock());
3149            let mut acquired = false;
3150            let result = finder.lock_snapshots_with(wait, &stop, |remaining| {
3151                assert!(!stop.load(Ordering::Acquire));
3152                assert!(remaining > Duration::ZERO && remaining <= POLL_INTERVAL);
3153                // Model cancellation arriving while the acquisition waits,
3154                // followed by the current holder releasing within this slice.
3155                stop.store(true, Ordering::Release);
3156                drop(held.take());
3157                let instance = finder.sources_lock.try_lock_for(remaining);
3158                acquired = instance.is_some();
3159                instance
3160            });
3161            assert!(
3162                acquired,
3163                "the cancelled wait must exercise a successful acquisition"
3164            );
3165            assert!(
3166                matches!(result, Err(crate::timeout::Stopped)),
3167                "cancellation must withhold the native snapshot guard"
3168            );
3169            assert!(
3170                finder.sources_lock.try_lock().is_some(),
3171                "the cancelled acquisition must release its lock"
3172            );
3173        }
3174        check(&finder, UnboundedSnapshot);
3175        check(&finder, Deadline::after(Duration::from_secs(3)).unwrap());
3176    }
3177
3178    #[cfg(any(feature = "tokio", feature = "smol"))]
3179    #[test]
3180    fn cancelled_snapshot_lock_wait_finishes_without_entering_the_sdk() {
3181        use std::sync::{
3182            atomic::{AtomicBool, Ordering},
3183            mpsc,
3184        };
3185        const WATCHDOG: Duration = Duration::from_secs(5);
3186        let Some(ndi) = crate::test_support::ndi() else {
3187            return;
3188        };
3189        let finder = Finder::new(&ndi, &FinderOptions::new()).unwrap();
3190        let held = finder.sources_lock.lock();
3191        let stop = AtomicBool::new(false);
3192        let (ready, waiting) = mpsc::channel();
3193        let (finished, completion) = mpsc::channel();
3194        std::thread::scope(|scope| {
3195            // Keep cleanup inside the scope, so even a failed assertion drops
3196            // the held lock before scope waits for a blocked worker to finish.
3197            let held = held;
3198            let finder = &finder;
3199            let stop = &stop;
3200            let worker = scope.spawn(move || {
3201                let mut ready = Some(ready);
3202                let stopped = finder
3203                    .lock_snapshots_with(UnboundedSnapshot, stop, |remaining| {
3204                        assert!(remaining > Duration::ZERO && remaining <= POLL_INTERVAL);
3205                        if let Some(ready) = ready.take() {
3206                            ready.send(()).unwrap();
3207                        }
3208                        finder.sources_lock.try_lock_for(remaining)
3209                    })
3210                    .is_err();
3211                let _ = finished.send(stopped);
3212            });
3213            waiting.recv_timeout(WATCHDOG).unwrap();
3214            stop.store(true, Ordering::Release);
3215            // Completion must precede unlocking; the watchdog permits shared
3216            // CI scheduling delays, not an unbounded snapshot-lock wait.
3217            let result = completion.recv_timeout(WATCHDOG);
3218            drop(held);
3219            worker.join().unwrap();
3220            assert!(
3221                result.expect("cancelled snapshot wait did not finish while the lock was held"),
3222                "cancellation must withhold the native snapshot permission"
3223            );
3224        });
3225    }
3226
3227    #[test]
3228    fn the_first_watch_after_finder_creation_allocates_nothing() {
3229        let Some(ndi) = crate::test_support::ndi() else {
3230            return;
3231        };
3232        let finder = Finder::new(&ndi, &FinderOptions::new()).unwrap();
3233        // This exact Finder has had no watch, snapshot or generation query.
3234        // Native mutex initialization belongs to construction, not this call.
3235        let (watch, allocations) = crate::test_alloc::allocation_count(|| finder.watch());
3236        assert_eq!(allocations, 0);
3237        assert!(std::ptr::eq(watch.finder, &finder));
3238        assert_eq!(watch.cursor.observed(), 0);
3239    }
3240
3241    #[test]
3242    fn source_cache_moves_its_finder_without_allocating_or_recreating_it() {
3243        let Some(ndi) = crate::test_support::ndi() else {
3244            return;
3245        };
3246        let finder = Finder::new(&ndi, &FinderOptions::new().groups(["Studio"])).unwrap();
3247        let instance = finder.instance;
3248        let (cache, allocations) = crate::test_alloc::allocation_count(|| SourceCache::new(finder));
3249        assert_eq!(allocations, 0);
3250        assert_eq!(cache.finder().instance, instance);
3251        assert_eq!(cache.finder()._groups.as_deref(), Some(c"Studio"));
3252        assert!(cache.is_empty());
3253    }
3254
3255    fn host_key(host: &str) -> HostKey {
3256        HostKey::try_from(HostQuery::parse(host).unwrap()).unwrap()
3257    }
3258
3259    #[test]
3260    fn canonical_host_keys_obey_identity_and_hash_laws() {
3261        use std::hash::{DefaultHasher, Hash, Hasher};
3262        let hash = |key: &HostKey| {
3263            let mut state = DefaultHasher::new();
3264            key.hash(&mut state);
3265            let owned_hash = state.finish();
3266            let mut borrowed_state = DefaultHasher::new();
3267            std::borrow::Borrow::<dyn HostIdentity>::borrow(key).hash(&mut borrowed_state);
3268            assert_eq!(owned_hash, borrowed_state.finish());
3269            owned_hash
3270        };
3271        for variants in [
3272            vec!["camera.local", "CAMERA.LOCAL", "Camera.Local."],
3273            vec!["Studio A", "STUDIO A", "studio a."],
3274            vec!["STUDIO_PC", "studio_pc", "Studio_Pc."],
3275            vec!["ÉTAGE A", "Étage a", "Étage A."],
3276            vec!["2001:db8::1", "[2001:0DB8:0:0:0:0:0:1]", "2001:db8:0::1"],
3277            vec!["192.0.2.1", "[192.0.2.1]"],
3278        ] {
3279            for a in &variants {
3280                for b in &variants {
3281                    assert_eq!(host_key(a), host_key(b));
3282                    assert_eq!(hash(&host_key(a)), hash(&host_key(b)));
3283                }
3284            }
3285        }
3286        for name in [
3287            "camera",
3288            "camera-1.local",
3289            "a.b.c",
3290            "123",
3291            "Studio A",
3292            "studio_pc",
3293            "Étage A",
3294            &"a".repeat(63),
3295        ] {
3296            let expected = host_key(name);
3297            // Vary each ASCII letter's case independently, then the final dot.
3298            for i in 0..name.len() {
3299                let mut bytes = name.as_bytes().to_vec();
3300                bytes[i].make_ascii_uppercase();
3301                let variant = String::from_utf8(bytes).unwrap();
3302                for variant in [variant.clone(), format!("{variant}.")] {
3303                    let key = host_key(&variant);
3304                    assert_eq!(expected, key);
3305                    assert_eq!(hash(&expected), hash(&key));
3306                }
3307            }
3308        }
3309        let maximum = [
3310            "a".repeat(63),
3311            "b".repeat(63),
3312            "c".repeat(63),
3313            "d".repeat(61),
3314        ]
3315        .join(".");
3316        assert_eq!(maximum.len(), 253);
3317        assert_eq!(
3318            host_key(&maximum),
3319            host_key(&format!("{}.", maximum.to_uppercase()))
3320        );
3321        let distinct = [
3322            "camera",
3323            "camera1",
3324            "camera.local",
3325            "192.0.2.1",
3326            "192.0.2.2",
3327            "::1",
3328            "::ffff:192.0.2.1",
3329            "123",
3330            "studio a",
3331            "studio-a",
3332            "studio_a",
3333            "Étage a",
3334            "étage a",
3335        ];
3336        assert_eq!(
3337            distinct
3338                .iter()
3339                .map(|host| host_key(host))
3340                .collect::<HashSet<_>>()
3341                .len(),
3342            distinct.len()
3343        );
3344    }
3345
3346    #[test]
3347    fn typed_host_keys_match_borrowed_identity_and_hashes() {
3348        use std::hash::DefaultHasher;
3349        fn hash(key: &dyn HostIdentity) -> u64 {
3350            let mut state = DefaultHasher::new();
3351            key.hash(&mut state);
3352            state.finish()
3353        }
3354        for (a, b, equal) in [
3355            ("192.0.2.1", "[::ffff:192.0.2.1]", false),
3356            ("[2001:db8::1]", "2001:DB8::1", true),
3357            ("Camera.Local.", "camera.local", true),
3358            ("MY MACHINE", "my machine", true),
3359            ("Ä", "ä", false),
3360            ("camera..", "camera", false),
3361        ] {
3362            let a = HostQuery::checked(a).unwrap();
3363            let b = HostQuery::checked(b).unwrap();
3364            let key_a = HostKey::try_from(a).unwrap();
3365            let key_b = HostKey::try_from(b).unwrap();
3366            assert_eq!(key_a == key_b, equal);
3367            assert_eq!(hash(&a) == hash(&b), equal);
3368            assert_eq!(hash(&key_a), hash(&a));
3369            assert_eq!(hash(&key_b), hash(&b));
3370            let map = HashMap::from([(key_a, ())]);
3371            assert_eq!(map.contains_key(&b as &dyn HostIdentity), equal);
3372        }
3373        // The type keeps an IP and an identically spelled future name disjoint.
3374        let ip = HostKey::try_from(HostQuery::Ip("192.0.2.1".parse().unwrap())).unwrap();
3375        let name = HostKey::try_from(HostQuery::Machine("192.0.2.1")).unwrap();
3376        assert_ne!(ip, name);
3377        let map = HashMap::from([(ip, ())]);
3378        assert!(!map.contains_key(&HostQuery::Machine("192.0.2.1") as &dyn HostIdentity));
3379    }
3380
3381    #[test]
3382    fn borrowed_host_identity_preserves_map_laws_without_allocating_for_edge_spellings() {
3383        use std::hash::DefaultHasher;
3384        let spellings = [
3385            "camera",
3386            "Camera.",
3387            "camera..",
3388            "CAMERA..",
3389            "camera...",
3390            "Étage A",
3391            "ÉTAGE a.",
3392            "étage a",
3393            "E\u{301}tage A",
3394            "İS",
3395            "İs.",
3396            "is",
3397            "K",
3398            "K",
3399            "k.",
3400            "192.0.2.1",
3401            "[192.0.2.1]",
3402            "::ffff:192.0.2.1",
3403            "[::ffff:192.0.2.1]",
3404            "[2001:db8::1]",
3405            "2001:DB8::1",
3406        ];
3407        let queries: Vec<_> = spellings
3408            .iter()
3409            .map(|text| HostQuery::checked(text).unwrap())
3410            .collect();
3411        let keys: Vec<_> = queries
3412            .iter()
3413            .map(|&query| HostKey::try_from(query).unwrap())
3414            .collect();
3415        let hash = |value: &dyn HostIdentity| {
3416            let mut state = DefaultHasher::new();
3417            value.hash(&mut state);
3418            state.finish()
3419        };
3420        for (i, &query) in queries.iter().enumerate() {
3421            let mut map = HashMap::from([(HostKey::try_from(query).unwrap(), ())]);
3422            let ((), allocations) = crate::test_alloc::allocation_count(|| {
3423                for (j, other) in queries.iter().enumerate() {
3424                    let equal = keys[i] == keys[j];
3425                    assert_eq!(
3426                        (&query as &dyn HostIdentity) == (other as &dyn HostIdentity),
3427                        equal
3428                    );
3429                    assert_eq!(hash(&keys[j]), hash(other));
3430                    if equal {
3431                        assert_eq!(hash(&query), hash(other));
3432                    }
3433                    assert_eq!(
3434                        map.contains_key(other as &dyn HostIdentity),
3435                        equal,
3436                        "{} versus {}",
3437                        spellings[i],
3438                        spellings[j]
3439                    );
3440                    let removed = map.remove_entry(other as &dyn HostIdentity);
3441                    assert_eq!(removed.is_some(), equal);
3442                    if let Some((key, value)) = removed {
3443                        map.insert(key, value);
3444                    }
3445                }
3446            });
3447            assert_eq!(allocations, 0, "{}", spellings[i]);
3448        }
3449    }
3450
3451    #[test]
3452    fn equivalent_cache_hits_and_invalidation_share_one_identity() {
3453        for (a, b) in [
3454            ("CAMERA.LOCAL", "camera.local"),
3455            ("camera.local.", "camera.local"),
3456            ("STUDIO A", "studio a."),
3457            ("STUDIO_PC.", "studio_pc"),
3458            ("[2001:0db8:0:0:0:0:0:1]", "2001:db8::1"),
3459        ] {
3460            for (first, second) in [(a, b), (b, a)] {
3461                let cache = CachedSources::default();
3462                let old = Source::new("camera")
3463                    .unwrap()
3464                    .with_address(SourceAddress::new("192.0.2.1:5960").unwrap());
3465                let fresh = old
3466                    .clone()
3467                    .with_address(SourceAddress::new("192.0.2.1:5961").unwrap());
3468                cache
3469                    .lookup(first, Duration::ZERO, |_| Ok(vec![old.clone()]))
3470                    .unwrap();
3471                let (identical, identical_allocs) = crate::test_alloc::allocation_count(|| {
3472                    cache
3473                        .lookup(first, Duration::ZERO, |_| panic!("cache hit"))
3474                        .unwrap()
3475                });
3476                let (equivalent, equivalent_allocs) = crate::test_alloc::allocation_count(|| {
3477                    cache
3478                        .lookup(second, Duration::ZERO, |_| panic!("equivalent cache hit"))
3479                        .unwrap()
3480                });
3481                assert_eq!(identical, vec![old.clone()]);
3482                assert_eq!(equivalent, vec![old]);
3483                assert_eq!(identical_allocs, 1); // Only the vector; validated strings are shared.
3484                assert_eq!(equivalent_allocs, identical_allocs);
3485                assert_eq!(cache.len(), 1);
3486                assert!(cache
3487                    .lookup(second, Duration::MAX, |_| panic!("invalid timeout"))
3488                    .is_err());
3489                cache.invalidate(second);
3490                assert!(cache.is_empty());
3491                assert_eq!(
3492                    cache
3493                        .lookup(first, Duration::ZERO, |_| Ok(vec![fresh.clone()]))
3494                        .unwrap(),
3495                    vec![fresh]
3496                );
3497                assert_eq!(cache.len(), 1);
3498                cache.invalidate("invalid:host:port");
3499                assert_eq!(cache.len(), 1);
3500                cache.clear();
3501                assert!(cache
3502                    .lookup(first, Duration::ZERO, |_| Err(Error::InvalidInput(
3503                        crate::InputDefect::InvalidHostQuery
3504                    )))
3505                    .is_err());
3506                assert!(cache
3507                    .lookup(second, Duration::ZERO, |_| Ok(Vec::new()))
3508                    .unwrap()
3509                    .is_empty());
3510                assert!(cache.is_empty());
3511            }
3512        }
3513    }
3514
3515    #[test]
3516    fn exact_host_matching_ignores_labels_ports_and_url_payloads() {
3517        let other = Source::new("CAMERA10 (192.168.1.1)")
3518            .unwrap()
3519            .with_address(SourceAddress::new("192.168.1.100:5960").unwrap());
3520        assert!(!other.matches_host("192.168.1.1"));
3521        assert!(!other.matches_host("5960"));
3522        assert!(!other.matches_host("CAMERA1"));
3523        let exact = Source::new("CAMERA1 (Program)").unwrap().with_address(
3524            SourceAddress::new("http://user:pass@Camera.Local:8080/ndi?next=192.0.2.1").unwrap(),
3525        );
3526        assert!(exact.matches_host("camera.local."));
3527        assert!(exact.matches_host("camera1"));
3528        assert!(!exact.matches_host("192.0.2.1"));
3529        assert!(!exact.matches_host("Program"));
3530        let ipv6 = SourceAddress::new("[2001:0db8:0:0:0:0:0:1]:5960").unwrap();
3531        assert!(ipv6.matches_host("2001:db8::1"));
3532        assert!(ipv6.matches_host("[2001:db8::1]"));
3533        let studio = Source::new("Studio A (Camera)").unwrap();
3534        assert!(studio.matches_host("studio a"));
3535        assert!(studio.matches_host("STUDIO A."));
3536        assert!(!studio.matches_host("Studio"));
3537        assert!(!studio.matches_host("Camera"));
3538        assert!(Source::new("STUDIO_PC (Camera)")
3539            .unwrap()
3540            .matches_host("studio_pc"));
3541        let unicode = Source::new("ÉTAGE A (Camera)").unwrap();
3542        assert!(unicode.matches_host("Étage a"));
3543        assert!(!unicode.matches_host("étage a"));
3544        assert!(!SourceAddress::new("http://studio-a:80")
3545            .unwrap()
3546            .matches_host("Studio A"));
3547        // Even opaque address text that contains the same machine name cannot
3548        // make a machine query match an address rather than the SDK label.
3549        assert!(!SourceAddress::new("Studio A:5960")
3550            .unwrap()
3551            .matches_host("Studio A"));
3552        let too_long = "x".repeat(254);
3553        for invalid in [
3554            "",
3555            "camera:5960",
3556            "http://camera.local",
3557            "camera/local",
3558            "192.168.1",
3559            "foo\0bar",
3560            "[bad]",
3561            "Studio (A)",
3562            " Studio",
3563            "Studio\t",
3564            "Studio .",
3565            "\u{2003}Studio",
3566            "Studio\u{2003}",
3567            &too_long,
3568        ] {
3569            assert!(HostQuery::parse(invalid).is_none(), "{invalid:?}");
3570        }
3571        let (_, allocations) = crate::test_alloc::allocation_count(|| {
3572            for _ in 0..100 {
3573                assert!(exact.matches_host("CAMERA.LOCAL"));
3574                assert!(ipv6.matches_host("2001:db8::1"));
3575                assert!(studio.matches_host("STUDIO A."));
3576                assert!(unicode.matches_host("Étage a"));
3577                let query = HostQuery::parse("Studio A").unwrap();
3578                assert!(
3579                    (&query as &dyn HostIdentity)
3580                        == (&HostQuery::Machine("studio a") as &dyn HostIdentity)
3581                );
3582            }
3583        });
3584        assert_eq!(allocations, 0);
3585    }
3586
3587    #[test]
3588    fn machine_query_grammar_covers_each_printable_ascii_byte() {
3589        for byte in b' '..=b'~' {
3590            let delimiter = b":/?#@[]()".contains(&byte);
3591            let embedded = format!("Studio{}A", char::from(byte));
3592            assert_eq!(
3593                HostQuery::parse(&embedded).is_some(),
3594                !delimiter,
3595                "embedded byte {byte:#x}: {embedded:?}"
3596            );
3597            let single = char::from(byte).to_string();
3598            assert_eq!(
3599                HostQuery::parse(&single).is_some(),
3600                !delimiter && !matches!(byte, b' ' | b'.'),
3601                "standalone byte {byte:#x}: {single:?}"
3602            );
3603        }
3604        for character in (0..=31).chain(127..=159).map(char::from) {
3605            let name = format!("Studio{character}A");
3606            assert!(HostQuery::parse(&name).is_none(), "{name:?}");
3607        }
3608        for machine in ["Studio A", "STUDIO_PC", "Étage A", "a".repeat(253).as_str()] {
3609            assert!(
3610                matches!(HostQuery::parse(machine), Some(HostQuery::Machine(_))),
3611                "{machine:?}"
3612            );
3613        }
3614        for host in ["studio-a", "studio.local", "STUDIO"] {
3615            assert!(
3616                matches!(HostQuery::parse(host), Some(HostQuery::Host(_))),
3617                "{host:?}"
3618            );
3619        }
3620    }
3621
3622    #[test]
3623    fn cache_selects_exact_host_and_rejects_invalid_queries_before_discovery() {
3624        let cache = CachedSources::default();
3625        let wrong = Source::new("CAMERA10 (Program)")
3626            .unwrap()
3627            .with_address(SourceAddress::new("192.168.1.100:5960").unwrap());
3628        let right = Source::new("CAMERA1 (Program)")
3629            .unwrap()
3630            .with_address(SourceAddress::new("192.168.1.1:5961").unwrap());
3631        let timeout = Duration::ZERO;
3632        let selected = cache
3633            .lookup("192.168.1.1", timeout, |query| {
3634                Ok([wrong.clone(), right.clone()]
3635                    .into_iter()
3636                    .filter(|s| s.matches_query(query))
3637                    .collect())
3638            })
3639            .unwrap();
3640        assert_eq!(selected, vec![right.clone()]);
3641        assert_eq!(cache.len(), 1);
3642        assert_eq!(
3643            cache
3644                .lookup("192.168.1.1", timeout, |_| panic!("cache hit"))
3645                .unwrap(),
3646            vec![right]
3647        );
3648        let too_long = "x".repeat(254);
3649        for invalid in [
3650            "",
3651            "192.168.1.1:5961",
3652            "camera?query",
3653            "foo\0bar",
3654            "Studio (A)",
3655            " Studio",
3656            "Studio\t",
3657            &too_long,
3658        ] {
3659            assert!(matches!(
3660                cache.lookup(invalid, timeout, |_| panic!(
3661                    "invalid query reached discovery"
3662                )),
3663                Err(Error::InvalidInput(_))
3664            ));
3665        }
3666        assert_eq!(cache.len(), 1);
3667    }
3668
3669    #[test]
3670    fn invalidation_prevents_pending_lookup_from_repopulating_cache() {
3671        use std::sync::{mpsc, Arc};
3672        for clear in [false, true] {
3673            let cache = Arc::new(CachedSources::default());
3674            let (started_tx, started_rx) = mpsc::channel();
3675            let (resume_tx, resume_rx) = mpsc::channel();
3676            let old = Source::new("old")
3677                .unwrap()
3678                .with_address(SourceAddress::new("192.0.2.1:5960").unwrap());
3679            let fresh = Source::new("fresh")
3680                .unwrap()
3681                .with_address(SourceAddress::new("192.0.2.1:5961").unwrap());
3682            let pending = Arc::clone(&cache);
3683            let old_result = old.clone();
3684            let thread = std::thread::spawn(move || {
3685                pending
3686                    .lookup("CAMERA.LOCAL.", Duration::ZERO, |_| {
3687                        started_tx.send(()).unwrap();
3688                        resume_rx.recv().unwrap();
3689                        Ok(vec![old_result])
3690                    })
3691                    .unwrap()
3692            });
3693            started_rx.recv().unwrap();
3694            if clear {
3695                cache.clear();
3696            } else {
3697                cache.invalidate("camera.local");
3698            }
3699            assert_eq!(cache.len(), 0);
3700            let found = cache
3701                .lookup("camera.local", Duration::ZERO, |_| Ok(vec![fresh.clone()]))
3702                .unwrap();
3703            assert_eq!(found, vec![fresh.clone()]);
3704            resume_tx.send(()).unwrap();
3705            assert_eq!(thread.join().unwrap(), vec![old]);
3706            assert_eq!(
3707                cache
3708                    .lookup("Camera.Local.", Duration::ZERO, |_| panic!(
3709                        "fresh entry was overwritten"
3710                    ))
3711                    .unwrap(),
3712                vec![fresh]
3713            );
3714        }
3715    }
3716
3717    #[test]
3718    fn absent_invalidation_and_empty_clear_suppress_pending_fills() {
3719        use std::sync::{mpsc, Arc};
3720        for clear in [false, true] {
3721            let cache = Arc::new(CachedSources::default());
3722            let (started_tx, started_rx) = mpsc::channel();
3723            let (resume_tx, resume_rx) = mpsc::channel();
3724            let pending = Arc::clone(&cache);
3725            let thread = std::thread::spawn(move || {
3726                pending
3727                    .lookup("camera.local", Duration::ZERO, |_| {
3728                        started_tx.send(()).unwrap();
3729                        resume_rx.recv().unwrap();
3730                        Ok(vec![Source::new("CAMERA (Program)").unwrap()])
3731                    })
3732                    .unwrap()
3733            });
3734            started_rx.recv().unwrap();
3735            if clear {
3736                cache.clear();
3737            } else {
3738                cache.invalidate("absent.local");
3739            }
3740            resume_tx.send(()).unwrap();
3741            thread.join().unwrap();
3742            assert!(cache.is_empty());
3743        }
3744    }
3745
3746    #[test]
3747    fn exhausted_generation_suppresses_publication() {
3748        let cache = CachedSources::default();
3749        cache.cache.lock().unwrap().generation = Some(u64::MAX);
3750        cache.invalidate("absent");
3751        let source = Source::new("camera")
3752            .unwrap()
3753            .with_address(SourceAddress::new("192.0.2.1").unwrap());
3754        assert_eq!(
3755            cache
3756                .lookup("192.0.2.1", Duration::ZERO, |_| Ok(vec![source.clone()]))
3757                .unwrap(),
3758            vec![source]
3759        );
3760        assert!(cache.is_empty());
3761    }
3762    use std::ffi::CString;
3763
3764    #[test]
3765    fn defaults_include_local_sources() {
3766        for options in [FinderOptions::default(), FinderOptions::new()] {
3767            assert!(options.show_local_sources);
3768            assert!(options.groups.is_none() && options.extra_ips.is_none());
3769        }
3770        assert!(
3771            !FinderOptions::new()
3772                .show_local_sources(false)
3773                .show_local_sources
3774        );
3775    }
3776
3777    #[test]
3778    fn authority_parsing_separates_hosts_ports_and_url_components() {
3779        for (address, host, port) in [
3780            ("192.0.2.1:5960", "192.0.2.1", Some(5960)),
3781            ("2001:db8::1", "2001:db8::1", None),
3782            ("[::1]:5960", "::1", Some(5960)),
3783            (
3784                "http://camera:8080/path:123?port=456#789",
3785                "camera",
3786                Some(8080),
3787            ),
3788            ("http://camera?x=:123", "camera", None),
3789            ("http://user:pass@[::1]:8080/path", "::1", Some(8080)),
3790        ] {
3791            let source = Source::new("")
3792                .unwrap()
3793                .with_address(SourceAddress::new(address).unwrap());
3794            assert_eq!(source.host(), Some(host), "{address}");
3795            assert_eq!(source.address().unwrap().port(), port, "{address}");
3796        }
3797        assert!(parse_authority("[::1").is_none());
3798        assert!(parse_authority("camera:invalid").is_none());
3799        assert!(parse_authority("").is_none());
3800    }
3801
3802    fn source_entry(name: *const c_char, address: *const c_char) -> NDIlib_source_t {
3803        NDIlib_source_t {
3804            p_ndi_name: name,
3805            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
3806                p_url_address: address,
3807            },
3808        }
3809    }
3810
3811    #[test]
3812    fn authority_parsing_uses_the_outer_endpoint() {
3813        for (endpoint, host, port, is_url) in [
3814            ("camera-a.local", "camera-a.local", None, false),
3815            ("camera-a.local.:5960", "camera-a.local.", Some(5960), false),
3816            (
3817                "NDI+v6.4-test://user:pass@[2001:db8::1]:5960",
3818                "2001:db8::1",
3819                Some(5960),
3820                true,
3821            ),
3822            ("[2001:db8::1]:5960", "2001:db8::1", Some(5960), false),
3823            ("2001:db8::1", "2001:db8::1", None, false),
3824        ] {
3825            for delimiter in ["/path/", "?next=", "#next="] {
3826                let text = format!("{endpoint}{delimiter}https://camera-b.local:7443/live");
3827                let source = Source::new("OTHER (Feed)")
3828                    .unwrap()
3829                    .with_address(SourceAddress::new(&text).unwrap());
3830                let address = source.address().unwrap();
3831                let query = host.trim_end_matches('.');
3832                assert_eq!(address.as_str(), text);
3833                assert_eq!(address.is_url(), is_url, "{text}");
3834                assert_eq!(address.port(), port, "{text}");
3835                assert_eq!(source.host(), Some(host), "{text}");
3836                assert!(address.matches_host(query), "{text}");
3837                assert!(source.matches_host(query), "{text}");
3838                assert!(!address.matches_host("camera-b.local"), "{text}");
3839                assert!(!source.matches_host("camera-b.local"), "{text}");
3840            }
3841        }
3842    }
3843
3844    #[test]
3845    fn authority_parsing_requires_an_unsigned_decimal_port() {
3846        for (authority, host) in [
3847            ("studio.example", "studio.example"),
3848            ("192.0.2.1", "192.0.2.1"),
3849            ("[::1]", "::1"),
3850        ] {
3851            for (prefix, tail) in [
3852                ("", ""),
3853                ("ndi://user:pass@", "/video"),
3854                ("ndi://", "?video"),
3855                ("ndi://", "#video"),
3856            ] {
3857                for (suffix, port, valid) in [
3858                    ("", None, !prefix.is_empty()),
3859                    ("+5960", None, false),
3860                    ("-5960", None, false),
3861                    (" 5960", None, false),
3862                    ("5960", None, false),
3863                    ("59a0", None, false),
3864                    ("5960+", None, false),
3865                    ("65536", None, false),
3866                    ("0", Some(0), true),
3867                    ("05960", Some(5960), true),
3868                    ("65535", Some(65535), true),
3869                ] {
3870                    let text = format!("{prefix}{authority}:{suffix}{tail}");
3871                    let source = Source::new("OTHER (Camera)")
3872                        .unwrap()
3873                        .with_address(SourceAddress::new(&text).unwrap());
3874                    let address = source.address().unwrap();
3875                    assert_eq!(address.as_str(), text);
3876                    assert_eq!(source.host(), valid.then_some(host), "{text}");
3877                    assert_eq!(address.port(), port, "{text}");
3878                    assert_eq!(address.matches_host(host), valid, "{text}");
3879                    assert_eq!(source.matches_host(host), valid, "{text}");
3880                    assert!(!address.matches_host("OTHER"), "{text}");
3881                    assert!(source.matches_host("OTHER"), "{text}");
3882                }
3883            }
3884        }
3885    }
3886
3887    #[test]
3888    fn discovery_uses_valid_url_authorities_for_host_selection() {
3889        let name = c"OTHER (Camera)".as_ptr();
3890        let entries = [
3891            source_entry(name, c"ndi://studio.example:+5960/video".as_ptr()),
3892            source_entry(name, c"ndi://studio.example:/video".as_ptr()),
3893            source_entry(name, c"[::1]:+5960".as_ptr()),
3894            source_entry(name, c"ndi://[::1]:/video".as_ptr()),
3895        ];
3896        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
3897        let guard = SnapshotGuard {
3898            instance: mutex.lock(),
3899        };
3900        for (host, expected) in [
3901            ("studio.example", "ndi://studio.example:/video"),
3902            ("::1", "ndi://[::1]:/video"),
3903        ] {
3904            let query = HostQuery::checked(host).unwrap();
3905            let mut window = DiscoveryWindow::default();
3906            guard
3907                .discover(&SliceSnapshot(&entries), &mut window, Some(query))
3908                .unwrap();
3909            assert_eq!(window.sources.len(), 1);
3910            let selected = &window.sources[0];
3911            assert_eq!(selected.address().unwrap().as_str(), expected);
3912            assert_eq!(selected.host(), Some(host));
3913        }
3914    }
3915
3916    #[test]
3917    fn url_classification_requires_a_valid_initial_scheme() {
3918        for text in [
3919            "://camera.local",
3920            "1ndi://camera.local",
3921            "_ndi://camera.local",
3922            "nd_i://camera.local",
3923            "ndí://camera.local",
3924            " ndi://camera.local",
3925            "//camera.local",
3926        ] {
3927            assert!(!SourceAddress::new(text).unwrap().is_url(), "{text}");
3928            assert!(parse_authority(text).is_none(), "{text}");
3929        }
3930        assert!(SourceAddress::new("a://camera.local").unwrap().is_url());
3931    }
3932
3933    #[test]
3934    fn discovery_skips_malformed_and_unmatched_text_without_allocating() {
3935        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
3936        let guard = SnapshotGuard {
3937            instance: mutex.lock(),
3938        };
3939        let cases = [
3940            (
3941                "192.0.2.44",
3942                [
3943                    (c"STUDIO (Camera)", c"192.0.2.1:5960"),
3944                    (c"STUDIO (Camera \xff)", c"192.0.2.1:5960"),
3945                ],
3946            ),
3947            (
3948                "STUDIO_B",
3949                [
3950                    (c"STUDIO_A (Camera)", c"ndi://studio.local:5960/feed"),
3951                    (c"STUDIO_A (Camera)", c"ndi://studio.local:5960/feed\xff"),
3952                ],
3953            ),
3954        ];
3955
3956        let allocations = cases.map(|(host, source_text)| {
3957            let query = HostQuery::checked(host).unwrap();
3958            source_text.map(|(name, address)| {
3959                let entries = [source_entry(name.as_ptr(), address.as_ptr()); 128];
3960                let mut window = DiscoveryWindow::default();
3961                let (result, allocations) = crate::test_alloc::allocation_count(|| {
3962                    guard.discover(&SliceSnapshot(&entries), &mut window, Some(query))
3963                });
3964                result.unwrap();
3965                assert!(window.sources.is_empty(), "{host}");
3966                allocations
3967            })
3968        });
3969        assert_eq!(allocations, [[0, 0], [0, 0]]);
3970    }
3971
3972    #[test]
3973    fn discovery_accumulates_distinct_name_and_address_text_in_order() {
3974        let invalid = source_entry(c"STUDIO (Camera \xff)".as_ptr(), c"192.0.2.1".as_ptr());
3975        let same = source_entry(c"STUDIO (Camera �)".as_ptr(), c"192.0.2.1".as_ptr());
3976        let changed = source_entry(c"STUDIO (Camera �)".as_ptr(), c"192.0.2.2".as_ptr());
3977        let last = source_entry(c"STUDIO (Last)".as_ptr(), ptr::null());
3978        let unrelated = source_entry(c"OTHER (Feed)".as_ptr(), ptr::null());
3979        let unterminated = vec![b'x'; crate::sdk_copy::MAX_SDK_STRING_BYTES];
3980        let malformed = source_entry(unterminated.as_ptr().cast(), ptr::null());
3981        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
3982        let guard = SnapshotGuard {
3983            instance: mutex.lock(),
3984        };
3985        let mut window = DiscoveryWindow::default();
3986        let query = Some(HostQuery::checked("STUDIO").unwrap());
3987        let initial = [malformed, invalid, same, unrelated, changed, changed];
3988        let subsequent = [same, changed, last, invalid, last];
3989        guard
3990            .discover(&SliceSnapshot(&initial), &mut window, query)
3991            .unwrap();
3992        guard
3993            .discover(&SliceSnapshot(&subsequent), &mut window, query)
3994            .unwrap();
3995        assert_eq!(
3996            window
3997                .sources
3998                .iter()
3999                .map(SourceIdentity::key)
4000                .collect::<Vec<_>>(),
4001            [
4002                ("STUDIO (Camera �)", Some("192.0.2.1")),
4003                ("STUDIO (Camera �)", Some("192.0.2.2")),
4004                ("STUDIO (Last)", None),
4005            ]
4006        );
4007        let first_named = guard
4008            .first_named(&SliceSnapshot(&initial), "STUDIO (Camera �)")
4009            .unwrap()
4010            .unwrap();
4011        assert_eq!(first_named, window.sources[0]);
4012
4013        let mut matched_ip = DiscoveryWindow::default();
4014        guard
4015            .discover(
4016                &SliceSnapshot(&[invalid, same, unrelated]),
4017                &mut matched_ip,
4018                Some(HostQuery::checked("192.0.2.1").unwrap()),
4019            )
4020            .unwrap();
4021        assert_eq!(matched_ip.sources, window.sources[..1]);
4022    }
4023
4024    #[test]
4025    fn duplicate_snapshots_allocate_like_a_single_selected_descriptor() {
4026        let entry = source_entry(c"STUDIO (Camera)".as_ptr(), c"192.0.2.1".as_ptr());
4027        let control = [entry];
4028        let duplicates = vec![entry; budget::MAX_SOURCES];
4029        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
4030        let guard = SnapshotGuard {
4031            instance: mutex.lock(),
4032        };
4033        let name = "STUDIO (Camera)";
4034        let query = HostQuery::checked("STUDIO").unwrap();
4035        let first = |entries| guard.first_named(&SliceSnapshot(entries), name).unwrap();
4036        let discover = |entries, query| {
4037            let mut window = DiscoveryWindow::default();
4038            guard
4039                .discover(&SliceSnapshot(entries), &mut window, query)
4040                .unwrap();
4041            window.sources
4042        };
4043        for entries in [&control[..], &duplicates] {
4044            let (missing, missing_allocations) = crate::test_alloc::allocation_count(|| {
4045                guard
4046                    .first_named(&SliceSnapshot(entries), "missing")
4047                    .unwrap()
4048            });
4049            let (_, missing_peak) = crate::test_alloc::peak_bytes(|| {
4050                guard
4051                    .first_named(&SliceSnapshot(entries), "missing")
4052                    .unwrap()
4053            });
4054            assert_eq!((missing, missing_allocations, missing_peak), (None, 0, 0));
4055        }
4056        let (first_control, first_allocations) =
4057            crate::test_alloc::allocation_count(|| first(&control));
4058        let (first_duplicate, duplicate_allocations) =
4059            crate::test_alloc::allocation_count(|| first(&duplicates));
4060        assert_eq!(first_duplicate, first_control);
4061        assert!(first_duplicate.is_some());
4062        assert_eq!(duplicate_allocations, first_allocations);
4063        let (_, first_peak) = crate::test_alloc::peak_bytes(|| first(&control));
4064        let (_, duplicate_peak) = crate::test_alloc::peak_bytes(|| first(&duplicates));
4065        assert_eq!(duplicate_peak, first_peak);
4066        for query in [
4067            None,
4068            Some(query),
4069            Some(HostQuery::checked("192.0.2.1").unwrap()),
4070        ] {
4071            let (expected, control_allocations) =
4072                crate::test_alloc::allocation_count(|| discover(&control, query));
4073            let (actual, allocations) =
4074                crate::test_alloc::allocation_count(|| discover(&duplicates, query));
4075            assert_eq!(actual, expected);
4076            assert_eq!(actual.len(), 1);
4077            assert_eq!(allocations, control_allocations);
4078            let (_, control_peak) = crate::test_alloc::peak_bytes(|| discover(&control, query));
4079            let (_, duplicate_peak) =
4080                crate::test_alloc::peak_bytes(|| discover(&duplicates, query));
4081            assert_eq!(duplicate_peak, control_peak);
4082        }
4083    }
4084
4085    #[test]
4086    fn snapshot_limit_after_a_match_takes_priority_over_discovery_limit() {
4087        let named = source_entry(c"STUDIO (Camera)".as_ptr(), ptr::null());
4088        let unterminated = vec![b'x'; crate::sdk_copy::MAX_SDK_STRING_BYTES];
4089        let malformed = source_entry(unterminated.as_ptr().cast(), ptr::null());
4090        let mut entries = vec![named];
4091        entries.extend([malformed; 4]);
4092        let entries = SliceSnapshot(&entries);
4093        let mutex = parking_lot::Mutex::new(FindInstance(ptr::null_mut()));
4094        let guard = SnapshotGuard {
4095            instance: mutex.lock(),
4096        };
4097        let mut window = DiscoveryWindow {
4098            retained_bytes: budget::MAX_BYTES,
4099            ..Default::default()
4100        };
4101        assert!(matches!(
4102            guard.discover(&SliceSnapshot(&[named]), &mut window, None),
4103            Err(Error::ResourceLimit {
4104                resource: ResourceKind::FinderDiscoveryBytes,
4105                ..
4106            })
4107        ));
4108        assert!(matches!(
4109            guard.discover(&entries, &mut window, None),
4110            Err(Error::ResourceLimit {
4111                resource: ResourceKind::FinderSnapshotBytes,
4112                ..
4113            })
4114        ));
4115        assert!(matches!(
4116            guard.first_named(&entries, "STUDIO (Camera)"),
4117            Err(Error::ResourceLimit {
4118                resource: ResourceKind::FinderSnapshotBytes,
4119                ..
4120            })
4121        ));
4122        assert!(window.sources.is_empty());
4123    }
4124
4125    #[test]
4126    fn cache_validates_timeout_before_returning_cached_source() {
4127        let cache = CachedSources::default();
4128        cache.cache.lock().unwrap().entries.insert(
4129            HostKey::try_from(HostQuery::parse("camera").unwrap()).unwrap(),
4130            Arc::new(vec![Source::new("camera").unwrap()]),
4131        );
4132        for host in ["camera", "not_cached"] {
4133            assert!(matches!(
4134                cache.lookup(host, Duration::MAX, |_| panic!("invalid timeout")),
4135                Err(Error::InvalidInput(_))
4136            ));
4137        }
4138        // A hit is answered without reaching discovery, the only step that
4139        // uses the runtime.
4140        assert_eq!(
4141            cache
4142                .lookup("camera", Duration::ZERO, |_| panic!("cache hit"))
4143                .unwrap(),
4144            vec![Source::new("camera").unwrap()]
4145        );
4146    }
4147
4148    #[test]
4149    fn concurrent_snapshots_keep_sdk_buffers_exclusive_until_copied() {
4150        use std::sync::{
4151            atomic::{AtomicUsize, Ordering},
4152            Barrier,
4153        };
4154
4155        struct Probe<'a> {
4156            finder: &'a Finder,
4157            raw: &'a NDIlib_source_t,
4158            active: &'a AtomicUsize,
4159        }
4160        impl snapshot_sealed::Sealed for Probe<'_> {}
4161        // SAFETY: the probe borrows its stack descriptor and live C strings
4162        // through the entire serialized call and retains no native reference.
4163        unsafe impl FinderSnapshot for Probe<'_> {
4164            type Descriptor = NDIlib_source_t;
4165            type Item = Source;
4166
4167            unsafe fn fetch(
4168                &self,
4169                instance: NDIlib_find_instance_t,
4170                count: &mut u32,
4171            ) -> *const Self::Descriptor {
4172                assert_eq!(instance, self.finder.instance.0);
4173                assert_eq!(self.active.fetch_add(1, Ordering::SeqCst), 0);
4174                assert!(self.finder.sources_lock.try_lock().is_none());
4175                *count = 1;
4176                std::thread::yield_now();
4177                self.raw
4178            }
4179
4180            unsafe fn copy(
4181                &self,
4182                source: &Self::Descriptor,
4183                budget: &mut SnapshotBudget,
4184            ) -> Result<Option<Source>> {
4185                assert!(self.finder.sources_lock.try_lock().is_none());
4186                std::thread::yield_now();
4187                // SAFETY: the probe's borrowed C strings remain live.
4188                let owned = unsafe {
4189                    {
4190                        let (name, address) = source_pointers(source);
4191                        decode_source(name, address, budget, |_| true)
4192                    }
4193                };
4194                assert_eq!(self.active.fetch_sub(1, Ordering::SeqCst), 1);
4195                owned
4196            }
4197        }
4198
4199        let Some(ndi) = crate::test_support::ndi() else {
4200            return;
4201        };
4202        let finder = Finder::new(&ndi, &FinderOptions::default()).unwrap();
4203        let start = Barrier::new(8);
4204        let active_snapshot = AtomicUsize::new(0);
4205
4206        std::thread::scope(|scope| {
4207            for index in 0..8 {
4208                let finder = &finder;
4209                let start = &start;
4210                let active_snapshot = &active_snapshot;
4211                scope.spawn(move || {
4212                    let name = CString::new(format!("Camera {index}")).unwrap();
4213                    let address = CString::new(format!("192.0.2.{index}:5960")).unwrap();
4214                    let raw = NDIlib_source_t {
4215                        p_ndi_name: name.as_ptr(),
4216                        __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4217                            p_ip_address: address.as_ptr(),
4218                        },
4219                    };
4220                    start.wait();
4221                    let sources = finder.snapshot(&Probe {
4222                        finder,
4223                        raw: &raw,
4224                        active: active_snapshot,
4225                    }).unwrap();
4226                    drop(name);
4227                    drop(address);
4228                    assert_eq!(sources[0].name(), format!("Camera {index}"));
4229                    assert!(matches!(sources[0].address(), Some(address) if address.as_str() == format!("192.0.2.{index}:5960")));
4230                });
4231            }
4232        });
4233        assert_eq!(active_snapshot.load(Ordering::SeqCst), 0);
4234
4235        // A panic while copying must not disable later snapshots. The mutex
4236        // protects a lifetime window, not mutable Rust state needing repair.
4237        std::thread::scope(|scope| {
4238            assert!(scope
4239                .spawn(|| {
4240                    let _guard = finder.sources_lock.lock();
4241                    panic!("interrupted snapshot");
4242                })
4243                .join()
4244                .is_err());
4245        });
4246        assert!(finder.current_sources().is_ok());
4247    }
4248
4249    #[test]
4250    fn test_try_from_raw_null_pointer() {
4251        // A null descriptor is a failure of the function that returned it.
4252        let result = unsafe { source_from_raw(ptr::null(), c"NDIlib_send_get_source_name") };
4253        assert!(matches!(
4254            result,
4255            Err(Error::NativeOperationFailed {
4256                operation}) if operation.name() == c"NDIlib_send_get_source_name"
4257        ));
4258    }
4259
4260    #[test]
4261    fn source_copy_policies_decode_the_same_descriptors() {
4262        enum Expected {
4263            Source(Source),
4264            Missing,
4265            Malformed,
4266            InvalidUtf8(std::str::Utf8Error),
4267        }
4268
4269        let name = c"Camera".as_ptr();
4270        let ip = c"192.0.2.1:5960".as_ptr();
4271        let url = c"ndi://camera.local:5960".as_ptr();
4272        let empty = c"".as_ptr();
4273        let unterminated = vec![b'x'; crate::sdk_copy::MAX_SDK_STRING_BYTES];
4274        let malformed = unterminated.as_ptr().cast();
4275        let cases = [
4276            (
4277                "name and IP",
4278                name,
4279                ip,
4280                Expected::Source(
4281                    Source::new("Camera")
4282                        .unwrap()
4283                        .with_address(SourceAddress::new("192.0.2.1:5960").unwrap()),
4284                ),
4285            ),
4286            (
4287                "name and URL",
4288                name,
4289                url,
4290                Expected::Source(
4291                    Source::new("Camera")
4292                        .unwrap()
4293                        .with_address(SourceAddress::new("ndi://camera.local:5960").unwrap()),
4294                ),
4295            ),
4296            (
4297                "address only",
4298                ptr::null(),
4299                ip,
4300                Expected::Source(
4301                    Source::new("")
4302                        .unwrap()
4303                        .with_address(SourceAddress::new("192.0.2.1:5960").unwrap()),
4304                ),
4305            ),
4306            (
4307                "neither pointer",
4308                ptr::null(),
4309                ptr::null(),
4310                Expected::Missing,
4311            ),
4312            (
4313                "invalid name",
4314                c"Cam\xff".as_ptr(),
4315                ip,
4316                Expected::InvalidUtf8(c"Cam\xff".to_str().unwrap_err()),
4317            ),
4318            (
4319                "invalid address",
4320                name,
4321                c"ndi://camera.local/\xff".as_ptr(),
4322                Expected::InvalidUtf8(c"ndi://camera.local/\xff".to_str().unwrap_err()),
4323            ),
4324            (
4325                "literal replacement characters",
4326                c"Cam�".as_ptr(),
4327                c"ndi://camera.local/�".as_ptr(),
4328                Expected::Source(
4329                    Source::new("Cam�")
4330                        .unwrap()
4331                        .with_address(SourceAddress::new("ndi://camera.local/�").unwrap()),
4332                ),
4333            ),
4334            ("unterminated name", malformed, ip, Expected::Malformed),
4335            (
4336                "name only",
4337                name,
4338                ptr::null(),
4339                Expected::Source(Source::new("Camera").unwrap()),
4340            ),
4341            (
4342                "empty name",
4343                empty,
4344                ptr::null(),
4345                Expected::Source(Source::new("").unwrap()),
4346            ),
4347            (
4348                "empty address only",
4349                ptr::null(),
4350                empty,
4351                Expected::Source(
4352                    Source::new("")
4353                        .unwrap()
4354                        .with_address(SourceAddress::new("").unwrap()),
4355                ),
4356            ),
4357            (
4358                "empty address",
4359                name,
4360                empty,
4361                Expected::Source(
4362                    Source::new("Camera")
4363                        .unwrap()
4364                        .with_address(SourceAddress::new("").unwrap()),
4365                ),
4366            ),
4367            ("unterminated address", name, malformed, Expected::Malformed),
4368        ];
4369
4370        for (label, name, address, expected) in cases {
4371            let raw = NDIlib_source_t {
4372                p_ndi_name: name,
4373                __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4374                    p_url_address: address,
4375                },
4376            };
4377            // SAFETY: pointers are null, live C string literals, or the live
4378            // buffer readable for the complete SDK string bound. Both copies
4379            // finish before any backing storage is dropped.
4380            let mut accepted_budget = SnapshotBudget::new();
4381            let mut rejected_budget = SnapshotBudget::new();
4382            let ((snapshot, accepted_allocations), (rejected, rejected_allocations), single) = unsafe {
4383                (
4384                    crate::test_alloc::allocation_count(|| {
4385                        decode_source(name, address, &mut accepted_budget, |_| true)
4386                    }),
4387                    crate::test_alloc::allocation_count(|| {
4388                        decode_source(name, address, &mut rejected_budget, |_| false)
4389                    }),
4390                    source_from_raw(&raw, c"test source query"),
4391                )
4392            };
4393            assert!(rejected.unwrap().is_none(), "{label}");
4394            assert_eq!(rejected_allocations, 0, "{label}");
4395            assert_eq!(accepted_budget.spent(), rejected_budget.spent(), "{label}");
4396            let strings = usize::from(!address.is_null()) + 1;
4397            assert_eq!(
4398                accepted_allocations,
4399                if snapshot.as_ref().is_ok_and(Option::is_some) {
4400                    2 * strings
4401                } else {
4402                    0
4403                },
4404                "{label}"
4405            );
4406            match expected {
4407                Expected::Source(expected) => {
4408                    let source = snapshot.unwrap().unwrap();
4409                    assert_eq!(source, expected, "{label}");
4410                    assert_eq!(single.unwrap(), expected, "{label}");
4411                    let retained = crate::source_retention::RetainedSource::new(&source);
4412                    let (retained_name, retained_address) = source_pointers(retained.descriptor());
4413                    // SAFETY: the raw and retained C strings above remain live
4414                    // through the comparisons. A retained name is always present.
4415                    unsafe {
4416                        let original_name = if name.is_null() {
4417                            c""
4418                        } else {
4419                            CStr::from_ptr(name)
4420                        };
4421                        assert_eq!(CStr::from_ptr(retained_name), original_name, "{label}");
4422                        if address.is_null() {
4423                            assert!(retained_address.is_null(), "{label}");
4424                        } else {
4425                            assert_eq!(
4426                                CStr::from_ptr(retained_address),
4427                                CStr::from_ptr(address),
4428                                "{label}"
4429                            );
4430                        }
4431                    }
4432                    #[cfg(feature = "file-io")]
4433                    {
4434                        let spec = crate::file::SourceSpec::try_from(&source);
4435                        match source.address() {
4436                            Some(address) if !address.as_str().is_empty() => {
4437                                let spec = spec.unwrap();
4438                                assert_eq!(spec.url(), Some(address.as_str()), "{label}");
4439                                assert_eq!(spec.name(), None, "{label}");
4440                            }
4441                            None if !source.name().is_empty() => {
4442                                let spec = spec.unwrap();
4443                                assert_eq!(spec.url(), None, "{label}");
4444                                assert_eq!(spec.name(), Some(source.name()), "{label}");
4445                            }
4446                            _ => assert!(spec.is_err(), "{label}"),
4447                        }
4448                    }
4449                }
4450                Expected::Missing => {
4451                    assert_eq!(snapshot.unwrap(), None, "{label}");
4452                    assert!(
4453                        matches!(
4454                            &single,
4455                            Err(Error::NativeOperationFailed {
4456                                operation}) if operation.name() == c"test source query"
4457                        ),
4458                        "{label}: {single:?}"
4459                    );
4460                }
4461                Expected::InvalidUtf8(expected) => {
4462                    assert!(snapshot.unwrap().is_none(), "{label}");
4463                    assert!(
4464                        matches!(single, Err(Error::InvalidUtf8(error)) if error == expected),
4465                        "{label}: {single:?}"
4466                    );
4467                }
4468                Expected::Malformed => {
4469                    assert_eq!(snapshot.unwrap(), None, "{label}");
4470                    assert!(
4471                        matches!(&single, Err(Error::UnexpectedSdkResult(_))),
4472                        "{label}: {single:?}"
4473                    );
4474                }
4475            }
4476        }
4477    }
4478
4479    #[test]
4480    fn source_descriptor_and_snapshot_allocations_name_their_storage() {
4481        let name = CString::new(vec![b'x'; 1 << 20]).unwrap();
4482        let raw = NDIlib_source_t {
4483            p_ndi_name: name.as_ptr(),
4484            ..Default::default()
4485        };
4486        let single = crate::test_alloc::fail_allocations_at_least(1 << 20, || {
4487            // SAFETY: the descriptor and its complete terminated name stay live.
4488            unsafe { source_from_raw(&raw, c"test source query") }
4489        });
4490        assert!(matches!(
4491            single,
4492            Err(Error::AllocationFailed(crate::AllocationFailure {
4493                kind: crate::AllocationKind::SourceDescriptor,
4494                bytes: Some(1_048_577),
4495            }))
4496        ));
4497        let snapshot = crate::test_alloc::fail_allocations_at_least(1 << 20, || {
4498            // SAFETY: the descriptor and its complete terminated name stay live.
4499            unsafe {
4500                decode_source(
4501                    name.as_ptr(),
4502                    ptr::null(),
4503                    &mut SnapshotBudget::new(),
4504                    |_| true,
4505                )
4506            }
4507        });
4508        assert!(matches!(
4509            snapshot,
4510            Err(Error::AllocationFailed(crate::AllocationFailure {
4511                kind: crate::AllocationKind::DiscoveryResults,
4512                bytes: Some(1_048_577),
4513            }))
4514        ));
4515    }
4516
4517    #[cfg(not(miri))] // Requires re-executing this test binary.
4518    #[test]
4519    fn source_descriptor_shared_owner_uses_the_global_allocation_failure_handler() {
4520        const CHILD: &str = "GRAFTON_NDI_TEST_SOURCE_OWNER_ALLOCATION_CHILD";
4521        if std::env::var_os(CHILD).is_some() {
4522            let raw = NDIlib_source_t {
4523                p_ndi_name: c"x".as_ptr(),
4524                ..Default::default()
4525            };
4526            // The name and its terminator need two bytes. The Arc owner
4527            // requires a larger allocation on every supported target.
4528            let result = crate::test_alloc::fail_allocations_at_least(3, || {
4529                // SAFETY: the raw descriptor and its terminated C literal stay live.
4530                unsafe { source_from_raw(&raw, c"test source query") }
4531            });
4532            panic!("shared-owner allocation unexpectedly returned {result:?}");
4533        }
4534        let output = crate::test_support::TestChild::new(
4535            "finder::tests::source_descriptor_shared_owner_uses_the_global_allocation_failure_handler",
4536        )
4537        .env(CHILD, "1")
4538        .run_expecting(false);
4539        let stderr = String::from_utf8_lossy(&output.stderr);
4540        assert!(
4541            stderr.contains("memory allocation of") && stderr.contains("bytes failed"),
4542            "{stderr}"
4543        );
4544    }
4545
4546    #[test]
4547    fn source_strings_are_bounded_by_the_sdk_string_limit() {
4548        use crate::sdk_copy::MAX_SDK_STRING_BYTES;
4549        // The longest name that fits: its terminator is the last byte the
4550        // scan may read. One byte longer, the terminator lies past the limit.
4551        let mut longest = vec![b'x'; MAX_SDK_STRING_BYTES];
4552        longest[MAX_SDK_STRING_BYTES - 1] = 0;
4553        let mut too_long = vec![b'x'; MAX_SDK_STRING_BYTES + 1];
4554        too_long[MAX_SDK_STRING_BYTES] = 0;
4555        let address = c"192.0.2.1:5960";
4556        let descriptor = |name: &[u8], address: *const std::ffi::c_char| NDIlib_source_t {
4557            p_ndi_name: name.as_ptr().cast(),
4558            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4559                p_ip_address: address,
4560            },
4561        };
4562
4563        // SAFETY: every descriptor points to live NUL-terminated strings.
4564        unsafe {
4565            let fits = source_from_raw(&descriptor(&longest, ptr::null()), c"test").unwrap();
4566            assert_eq!(fits.name().len(), MAX_SDK_STRING_BYTES - 1);
4567            for raw in [
4568                descriptor(&too_long, address.as_ptr()),
4569                descriptor(c"Camera".to_bytes_with_nul(), too_long.as_ptr().cast()),
4570            ] {
4571                let Err(Error::UnexpectedSdkResult(reason)) =
4572                    source_from_raw(&raw, c"NDIlib_send_get_source_name")
4573                else {
4574                    panic!("a string longer than the limit must be refused");
4575                };
4576                assert_eq!(
4577                    reason,
4578                    crate::SdkResultDefect::UnterminatedText {
4579                        operation: sys::table::for_test((), c"NDIlib_send_get_source_name")
4580                            .function()
4581                    }
4582                );
4583            }
4584        }
4585    }
4586
4587    struct SliceSnapshot<'a>(&'a [NDIlib_source_t]);
4588    impl snapshot_sealed::Sealed for SliceSnapshot<'_> {}
4589    // SAFETY: this fixture is created only below, where its array and all
4590    // strings stay live until the guard completes the bounded copy.
4591    unsafe impl FinderSnapshot for SliceSnapshot<'_> {
4592        type Descriptor = NDIlib_source_t;
4593        type Item = Source;
4594
4595        unsafe fn fetch(
4596            &self,
4597            _: NDIlib_find_instance_t,
4598            count: &mut u32,
4599        ) -> *const Self::Descriptor {
4600            *count = self.0.len() as u32;
4601            self.0.as_ptr()
4602        }
4603
4604        unsafe fn copy(
4605            &self,
4606            source: &Self::Descriptor,
4607            budget: &mut SnapshotBudget,
4608        ) -> Result<Option<Source>> {
4609            // SAFETY: all fixture strings remain live through this call.
4610            unsafe { copy_source(source, budget, |_| true) }
4611        }
4612    }
4613
4614    #[test]
4615    fn a_snapshot_leaves_out_only_the_malformed_entries() {
4616        let Some(ndi) = crate::test_support::ndi() else {
4617            return;
4618        };
4619        let finder = Finder::new(&ndi, &FinderOptions::default()).unwrap();
4620        let mut too_long = vec![b'x'; crate::sdk_copy::MAX_SDK_STRING_BYTES + 1];
4621        *too_long.last_mut().unwrap() = 0;
4622        let named = |name: *const std::ffi::c_char| NDIlib_source_t {
4623            p_ndi_name: name,
4624            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4625                p_ip_address: ptr::null(),
4626            },
4627        };
4628        let snapshot = [
4629            named(c"First".as_ptr()),
4630            named(too_long.as_ptr().cast()),
4631            named(ptr::null()),
4632            named(c"Last".as_ptr()),
4633        ];
4634        let sources = finder.snapshot(&SliceSnapshot(&snapshot));
4635        let sources = sources.unwrap();
4636        let names: Vec<_> = sources.iter().map(Source::name).collect();
4637        assert_eq!(names, ["First", "Last"]);
4638    }
4639
4640    #[test]
4641    fn test_try_from_raw_null_name() {
4642        // Create a source with null p_ndi_name
4643        let source = NDIlib_source_t {
4644            p_ndi_name: ptr::null(),
4645            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4646                p_ip_address: ptr::null(),
4647            },
4648        };
4649
4650        let result = unsafe { source_from_raw(&source, c"NDIlib_find_get_current_sources") };
4651        assert!(matches!(
4652            result,
4653            Err(Error::NativeOperationFailed {
4654                operation}) if operation.name() == c"NDIlib_find_get_current_sources"
4655        ));
4656    }
4657
4658    #[test]
4659    fn test_try_from_raw_valid_source_with_ip() {
4660        // Create valid C strings
4661        let name = CString::new("Test Source").unwrap();
4662        let ip = CString::new("192.168.1.100:5960").unwrap();
4663
4664        let source = NDIlib_source_t {
4665            p_ndi_name: name.as_ptr(),
4666            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4667                p_ip_address: ip.as_ptr(),
4668            },
4669        };
4670
4671        let result = unsafe { source_from_raw(&source, c"test") };
4672        assert!(result.is_ok());
4673
4674        let source = result.unwrap();
4675        assert_eq!(source.name(), "Test Source");
4676        let address = source.address().expect("an address");
4677        assert_eq!(address.as_str(), "192.168.1.100:5960");
4678        assert!(!address.is_url());
4679    }
4680
4681    #[test]
4682    fn test_try_from_raw_valid_source_with_url() {
4683        // Create valid C strings
4684        let name = CString::new("HX Source").unwrap();
4685        let url = CString::new("http://camera.local:8080/ndi").unwrap();
4686
4687        let source = NDIlib_source_t {
4688            p_ndi_name: name.as_ptr(),
4689            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4690                p_url_address: url.as_ptr(),
4691            },
4692        };
4693
4694        let result = unsafe { source_from_raw(&source, c"test") };
4695        assert!(result.is_ok());
4696
4697        let source = result.unwrap();
4698        assert_eq!(source.name(), "HX Source");
4699        let address = source.address().expect("an address");
4700        assert_eq!(address.as_str(), "http://camera.local:8080/ndi");
4701        assert!(address.is_url());
4702    }
4703
4704    #[test]
4705    fn test_try_from_raw_valid_source_no_address() {
4706        // Create valid C string for name, null for address
4707        let name = CString::new("Source No Addr").unwrap();
4708
4709        let source = NDIlib_source_t {
4710            p_ndi_name: name.as_ptr(),
4711            __bindgen_anon_1: NDIlib_source_t__bindgen_ty_1 {
4712                p_ip_address: ptr::null(),
4713            },
4714        };
4715
4716        let result = unsafe { source_from_raw(&source, c"test") };
4717        assert!(result.is_ok());
4718
4719        let source = result.unwrap();
4720        assert_eq!(source.name(), "Source No Addr");
4721        assert!(source.address().is_none());
4722    }
4723
4724    #[test]
4725    fn test_source_cache_poison_recovery() {
4726        use std::sync::Arc;
4727        use std::thread;
4728
4729        let cache = Arc::new(CachedSources::default());
4730        let cache_clone = Arc::clone(&cache);
4731
4732        // Spawn a thread that acquires the lock and panics
4733        let handle = thread::spawn(move || {
4734            let _lock = cache_clone
4735                .cache
4736                .lock()
4737                .unwrap_or_else(|poisoned| poisoned.into_inner());
4738            panic!("intentional panic while holding lock");
4739        });
4740
4741        // Wait for the thread to panic
4742        let _ = handle.join();
4743
4744        // Verify all cache methods still work after poison
4745        assert!(cache.is_empty(), "is_empty should work after poison");
4746        assert_eq!(cache.len(), 0, "len should work after poison");
4747        cache.invalidate("test");
4748        cache.clear();
4749    }
4750}