Skip to main content

grafton_ndi/discovery/
listener.rs

1//! Snapshots of, events from, and connection requests to what a Discovery
2//! Server advertises.
3
4use super::{Retained, ServerApi, ServerObject};
5use crate::{
6    finder::{SourceName, SourceText, SourceTextView},
7    sdk_copy::{
8        bounded_sdk_text, copy_lossy, CopyBudget, CopyResult, LossyText, SpanError, COPY_LIMIT,
9        MAX_SDK_STRING_BYTES,
10    },
11    sys::{self, bindings::*},
12    to_ms_checked, Error, Ndi, ResourceKind, Result,
13};
14use std::{
15    borrow::Cow,
16    collections::BTreeSet,
17    ffi::{c_char, CStr, CString},
18    fmt,
19    num::NonZeroU16,
20    ptr,
21    time::Duration,
22};
23
24/// The operations the sender and receiver listener tables have in common.
25trait ListenerApi: ServerApi {
26    type Entry;
27    type Id: Identifier;
28    /// # Safety
29    ///
30    /// Each method requires `instance` to be a live listener created by this
31    /// table; pointer arguments must be valid for the SDK's documented use.
32    unsafe fn is_connected(&self, instance: Self::Instance) -> bool;
33    unsafe fn server_url(&self, instance: Self::Instance) -> *const c_char;
34    unsafe fn entries(&self, instance: Self::Instance, count: &mut u32) -> *const Self::Entry;
35    unsafe fn wait_for_entries(&self, instance: Self::Instance, timeout_ms: u32) -> bool;
36    unsafe fn subscribe(&self, instance: Self::Instance, id: *const c_char);
37    unsafe fn unsubscribe(&self, instance: Self::Instance, id: *const c_char);
38    unsafe fn events(
39        &self,
40        instance: Self::Instance,
41        count: &mut u32,
42        timeout_ms: u32,
43    ) -> *const NDIlib_listener_event;
44    unsafe fn free_events(&self, instance: Self::Instance, events: *const NDIlib_listener_event);
45}
46
47macro_rules! listener_api {
48    (
49        $Table:ty, $Entry:ty, $Id:ty,
50        is_connected = $is_connected:ident,
51        server_url = $server_url:ident,
52        entries = $entries:ident,
53        wait = $wait:ident,
54        subscribe = $subscribe:ident,
55        unsubscribe = $unsubscribe:ident,
56        events = $events:ident,
57        free_events = $free_events:ident
58    ) => {
59        impl ListenerApi for $Table {
60            type Entry = $Entry;
61            type Id = $Id;
62            unsafe fn is_connected(&self, instance: Self::Instance) -> bool {
63                self.$is_connected(instance.0)
64            }
65            unsafe fn server_url(&self, instance: Self::Instance) -> *const c_char {
66                self.$server_url(instance.0)
67            }
68            unsafe fn entries(
69                &self,
70                instance: Self::Instance,
71                count: &mut u32,
72            ) -> *const Self::Entry {
73                self.$entries(instance.0, count)
74            }
75            unsafe fn wait_for_entries(&self, instance: Self::Instance, timeout_ms: u32) -> bool {
76                self.$wait(instance.0, timeout_ms)
77            }
78            unsafe fn subscribe(&self, instance: Self::Instance, id: *const c_char) {
79                self.$subscribe(instance.0, id)
80            }
81            unsafe fn unsubscribe(&self, instance: Self::Instance, id: *const c_char) {
82                self.$unsubscribe(instance.0, id)
83            }
84            unsafe fn events(
85                &self,
86                instance: Self::Instance,
87                count: &mut u32,
88                timeout_ms: u32,
89            ) -> *const NDIlib_listener_event {
90                self.$events(instance.0, count, timeout_ms)
91            }
92            unsafe fn free_events(
93                &self,
94                instance: Self::Instance,
95                events: *const NDIlib_listener_event,
96            ) {
97                self.$free_events(instance.0, events)
98            }
99        }
100    };
101}
102
103listener_api!(
104    sys::SenderDiscovery,
105    NDIlib_sender_t,
106    SenderId,
107    is_connected = NDIlib_send_listener_is_connected,
108    server_url = NDIlib_send_listener_get_server_url,
109    entries = NDIlib_send_listener_get_senders,
110    wait = NDIlib_send_listener_wait_for_senders,
111    subscribe = NDIlib_send_listener_subscribe_events,
112    unsubscribe = NDIlib_send_listener_unsubscribe_events,
113    events = NDIlib_send_listener_get_events,
114    free_events = NDIlib_send_listener_free_events
115);
116listener_api!(
117    sys::ReceiverDiscovery,
118    NDIlib_receiver_t,
119    ReceiverId,
120    is_connected = NDIlib_recv_listener_is_connected,
121    server_url = NDIlib_recv_listener_get_server_url,
122    entries = NDIlib_recv_listener_get_receivers,
123    wait = NDIlib_recv_listener_wait_for_receivers,
124    subscribe = NDIlib_recv_listener_subscribe_events,
125    unsubscribe = NDIlib_recv_listener_unsubscribe_events,
126    events = NDIlib_recv_listener_get_events,
127    free_events = NDIlib_recv_listener_free_events
128);
129
130/// The Discovery Server a listener connects to.
131///
132/// Without an explicit server the SDK uses the Discovery Server from the NDI
133/// configuration. Creation fails when it names no server or one the SDK
134/// cannot use.
135#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
136pub struct ListenerOptions {
137    server: Option<String>,
138    #[cfg(feature = "advanced")]
139    config: Option<crate::advanced::AdvancedConfig>,
140}
141impl ListenerOptions {
142    /// Inherit the Discovery Server endpoint from the NDI configuration.
143    #[must_use]
144    pub fn clear_server(mut self) -> Self {
145        self.server = None;
146        self
147    }
148
149    /// Remove the per-instance Advanced configuration override.
150    #[cfg(feature = "advanced")]
151    #[must_use]
152    pub fn clear_config(mut self) -> Self {
153        self.config = None;
154        self
155    }
156
157    /// Requested server endpoint, or `None` to inherit the NDI configuration.
158    #[must_use]
159    pub fn configured_server(&self) -> Option<&str> {
160        self.server.as_deref()
161    }
162
163    /// The stored Advanced configuration handle, if any.
164    #[cfg(feature = "advanced")]
165    #[must_use]
166    pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
167        self.config.as_ref()
168    }
169
170    /// The default options: the Discovery Server of the NDI configuration.
171    pub fn new() -> Self {
172        Self::default()
173    }
174    /// Use one non-empty endpoint in place of the NDI configuration: a host name
175    /// or IP address, optionally followed by a colon and a port (5959 when
176    /// omitted). Use [`Self::clear_server`] to inherit the configuration.
177    ///
178    /// The listener constructors refuse a comma-separated list of endpoints.
179    #[must_use]
180    pub fn server(mut self, server: impl Into<String>) -> Self {
181        self.server = Some(server.into());
182        self
183    }
184    /// Create the listener with this per-instance Advanced SDK configuration,
185    /// which it keeps for as long as it lives.
186    ///
187    /// [`SendListener::new`] and [`RecvListener::new`] then need an Advanced
188    /// runtime, and a build with the Advanced SDK.
189    #[cfg(feature = "advanced")]
190    #[must_use]
191    pub fn config(mut self, config: crate::advanced::AdvancedConfig) -> Self {
192        self.config = Some(config);
193        self
194    }
195}
196
197/// An identifier a Discovery Server assigned, kept byte for byte.
198///
199/// Each kind of identifier is its own type, so one cannot be passed where
200/// another is meant.
201trait Identifier: Sized + Clone + Ord {
202    /// The identifier with exactly the bytes the server supplied.
203    fn from_exact(bytes: CString) -> Self;
204    /// Those bytes, as the SDK takes them back.
205    fn as_c_str(&self) -> &CStr;
206}
207
208macro_rules! identifier {
209    ($(#[$doc:meta])* $Id:ident) => {
210        $(#[$doc])*
211        ///
212        /// The identifier is opaque: no UUID spelling is assumed, and it keeps
213        /// exactly the bytes the server supplied, so it always names the same
214        /// peer even when those bytes are not valid UTF-8.
215        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
216        pub struct $Id(CString);
217
218        impl $Id {
219            /// Make an identifier from bytes obtained elsewhere, such as a
220            /// saved selection.
221            ///
222            /// # Errors
223            ///
224            /// Returns [`Error::InvalidCString`] when the bytes contain a NUL.
225            pub fn new(value: impl Into<Vec<u8>>) -> Result<Self> {
226                Ok(Self(CString::new(value)?))
227            }
228            /// The exact bytes the server supplied.
229            pub fn as_bytes(&self) -> &[u8] {
230                self.0.as_bytes()
231            }
232            /// The identifier as text for display, with any bytes that are not
233            /// UTF-8 replaced by U+FFFD. Use the identifier itself, not this
234            /// text, to name the peer again.
235            pub fn to_string_lossy(&self) -> Cow<'_, str> {
236                self.0.to_string_lossy()
237            }
238        }
239
240        impl fmt::Display for $Id {
241            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242                f.write_str(&self.to_string_lossy())
243            }
244        }
245
246        impl Identifier for $Id {
247            fn from_exact(bytes: CString) -> Self {
248                Self(bytes)
249            }
250            fn as_c_str(&self) -> &CStr {
251                &self.0
252            }
253        }
254    };
255}
256
257identifier!(
258    /// The identifier a Discovery Server gives an advertised sender.
259    ///
260    /// [`SendListener`] reports it and takes it back to subscribe to the
261    /// sender's events.
262    SenderId
263);
264identifier!(
265    /// The identifier a Discovery Server gives an advertised receiver.
266    ///
267    /// [`RecvListener`] reports it and takes it back to subscribe to the
268    /// receiver's events and to ask the receiver to change source.
269    ReceiverId
270);
271identifier!(
272    /// The identifier a Discovery Server gives a receiver's input group.
273    ///
274    /// Receivers advertised with the same
275    /// [input group](super::RecvAdvertisement::input_group) report the same
276    /// identifier. It names a group, not a receiver, so no operation takes it.
277    InputGroupId
278);
279
280/// An event a subscribed sender or receiver reported.
281///
282/// `Id` is the kind of peer the event came from: [`SenderId`] for the events
283/// of a [`SendListener`], [`ReceiverId`] for those of a [`RecvListener`].
284///
285/// Event names and values are defined by the peer and are preserved as sent,
286/// apart from the lossy decoding described on [`ListenerEvent::name`].
287#[derive(Debug, Clone, PartialEq, Eq, Hash)]
288pub struct ListenerEvent<Id> {
289    id: Option<Id>,
290    name: Option<String>,
291    value: Option<String>,
292}
293impl<Id> ListenerEvent<Id> {
294    /// The peer the event came from, when the server supplied it.
295    pub fn id(&self) -> Option<&Id> {
296        self.id.as_ref()
297    }
298    /// The event's name. Bytes that are not UTF-8 are replaced by U+FFFD.
299    pub fn name(&self) -> Option<&str> {
300        self.name.as_deref()
301    }
302    /// The event's value. Bytes that are not UTF-8 are replaced by U+FFFD.
303    pub fn value(&self) -> Option<&str> {
304        self.value.as_deref()
305    }
306}
307
308/// A receiver stream kind. These are individual values, not bit flags.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
310#[non_exhaustive]
311pub enum ReceiverStream {
312    /// The receiver accepts metadata.
313    Metadata,
314    /// The receiver accepts video.
315    Video,
316    /// The receiver accepts audio.
317    Audio,
318    /// A stream kind this crate does not name, with its native value.
319    Unknown(u32),
320}
321impl ReceiverStream {
322    /// The stream kind the SDK's `value` names, or `None` for the SDK's
323    /// "none", which only terminates the list a receiver advertises.
324    fn from_sdk(value: NDIlib_receiver_type_e) -> Option<Self> {
325        match value {
326            sys::bindings::NDIlib_receiver_type_e_NDIlib_receiver_type_none => None,
327            sys::bindings::NDIlib_receiver_type_e_NDIlib_receiver_type_metadata => {
328                Some(Self::Metadata)
329            }
330            sys::bindings::NDIlib_receiver_type_e_NDIlib_receiver_type_video => Some(Self::Video),
331            sys::bindings::NDIlib_receiver_type_e_NDIlib_receiver_type_audio => Some(Self::Audio),
332            value => Some(Self::Unknown(value)),
333        }
334    }
335}
336/// A remote command a receiver advertises that it accepts.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
338#[non_exhaustive]
339pub enum ReceiverCommand {
340    /// The receiver accepts requests to connect to another source.
341    Connect,
342    /// A command this crate does not name, with its native value.
343    Unknown(u32),
344}
345impl ReceiverCommand {
346    /// The command the SDK's `value` names, or `None` for the SDK's "none",
347    /// which only terminates the list a receiver advertises.
348    fn from_sdk(value: NDIlib_receiver_command_e) -> Option<Self> {
349        match value {
350            sys::bindings::NDIlib_receiver_command_e_NDIlib_receiver_command_none => None,
351            sys::bindings::NDIlib_receiver_command_e_NDIlib_receiver_command_connect => {
352                Some(Self::Connect)
353            }
354            value => Some(Self::Unknown(value)),
355        }
356    }
357}
358
359#[derive(Debug, Clone, PartialEq, Eq, Hash)]
360enum AdvertisedSourceText {
361    Exact(SourceText),
362    DisplayOnly(String),
363}
364
365impl AdvertisedSourceText {
366    /// # Safety
367    /// The pointer is null or readable through its first NUL or the SDK bound.
368    unsafe fn copy(
369        pointer: *const std::ffi::c_char,
370        budget: &mut CopyBudget,
371    ) -> CopyResult<Option<Self>> {
372        // SAFETY: forwarded to the caller's bounded read obligation.
373        let Some(raw) = (unsafe { budget.c_str(pointer)? }) else {
374            return Ok(None);
375        };
376        let field = match SourceTextView::new(raw) {
377            Ok(text) => {
378                budget.take(text.as_str().len() + SourceText::STORAGE_OVERHEAD)?;
379                Self::Exact(SourceText::from_sdk(
380                    text,
381                    crate::AllocationKind::DiscoveryResults,
382                )?)
383            }
384            Err(_) => {
385                let text = LossyText::new(raw);
386                budget.take(text.len())?;
387                Self::DisplayOnly(
388                    text.copy()
389                        .map_err(|_| crate::sdk_copy::allocation_failed())?,
390                )
391            }
392        };
393        Ok(Some(field))
394    }
395
396    fn as_str(&self) -> &str {
397        match self {
398            Self::Exact(text) => text.as_str(),
399            Self::DisplayOnly(text) => text,
400        }
401    }
402}
403
404/// An owned description of one advertised sender, independent of later
405/// listener calls.
406///
407/// Every string is whatever the sender advertised. Text that is not valid
408/// UTF-8 is decoded with U+FFFD in place of the offending bytes; only the
409/// [identifier](Self::id) keeps its exact bytes. [`Self::to_source`] requires
410/// the original name and any advertised address to be valid UTF-8.
411#[derive(Debug, Clone, PartialEq, Eq, Hash)]
412pub struct AdvertisedSender {
413    id: Option<SenderId>,
414    name: Option<AdvertisedSourceText>,
415    metadata: Option<String>,
416    address: Option<AdvertisedSourceText>,
417    port: Option<NonZeroU16>,
418    groups: Vec<String>,
419    subscribed: bool,
420}
421impl AdvertisedSender {
422    /// The server's identifier for this sender.
423    pub fn id(&self) -> Option<&SenderId> {
424        self.id.as_ref()
425    }
426    /// The sender's source name.
427    pub fn name(&self) -> Option<&str> {
428        self.name.as_ref().map(AdvertisedSourceText::as_str)
429    }
430    /// The connection metadata the sender advertises.
431    pub fn metadata(&self) -> Option<&str> {
432        self.metadata.as_deref()
433    }
434    /// The sender's network address.
435    pub fn address(&self) -> Option<&str> {
436        self.address.as_ref().map(AdvertisedSourceText::as_str)
437    }
438    /// The sender's non-zero network port, or `None` when the advertised value
439    /// is outside the range 1–65535.
440    pub fn port(&self) -> Option<NonZeroU16> {
441        self.port
442    }
443    /// The discovery groups the sender belongs to.
444    pub fn groups(&self) -> &[String] {
445        &self.groups
446    }
447    /// Convert this advertised sender into a connection target.
448    ///
449    /// Returns `None` when the server supplied no source name or when the
450    /// original name or address contains invalid UTF-8. An address is included
451    /// when the advertised host is an IP address or host name and the port is
452    /// non-zero. IPv6 literals are enclosed in brackets. Otherwise the receiver
453    /// can look up the source by name.
454    pub fn to_source(&self) -> Option<crate::Source> {
455        let AdvertisedSourceText::Exact(name) = self.name.as_ref()? else {
456            return None;
457        };
458        let host = match self.address.as_ref() {
459            Some(AdvertisedSourceText::Exact(address)) => Some(address.as_str()),
460            Some(AdvertisedSourceText::DisplayOnly(_)) => return None,
461            None => None,
462        };
463        let address = host
464            .zip(self.port)
465            .and_then(|(host, port)| crate::SourceAddress::from_advertised_host(host, port));
466        Some(crate::Source::from_text(name.clone(), address))
467    }
468
469    /// Whether this listener is subscribed to the sender's events.
470    pub fn events_subscribed(&self) -> bool {
471        self.subscribed
472    }
473}
474/// An owned description of one advertised receiver, independent of later
475/// listener calls.
476///
477/// Every string is whatever the receiver advertised. Text that is not valid
478/// UTF-8 is decoded with U+FFFD in place of the offending bytes; only the
479/// identifiers keep their exact bytes.
480#[derive(Debug, Clone, PartialEq, Eq, Hash)]
481pub struct AdvertisedReceiver {
482    id: Option<ReceiverId>,
483    name: Option<String>,
484    input_id: Option<InputGroupId>,
485    input_name: Option<String>,
486    address: Option<String>,
487    streams: Vec<ReceiverStream>,
488    commands: Vec<ReceiverCommand>,
489    subscribed: bool,
490}
491impl AdvertisedReceiver {
492    /// The server's identifier for this receiver.
493    pub fn id(&self) -> Option<&ReceiverId> {
494        self.id.as_ref()
495    }
496    /// The receiver's name.
497    pub fn name(&self) -> Option<&str> {
498        self.name.as_deref()
499    }
500    /// The identifier of the input group the receiver belongs to.
501    pub fn input_id(&self) -> Option<&InputGroupId> {
502        self.input_id.as_ref()
503    }
504    /// The name of the input group the receiver belongs to, which is empty
505    /// for a receiver advertised without one.
506    pub fn input_name(&self) -> Option<&str> {
507        self.input_name.as_deref()
508    }
509    /// The receiver's network address.
510    pub fn address(&self) -> Option<&str> {
511        self.address.as_deref()
512    }
513    /// The stream kinds the receiver accepts.
514    pub fn streams(&self) -> &[ReceiverStream] {
515        &self.streams
516    }
517    /// The remote commands the receiver accepts.
518    pub fn commands(&self) -> &[ReceiverCommand] {
519        &self.commands
520    }
521    /// Whether this listener is subscribed to the receiver's events.
522    pub fn events_subscribed(&self) -> bool {
523        self.subscribed
524    }
525}
526
527fn copy_budget() -> CopyBudget {
528    CopyBudget::new(COPY_LIMIT, ResourceKind::DiscoveryServerCopyBytes)
529}
530
531/// Compare only the prefix that could match, including its exact terminator.
532/// No native string, including one compared with a longer caller-supplied ID,
533/// is read beyond the SDK string bound.
534///
535/// # Safety
536/// A non-null `value` must remain readable byte by byte until the first NUL,
537/// mismatching byte, or `MAX_SDK_STRING_BYTES`, whichever comes first.
538unsafe fn receiver_id_matches(value: *const c_char, id: &ReceiverId) -> bool {
539    if value.is_null() {
540        return false;
541    }
542    for (offset, &expected) in id
543        .as_c_str()
544        .to_bytes_with_nul()
545        .iter()
546        .take(MAX_SDK_STRING_BYTES)
547        .enumerate()
548    {
549        // SAFETY: the comparison stops at the first mismatch or NUL, and the
550        // iterator caps every native read at the SDK string bound.
551        let byte = unsafe { value.cast::<u8>().add(offset).read() };
552        if byte != expected {
553            return false;
554        }
555        if byte == 0 {
556            return true;
557        }
558    }
559    false
560}
561
562/// Validate one receiver's connection-request precondition without copying
563/// the registry or inspecting fields unrelated to its ID and commands.
564///
565/// # Safety
566/// Every non-null UUID must satisfy `receiver_id_matches`'s readable bound.
567/// A matched entry's non-null commands pointer must hold its stated number
568/// of initialized commands. All of this storage must remain unchanged for
569/// the call. Other pointer fields are never read.
570pub(crate) unsafe fn require_receiver_connect(
571    receivers: &[NDIlib_receiver_t],
572    id: &ReceiverId,
573    budget: &mut CopyBudget,
574) -> Result<()> {
575    let Some(receiver) = receivers.iter().find(|receiver| {
576        // SAFETY: the caller keeps each UUID's bounded prefix readable.
577        unsafe { receiver_id_matches(receiver.p_uuid, id) }
578    }) else {
579        return Err(Error::ReceiverRequestNotAccepted { advertised: false });
580    };
581    // SAFETY: the caller keeps the matched command array readable. Preflight
582    // validates its pointer, count, span and budget before constructing a slice.
583    let commands =
584        match unsafe { budget.slice(receiver.p_commands.cast_const(), receiver.num_commands) } {
585            Ok(commands) => commands,
586            Err(SpanError::Array(_)) => {
587                return Err(Error::ReceiverRequestNotAccepted { advertised: true });
588            }
589            Err(SpanError::Failed(error)) => return Err(error),
590        };
591    if commands.contains(&NDIlib_receiver_command_e_NDIlib_receiver_command_connect) {
592        Ok(())
593    } else {
594        Err(Error::ReceiverRequestNotAccepted { advertised: true })
595    }
596}
597
598/// Copy the Discovery Server endpoint a listener reports: `None` for a null
599/// pointer, or for a string with no terminator within
600/// [`MAX_SDK_STRING_BYTES`], and bytes that are not UTF-8 replaced with
601/// U+FFFD.
602///
603/// # Safety
604///
605/// A non-null `url` must be readable byte by byte until either its first NUL
606/// or [`MAX_SDK_STRING_BYTES`] bytes have been read.
607unsafe fn endpoint(url: *const c_char) -> Option<String> {
608    if url.is_null() {
609        return None;
610    }
611    // SAFETY: forwarded to the caller's obligation for a non-null pointer.
612    let bytes = unsafe { bounded_sdk_text(url, MAX_SDK_STRING_BYTES) }?;
613    Some(copy_lossy(bytes))
614}
615
616/// A listener adds membership operations to the shared lifecycle owner.
617struct Listener<A: ListenerApi>(ServerObject<A, BTreeSet<A::Id>>);
618
619// SAFETY: the default set is empty. Subscription changes retain each ID until
620// its own listener unsubscribes or is destroyed; no pre-destroy calls are needed.
621unsafe impl<A: ListenerApi> Retained<A> for BTreeSet<A::Id> {}
622
623const_assert!({
624    const fn assert_send<T: Send>() {}
625    assert_send::<Listener<sys::SenderDiscovery>>();
626    assert_send::<Listener<sys::ReceiverDiscovery>>();
627});
628
629impl<A: ListenerApi> Listener<A>
630where
631    A: ServerApi<Options = ListenerOptions>,
632{
633    fn new(ndi: &Ndi, options: &ListenerOptions) -> Result<Self> {
634        ServerObject::new(ndi, options).map(Self)
635    }
636}
637
638impl<A: ListenerApi> Listener<A> {
639    fn is_connected(&self) -> bool {
640        // SAFETY: the listener instance is live for this borrow.
641        unsafe { self.0.api.is_connected(self.0.instance()) }
642    }
643    fn server_url(&self) -> Option<String> {
644        // SAFETY: the listener instance is live for this borrow.
645        let url = unsafe { self.0.api.server_url(self.0.instance()) };
646        // SAFETY: Processing.NDI.{Send,Recv}Listener.h only documents that the
647        // result may be null; it promises neither a lifetime nor a terminator.
648        // The bounded endpoint copy completes within this borrow, and this
649        // Send, !Sync owner prevents another listener call during that copy.
650        // We assume a non-null getter result stays readable through its first
651        // NUL or the SDK string bound for that interval. The real-server getter
652        // check in tests/discovery_server.rs exercises that SDK assumption.
653        unsafe { endpoint(url) }
654    }
655    fn wait_for_change(&mut self, timeout: Duration) -> Result<bool> {
656        let timeout = to_ms_checked(timeout)?;
657        // SAFETY: the listener instance is live for this borrow.
658        Ok(unsafe { self.0.api.wait_for_entries(self.0.instance(), timeout) })
659    }
660    /// The native membership snapshot, valid until the next call on this listener.
661    fn entries<'a>(&'a mut self, budget: &mut CopyBudget) -> Result<&'a [A::Entry]> {
662        let mut count = 0;
663        // SAFETY: the exclusive borrow keeps the SDK-owned array unchanged for
664        // `'a`; the budget validates the pointer and count before use.
665        Ok(unsafe { budget.slice(self.0.api.entries(self.0.instance(), &mut count), count) }?)
666    }
667    fn subscription(&mut self, id: &A::Id, subscribe: bool) {
668        if subscribe {
669            let pointer = if let Some(retained) = self.0.retained().get(id) {
670                retained.as_c_str().as_ptr()
671            } else {
672                let retained = id.clone();
673                let pointer = retained.as_c_str().as_ptr();
674                self.0.retained_mut().insert(retained);
675                pointer
676            };
677            // SAFETY: the listener and its stable identifier allocation stay
678            // live until unsubscribe returns or after native destruction.
679            unsafe { self.0.api.subscribe(self.0.instance(), pointer) };
680        } else {
681            let retained = self.0.retained().get(id).unwrap_or(id);
682            // SAFETY: a retained identifier stays live through unsubscribe;
683            // an identifier never subscribed is borrowed only for this call.
684            unsafe {
685                self.0
686                    .api
687                    .unsubscribe(self.0.instance(), retained.as_c_str().as_ptr())
688            };
689            self.0.retained_mut().remove(id);
690        }
691    }
692    fn next_events(&mut self, timeout: Duration) -> Result<Vec<ListenerEvent<A::Id>>> {
693        struct Batch<'a, A: ListenerApi> {
694            listener: &'a Listener<A>,
695            events: *const NDIlib_listener_event,
696        }
697        impl<A: ListenerApi> Drop for Batch<'_, A> {
698            fn drop(&mut self) {
699                // SAFETY: the batch came from this listener and is freed once.
700                unsafe {
701                    self.listener
702                        .0
703                        .api
704                        .free_events(self.listener.0.instance(), self.events)
705                };
706            }
707        }
708        let timeout = to_ms_checked(timeout)?;
709        let mut count = 0;
710        // SAFETY: the listener instance is live for this borrow.
711        let events = unsafe { self.0.api.events(self.0.instance(), &mut count, timeout) };
712        let mut budget = copy_budget();
713        if events.is_null() {
714            // No event arrived only if the count agrees. A null batch with
715            // a positive count is malformed, as a membership snapshot is.
716            // SAFETY: null is permitted and checked without dereferencing.
717            unsafe { budget.slice(events, count) }?;
718            return Ok(Vec::new());
719        }
720        let batch = Batch {
721            listener: self,
722            events,
723        };
724        // SAFETY: the batch stays allocated until `batch` is dropped below.
725        let raw = unsafe { budget.slice(batch.events, count) }?;
726        budget.collect_entries(raw, |event, budget| {
727            // SAFETY: the strings belong to the batch, which is still
728            // allocated.
729            unsafe {
730                Ok(ListenerEvent {
731                    id: budget.id(event.p_uuid)?.map(A::Id::from_exact),
732                    name: budget.text(event.p_name)?,
733                    value: budget.text(event.p_value)?,
734                })
735            }
736        })
737    }
738}
739
740/// Lists the senders registered with a Discovery Server and reports their
741/// events.
742///
743/// # Connection
744///
745/// A listener connects in the background and keeps trying for as long as it
746/// lives. It is created whether or not its server can be reached; until the
747/// server answers, which can take several seconds after it appears,
748/// [`is_connected`](Self::is_connected) is `false` and snapshots are empty.
749///
750/// # Threading
751///
752/// A listener is [`Send`] but not [`Sync`]: it may be moved to another thread,
753/// and is used by one thread at a time. [`is_connected`](Self::is_connected)
754/// and [`server_url`](Self::server_url) take a shared reference, and the SDK
755/// documents neither as safe to call on one listener from several threads at
756/// once; it forbids overlapping membership queries on one listener. Snapshots
757/// and events are plain owned data and can be shared freely.
758pub struct SendListener {
759    inner: Listener<sys::SenderDiscovery>,
760}
761/// Lists the receivers registered with a Discovery Server, reports their
762/// events, and asks them to change source. Remote control is always an
763/// explicit call.
764///
765/// # Connection
766///
767/// A listener connects in the background and keeps trying for as long as it
768/// lives. It is created whether or not its server can be reached; until the
769/// server answers, which can take several seconds after it appears,
770/// [`is_connected`](Self::is_connected) is `false` and snapshots are empty.
771///
772/// # Threading
773///
774/// A listener is [`Send`] but not [`Sync`]: it may be moved to another thread,
775/// and is used by one thread at a time. [`is_connected`](Self::is_connected)
776/// and [`server_url`](Self::server_url) take a shared reference, and the SDK
777/// documents neither as safe to call on one listener from several threads at
778/// once; it forbids overlapping membership queries on one listener. Snapshots
779/// and events are plain owned data and can be shared freely.
780pub struct RecvListener {
781    inner: Listener<sys::ReceiverDiscovery>,
782}
783
784const_assert!({
785    const fn assert_send<T: Send>() {}
786    assert_send::<SendListener>();
787    assert_send::<RecvListener>();
788});
789
790impl fmt::Debug for SendListener {
791    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792        f.debug_struct("SendListener")
793            .field("server", &self.inner.0._url)
794            .finish_non_exhaustive()
795    }
796}
797impl fmt::Debug for RecvListener {
798    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799        f.debug_struct("RecvListener")
800            .field("server", &self.inner.0._url)
801            .finish_non_exhaustive()
802    }
803}
804
805macro_rules! listener_methods {
806    ($Id:ty) => {
807        /// Whether the listener is connected to its Discovery Server right
808        /// now. A listener that is not connected keeps trying. This reports
809        /// registry connectivity, not progress of any receiver media.
810        #[doc(alias = "NDIlib_send_listener_is_connected")]
811        #[doc(alias = "NDIlib_recv_listener_is_connected")]
812        pub fn is_connected(&self) -> bool {
813            self.inner.is_connected()
814        }
815        /// The Discovery Server endpoint the listener uses, when the SDK
816        /// reports one.
817        ///
818        /// `None` when the SDK reports none, and also when what it reports
819        /// is no string of less than 4 MiB, the most this crate reads from
820        /// one SDK string. No endpoint is that long, and the value is for
821        /// display only: the listener does not depend on it and the crate
822        /// never passes it back to the SDK. So a value that cannot be read
823        /// is reported as no value, rather than as an error that every
824        /// caller of this getter would have to handle. Bytes that are not
825        /// UTF-8 are replaced with U+FFFD, as in the other text a listener
826        /// reports.
827        #[doc(alias = "NDIlib_send_listener_get_server_url")]
828        #[doc(alias = "NDIlib_recv_listener_get_server_url")]
829        pub fn server_url(&self) -> Option<String> {
830            self.inner.server_url()
831        }
832        /// Wait for the advertised membership to change; a zero timeout polls.
833        ///
834        /// # Errors
835        ///
836        /// Returns [`Error::InvalidInput`] when `timeout` exceeds
837        /// [`crate::MAX_TIMEOUT`].
838        #[doc(alias = "NDIlib_send_listener_wait_for_senders")]
839        #[doc(alias = "NDIlib_recv_listener_wait_for_receivers")]
840        pub fn wait_for_change(&mut self, timeout: Duration) -> Result<bool> {
841            self.inner.wait_for_change(timeout)
842        }
843        /// Ask to receive the events of the peer `id` names. The next snapshot
844        /// reports whether the subscription is active.
845        ///
846        /// The listener keeps its own copy of the identifier until
847        /// [`unsubscribe`](Self::unsubscribe) returns or the listener is dropped.
848        #[doc(alias = "NDIlib_send_listener_subscribe_events")]
849        #[doc(alias = "NDIlib_recv_listener_subscribe_events")]
850        pub fn subscribe(&mut self, id: &$Id) {
851            self.inner.subscription(id, true)
852        }
853        /// Ask to stop receiving the events of the peer `id` names.
854        ///
855        /// With the NDI 6.3.2 and 6.4.0.2 runtimes, unsubscribing from a
856        /// receiver can permanently block that receiver's connect, in this
857        /// process or another, when it connects at the same moment: an SDK
858        /// defect the crate cannot prevent. Dropping the listener ends its
859        /// subscriptions without that risk. See the
860        /// [module documentation](super#sdk-defects-that-remain-in-64).
861        #[doc(alias = "NDIlib_send_listener_unsubscribe_events")]
862        #[doc(alias = "NDIlib_recv_listener_unsubscribe_events")]
863        pub fn unsubscribe(&mut self, id: &$Id) {
864            self.inner.subscription(id, false)
865        }
866        /// Take the events that arrived since the last call, in arrival order,
867        /// waiting up to `timeout` for the first one. An empty batch means none
868        /// arrived in time; a zero timeout polls.
869        ///
870        /// An event with a string of 4 MiB or longer is omitted; its scan
871        /// still spends the shared budget. Other events remain in order.
872        ///
873        /// # Errors
874        ///
875        /// Returns [`Error::InvalidInput`] when `timeout` exceeds
876        /// [`crate::MAX_TIMEOUT`], [`Error::ResourceLimit`] when copying the
877        /// batch would exceed its 16 MiB budget, and
878        /// [`Error::UnexpectedSdkResult`] when the top-level batch array is
879        /// malformed, or [`Error::AllocationFailed`] when storage cannot be
880        /// reserved. The SDK has already
881        /// handed a rejected batch over, so it is freed and its events are lost.
882        #[doc(alias = "NDIlib_send_listener_get_events")]
883        #[doc(alias = "NDIlib_recv_listener_get_events")]
884        pub fn next_events(&mut self, timeout: Duration) -> Result<Vec<ListenerEvent<$Id>>> {
885            self.inner.next_events(timeout)
886        }
887    };
888}
889impl SendListener {
890    /// Create a listener for the Discovery Server `options` name.
891    ///
892    /// Success does not mean the server was reached; see
893    /// [Connection](Self#connection).
894    ///
895    /// # Errors
896    ///
897    /// Returns [`Error::UnsupportedCapability`] when the selected runtime
898    /// cannot provide [sender discovery], which needs NDI 6.4.0 or later, or the
899    /// options carry an Advanced configuration that the runtime or this build
900    /// cannot take; [`Error::InvalidCString`] when the endpoint contains a NUL
901    /// byte; and [`Error::InvalidInput`] when the endpoint is empty, the options
902    /// name multiple endpoints, or the SDK creates no listener. Without an explicit server the
903    /// SDK uses its configuration; creation fails when it names no server or
904    /// one the SDK cannot use. An explicit address the SDK cannot parse is also
905    /// refused.
906    ///
907    /// [sender discovery]: crate::capabilities::RuntimeFeature::SenderDiscovery
908    #[doc(alias = "NDIlib_send_listener_create")]
909    #[doc(alias = "NDIlib_send_listener_create_ex")]
910    pub fn new(ndi: &Ndi, options: &ListenerOptions) -> Result<Self> {
911        Ok(Self {
912            inner: Listener::new(ndi, options)?,
913        })
914    }
915    listener_methods!(SenderId);
916    /// Copy the senders currently advertised. The list is empty while the
917    /// listener is not connected.
918    ///
919    /// An entry with a string of 4 MiB or longer, or a malformed nested
920    /// array, is omitted. Its scans still spend the shared budget. Text that
921    /// is not valid UTF-8 is decoded lossily; see the [module documentation](super).
922    ///
923    /// # Errors
924    ///
925    /// Returns [`Error::ResourceLimit`] when copying would exceed the 16 MiB
926    /// budget, and [`Error::UnexpectedSdkResult`] when the top-level snapshot
927    /// array is malformed. [`Error::AllocationFailed`] when storage cannot be
928    /// reserved.
929    #[doc(alias = "NDIlib_send_listener_get_senders")]
930    pub fn current_senders(&mut self) -> Result<Vec<AdvertisedSender>> {
931        let mut budget = copy_budget();
932        let raw = self.inner.entries(&mut budget)?;
933        budget.collect_entries(raw, |sender, budget| {
934            // SAFETY: the snapshot and everything it points to stay valid
935            // until the next call on this listener, after this copy.
936            unsafe {
937                let groups = budget.slice(sender.p_groups.cast_const(), sender.num_groups)?;
938                let groups = budget.collect(groups, |group, budget| Ok(budget.text(*group)?))?;
939                Ok(AdvertisedSender {
940                    id: budget.id(sender.p_uuid)?.map(SenderId::from_exact),
941                    name: AdvertisedSourceText::copy(sender.p_name, budget)?,
942                    metadata: budget.text(sender.p_metadata)?,
943                    address: AdvertisedSourceText::copy(sender.p_address, budget)?,
944                    port: advertised_port(sender.port),
945                    groups,
946                    subscribed: sender.events_subscribed,
947                })
948            }
949        })
950    }
951}
952fn advertised_port(port: std::ffi::c_int) -> Option<NonZeroU16> {
953    u16::try_from(port).ok().and_then(NonZeroU16::new)
954}
955
956impl RecvListener {
957    /// Create a listener for the Discovery Server `options` name.
958    ///
959    /// Success does not mean the server was reached; see
960    /// [Connection](Self#connection).
961    ///
962    /// # Errors
963    ///
964    /// Returns [`Error::UnsupportedCapability`] when the selected runtime
965    /// cannot provide [receiver discovery], which needs NDI 6.4.0 or later, or the
966    /// options carry an Advanced configuration that the runtime or this build
967    /// cannot take; [`Error::InvalidCString`] when the endpoint contains a NUL
968    /// byte; and [`Error::InvalidInput`] when the endpoint is empty, the options
969    /// name multiple endpoints, or the SDK creates no listener. Without an explicit server the
970    /// SDK uses its configuration; creation fails when it names no server or
971    /// one the SDK cannot use. An explicit address the SDK cannot parse is also
972    /// refused.
973    ///
974    /// [receiver discovery]: crate::capabilities::RuntimeFeature::ReceiverDiscovery
975    #[doc(alias = "NDIlib_recv_listener_create")]
976    #[doc(alias = "NDIlib_recv_listener_create_ex")]
977    pub fn new(ndi: &Ndi, options: &ListenerOptions) -> Result<Self> {
978        Ok(Self {
979            inner: Listener::new(ndi, options)?,
980        })
981    }
982    listener_methods!(ReceiverId);
983    /// Copy the receivers currently advertised. The list is empty while the
984    /// listener is not connected.
985    ///
986    /// An entry with a string of 4 MiB or longer, or a malformed nested
987    /// array, is omitted. Its scans still spend the shared budget. Text that
988    /// is not valid UTF-8 is decoded lossily; see the [module documentation](super).
989    ///
990    /// # Errors
991    ///
992    /// Returns [`Error::ResourceLimit`] when copying would exceed the 16 MiB
993    /// budget, and [`Error::UnexpectedSdkResult`] when the top-level snapshot
994    /// array is malformed. [`Error::AllocationFailed`] when storage cannot be
995    /// reserved.
996    #[doc(alias = "NDIlib_recv_listener_get_receivers")]
997    pub fn current_receivers(&mut self) -> Result<Vec<AdvertisedReceiver>> {
998        let mut budget = copy_budget();
999        let raw = self.inner.entries(&mut budget)?;
1000        budget.collect_entries(raw, |receiver, budget| {
1001            // SAFETY: the snapshot and everything it points to stay valid
1002            // until the next call on this listener, after this copy.
1003            unsafe {
1004                let streams =
1005                    budget.slice(receiver.p_streams.cast_const(), receiver.num_streams)?;
1006                let streams =
1007                    budget.collect(streams, |stream, _| Ok(ReceiverStream::from_sdk(*stream)))?;
1008                let commands =
1009                    budget.slice(receiver.p_commands.cast_const(), receiver.num_commands)?;
1010                let commands = budget.collect(commands, |command, _| {
1011                    Ok(ReceiverCommand::from_sdk(*command))
1012                })?;
1013                Ok(AdvertisedReceiver {
1014                    id: budget.id(receiver.p_uuid)?.map(ReceiverId::from_exact),
1015                    name: budget.text(receiver.p_name)?,
1016                    input_id: budget
1017                        .id(receiver.p_input_uuid)?
1018                        .map(InputGroupId::from_exact),
1019                    input_name: budget.text(receiver.p_input_name)?,
1020                    address: budget.text(receiver.p_address)?,
1021                    streams,
1022                    commands,
1023                    subscribed: receiver.events_subscribed,
1024                })
1025            }
1026        })
1027    }
1028    /// Ask the receiver `id` names to connect to the NDI source called
1029    /// `source_name`.
1030    ///
1031    /// The request checks the listener's current borrowed membership, comparing
1032    /// exact identifiers and reading only the matched receiver's commands. It
1033    /// is sent only when that receiver advertises [`ReceiverCommand::Connect`].
1034    /// Malformed names, input groups, addresses or streams do not prevent a
1035    /// request. Success means it was sent, not that the receiver acted on it.
1036    ///
1037    /// # Errors
1038    ///
1039    /// Returns [`Error::InvalidInput`] when `source_name` is empty, and
1040    /// [`Error::InvalidCString`] when it contains a NUL byte, before reading
1041    /// listener membership. For this error, [`NulError::into_vec`](std::ffi::NulError::into_vec)
1042    /// returns the bytes through the first NUL.
1043    ///
1044    /// Returns [`Error::ReceiverRequestNotAccepted`] when no receiver the listener
1045    /// lists has this identifier (`advertised` is false: the listener may not
1046    /// have connected yet, the receiver may not be registered, or its entry
1047    /// may have an unreadable identifier; a later request can succeed) or the
1048    /// receiver does not accept connection requests
1049    /// (`advertised` is true, including a malformed command array);
1050    /// [`Error::NativeOperationFailed`] when the SDK cannot send the request;
1051    /// [`Error::UnexpectedSdkResult`] for a malformed top-level membership
1052    /// array; and [`Error::ResourceLimit`] when that array and the target's
1053    /// commands exceed the 16 MiB inspection budget. Unrelated fields are
1054    /// neither scanned nor copied and cannot spend that budget.
1055    #[doc(alias = "NDIlib_recv_listener_send_connect")]
1056    pub fn request_connect(&mut self, id: &ReceiverId, source_name: &str) -> Result<()> {
1057        self.request(id, Some(SourceName::checked(source_name)?))
1058    }
1059    /// Ask the receiver `id` names to disconnect from its current source.
1060    ///
1061    /// This is the connection request without a source, so it too is sent
1062    /// only to a receiver that advertises [`ReceiverCommand::Connect`].
1063    /// It compares exact identifiers and reads only the matched command array;
1064    /// unrelated fields are neither scanned nor copied.
1065    ///
1066    /// # Errors
1067    ///
1068    /// As for [`Self::request_connect`], without source-name validation.
1069    #[doc(alias = "NDIlib_recv_listener_send_connect")]
1070    pub fn request_disconnect(&mut self, id: &ReceiverId) -> Result<()> {
1071        self.request(id, None)
1072    }
1073    fn request(&mut self, id: &ReceiverId, source: Option<SourceName<'_>>) -> Result<()> {
1074        let source = source.map(SourceName::into_c_string);
1075        // The SDK accepts this command only for a receiver that advertises it.
1076        // Read current membership rather than trust what the caller last saw.
1077        let mut budget = copy_budget();
1078        let receivers = self.inner.entries(&mut budget)?;
1079        // SAFETY: the exclusive listener borrow keeps its SDK-owned entries,
1080        // UUIDs and matched commands unchanged until this inspection finishes.
1081        unsafe { require_receiver_connect(receivers, id, &mut budget)? };
1082        // SAFETY: the listener instance is live and both strings outlive the call.
1083        unsafe {
1084            self.inner.0.api.named().NDIlib_recv_listener_send_connect(
1085                self.inner.0.instance().0,
1086                id.as_c_str().as_ptr(),
1087                source.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1088            )
1089        }
1090        .performed()
1091    }
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096    use super::*;
1097
1098    #[test]
1099    fn advertised_sources_use_name_and_only_complete_addresses() {
1100        let mut sender = AdvertisedSender {
1101            id: None,
1102            name: Some(AdvertisedSourceText::Exact(
1103                SourceText::new("Studio (Camera)".into()).unwrap(),
1104            )),
1105            metadata: None,
1106            address: Some(AdvertisedSourceText::Exact(
1107                SourceText::new("192.0.2.10".into()).unwrap(),
1108            )),
1109            port: NonZeroU16::new(5960),
1110            groups: vec![],
1111            subscribed: false,
1112        };
1113        let source = sender.to_source().unwrap();
1114        assert_eq!(source.name(), "Studio (Camera)");
1115        assert_eq!(source.address().unwrap().as_str(), "192.0.2.10:5960");
1116        for (address, endpoint) in [
1117            ("192.0.2.10", "192.0.2.10:5960"),
1118            ("camera.local", "camera.local:5960"),
1119            ("2001:db8::10", "[2001:db8::10]:5960"),
1120            ("[2001:db8::10]", "[2001:db8::10]:5960"),
1121        ] {
1122            sender.address = Some(AdvertisedSourceText::Exact(
1123                SourceText::new(address.into()).unwrap(),
1124            ));
1125            let source = sender.to_source().unwrap();
1126            let actual = source.address().unwrap();
1127            assert_eq!(actual.as_str(), endpoint);
1128            assert_eq!(actual.port(), Some(5960));
1129            assert!(source.host().is_some());
1130        }
1131        for port in [0, -1, 65_536] {
1132            sender.port = advertised_port(port);
1133            assert!(sender.port().is_none());
1134            assert!(sender.to_source().unwrap().address().is_none());
1135        }
1136        sender.port = advertised_port(5960);
1137        for address in [
1138            "",
1139            "fe80::1%eth0",
1140            "bad\u{fffd}.local",
1141            "192.0.2.10:1234",
1142            "Camera Desk",
1143        ] {
1144            sender.address = Some(AdvertisedSourceText::Exact(
1145                SourceText::new(address.into()).unwrap(),
1146            ));
1147            let source = sender.to_source().unwrap();
1148            assert_eq!(source.name(), "Studio (Camera)");
1149            assert!(source.address().is_none(), "{address}");
1150        }
1151        sender.address = None;
1152        assert!(sender.to_source().unwrap().address().is_none());
1153        sender.name = None;
1154        assert!(sender.to_source().is_none());
1155    }
1156
1157    #[test]
1158    fn receiver_request_lookup_uses_exact_ids_and_only_the_matched_commands() {
1159        let mut commands = [
1160            999,
1161            NDIlib_receiver_command_e_NDIlib_receiver_command_connect,
1162            NDIlib_receiver_command_e_NDIlib_receiver_command_none,
1163        ];
1164        let target = ReceiverId::new(b"receiver-\xff".to_vec()).unwrap();
1165        let matching = NDIlib_receiver_t {
1166            p_uuid: c"receiver-\xff".as_ptr(),
1167            // Unrelated fields are intentionally not usable as a snapshot.
1168            p_name: ptr::dangling(),
1169            p_input_uuid: ptr::dangling(),
1170            p_input_name: ptr::dangling(),
1171            p_address: ptr::dangling(),
1172            num_streams: 1,
1173            p_commands: commands.as_mut_ptr(),
1174            num_commands: commands.len() as u32,
1175            ..Default::default()
1176        };
1177        let unrelated = NDIlib_receiver_t {
1178            p_uuid: c"receiver-\xff-longer".as_ptr(),
1179            p_commands: ptr::null_mut(),
1180            num_commands: 1,
1181            ..Default::default()
1182        };
1183        // SAFETY: UUIDs and the matched commands remain live and unchanged;
1184        // malformed unrelated fields and unmatched commands are not read.
1185        unsafe {
1186            require_receiver_connect(&[unrelated, matching], &target, &mut copy_budget()).unwrap();
1187            for id in [c"receiver-\xff-longer", c"receiver", c"", c"other"] {
1188                let receiver = NDIlib_receiver_t {
1189                    p_uuid: id.as_ptr(),
1190                    ..matching
1191                };
1192                assert!(matches!(
1193                    require_receiver_connect(&[receiver], &target, &mut copy_budget()),
1194                    Err(Error::ReceiverRequestNotAccepted { advertised: false })
1195                ));
1196            }
1197            for (pointer, count) in [
1198                (ptr::null_mut(), 0),
1199                (ptr::null_mut(), 1),
1200                (commands.as_mut_ptr(), 1),
1201            ] {
1202                let receiver = NDIlib_receiver_t {
1203                    p_commands: pointer,
1204                    num_commands: count,
1205                    ..matching
1206                };
1207                assert!(matches!(
1208                    require_receiver_connect(&[receiver], &target, &mut copy_budget()),
1209                    Err(Error::ReceiverRequestNotAccepted { advertised: true })
1210                ));
1211            }
1212            assert!(matches!(
1213                require_receiver_connect(&[], &target, &mut copy_budget()),
1214                Err(Error::ReceiverRequestNotAccepted { advertised: false })
1215            ));
1216            let no_id = NDIlib_receiver_t {
1217                p_uuid: ptr::null(),
1218                ..matching
1219            };
1220            assert!(matches!(
1221                require_receiver_connect(&[no_id], &target, &mut copy_budget()),
1222                Err(Error::ReceiverRequestNotAccepted { advertised: false })
1223            ));
1224        }
1225    }
1226
1227    #[test]
1228    fn receiver_request_lookup_does_not_copy_or_budget_unrelated_strings() {
1229        let text = CString::new(vec![b'x'; MAX_SDK_STRING_BYTES - 1]).unwrap();
1230        let unrelated = NDIlib_receiver_t {
1231            p_uuid: c"unrelated".as_ptr(),
1232            p_name: text.as_ptr(),
1233            p_input_uuid: text.as_ptr(),
1234            p_input_name: text.as_ptr(),
1235            p_address: text.as_ptr(),
1236            num_streams: 1,
1237            num_commands: 1,
1238            ..Default::default()
1239        };
1240        let mut receivers = vec![unrelated; 1_000];
1241        let mut connect = [NDIlib_receiver_command_e_NDIlib_receiver_command_connect];
1242        receivers.push(NDIlib_receiver_t {
1243            p_uuid: c"target".as_ptr(),
1244            p_commands: connect.as_mut_ptr(),
1245            num_commands: 1,
1246            ..unrelated
1247        });
1248        // Even one unrelated entry cannot be copied within the shared
1249        // snapshot budget once its four large text fields are included.
1250        let mut budget = copy_budget();
1251        // SAFETY: `text` is a live terminated string for every attempted copy.
1252        unsafe {
1253            budget.text(text.as_ptr()).unwrap();
1254            budget.text(text.as_ptr()).unwrap();
1255            assert!(matches!(
1256                budget.text(text.as_ptr()),
1257                Err(crate::sdk_copy::TextError::Failed(Error::ResourceLimit {
1258                    resource: ResourceKind::DiscoveryServerCopyBytes,
1259                    ..
1260                }))
1261            ));
1262        }
1263        let target = ReceiverId::new("target").unwrap();
1264        let (result, allocations) = crate::test_alloc::allocation_count(|| {
1265            // SAFETY: all UUIDs and the target's commands remain readable.
1266            // The malformed unrelated arrays are never inspected.
1267            unsafe { require_receiver_connect(&receivers, &target, &mut copy_budget()) }
1268        });
1269        result.unwrap();
1270        assert_eq!(allocations, 0);
1271    }
1272
1273    #[cfg(target_os = "linux")]
1274    #[test]
1275    fn receiver_id_comparison_stops_at_nul_mismatch_and_the_native_string_cap() {
1276        struct Guarded {
1277            mapping: *mut libc::c_void,
1278            mapped: usize,
1279            data: *mut u8,
1280        }
1281        impl Guarded {
1282            fn new(bytes: &[u8]) -> Self {
1283                // SAFETY: the private mapping owns its initialized prefix and
1284                // inaccessible last page until Drop releases it.
1285                unsafe {
1286                    let page = usize::try_from(libc::sysconf(libc::_SC_PAGESIZE)).unwrap();
1287                    let body = bytes.len().div_ceil(page) * page;
1288                    let mapped = body + page;
1289                    let mapping = libc::mmap(
1290                        ptr::null_mut(),
1291                        mapped,
1292                        libc::PROT_READ | libc::PROT_WRITE,
1293                        libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
1294                        -1,
1295                        0,
1296                    );
1297                    assert_ne!(mapping, libc::MAP_FAILED);
1298                    let guard = mapping.cast::<u8>().add(body);
1299                    assert_eq!(libc::mprotect(guard.cast(), page, libc::PROT_NONE), 0);
1300                    let data = guard.sub(bytes.len());
1301                    ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
1302                    Self {
1303                        mapping,
1304                        mapped,
1305                        data,
1306                    }
1307                }
1308            }
1309        }
1310        impl Drop for Guarded {
1311            fn drop(&mut self) {
1312                // SAFETY: this is the mapping allocated in new, with no live borrows.
1313                assert_eq!(unsafe { libc::munmap(self.mapping, self.mapped) }, 0);
1314            }
1315        }
1316        let target = ReceiverId::new("target").unwrap();
1317        for bytes in [b"t\0".as_slice(), b"\0", b"u", b"target\0", b"targetx"] {
1318            let native = Guarded::new(bytes);
1319            // SAFETY: the bytewise comparison's required prefix is readable:
1320            // it must stop at NUL, mismatch, or the target's exact terminator.
1321            assert_eq!(
1322                unsafe { receiver_id_matches(native.data.cast(), &target) },
1323                bytes == b"target\0"
1324            );
1325        }
1326        let bytes = vec![b'x'; MAX_SDK_STRING_BYTES];
1327        let native = Guarded::new(&bytes);
1328        let long_target = ReceiverId::new(vec![b'x'; MAX_SDK_STRING_BYTES + 10]).unwrap();
1329        // SAFETY: the complete native scan cap is readable; its next byte is
1330        // intentionally inaccessible even though the caller's ID is longer.
1331        assert!(!unsafe { receiver_id_matches(native.data.cast(), &long_target) });
1332        let mut terminated = bytes;
1333        *terminated.last_mut().unwrap() = 0;
1334        let native = Guarded::new(&terminated);
1335        let longest_target = ReceiverId::new(vec![b'x'; MAX_SDK_STRING_BYTES - 1]).unwrap();
1336        // SAFETY: the longest permitted native string includes its final NUL.
1337        assert!(unsafe { receiver_id_matches(native.data.cast(), &longest_target) });
1338    }
1339
1340    #[test]
1341    fn list_terminators_are_dropped_and_unknown_values_kept() {
1342        assert_eq!(
1343            ReceiverStream::from_sdk(NDIlib_receiver_type_e_NDIlib_receiver_type_none),
1344            None
1345        );
1346        assert_eq!(
1347            ReceiverStream::from_sdk(NDIlib_receiver_type_e_NDIlib_receiver_type_audio),
1348            Some(ReceiverStream::Audio)
1349        );
1350        assert_eq!(
1351            ReceiverStream::from_sdk(999),
1352            Some(ReceiverStream::Unknown(999))
1353        );
1354        assert_eq!(
1355            ReceiverCommand::from_sdk(NDIlib_receiver_command_e_NDIlib_receiver_command_none),
1356            None
1357        );
1358        assert_eq!(
1359            ReceiverCommand::from_sdk(NDIlib_receiver_command_e_NDIlib_receiver_command_connect),
1360            Some(ReceiverCommand::Connect)
1361        );
1362        assert_eq!(
1363            ReceiverCommand::from_sdk(999),
1364            Some(ReceiverCommand::Unknown(999))
1365        );
1366    }
1367    #[test]
1368    fn text_is_decoded_lossily_and_identifiers_keep_their_bytes() {
1369        let malformed = c"caf\xe9 \xff";
1370        let mut budget = copy_budget();
1371        // SAFETY: the pointer is a live NUL-terminated string.
1372        let (text, id) = unsafe {
1373            (
1374                budget.text(malformed.as_ptr()).unwrap().unwrap(),
1375                budget
1376                    .id(malformed.as_ptr())
1377                    .unwrap()
1378                    .map(ReceiverId::from_exact)
1379                    .unwrap(),
1380            )
1381        };
1382        assert_eq!(text, "caf\u{fffd} \u{fffd}");
1383        assert_eq!(id.as_bytes(), malformed.to_bytes());
1384        assert_eq!(id.to_string(), text);
1385        assert_eq!(id, ReceiverId::new(malformed.to_bytes()).unwrap());
1386        assert_ne!(id, ReceiverId::new(text).unwrap());
1387        assert!(ReceiverId::new("a\0b").is_err());
1388    }
1389    #[test]
1390    fn an_endpoint_is_read_only_up_to_the_string_limit() {
1391        let mut longest = vec![b'x'; MAX_SDK_STRING_BYTES];
1392        longest[MAX_SDK_STRING_BYTES - 1] = 0;
1393        // Its terminator lies just past the limit, so the scan never reaches
1394        // it; nothing past the limit is read.
1395        let mut too_long = vec![b'x'; MAX_SDK_STRING_BYTES + 1];
1396        too_long[MAX_SDK_STRING_BYTES] = 0;
1397        // SAFETY: every non-null pointer is a live NUL-terminated string.
1398        unsafe {
1399            assert_eq!(endpoint(ptr::null()), None);
1400            assert_eq!(
1401                endpoint(c"192.0.2.1:5959".as_ptr()).as_deref(),
1402                Some("192.0.2.1:5959")
1403            );
1404            assert_eq!(
1405                endpoint(c"host-\xff:5959".as_ptr()).as_deref(),
1406                Some("host-\u{fffd}:5959")
1407            );
1408            assert_eq!(
1409                endpoint(longest.as_ptr().cast()).map(|url| url.len()),
1410                Some(MAX_SDK_STRING_BYTES - 1)
1411            );
1412            assert_eq!(endpoint(too_long.as_ptr().cast()), None);
1413        }
1414    }
1415}