1#[cfg(test)]
36use crate::RuntimeFeature;
37#[cfg(test)]
38use std::sync::atomic::AtomicBool;
39
40#[cfg(feature = "advanced")]
41use crate::advanced::{AvSyncAttached, PacketAttached};
42
43use std::{
44 ffi::{CStr, CString},
45 marker::PhantomData,
46 os::raw::c_char,
47 ptr,
48 sync::{
49 atomic::{AtomicUsize, Ordering},
50 Arc,
51 },
52 time::{Duration, Instant},
53};
54
55use parking_lot::{Mutex, MutexGuard, RwLock};
56
57use crate::{
58 capture::{
59 capture_any, AllSlots, AudioKind, CaptureKind, CaptureStrategy, Delivered, Media,
60 MetadataKind, NoSlots, Notification, Only, SlotSet, VideoKind,
61 },
62 connection_metadata::ConnectionMetadata,
63 finder::Source,
64 frames::MetadataPartsExt,
65 source_retention::RetainedSource,
66 sys::{self, bindings::*},
67 timeout::{self, Deadline, NeverStop, Stop, POLL_INTERVAL},
68 AudioFrame, AudioFrameRef, Error, MetadataFrame, MetadataFrameRef, MetadataSource, Ndi, Result,
69 VideoFrame, VideoFrameRef,
70};
71
72pub(crate) mod attached;
73pub(crate) mod control;
74mod pending;
75
76use control::ControlPermit;
77
78pub(crate) use pending::PendingEvents;
79
80struct RecvStringGuard<'a> {
82 core: &'a ReceiverCore,
83 string: sys::table::Called<*const c_char>,
84 strings: &'a sys::ReceiverStrings,
85}
86impl RecvStringGuard<'_> {
87 fn bytes(&self) -> Result<Option<&[u8]>> {
93 if self.string.value().is_null() {
94 return Ok(None);
95 }
96 let bytes = unsafe { crate::sdk_copy::sdk_text(self.string) }?;
99 Ok(Some(bytes.to_bytes()))
100 }
101
102 fn copy(&self) -> Result<Option<String>> {
104 self.bytes()?
105 .map(|bytes| {
106 std::str::from_utf8(bytes)
107 .map(str::to_owned)
108 .map_err(Error::InvalidUtf8)
109 })
110 .transpose()
111 }
112
113 fn copy_lossy(&self) -> Result<Option<String>> {
117 Ok(self.bytes()?.map(crate::sdk_copy::copy_lossy))
118 }
119}
120impl Drop for RecvStringGuard<'_> {
121 fn drop(&mut self) {
122 if !self.string.value().is_null() {
123 unsafe {
127 self.strings
128 .NDIlib_recv_free_string(self.core.instance.0, self.string.into_value())
129 };
130 }
131 }
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
136pub struct ReceiveDelay(i32);
137
138impl ReceiveDelay {
139 pub const ZERO: Self = Self(0);
141
142 pub const MAX: Self = Self(2000);
144
145 pub fn new(delay: Duration) -> Result<Self> {
152 timeout::sdk_millis(delay)
153 .and_then(|millis| Self::checked(i64::from(millis)))
154 .ok_or(Error::InvalidInput(
155 crate::InputDefect::ReceiveDelayTooLong {
156 requested: delay.into(),
157 },
158 ))
159 }
160
161 pub const fn duration(self) -> Duration {
163 Duration::from_millis(self.0 as u64)
164 }
165
166 pub(crate) const fn to_sdk(self) -> i32 {
167 self.0
168 }
169
170 pub(crate) fn from_sdk(millis: i32) -> Result<Self> {
171 Self::checked(i64::from(millis)).ok_or(Error::UnexpectedSdkResult(
172 crate::SdkResultDefect::InvalidReceiveDelay { millis },
173 ))
174 }
175
176 fn checked(millis: i64) -> Option<Self> {
177 (0..=i64::from(Self::MAX.0))
178 .contains(&millis)
179 .then_some(Self(millis as i32))
180 }
181}
182
183enum ReceiveDelayStream {
184 Video,
185 Audio,
186}
187
188#[derive(Debug)]
191pub(crate) struct ReceiverReport<T> {
192 sequence: u64,
193 pub(crate) value: T,
194}
195
196impl<T> ReceiverReport<T> {
197 pub(crate) fn unsequenced(value: T) -> Self {
198 Self { sequence: 0, value }
199 }
200
201 pub(crate) fn map<U>(self, convert: impl FnOnce(T) -> U) -> ReceiverReport<U> {
202 ReceiverReport {
203 sequence: self.sequence,
204 value: convert(self.value),
205 }
206 }
207
208 pub(crate) fn into_value(self) -> T {
209 self.value
210 }
211}
212
213struct LatestReport<T> {
216 sequence: u64,
217 pending: Option<ReceiverReport<T>>,
218}
219
220impl<T> Default for LatestReport<T> {
221 fn default() -> Self {
222 Self {
223 sequence: 0,
224 pending: None,
225 }
226 }
227}
228
229impl<T> LatestReport<T> {
230 fn advance(&mut self) -> u64 {
231 self.sequence = self.sequence.wrapping_add(1);
232 self.pending = None;
233 self.sequence
234 }
235
236 fn report(&mut self, value: T) -> ReceiverReport<T> {
237 ReceiverReport {
238 sequence: self.advance(),
239 value,
240 }
241 }
242
243 fn publish(&mut self, value: T) {
244 let report = self.report(value);
245 self.pending = Some(report);
246 }
247
248 #[cfg(any(test, feature = "tokio", feature = "smol"))]
249 fn replay(&mut self, report: ReceiverReport<T>) {
250 if report.sequence == self.sequence {
251 self.pending = Some(report);
252 }
253 }
254}
255
256#[cfg(test)]
257mod latest_report_tests {
258 use super::LatestReport;
259
260 #[test]
261 fn publishing_coalesces_and_taking_consumes_the_latest_value() {
262 let mut latest = LatestReport::default();
263 latest.publish("first");
264 latest.publish("second");
265 assert_eq!(latest.pending.take().unwrap().value, "second");
266 assert!(latest.pending.take().is_none());
267 }
268
269 #[test]
270 fn the_current_report_can_be_replayed_after_it_is_taken() {
271 let mut latest = LatestReport::default();
272 latest.publish("current");
273 let abandoned = latest.pending.take().unwrap();
274 latest.replay(abandoned);
275 assert_eq!(latest.pending.take().unwrap().value, "current");
276 assert!(latest.pending.take().is_none());
277 }
278
279 #[test]
280 fn an_older_report_cannot_follow_a_newer_report() {
281 let mut latest = LatestReport::default();
282 let older = latest.report("first");
283 let current = latest.report("second");
284 latest.replay(older);
285 assert!(latest.pending.is_none());
286 latest.replay(current);
287 assert_eq!(latest.pending.take().unwrap().value, "second");
288 }
289
290 #[test]
291 fn only_the_newest_abandoned_value_is_replayed() {
292 let mut latest = LatestReport::default();
293 let older = latest.report("first");
294 let current = latest.report("second");
295 latest.replay(current);
296 latest.replay(older);
297 assert_eq!(latest.pending.take().unwrap().value, "second");
298 assert!(latest.pending.is_none());
299 }
300
301 #[test]
302 fn taking_a_newer_publication_does_not_readmit_an_older_report() {
303 let mut latest = LatestReport::default();
304 latest.publish(1);
305 let old = latest.pending.take().unwrap();
306 latest.publish(2);
307 latest.replay(old);
308 let current = latest.pending.take().unwrap();
309 assert_eq!(current.value, 2);
310 latest.publish(3);
311 assert_eq!(latest.pending.take().unwrap().value, 3);
312 latest.replay(current);
313 assert!(latest.pending.is_none());
314 }
315
316 #[test]
317 fn replay_order_survives_sequence_wrap() {
318 let mut latest = LatestReport {
319 sequence: u64::MAX - 1,
320 pending: None,
321 };
322 let before_wrap = latest.report("before wrap");
323 assert_eq!(before_wrap.sequence, u64::MAX);
324 latest.replay(before_wrap);
325 let abandoned = latest.pending.take().unwrap();
326 let wrapped = latest.report("wrapped");
327 assert_eq!(wrapped.sequence, 0);
328 latest.replay(abandoned);
329 assert!(latest.pending.is_none());
330 latest.replay(wrapped);
331 let abandoned = latest.pending.take().unwrap();
332 assert_eq!(abandoned.value, "wrapped");
333 latest.publish("after wrap");
334 latest.replay(abandoned);
335 assert_eq!(latest.pending.take().unwrap().value, "after wrap");
336 }
337}
338
339#[derive(Default)]
343struct PendingStatus(AtomicUsize);
344
345impl PendingStatus {
346 const PENDING: usize = 1;
347 const REPORTED: usize = 2;
348
349 fn publish(&self) {
350 let mut observed = self.0.load(Ordering::Acquire);
351 loop {
352 match self.0.compare_exchange_weak(
353 observed,
354 (observed.wrapping_add(4) & !(Self::PENDING | Self::REPORTED)) | Self::PENDING,
355 Ordering::AcqRel,
356 Ordering::Acquire,
357 ) {
358 Ok(_) => return,
359 Err(current) => observed = current,
360 }
361 }
362 }
363
364 #[cfg(test)]
365 fn is_pending(&self) -> bool {
366 self.0.load(Ordering::Acquire) & Self::PENDING != 0
367 }
368
369 #[cfg(test)]
370 fn take_with<T>(&self, snapshot: impl FnOnce() -> Result<T>) -> Result<Option<T>> {
371 self.take_or_else_with(snapshot, || None)
372 }
373
374 fn take_or_else_with<T>(
375 &self,
376 snapshot: impl FnOnce() -> Result<T>,
377 other: impl FnOnce() -> Option<T>,
378 ) -> Result<Option<T>> {
379 let observed = self.0.load(Ordering::Acquire);
380 if observed & Self::PENDING == 0 {
381 return Ok(None);
382 }
383 let status = match snapshot() {
384 Ok(status) => status,
385 Err(error) => {
386 if let Some(other) = other() {
389 return Ok(Some(other));
390 }
391 if observed & Self::REPORTED != 0 {
392 return Ok(None);
393 }
394 return match self.0.compare_exchange(
395 observed,
396 observed | Self::REPORTED,
397 Ordering::AcqRel,
398 Ordering::Acquire,
399 ) {
400 Ok(_) => Err(error),
401 Err(_) => Ok(None),
402 };
403 }
404 };
405 Ok(self
408 .0
409 .compare_exchange(
410 observed,
411 observed & !(Self::PENDING | Self::REPORTED),
412 Ordering::AcqRel,
413 Ordering::Acquire,
414 )
415 .ok()
416 .map(|_| status))
417 }
418}
419
420const EARLY_RETURN_PAUSE: Duration = Duration::from_millis(10);
423
424const IMMEDIATE_NOTIFICATION_RETRIES: usize = 8;
427
428enum Retry<T> {
429 Item(T),
430 Progress,
431 Idle,
432}
433
434impl<T> From<Option<T>> for Retry<T> {
435 fn from(value: Option<T>) -> Self {
436 value.map_or(Self::Idle, Self::Item)
437 }
438}
439
440fn capture_within<T, R: Into<Retry<T>>>(
454 deadline: Deadline,
455 stop: impl Stop,
456 attempt: impl FnMut(Attempt) -> Result<R>,
457) -> Result<Option<T>> {
458 capture_within_clock_with_stop(deadline, stop, attempt, Instant::now, std::thread::sleep)
459}
460
461#[cfg(test)]
473fn capture_within_clock<T, R: Into<Retry<T>>>(
474 deadline: Deadline,
475 attempt: impl FnMut(Attempt) -> Result<R>,
476 now: impl FnMut() -> Instant,
477 sleep: impl FnMut(Duration),
478) -> Result<Option<T>> {
479 capture_within_clock_with_stop(deadline, NeverStop, attempt, now, sleep)
480}
481
482fn capture_within_clock_with_stop<T, R: Into<Retry<T>>>(
483 deadline: Deadline,
484 stop: impl Stop,
485 mut attempt: impl FnMut(Attempt) -> Result<R>,
486 mut now: impl FnMut() -> Instant,
487 mut sleep: impl FnMut(Duration),
488) -> Result<Option<T>> {
489 let mut notifications = 0;
490 loop {
491 let this = Attempt(deadline.within_at(now(), POLL_INTERVAL));
492 let progress = match attempt(this)?.into() {
493 Retry::Item(value) => return Ok(Some(value)),
494 Retry::Progress => true,
495 Retry::Idle => false,
496 };
497 let mut returned = now();
498 if deadline.remaining_at(returned).is_zero() {
499 return Ok(None);
500 }
501 if returned < this.0.end() && (!progress || notifications >= IMMEDIATE_NOTIFICATION_RETRIES)
502 {
503 sleep(EARLY_RETURN_PAUSE.min(deadline.remaining_at(returned).duration()));
505 returned = now();
506 notifications = 0;
507 } else if progress && returned < this.0.end() {
508 notifications += 1;
509 } else {
510 notifications = 0;
511 }
512 if deadline.remaining_at(returned).is_zero() || stop.is_stopped() {
513 return Ok(None);
514 }
515 }
516}
517
518#[derive(Clone, Copy, Debug)]
526pub(crate) struct Attempt(Deadline);
527
528fn validate_ptz_value(name: &'static str, value: f32, min: f32, max: f32) -> Result<()> {
529 if value.is_finite() && (min..=max).contains(&value) {
530 Ok(())
531 } else {
532 Err(Error::InvalidInput(crate::InputDefect::PtzValue {
533 detail: crate::CompactDiagnostic::new(crate::PtzDefect {
534 name,
535 minimum: min,
536 maximum: max,
537 }),
538 }))
539 }
540}
541
542fn validate_ptz_preset(preset: u8) -> Result<i32> {
543 if preset <= 99 {
544 Ok(i32::from(preset))
545 } else {
546 Err(Error::InvalidInput(crate::InputDefect::PtzPreset))
547 }
548}
549
550macro_rules! ptz_command {
553 ($ptz:expr, $func:ident $(, $arg:expr)*) => {{
554 $ptz.core.lock_mutating_control()?.$func($ptz.core.sdk() $(, $arg)*)
555 }};
556}
557
558#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
573#[non_exhaustive]
574pub enum ReceiverColorFormat {
575 #[default]
577 BgrxBgra,
578 UyvyBgra,
580 RgbxRgba,
582 UyvyRgba,
584 Fastest,
587 Best,
591 Best444,
594}
595
596impl ReceiverColorFormat {
597 const fn to_sdk(self) -> NDIlib_recv_color_format_e {
599 match self {
600 Self::BgrxBgra => NDIlib_recv_color_format_e_NDIlib_recv_color_format_BGRX_BGRA,
601 Self::UyvyBgra => NDIlib_recv_color_format_e_NDIlib_recv_color_format_UYVY_BGRA,
602 Self::RgbxRgba => NDIlib_recv_color_format_e_NDIlib_recv_color_format_RGBX_RGBA,
603 Self::UyvyRgba => NDIlib_recv_color_format_e_NDIlib_recv_color_format_UYVY_RGBA,
604 Self::Fastest => NDIlib_recv_color_format_e_NDIlib_recv_color_format_fastest,
605 Self::Best => NDIlib_recv_color_format_e_NDIlib_recv_color_format_best,
606 Self::Best444 => NDIlib_recv_color_format_e_NDIlib_recv_color_format_best_444,
607 }
608 }
609}
610
611#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
626#[non_exhaustive]
627pub enum ReceiverBandwidth {
628 MetadataOnly,
630 AudioOnly,
632 Lowest,
634 #[default]
636 Highest,
637 VideoOnlyLowest,
639 VideoOnlyHighest,
641}
642
643impl ReceiverBandwidth {
644 const fn to_sdk(self) -> NDIlib_recv_bandwidth_e {
646 match self {
647 Self::MetadataOnly => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_metadata_only,
648 Self::AudioOnly => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_audio_only,
649 Self::Lowest => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_lowest,
650 Self::Highest => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest,
651 Self::VideoOnlyLowest => {
652 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_video_only_lowest
653 }
654 Self::VideoOnlyHighest => {
655 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_video_only_highest
656 }
657 }
658 }
659}
660
661#[derive(Debug, Clone, PartialEq, Eq, Hash)]
685pub struct ReceiverOptions {
686 source: Option<Source>,
687 color_format: ReceiverColorFormat,
688 bandwidth: ReceiverBandwidth,
689 allow_video_fields: bool,
690 name: Option<String>,
691 #[cfg(feature = "advanced")]
692 pub(crate) config: Option<crate::advanced::AdvancedConfig>,
693 #[cfg(feature = "advanced")]
697 passthrough: Option<NDIlib_recv_color_format_e>,
698}
699
700pub(crate) struct ReceiveSettings<'a> {
702 raw: NDIlib_recv_create_v3_t,
703 _storage: PhantomData<(&'a RetainedSource, Option<&'a CStr>)>,
704}
705
706impl ReceiveSettings<'_> {
707 pub(crate) fn raw(&self) -> &NDIlib_recv_create_v3_t {
708 &self.raw
709 }
710}
711
712impl ReceiverOptions {
713 #[must_use]
716 pub fn source(mut self, source: Source) -> Self {
717 self.source = has_receiver_target(&source).then_some(source);
718 self
719 }
720
721 #[must_use]
723 pub fn clear_source(mut self) -> Self {
724 self.source = None;
725 self
726 }
727
728 #[must_use]
730 pub fn clear_name(mut self) -> Self {
731 self.name = None;
732 self
733 }
734
735 #[cfg(feature = "advanced")]
737 #[must_use]
738 pub fn clear_config(mut self) -> Self {
739 self.config = None;
740 self
741 }
742
743 #[must_use]
745 pub fn configured_source(&self) -> Option<&Source> {
746 self.source.as_ref()
747 }
748
749 #[must_use]
752 pub fn configured_color_format(&self) -> ReceiverColorFormat {
753 self.color_format
754 }
755
756 #[must_use]
758 pub fn configured_bandwidth(&self) -> ReceiverBandwidth {
759 self.bandwidth
760 }
761
762 #[must_use]
764 pub fn configured_allow_video_fields(&self) -> bool {
765 self.allow_video_fields
766 }
767
768 #[must_use]
770 pub fn configured_name(&self) -> Option<&str> {
771 self.name.as_deref()
772 }
773
774 #[cfg(feature = "advanced")]
777 #[must_use]
778 pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
779 self.config.as_ref()
780 }
781
782 pub fn new(source: Source) -> Self {
786 Self::disconnected().source(source)
787 }
788
789 pub fn disconnected() -> Self {
794 Self {
795 source: None,
796 color_format: ReceiverColorFormat::BgrxBgra,
797 bandwidth: ReceiverBandwidth::Highest,
798 allow_video_fields: true,
799 name: None,
800 #[cfg(feature = "advanced")]
801 config: None,
802 #[cfg(feature = "advanced")]
803 passthrough: None,
804 }
805 }
806
807 pub fn snapshot_preset(source: Source) -> Self {
849 Self::new(source)
850 .color_format(ReceiverColorFormat::RgbxRgba)
851 .bandwidth(ReceiverBandwidth::Lowest)
852 .allow_video_fields(false)
853 }
854
855 pub fn high_quality_preset(source: Source) -> Self {
893 Self::new(source)
894 .color_format(ReceiverColorFormat::RgbxRgba)
895 .bandwidth(ReceiverBandwidth::Highest)
896 .allow_video_fields(true)
897 }
898
899 pub fn monitoring_preset(source: Source) -> Self {
930 Self::new(source)
931 .bandwidth(ReceiverBandwidth::MetadataOnly)
932 .allow_video_fields(false)
933 }
934
935 #[must_use]
937 pub fn color_format(mut self, color_format: ReceiverColorFormat) -> Self {
938 self.color_format = color_format;
939 self
940 }
941
942 #[must_use]
945 pub fn bandwidth(mut self, bandwidth: ReceiverBandwidth) -> Self {
946 self.bandwidth = bandwidth;
947 self
948 }
949
950 #[must_use]
953 pub fn allow_video_fields(mut self, allow: bool) -> Self {
954 self.allow_video_fields = allow;
955 self
956 }
957
958 #[must_use]
960 pub fn name(mut self, name: impl Into<String>) -> Self {
961 self.name = Some(name.into());
962 self
963 }
964
965 #[cfg(feature = "advanced")]
971 #[must_use]
972 pub fn config(mut self, config: crate::advanced::AdvancedConfig) -> Self {
973 self.config = Some(config);
974 self
975 }
976
977 #[cfg(feature = "advanced")]
982 pub(crate) fn with_passthrough(mut self, format: NDIlib_recv_color_format_e) -> Self {
983 self.passthrough = Some(format);
984 self
985 }
986
987 fn sdk_color_format(&self) -> NDIlib_recv_color_format_e {
989 #[cfg(feature = "advanced")]
990 if let Some(format) = self.passthrough {
991 return format;
992 }
993 self.color_format.to_sdk()
994 }
995
996 pub(crate) fn validate_runtime<'a>(
999 &'a self,
1000 evidence: sys::Evidence<'a>,
1001 ) -> Result<ValidatedReceiveOptions<'a>> {
1002 let best444 = (self.sdk_color_format() == ReceiverColorFormat::Best444.to_sdk())
1003 .then(|| <sys::ReceiveBest444 as sys::Table>::within(evidence))
1004 .transpose()?;
1005 let video_only = matches!(
1006 self.bandwidth,
1007 ReceiverBandwidth::VideoOnlyLowest | ReceiverBandwidth::VideoOnlyHighest
1008 )
1009 .then(|| <sys::ReceiveVideoOnly as sys::Table>::within(evidence))
1010 .transpose()?;
1011 Ok(ValidatedReceiveOptions {
1012 options: self,
1013 _best444: best444,
1014 _video_only: video_only,
1015 })
1016 }
1017}
1018
1019fn has_receiver_target(source: &Source) -> bool {
1021 !source.name().is_empty()
1022 || source
1023 .address()
1024 .is_some_and(|address| !address.as_str().is_empty())
1025}
1026
1027pub(crate) fn prepare_receiver_target(source: &Source) -> Option<RetainedSource> {
1028 has_receiver_target(source).then(|| RetainedSource::new(source))
1029}
1030
1031pub(crate) struct ValidatedReceiveOptions<'a> {
1032 options: &'a ReceiverOptions,
1033 _best444: Option<&'a sys::ReceiveBest444>,
1034 _video_only: Option<&'a sys::ReceiveVideoOnly>,
1035}
1036
1037impl ValidatedReceiveOptions<'_> {
1038 pub(crate) fn settings<'a>(
1039 &self,
1040 target: Option<&'a RetainedSource>,
1041 name: Option<&'a CStr>,
1042 ) -> ReceiveSettings<'a> {
1043 ReceiveSettings {
1044 raw: NDIlib_recv_create_v3_t {
1045 source_to_connect_to: target
1046 .map(|target| *target.descriptor())
1047 .unwrap_or_default(),
1048 color_format: self.options.sdk_color_format(),
1049 bandwidth: self.options.bandwidth.to_sdk(),
1050 allow_video_fields: self.options.allow_video_fields,
1051 p_ndi_recv_name: name.map_or(ptr::null(), CStr::as_ptr),
1052 },
1053 _storage: PhantomData,
1054 }
1055 }
1056}
1057
1058mod mode_sealed {
1059 pub trait Sealed {}
1060 #[allow(private_bounds)]
1061 pub trait MetadataSealed: super::Permits<crate::capture::MetadataKind> {}
1062 #[allow(private_bounds)]
1063 pub trait EventSealed: super::Permits<crate::capture::NoSlots> {}
1064 #[allow(private_bounds)]
1065 pub trait AudioSealed: super::Permits<crate::capture::AudioKind> {}
1066 #[allow(private_bounds)]
1067 pub trait VideoSealed: super::Permits<crate::capture::VideoKind> {}
1068}
1069
1070pub trait ReceiverMode: mode_sealed::Sealed + Send + Sync {}
1080
1081pub trait MetadataMode: ReceiverMode + mode_sealed::MetadataSealed {}
1087
1088pub trait EventMode: ReceiverMode + mode_sealed::EventSealed {}
1095
1096pub trait AudioMode: MetadataMode + mode_sealed::AudioSealed {}
1104
1105pub trait VideoMode: ReceiverMode + mode_sealed::VideoSealed {}
1112
1113pub(crate) trait Permits<K>: ReceiverMode {}
1117
1118impl<K: CaptureKind> Permits<K> for RawCapture {}
1121impl Permits<AllSlots> for RawCapture {}
1122impl Permits<NoSlots> for RawCapture {}
1123impl Permits<MetadataKind> for FrameSyncAttached {}
1124#[cfg(feature = "advanced")]
1125impl Permits<AllSlots> for PacketAttached {}
1126#[cfg(feature = "advanced")]
1127impl Permits<VideoKind> for AvSyncAttached {}
1128#[cfg(feature = "advanced")]
1129impl Permits<MetadataKind> for AvSyncAttached {}
1130
1131pub(crate) trait CreatableMode: ReceiverMode {}
1133impl CreatableMode for RawCapture {}
1134#[cfg(feature = "advanced")]
1135impl CreatableMode for PacketAttached {}
1136
1137pub(crate) trait SynchronizerMode: ReceiverMode {}
1139impl SynchronizerMode for FrameSyncAttached {}
1140#[cfg(feature = "advanced")]
1141impl SynchronizerMode for AvSyncAttached {}
1142
1143#[derive(Debug)]
1145pub enum RawCapture {}
1146#[derive(Debug)]
1170pub enum FrameSyncAttached {}
1171impl mode_sealed::Sealed for RawCapture {}
1172impl mode_sealed::Sealed for FrameSyncAttached {}
1173impl mode_sealed::MetadataSealed for RawCapture {}
1174impl mode_sealed::EventSealed for RawCapture {}
1175impl mode_sealed::MetadataSealed for FrameSyncAttached {}
1176impl mode_sealed::AudioSealed for RawCapture {}
1177impl mode_sealed::VideoSealed for RawCapture {}
1178impl ReceiverMode for RawCapture {}
1179impl ReceiverMode for FrameSyncAttached {}
1180impl MetadataMode for RawCapture {}
1181impl EventMode for RawCapture {}
1182impl MetadataMode for FrameSyncAttached {}
1183impl AudioMode for RawCapture {}
1184impl VideoMode for RawCapture {}
1185#[cfg(feature = "advanced")]
1186impl mode_sealed::Sealed for PacketAttached {}
1187#[cfg(feature = "advanced")]
1188impl ReceiverMode for PacketAttached {}
1189#[cfg(feature = "advanced")]
1190impl mode_sealed::Sealed for AvSyncAttached {}
1191#[cfg(feature = "advanced")]
1192impl mode_sealed::MetadataSealed for AvSyncAttached {}
1193#[cfg(feature = "advanced")]
1194impl mode_sealed::VideoSealed for AvSyncAttached {}
1195#[cfg(feature = "advanced")]
1196impl ReceiverMode for AvSyncAttached {}
1197#[cfg(feature = "advanced")]
1198impl MetadataMode for AvSyncAttached {}
1199#[cfg(feature = "advanced")]
1200impl VideoMode for AvSyncAttached {}
1201
1202pub struct Receiver<M: ReceiverMode = RawCapture> {
1230 pub(crate) core: Arc<ReceiverCore>,
1231 _mode: PhantomData<M>,
1232}
1233
1234impl<M: ReceiverMode> std::fmt::Debug for Receiver<M> {
1235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1236 ReceiverIdentity::new::<M>(&self.core).fmt(f)
1237 }
1238}
1239
1240pub(crate) struct ReceiverIdentity<'a> {
1242 core: &'a ReceiverCore,
1243 mode: &'static str,
1244}
1245
1246impl<'a> ReceiverIdentity<'a> {
1247 pub(crate) fn new<M: ReceiverMode>(core: &'a ReceiverCore) -> Self {
1248 Self {
1249 core,
1250 mode: std::any::type_name::<M>(),
1251 }
1252 }
1253
1254 fn name(core: &ReceiverCore) -> Option<std::borrow::Cow<'_, str>> {
1255 core._name.as_ref().map(|name| name.to_string_lossy())
1256 }
1257}
1258
1259impl std::fmt::Debug for ReceiverIdentity<'_> {
1260 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1261 f.debug_struct("Receiver")
1262 .field("name", &Self::name(self.core))
1263 .field("mode", &self.mode)
1264 .finish_non_exhaustive()
1265 }
1266}
1267
1268struct ChangePermit;
1270
1271struct ConnectionChange<'a> {
1273 core: &'a ReceiverCore,
1274 _exclusive: MutexGuard<'a, ChangePermit>,
1275}
1276
1277impl ConnectionChange<'_> {
1278 fn instance(&self) -> NDIlib_recv_instance_t {
1279 self.core.instance.0
1280 }
1281}
1282
1283impl Drop for ConnectionChange<'_> {
1284 fn drop(&mut self) {
1285 if self.core.guard_local_connection_changes {
1286 self.finish_control_change();
1287 }
1288 }
1289}
1290
1291enum ConnectionRequest {
1292 Connect(RetainedSource),
1293 Reconnect,
1294 Disconnect,
1295}
1296
1297impl ReceiverCore {
1298 fn request(&self, request: ConnectionRequest) {
1299 let exclusive = self.change_guard.lock();
1300 let remember_target = matches!(request, ConnectionRequest::Connect(_));
1301 let target = match request {
1302 ConnectionRequest::Connect(next) => Some(next),
1303 ConnectionRequest::Reconnect => {
1304 let Some(last) = self.target.read().clone() else {
1307 return;
1308 };
1309 Some(last)
1310 }
1311 ConnectionRequest::Disconnect => None,
1312 };
1313 let connection = self.begin_change(exclusive);
1314 let call = |source| {
1315 unsafe {
1318 self.sdk()
1319 .NDIlib_recv_connect(connection.instance(), source)
1320 };
1321 };
1322 match &target {
1323 Some(target) => target.reissue(call),
1324 None => call(ptr::null()),
1325 }
1326 if remember_target {
1327 *self.target.write() = target;
1330 }
1331 }
1332}
1333
1334#[cfg(feature = "advanced")]
1337pub(crate) struct Exclusive<'a> {
1338 core: &'a ReceiverCore,
1339}
1340
1341#[cfg(feature = "advanced")]
1342impl Exclusive<'_> {
1343 #[cfg(any(
1344 test,
1345 ndi_has_advanced_receiver_bandwidth_control,
1346 ndi_has_advanced_receiver_stream_control
1347 ))]
1348 pub(crate) fn instance(&self) -> NDIlib_recv_instance_t {
1349 self.core.instance.0
1350 }
1351
1352 pub(crate) fn ndi(&self) -> &Ndi {
1353 self.core.ndi()
1354 }
1355}
1356
1357#[cfg(feature = "advanced")]
1362pub(crate) struct AllocatorOwner(
1363 #[cfg_attr(
1364 all(not(test), not(ndi_has_advanced_receive_allocators)),
1365 expect(
1366 dead_code,
1367 reason = "allocator authority is retained even without native declarations"
1368 )
1369 )]
1370 Arc<ReceiverCore>,
1371);
1372
1373#[cfg(feature = "advanced")]
1374impl AllocatorOwner {
1375 #[cfg(any(test, ndi_has_advanced_receive_allocators))]
1376 pub(crate) fn access(&self) -> AllocatorAccess<'_> {
1377 AllocatorAccess { core: &self.0 }
1378 }
1379}
1380
1381#[cfg(all(feature = "advanced", any(test, ndi_has_advanced_receive_allocators)))]
1386pub(crate) struct AllocatorAccess<'a> {
1387 core: &'a ReceiverCore,
1388}
1389
1390#[cfg(all(feature = "advanced", any(test, ndi_has_advanced_receive_allocators)))]
1391impl AllocatorAccess<'_> {
1392 pub(crate) fn instance(&self) -> NDIlib_recv_instance_t {
1393 self.core.instance.0
1394 }
1395}
1396
1397#[cfg(feature = "advanced")]
1398impl<M: ReceiverMode> Receiver<M> {
1399 pub(crate) fn exclusive(&mut self) -> Exclusive<'_> {
1400 Exclusive { core: &self.core }
1401 }
1402
1403 pub(crate) fn allocator_owner(&mut self) -> AllocatorOwner {
1404 AllocatorOwner(Arc::clone(&self.core))
1405 }
1406}
1407
1408pub(crate) struct AdvertiserMembership<'a>(&'a ReceiverCore);
1415
1416impl AdvertiserMembership<'_> {
1417 pub(crate) fn instance(&self) -> NDIlib_recv_instance_t {
1418 self.0.instance.0
1419 }
1420}
1421
1422struct SourceQueryPermit;
1424
1425struct SourceQuery<'a> {
1427 instance: RecvInstance,
1428 _query: MutexGuard<'a, SourceQueryPermit>,
1429}
1430
1431impl SourceQuery<'_> {
1432 fn instance(&self) -> NDIlib_recv_instance_t {
1433 self.instance.0
1434 }
1435}
1436
1437#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1439pub(crate) struct RecvInstance(NDIlib_recv_instance_t);
1440
1441unsafe impl Send for RecvInstance {}
1542unsafe impl Sync for RecvInstance {}
1544
1545pub(crate) struct ReceiverCore {
1546 instance: RecvInstance,
1547 pub(crate) sdk: crate::runtime::Bound<sys::Core>,
1548 change_guard: Mutex<ChangePermit>,
1551 control_guard: Mutex<ControlPermit>,
1553 guard_local_connection_changes: bool,
1557 target: RwLock<Option<RetainedSource>>,
1561 pending: PendingEvents,
1562 source_query_guard: Mutex<SourceQueryPermit>,
1565 source_name: Mutex<LatestReport<SourceNameChange>>,
1566 _name: Option<CString>,
1567 #[cfg(feature = "advanced")]
1568 _config: crate::advanced::RetainedConfig,
1569}
1570
1571impl Receiver {
1572 #[doc(alias = "NDIlib_recv_capture_v3")]
1601 pub fn capture_any_ref(&self, timeout: Duration) -> Result<Option<ReceiverItemRef<'_>>> {
1602 self.capture_any_ref_until(Deadline::after(timeout)?, NeverStop)
1603 }
1604
1605 #[doc(alias = "NDIlib_recv_capture_v3")]
1619 pub fn capture_any(&self, timeout: Duration) -> Result<Option<ReceiverItem>> {
1620 self.capture_any_until(Deadline::after(timeout)?)
1621 }
1622
1623 #[doc(alias = "NDIlib_recv_create_v3")]
1633 pub fn new(ndi: &Ndi, options: &ReceiverOptions) -> Result<Self> {
1634 #[cfg(feature = "advanced")]
1635 {
1636 <Self as crate::advanced::Configurable>::create_from_options(ndi, options)
1637 }
1638 #[cfg(not(feature = "advanced"))]
1639 {
1640 Self::create_plain(ndi, options)
1641 }
1642 }
1643}
1644
1645#[allow(private_bounds)]
1646impl<M: CreatableMode> Receiver<M> {
1647 pub(crate) fn create_plain(ndi: &Ndi, options: &ReceiverOptions) -> Result<Self> {
1648 unsafe {
1651 Self::create(ndi, options, |core, raw| {
1652 crate::runtime::NativeCreation::plain(core.named().NDIlib_recv_create_v3(raw))
1653 })
1654 }
1655 }
1656 pub(crate) unsafe fn create(
1666 ndi: &Ndi,
1667 options: &ReceiverOptions,
1668 create: impl FnOnce(
1669 &sys::Core,
1670 &NDIlib_recv_create_v3_t,
1671 ) -> crate::runtime::NativeCreation<NDIlib_recv_instance_t>,
1672 ) -> Result<Self> {
1673 let validated = options.validate_runtime(ndi.evidence())?;
1674 let target = options.configured_source().map(RetainedSource::new);
1675 let name = options.name.as_deref().map(CString::new).transpose()?;
1676 let settings = validated.settings(target.as_ref(), name.as_deref());
1677 let sdk = ndi.bind_core();
1678 let created = create(&sdk, settings.raw());
1681 let instance = created.call.created()?.as_ptr();
1682 Ok(Self {
1683 core: Arc::new(ReceiverCore {
1684 instance: RecvInstance(instance),
1685 sdk,
1686 change_guard: Mutex::new(ChangePermit),
1687 control_guard: Mutex::new(ControlPermit::default()),
1688 guard_local_connection_changes: !ndi
1689 .capabilities()
1690 .has_native_receiver_connection_exclusion(),
1691 target: RwLock::new(target),
1692 pending: PendingEvents::default(),
1693 source_query_guard: Mutex::new(SourceQueryPermit),
1694 source_name: Mutex::new(LatestReport::default()),
1695 _name: name,
1696 #[cfg(feature = "advanced")]
1697 _config: created.config,
1698 }),
1699 _mode: PhantomData,
1700 })
1701 }
1702}
1703
1704impl Receiver<RawCapture> {
1705 #[cfg(all(test, feature = "advanced"))]
1707 pub(crate) fn into_packet_for_test(self) -> Receiver<PacketAttached> {
1708 Receiver {
1709 core: self.core,
1710 _mode: PhantomData,
1711 }
1712 }
1713}
1714
1715macro_rules! receiver_capture_methods {
1716 ($(($mode:ident, $kind:ident, $owned:ident, $borrowed:ident,
1717 $capture:ident, $capture_ref:ident, $capture_with:ident, $label:literal)),* $(,)?) => {
1718 $(
1719 impl<M: $mode> Receiver<M> {
1720 #[doc = concat!("Wait up to `timeout` for ", $label, " and copy it into an owned frame.")]
1721 #[doc(alias = "NDIlib_recv_capture_v3")]
1734 pub fn $capture(&self, timeout: Duration) -> Result<Option<$owned>> {
1735 Ok(self.$capture_ref(timeout)?.as_ref().map($borrowed::to_owned))
1736 }
1737
1738 #[doc = concat!("Wait up to `timeout` for ", $label, " and borrow its native buffer.")]
1739 #[doc(alias = "NDIlib_recv_capture_v3")]
1750 pub fn $capture_ref(&self, timeout: Duration) -> Result<Option<$borrowed<'_>>> {
1751 self.core.capture_ref_until::<$kind>(Deadline::after(timeout)?, NeverStop)
1752 }
1753 }
1754 )*
1755 };
1756}
1757crate::capture::capture_method_kinds!(receiver_capture_methods);
1758
1759impl<M: ReceiverMode> Receiver<M> {
1760 #[cfg(any(feature = "tokio", feature = "smol", ndi_test_capture_permissions))]
1762 pub(crate) fn capture_ref_until<K: CaptureKind>(
1763 &self,
1764 deadline: Deadline,
1765 stop: impl Stop,
1766 ) -> Result<Option<K::Ref<'_>>>
1767 where
1768 M: Permits<K>,
1769 {
1770 self.core.capture_ref_until::<K>(deadline, stop)
1771 }
1772
1773 pub(crate) fn capture_any_until_with<'rx, S: SlotSet, T>(
1775 &'rx self,
1776 deadline: Deadline,
1777 stop: impl Stop,
1778 mut event: impl FnMut(ReceiverEvent) -> T,
1779 convert: impl FnMut(S::Media<'rx>) -> Result<T>,
1780 ) -> Result<Option<T>>
1781 where
1782 M: Permits<S>,
1783 {
1784 self.core.capture_any_until_with::<S, T>(
1785 deadline,
1786 stop,
1787 |report| event(report.value),
1788 convert,
1789 )
1790 }
1791
1792 #[cfg(any(feature = "tokio", feature = "smol"))]
1793 pub(crate) fn capture_any_report_until<S: SlotSet, T>(
1794 &self,
1795 deadline: Deadline,
1796 stop: impl Stop,
1797 event: impl FnMut(ReceiverReport<ReceiverEvent>) -> T,
1798 convert: impl FnMut(S::Media<'_>) -> Result<T>,
1799 ) -> Result<Option<T>>
1800 where
1801 M: Permits<S>,
1802 {
1803 self.core
1804 .capture_any_until_with::<S, T>(deadline, stop, event, convert)
1805 }
1806
1807 pub(crate) fn capture_any_ref_until(
1808 &self,
1809 deadline: Deadline,
1810 stop: impl Stop,
1811 ) -> Result<Option<ReceiverItemRef<'_>>>
1812 where
1813 M: Permits<AllSlots>,
1814 {
1815 self.capture_any_until_with::<AllSlots, _>(
1816 deadline,
1817 stop,
1818 ReceiverItemRef::Event,
1819 ReceiverCore::combined_result,
1820 )
1821 }
1822
1823 fn capture_any_until(&self, deadline: Deadline) -> Result<Option<ReceiverItem>>
1824 where
1825 M: Permits<AllSlots>,
1826 {
1827 Ok(self
1828 .capture_any_ref_until(deadline, NeverStop)?
1829 .as_ref()
1830 .map(ReceiverItemRef::to_owned))
1831 }
1832
1833 pub(crate) fn next_event_until(
1834 &self,
1835 deadline: Deadline,
1836 stop: impl Stop,
1837 ) -> Result<Option<ReceiverEvent>>
1838 where
1839 M: Permits<NoSlots>,
1840 {
1841 self.capture_any_until_with::<NoSlots, _>(
1842 deadline,
1843 stop,
1844 |event| event,
1845 |media| match media {},
1846 )
1847 }
1848
1849 #[doc(alias = "NDIlib_recv_set_video_delay")]
1860 pub fn set_video_delay(&self, delay: ReceiveDelay) -> Result<SettingChange> {
1861 self.core.set_delay(ReceiveDelayStream::Video, delay)
1862 }
1863
1864 #[doc(alias = "NDIlib_recv_get_video_delay")]
1872 pub fn video_delay(&self) -> Result<ReceiveDelay> {
1873 self.core.delay(ReceiveDelayStream::Video)
1874 }
1875
1876 #[doc(alias = "NDIlib_recv_set_audio_delay")]
1885 pub fn set_audio_delay(&self, delay: ReceiveDelay) -> Result<SettingChange> {
1886 self.core.set_delay(ReceiveDelayStream::Audio, delay)
1887 }
1888
1889 #[doc(alias = "NDIlib_recv_get_audio_delay")]
1895 pub fn audio_delay(&self) -> Result<ReceiveDelay> {
1896 self.core.delay(ReceiveDelayStream::Audio)
1897 }
1898
1899 #[doc(alias = "NDIlib_recv_add_connection_metadata")]
1918 pub fn add_connection_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S) -> Result<()> {
1919 let table = self.core.connection_metadata()?;
1920 self.core
1921 .lock_mutating_control()?
1922 .add_metadata(table, metadata);
1923 Ok(())
1924 }
1925
1926 #[doc(alias = "NDIlib_recv_clear_connection_metadata")]
1933 pub fn clear_connection_metadata(&self) -> Result<()> {
1934 let table = self.core.connection_metadata()?;
1935 self.core.lock_control().clear_metadata(table);
1936 Ok(())
1937 }
1938
1939 #[doc(alias = "NDIlib_recv_get_web_control")]
1949 pub fn web_control_url(&self) -> Result<Option<String>> {
1950 let (web_control, strings) = self
1952 .core
1953 .ndi()
1954 .table::<(sys::ReceiverWebControl, sys::ReceiverStrings)>()?;
1955 let connection = self.core.lock_control();
1956 let guard = RecvStringGuard {
1957 core: &self.core,
1958 string: connection.web_control(web_control),
1959 strings,
1960 };
1961 guard.copy()
1962 }
1963
1964 #[doc(alias = "NDIlib_recv_get_source_name")]
1981 pub fn wait_for_source_name_change(
1982 &self,
1983 timeout: Duration,
1984 ) -> Result<Option<SourceNameChange>> {
1985 self.core
1986 .wait_for_source_name_change_until(Deadline::after(timeout)?, NeverStop)
1987 }
1988
1989 #[doc(alias = "NDIlib_recv_connect")]
2000 pub fn connect_to(&self, source: &Source) {
2001 self.connect_target(prepare_receiver_target(source));
2002 }
2003
2004 pub(crate) fn connect_target(&self, target: Option<RetainedSource>) {
2006 self.core
2007 .request(target.map_or(ConnectionRequest::Disconnect, ConnectionRequest::Connect));
2008 }
2009
2010 #[doc(alias = "NDIlib_recv_connect")]
2015 pub fn disconnect(&self) {
2016 self.core.request(ConnectionRequest::Disconnect);
2017 }
2018
2019 #[doc(alias = "NDIlib_recv_set_tally")]
2026 pub fn set_tally(&self, tally: Tally) {
2027 self.core.set_tally(tally);
2028 }
2029
2030 #[doc(alias = "NDIlib_recv_send_metadata")]
2041 pub fn send_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S) -> Result<()> {
2042 self.core
2043 .lock_mutating_control()?
2044 .send_metadata(self.core.sdk(), metadata)
2045 }
2046
2047 #[must_use = "the Ptz handle does nothing until a command is called"]
2067 pub fn ptz(&self) -> Ptz<'_> {
2068 Ptz { core: &self.core }
2069 }
2070
2071 #[doc(alias = "NDIlib_recv_get_no_connections")]
2096 pub fn is_connected(&self) -> bool {
2097 self.core.connections().is_ok_and(|count| count > 0)
2098 }
2099
2100 #[doc(alias = "NDIlib_recv_connect")]
2135 pub fn reconnect(&self) {
2136 self.core.request(ConnectionRequest::Reconnect);
2137 }
2138
2139 pub fn connection_target(&self) -> Option<Source> {
2163 self.core
2164 .target
2165 .read()
2166 .as_ref()
2167 .map(|target| target.current().clone())
2168 }
2169
2170 #[doc(alias = "NDIlib_recv_get_no_connections")]
2206 #[doc(alias = "NDIlib_recv_get_performance")]
2207 #[doc(alias = "NDIlib_recv_get_queue")]
2208 pub fn connection_stats(&self) -> Result<ConnectionStats> {
2209 let connection = self.core.lock_control();
2210 let connections = self.core.connections()?;
2211
2212 let mut total = NDIlib_recv_performance_t::default();
2213 let mut dropped = NDIlib_recv_performance_t::default();
2214 let performance = connection.performance(self.core.sdk(), &mut total, &mut dropped);
2215 let mut queue = NDIlib_recv_queue_t::default();
2216 let queued = connection.queue(self.core.sdk(), &mut queue);
2217
2218 Ok(ConnectionStats {
2219 connections,
2220 video_frames_received: performance.map(|()| total.video_frames).count()?,
2221 audio_frames_received: performance.map(|()| total.audio_frames).count()?,
2222 metadata_frames_received: performance.map(|()| total.metadata_frames).count()?,
2223 video_frames_dropped: performance.map(|()| dropped.video_frames).count()?,
2224 audio_frames_dropped: performance.map(|()| dropped.audio_frames).count()?,
2225 metadata_frames_dropped: performance.map(|()| dropped.metadata_frames).count()?,
2226 video_frames_queued: queued.map(|()| queue.video_frames).count()?,
2227 audio_frames_queued: queued.map(|()| queue.audio_frames).count()?,
2228 metadata_frames_queued: queued.map(|()| queue.metadata_frames).count()?,
2229 })
2230 }
2231}
2232
2233impl<M: EventMode> Receiver<M> {
2235 #[doc(alias = "NDIlib_recv_capture_v3")]
2262 pub fn next_event(&self, timeout: Duration) -> Result<Option<ReceiverEvent>> {
2263 self.next_event_until(Deadline::after(timeout)?, NeverStop)
2264 }
2265}
2266
2267impl ReceiverCore {
2268 pub(crate) fn ndi(&self) -> &Ndi {
2269 self.sdk.ndi()
2270 }
2271
2272 pub(crate) fn sdk(&self) -> &sys::Core {
2274 &self.sdk
2275 }
2276
2277 fn connection_metadata(&self) -> Result<&sys::ReceiverConnectionMetadata> {
2278 self.ndi().table()
2279 }
2280
2281 #[cfg(test)]
2282 fn lock_change(&self) -> ConnectionChange<'_> {
2283 self.begin_change(self.change_guard.lock())
2284 }
2285
2286 fn begin_change<'a>(&'a self, exclusive: MutexGuard<'a, ChangePermit>) -> ConnectionChange<'a> {
2287 if self.guard_local_connection_changes {
2288 self.begin_control_change();
2289 }
2290 ConnectionChange {
2291 core: self,
2292 _exclusive: exclusive,
2293 }
2294 }
2295
2296 fn lock_source_query(&self, until: Instant) -> Option<SourceQuery<'_>> {
2297 self.source_query_guard
2298 .try_lock_until(until)
2299 .map(|query| SourceQuery {
2300 instance: self.instance,
2301 _query: query,
2302 })
2303 }
2304
2305 pub(crate) fn advertiser_membership(&self) -> AdvertiserMembership<'_> {
2306 AdvertiserMembership(self)
2307 }
2308
2309 fn capture_lock(&self, attempt: Attempt) -> CaptureLock<'_> {
2315 CaptureLock {
2316 core: self,
2317 attempt,
2318 }
2319 }
2320
2321 #[cfg(all(test, any(feature = "tokio", feature = "smol")))]
2324 pub(crate) fn reconnect_lock(&self) -> impl Drop + '_ {
2325 self.lock_change()
2326 }
2327
2328 fn poll_ref_until<K: CaptureKind>(&self, attempt: Attempt) -> Result<Retry<K::Ref<'_>>> {
2334 let lock = self.capture_lock(attempt);
2335 let result = capture_any::<Only<K>>(&lock)?;
2336 let progress = matches!(result, Delivered::Notification(n) if n != Notification::None);
2339 Ok(match self.capture_result::<K>(result)? {
2340 Some(frame) => Retry::Item(frame),
2341 None if progress => Retry::Progress,
2342 None => Retry::Idle,
2343 })
2344 }
2345
2346 fn capture_result<'rx, K: CaptureKind>(
2347 &'rx self,
2348 result: Delivered<'rx, Only<K>>,
2349 ) -> Result<Option<K::Ref<'rx>>> {
2350 match result {
2351 Delivered::Media(guard) => {
2352 let frame_ref = K::make_ref(guard)?;
2354 Ok(Some(frame_ref))
2355 }
2356 Delivered::Notification(notification) => {
2357 self.retain(notification);
2358 Ok(None)
2359 }
2360 }
2361 }
2362
2363 fn capture_ref_until<K: CaptureKind>(
2367 &self,
2368 deadline: Deadline,
2369 stop: impl Stop,
2370 ) -> Result<Option<K::Ref<'_>>> {
2371 capture_within(deadline, stop, |attempt| self.poll_ref_until::<K>(attempt))
2372 }
2373
2374 fn capture_any_until_with<'rx, S: SlotSet, T>(
2380 &'rx self,
2381 deadline: Deadline,
2382 stop: impl Stop,
2383 mut event: impl FnMut(ReceiverReport<ReceiverEvent>) -> T,
2384 mut convert: impl FnMut(S::Media<'rx>) -> Result<T>,
2385 ) -> Result<Option<T>> {
2386 capture_within(deadline, stop, |attempt| {
2387 if let Some(pending) = self.take_pending_event_report()? {
2388 return Ok(Some(event(pending)));
2389 }
2390 let lock = self.capture_lock(attempt);
2391 let delivered = capture_any::<S>(&lock)?;
2392 self.capture_any_report_result_with(delivered, &mut event, &mut convert)
2393 })
2394 }
2395
2396 #[cfg(all(test, feature = "advanced"))]
2400 pub(crate) fn capture_any_result_with<'rx, S: SlotSet, T>(
2401 &'rx self,
2402 delivered: Delivered<'rx, S>,
2403 event: impl FnOnce(ReceiverEvent) -> T,
2404 convert: impl FnOnce(S::Media<'rx>) -> Result<T>,
2405 ) -> Result<Option<T>> {
2406 self.capture_any_report_result_with(delivered, |report| event(report.value), convert)
2407 }
2408
2409 fn capture_any_report_result_with<'rx, S: SlotSet, T>(
2410 &'rx self,
2411 delivered: Delivered<'rx, S>,
2412 event: impl FnOnce(ReceiverReport<ReceiverEvent>) -> T,
2413 convert: impl FnOnce(S::Media<'rx>) -> Result<T>,
2414 ) -> Result<Option<T>> {
2415 match delivered {
2416 Delivered::Media(media) => convert(media).map(Some),
2417 Delivered::Notification(notification) => {
2418 self.retain(notification);
2419 self.take_pending_event_report().map(|item| item.map(event))
2420 }
2421 }
2422 }
2423
2424 pub(crate) fn combined_result(media: Media<'_>) -> Result<ReceiverItemRef<'_>> {
2425 Ok(match media {
2426 Media::Video(guard) => ReceiverItemRef::Video(VideoKind::make_ref(guard)?),
2427 Media::Audio(guard) => ReceiverItemRef::Audio(AudioKind::make_ref(guard)?),
2428 Media::Metadata(guard) => ReceiverItemRef::Metadata(MetadataKind::make_ref(guard)?),
2429 })
2430 }
2431
2432 #[cfg(test)]
2433 fn take_pending_status(&self) -> Result<Option<ReceiverStatus>> {
2434 self.pending.status.take_with(|| self.current_status())
2435 }
2436
2437 fn connections(&self) -> Result<u32> {
2438 unsafe {
2442 self.sdk()
2443 .named()
2444 .NDIlib_recv_get_no_connections(self.instance.0)
2445 }
2446 .count()
2447 }
2448
2449 fn current_status(&self) -> Result<ReceiverStatus> {
2450 Ok(ReceiverStatus {
2451 connections: self.connections()?,
2452 })
2453 }
2454
2455 fn retain(&self, notification: Notification) {
2457 self.pending.publish(notification);
2458 }
2459
2460 #[cfg(any(feature = "tokio", feature = "smol"))]
2462 pub(crate) fn retain_event(&self, event: ReceiverReport<ReceiverEvent>) {
2463 self.pending.replay(event);
2464 }
2465
2466 #[cfg(any(feature = "tokio", feature = "smol"))]
2467 pub(crate) fn retain_source_name_change(&self, change: ReceiverReport<SourceNameChange>) {
2468 self.source_name.lock().replay(change);
2469 }
2470
2471 fn take_pending_event_report(&self) -> Result<Option<ReceiverReport<ReceiverEvent>>> {
2472 self.pending.take(|| self.current_status())
2473 }
2474
2475 pub(crate) fn wait_for_source_name_change_until(
2482 &self,
2483 deadline: Deadline,
2484 stop: impl Stop,
2485 ) -> Result<Option<SourceNameChange>> {
2486 let (source_name, strings) = self.ndi().table()?;
2488 self.wait_for_source_name_change_with(source_name, strings, deadline, stop)
2489 .map(|change| change.map(ReceiverReport::into_value))
2490 }
2491
2492 pub(crate) fn wait_for_source_name_change_with(
2495 &self,
2496 source_name: &sys::ReceiverSourceName,
2497 strings: &sys::ReceiverStrings,
2498 deadline: Deadline,
2499 stop: impl Stop,
2500 ) -> Result<Option<ReceiverReport<SourceNameChange>>> {
2501 capture_within(deadline, stop, |attempt| {
2502 if let Some(change) = self.source_name.lock().pending.take() {
2503 return Ok(Some(change));
2504 }
2505 let Some(query) = self.lock_source_query(attempt.0.end()) else {
2506 return Ok(None);
2507 };
2508 if let Some(change) = self.source_name.lock().pending.take() {
2510 return Ok(Some(change));
2511 }
2512 let mut pointer = ptr::null();
2513 let remaining = attempt.0.remaining_ms();
2514 let changed = unsafe {
2518 source_name.named().NDIlib_recv_get_source_name(
2519 query.instance(),
2520 &mut pointer,
2521 remaining,
2522 )
2523 };
2524 let guard = RecvStringGuard {
2525 core: self,
2526 string: changed.map(|_| pointer),
2527 strings,
2528 };
2529 if !changed.into_value() {
2530 return Ok(self.source_name.lock().pending.take());
2531 }
2532 let sequence = self.source_name.lock().advance();
2535 let change = match guard.copy_lossy()? {
2538 Some(name) => SourceNameChange::Connected(name),
2539 None => SourceNameChange::Disconnected,
2540 };
2541 Ok(Some(ReceiverReport {
2542 sequence,
2543 value: change,
2544 }))
2545 })
2546 }
2547}
2548
2549pub(crate) struct CaptureLock<'rx> {
2583 core: &'rx ReceiverCore,
2584 attempt: Attempt,
2585}
2586
2587#[derive(Clone, Copy)]
2590pub(crate) struct ReceiverFrameSource<'rx> {
2591 core: &'rx ReceiverCore,
2592}
2593
2594impl crate::capture::source_sealed::Sealed for ReceiverFrameSource<'_> {}
2595
2596unsafe impl<'rx, S: crate::capture::CaptureStrategy> crate::capture::FrameSource<'rx, S>
2599 for ReceiverFrameSource<'rx>
2600{
2601 fn runtime(&self) -> &'rx Ndi {
2602 self.core.ndi()
2603 }
2604
2605 fn instance(&self) -> NDIlib_recv_instance_t {
2606 self.core.instance.0
2607 }
2608}
2609
2610impl<'rx> CaptureLock<'rx> {
2611 pub(crate) fn source(&self) -> ReceiverFrameSource<'rx> {
2613 ReceiverFrameSource { core: self.core }
2614 }
2615
2616 pub(crate) fn capture(
2625 &self,
2626 video: Option<&mut NDIlib_video_frame_v2_t>,
2627 audio: Option<&mut NDIlib_audio_frame_v3_t>,
2628 metadata: Option<&mut NDIlib_metadata_frame_t>,
2629 ) -> NDIlib_frame_type_e {
2630 unsafe {
2636 self.core.sdk().NDIlib_recv_capture_v3(
2637 self.core.instance.0,
2638 video.map_or(ptr::null_mut(), ptr::from_mut),
2639 audio.map_or(ptr::null_mut(), ptr::from_mut),
2640 metadata.map_or(ptr::null_mut(), ptr::from_mut),
2641 self.attempt.0.remaining_ms(),
2642 )
2643 }
2644 }
2645}
2646
2647#[derive(Clone, Copy)]
2656pub struct Ptz<'rx> {
2657 core: &'rx ReceiverCore,
2658}
2659
2660impl std::fmt::Debug for Ptz<'_> {
2661 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2662 f.debug_struct("Ptz")
2663 .field("receiver_name", &ReceiverIdentity::name(self.core))
2664 .finish_non_exhaustive()
2665 }
2666}
2667
2668impl Ptz<'_> {
2669 #[must_use]
2673 #[doc(alias = "NDIlib_recv_ptz_is_supported")]
2674 pub fn is_supported(&self) -> bool {
2675 self.core
2676 .lock_mutating_control()
2677 .is_ok_and(|connection| connection.ptz_is_supported(self.core.sdk()))
2678 }
2679
2680 #[doc(alias = "NDIlib_recv_ptz_recall_preset")]
2686 pub fn recall_preset(&self, preset: u8, speed: f32) -> Result<()> {
2687 let preset = validate_ptz_preset(preset)?;
2688 validate_ptz_value("speed", speed, 0.0, 1.0)?;
2689 ptz_command!(self, ptz_recall_preset, preset, speed)
2690 }
2691
2692 #[doc(alias = "NDIlib_recv_ptz_store_preset")]
2698 pub fn store_preset(&self, preset: u8) -> Result<()> {
2699 let preset = validate_ptz_preset(preset)?;
2700 ptz_command!(self, ptz_store_preset, preset)
2701 }
2702
2703 #[doc(alias = "NDIlib_recv_ptz_zoom")]
2710 pub fn zoom(&self, zoom: f32) -> Result<()> {
2711 validate_ptz_value("zoom", zoom, 0.0, 1.0)?;
2712 ptz_command!(self, ptz_zoom, zoom)
2713 }
2714
2715 #[doc(alias = "NDIlib_recv_ptz_zoom_speed")]
2722 pub fn zoom_speed(&self, speed: f32) -> Result<()> {
2723 validate_ptz_value("zoom speed", speed, -1.0, 1.0)?;
2724 ptz_command!(self, ptz_zoom_speed, speed)
2725 }
2726
2727 #[doc(alias = "NDIlib_recv_ptz_pan_tilt")]
2734 pub fn pan_tilt(&self, pan: f32, tilt: f32) -> Result<()> {
2735 validate_ptz_value("pan", pan, -1.0, 1.0)?;
2736 validate_ptz_value("tilt", tilt, -1.0, 1.0)?;
2737 ptz_command!(self, ptz_pan_tilt, pan, tilt)
2738 }
2739
2740 #[doc(alias = "NDIlib_recv_ptz_pan_tilt_speed")]
2747 pub fn pan_tilt_speed(&self, pan_speed: f32, tilt_speed: f32) -> Result<()> {
2748 validate_ptz_value("pan speed", pan_speed, -1.0, 1.0)?;
2749 validate_ptz_value("tilt speed", tilt_speed, -1.0, 1.0)?;
2750 ptz_command!(self, ptz_pan_tilt_speed, pan_speed, tilt_speed)
2751 }
2752
2753 #[doc(alias = "NDIlib_recv_ptz_auto_focus")]
2759 pub fn auto_focus(&self) -> Result<()> {
2760 ptz_command!(self, ptz_auto_focus)
2761 }
2762
2763 #[doc(alias = "NDIlib_recv_ptz_focus")]
2770 pub fn focus(&self, focus: f32) -> Result<()> {
2771 validate_ptz_value("focus", focus, 0.0, 1.0)?;
2772 ptz_command!(self, ptz_focus, focus)
2773 }
2774
2775 #[doc(alias = "NDIlib_recv_ptz_focus_speed")]
2782 pub fn focus_speed(&self, speed: f32) -> Result<()> {
2783 validate_ptz_value("focus speed", speed, -1.0, 1.0)?;
2784 ptz_command!(self, ptz_focus_speed, speed)
2785 }
2786
2787 #[doc(alias = "NDIlib_recv_ptz_white_balance_auto")]
2793 pub fn white_balance_auto(&self) -> Result<()> {
2794 ptz_command!(self, ptz_white_balance_auto)
2795 }
2796
2797 #[doc(alias = "NDIlib_recv_ptz_white_balance_indoor")]
2803 pub fn white_balance_indoor(&self) -> Result<()> {
2804 ptz_command!(self, ptz_white_balance_indoor)
2805 }
2806
2807 #[doc(alias = "NDIlib_recv_ptz_white_balance_outdoor")]
2813 pub fn white_balance_outdoor(&self) -> Result<()> {
2814 ptz_command!(self, ptz_white_balance_outdoor)
2815 }
2816
2817 #[doc(alias = "NDIlib_recv_ptz_white_balance_oneshot")]
2823 pub fn white_balance_oneshot(&self) -> Result<()> {
2824 ptz_command!(self, ptz_white_balance_oneshot)
2825 }
2826
2827 #[doc(alias = "NDIlib_recv_ptz_white_balance_manual")]
2833 pub fn white_balance_manual(&self, red: f32, blue: f32) -> Result<()> {
2834 validate_ptz_value("red", red, 0.0, 1.0)?;
2835 validate_ptz_value("blue", blue, 0.0, 1.0)?;
2836 ptz_command!(self, ptz_white_balance_manual, red, blue)
2837 }
2838
2839 #[doc(alias = "NDIlib_recv_ptz_exposure_auto")]
2845 pub fn exposure_auto(&self) -> Result<()> {
2846 ptz_command!(self, ptz_exposure_auto)
2847 }
2848
2849 #[doc(alias = "NDIlib_recv_ptz_exposure_manual")]
2855 pub fn exposure_manual(&self, level: f32) -> Result<()> {
2856 validate_ptz_value("exposure level", level, 0.0, 1.0)?;
2857 ptz_command!(self, ptz_exposure_manual, level)
2858 }
2859
2860 #[doc(alias = "NDIlib_recv_ptz_exposure_manual_v2")]
2867 pub fn exposure_manual_detailed(&self, iris: f32, gain: f32, shutter_speed: f32) -> Result<()> {
2868 validate_ptz_value("iris", iris, 0.0, 1.0)?;
2869 validate_ptz_value("gain", gain, 0.0, 1.0)?;
2870 validate_ptz_value("shutter speed", shutter_speed, 0.0, 1.0)?;
2871 ptz_command!(self, ptz_exposure_manual_v2, iris, gain, shutter_speed)
2872 }
2873}
2874
2875impl Drop for ReceiverCore {
2876 fn drop(&mut self) {
2877 unsafe {
2881 self.sdk().NDIlib_recv_destroy(self.instance.0);
2882 }
2883 }
2884}
2885
2886const_assert!({
2887 const fn assert_send_sync<T: Send + Sync>() {}
2888 assert_send_sync::<ReceiverCore>();
2889});
2890
2891impl std::panic::RefUnwindSafe for ReceiverCore {}
2904
2905#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2907#[non_exhaustive]
2908pub enum SourceNameChange {
2909 Connected(String),
2911 Disconnected,
2913}
2914
2915#[derive(Debug, Clone)]
2919#[non_exhaustive]
2920pub enum ReceiverItem {
2921 Video(VideoFrame),
2923 Audio(AudioFrame),
2925 Metadata(MetadataFrame),
2927 Event(ReceiverEvent),
2929}
2930
2931#[derive(Debug)]
2941#[non_exhaustive]
2942pub enum ReceiverItemRef<'rx> {
2943 Video(VideoFrameRef<'rx>),
2945 Audio(AudioFrameRef<'rx>),
2947 Metadata(MetadataFrameRef<'rx>),
2949 Event(ReceiverEvent),
2951}
2952
2953impl ReceiverItemRef<'_> {
2954 pub fn to_owned(&self) -> ReceiverItem {
2960 match self {
2961 Self::Video(frame) => ReceiverItem::Video(frame.to_owned()),
2962 Self::Audio(frame) => ReceiverItem::Audio(frame.to_owned()),
2963 Self::Metadata(frame) => ReceiverItem::Metadata(frame.to_owned()),
2964 Self::Event(event) => ReceiverItem::Event(*event),
2965 }
2966 }
2967}
2968
2969#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2971#[non_exhaustive]
2972pub enum ReceiverEvent {
2973 StatusChanged(ReceiverStatus),
2978 SourceChanged,
2980 Unknown(u32),
2982}
2983
2984#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2993pub struct ReceiverStatus {
2994 connections: u32,
2995}
2996
2997impl ReceiverStatus {
2998 #[must_use]
3001 pub const fn connections(self) -> u32 {
3002 self.connections
3003 }
3004}
3005
3006#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3008pub struct Tally {
3009 on_program: bool,
3010 on_preview: bool,
3011}
3012
3013impl Tally {
3014 #[must_use]
3016 pub const fn new(on_program: bool, on_preview: bool) -> Self {
3017 Self {
3018 on_program,
3019 on_preview,
3020 }
3021 }
3022
3023 #[must_use]
3025 pub const fn on_program(self) -> bool {
3026 self.on_program
3027 }
3028
3029 #[must_use]
3031 pub const fn on_preview(self) -> bool {
3032 self.on_preview
3033 }
3034
3035 pub(crate) const fn to_sdk(self) -> NDIlib_tally_t {
3036 NDIlib_tally_t {
3037 on_program: self.on_program,
3038 on_preview: self.on_preview,
3039 }
3040 }
3041}
3042
3043#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3048pub enum SettingChange {
3049 Applied,
3051 Unchanged,
3054}
3055
3056impl SettingChange {
3057 pub(crate) const fn from_sdk(changed: bool) -> Self {
3059 if changed {
3060 Self::Applied
3061 } else {
3062 Self::Unchanged
3063 }
3064 }
3065}
3066
3067#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3078pub struct ConnectionStats {
3079 connections: u32,
3080 video_frames_received: u64,
3081 audio_frames_received: u64,
3082 metadata_frames_received: u64,
3083 video_frames_dropped: u64,
3084 audio_frames_dropped: u64,
3085 metadata_frames_dropped: u64,
3086 video_frames_queued: u32,
3087 audio_frames_queued: u32,
3088 metadata_frames_queued: u32,
3089}
3090
3091impl ConnectionStats {
3092 #[must_use]
3094 pub const fn connections(&self) -> u32 {
3095 self.connections
3096 }
3097
3098 #[must_use]
3100 pub const fn video_frames_received(&self) -> u64 {
3101 self.video_frames_received
3102 }
3103
3104 #[must_use]
3106 pub const fn audio_frames_received(&self) -> u64 {
3107 self.audio_frames_received
3108 }
3109
3110 #[must_use]
3112 pub const fn metadata_frames_received(&self) -> u64 {
3113 self.metadata_frames_received
3114 }
3115
3116 #[must_use]
3119 pub const fn video_frames_dropped(&self) -> u64 {
3120 self.video_frames_dropped
3121 }
3122
3123 #[must_use]
3125 pub const fn audio_frames_dropped(&self) -> u64 {
3126 self.audio_frames_dropped
3127 }
3128
3129 #[must_use]
3131 pub const fn metadata_frames_dropped(&self) -> u64 {
3132 self.metadata_frames_dropped
3133 }
3134
3135 #[must_use]
3137 pub const fn video_frames_queued(&self) -> u32 {
3138 self.video_frames_queued
3139 }
3140
3141 #[must_use]
3143 pub const fn audio_frames_queued(&self) -> u32 {
3144 self.audio_frames_queued
3145 }
3146
3147 #[must_use]
3149 pub const fn metadata_frames_queued(&self) -> u32 {
3150 self.metadata_frames_queued
3151 }
3152
3153 #[must_use]
3157 pub fn video_drop_percentage(&self) -> f64 {
3158 drop_percentage(self.video_frames_received, self.video_frames_dropped)
3159 }
3160
3161 #[must_use]
3165 pub fn audio_drop_percentage(&self) -> f64 {
3166 drop_percentage(self.audio_frames_received, self.audio_frames_dropped)
3167 }
3168
3169 #[must_use]
3173 pub fn metadata_drop_percentage(&self) -> f64 {
3174 drop_percentage(self.metadata_frames_received, self.metadata_frames_dropped)
3175 }
3176
3177 #[must_use]
3180 pub const fn is_connected(&self) -> bool {
3181 self.connections > 0
3182 }
3183}
3184
3185fn drop_percentage(received: u64, dropped: u64) -> f64 {
3186 if received == 0 {
3187 0.0
3188 } else {
3189 100.0 * (dropped.min(received) as f64 / received as f64)
3190 }
3191}
3192
3193#[cfg(test)]
3194#[path = "receiver_mixed_tests.rs"]
3195mod mixed_tests;
3196
3197#[cfg(test)]
3198mod tests {
3199 use super::*;
3200
3201 use std::cell::Cell;
3202
3203 #[test]
3204 fn receive_delay_rounds_up_and_rejects_out_of_range_values() {
3205 for (duration, millis) in [
3206 (Duration::ZERO, 0),
3207 (Duration::from_nanos(1), 1),
3208 (Duration::from_nanos(999_999), 1),
3209 (Duration::from_millis(1), 1),
3210 (Duration::from_nanos(1_000_001), 2),
3211 (Duration::from_nanos(1_999_999_999), 2000),
3212 (Duration::from_secs(2), 2000),
3213 ] {
3214 let delay = ReceiveDelay::new(duration).unwrap();
3215 assert_eq!(delay.to_sdk(), millis);
3216 assert_eq!(delay.duration(), Duration::from_millis(millis as u64));
3217 assert_eq!(ReceiveDelay::from_sdk(delay.to_sdk()).unwrap(), delay);
3218 }
3219 for too_long in [
3220 ReceiveDelay::MAX.duration() + Duration::from_nanos(1),
3221 Duration::MAX,
3222 ] {
3223 assert!(matches!(
3224 ReceiveDelay::new(too_long),
3225 Err(Error::InvalidInput(
3226 crate::InputDefect::ReceiveDelayTooLong { .. }
3227 ))
3228 ));
3229 }
3230 for millis in [0, 1, 1999, 2000] {
3231 assert_eq!(ReceiveDelay::from_sdk(millis).unwrap().to_sdk(), millis);
3232 }
3233 for millis in [-1, 2001, i32::MIN, i32::MAX] {
3234 assert!(matches!(
3235 ReceiveDelay::from_sdk(millis),
3236 Err(Error::UnexpectedSdkResult(crate::SdkResultDefect::InvalidReceiveDelay { millis: reported })) if reported == millis
3237 ));
3238 }
3239 }
3240
3241 #[test]
3242 fn receive_64_modes_require_the_selected_runtime_before_native_creation() {
3243 for version in ["6.1.1.0", "6.4.0.2"] {
3244 sys::with_test_evidence(version, |evidence| {
3245 let supported = version == "6.4.0.2";
3246 let best =
3247 ReceiverOptions::new(test_source()).color_format(ReceiverColorFormat::Best444);
3248 let validated = best.validate_runtime(evidence);
3249 assert_eq!(validated.is_ok(), supported);
3250 if let Ok(validated) = validated {
3251 assert!(validated._best444.is_some());
3252 assert_eq!(validated.settings(None, None).raw().color_format, 102);
3253 }
3254 for (bandwidth, value) in [
3255 (ReceiverBandwidth::VideoOnlyLowest, 1),
3256 (ReceiverBandwidth::VideoOnlyHighest, 101),
3257 ] {
3258 let options = ReceiverOptions::new(test_source()).bandwidth(bandwidth);
3259 let validated = options.validate_runtime(evidence);
3260 assert_eq!(validated.is_ok(), supported);
3261 if let Ok(validated) = validated {
3262 assert!(validated._video_only.is_some());
3263 assert_eq!(validated.settings(None, None).raw().bandwidth, value);
3264 }
3265 }
3266 assert!(unconnected().validate_runtime(evidence).is_ok());
3267 });
3268 }
3269 }
3270
3271 #[test]
3272 fn typed_capture_paths_publish_notifications() {
3273 let Some(ndi) = crate::test_support::ndi() else {
3274 return;
3275 };
3276 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3277 fn check<K: CaptureKind>(receiver: &Receiver) {
3278 assert!(receiver
3279 .core
3280 .capture_result::<K>(Delivered::Notification(Notification::SourceChanged))
3281 .unwrap()
3282 .is_none());
3283 assert!(matches!(
3284 receiver.next_event(Duration::ZERO).unwrap(),
3285 Some(ReceiverEvent::SourceChanged)
3286 ));
3287 }
3288 check::<VideoKind>(&receiver);
3289 check::<AudioKind>(&receiver);
3290 check::<MetadataKind>(&receiver);
3291 }
3292
3293 #[test]
3294 fn receive_delay_native_changed_flag_and_capability_failure() {
3295 let Some(ndi) = crate::test_support::ndi() else {
3296 return;
3297 };
3298 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3299 if ndi.require_feature(RuntimeFeature::ReceiveDelay).is_ok() {
3300 assert_eq!(receiver.video_delay().unwrap(), ReceiveDelay::ZERO);
3301 assert_eq!(receiver.audio_delay().unwrap(), ReceiveDelay::ZERO);
3302 use SettingChange::{Applied, Unchanged};
3303 assert_eq!(
3304 receiver.set_video_delay(ReceiveDelay::ZERO).unwrap(),
3305 Unchanged
3306 );
3307 assert_eq!(
3308 receiver
3309 .set_video_delay(ReceiveDelay::new(Duration::from_nanos(1)).unwrap())
3310 .unwrap(),
3311 Applied
3312 );
3313 assert_eq!(
3314 receiver.video_delay().unwrap(),
3315 ReceiveDelay::new(Duration::from_millis(1)).unwrap()
3316 );
3317 assert_eq!(
3318 receiver
3319 .set_video_delay(ReceiveDelay::new(Duration::from_millis(1)).unwrap())
3320 .unwrap(),
3321 Unchanged
3322 );
3323 assert_eq!(receiver.audio_delay().unwrap(), ReceiveDelay::ZERO);
3324 assert_eq!(
3325 receiver.set_audio_delay(ReceiveDelay::MAX).unwrap(),
3326 Applied
3327 );
3328 assert_eq!(receiver.audio_delay().unwrap(), ReceiveDelay::MAX);
3329 assert_eq!(
3330 receiver.set_audio_delay(ReceiveDelay::MAX).unwrap(),
3331 Unchanged
3332 );
3333 } else {
3334 assert!(matches!(
3335 receiver.video_delay(),
3336 Err(Error::UnsupportedCapability { .. })
3337 ));
3338 assert!(matches!(
3339 receiver.audio_delay(),
3340 Err(Error::UnsupportedCapability { .. })
3341 ));
3342 assert!(matches!(
3343 receiver.set_video_delay(ReceiveDelay::ZERO),
3344 Err(Error::UnsupportedCapability { .. })
3345 ));
3346 assert!(matches!(
3347 receiver.set_audio_delay(ReceiveDelay::ZERO),
3348 Err(Error::UnsupportedCapability { .. })
3349 ));
3350 }
3351 }
3352
3353 #[test]
3354 fn disconnected_receiver_allocates_only_its_core() {
3355 let Some(ndi) = crate::test_support::ndi() else {
3356 return;
3357 };
3358 let (receiver, allocations) = crate::test_alloc::allocation_count(|| {
3359 Receiver::new(&ndi, &ReceiverOptions::disconnected()).unwrap()
3360 });
3361 assert_eq!(
3362 allocations, 1,
3363 "only the shared receiver core should allocate"
3364 );
3365 let (target, allocations) = crate::test_alloc::allocation_count(|| {
3366 receiver.reconnect();
3367 receiver.connection_target()
3368 });
3369 assert_eq!(target, None);
3370 assert_eq!(allocations, 0);
3371 }
3372
3373 #[test]
3374 fn reconnect_reuses_validated_name_url_and_ip_targets_without_allocating() {
3375 let Some(ndi) = crate::test_support::ndi() else {
3376 return;
3377 };
3378 for source in [
3379 Source::new("retained name").unwrap(),
3380 Source::new("")
3381 .unwrap()
3382 .with_address(crate::SourceAddress::new("ndi://127.0.0.1:5961").unwrap()),
3383 Source::new("retained URL")
3384 .unwrap()
3385 .with_address(crate::SourceAddress::new("ndi://127.0.0.1:5961").unwrap()),
3386 Source::new("retained IP")
3387 .unwrap()
3388 .with_address(crate::SourceAddress::new("127.0.0.1:5961").unwrap()),
3389 ] {
3390 let receiver = Receiver::new(&ndi, &ReceiverOptions::new(source.clone())).unwrap();
3391 let ((), allocations) = crate::test_alloc::allocation_count(|| receiver.reconnect());
3392 assert_eq!(allocations, 0);
3393 assert_eq!(receiver.connection_target().as_ref(), Some(&source));
3394 receiver.disconnect();
3395 let ((), allocations) = crate::test_alloc::allocation_count(|| receiver.reconnect());
3396 assert_eq!(allocations, 0);
3397 assert_eq!(receiver.connection_target().as_ref(), Some(&source));
3398 }
3399 }
3400
3401 #[test]
3402 fn receiver_allocated_strings_free_once_even_when_utf8_is_invalid() {
3403 use std::sync::atomic::AtomicUsize;
3404 static FREES: AtomicUsize = AtomicUsize::new(0);
3405 unsafe extern "C" fn free(_instance: NDIlib_recv_instance_t, pointer: *const c_char) {
3406 FREES.fetch_add(1, Ordering::Relaxed);
3407 drop(unsafe { CString::from_raw(pointer.cast_mut()) });
3408 }
3409 let Some(ndi) = crate::test_support::ndi() else {
3410 return;
3411 };
3412 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3413 let strings = sys::ReceiverStrings {
3414 NDIlib_recv_free_string: free,
3415 };
3416 let before = FREES.load(Ordering::Relaxed);
3417 for (bytes, valid) in [
3418 (b"source".to_vec(), true),
3419 (Vec::new(), true),
3420 (vec![255], false),
3421 ] {
3422 let guard = RecvStringGuard {
3423 core: &receiver.core,
3424 string: sys::table::for_test(
3425 CString::new(bytes).unwrap().into_raw().cast_const(),
3426 c"NDIlib_recv_get_web_control",
3427 ),
3428 strings: &strings,
3429 };
3430 assert_eq!(guard.copy().is_ok(), valid);
3431 drop(guard);
3432 }
3433 let empty = RecvStringGuard {
3434 core: &receiver.core,
3435 string: sys::table::for_test(ptr::null(), c"NDIlib_recv_get_web_control"),
3436 strings: &strings,
3437 };
3438 assert_eq!(empty.copy().unwrap(), None);
3439 assert_eq!(empty.copy_lossy().unwrap(), None);
3440 drop(empty);
3441 assert_eq!(FREES.load(Ordering::Relaxed) - before, 3);
3442 }
3443
3444 #[test]
3445 fn lossy_receiver_strings_keep_the_terminator_bound() {
3446 unsafe extern "C" fn keep(_instance: NDIlib_recv_instance_t, _pointer: *const c_char) {}
3447 let Some(ndi) = crate::test_support::ndi() else {
3448 return;
3449 };
3450 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3451 let strings = sys::ReceiverStrings {
3452 NDIlib_recv_free_string: keep,
3453 };
3454 let max = crate::sdk_copy::MAX_SDK_STRING_BYTES;
3455 let copy = |bytes: &[u8]| {
3456 RecvStringGuard {
3457 core: &receiver.core,
3458 string: sys::table::for_test(bytes.as_ptr().cast(), c"NDIlib_recv_get_source_name"),
3459 strings: &strings,
3460 }
3461 .copy_lossy()
3462 };
3463 assert_eq!(copy(b"\0").unwrap().as_deref(), Some(""));
3464 assert_eq!(copy(b"a\xffb\0").unwrap().as_deref(), Some("a\u{FFFD}b"));
3465 assert_eq!(copy(b"a\0\xff\0").unwrap().as_deref(), Some("a"));
3467 let mut longest = vec![b'x'; max];
3469 longest[max - 1] = 0;
3470 assert_eq!(copy(&longest).unwrap().unwrap().len(), max - 1);
3471 let unterminated = vec![b'x'; max];
3473 let (result, allocations) = crate::test_alloc::allocation_count(|| copy(&unterminated));
3474 assert!(
3475 matches!(result, Err(Error::UnexpectedSdkResult(crate::SdkResultDefect::UnterminatedText { operation }))
3476 if operation == c"NDIlib_recv_get_source_name")
3477 );
3478 assert_eq!(allocations, 0);
3479 let guard = RecvStringGuard {
3480 core: &receiver.core,
3481 string: sys::table::for_test(
3482 unterminated.as_ptr().cast(),
3483 c"NDIlib_recv_get_web_control",
3484 ),
3485 strings: &strings,
3486 };
3487 assert!(
3488 matches!(guard.copy(), Err(Error::UnexpectedSdkResult(crate::SdkResultDefect::UnterminatedText { operation }))
3489 if operation == c"NDIlib_recv_get_web_control")
3490 );
3491 }
3492
3493 #[test]
3494 fn a_changed_source_name_that_is_not_utf8_is_still_reported_and_freed_once() {
3495 use std::{cell::RefCell, sync::atomic::AtomicUsize};
3496 static FREES: AtomicUsize = AtomicUsize::new(0);
3497 std::thread_local! {
3498 static NEXT: RefCell<(bool, Option<Vec<u8>>)> = const { RefCell::new((false, None)) };
3501 }
3502 unsafe extern "C" fn free(_instance: NDIlib_recv_instance_t, pointer: *const c_char) {
3503 FREES.fetch_add(1, Ordering::Relaxed);
3504 drop(unsafe { CString::from_raw(pointer.cast_mut()) });
3505 }
3506 unsafe extern "C" fn get_source_name(
3507 _instance: NDIlib_recv_instance_t,
3508 name: *mut *const c_char,
3509 _timeout_in_ms: u32,
3510 ) -> bool {
3511 let (changed, next) = NEXT.with(|next| next.take());
3512 let pointer = next.map_or(ptr::null(), |bytes| {
3513 CString::new(bytes).unwrap().into_raw().cast_const()
3514 });
3515 unsafe { name.write(pointer) };
3517 changed
3518 }
3519 let Some(ndi) = crate::test_support::ndi() else {
3520 return;
3521 };
3522 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3523 let source_name = sys::ReceiverSourceName {
3524 NDIlib_recv_get_source_name: get_source_name,
3525 };
3526 let strings = sys::ReceiverStrings {
3527 NDIlib_recv_free_string: free,
3528 };
3529 let poll = |changed, name: Option<&[u8]>| {
3530 NEXT.with(|next| *next.borrow_mut() = (changed, name.map(<[u8]>::to_vec)));
3531 let before = FREES.load(Ordering::Relaxed);
3532 let change = receiver.core.wait_for_source_name_change_with(
3533 &source_name,
3534 &strings,
3535 Deadline::after(Duration::ZERO).unwrap(),
3536 NeverStop,
3537 );
3538 (
3539 change.unwrap().map(ReceiverReport::into_value),
3540 FREES.load(Ordering::Relaxed) - before,
3541 )
3542 };
3543 assert_eq!(
3544 poll(true, Some(b"Studio \xff\xfe camera")),
3545 (
3546 Some(SourceNameChange::Connected(
3547 "Studio \u{FFFD}\u{FFFD} camera".into()
3548 )),
3549 1
3550 )
3551 );
3552 assert_eq!(
3553 poll(true, Some("Studio é".as_bytes())),
3554 (Some(SourceNameChange::Connected("Studio é".into())), 1)
3555 );
3556 assert_eq!(poll(true, None), (Some(SourceNameChange::Disconnected), 0));
3557 assert_eq!(poll(false, Some(b"\xff")), (None, 1));
3559 assert_eq!(poll(false, None), (None, 0));
3560 }
3561
3562 #[test]
3563 fn source_name_wait_retries_bounded_queries_and_honors_cancellation() {
3564 use std::cell::RefCell;
3565 std::thread_local! {
3566 static CALLS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
3567 }
3568 unsafe extern "C" fn get_source_name(
3569 _instance: NDIlib_recv_instance_t,
3570 name: *mut *const c_char,
3571 timeout_ms: u32,
3572 ) -> bool {
3573 let changed = CALLS.with(|calls| {
3574 let mut calls = calls.borrow_mut();
3575 calls.push(timeout_ms);
3576 calls.len() == 3
3577 });
3578 unsafe {
3579 name.write(if changed {
3580 c"later source".as_ptr()
3581 } else {
3582 ptr::null()
3583 })
3584 };
3585 changed
3586 }
3587 unsafe extern "C" fn free(_instance: NDIlib_recv_instance_t, _name: *const c_char) {}
3588 let Some(ndi) = crate::test_support::ndi() else {
3589 return;
3590 };
3591 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3592 let source_name = sys::ReceiverSourceName {
3593 NDIlib_recv_get_source_name: get_source_name,
3594 };
3595 let strings = sys::ReceiverStrings {
3596 NDIlib_recv_free_string: free,
3597 };
3598 let result = receiver
3599 .core
3600 .wait_for_source_name_change_with(
3601 &source_name,
3602 &strings,
3603 Deadline::after(Duration::from_secs(2)).unwrap(),
3604 NeverStop,
3605 )
3606 .unwrap();
3607 assert_eq!(
3608 result.map(ReceiverReport::into_value),
3609 Some(SourceNameChange::Connected("later source".into()))
3610 );
3611 CALLS.with(|calls| {
3612 assert_eq!(calls.borrow().len(), 3);
3613 assert!(calls.borrow().iter().all(|&wait| wait <= 100));
3614 calls.borrow_mut().clear();
3615 });
3616 let stopped = AtomicBool::new(true);
3619 assert!(receiver
3620 .core
3621 .wait_for_source_name_change_with(
3622 &source_name,
3623 &strings,
3624 Deadline::after(Duration::from_secs(2)).unwrap(),
3625 &stopped,
3626 )
3627 .unwrap()
3628 .is_none());
3629 CALLS.with(|calls| assert_eq!(calls.borrow().len(), 1));
3630 }
3631
3632 #[cfg(any(feature = "tokio", feature = "smol"))]
3633 mod replay_tests {
3634 use super::*;
3635 use std::{cell::Cell, ffi::CStr};
3636
3637 thread_local! {
3638 static NEXT: Cell<Option<&'static CStr>> = const { Cell::new(None) };
3639 static CALLS: Cell<usize> = const { Cell::new(0) };
3640 }
3641
3642 unsafe extern "C" fn get_source_name(
3643 _instance: NDIlib_recv_instance_t,
3644 name: *mut *const c_char,
3645 _timeout_ms: u32,
3646 ) -> bool {
3647 CALLS.with(|calls| calls.set(calls.get() + 1));
3648 let next = NEXT.take();
3649 unsafe { name.write(next.map_or(ptr::null(), CStr::as_ptr)) };
3651 next.is_some()
3652 }
3653 unsafe extern "C" fn free(_instance: NDIlib_recv_instance_t, _name: *const c_char) {}
3654
3655 fn poll(
3656 core: &ReceiverCore,
3657 name: Option<&'static CStr>,
3658 ) -> Option<ReceiverReport<SourceNameChange>> {
3659 NEXT.set(name);
3660 core.wait_for_source_name_change_with(
3661 &sys::ReceiverSourceName {
3662 NDIlib_recv_get_source_name: get_source_name,
3663 },
3664 &sys::ReceiverStrings {
3665 NDIlib_recv_free_string: free,
3666 },
3667 Deadline::after(Duration::ZERO).unwrap(),
3668 NeverStop,
3669 )
3670 .unwrap()
3671 }
3672
3673 #[test]
3674 fn only_the_newest_abandoned_name_precedes_a_native_query() {
3675 let Some(ndi) = crate::test_support::ndi() else {
3676 return;
3677 };
3678 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3679 let first = poll(&receiver.core, Some(c"first")).unwrap();
3680 let second = poll(&receiver.core, Some(c"second")).unwrap();
3681 receiver.core.retain_source_name_change(second);
3682 receiver.core.retain_source_name_change(first);
3683 let before = CALLS.get();
3684 assert_eq!(
3685 poll(&receiver.core, None).unwrap().value,
3686 SourceNameChange::Connected("second".into())
3687 );
3688 assert_eq!(CALLS.get(), before);
3689 assert!(poll(&receiver.core, None).is_none());
3690 assert_eq!(CALLS.get(), before + 1);
3691 }
3692
3693 #[test]
3694 fn replay_does_not_wait_for_another_pollers_native_query() {
3695 use std::sync::mpsc;
3696
3697 type QueryGate = (mpsc::Sender<()>, mpsc::Receiver<()>);
3698 static GATE: Mutex<Option<QueryGate>> = Mutex::new(None);
3699 unsafe extern "C" fn held_query(
3700 _instance: NDIlib_recv_instance_t,
3701 name: *mut *const c_char,
3702 _timeout_ms: u32,
3703 ) -> bool {
3704 let (entered, release) = GATE.lock().take().unwrap();
3705 let _ = entered.send(());
3706 let _ = release.recv();
3707 unsafe { name.write(c"second".as_ptr()) };
3709 true
3710 }
3711
3712 let Some(ndi) = crate::test_support::ndi() else {
3713 return;
3714 };
3715 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3716 let abandoned = poll(&receiver.core, Some(c"first")).unwrap();
3717 std::thread::scope(|scope| {
3718 let (entered, waiting) = mpsc::channel();
3719 let (release, blocked) = mpsc::channel();
3720 *GATE.lock() = Some((entered, blocked));
3721 let worker = scope.spawn(|| {
3722 receiver
3723 .core
3724 .wait_for_source_name_change_with(
3725 &sys::ReceiverSourceName {
3726 NDIlib_recv_get_source_name: held_query,
3727 },
3728 &sys::ReceiverStrings {
3729 NDIlib_recv_free_string: free,
3730 },
3731 Deadline::after(Duration::from_secs(3)).unwrap(),
3732 NeverStop,
3733 )
3734 .unwrap()
3735 });
3736 waiting.recv_timeout(Duration::from_secs(2)).unwrap();
3737 let (done, completed) = mpsc::channel();
3738 let receiver = &receiver;
3739 scope.spawn(move || {
3740 receiver.core.retain_source_name_change(abandoned);
3741 done.send(()).unwrap();
3742 });
3743 let replayed = completed.recv_timeout(Duration::from_secs(2));
3744 drop(release);
3746 replayed.expect("replay waited for the native query");
3747 assert_eq!(
3748 worker.join().unwrap().unwrap().value,
3749 SourceNameChange::Connected("second".into())
3750 );
3751 assert!(poll(&receiver.core, None).is_none());
3752 });
3753 }
3754 }
3755
3756 fn test_source() -> Source {
3758 Source::new("receiver test target").unwrap()
3759 }
3760
3761 fn unconnected() -> ReceiverOptions {
3763 ReceiverOptions::disconnected()
3764 }
3765
3766 struct FakeClock {
3769 start: Instant,
3770 elapsed: Cell<Duration>,
3771 }
3772
3773 impl FakeClock {
3774 fn new() -> Self {
3775 Self {
3776 start: Instant::now(),
3777 elapsed: Cell::new(Duration::ZERO),
3778 }
3779 }
3780
3781 fn now(&self) -> Instant {
3782 self.start + self.elapsed.get()
3783 }
3784
3785 fn elapsed(&self) -> Duration {
3786 self.elapsed.get()
3787 }
3788
3789 fn advance(&self, duration: Duration) {
3790 self.elapsed.set(self.elapsed.get() + duration);
3791 }
3792
3793 fn deadline(&self, budget: Duration) -> Deadline {
3795 Deadline::starting(self.start, crate::timeout::Timeout::new(budget).unwrap()).unwrap()
3796 }
3797
3798 fn timeout(&self, attempt: Attempt) -> Duration {
3801 attempt.0.remaining_at(self.now()).duration()
3802 }
3803 }
3804
3805 fn assert_raw_receiver_modes(
3806 raw: &TestSettings,
3807 expected_color_format: NDIlib_recv_color_format_e,
3808 expected_bandwidth: NDIlib_recv_bandwidth_e,
3809 ) {
3810 assert_eq!(raw.raw.color_format, expected_color_format);
3811 assert_eq!(raw.raw.bandwidth, expected_bandwidth);
3812 assert_ne!(
3813 raw.raw.color_format,
3814 NDIlib_recv_color_format_e_NDIlib_recv_color_format_max
3815 );
3816 assert_ne!(
3817 raw.raw.bandwidth,
3818 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_max
3819 );
3820 }
3821
3822 #[test]
3823 fn pending_status_keeps_failed_and_newer_publications() {
3824 let pending = PendingStatus::default();
3825 pending.publish();
3826 assert!(matches!(
3827 pending.take_with::<()>(|| Err(Error::ConnectionLost)),
3828 Err(Error::ConnectionLost)
3829 ));
3830 assert!(pending.is_pending());
3831 assert_eq!(
3832 pending
3833 .take_with(|| {
3834 pending.publish();
3835 Ok(1)
3836 })
3837 .unwrap(),
3838 None
3839 );
3840 assert!(
3841 pending.is_pending(),
3842 "a publication during validation must survive"
3843 );
3844 assert_eq!(pending.take_with(|| Ok(2)).unwrap(), Some(2));
3845 assert!(!pending.is_pending());
3846 pending.publish();
3847 assert!(pending
3848 .take_with::<()>(|| {
3849 pending.publish();
3850 Err(Error::ConnectionLost)
3851 })
3852 .unwrap()
3853 .is_none());
3854 assert!(pending.is_pending());
3855 assert_eq!(pending.take_with(|| Ok(3)).unwrap(), Some(3));
3856 }
3857
3858 #[test]
3859 fn pending_status_reports_each_publication_once_and_retries_validation() {
3860 let pending = PendingStatus::default();
3861 for _ in 0..2 {
3862 pending.publish();
3863 assert!(matches!(
3864 pending.take_with::<()>(|| Err(Error::ConnectionLost)),
3865 Err(Error::ConnectionLost)
3866 ));
3867 assert!(pending
3868 .take_with::<()>(|| Err(Error::ConnectionLost))
3869 .unwrap()
3870 .is_none());
3871 assert!(pending.is_pending());
3872 }
3873 assert_eq!(pending.take_with(|| Ok(7)).unwrap(), Some(7));
3874 assert!(!pending.is_pending());
3875 }
3876
3877 #[test]
3878 fn pending_status_defers_failure_reporting_when_another_event_is_ready() {
3879 let pending = PendingStatus::default();
3880 pending.publish();
3881 assert_eq!(
3882 pending
3883 .take_or_else_with(|| Err(Error::ConnectionLost), || Some(7))
3884 .unwrap(),
3885 Some(7)
3886 );
3887 assert!(matches!(
3888 pending.take_with::<()>(|| Err(Error::ConnectionLost)),
3889 Err(Error::ConnectionLost)
3890 ));
3891 }
3892
3893 #[test]
3894 fn pending_status_failure_has_one_competing_reporter() {
3895 let pending = PendingStatus::default();
3896 pending.publish();
3897 let barrier = std::sync::Barrier::new(2);
3898 std::thread::scope(|scope| {
3899 let workers: Vec<_> = (0..2)
3900 .map(|_| {
3901 scope.spawn(|| {
3902 pending
3903 .take_with::<()>(|| {
3904 barrier.wait();
3905 Err(Error::ConnectionLost)
3906 })
3907 .is_err()
3908 })
3909 })
3910 .collect();
3911 assert_eq!(
3912 workers
3913 .into_iter()
3914 .map(|worker| worker.join().unwrap())
3915 .filter(|reported| *reported)
3916 .count(),
3917 1
3918 );
3919 });
3920 assert!(pending.is_pending());
3921 }
3922
3923 #[test]
3924 fn pending_status_validation_has_one_competing_consumer() {
3925 let pending = PendingStatus::default();
3926 pending.publish();
3927 let barrier = std::sync::Barrier::new(2);
3928 std::thread::scope(|scope| {
3929 let workers: Vec<_> = (0..2)
3930 .map(|_| {
3931 scope.spawn(|| {
3932 pending
3933 .take_with(|| {
3934 barrier.wait();
3935 Ok(())
3936 })
3937 .unwrap()
3938 .is_some()
3939 })
3940 })
3941 .collect();
3942 assert_eq!(
3943 workers
3944 .into_iter()
3945 .map(|worker| worker.join().unwrap())
3946 .filter(|taken| *taken)
3947 .count(),
3948 1
3949 );
3950 });
3951 assert!(!pending.is_pending());
3952 }
3953
3954 #[test]
3955 fn pending_status_survives_an_invalid_next_event_timeout() {
3956 let Some(ndi) = crate::test_support::ndi() else {
3957 return;
3958 };
3959 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3960 receiver.core.pending.status.publish();
3961 assert!(receiver.next_event(Duration::MAX).is_err());
3962 assert!(receiver.core.pending.status.is_pending());
3963 assert!(matches!(
3964 receiver.next_event(Duration::ZERO).unwrap(),
3965 Some(ReceiverEvent::StatusChanged(_))
3966 ));
3967 assert!(!receiver.core.pending.status.is_pending());
3968 }
3969
3970 #[test]
3971 fn every_receiver_wait_refuses_a_timeout_above_max_timeout() {
3972 let Some(ndi) = crate::test_support::ndi() else {
3973 return;
3974 };
3975 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3976 let excessive = crate::MAX_TIMEOUT + Duration::from_nanos(1);
3977 for result in [
3978 receiver.capture_video(excessive).map(drop),
3979 receiver.capture_audio_ref(excessive).map(drop),
3980 receiver.capture_metadata(excessive).map(drop),
3981 receiver.capture_any(excessive).map(drop),
3982 receiver.capture_any_ref(excessive).map(drop),
3983 receiver.next_event(excessive).map(drop),
3984 receiver.wait_for_source_name_change(excessive).map(drop),
3985 ] {
3986 assert!(matches!(result, Err(Error::InvalidInput(_))), "{result:?}");
3987 }
3988 }
3989
3990 #[test]
3991 fn concurrent_status_pollers_take_once_and_later_publications_survive() {
3992 let Some(ndi) = crate::test_support::ndi() else {
3993 return;
3994 };
3995 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
3996 receiver.core.pending.status.publish();
3997 let barrier = std::sync::Barrier::new(3);
3998 std::thread::scope(|scope| {
3999 let handles: Vec<_> = (0..2)
4000 .map(|_| {
4001 let receiver = &receiver;
4002 let barrier = &barrier;
4003 scope.spawn(move || {
4004 barrier.wait();
4005 receiver.core.take_pending_status().unwrap().is_some()
4006 })
4007 })
4008 .collect();
4009 barrier.wait();
4010 assert_eq!(
4011 handles
4012 .into_iter()
4013 .map(|h| usize::from(h.join().unwrap()))
4014 .sum::<usize>(),
4015 1
4016 );
4017 });
4018 receiver.core.pending.status.publish();
4019 assert!(receiver.core.take_pending_status().unwrap().is_some());
4020 }
4021
4022 #[test]
4023 fn source_query_permit_excludes_another_issuer_until_drop() {
4024 let Some(ndi) = crate::test_support::ndi() else {
4025 return;
4026 };
4027 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4028 let query = receiver.core.lock_source_query(Instant::now()).unwrap();
4029 assert!(receiver.core.lock_source_query(Instant::now()).is_none());
4030 drop(query);
4031 assert!(receiver.core.lock_source_query(Instant::now()).is_some());
4032 }
4033
4034 #[test]
4035 fn receiver_permissions_do_not_add_pointer_storage() {
4036 assert_eq!(
4037 std::mem::size_of::<control::Control<'_>>(),
4038 2 * std::mem::size_of::<usize>()
4039 );
4040 for bytes in [
4041 std::mem::size_of::<AdvertiserMembership<'_>>(),
4042 std::mem::size_of::<attached::Adoption<'_>>(),
4043 ] {
4044 assert_eq!(bytes, std::mem::size_of::<usize>());
4045 }
4046 #[cfg(feature = "advanced")]
4047 for bytes in [
4048 std::mem::size_of::<Exclusive<'_>>(),
4049 std::mem::size_of::<AllocatorAccess<'_>>(),
4050 ] {
4051 assert_eq!(bytes, std::mem::size_of::<usize>());
4052 }
4053 }
4054
4055 #[cfg(feature = "advanced")]
4056 #[test]
4057 fn advertiser_membership_is_independent_of_connection_and_allocator_permissions() {
4058 let Some(ndi) = crate::test_support::ndi() else {
4059 return;
4060 };
4061 let mut receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4062 let allocator = receiver.allocator_owner();
4063 let core = Arc::clone(&receiver.core);
4064 let expected = core.instance.0 as usize;
4065 {
4066 let exclusive = receiver.exclusive();
4067 assert_eq!(exclusive.instance() as usize, expected);
4068 }
4069 let permission = receiver.core.lock_change();
4070 std::thread::scope(|scope| {
4071 let (started, waiting) = std::sync::mpsc::channel();
4072 let (done, completed) = std::sync::mpsc::channel();
4073 let member = scope.spawn(move || {
4074 started.send(()).unwrap();
4075 done.send(core.advertiser_membership().instance() as usize)
4076 .unwrap();
4077 });
4078 waiting.recv_timeout(Duration::from_secs(2)).unwrap();
4079 let concurrent = completed.recv_timeout(Duration::from_secs(2));
4080 drop(permission);
4081 member.join().unwrap();
4082 assert_eq!(
4083 concurrent.expect("membership waited for the change permit"),
4084 expected
4085 );
4086 });
4087 let access = allocator.access();
4089 let removal = receiver.core.advertiser_membership();
4090 assert_eq!(access.instance(), removal.instance());
4091 }
4092
4093 #[cfg(all(feature = "advanced", ndi_has_advanced_receive_allocators))]
4094 #[test]
4095 fn retiring_an_allocator_policy_releases_receiver_permission_before_user_drop() {
4096 use crate::advanced::{AllocationBuffer, AllocatorService};
4097 use std::sync::atomic::{AtomicBool, Ordering};
4098 struct ObserveDrop {
4099 core: Arc<ReceiverCore>,
4100 available: Arc<AtomicBool>,
4101 }
4102 impl Drop for ObserveDrop {
4103 fn drop(&mut self) {
4104 self.available.store(
4107 self.core.control_guard.try_lock().is_some(),
4108 Ordering::Release,
4109 );
4110 }
4111 }
4112 let Some(ndi) = crate::test_support::ndi() else {
4113 return;
4114 };
4115 if !crate::test_support::require_feature(
4116 ndi.require_feature(crate::RuntimeFeature::ReceiveAllocators),
4117 ) {
4118 return;
4119 }
4120 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4121 let available = Arc::new(AtomicBool::new(false));
4122 let observer = ObserveDrop {
4123 core: Arc::clone(&receiver.core),
4124 available: Arc::clone(&available),
4125 };
4126 let service = AllocatorService::for_test(ndi.process_lifetime());
4127 let mut allocated = service.attach(receiver).unwrap();
4128 allocated
4129 .set_video_allocator(move |request| {
4130 let _ = &observer;
4131 AllocationBuffer::zeroed(request)
4132 })
4133 .unwrap();
4134 allocated.reset_video_allocator();
4135 assert!(
4136 available.load(Ordering::Acquire),
4137 "policy destructor ran under receiver permission"
4138 );
4139 }
4140
4141 #[test]
4142 fn connection_target_waits_for_neither_captures_nor_queued_connection_changes() {
4143 let Some(ndi) = crate::test_support::ndi() else {
4144 return;
4145 };
4146 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4147 let expected = receiver.connection_target();
4148 let connection = receiver.core.lock_change();
4149 std::thread::scope(|scope| {
4150 let (started, waiting) = std::sync::mpsc::channel();
4151 let receiver = &receiver;
4152 let reconnect = scope.spawn(move || {
4153 started.send(()).unwrap();
4154 receiver.reconnect();
4155 });
4156 waiting.recv_timeout(Duration::from_secs(2)).unwrap();
4157 let (done, completed) = std::sync::mpsc::channel();
4158 let getter = scope.spawn(move || {
4159 done.send(receiver.connection_target()).unwrap();
4160 });
4161 let snapshot = completed.recv_timeout(Duration::from_secs(2));
4162 drop(connection);
4165 getter.join().unwrap();
4166 reconnect.join().unwrap();
4167 assert_eq!(snapshot.expect("the getter waited for capture"), expected);
4168 });
4169 assert_eq!(receiver.connection_target(), expected);
4170 }
4171
4172 #[test]
4173 fn reconnect_returns_while_a_capture_attempt_is_in_flight() {
4174 struct FinishTrace(bool);
4175 impl Drop for FinishTrace {
4176 fn drop(&mut self) {
4177 if self.0 {
4178 eprintln!("receiver-watchdog: reconnect case finished");
4179 }
4180 }
4181 }
4182 let diagnostics = std::env::var("GRAFTON_NDI_RECEIVER_DIAGNOSTICS").as_deref() == Ok("1");
4183 let trace = |phase| {
4184 if diagnostics {
4185 eprintln!("receiver-watchdog: reconnect {phase}");
4186 }
4187 };
4188 let _finish = FinishTrace(diagnostics);
4189 trace("case started");
4190 let Some(ndi) = crate::test_support::ndi() else {
4191 return;
4192 };
4193 let receiver = Receiver::new(&ndi, &ReceiverOptions::new(test_source())).unwrap();
4194 trace("receiver created");
4195 std::thread::scope(|scope| {
4196 let (done, completed) = std::sync::mpsc::channel();
4197 let result = {
4198 let _attempt = receiver
4199 .core
4200 .capture_lock(Attempt(Deadline::after(Duration::from_secs(1)).unwrap()));
4201 trace("capture attempt acquired");
4202 let receiver = &receiver;
4203 scope.spawn(move || {
4204 trace("entering Receiver::reconnect");
4205 receiver.reconnect();
4206 trace("returned from Receiver::reconnect");
4207 done.send(()).unwrap();
4208 });
4209 completed.recv_timeout(Duration::from_secs(2))
4212 };
4213 trace("capture attempt released");
4214 result.expect("reconnect waited for the capture attempt");
4215 });
4216 trace("destroying receiver");
4217 drop(receiver);
4218 }
4219
4220 #[test]
4221 fn combined_and_event_consumers_compete_for_one_retained_invalidation() {
4222 let Some(ndi) = crate::test_support::ndi() else {
4223 return;
4224 };
4225 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4226 receiver
4227 .core
4228 .capture_result::<VideoKind>(Delivered::Notification(Notification::Unknown(987)))
4229 .unwrap();
4230 let barrier = std::sync::Barrier::new(3);
4231 std::thread::scope(|scope| {
4232 let combined = scope.spawn(|| {
4233 barrier.wait();
4234 matches!(
4235 receiver.capture_any(Duration::ZERO).unwrap(),
4236 Some(ReceiverItem::Event(ReceiverEvent::Unknown(987)))
4237 )
4238 });
4239 let events = scope.spawn(|| {
4240 barrier.wait();
4241 matches!(
4242 receiver.next_event(Duration::ZERO).unwrap(),
4243 Some(ReceiverEvent::Unknown(987))
4244 )
4245 });
4246 barrier.wait();
4247 assert_eq!(
4248 usize::from(combined.join().unwrap()) + usize::from(events.join().unwrap()),
4249 1
4250 );
4251 });
4252 receiver.core.retain(Notification::Unknown(988));
4253 assert!(matches!(
4254 receiver.capture_any(Duration::ZERO).unwrap(),
4255 Some(ReceiverItem::Event(ReceiverEvent::Unknown(988)))
4256 ));
4257 }
4258
4259 #[test]
4260 fn receiver_mode_transitions_preserve_pending_status_and_core_identity() {
4261 let Some(ndi) = crate::test_support::ndi() else {
4262 return;
4263 };
4264 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4265 let original_core = Arc::as_ptr(&receiver.core);
4266 receiver.core.pending.status.publish();
4267 let fs = crate::FrameSync::new(receiver).unwrap();
4268 assert!(fs.receiver().core.pending.status.is_pending());
4269 assert_eq!(Arc::as_ptr(&fs.receiver().core), original_core);
4270 let receiver = fs.into_receiver();
4271 assert!(matches!(
4272 receiver.next_event(Duration::ZERO).unwrap(),
4273 Some(ReceiverEvent::StatusChanged(_))
4274 ));
4275 assert!(!receiver.core.pending.status.is_pending());
4276 assert_eq!(Arc::as_ptr(&receiver.core), original_core);
4277 assert_eq!(
4278 std::mem::size_of::<Receiver>(),
4279 std::mem::size_of::<Receiver<FrameSyncAttached>>()
4280 );
4281 }
4282
4283 #[test]
4284 fn value_types_read_back_what_the_sdk_reported() {
4285 assert_eq!(SettingChange::from_sdk(true), SettingChange::Applied);
4286 assert_eq!(SettingChange::from_sdk(false), SettingChange::Unchanged);
4287 let idle = ConnectionStats::default();
4288 assert!(!idle.is_connected());
4289 assert_eq!(idle.connections(), 0);
4290 assert_eq!(idle.video_drop_percentage(), 0.0);
4291 let stats = ConnectionStats {
4292 connections: 1,
4293 video_frames_received: 900,
4294 video_frames_dropped: 100,
4295 audio_frames_received: 3,
4296 metadata_frames_dropped: 1,
4297 video_frames_queued: 5,
4298 ..idle
4299 };
4300 assert!(stats.is_connected());
4301 assert!((stats.video_drop_percentage() - 100.0 / 9.0).abs() < 1e-12);
4302 assert_eq!(stats.audio_drop_percentage(), 0.0);
4303 assert_eq!(stats.metadata_drop_percentage(), 0.0);
4304 let per_media = ConnectionStats {
4305 audio_frames_received: 1000,
4306 audio_frames_dropped: 100,
4307 metadata_frames_received: 350,
4308 metadata_frames_dropped: 285,
4309 ..stats
4310 };
4311 assert_eq!(per_media.audio_drop_percentage(), 10.0);
4312 assert!((per_media.metadata_drop_percentage() - 81.42857142857143).abs() < 1e-12);
4313 assert_eq!(
4314 (
4315 stats.video_frames_received(),
4316 stats.audio_frames_received(),
4317 stats.video_frames_queued()
4318 ),
4319 (900, 3, 5)
4320 );
4321 assert_eq!(ReceiverStatus { connections: 2 }.connections(), 2);
4322 }
4323
4324 #[test]
4325 fn drop_rates_handle_extreme_public_counters() {
4326 assert_eq!(drop_percentage(0, 0), 0.0);
4327 assert_eq!(drop_percentage(1000, 0), 0.0);
4328 assert_eq!(drop_percentage(1000, 1000), 100.0);
4329 assert_eq!(drop_percentage(1000, 100), 10.0);
4330 assert!((drop_percentage(900, 100) - 100.0 / 9.0).abs() < 1e-12);
4331 assert!((drop_percentage(350, 285) - 81.42857142857143).abs() < 1e-12);
4332 assert_eq!(drop_percentage(u64::MAX, u64::MAX), 100.0);
4333 assert_eq!(drop_percentage(0, u64::MAX), 0.0);
4334 assert_eq!(drop_percentage(1, u64::MAX), 100.0);
4335 }
4336
4337 #[test]
4338 fn ptz_rejects_invalid_commands_before_calling_sdk() {
4339 let Some(ndi) = crate::test_support::ndi() else {
4340 return;
4341 };
4342 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4343 let ptz = receiver.ptz();
4344 for result in [
4345 ptz.recall_preset(u8::MAX, 0.5),
4346 ptz.recall_preset(100, 0.5),
4347 ptz.recall_preset(0, f32::NAN),
4348 ptz.store_preset(100),
4349 ptz.zoom(f32::INFINITY),
4350 ptz.zoom_speed(-1.1),
4351 ptz.pan_tilt(0.0, 1.1),
4352 ptz.pan_tilt_speed(f32::NAN, 0.0),
4353 ptz.focus(-0.1),
4354 ptz.focus_speed(1.1),
4355 ptz.white_balance_manual(0.0, 1.1),
4356 ptz.exposure_manual(f32::NEG_INFINITY),
4357 ptz.exposure_manual_detailed(0.5, f32::NAN, 0.5),
4358 ] {
4359 assert!(matches!(result, Err(Error::InvalidInput(_))));
4360 }
4361 assert_eq!(validate_ptz_preset(0).unwrap(), 0);
4362 assert_eq!(validate_ptz_preset(99).unwrap(), 99);
4363 assert!(validate_ptz_value("speed", -1.0, -1.0, 1.0).is_ok());
4364 assert!(validate_ptz_value("speed", 1.0, -1.0, 1.0).is_ok());
4365 }
4366
4367 #[test]
4368 fn outbound_controls_accept_invocation_without_a_source() {
4369 let Some(ndi) = crate::test_support::ndi() else {
4370 return;
4371 };
4372 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4373 receiver.set_tally(Tally::new(true, false));
4376 let frame = MetadataFrame::new("<ndi_text>é</ndi_text>")
4377 .unwrap()
4378 .with_timecode(crate::Timecode::from_ticks(42));
4379 let pointer = frame.metadata_raw().p_data;
4380 for _ in 0..3 {
4381 let sent = receiver.send_metadata(&frame);
4382 assert!(
4383 matches!(sent, Ok(()) | Err(Error::NotConnected)),
4384 "{sent:?}"
4385 );
4386 assert_eq!(frame.metadata_raw().p_data, pointer);
4387 }
4388 }
4389
4390 #[test]
4391 fn legacy_controls_refuse_changes_without_blocking_getters_or_losing_tally() {
4392 let Some(ndi) = crate::test_support::ndi() else {
4393 return;
4394 };
4395 let mut receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4396 Arc::get_mut(&mut receiver.core)
4397 .unwrap()
4398 .guard_local_connection_changes = true;
4399 let change = receiver.core.lock_change();
4400 assert!(matches!(
4401 receiver.core.lock_mutating_control(),
4402 Err(Error::NotConnected)
4403 ));
4404 receiver.set_tally(Tally::new(true, false));
4405 receiver.set_tally(Tally::new(false, true));
4406 assert_eq!(
4407 receiver.core.lock_control().pending_tally(),
4408 Some(Tally::new(false, true))
4409 );
4410 let metadata = MetadataFrame::new("<during-change/>").unwrap();
4411 assert!(matches!(
4412 receiver.send_metadata(&metadata),
4413 Err(Error::NotConnected)
4414 ));
4415 assert!(matches!(receiver.ptz().zoom(0.5), Err(Error::NotConnected)));
4416 assert!(!receiver.ptz().is_supported());
4417 receiver.connection_stats().unwrap();
4419 drop(change);
4420 let control = receiver.core.lock_control();
4421 assert_eq!(control.pending_tally(), None);
4422 drop(control);
4423 assert!(receiver.core.lock_mutating_control().is_ok());
4424 }
4425
4426 #[test]
4427 fn shared_controls_proceed_during_local_connection_changes() {
4428 let Some(ndi) = crate::test_support::ndi() else {
4429 return;
4430 };
4431 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4432 let exclusive = receiver.core.lock_change();
4433 std::thread::scope(|scope| {
4434 let (done, completed) = std::sync::mpsc::channel();
4435 let receiver = &receiver;
4436 let worker = scope.spawn(move || {
4437 receiver.set_tally(Tally::new(false, false));
4438 let _ = receiver.ptz().is_supported();
4439 receiver.connection_stats().unwrap();
4440 done.send(()).unwrap();
4441 });
4442 let result = completed.recv_timeout(Duration::from_secs(2));
4443 drop(exclusive);
4444 worker.join().unwrap();
4445 result.expect("shared controls waited for a local connection change");
4446 });
4447 }
4448
4449 #[test]
4450 fn shared_controls_serialize_with_one_another() {
4451 let Some(ndi) = crate::test_support::ndi() else {
4452 return;
4453 };
4454 let receiver = Receiver::new(&ndi, &unconnected()).unwrap();
4455 for control in [
4459 |receiver: &Receiver| receiver.set_tally(Tally::new(false, false)),
4460 |receiver: &Receiver| {
4461 let _ = receiver.ptz().is_supported();
4462 },
4463 |receiver: &Receiver| {
4464 receiver.connection_stats().unwrap();
4465 },
4466 ] {
4467 let exclusive = receiver.core.lock_control();
4468 std::thread::scope(|scope| {
4469 let (started, entering) = std::sync::mpsc::channel();
4470 let (done, completed) = std::sync::mpsc::channel();
4471 let receiver = &receiver;
4472 let worker = scope.spawn(move || {
4473 started.send(()).unwrap();
4474 control(receiver);
4475 done.send(()).unwrap();
4476 });
4477 entering.recv_timeout(Duration::from_secs(2)).unwrap();
4478 let early = completed.recv_timeout(Duration::from_millis(20));
4479 drop(exclusive);
4480 worker.join().unwrap();
4481 assert!(matches!(
4482 early,
4483 Err(std::sync::mpsc::RecvTimeoutError::Timeout)
4484 ));
4485 completed.recv_timeout(Duration::from_secs(2)).unwrap();
4486 });
4487 }
4488 }
4489
4490 #[test]
4491 fn receiver_color_format_maps_to_exact_sdk_values() {
4492 assert_eq!(
4493 ReceiverColorFormat::BgrxBgra.to_sdk(),
4494 NDIlib_recv_color_format_e_NDIlib_recv_color_format_BGRX_BGRA
4495 );
4496 assert_eq!(
4497 ReceiverColorFormat::UyvyBgra.to_sdk(),
4498 NDIlib_recv_color_format_e_NDIlib_recv_color_format_UYVY_BGRA
4499 );
4500 assert_eq!(
4501 ReceiverColorFormat::RgbxRgba.to_sdk(),
4502 NDIlib_recv_color_format_e_NDIlib_recv_color_format_RGBX_RGBA
4503 );
4504 assert_eq!(
4505 ReceiverColorFormat::UyvyRgba.to_sdk(),
4506 NDIlib_recv_color_format_e_NDIlib_recv_color_format_UYVY_RGBA
4507 );
4508 assert_eq!(
4509 ReceiverColorFormat::Fastest.to_sdk(),
4510 NDIlib_recv_color_format_e_NDIlib_recv_color_format_fastest
4511 );
4512 assert_eq!(
4513 ReceiverColorFormat::Best.to_sdk(),
4514 NDIlib_recv_color_format_e_NDIlib_recv_color_format_best
4515 );
4516 }
4517
4518 #[test]
4519 fn receiver_bandwidth_maps_to_exact_sdk_values() {
4520 assert_eq!(
4521 ReceiverBandwidth::MetadataOnly.to_sdk(),
4522 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_metadata_only
4523 );
4524 assert_eq!(
4525 ReceiverBandwidth::AudioOnly.to_sdk(),
4526 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_audio_only
4527 );
4528 assert_eq!(
4529 ReceiverBandwidth::Lowest.to_sdk(),
4530 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_lowest
4531 );
4532 assert_eq!(
4533 ReceiverBandwidth::Highest.to_sdk(),
4534 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest
4535 );
4536 }
4537
4538 struct TestSettings {
4539 raw: NDIlib_recv_create_v3_t,
4540 _target: Option<RetainedSource>,
4541 _name: Option<CString>,
4542 }
4543
4544 fn raw_settings(options: &ReceiverOptions) -> TestSettings {
4545 sys::with_test_evidence("6.4.0.2", |evidence| {
4546 let target = options.configured_source().map(RetainedSource::new);
4547 let name = options
4548 .name
4549 .as_deref()
4550 .map(CString::new)
4551 .transpose()
4552 .unwrap();
4553 let raw = *options
4554 .validate_runtime(evidence)
4555 .unwrap()
4556 .settings(target.as_ref(), name.as_deref())
4557 .raw();
4558 TestSettings {
4559 raw,
4560 _target: target,
4561 _name: name,
4562 }
4563 })
4564 }
4565
4566 #[test]
4567 fn creation_settings_borrow_the_retained_targets_own_pointers() {
4568 let source = Source::new("creation target")
4569 .unwrap()
4570 .with_address(crate::SourceAddress::new("192.0.2.19:5960").unwrap());
4571 let target = RetainedSource::new(&source);
4572 let options = ReceiverOptions::new(source).name("retained receiver");
4573 let name = CString::new("retained receiver").unwrap();
4574 sys::with_test_evidence("6.4.0.2", |evidence| {
4575 let validated = options.validate_runtime(evidence).unwrap();
4576 let settings = validated.settings(Some(&target), Some(&name));
4577 let raw = settings.raw();
4578 assert_eq!(
4579 raw.source_to_connect_to.p_ndi_name,
4580 target.descriptor().p_ndi_name
4581 );
4582 assert_eq!(
4584 unsafe { raw.source_to_connect_to.__bindgen_anon_1.p_url_address },
4585 unsafe { target.descriptor().__bindgen_anon_1.p_url_address }
4586 );
4587 assert_eq!(raw.p_ndi_recv_name, name.as_ptr());
4588 });
4589 }
4590
4591 #[test]
4592 fn receiver_options_defaults_emit_operational_raw_modes() {
4593 let raw = raw_settings(&unconnected());
4594
4595 assert_raw_receiver_modes(
4596 &raw,
4597 NDIlib_recv_color_format_e_NDIlib_recv_color_format_BGRX_BGRA,
4598 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest,
4599 );
4600 assert!(raw.raw.allow_video_fields);
4601 assert!(raw.raw.source_to_connect_to.p_ndi_name.is_null());
4602 assert!(unsafe { raw.raw.source_to_connect_to.__bindgen_anon_1.p_url_address }.is_null());
4604 }
4605
4606 #[test]
4607 fn snapshot_preset_emits_operational_raw_modes() {
4608 let raw = raw_settings(&ReceiverOptions::snapshot_preset(test_source()));
4609
4610 assert_raw_receiver_modes(
4611 &raw,
4612 NDIlib_recv_color_format_e_NDIlib_recv_color_format_RGBX_RGBA,
4613 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_lowest,
4614 );
4615 assert!(!raw.raw.allow_video_fields);
4616 }
4617
4618 #[test]
4619 fn high_quality_preset_emits_operational_raw_modes() {
4620 let raw = raw_settings(&ReceiverOptions::high_quality_preset(test_source()));
4621
4622 assert_raw_receiver_modes(
4623 &raw,
4624 NDIlib_recv_color_format_e_NDIlib_recv_color_format_RGBX_RGBA,
4625 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest,
4626 );
4627 assert!(raw.raw.allow_video_fields);
4628 }
4629
4630 #[test]
4631 fn monitoring_preset_emits_operational_raw_modes() {
4632 let raw = raw_settings(&ReceiverOptions::monitoring_preset(test_source()));
4633
4634 assert_raw_receiver_modes(
4635 &raw,
4636 NDIlib_recv_color_format_e_NDIlib_recv_color_format_BGRX_BGRA,
4637 NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_metadata_only,
4638 );
4639 assert!(!raw.raw.allow_video_fields);
4640 }
4641
4642 #[test]
4643 fn retry_notifications_reach_a_queued_frame_without_sleeping() {
4644 for count in 1..=IMMEDIATE_NOTIFICATION_RETRIES {
4645 let clock = FakeClock::new();
4646 let mut calls = 0;
4647 let result = capture_within_clock(
4648 clock.deadline(Duration::from_secs(1)),
4649 |_| {
4650 calls += 1;
4651 Ok(if calls <= count {
4652 Retry::Progress
4653 } else {
4654 Retry::Item(42)
4655 })
4656 },
4657 || clock.now(),
4658 |_| panic!("a queued frame after a notification must not be delayed"),
4659 );
4660 assert_eq!(result.unwrap(), Some(42));
4661 assert_eq!(calls, count + 1);
4662 }
4663 }
4664
4665 #[test]
4666 fn cancellation_stops_before_another_attempt_or_pending_event() {
4667 assert_eq!(std::mem::size_of::<NeverStop>(), 0);
4668 for progress in [false, true] {
4669 let clock = FakeClock::new();
4670 let cancelled = AtomicBool::new(false);
4671 let mut calls = 0;
4672 let mut pending = false;
4673 let result: Result<Option<()>> = capture_within_clock_with_stop(
4674 clock.deadline(Duration::from_secs(30)),
4675 &cancelled,
4676 |_| {
4677 calls += 1;
4678 assert!(!pending, "a stopped retry consumed the pending event");
4679 pending = true;
4680 cancelled.store(true, Ordering::Release);
4681 Ok(if progress {
4682 Retry::Progress
4683 } else {
4684 Retry::Idle
4685 })
4686 },
4687 || clock.now(),
4688 |pause| clock.advance(pause),
4689 );
4690 assert!(result.unwrap().is_none());
4691 assert_eq!(calls, 1);
4692 assert!(pending);
4693 }
4694 }
4695
4696 #[test]
4697 fn cancellation_preserves_the_item_from_the_attempt_in_flight() {
4698 let clock = FakeClock::new();
4699 let cancelled = AtomicBool::new(false);
4700 let result = capture_within_clock_with_stop(
4701 clock.deadline(Duration::from_secs(30)),
4702 &cancelled,
4703 |_| {
4704 cancelled.store(true, Ordering::Release);
4705 Ok(Some(42))
4706 },
4707 || clock.now(),
4708 |_| panic!("delivered items must not wait again"),
4709 );
4710 assert_eq!(result.unwrap(), Some(42));
4711 }
4712
4713 #[test]
4714 fn retry_notification_storm_is_bounded_and_idle_still_backs_off() {
4715 for idle in [false, true] {
4716 let clock = FakeClock::new();
4717 let mut calls = 0;
4718 let mut sleeps = 0;
4719 let result: Result<Option<()>> = capture_within_clock(
4720 clock.deadline(Duration::from_millis(25)),
4721 |_| {
4722 calls += 1;
4723 Ok(if idle && calls % 2 == 0 {
4724 Retry::Idle
4725 } else {
4726 Retry::Progress
4727 })
4728 },
4729 || clock.now(),
4730 |pause| {
4731 sleeps += 1;
4732 clock.advance(pause);
4733 },
4734 );
4735 assert!(result.unwrap().is_none());
4736 assert_eq!(sleeps, 3);
4737 assert!(calls <= 3 * (IMMEDIATE_NOTIFICATION_RETRIES + 1));
4738 assert_eq!(clock.elapsed(), Duration::from_millis(25));
4739 }
4740 }
4741
4742 #[test]
4743 fn retry_zero_or_spent_budget_observes_only_one_notification() {
4744 for spent in [Duration::ZERO, Duration::from_millis(30)] {
4745 let clock = FakeClock::new();
4746 let deadline = clock.deadline(Duration::ZERO);
4747 clock.advance(spent);
4748 let mut calls = 0;
4749 let result: Result<Option<()>> = capture_within_clock(
4750 deadline,
4751 |attempt| {
4752 calls += 1;
4753 assert!(clock.timeout(attempt).is_zero());
4754 Ok(Retry::Progress)
4755 },
4756 || clock.now(),
4757 |_| panic!("spent budgets must not sleep"),
4758 );
4759 assert!(result.unwrap().is_none());
4760 assert_eq!(calls, 1);
4761 }
4762 }
4763
4764 #[test]
4765 fn retry_caps_sub_poll_timeout_to_total_budget() {
4766 let clock = FakeClock::new();
4767 let mut polls = Vec::new();
4768
4769 let result = capture_within_clock(
4770 clock.deadline(Duration::from_millis(25)),
4771 |attempt| {
4772 polls.push(clock.timeout(attempt));
4773 Ok(Some(42))
4774 },
4775 || clock.now(),
4776 |_| {},
4777 );
4778
4779 assert_eq!(result.unwrap(), Some(42));
4780 assert_eq!(polls, [Duration::from_millis(25)]);
4781 }
4782
4783 #[test]
4784 fn retry_shrinks_later_poll_to_remaining_budget() {
4785 let clock = FakeClock::new();
4786 let mut polls = Vec::new();
4787 let mut sleeps = Vec::new();
4788
4789 let result: Result<Option<i32>> = capture_within_clock(
4790 clock.deadline(Duration::from_millis(110)),
4791 |attempt| {
4792 let poll = clock.timeout(attempt);
4793 polls.push(poll);
4794 if polls.len() == 1 {
4795 clock.advance(Duration::from_millis(5));
4796 } else {
4797 clock.advance(poll);
4798 }
4799 Ok(None)
4800 },
4801 || clock.now(),
4802 |sleep| {
4803 sleeps.push(sleep);
4804 clock.advance(sleep);
4805 },
4806 );
4807
4808 assert!(result.unwrap().is_none());
4809 assert_eq!(
4810 polls,
4811 [Duration::from_millis(100), Duration::from_millis(95)]
4812 );
4813 assert_eq!(sleeps, [Duration::from_millis(10)]);
4814 }
4815
4816 #[test]
4817 fn retry_zero_timeout_success_makes_one_nonblocking_attempt() {
4818 let clock = FakeClock::new();
4819 let mut polls = Vec::new();
4820
4821 let result = capture_within_clock(
4822 clock.deadline(Duration::ZERO),
4823 |attempt| {
4824 polls.push(clock.timeout(attempt));
4825 Ok(Some(42))
4826 },
4827 || clock.now(),
4828 |_| panic!("zero-timeout success should not sleep"),
4829 );
4830
4831 assert_eq!(result.unwrap(), Some(42));
4832 assert_eq!(polls, [Duration::ZERO]);
4833 }
4834
4835 #[test]
4836 fn retry_zero_timeout_miss_gives_up_after_one_attempt() {
4837 let clock = FakeClock::new();
4838 let mut polls = Vec::new();
4839
4840 let result: Result<Option<i32>> = capture_within_clock(
4841 clock.deadline(Duration::ZERO),
4842 |attempt| {
4843 polls.push(clock.timeout(attempt));
4844 Ok(None)
4845 },
4846 || clock.now(),
4847 |_| panic!("zero-timeout miss should not sleep"),
4848 );
4849
4850 assert!(result.unwrap().is_none());
4851 assert_eq!(polls, [Duration::ZERO]);
4852 }
4853
4854 #[test]
4855 fn retry_stops_when_an_attempt_spends_the_budget() {
4856 let clock = FakeClock::new();
4857 let mut polls = Vec::new();
4858
4859 let result: Result<Option<i32>> = capture_within_clock(
4860 clock.deadline(Duration::from_millis(120)),
4861 |attempt| {
4862 polls.push(clock.timeout(attempt));
4863 clock.advance(Duration::from_millis(120));
4865 Ok(None)
4866 },
4867 || clock.now(),
4868 |_| panic!("expired timeout should not sleep"),
4869 );
4870
4871 assert!(result.unwrap().is_none());
4872 assert_eq!(polls, [POLL_INTERVAL]);
4873 }
4874
4875 #[test]
4876 fn retry_caps_sleep_to_remaining_budget() {
4877 let clock = FakeClock::new();
4878 let mut sleeps = Vec::new();
4879
4880 let mut attempts = 0;
4881
4882 let result: Result<Option<i32>> = capture_within_clock(
4883 clock.deadline(Duration::from_millis(105)),
4884 |attempt| {
4885 attempts += 1;
4886 assert_eq!(clock.timeout(attempt), POLL_INTERVAL);
4887 clock.advance(Duration::from_millis(99));
4889 Ok(None)
4890 },
4891 || clock.now(),
4892 |sleep| {
4893 sleeps.push(sleep);
4894 clock.advance(sleep);
4895 },
4896 );
4897
4898 assert!(result.unwrap().is_none());
4899 assert_eq!(attempts, 1);
4900 assert_eq!(sleeps, [Duration::from_millis(6)]);
4901 }
4902
4903 #[test]
4904 fn retry_follows_a_full_wait_at_once() {
4905 let clock = FakeClock::new();
4909 let mut polls = Vec::new();
4910
4911 let result: Result<Option<i32>> = capture_within_clock(
4912 clock.deadline(Duration::from_millis(250)),
4913 |attempt| {
4914 let poll = clock.timeout(attempt);
4915 polls.push(poll);
4916 clock.advance(poll);
4917 Ok(None)
4918 },
4919 || clock.now(),
4920 |_| panic!("an attempt that waited out its timeout must not be followed by a pause"),
4921 );
4922
4923 assert!(result.unwrap().is_none());
4924 assert_eq!(clock.elapsed(), Duration::from_millis(250));
4925 assert_eq!(
4926 polls,
4927 [
4928 Duration::from_millis(100),
4929 Duration::from_millis(100),
4930 Duration::from_millis(50),
4931 ]
4932 );
4933 }
4934
4935 #[test]
4936 fn retry_pauses_only_after_an_early_return() {
4937 let clock = FakeClock::new();
4940 let mut polls = Vec::new();
4941 let mut sleeps = Vec::new();
4942 let waits = [3, 0, 100].map(Duration::from_millis);
4943
4944 let result = capture_within_clock(
4945 clock.deadline(Duration::from_secs(1)),
4946 |attempt| {
4947 let Some(wait) = waits.get(polls.len()).copied() else {
4948 return Ok(Some(42));
4949 };
4950 polls.push(clock.timeout(attempt));
4951 clock.advance(wait);
4952 Ok(None)
4953 },
4954 || clock.now(),
4955 |sleep| {
4956 sleeps.push(sleep);
4957 clock.advance(sleep);
4958 },
4959 );
4960
4961 assert_eq!(result.unwrap(), Some(42));
4962 assert_eq!(polls, [Duration::from_millis(100); 3]);
4963 assert_eq!(sleeps, [EARLY_RETURN_PAUSE; 2]);
4964 assert_eq!(clock.elapsed(), Duration::from_millis(123));
4966 }
4967
4968 #[test]
4969 fn every_attempt_ends_within_one_poll_interval_and_the_callers_deadline() {
4970 let clock = FakeClock::new();
4973 let deadline = clock.deadline(Duration::from_millis(1000));
4974 let waits = [3, 100, 0, 130, 100, 40].map(Duration::from_millis);
4975 let mut attempts = 0;
4976
4977 let result: Result<Option<i32>> = capture_within_clock(
4978 deadline,
4979 |attempt| {
4980 assert!(attempt.0.end() <= deadline.end());
4981 assert!(attempt.0.end() <= clock.now() + POLL_INTERVAL);
4982 clock.advance(waits[attempts % waits.len()]);
4983 attempts += 1;
4984 Ok(None)
4985 },
4986 || clock.now(),
4987 |sleep| clock.advance(sleep),
4988 );
4989
4990 assert!(result.unwrap().is_none());
4991 assert!(attempts > waits.len(), "{attempts} attempts");
4992 assert!(clock.elapsed() >= Duration::from_millis(1000));
4993 }
4994
4995 #[test]
4996 fn retry_timeout_counts_time_spent_before_the_first_attempt() {
4997 let clock = FakeClock::new();
5000 let deadline = clock.deadline(Duration::from_millis(50));
5001 clock.advance(Duration::from_millis(30));
5002 let mut polls = Vec::new();
5003
5004 let result: Result<Option<i32>> = capture_within_clock(
5005 deadline,
5006 |attempt| {
5007 let poll = clock.timeout(attempt);
5008 polls.push(poll);
5009 clock.advance(poll);
5010 Ok(None)
5011 },
5012 || clock.now(),
5013 |_| panic!("an expired budget should not sleep"),
5014 );
5015
5016 assert!(result.unwrap().is_none());
5017 assert_eq!(clock.elapsed(), Duration::from_millis(50));
5018 assert_eq!(polls, [Duration::from_millis(20)]);
5019 }
5020
5021 #[test]
5022 fn retry_with_a_spent_budget_makes_one_nonblocking_attempt() {
5023 let clock = FakeClock::new();
5024 let deadline = clock.deadline(Duration::from_millis(50));
5025 clock.advance(Duration::from_millis(70));
5026 let mut polls = Vec::new();
5027
5028 let result: Result<Option<i32>> = capture_within_clock(
5029 deadline,
5030 |attempt| {
5031 polls.push(clock.timeout(attempt));
5032 Ok(None)
5033 },
5034 || clock.now(),
5035 |_| panic!("a spent budget should not sleep"),
5036 );
5037
5038 assert!(result.unwrap().is_none());
5039 assert_eq!(polls, [Duration::ZERO]);
5040 }
5041
5042 #[test]
5043 fn capture_within_measures_the_callers_budget() {
5044 let deadline = Deadline::after(Duration::from_millis(20)).unwrap();
5045 std::thread::sleep(Duration::from_millis(5));
5046 let mut polls = Vec::new();
5047
5048 let result: Result<Option<i32>> = capture_within(deadline, NeverStop, |attempt| {
5049 polls.push(attempt.0.remaining());
5050 Ok(None)
5051 });
5052
5053 assert!(result.unwrap().is_none());
5054 assert!(!polls.is_empty());
5055 assert!(deadline.is_expired());
5057 assert!(polls[0] <= Duration::from_millis(15), "{polls:?}");
5059 }
5060
5061 #[test]
5062 fn retry_succeeds_after_retry_before_timeout() {
5063 let clock = FakeClock::new();
5064 let attempts = Cell::new(0);
5065
5066 let result = capture_within_clock(
5067 clock.deadline(Duration::from_millis(50)),
5068 |_| {
5069 attempts.set(attempts.get() + 1);
5070 if attempts.get() == 1 {
5071 Ok(None)
5072 } else {
5073 Ok(Some(42))
5074 }
5075 },
5076 || clock.now(),
5077 |sleep| clock.advance(sleep),
5078 );
5079
5080 assert_eq!(result.unwrap(), Some(42));
5081 assert_eq!(attempts.get(), 2);
5082 }
5083
5084 #[test]
5085 fn retry_propagates_error() {
5086 let clock = FakeClock::new();
5087 let attempts = Cell::new(0);
5088 let mut sleeps = Vec::new();
5089
5090 let result: Result<Option<i32>> = capture_within_clock(
5091 clock.deadline(Duration::from_secs(1)),
5092 |_| {
5093 attempts.set(attempts.get() + 1);
5094 Err::<Option<i32>, _>(Error::ConnectionLost)
5095 },
5096 || clock.now(),
5097 |sleep| sleeps.push(sleep),
5098 );
5099
5100 assert!(
5101 matches!(result, Err(Error::ConnectionLost)),
5102 "Should propagate ConnectionLost error"
5103 );
5104 assert_eq!(attempts.get(), 1);
5105 assert!(sleeps.is_empty());
5106 }
5107}
5108
5109#[cfg(ndi_test_capture_permissions)]
5112#[path = "../tests/ui/internal/capture_permissions.rs"]
5113mod capture_permission_fixture;
5114
5115#[cfg(test)]
5116#[path = "receiver/legacy_control_tests.rs"]
5117mod legacy_control_tests;