1mod 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#[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 #[must_use]
73 pub fn clear_groups(mut self) -> Self {
74 self.groups = None;
75 self
76 }
77
78 #[must_use]
80 pub fn clear_extra_ips(mut self) -> Self {
81 self.extra_ips = None;
82 self
83 }
84
85 #[cfg(feature = "advanced")]
87 #[must_use]
88 pub fn clear_config(mut self) -> Self {
89 self.config = None;
90 self
91 }
92
93 #[must_use]
95 pub fn configured_show_local_sources(&self) -> bool {
96 self.show_local_sources
97 }
98
99 #[must_use]
101 pub fn configured_groups(&self) -> Option<&[String]> {
102 self.groups.as_deref()
103 }
104
105 #[must_use]
107 pub fn configured_extra_ips(&self) -> Option<&[String]> {
108 self.extra_ips.as_deref()
109 }
110
111 #[cfg(feature = "advanced")]
113 #[must_use]
114 pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
115 self.config.as_ref()
116 }
117
118 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 #[must_use]
132 pub fn show_local_sources(mut self, show: bool) -> Self {
133 self.show_local_sources = show;
134 self
135 }
136
137 #[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 #[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 #[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
172unsafe impl Send for FindInstance {}
181unsafe impl Sync for FindInstance {}
183
184pub struct Finder {
212 instance: FindInstance,
213 sources_lock: parking_lot::Mutex<FindInstance>,
215 changes: ChangeFeed,
216 _groups: Option<CString>, _extra_ips: Option<CString>, #[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
232impl std::panic::RefUnwindSafe for Finder {}
236
237pub(crate) mod snapshot_sealed {
238 pub trait Sealed {}
239}
240
241pub(crate) unsafe trait FinderSnapshot: snapshot_sealed::Sealed {
251 type Descriptor;
252 type Item;
253
254 unsafe fn fetch(
257 &self,
258 instance: NDIlib_find_instance_t,
259 count: &mut u32,
260 ) -> *const Self::Descriptor;
261
262 unsafe fn copy(
265 &self,
266 source: &Self::Descriptor,
267 budget: &mut SnapshotBudget,
268 ) -> Result<Option<Self::Item>>;
269}
270
271struct SourceSnapshot<'a>(&'a sys::Core);
273
274impl snapshot_sealed::Sealed for SourceSnapshot<'_> {}
275
276unsafe 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 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 unsafe { copy_source(source, budget, |_| true) }
298 }
299}
300
301struct SnapshotGuard<'finder> {
304 instance: parking_lot::MutexGuard<'finder, FindInstance>,
305}
306
307trait 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 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 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 if let Some(source) = unsafe {
402 copy_source(entry, budget, |source| {
403 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 unsafe {
425 let descriptors = snapshot.fetch(self.instance.0, &mut count);
426 budget::scan_snapshot::<_, S::Item>(descriptors, count, visit)
427 }
428 }
429}
430
431pub(crate) struct SourceCursor {
434 observed: Cell<u64>,
435}
436
437pub(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 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 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
507pub 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 #[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 #[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
627pub(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 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 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 unsafe { crate::sdk_copy::sdk_text(self.0.map(|()| pointer)) }.map(Some)
669 }
670}
671
672pub(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 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 let Some(address) = (unsafe { text.view(address) })? else {
704 return Ok(None);
705 };
706 Some(address)
707 };
708 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
733fn source_pointers(source: &NDIlib_source_t) -> (*const c_char, *const c_char) {
736 let address = unsafe { source.__bindgen_anon_1.p_url_address };
738 (source.p_ndi_name, address)
739}
740
741unsafe 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 unsafe { decode_source(name, address, budget, select) }
754}
755
756impl Finder {
757 #[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 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 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 let _ = finder.changes.generation();
836 Ok(finder)
837 }
838
839 #[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 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 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 #[cfg(feature = "advanced")]
915 pub(crate) fn runtime(&self) -> &Ndi {
916 self.sdk.ndi()
917 }
918
919 #[must_use]
925 pub fn watch(&self) -> SourceWatch<'_> {
926 SourceWatch {
927 finder: self,
928 cursor: SourceCursor::new(self.changes.generation()),
929 }
930 }
931
932 pub(crate) fn wait_for_sources_since(
934 &self,
935 generation: u64,
936 deadline: Deadline,
937 stop: impl Stop,
938 ) -> bool {
939 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 #[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 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 watch.wait_until(deadline, stop);
1049 }
1050 }
1051
1052 #[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 #[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 #[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 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 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 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#[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 let mut bytes = Vec::with_capacity(self.0.len() + 1);
1331 bytes.extend_from_slice(self.0.as_bytes());
1332 unsafe { CString::from_vec_unchecked(bytes) }
1335 }
1336}
1337
1338#[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
1351pub(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#[derive(Default)]
1372struct DiscoveryWindow {
1373 sources: Vec<Source>,
1374 seen: HashSet<SeenSource>,
1375 retained_bytes: usize,
1376}
1377
1378impl DiscoveryWindow {
1379 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 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 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
1435fn 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
1447fn parse_port(text: &str, allow_empty: bool) -> Option<Option<u16>> {
1449 match text.as_bytes().first() {
1450 None => allow_empty.then_some(None),
1451 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#[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#[derive(Debug, PartialEq, Eq)]
1607enum HostKey {
1608 Ip(IpAddr),
1609 Name(Box<str>),
1610}
1611
1612pub(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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1697pub struct SourceAddress(SourceText);
1698
1699#[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#[derive(Clone, PartialEq, Eq, Hash)]
1716pub(crate) struct SourceText(Arc<CString>);
1717
1718impl SourceText {
1719 pub(crate) const STORAGE_OVERHEAD: usize =
1721 2 * std::mem::size_of::<usize>() + std::mem::size_of::<CString>() + 1;
1722
1723 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 Ok(unsafe { Self::from_nul_free_string(text) })
1736 }
1737
1738 unsafe fn from_nul_free_string(text: String) -> Self {
1743 let mut bytes = text.into_bytes();
1744 bytes.push(0);
1745 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 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 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 Some(Self(unsafe { SourceText::from_nul_free_string(endpoint) }))
1799 }
1800
1801 pub fn new(text: impl Into<String>) -> Result<Self> {
1807 SourceText::new(text.into()).map(Self)
1808 }
1809
1810 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 pub fn is_url(&self) -> bool {
1825 strip_url_scheme(self.as_str()).is_some()
1826 }
1827
1828 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 pub fn port(&self) -> Option<u16> {
1883 self.authority().and_then(|authority| authority.port)
1884 }
1885
1886 fn authority(&self) -> Option<Authority<'_>> {
1889 parse_authority(self.as_str())
1890 }
1891}
1892
1893#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1914pub struct Source {
1915 name: SourceText,
1916 address: Option<SourceAddress>,
1917}
1918
1919#[repr(transparent)]
1922#[derive(Clone, PartialEq, Eq)]
1923struct SeenSource(Source);
1924
1925const_assert!(std::mem::size_of::<SeenSource>() == std::mem::size_of::<Source>());
1926
1927trait 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 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 #[must_use]
1999 pub fn with_address(self, address: SourceAddress) -> Self {
2000 Self {
2001 address: Some(address),
2002 ..self
2003 }
2004 }
2005
2006 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 pub fn address(&self) -> Option<&SourceAddress> {
2018 self.address.as_ref()
2019 }
2020
2021 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 pub fn host(&self) -> Option<&str> {
2092 self.address
2093 .as_ref()?
2094 .authority()
2095 .map(|authority| authority.host)
2096 }
2097
2098 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 let ndi_source = unsafe { &*source_ptr };
2130 let (name, address) = source_pointers(ndi_source);
2131 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
2160pub 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
2244pub(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 pub fn new(finder: Finder) -> Self {
2288 Self {
2289 finder,
2290 entries: CachedSources::default(),
2291 }
2292 }
2293
2294 #[must_use]
2299 pub fn finder(&self) -> &Finder {
2300 &self.finder
2301 }
2302
2303 #[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 pub fn invalidate(&self, host: &str) {
2371 self.entries.invalidate(host);
2372 }
2373
2374 pub fn clear(&self) {
2376 self.entries.clear();
2377 }
2378
2379 pub fn len(&self) -> usize {
2381 self.entries.len()
2382 }
2383
2384 pub fn is_empty(&self) -> bool {
2386 self.entries.is_empty()
2387 }
2388}
2389
2390fn 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 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 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 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 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 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 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 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 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 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 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 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; 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 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 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 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 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 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 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 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 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); 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 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 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 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 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 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 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 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 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 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 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))] #[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 let result = crate::test_alloc::fail_allocations_at_least(3, || {
4529 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 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 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 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 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 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 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 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 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 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 let _ = handle.join();
4743
4744 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}