Skip to main content

grafton_ndi/
receiver.rs

1//! NDI receiving functionality for video, audio, and metadata.
2//!
3//! # Connection state and SDK status reports
4//!
5//! Poll [`Receiver::is_connected`] or [`Receiver::connection_stats`] to track
6//! connections. Losing a connection can produce no [`ReceiverEvent::StatusChanged`]
7//! event; that event reports SDK status information, such as source capabilities:
8//!
9//! ```no_run
10//! # use grafton_ndi::{Finder, FinderOptions, Ndi, Receiver, ReceiverEvent, ReceiverOptions, ReceiverBandwidth};
11//! # use std::time::Duration;
12//! # fn main() -> Result<(), grafton_ndi::Error> {
13//! # let ndi = Ndi::new()?;
14//! # let finder = Finder::new(&ndi, &FinderOptions::new())?;
15//! # let Some(source) = finder.find_source_by_name("CAMERA (Program)", Duration::from_secs(5))?
16//! # else { return Ok(()); };
17//! let options = ReceiverOptions::new(source).bandwidth(ReceiverBandwidth::MetadataOnly);
18//! let receiver = Receiver::new(&ndi, &options)?;
19//!
20//! if let Some(ReceiverEvent::StatusChanged(_)) =
21//!     receiver.next_event(Duration::from_millis(1000))?
22//! {
23//!     println!("The SDK reported a status change");
24//! }
25//! // Query connection state even when no status event arrived.
26//! println!("Connected: {}", receiver.is_connected());
27//! println!("Active connections: {}", receiver.connection_stats()?.connections());
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! See [status_monitor.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/status_monitor.rs)
33//! for a runnable connection monitor.
34
35#[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
80/// A string the receiver API returned, released when dropped.
81struct RecvStringGuard<'a> {
82    core: &'a ReceiverCore,
83    string: sys::table::Called<*const c_char>,
84    strings: &'a sys::ReceiverStrings,
85}
86impl RecvStringGuard<'_> {
87    /// The string's bytes before its terminator, or `None` for a null string.
88    ///
89    /// The scan for the terminator is bounded by
90    /// [`MAX_SDK_STRING_BYTES`](crate::sdk_copy::MAX_SDK_STRING_BYTES); a string
91    /// without one within it is an [`Error::UnexpectedSdkResult`].
92    fn bytes(&self) -> Result<Option<&[u8]>> {
93        if self.string.value().is_null() {
94            return Ok(None);
95        }
96        // SAFETY: the SDK returned a readable NUL-terminated string, which
97        // this guard keeps allocated for as long as it is borrowed.
98        let bytes = unsafe { crate::sdk_copy::sdk_text(self.string) }?;
99        Ok(Some(bytes.to_bytes()))
100    }
101
102    /// Copy the string, failing with [`Error::InvalidUtf8`] when it is not UTF-8.
103    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    /// Copy the string, replacing invalid UTF-8 with U+FFFD.
114    ///
115    /// For a value the SDK reports only once, where an error would lose it.
116    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            // SAFETY: the SDK returned this string for this instance and it is
124            // released exactly once. The RecvInstance inventory records its
125            // native connection read lock, including source-name query cleanup.
126            unsafe {
127                self.strings
128                    .NDIlib_recv_free_string(self.core.instance.0, self.string.into_value())
129            };
130        }
131    }
132}
133
134/// A receiver's native video or audio buffering delay.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
136pub struct ReceiveDelay(i32);
137
138impl ReceiveDelay {
139    /// No additional buffering.
140    pub const ZERO: Self = Self(0);
141
142    /// The largest delay supported by the SDK.
143    pub const MAX: Self = Self(2000);
144
145    /// Round positive fractional milliseconds up to the next millisecond.
146    ///
147    /// # Errors
148    ///
149    /// Returns [`Error::InvalidInput`] when the rounded delay exceeds
150    /// [`Self::MAX`].
151    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    /// The validated delay at the SDK's millisecond precision.
162    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/// A consumable report carries its publication order across an async worker.
189/// The sequence is private: only the state that published it can admit a replay.
190#[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
213/// Latest-value reports coalesce like the SDK's one-shot queries. This lock
214/// protects only bookkeeping; no SDK call or native-query permit is taken in it.
215struct 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/// A coalesced status invalidation, its failure-report bit and publication
340/// generation. Validation completes before a compare/exchange consumes that
341/// generation; a failed snapshot stays pending and reports at most once.
342#[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                // A bad status must not hide an independent notification. Do
387                // not mark its breach reported until a caller receives it.
388                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        // A failed CAS means another consumer took it or a new generation was
406        // published while validating. Neither case may consume that newer event.
407        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
420/// The pause after an attempt that returned before its own end without a
421/// value: the SDK's early return, which would otherwise busy-wait.
422const EARLY_RETURN_PAUSE: Duration = Duration::from_millis(10);
423
424/// Maximum consecutive notifications retried without yielding. An idle
425/// response always backs off; an endless notification stream must do so too.
426const 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
440/// Run `attempt` until it returns a value or `deadline` is spent: the one
441/// capture loop behind every receiver capture, for all frame kinds, for both
442/// typed capture methods and the async ones, and behind [`Receiver::next_event`]
443/// and the Advanced packet receivers' capture.
444///
445/// The SDK returns from a capture early, without a frame, while a new
446/// connection synchronizes and whenever it reports a status or source change,
447/// so one SDK call does not wait out the caller's timeout. Each attempt is
448/// handed what is left of `deadline`, which may have started before this
449/// call, narrowed to [`POLL_INTERVAL`].
450///
451/// Returns `Ok(None)` once the budget is spent without a value. An error from
452/// an attempt ends the loop.
453fn 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/// [`capture_within`] with `now` reading the clock and `sleep` pausing, so
462/// that a test can drive the loop with a clock of its own.
463///
464/// The first attempt is made even when nothing is left of `deadline`, so a
465/// spent or zero budget makes exactly one attempt, with a zero timeout.
466///
467/// Idle early returns and exhausted notification bursts are followed by
468/// [`EARLY_RETURN_PAUSE`], never past the end of `deadline`. Notifications
469/// otherwise retry immediately. An attempt that waited
470/// until its end is followed at once by the next, so that a frame arriving in
471/// between is not delayed by a pause.
472#[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            // Before the attempt's end, and so before the deadline's.
504            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/// One attempt of [`capture_within`]: the caller's deadline, narrowed to
519/// [`POLL_INTERVAL`] from when the attempt began.
520///
521/// Only [`capture_within`] makes one. [`ReceiverCore::capture_lock`] fixes the
522/// instance and runtime for its native capture, which waits only for what is
523/// left of the attempt. Cancellation and pending notifications are checked
524/// again between attempts, whatever the caller's timeout.
525#[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
550/// Send one PTZ command, the SDK function `$func` with arguments `$arg`, to
551/// the source `$ptz` controls.
552macro_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/// Operational color formats for received video frames.
559///
560/// These values are receiver configuration modes that the NDI SDK can use for
561/// normal receive operation. SDK `Max` sentinel values are intentionally not
562/// exposed in safe Rust because they are placeholders, not valid receiver
563/// modes.
564///
565/// This enum is marked `#[non_exhaustive]` so future SDK receiver modes can be
566/// added without another avoidable public enum break. Downstream `match`
567/// expressions should include a wildcard arm.
568///
569/// Choose an explicit operational value such as [`ReceiverColorFormat::Fastest`],
570/// [`ReceiverColorFormat::Best`], [`ReceiverColorFormat::RgbxRgba`], or
571/// [`ReceiverColorFormat::BgrxBgra`] for receiver configuration.
572#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
573#[non_exhaustive]
574pub enum ReceiverColorFormat {
575    /// BGRX for opaque video and BGRA when the source has alpha.
576    #[default]
577    BgrxBgra,
578    /// UYVY for opaque video and BGRA when the source has alpha.
579    UyvyBgra,
580    /// RGBX for opaque video and RGBA when the source has alpha.
581    RgbxRgba,
582    /// UYVY for opaque video and RGBA when the source has alpha.
583    UyvyRgba,
584    /// The format the SDK can deliver with the least conversion work.
585    /// Individual fields are delivered even if video fields were disabled.
586    Fastest,
587    /// The format closest to the source's native precision, including
588    /// 16-bit formats. Individual fields are delivered even if video fields
589    /// were disabled.
590    Best,
591    /// Preserve native planar 4:4:4 color when available. Requires NDI 6.4.
592    /// Individual fields are delivered, like `Best`, even if video fields were disabled.
593    Best444,
594}
595
596impl ReceiverColorFormat {
597    /// The SDK's value for this format.
598    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/// Operational bandwidth modes for receivers.
612///
613/// These values are receiver configuration modes that the NDI SDK can use for
614/// normal receive operation. SDK `Max` sentinel values are intentionally not
615/// exposed in safe Rust because they are placeholders, not valid receiver
616/// modes.
617///
618/// This enum is marked `#[non_exhaustive]` so future SDK receiver modes can be
619/// added without another avoidable public enum break. Downstream `match`
620/// expressions should include a wildcard arm.
621///
622/// Choose an explicit operational value such as [`ReceiverBandwidth::Highest`],
623/// [`ReceiverBandwidth::Lowest`], [`ReceiverBandwidth::AudioOnly`], or
624/// [`ReceiverBandwidth::MetadataOnly`] for receiver configuration.
625#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
626#[non_exhaustive]
627pub enum ReceiverBandwidth {
628    /// Receive metadata only.
629    MetadataOnly,
630    /// Receive metadata and audio, without video.
631    AudioOnly,
632    /// Receive metadata, audio and lower-bandwidth preview video.
633    Lowest,
634    /// Receive metadata, audio and full-bandwidth video.
635    #[default]
636    Highest,
637    /// Receive metadata and lower-bandwidth video, without audio. Requires NDI 6.4.
638    VideoOnlyLowest,
639    /// Receive metadata and full-bandwidth video, without audio. Requires NDI 6.4.
640    VideoOnlyHighest,
641}
642
643impl ReceiverBandwidth {
644    /// The SDK's value for this mode.
645    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/// Configuration for creating a [`Receiver`], including an optional initial
662/// source and how the receiver delivers media.
663///
664/// [`new`](Self::new) and [`disconnected`](Self::disconnected) start from the
665/// defaults. The presets start from settings suited to one use. Every setter
666/// replaces one setting.
667///
668/// # Examples
669///
670/// ```no_run
671/// # use grafton_ndi::{Ndi, Receiver, ReceiverBandwidth, ReceiverColorFormat, ReceiverOptions, Source};
672/// # fn main() -> Result<(), grafton_ndi::Error> {
673/// # let ndi = Ndi::new()?;
674/// # let source = Source::new("CAMERA (Program)").unwrap();
675/// // In real usage, obtain the source from Finder::find_sources().
676/// let options = ReceiverOptions::new(source)
677///     .color_format(ReceiverColorFormat::UyvyBgra)
678///     .bandwidth(ReceiverBandwidth::Lowest)
679///     .name("Multiviewer");
680/// let receiver = Receiver::new(&ndi, &options)?;
681/// # Ok(())
682/// # }
683/// ```
684#[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    /// A native color format that the creation settings carry in place of
694    /// `color_format`: a passthrough preset's, which no
695    /// [`ReceiverColorFormat`] names.
696    #[cfg(feature = "advanced")]
697    passthrough: Option<NDIlib_recv_color_format_e>,
698}
699
700/// Creation settings borrow exactly the storage retained by the receiver.
701pub(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    /// Replace the source, preserving every other receiver setting.
714    /// An empty name and an absent or empty address clear the source.
715    #[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    /// Clear the initial source, preserving every other receiver setting.
722    #[must_use]
723    pub fn clear_source(mut self) -> Self {
724        self.source = None;
725        self
726    }
727
728    /// Let the SDK choose the receiver name again.
729    #[must_use]
730    pub fn clear_name(mut self) -> Self {
731        self.name = None;
732        self
733    }
734
735    /// Remove the per-instance Advanced configuration override.
736    #[cfg(feature = "advanced")]
737    #[must_use]
738    pub fn clear_config(mut self) -> Self {
739        self.config = None;
740        self
741    }
742
743    /// The optional initial source, independent of later live source changes.
744    #[must_use]
745    pub fn configured_source(&self) -> Option<&Source> {
746        self.source.as_ref()
747    }
748
749    /// The stored color choice. Packet passthrough presets may override this
750    /// when creating a native receiver.
751    #[must_use]
752    pub fn configured_color_format(&self) -> ReceiverColorFormat {
753        self.color_format
754    }
755
756    /// The requested bandwidth, before native creation.
757    #[must_use]
758    pub fn configured_bandwidth(&self) -> ReceiverBandwidth {
759        self.bandwidth
760    }
761
762    /// Whether the requested configuration permits video fields.
763    #[must_use]
764    pub fn configured_allow_video_fields(&self) -> bool {
765        self.allow_video_fields
766    }
767
768    /// The requested receiver name, or `None` to let the SDK choose one.
769    #[must_use]
770    pub fn configured_name(&self) -> Option<&str> {
771        self.name.as_deref()
772    }
773
774    /// The stored Advanced configuration, when explicitly set. Reading it
775    /// does not expose its JSON or test native support.
776    #[cfg(feature = "advanced")]
777    #[must_use]
778    pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
779        self.config.as_ref()
780    }
781
782    /// Receive from `source` with the settings of [`Self::disconnected`].
783    /// An empty name and an absent or empty address leave the receiver
784    /// disconnected. An address alone can identify a source.
785    pub fn new(source: Source) -> Self {
786        Self::disconnected().source(source)
787    }
788
789    /// Start without a source, using [`ReceiverColorFormat::BgrxBgra`],
790    /// [`ReceiverBandwidth::Highest`], video fields allowed, and a receiver
791    /// name the SDK chooses. Use
792    /// [`Receiver::connect_to`] after selecting a source.
793    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    /// Settings for capturing snapshots: RGB color, low bandwidth, whole
808    /// frames.
809    ///
810    /// Suited to image export, thumbnails and analysis pipelines, and to
811    /// networks with little bandwidth to spare:
812    /// - color format [`ReceiverColorFormat::RgbxRgba`], convenient for
813    ///   encoding untagged sources directly;
814    /// - bandwidth [`ReceiverBandwidth::Lowest`], the source's preview stream;
815    /// - video fields not allowed, so interlaced video arrives as whole frames.
816    ///
817    /// The SDK converts YUV to RGB with BT.709 limited range even when
818    /// `ndi_color_info` names another matrix. This preset's RGB frames already
819    /// carry that conversion. See the
820    /// [image encoding color guidance](https://grantsparks.github.io/grafton-ndi/grafton_ndi/image_encoding/struct.ImageOptions.html#color)
821    /// for receiving YUV when the tag's matrix matters, including alpha and
822    /// high bit depth sources. Tags still control HDR refusal and PNG tagging.
823    ///
824    /// # Example
825    ///
826    /// ```no_run
827    /// # use grafton_ndi::{Ndi, Finder, FinderOptions, ReceiverOptions, Receiver};
828    /// # use std::time::Duration;
829    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
830    /// # let ndi = Ndi::new()?;
831    /// # let finder = Finder::new(&ndi, &FinderOptions::default())?;
832    /// # let Some(source) = finder.find_sources(Duration::from_secs(1))?.into_iter().next()
833    /// # else { return Ok(()); };
834    /// let options = ReceiverOptions::snapshot_preset(source).name("Snapshot Receiver");
835    /// let receiver = Receiver::new(&ndi, &options)?;
836    ///
837    /// // Capture and encode in one line (requires image-encoding feature)
838    /// #[cfg(feature = "image-encoding")]
839    /// if let Some(frame) = receiver.capture_video(Duration::from_secs(5))? {
840    ///     let png_bytes = frame.encode_image(&grafton_ndi::image_encoding::ImageOptions::new(
841    ///         grafton_ndi::image_encoding::ImageFormat::Png,
842    ///     ))?;
843    ///     std::fs::write("snapshot.png", &png_bytes)?;
844    /// }
845    /// # Ok(())
846    /// # }
847    /// ```
848    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    /// Settings for full-quality video processing: RGB color, full
856    /// bandwidth, interlaced video as fields.
857    ///
858    /// Suited to recording, broadcast and analysis that needs every pixel:
859    /// - color format [`ReceiverColorFormat::RgbxRgba`];
860    /// - bandwidth [`ReceiverBandwidth::Highest`], the source's program stream;
861    /// - video fields allowed, so interlaced video keeps its fields.
862    ///
863    /// RGB is convenient for untagged sources. For tagged YUV, the SDK has
864    /// already converted to BT.709 limited range, ignoring `ndi_color_info`;
865    /// image encoding cannot apply the tagged matrix to these RGB frames.
866    /// See the
867    /// [image encoding color guidance](https://grantsparks.github.io/grafton-ndi/grafton_ndi/image_encoding/struct.ImageOptions.html#color)
868    /// for receiving YUV when the tag's matrix matters, including alpha and
869    /// high bit depth sources. Tags still control HDR refusal and PNG tagging.
870    ///
871    /// # Example
872    ///
873    /// ```no_run
874    /// # use grafton_ndi::{Ndi, Finder, FinderOptions, ReceiverOptions, Receiver};
875    /// # use std::time::Duration;
876    /// # fn main() -> Result<(), grafton_ndi::Error> {
877    /// # let ndi = Ndi::new()?;
878    /// # let finder = Finder::new(&ndi, &FinderOptions::default())?;
879    /// # let Some(source) = finder.find_sources(Duration::from_secs(1))?.into_iter().next()
880    /// # else { return Ok(()); };
881    /// let options =
882    ///     ReceiverOptions::high_quality_preset(source).name("High Quality Receiver");
883    /// let receiver = Receiver::new(&ndi, &options)?;
884    ///
885    /// // Capture full quality frames
886    /// if let Some(frame) = receiver.capture_video(Duration::from_secs(5))? {
887    ///     println!("Captured {width}x{height} frame", width = frame.width(), height = frame.height());
888    /// }
889    /// # Ok(())
890    /// # }
891    /// ```
892    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    /// Settings for monitoring a connection and controlling the source,
900    /// without its video or audio.
901    ///
902    /// Suited to polling connection state with [`Receiver::is_connected`] or
903    /// [`Receiver::connection_stats`], tally and PTZ control. Connection loss
904    /// need not produce a [`ReceiverEvent::StatusChanged`] event.
905    ///
906    /// Uses these settings:
907    /// - bandwidth [`ReceiverBandwidth::MetadataOnly`];
908    /// - the default color format, which no frame uses;
909    /// - video fields not allowed.
910    ///
911    /// # Example
912    ///
913    /// ```no_run
914    /// # use grafton_ndi::{Ndi, Finder, FinderOptions, ReceiverOptions, Receiver};
915    /// # use std::time::Duration;
916    /// # fn main() -> Result<(), grafton_ndi::Error> {
917    /// # let ndi = Ndi::new()?;
918    /// # let finder = Finder::new(&ndi, &FinderOptions::default())?;
919    /// # let Some(source) = finder.find_sources(Duration::from_secs(1))?.into_iter().next()
920    /// # else { return Ok(()); };
921    /// let options = ReceiverOptions::monitoring_preset(source).name("Status Monitor");
922    /// let receiver = Receiver::new(&ndi, &options)?;
923    ///
924    /// println!("Connected: {}", receiver.is_connected());
925    /// println!("Active connections: {}", receiver.connection_stats()?.connections());
926    /// # Ok(())
927    /// # }
928    /// ```
929    pub fn monitoring_preset(source: Source) -> Self {
930        Self::new(source)
931            .bandwidth(ReceiverBandwidth::MetadataOnly)
932            .allow_video_fields(false)
933    }
934
935    /// Set the pixel formats the receiver delivers video in.
936    #[must_use]
937    pub fn color_format(mut self, color_format: ReceiverColorFormat) -> Self {
938        self.color_format = color_format;
939        self
940    }
941
942    /// Set which of the source's streams the receiver takes, and at what
943    /// quality.
944    #[must_use]
945    pub fn bandwidth(mut self, bandwidth: ReceiverBandwidth) -> Self {
946        self.bandwidth = bandwidth;
947        self
948    }
949
950    /// Set whether interlaced video is delivered as individual fields rather
951    /// than whole frames.
952    #[must_use]
953    pub fn allow_video_fields(mut self, allow: bool) -> Self {
954        self.allow_video_fields = allow;
955        self
956    }
957
958    /// Set the receiver's own name, which the SDK otherwise chooses.
959    #[must_use]
960    pub fn name(mut self, name: impl Into<String>) -> Self {
961        self.name = Some(name.into());
962        self
963    }
964
965    /// Create the receiver with this per-instance Advanced SDK configuration,
966    /// which it keeps for as long as it lives.
967    ///
968    /// [`Receiver::new`] then needs an Advanced runtime, and a build with the
969    /// Advanced SDK.
970    #[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    /// These options with the native color format `format`, which no
978    /// [`ReceiverColorFormat`] names, in place of their own: the one a
979    /// passthrough preset selects. Validation and the creation settings both
980    /// take it, so what is checked is what the SDK is given.
981    #[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    /// The color format the creation settings carry.
988    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    /// Validate exactly the options passed to the SDK, retaining each
997    /// capability proof the native descriptor relies on.
998    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
1019/// Only receivers interpret a completely empty descriptor as no target.
1020fn 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
1070/// Sealed receiver capability mode: what a [`Receiver`] may do besides its
1071/// common controls.
1072///
1073/// The common controls work in every mode: tally, PTZ, upstream metadata,
1074/// connection statistics, delays, source-name changes, connecting and
1075/// reconnecting. [`MetadataMode`] adds typed metadata capture, [`EventMode`]
1076/// adds event polling, [`AudioMode`] adds audio capture, and [`VideoMode`]
1077/// adds video capture. Only [`RawCapture`] permits every capture kind and
1078/// event polling.
1079pub trait ReceiverMode: mode_sealed::Sealed + Send + Sync {}
1080
1081/// Sealed receiver mode permitting typed metadata capture: [`RawCapture`],
1082/// [`FrameSyncAttached`] and, with `advanced`, `AvSyncAttached`.
1083///
1084/// Metadata capture retains any notifications it encounters for a later raw
1085/// receiver, but does not grant event polling; see [`EventMode`].
1086pub trait MetadataMode: ReceiverMode + mode_sealed::MetadataSealed {}
1087
1088/// Sealed receiver mode permitting event polling: [`RawCapture`].
1089///
1090/// Native FrameSync and AV sync can consume status notifications before an
1091/// attached receiver observes them. Attached receivers therefore use capability
1092/// getters, [`Receiver::wait_for_source_name_change`], [`Receiver::is_connected`]
1093/// and [`Receiver::connection_stats`] rather than event polling.
1094pub trait EventMode: ReceiverMode + mode_sealed::EventSealed {}
1095
1096/// Sealed receiver mode in which the receiver's own audio and metadata
1097/// capture are available: [`RawCapture`].
1098///
1099/// A [`MetadataMode`] without it hands the receiver's audio to the object
1100/// that holds the receiver: [`FrameSyncAttached`] to a
1101/// [`FrameSync`](crate::FrameSync) and, with the `advanced` feature,
1102/// `AvSyncAttached` to an Advanced `AvSync`.
1103pub trait AudioMode: MetadataMode + mode_sealed::AudioSealed {}
1104
1105/// Sealed receiver mode in which the receiver's own video capture is
1106/// available: [`RawCapture`] and, with the `advanced` feature, the
1107/// `AvSyncAttached` mode of an Advanced `AvSync`'s receiver.
1108///
1109/// A mode without it hands the receiver's video to the object that holds the
1110/// receiver.
1111pub trait VideoMode: ReceiverMode + mode_sealed::VideoSealed {}
1112
1113/// The one crate-internal permission table for both typed and slot-set capture.
1114/// ReceiverMode seals the implementors. Public modes inherit their permissions,
1115/// so a generic adapter's public mode bound carries this same internal gate.
1116pub(crate) trait Permits<K>: ReceiverMode {}
1117
1118// Raw capture permits every sealed public kind, including generic CaptureKind
1119// callers. Attached modes retain only the slots their synchronizer leaves free.
1120impl<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
1131/// Modes native receiver creation can produce directly.
1132pub(crate) trait CreatableMode: ReceiverMode {}
1133impl CreatableMode for RawCapture {}
1134#[cfg(feature = "advanced")]
1135impl CreatableMode for PacketAttached {}
1136
1137/// Modes whose native synchronizer must be destroyed before raw capture returns.
1138pub(crate) trait SynchronizerMode: ReceiverMode {}
1139impl SynchronizerMode for FrameSyncAttached {}
1140#[cfg(feature = "advanced")]
1141impl SynchronizerMode for AvSyncAttached {}
1142
1143/// Ordinary receiver mode, permitting raw video capture.
1144#[derive(Debug)]
1145pub enum RawCapture {}
1146/// Receiver mode held exclusively by [`crate::FrameSync`], whose synchronizer
1147/// takes the receiver's video and audio.
1148///
1149/// The receiver's own metadata capture and common controls are available.
1150/// Event polling is unavailable because native synchronization can consume
1151/// status notifications. Query capabilities with [`Ptz::is_supported`] and
1152/// [`Receiver::web_control_url`] (or Advanced KVM's `is_supported`), source
1153/// names with [`Receiver::wait_for_source_name_change`], and connection state with
1154/// [`Receiver::is_connected`] and [`Receiver::connection_stats`].
1155/// Its video and audio capture are unavailable: FrameSync returns them through
1156/// [`FrameSync::capture_video`](crate::FrameSync::capture_video) and
1157/// [`FrameSync::capture_audio`](crate::FrameSync::capture_audio).
1158///
1159/// Raw audio capture on the attached receiver would compete with the
1160/// synchronizer for the receiver's audio: each audio frame reaches only one
1161/// of them. Measured with NDI 6.3.2 and 6.4 over loopback, raw capture
1162/// interleaved with FrameSync pulls takes most of a 30 fps stream's audio
1163/// frames, none of which then reach the FrameSync, which returns silence in
1164/// their place. Metadata is not taken that way: every metadata frame still
1165/// reaches the receiver's own capture while the FrameSync pulls video and
1166/// audio. `framesync_pulls_leave_sequenced_metadata_for_the_attached_receiver`
1167/// in `tests/framesync_capture_boundary.rs` repeats that metadata check on
1168/// every runtime exercised by CI.
1169#[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
1202/// An owned NDI receiver. The default mode permits all raw capture kinds.
1203/// [`FrameSync`](crate::FrameSync) and the Advanced `AvSync` change the mode of
1204/// the receiver they hold while retaining the same resource core. The Advanced
1205/// `PacketReceiver` creates its receiver in `PacketAttached` mode; see [`ReceiverMode`].
1206///
1207/// Dropping the receiver disconnects it from its source, unless a
1208/// [`RecvAdvertiser`](crate::discovery_server::RecvAdvertiser) registration still
1209/// holds it: a registered receiver stays connected, and advertised, until that
1210/// registration is removed or its advertiser is dropped.
1211///
1212/// # Waiting
1213///
1214/// Captures, events, source-name waits, getters, [`Self::is_connected`] and
1215/// [`Self::connection_target`] never wait for a local connection change.
1216/// Shared controls serialize briefly with one another. On Standard Windows,
1217/// PTZ commands, upstream metadata and connection-metadata additions return
1218/// [`Error::NotConnected`] during a local connection change; tally is retained
1219/// and applied when that native request returns. These controls do not wait
1220/// for the change. The Standard Windows SDK does not provide the native
1221/// exclusion necessary for SDK-internal changes, so an advertiser refuses
1222/// [remote receiver control](crate::RuntimeFeature::RemoteReceiverControl)
1223/// there. Other runtimes synchronize controls with local and SDK-internal
1224/// changes through their native receiver lock. Local
1225/// [`Self::connect_to`], [`Self::disconnect`] and [`Self::reconnect`] requests
1226/// serialize with one another and may wait for running allocator policies.
1227/// Dropping the last owner destroys the native receiver on the dropping
1228/// thread, including when the owner is an async adapter or registration.
1229pub 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
1240/// The same receiver identity is available both to owners and to split views.
1241pub(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
1268/// Only a receiver's local-change lock can issue this permit.
1269struct ChangePermit;
1270
1271/// Exclusive permission for one local connection request.
1272struct 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                // Keep the target alive without holding the read lock across
1305                // the native call. An idle retry needs no control transition.
1306                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            // SAFETY: the proof authorizes this live receiver's connection
1316            // request. RetainedSource keeps the native descriptor and strings.
1317            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            // The change permit keeps the previous target in place until the
1328            // native call returns. Readers can snapshot it during the call.
1329            *self.target.write() = target;
1330        }
1331    }
1332}
1333
1334/// Stream mutation borrowed only from an exclusive receiver/control borrow.
1335/// Native advertiser operations use their independent observer-registry lock.
1336#[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/// Owned allocator authority minted while taking exclusive receiver ownership.
1358/// Only allocator registration stores it; it cannot be cloned or recovered as
1359/// a receiver. Registration borrows this authority only during its exclusive
1360/// install/reset operations.
1361#[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/// Allocator installation borrows its nonclone owned authority. Native setters
1382/// replace callback state under the allocator's own rwlock. Native policy calls
1383/// run under its read side; keeping unrelated Rust gates across this wait would
1384/// add lock-order obligations to arbitrary policy callbacks.
1385#[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
1408/// Membership borrows the retained receiver and reaches only its immutable
1409/// creation properties and stable observer registry. The native advertiser and
1410/// observer registries serialize their mutations independently of connection
1411/// state. Never take the Rust change permit: a native connection change
1412/// can hold it while joining a decoder thread whose allocator policy adds or
1413/// removes this same receiver's membership.
1414pub(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
1422/// Only this receiver's source-query lock issues this permit.
1423struct SourceQueryPermit;
1424
1425/// One source-report consumer under the native report mutex and Rust query gate.
1426struct 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/// A receiver's opaque native identity; ownership stays with `ReceiverCore`.
1438#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1439pub(crate) struct RecvInstance(NDIlib_recv_instance_t);
1440
1441// SAFETY: receivers have no thread affinity. Every shared native entry point
1442// has one of the following concurrency bases (NDIlib_recv_ prefix omitted):
1443//
1444// Entry points                                      | Concurrency basis
1445// --------------------------------------------------|---------------------------
1446// capture_v3; free_video_v2, free_audio_v3,           | SDK concurrent-capture/free
1447// free_metadata                                     | contract; see CaptureLock
1448// connect                                           | Change permit
1449// set_tally, send_metadata                          | Connection-use permit
1450// add_connection_metadata                          | Connection-use permit and retained registrations
1451// clear_connection_metadata                         | Control permit and retained registrations
1452// set/get_video_delay, set/get_audio_delay           | Control permit and native delay-state locks
1453// get_web_control, get_performance, get_queue        | Control permit
1454// get_no_connections                                | Measured native read lock
1455// get_source_name                                   | Native report mutex +
1456//                                                   | Rust source-query permit
1457// free_string                                       | Measured native read lock
1458// ptz_is_supported, ptz_recall_preset,               | Connection-use permit (each PTZ entry point)
1459// ptz_store_preset, ptz_zoom, ptz_zoom_speed,         |
1460// ptz_pan_tilt, ptz_pan_tilt_speed, ptz_auto_focus,   |
1461// ptz_focus, ptz_focus_speed, ptz_white_balance_auto, |
1462// ptz_white_balance_indoor/outdoor/oneshot/manual,   |
1463// ptz_exposure_auto/manual/manual_v2                 |
1464// request_keyframe                                  | Connection-use permit
1465// set_bandwidth, set_enabled_streams                 | Exclusive (&mut Receiver)
1466// set_video_allocator, set_audio_allocator           | Owned allocator authority
1467//                                                   | Native allocator rwlock
1468// framesync_create, avsync_create (NDIlib_ prefix)    | By-value adoption
1469// destroy                                           | Last owning ReceiverCore
1470// recv_advertiser_add_receiver,                      | Immutable creation identity;
1471// recv_advertiser_del_receiver (NDIlib_ prefix)       | native observer-registry mutex
1472// kvm_is_supported, kvm_send_keyboard_press/release, | Connection-use permit (including held-input
1473// kvm_send_left/middle/right_mouse_click/release,    | cleanup and Drop)
1474// kvm_send_vertical/horizontal_mouse_wheel,         |
1475// kvm_send_mouse_position/clipboard_contents,       |
1476// kvm_send_touch_positions, kvm_send_touch_finish    |
1477//
1478// Native lock interposition and disassembly on Linux x86-64 Standard 6.1.1,
1479// Standard/Advanced 6.3.2 and 6.4.0.2 provide the additional basis for controls
1480// overlapping captures and local or SDK-internal (Discovery Server) changes:
1481// all available connection-facing controls, including PTZ and KVM message
1482// sends, take the same receiver read lock at +0x108 as capture. Local changes
1483// take it exclusively, as recorded beside CaptureLock. Connection-metadata
1484// registration additionally uses its own lock at +0x158. The 6.4 delay getters
1485// read receiver-owned delay state under that state's lock, independent of the
1486// replaceable connection; setters also take the connection read lock.
1487// get_source_name (6.3.2/6.4) copies a report under the report mutex at +0x218,
1488// never dereferencing replaceable connection state. free_string takes the
1489// connection read lock before releasing its owned string. Missing entry points
1490// cannot be called.
1491//
1492// Advertiser add/del were interposed on Standard/Advanced 6.3.2 and 6.4.0.2:
1493// neither takes the receiver connection rwlock. Both serialize through the
1494// advertiser member-map mutex and the receiver observer-registry mutex at +0x10.
1495// Their receiver virtuals read only its retained name/configuration, the stable
1496// observer-registry pointer, and (for add) immutable creation capabilities.
1497// They do not access replaceable connections or allocator callback fields.
1498// Standard 6.1.1 has no advertiser symbols. Membership must remain independent
1499// of the Rust change permit, including unregister and Drop: a policy may
1500// add/remove membership while a connection change holds its change permit and joins
1501// the decoder thread running the policy.
1502// Allocator setters update only their separately locked callback state.
1503// Advanced 6.3.2/6.4.0.2 interposition and disassembly find a native allocator
1504// write lock for each setter and its read side across policy calls. The bounded
1505// native regression covers policy membership add/remove during allocator reset,
1506// reconnect and disconnect. Exclusive stream controls and adoption retain their
1507// original &mut/by-value basis; advertiser-held Arcs are covered by the native
1508// registry synchronization and field independence above.
1509//
1510// Windows native editions differ. Standard 6.3.2 and 6.4 pin only receiver
1511// lifetime in their exported helper; connect replaces connection pointers at
1512// +0x198/+0x1a0 under a lock at +0x1a8, while tally, metadata sends and PTZ
1513// commands dereference those pointers without that lock. Their Rust control
1514// permit therefore publishes a changing phase before local connect, then is
1515// released. Connection-reading controls refuse that phase; tally is retained
1516// and replayed after native connect. SDK-internal Discovery Server requests
1517// cannot enter the Rust phase, so controlling registrations are refused on
1518// that edition. Receiver-owned getters, source queries, delay state and
1519// metadata clearing stay independent. Advanced Windows
1520// 6.3.2/6.4 instead use the +0x108 shared/exclusive connection lock; connect
1521// releases it before destroying retired connections. Allocators require that
1522// Advanced edition, so their callbacks retain the independent-control basis.
1523//
1524// A Rust control permit serializes the listed controls with one another.
1525// The native connection-lock basis above applies to measured Linux and
1526// Advanced Windows runtimes and covers both local and SDK-internal changes.
1527// Standard Windows local changes use the explicit changing phase.
1528// No Rust control permit is held during native connect,
1529// so Advanced allocator callbacks can capture and use shared controls.
1530// tests/receiver_connect_overlap_sdk.rs exercises every available
1531// shared control against captures, local changes and 6.4 remote changes.
1532// Sixteen capture threads, three control threads and 1080p feeds completed
1533// 120-second local connection storms on each of the five runtimes above,
1534// validating frames, operation budgets, resumed progress and balanced loans.
1535// Helgrind 3.19 workloads on Standard/Advanced 6.3.2 and 6.4 also completed,
1536// including Advanced KVM input/capture. They report SDK allocator/state handoffs,
1537// the capture polling flag and Rust synchronization; these are qualified
1538// detector runs, not zero-error results. The exclusion and observed native
1539// locking above supply the concurrency argument.
1540// Every native use retains the core; its other fields determine its auto traits.
1541unsafe impl Send for RecvInstance {}
1542// SAFETY: as above; receiver modes reserve the media paths used by synchronizers.
1543unsafe impl Sync for RecvInstance {}
1544
1545pub(crate) struct ReceiverCore {
1546    instance: RecvInstance,
1547    pub(crate) sdk: crate::runtime::Bound<sys::Core>,
1548    /// Serializes local connection changes; callbacks may take the independent
1549    /// control permit while a native connection change waits for them.
1550    change_guard: Mutex<ChangePermit>,
1551    /// Serializes shared controls only; never held across a connection change.
1552    control_guard: Mutex<ControlPermit>,
1553    /// Standard Windows uses a native implementation without the Advanced
1554    /// receiver's connection read lock. Its unsafe controls refuse the brief
1555    /// transition instead of waiting for native connect.
1556    guard_local_connection_changes: bool,
1557    /// The latest requested target. The change permit serializes its writers;
1558    /// snapshots never take it and therefore never wait for a capture or a queued
1559    /// connection change. Writers hold this lock only to replace the value.
1560    target: RwLock<Option<RetainedSource>>,
1561    pending: PendingEvents,
1562    // Only native source-name queries take this permit. Replaying an abandoned
1563    // result takes the separate short lock, never waiting for the SDK.
1564    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    /// Wait up to `timeout` for video, audio, metadata, or a receiver event,
1573    /// borrowing delivered media directly from the SDK without a payload
1574    /// copy or allocation. No Advanced feature or runtime is required.
1575    ///
1576    /// A single native wait requests every media kind, so a silent stream
1577    /// does not delay other kinds behind its own timeout. All capture methods share the same wait-budget and zero-timeout
1578    /// behavior described by [`Self::capture_video_ref`]. The returned item borrows this receiver; media references
1579    /// may move to scoped worker threads while that borrow remains live.
1580    ///
1581    /// Pending and native events are consumed once, competing with
1582    /// [`Self::next_event`] and other combined captures. They are coalesced
1583    /// invalidations, with no ordered history or broadcast guarantee. Typed
1584    /// media captures retain their events for these consumers.
1585    /// [`ReceiverEvent::SourceChanged`] requires the separate
1586    /// [`Self::wait_for_source_name_change`] query for the new name.
1587    ///
1588    /// This operation exists only in ordinary raw-capture mode. FrameSync,
1589    /// AvSync and packet receivers reserve some or all native media slots.
1590    ///
1591    /// # Errors
1592    ///
1593    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
1594    /// [`Error::ConnectionLost`] when the SDK reports a lost connection, and
1595    /// the same frame-validation errors as typed borrowed capture. Rejected
1596    /// frames are freed through their matching native free operation.
1597    /// [`Error::UnexpectedSdkResult`] reports a negative status connection
1598    /// count once per publication. That status stays pending for recovery;
1599    /// other events and subsequent media capture remain available.
1600    #[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    /// Wait up to `timeout` for any media or receiver event and return an
1606    /// owned item. See [`Self::capture_any_ref`] for delivery and wait rules.
1607    ///
1608    /// Media is copied through the same validated paths as typed capture:
1609    /// active video rows are packed, audio channel padding is omitted, and
1610    /// timing and metadata are preserved. Video/audio allocate one payload
1611    /// buffer plus metadata when present; standalone metadata allocates its
1612    /// text. Events allocate nothing. Copying may finish after the wait
1613    /// budget expires. Use [`Self::capture_any_ref`] for in-place processing.
1614    ///
1615    /// # Errors
1616    ///
1617    /// The errors of [`Self::capture_any_ref`].
1618    #[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    /// Create a receiver, requesting the configured source if one is set.
1624    ///
1625    /// # Errors
1626    ///
1627    /// Returns [`Error::UnsupportedCapability`] when the options need a mode the
1628    /// selected runtime lacks, or carry an Advanced configuration that the
1629    /// runtime or this build cannot take; [`Error::InvalidCString`] for a receiver
1630    /// name that contains a NUL byte; and [`Error::NativeOperationFailed`]
1631    /// when the SDK creates no receiver.
1632    #[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        // SAFETY: the SDK's receiver creation returns null or a fresh receiver
1649        // that nothing else owns, and the settings outlive the call.
1650        unsafe {
1651            Self::create(ndi, options, |core, raw| {
1652                crate::runtime::NativeCreation::plain(core.named().NDIlib_recv_create_v3(raw))
1653            })
1654        }
1655    }
1656    /// The one creation path: check `options` against the runtime, create a
1657    /// receiver through `create`, which is
1658    /// handed the core table and the native settings for `options`, and keep
1659    /// `config` for as long as the native receiver lives.
1660    ///
1661    /// # Safety
1662    ///
1663    /// `create` returns null or a live receiver of `ndi`'s runtime, made from
1664    /// the settings it was handed, that nothing else owns.
1665    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        // The settings borrow the target's own descriptor and name. Both
1679        // owners move into the core after creation without moving their buffers.
1680        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    /// Synthetic packet-mode receiver for tests without a passthrough SDK.
1706    #[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                ///
1722                /// A zero timeout makes one nonblocking SDK attempt. Early SDK
1723                /// status and source reports are retained for `next_event`, or, on an
1724                /// attached receiver, for the raw receiver that detaching returns;
1725                /// capture continues until a frame arrives or the budget expires.
1726                /// Each native attempt waits at most 100 ms; validation and copying
1727                /// can finish after the budget. `None` alone does not establish
1728                /// disconnection or freshness.
1729                ///
1730                /// # Errors
1731                ///
1732                /// Invalid timeouts, a lost connection, or invalid SDK frame data.
1733                #[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                ///
1740                /// The returned frame borrows the receiver and releases its SDK
1741                /// buffer when dropped. Capture retains status and source reports
1742                /// for `next_event`, or, on an attached receiver, for the raw
1743                /// receiver that detaching returns. A zero timeout makes one nonblocking attempt;
1744                /// each other attempt waits at most 100 ms within the shared budget.
1745                ///
1746                /// # Errors
1747                ///
1748                /// Invalid timeouts, a lost connection, or invalid SDK frame data.
1749                #[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    /// Typed capture for an adapter whose receiver mode permits this kind.
1761    #[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    /// Mixed capture selects its slot set through the same mode permission.
1774    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    /// Set native video buffering.
1850    ///
1851    /// [`SettingChange::Unchanged`] means the delay already had this value.
1852    /// Delay is independent of audio
1853    /// buffering and stacks with FrameSync correction.
1854    ///
1855    /// # Errors
1856    ///
1857    /// [`Error::UnsupportedCapability`] without
1858    /// [`RuntimeFeature::ReceiveDelay`](crate::RuntimeFeature::ReceiveDelay).
1859    #[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    /// Return the effective native video delay. Requires receiver-delay support.
1865    ///
1866    /// # Errors
1867    ///
1868    /// [`Error::UnsupportedCapability`] without
1869    /// [`RuntimeFeature::ReceiveDelay`](crate::RuntimeFeature::ReceiveDelay), and [`Error::UnexpectedSdkResult`]
1870    /// when the SDK reports a delay outside 0 to 2000 ms.
1871    #[doc(alias = "NDIlib_recv_get_video_delay")]
1872    pub fn video_delay(&self) -> Result<ReceiveDelay> {
1873        self.core.delay(ReceiveDelayStream::Video)
1874    }
1875
1876    /// Set native audio buffering independently of [`Self::set_video_delay`].
1877    ///
1878    /// Equal audio and video delays preserve their relative timing; different
1879    /// values deliberately offset the streams.
1880    ///
1881    /// # Errors
1882    ///
1883    /// As for [`Self::set_video_delay`].
1884    #[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    /// Return the effective native audio delay. Requires receiver-delay support.
1890    ///
1891    /// # Errors
1892    ///
1893    /// As for [`Self::video_delay`].
1894    #[doc(alias = "NDIlib_recv_get_audio_delay")]
1895    pub fn audio_delay(&self) -> Result<ReceiveDelay> {
1896        self.core.delay(ReceiveDelayStream::Audio)
1897    }
1898
1899    /// Add validated metadata sent immediately and again on each connection.
1900    ///
1901    /// Accepts owned or captured metadata. The receiver keeps its own copy,
1902    /// so the input need not outlive the registration.
1903    ///
1904    /// On Windows x64, the Standard NDI 6.3.2.0 and 6.4.0.2 builds tested in
1905    /// [issue #551](https://github.com/GrantSparks/grafton-ndi/issues/551) can
1906    /// omit automatic delivery. Applications that manage reconnects can send
1907    /// the payload explicitly with [`Self::send_metadata`] after confirming
1908    /// each connection is live. Use a single send path for the payload to
1909    /// avoid duplicates.
1910    ///
1911    /// # Errors
1912    ///
1913    /// [`Error::UnsupportedCapability`] without
1914    /// [`RuntimeFeature::ReceiverConnectionMetadata`](crate::RuntimeFeature::ReceiverConnectionMetadata).
1915    /// [`Error::NotConnected`] during a local connection change on Standard
1916    /// Windows; no metadata is registered in that case.
1917    #[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    /// Clear metadata registered for subsequent receiver connections.
1927    ///
1928    /// # Errors
1929    ///
1930    /// [`Error::UnsupportedCapability`] without
1931    /// [`RuntimeFeature::ReceiverConnectionMetadata`](crate::RuntimeFeature::ReceiverConnectionMetadata).
1932    #[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    /// Copy the optional device web-control URL. This does not open the URL.
1940    ///
1941    /// # Errors
1942    ///
1943    /// [`Error::UnsupportedCapability`] without
1944    /// [`RuntimeFeature::ReceiverWebControl`](crate::RuntimeFeature::ReceiverWebControl),
1945    /// [`Error::InvalidUtf8`] for an invalid URL encoding, and
1946    /// [`Error::UnexpectedSdkResult`] when the SDK does not terminate the URL
1947    /// within the bounded string scan.
1948    #[doc(alias = "NDIlib_recv_get_web_control")]
1949    pub fn web_control_url(&self) -> Result<Option<String>> {
1950        // The query comes with the function that releases what it returns.
1951        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    /// Observe a change to the actual connected source name.
1965    ///
1966    /// `None` means no change within the wait budget; `Disconnected` is an
1967    /// observed change to no source. Concurrent pollers compete for notifications.
1968    /// This differs from [`Self::connection_target`], the latest requested target.
1969    ///
1970    /// The SDK reports each change once. This notification replaces invalid
1971    /// UTF-8 sequences with U+FFFD so the change remains visible.
1972    ///
1973    /// # Errors
1974    ///
1975    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
1976    /// [`Error::UnsupportedCapability`] without
1977    /// [`RuntimeFeature::ConnectedSourceName`](crate::RuntimeFeature::ConnectedSourceName),
1978    /// and [`Error::UnexpectedSdkResult`] when the SDK does not terminate the
1979    /// name within the bounded string scan.
1980    #[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    /// Request a different source and remember it as the connection target.
1990    ///
1991    /// Serializes with other local connection changes, then issues the request
1992    /// and updates [`Self::connection_target`] together. Captures may continue
1993    /// while the SDK applies the change.
1994    /// Success means the request was issued, not that the source is available.
1995    /// The source was validated at construction. Existing FrameSync ownership
1996    /// remains.
1997    /// An empty name and an absent or empty address act like [`Self::disconnect`],
1998    /// preserving any last target.
1999    #[doc(alias = "NDIlib_recv_connect")]
2000    pub fn connect_to(&self, source: &Source) {
2001        self.connect_target(prepare_receiver_target(source));
2002    }
2003
2004    /// Apply an input already validated on the synchronous or async caller.
2005    pub(crate) fn connect_target(&self, target: Option<RetainedSource>) {
2006        self.core
2007            .request(target.map_or(ConnectionRequest::Disconnect, ConnectionRequest::Connect));
2008    }
2009
2010    /// Disconnect while retaining the target for [`Self::reconnect`].
2011    ///
2012    /// Serializes with other local connection changes, as [`Self::reconnect`]
2013    /// does, while captures may continue.
2014    #[doc(alias = "NDIlib_recv_connect")]
2015    pub fn disconnect(&self) {
2016        self.core.request(ConnectionRequest::Disconnect);
2017    }
2018
2019    /// Publish this receiver's program and preview tally to its source.
2020    ///
2021    /// The SDK keeps the state and sends it to every source the receiver
2022    /// connects to, so it can be set before a connection and survives a
2023    /// reconnect. On Standard Windows a tally changed during a local
2024    /// connection request is retained and sent as that request finishes.
2025    #[doc(alias = "NDIlib_recv_set_tally")]
2026    pub fn set_tally(&self, tally: Tally) {
2027        self.core.set_tally(tally);
2028    }
2029
2030    /// Send metadata upstream, to the source this receiver is connected to.
2031    ///
2032    /// Accepts owned or captured metadata without copying its text in the
2033    /// wrapper. The SDK copies the text before returning.
2034    ///
2035    /// # Errors
2036    ///
2037    /// [`Error::NotConnected`] when the receiver is connected to no source,
2038    /// so nothing was sent, or during a local connection change on Standard
2039    /// Windows. See the [waiting contract](Receiver#waiting).
2040    #[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    /// Control the pan, tilt, zoom, focus, white balance and exposure of the
2048    /// connected source.
2049    ///
2050    /// # Examples
2051    ///
2052    /// ```no_run
2053    /// # use grafton_ndi::{Ndi, Receiver, ReceiverOptions, Source};
2054    /// # fn main() -> Result<(), grafton_ndi::Error> {
2055    /// # let ndi = Ndi::new()?;
2056    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::monitoring_preset(Source::new("CAMERA (Program)").unwrap()))?;
2057    /// let ptz = receiver.ptz();
2058    /// if ptz.is_supported() {
2059    ///     ptz.zoom(0.5)?;
2060    ///     ptz.pan_tilt(-0.25, 0.1)?;
2061    ///     ptz.auto_focus()?;
2062    /// }
2063    /// # Ok(())
2064    /// # }
2065    /// ```
2066    #[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    /// Check if the receiver is still connected to its source.
2072    ///
2073    /// Returns `true` if there is at least one native connection to the source,
2074    /// `false` otherwise. A connection does not establish progress of any
2075    /// particular media stream; see the
2076    /// [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
2077    ///
2078    /// # Examples
2079    ///
2080    /// ```no_run
2081    /// # use grafton_ndi::{Ndi, Receiver, ReceiverOptions, Source};
2082    /// # fn main() -> Result<(), grafton_ndi::Error> {
2083    /// # let ndi = Ndi::new()?;
2084    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("CAMERA (Program)").unwrap()))?;
2085    /// if receiver.is_connected() {
2086    ///     println!("Still connected to source");
2087    /// } else {
2088    ///     println!("Lost connection to source");
2089    /// }
2090    /// # Ok(())
2091    /// # }
2092    /// ```
2093    /// A negative native count reports no established connection; use
2094    /// [`Self::connection_stats`] to inspect that SDK contract error.
2095    #[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    /// Re-establish this receiver's connection to its latest requested target,
2101    /// in place.
2102    ///
2103    /// Re-points the existing NDI receiver instance at the [`Source`] it
2104    /// most recently requested through [`Self::connect_to`] (or its initial
2105    /// source) without destroying and recreating the
2106    /// receiver. This is intended for mid-session recovery: when a
2107    /// source's feed has gone silent (for example an encoder-bound
2108    /// NDI|HX camera that dropped its proxy stream under load), a
2109    /// reconnect forces a fresh connection attempt while avoiding the
2110    /// source-rediscovery round trip — and the discovery race — that
2111    /// tearing down and rebuilding the receiver would incur.
2112    ///
2113    /// This requests the last local target again. If a Discovery Server client
2114    /// remotely changed this receiver's source, reconnecting replaces that
2115    /// remote routing with the local target. Observe remote changes through
2116    /// [`Self::wait_for_source_name_change`]. Before a local target is selected,
2117    /// this call returns without issuing an SDK request.
2118    ///
2119    /// Observe native connection state with [`Self::is_connected`] and
2120    /// progress of the expected media with [`Self::connection_stats`]. A
2121    /// reconnect alone does not establish that new media has arrived.
2122    ///
2123    /// # Thread safety
2124    ///
2125    /// Local connection changes serialize with one another. They may overlap
2126    /// captures, including FrameSync and AV sync, so this method does not wait
2127    /// for a Rust capture gate. Native synchronization and the request itself
2128    /// still run on the calling thread; async code should use
2129    /// `AsyncReceiver::reconnect` to run that work on its blocking pool.
2130    ///
2131    /// Uses the retained, validated target without allocation or conversion.
2132    /// `NDIlib_recv_connect` reports no status. Confirm recovery through
2133    /// [`Self::connection_stats`].
2134    #[doc(alias = "NDIlib_recv_connect")]
2135    pub fn reconnect(&self) {
2136        self.core.request(ConnectionRequest::Reconnect);
2137    }
2138
2139    /// An owned snapshot of the latest locally requested connection target.
2140    ///
2141    /// Initially the source specified in [`ReceiverOptions`], or `None` when
2142    /// created disconnected. [`Self::connect_to`] remembers each selected
2143    /// source. [`Self::disconnect`] retains it, and
2144    /// [`Self::reconnect`] requests it again. A Discovery Server client's remote
2145    /// connection change does not update this local target. Observe actual
2146    /// connection changes with [`Self::wait_for_source_name_change`].
2147    /// The snapshot shares the source's name and address. It never waits for
2148    /// captures or queued connection changes; a concurrent `connect_to` holds
2149    /// the target lock only while replacing the value after its request returns.
2150    ///
2151    /// ```no_run
2152    /// # use grafton_ndi::{Ndi, Receiver, ReceiverOptions, Source};
2153    /// # fn main() -> grafton_ndi::Result<()> {
2154    /// # let ndi = Ndi::new()?;
2155    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("CAMERA (Program)").unwrap()))?;
2156    /// if let Some(target) = receiver.connection_target() {
2157    ///     println!("Requested target: {target}");
2158    /// }
2159    /// # Ok(())
2160    /// # }
2161    /// ```
2162    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    /// Get connection and performance statistics for this receiver.
2171    ///
2172    /// Provides detailed statistics including:
2173    /// - Number of active connections
2174    /// - Total frames received (video, audio, metadata)
2175    /// - Dropped frames (video, audio, metadata)
2176    /// - Queued frames waiting to be processed
2177    ///
2178    /// The native received totals include frames later dropped from the
2179    /// receiver queue or processing. These three native calls do not form an
2180    /// atomic connection/performance/queue snapshot. Counters may reset on
2181    /// connection changes; see [`ConnectionStats`] and the
2182    /// [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
2183    ///
2184    /// # Errors
2185    ///
2186    /// [`Error::UnexpectedSdkResult`] when any native count is negative.
2187    ///
2188    /// # Examples
2189    ///
2190    /// ```no_run
2191    /// # use grafton_ndi::{Ndi, Receiver, ReceiverOptions, Source};
2192    /// # fn main() -> Result<(), grafton_ndi::Error> {
2193    /// # let ndi = Ndi::new()?;
2194    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("CAMERA (Program)").unwrap()))?;
2195    /// let stats = receiver.connection_stats()?;
2196    /// println!("Connections: {connections}", connections = stats.connections());
2197    /// println!("Video frames: {received} (dropped: {dropped})",
2198    ///          received = stats.video_frames_received(),
2199    ///          dropped = stats.video_frames_dropped());
2200    /// println!("Frame drop rate: {rate:.2}%",
2201    ///          rate = stats.video_drop_percentage());
2202    /// # Ok(())
2203    /// # }
2204    /// ```
2205    #[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
2233/// Event polling is available only before a synchronizer takes the receiver.
2234impl<M: EventMode> Receiver<M> {
2235    /// Wait up to `timeout` for a status or source change, or return `None`
2236    /// when none came.
2237    ///
2238    /// Events are coalesced invalidations, including those that media capture
2239    /// passed over and kept, not an ordered history or broadcast stream.
2240    /// Concurrent pollers and combined captures compete to consume a pending one. The new source
2241    /// name is read with the SDK's separate [`Self::wait_for_source_name_change`]
2242    /// API.
2243    ///
2244    /// The timeout is spent as the typed capture methods spend it: in attempts of
2245    /// at most 100 ms, each of which first takes a pending event and otherwise
2246    /// waits in the SDK for the rest of the attempt. The SDK's early returns
2247    /// are waited over, so `None`
2248    /// comes only once the whole timeout is spent, and [`Duration::ZERO`]
2249    /// makes one attempt without waiting. An event that a concurrent capture
2250    /// keeps is returned by the next attempt. Connection changes may run
2251    /// concurrently with these attempts.
2252    ///
2253    /// # Errors
2254    ///
2255    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`]
2256    /// (~49.7 days), and [`Error::ConnectionLost`] when the SDK reports a lost
2257    /// connection, or [`Error::UnexpectedSdkResult`] when a status snapshot
2258    /// contains a negative native connection count, once per publication.
2259    /// Its invalidation stays pending for recovery, without hiding other events
2260    /// or preventing subsequent native captures.
2261    #[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    /// The entry points of the runtime this receiver was created through.
2273    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    /// Bind `attempt` to this receiver and its runtime, without taking the
2310    /// connection guard. Connection changes may overlap native captures.
2311    ///
2312    /// This is the only way to make a [`CaptureLock`], and so to call
2313    /// `NDIlib_recv_capture_v3` on this instance.
2314    fn capture_lock(&self, attempt: Attempt) -> CaptureLock<'_> {
2315        CaptureLock {
2316            core: self,
2317            attempt,
2318        }
2319    }
2320
2321    /// Hold the local connection lock, so tests can verify captures and target
2322    /// snapshots proceed while another connection change is queued.
2323    #[cfg(all(test, any(feature = "tokio", feature = "smol")))]
2324    pub(crate) fn reconnect_lock(&self) -> impl Drop + '_ {
2325        self.lock_change()
2326    }
2327
2328    /// One SDK capture of kind `K` within `attempt`.
2329    ///
2330    /// Runs concurrently with other captures and connection changes. `None`
2331    /// when the SDK returned without a frame of this kind; a
2332    /// notification it returned instead is kept for [`Receiver::next_event`].
2333    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        // Classify the result itself, rather than inspecting pending events:
2337        // another consumer may take a retained event concurrently.
2338        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                // Validation (e.g. FourCC) happens during ref construction.
2353                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    /// The one capture loop, behind every borrowed and owned
2364    /// capture: SDK captures in [`capture_within`]'s attempts until one
2365    /// delivers a frame of kind `K` or `deadline` is spent.
2366    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    /// The mixed-capture kernel, shared by raw and packet receivers and
2375    /// notification-only polling. A pending event is taken before the native
2376    /// attempt; events retained during that attempt merge with its result.
2377    /// Only media reaches `convert`, retaining
2378    /// its guards through the caller's validation and copy.
2379    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    /// The kernel's delivery boundary. Notifications always coalesce through
2397    /// `event`, including a native miss when a typed capture retained an event
2398    /// during the wait. A caller can convert only media from its slot set.
2399    #[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        // SAFETY: the receiver is live; the RecvInstance inventory records the
2439        // native connection read lock. This query also serves capture events,
2440        // so it deliberately does not take the Rust control permit.
2441        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    /// Keep a notification a capture reported for [`Receiver::next_event`].
2456    fn retain(&self, notification: Notification) {
2457        self.pending.publish(notification);
2458    }
2459
2460    /// Return an undelivered async event without overwriting a newer report.
2461    #[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    /// The one implementation of [`Receiver::wait_for_source_name_change`], also
2476    /// behind the async receivers' version: wait until `deadline` for a
2477    /// change of the connected source's name.
2478    ///
2479    /// The tables are resolved after the caller validated the timeout, so an
2480    /// invalid timeout is reported before a missing capability.
2481    pub(crate) fn wait_for_source_name_change_until(
2482        &self,
2483        deadline: Deadline,
2484        stop: impl Stop,
2485    ) -> Result<Option<SourceNameChange>> {
2486        // The query comes with the function that releases what it returns.
2487        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    /// [`Self::wait_for_source_name_change_until`] through the given tables, so
2493    /// that a test can substitute the SDK functions.
2494    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            // A worker may have replayed while this poller waited for the permit.
2509            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            // SAFETY: the receiver is live and `pointer` is writable. The
2515            // RecvInstance inventory records the native report mutex; `query`
2516            // serializes consumers without excluding connection changes.
2517            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            // Still under the query permit: even a malformed newer report
2533            // supersedes older abandoned reports before its text is decoded.
2534            let sequence = self.source_name.lock().advance();
2535            // The SDK reports a change only once, since the previous call, so a
2536            // strict decoding error here would lose the name for good.
2537            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
2549/// Proof of one receiver, runtime and remaining [`Attempt`] for a native
2550/// capture. Only the receiver's permission-gated entry points make one, through
2551/// [`ReceiverCore::capture_lock`]; it holds no connection lock.
2552///
2553/// `Processing.NDI.Recv.h` documents simultaneous captures, and the SDK manual
2554/// permits connecting "at any time" without explicitly naming this overlap.
2555/// The connection/capture decision rests on native observations and tests on
2556/// Linux x86-64, as the FrameSync threading decision does:
2557///
2558/// - In Standard 6.1.1 and Standard/Advanced 6.3.2 and 6.4.0.2, connection
2559///   changes take the receiver's internal rwlock exclusively and capture takes
2560///   the same lock shared (receiver offset 0x108). Capture releases it around
2561///   a native wait and reacquires it before accessing the connection again.
2562/// - Helgrind 3.19 with four capture threads and 1080p feeds on Standard and
2563///   Advanced 6.3.2 and 6.4.0.2 reports direct cross connect/capture accesses
2564///   only to the byte polling flag at offset 0x152: single-byte loads, and stores
2565///   followed by MFENCE. This is consistent with fenced atomic access that
2566///   Helgrind does not model; a valid std::atomic byte/fence control compiled
2567///   to the same instructions reproduces its warning. These are qualified
2568///   detector results, not an assertion that Helgrind reported no errors.
2569/// - With the Rust exclusion bypassed, sixteen raw capture threads and local
2570///   connect/disconnect/reconnect storms ran for 120 seconds on each of those
2571///   five runtimes with 1920x1080 BGRA/UYVY video, audio and metadata. Frames
2572///   validated without tearing, calls stayed within the checked budgets,
2573///   progress resumed, and every delivered loan was released. Separate brief
2574///   runs on each runtime counted matching native captures and frees directly.
2575/// - Brief FrameSync and AV sync overlap cases, and Discovery Server remote
2576///   control on 6.4, also validate delivery and recovery. Remote changes happen
2577///   inside the SDK and are outside any Rust connection lock.
2578///
2579/// `tests/receiver_connect_overlap_sdk.rs` repeats the applicable cases briefly
2580/// on every runtime/platform the suite runs against. The retained core keeps
2581/// the native instance and its runtime live for the capture and its frames.
2582pub(crate) struct CaptureLock<'rx> {
2583    core: &'rx ReceiverCore,
2584    attempt: Attempt,
2585}
2586
2587/// The receiver owner retained by an authorized capture. Only CaptureLock
2588/// mints this proof, and its private borrow keeps the instance and runtime live.
2589#[derive(Clone, Copy)]
2590pub(crate) struct ReceiverFrameSource<'rx> {
2591    core: &'rx ReceiverCore,
2592}
2593
2594impl crate::capture::source_sealed::Sealed for ReceiverFrameSource<'_> {}
2595
2596// SAFETY: CaptureLock mints this proof from the core it captures through.
2597// The private core borrow retains both its instance and creating runtime.
2598unsafe 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    /// Mint the owner proof for frames delivered by this capture permission.
2612    pub(crate) fn source(&self) -> ReceiverFrameSource<'rx> {
2613        ReceiverFrameSource { core: self.core }
2614    }
2615
2616    /// The receiver's one `NDIlib_recv_capture_v3` call: wait for what is
2617    /// left of this lock's attempt for a frame of a kind whose descriptor is
2618    /// given, or for a notification, and return the frame type the SDK
2619    /// reported.
2620    ///
2621    /// The SDK fills only the descriptor of the kind it returns, and only
2622    /// when that descriptor was given; the caller frees such a frame through
2623    /// the matching `NDIlib_recv_free_*` function of its creating runtime.
2624    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        // SAFETY: the receiver instance is live for 'rx, which this lock
2631        // borrows it for. Each descriptor is null or exclusively borrowed,
2632        // writable storage that outlives the synchronous call. The proof fixes
2633        // this instance and its runtime. Connection changes may overlap this
2634        // call, as supported by the native observations beside CaptureLock.
2635        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/// Pan, tilt, zoom, focus, white balance and exposure control of the source a
2648/// [`Receiver`] is connected to, from [`Receiver::ptz`].
2649///
2650/// A value outside its range, or not finite, is refused with
2651/// [`Error::InvalidInput`] before anything is sent. A command the SDK does
2652/// not send is reported as [`Error::NativeOperationFailed`]. Commands return
2653/// [`Error::NotConnected`] during a local connection change on Standard Windows;
2654/// see the [waiting contract](Receiver#waiting).
2655#[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    /// Whether the connected source accepts PTZ commands.
2670    ///
2671    /// Returns `false` while Standard Windows is changing the connection.
2672    #[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    /// Recall preset `0..=99`, moving at `speed` within `0.0..=1.0`.
2681    ///
2682    /// # Errors
2683    ///
2684    /// See [`Ptz`].
2685    #[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    /// Store the current camera settings as preset `0..=99`.
2693    ///
2694    /// # Errors
2695    ///
2696    /// See [`Ptz`].
2697    #[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    /// Set the absolute zoom within `0.0..=1.0`: zero is zoomed in, one is
2704    /// zoomed out.
2705    ///
2706    /// # Errors
2707    ///
2708    /// See [`Ptz`].
2709    #[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    /// Set the zoom speed within `-1.0..=1.0`: negative zooms out, positive
2716    /// zooms in, zero stops.
2717    ///
2718    /// # Errors
2719    ///
2720    /// See [`Ptz`].
2721    #[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    /// Set the absolute pan and tilt within `-1.0..=1.0`: pan increases from
2728    /// left to right, tilt from bottom to top.
2729    ///
2730    /// # Errors
2731    ///
2732    /// See [`Ptz`].
2733    #[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    /// Set the pan and tilt speeds within `-1.0..=1.0`: positive pans left
2741    /// and tilts up, zero stops.
2742    ///
2743    /// # Errors
2744    ///
2745    /// See [`Ptz`].
2746    #[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    /// Focus automatically.
2754    ///
2755    /// # Errors
2756    ///
2757    /// See [`Ptz`].
2758    #[doc(alias = "NDIlib_recv_ptz_auto_focus")]
2759    pub fn auto_focus(&self) -> Result<()> {
2760        ptz_command!(self, ptz_auto_focus)
2761    }
2762
2763    /// Set the absolute focus within `0.0..=1.0`: zero focuses at infinity,
2764    /// one as close as possible.
2765    ///
2766    /// # Errors
2767    ///
2768    /// See [`Ptz`].
2769    #[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    /// Set the focus speed within `-1.0..=1.0`: negative focuses farther,
2776    /// positive nearer, zero stops.
2777    ///
2778    /// # Errors
2779    ///
2780    /// See [`Ptz`].
2781    #[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    /// Balance white automatically.
2788    ///
2789    /// # Errors
2790    ///
2791    /// See [`Ptz`].
2792    #[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    /// Select the indoor white-balance preset.
2798    ///
2799    /// # Errors
2800    ///
2801    /// See [`Ptz`].
2802    #[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    /// Select the outdoor white-balance preset.
2808    ///
2809    /// # Errors
2810    ///
2811    /// See [`Ptz`].
2812    #[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    /// Balance white once, from the current image.
2818    ///
2819    /// # Errors
2820    ///
2821    /// See [`Ptz`].
2822    #[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    /// Set the red and blue white-balance levels within `0.0..=1.0`.
2828    ///
2829    /// # Errors
2830    ///
2831    /// See [`Ptz`].
2832    #[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    /// Set the exposure automatically.
2840    ///
2841    /// # Errors
2842    ///
2843    /// See [`Ptz`].
2844    #[doc(alias = "NDIlib_recv_ptz_exposure_auto")]
2845    pub fn exposure_auto(&self) -> Result<()> {
2846        ptz_command!(self, ptz_exposure_auto)
2847    }
2848
2849    /// Set the exposure level within `0.0..=1.0`, from dark to light.
2850    ///
2851    /// # Errors
2852    ///
2853    /// See [`Ptz`].
2854    #[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    /// Set the iris, gain and shutter speed within `0.0..=1.0`: iris and gain
2861    /// from dark to light, shutter speed from slow to fast.
2862    ///
2863    /// # Errors
2864    ///
2865    /// See [`Ptz`].
2866    #[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        // SAFETY: exclusive ownership of the last core excludes every native
2878        // use and outstanding frame borrow. The runtime remains live through
2879        // native destruction, before retained descriptors and text are dropped.
2880        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
2891// A panic cannot leave a receiver's shared state half-changed: of its locks,
2892// the target and pending unknown event are replaced whole; the string-query
2893// lock protects complete retained changes. Control-owned registrations install
2894// retained storage before native add and release it only after native clear;
2895// unwinding leaves that storage valid. A native connection change can run
2896// application allocator code under the independent change permit. The
2897// ConnectionChange drop guard restores ControlPermit's changing phase and
2898// takes and replays its pending tally before releasing the change lock.
2899// The `parking_lot` locks do not poison and so do not declare this themselves,
2900// which would otherwise leave `Receiver` short of
2901// `RefUnwindSafe` and a `RecvAdvertiser`, which keeps registered receivers
2902// alive, short of the unwind safety a `SendAdvertiser` has.
2903impl std::panic::RefUnwindSafe for ReceiverCore {}
2904
2905/// A source-name change observed by the native receiver.
2906#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2907#[non_exhaustive]
2908pub enum SourceNameChange {
2909    /// The receiver is now connected to the named source.
2910    Connected(String),
2911    /// The receiver is no longer connected to any source.
2912    Disconnected,
2913}
2914
2915/// An owned item delivered by [`Receiver::capture_any`] or an async
2916/// receiver's combined capture. Media buffers and metadata can outlive the
2917/// receiver and move between threads.
2918#[derive(Debug, Clone)]
2919#[non_exhaustive]
2920pub enum ReceiverItem {
2921    /// Validated uncompressed video with packed active rows.
2922    Video(VideoFrame),
2923    /// Validated planar floating-point audio with packed channels.
2924    Audio(AudioFrame),
2925    /// Standalone frame metadata.
2926    Metadata(MetadataFrame),
2927    /// A consumed, coalesced receiver invalidation.
2928    Event(ReceiverEvent),
2929}
2930
2931/// An item delivered by [`Receiver::capture_any_ref`]. Media borrows native
2932/// storage and keeps the receiver borrowed until its matching guard is
2933/// dropped. Borrowed capture allocates and copies no payload; video row and
2934/// audio channel padding are never exposed as initialized slices.
2935///
2936/// These items implement `Send + Sync` under the same SDK contract as the
2937/// typed receiver references. They may move to scoped worker threads while
2938/// retaining their receiver borrow. Use [`Self::to_owned`] to keep an item
2939/// after releasing the receiver.
2940#[derive(Debug)]
2941#[non_exhaustive]
2942pub enum ReceiverItemRef<'rx> {
2943    /// Validated uncompressed video, possibly with padded rows or planes.
2944    Video(VideoFrameRef<'rx>),
2945    /// Validated planar audio, possibly with padded channels.
2946    Audio(AudioFrameRef<'rx>),
2947    /// Standalone frame metadata.
2948    Metadata(MetadataFrameRef<'rx>),
2949    /// A consumed, coalesced receiver invalidation; no native buffer.
2950    Event(ReceiverEvent),
2951}
2952
2953impl ReceiverItemRef<'_> {
2954    /// Copy media into an owned item using the typed capture copy paths.
2955    /// Video rows and audio channels become packed; timing and metadata are
2956    /// preserved. Video/audio allocate one payload buffer and metadata when
2957    /// present; metadata allocates its text; events simply copy their value.
2958    /// This makes no SDK call and retains no native frame or receiver borrow.
2959    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/// A coalesced receiver invalidation, not an ordered event history.
2970#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2971#[non_exhaustive]
2972pub enum ReceiverEvent {
2973    /// The SDK reported changed status information, such as source capabilities.
2974    ///
2975    /// Connection loss can produce no such event. Poll [`Receiver::is_connected`]
2976    /// or [`Receiver::connection_stats`] to track the connection itself.
2977    StatusChanged(ReceiverStatus),
2978    /// The connected source changed; poll its name for the new value.
2979    SourceChanged,
2980    /// An unknown non-media event value; no unknown payload is exposed.
2981    Unknown(u32),
2982}
2983
2984/// What a status-change notification reports: the current connection count.
2985///
2986/// The notification may also mean that the source's capabilities or web
2987/// control changed; the SDK does not say which. Its connection count is a
2988/// snapshot taken when the event is consumed, and connection loss need not
2989/// produce an event. Poll [`Receiver::is_connected`] or
2990/// [`Receiver::connection_stats`] for connection tracking. Tally is published
2991/// upstream through [`Receiver::set_tally`], rather than received here.
2992#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2993pub struct ReceiverStatus {
2994    connections: u32,
2995}
2996
2997impl ReceiverStatus {
2998    /// The number of sources the receiver is connected to: normally zero or
2999    /// one.
3000    #[must_use]
3001    pub const fn connections(self) -> u32 {
3002        self.connections
3003    }
3004}
3005
3006/// Whether a source is shown on program output, on preview, or both.
3007#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3008pub struct Tally {
3009    on_program: bool,
3010    on_preview: bool,
3011}
3012
3013impl Tally {
3014    /// A tally state: on program (live) output, on preview, both or neither.
3015    #[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    /// Whether the source is on program (live) output.
3024    #[must_use]
3025    pub const fn on_program(self) -> bool {
3026        self.on_program
3027    }
3028
3029    /// Whether the source is on preview output.
3030    #[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/// Whether a setting changed.
3044///
3045/// Returned by the setters whose SDK call reports whether it changed anything.
3046/// Callers that only want the setting in effect can ignore it.
3047#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3048pub enum SettingChange {
3049    /// The setting changed.
3050    Applied,
3051    /// The setting did not change: it was already in effect, or the SDK did
3052    /// not apply it. Each setter says when the SDK does not.
3053    Unchanged,
3054}
3055
3056impl SettingChange {
3057    /// The change an SDK call reported with `changed`.
3058    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/// Connection and performance statistics for a receiver.
3068///
3069/// Connection count, frame counts, drop rates and queue depths, from
3070/// [`Receiver::connection_stats`]. These are native counter snapshots, not an
3071/// atomic view of connection, performance and queue state. Counters can reset
3072/// when a connection changes. Received totals include frames later dropped by
3073/// the receiver queue or processing; drops are not a count of lost network
3074/// packets or a measure of downstream playback quality. For interval rates,
3075/// reset the baseline when either counter decreases or the source/connection
3076/// is explicitly reset.
3077#[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    /// The number of active connections.
3093    #[must_use]
3094    pub const fn connections(&self) -> u32 {
3095        self.connections
3096    }
3097
3098    /// The native total number of video frames received, including later drops.
3099    #[must_use]
3100    pub const fn video_frames_received(&self) -> u64 {
3101        self.video_frames_received
3102    }
3103
3104    /// The native total number of audio frames received, including later drops.
3105    #[must_use]
3106    pub const fn audio_frames_received(&self) -> u64 {
3107        self.audio_frames_received
3108    }
3109
3110    /// The native total number of metadata frames received, including later drops.
3111    #[must_use]
3112    pub const fn metadata_frames_received(&self) -> u64 {
3113        self.metadata_frames_received
3114    }
3115
3116    /// The number of video frames dropped, because a buffer overflowed or
3117    /// processing fell behind.
3118    #[must_use]
3119    pub const fn video_frames_dropped(&self) -> u64 {
3120        self.video_frames_dropped
3121    }
3122
3123    /// The number of audio frames dropped.
3124    #[must_use]
3125    pub const fn audio_frames_dropped(&self) -> u64 {
3126        self.audio_frames_dropped
3127    }
3128
3129    /// The number of metadata frames dropped.
3130    #[must_use]
3131    pub const fn metadata_frames_dropped(&self) -> u64 {
3132        self.metadata_frames_dropped
3133    }
3134
3135    /// The number of video frames queued, waiting to be captured.
3136    #[must_use]
3137    pub const fn video_frames_queued(&self) -> u32 {
3138        self.video_frames_queued
3139    }
3140
3141    /// The number of audio frames queued.
3142    #[must_use]
3143    pub const fn audio_frames_queued(&self) -> u32 {
3144        self.audio_frames_queued
3145    }
3146
3147    /// The number of metadata frames queued.
3148    #[must_use]
3149    pub const fn metadata_frames_queued(&self) -> u32 {
3150        self.metadata_frames_queued
3151    }
3152
3153    /// Cumulative receiver video queue/processing drops as a percentage of
3154    /// the native received total. Returns 0.0 for zero received frames and is
3155    /// bounded to 0..=100 even when native snapshots disagree.
3156    #[must_use]
3157    pub fn video_drop_percentage(&self) -> f64 {
3158        drop_percentage(self.video_frames_received, self.video_frames_dropped)
3159    }
3160
3161    /// Cumulative receiver audio queue/processing drops as a percentage of
3162    /// the native received total. Returns 0.0 for zero received frames and is
3163    /// bounded to 0..=100 even when native snapshots disagree.
3164    #[must_use]
3165    pub fn audio_drop_percentage(&self) -> f64 {
3166        drop_percentage(self.audio_frames_received, self.audio_frames_dropped)
3167    }
3168
3169    /// Cumulative receiver metadata queue/processing drops as a percentage of
3170    /// the native received total. Returns 0.0 for zero received frames and is
3171    /// bounded to 0..=100 even when native snapshots disagree.
3172    #[must_use]
3173    pub fn metadata_drop_percentage(&self) -> f64 {
3174        drop_percentage(self.metadata_frames_received, self.metadata_frames_dropped)
3175    }
3176
3177    /// Whether there is at least one native connection; this does not
3178    /// establish progress of a particular media stream.
3179    #[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        // Stops at the first terminator.
3466        assert_eq!(copy(b"a\0\xff\0").unwrap().as_deref(), Some("a"));
3467        // A terminator in the last byte the scan may read is accepted.
3468        let mut longest = vec![b'x'; max];
3469        longest[max - 1] = 0;
3470        assert_eq!(copy(&longest).unwrap().unwrap().len(), max - 1);
3471        // Without one, the scan stops at the bound and reports an error.
3472        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            // What the fake SDK reports next: whether the name changed, and
3499            // the new name, if any.
3500            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            // SAFETY: the caller passes writable storage for the pointer.
3516            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        // A string returned without a change is still released.
3558        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        // The entry gate already authorized the first attempt; stopping affects
3617        // later attempts even when a query returns immediately with no change.
3618        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            // SAFETY: the caller provides writable storage and the string is static.
3650            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                // SAFETY: the caller provides writable storage for the pointer.
3708                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                // Disconnecting the channel also releases the query on unwind.
3745                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    /// A named target with no sender in the fixture.
3757    fn test_source() -> Source {
3758        Source::new("receiver test target").unwrap()
3759    }
3760
3761    /// The options of a receiver that stays unconnected.
3762    fn unconnected() -> ReceiverOptions {
3763        ReceiverOptions::disconnected()
3764    }
3765
3766    /// A clock that moves only when a test advances it, to drive
3767    /// [`capture_within_clock`].
3768    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        /// A caller's budget that started when this clock did.
3794        fn deadline(&self, budget: Duration) -> Deadline {
3795            Deadline::starting(self.start, crate::timeout::Timeout::new(budget).unwrap()).unwrap()
3796        }
3797
3798        /// What is left of `attempt` now: the timeout its SDK call would get,
3799        /// for the current attempt.
3800        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        // These proofs coexist while native allocator state supplies its own lock.
4088        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                // A policy destructor may use shared controls through this permit.
4105                // Use try_lock so a regression reports failure without hanging.
4106                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            // Release the connection lock before inspecting the outcome, so a
4163            // regression fails instead of leaving scoped threads deadlocked.
4164            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                // Keep the attempt live across this wait. An accidental Rust
4210                // exclusion would hold the reconnect off until this block ends.
4211                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        // Tally is kept for a later connection. Metadata has nowhere to go,
4374        // which runtimes may or may not report; either way the call returns.
4375        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-owned observations never consult a replaced connection.
4418        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        // These families do not need optional runtime entry points. Each must
4456        // wait for the same shared-control permit; connection changes use
4457        // their independent permit.
4458        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            // SAFETY: both descriptors use the URL member of their union.
4583            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        // SAFETY: receive settings initialize the address pointer in the union.
4603        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                // The SDK overran the attempt's timeout and the budget.
4864                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                // An early return, 1 ms short of the attempt's timeout.
4888                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        // Every attempt waits out its timeout, as when no frame is sent: the
4906        // next attempt starts at once, so a frame arriving in between is taken
4907        // without a pause.
4908        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        // Warm-up: the SDK returns 3 ms into the first attempt and at once on
4938        // the second, then waits out the third, and the fourth delivers.
4939        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        // One deadline for the whole call: 3 + 10 + 0 + 10 + 100 ms.
4965        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        // Early returns, full waits and overruns alike: every attempt's
4971        // requested wait ends within one poll interval and the caller's budget.
4972        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        // A caller's 50 ms budget of which 30 ms went before the retry began,
4998        // as when an async capture waited for a blocking-pool thread.
4999        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        // `None` comes only once the whole budget is spent.
5056        assert!(deadline.is_expired());
5057        // The first poll is taken from what was left after the caller's 5 ms.
5058        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// This fixture is compiled in the crate, so it exercises internal gates rather
5110// than failing because an external doctest cannot access private methods.
5111#[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;