Skip to main content

grafton_ndi/discovery/
mod.rs

1//! Discovery Server monitoring and explicitly enabled remote control.
2//!
3//! A Discovery Server keeps a registry of senders and receivers that goes
4//! beyond what a [`Finder`](crate::Finder) reports: who is on the network, what
5//! each receiver is connected to, and events they choose to publish. This
6//! module has the two sides of that registry:
7//!
8//! * [`SendAdvertiser`] and [`RecvAdvertiser`] register this process's senders
9//!   and receivers;
10//! * [`SendListener`] and [`RecvListener`] list what is registered, subscribe
11//!   to events, and — for receivers that allow it — request a source change.
12//!
13//! All four need an NDI 6.4.0 or later runtime, so their constructors return
14//! [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
15//! before that. [`Ndi::capabilities`](crate::Ndi::capabilities) reports each
16//! one. A 6.3.2 runtime exports their functions, but destroying any of them
17//! while it is connected to a server aborts the process, and no order of
18//! calls avoids it.
19//!
20//! # SDK defects that remain in 6.4
21//!
22//! Four defects of the NDI 6.4.0.2 runtime involve these objects. The crate
23//! cannot prevent them, but none needs more than a little care to avoid:
24//!
25//! * Moving one sender or receiver from one advertiser to another on the same
26//!   server within a few tens of milliseconds can crash a listener on that
27//!   server, in any process. Wait a second between unregistering and
28//!   registering again, or drop the first advertiser before registering with
29//!   the second.
30//! * A [`RecvListener::unsubscribe`] can permanently block the connect of the
31//!   receiver it names, in this process or another, when that receiver
32//!   connects at the same moment. To stop receiving a receiver's events, drop
33//!   the listener; this crate's listeners never unsubscribe on their own.
34//! * Destroying a [`SendAdvertiser`] can block forever, about once in a
35//!   million destroys under heavy load.
36//! * A listener that does not find its server on its first attempt, such as
37//!   one created before the server appeared, connects on a later attempt but
38//!   then never lists the senders or receivers registered before it
39//!   connected: only those registered afterwards. Create listeners once their
40//!   server is up, or replace a listener that took ten seconds or more to
41//!   report `is_connected`, the interval at which the runtime tries again.
42//!
43//! See [Discovery Server deployment guidance](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/troubleshooting.md#discovery-server)
44//! when validating an application with its selected runtime and network.
45//!
46//! # Threads
47//!
48//! The native owners are [`Send`] but not [`Sync`]: each can move to another
49//! thread, and one thread at a time uses it. Snapshots and events are plain
50//! owned data. To keep an owner in state that several threads share, put it in
51//! a [`Mutex`](std::sync::Mutex). The owner is `Send`, so the mutex is `Sync`,
52//! and the methods that change an owner take it exclusively in any case:
53//!
54//! ```no_run
55//! use std::sync::{Arc, Mutex};
56//! use grafton_ndi::{
57//!     discovery_server::{AdvertiserOptions, SendAdvertisement, SendAdvertiser},
58//!     Ndi, Sender, SenderOptions,
59//! };
60//!
61//! /// What every request handler of a server shares.
62//! struct Shared {
63//!     advertiser: Mutex<SendAdvertiser>,
64//! }
65//!
66//! # fn main() -> grafton_ndi::Result<()> {
67//! let ndi = Ndi::new()?;
68//! let shared = Arc::new(Shared {
69//!     advertiser: Mutex::new(SendAdvertiser::new(&ndi, &AdvertiserOptions::new())?),
70//! });
71//! let sender = Sender::new(&ndi, &SenderOptions::new("Camera 1"))?;
72//! let worker = std::thread::spawn({
73//!     let shared = Arc::clone(&shared);
74//!     move || {
75//!         let mut advertiser = shared.advertiser.lock().unwrap();
76//!         advertiser.register(&sender, &SendAdvertisement::new())
77//!     }
78//! });
79//! let _registration = worker.join().unwrap()?;
80//! # Ok(())
81//! # }
82//! ```
83//!
84//! See [discovery_server.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/discovery_server.rs)
85//! for runnable registration and listener workflows.
86//!
87//! # Connecting
88//!
89//! Each object is created for a Discovery Server address: the one given in its
90//! options, or else the one in the NDI configuration. Creation can fail for
91//! an unavailable capability, a NUL byte in the endpoint, or an address the
92//! SDK cannot use; listeners also reject multiple endpoints. Each constructor
93//! lists its errors. Creation does not wait for the server, and a server that
94//! cannot be reached is not an error: the object
95//! keeps trying in the background for as long as it lives, and starts working
96//! within about ten seconds of the server appearing, as the 6.4.0.2 runtime
97//! tries again every ten seconds. A listener that connects only on such a
98//! later attempt misses earlier registrations; see the defects above.
99//!
100//! A listener reports its connection through `is_connected`, and its snapshots
101//! are empty until it connects. An advertiser reports nothing; whether its
102//! registrations arrived shows in a listener on the same server.
103//! Registry connectivity and membership do not establish media progress;
104//! monitor the receiver's expected-media counter separately.
105//!
106//! # Text from the network
107//!
108//! Names, metadata and event values are whatever a peer advertised. They are
109//! decoded lossily, replacing bytes that are not UTF-8 with U+FFFD, within the
110//! resource limits below. Identifiers are the exception:
111//! a [`SenderId`], [`ReceiverId`] or [`InputGroupId`] keeps the server's exact
112//! bytes, so handing one back in a subscription or a connection request always
113//! names the same peer. Each kind is its own type, so a sender's identifier
114//! cannot be used where a receiver's is meant. [`AdvertisedSender::to_source`]
115//! requires an exact UTF-8 name and address when converting an advertisement
116//! into a connection target.
117//!
118//! Each snapshot or event batch has one 16 MiB budget covering native arrays
119//! and strings scanned plus owned Rust storage reserved, including UTF-8
120//! replacement bytes and identifier terminators. Array storage is reserved
121//! for every reported element, even when null fields or list terminators are
122//! omitted from the result. A single native string must be shorter than 4 MiB.
123//! Exceeding the aggregate copy budget returns
124//! [`Error::ResourceLimit`](crate::Error::ResourceLimit), identifying
125//! [`ResourceKind::DiscoveryServerCopyBytes`](crate::ResourceKind::DiscoveryServerCopyBytes),
126//! before reserving the offending output. An entry or event with a string
127//! beyond its individual bound, or an entry with a malformed nested array,
128//! is omitted while the other entries are returned. Rejected string scans
129//! remain charged, so several malformed entries can still exhaust the budget.
130//! A malformed top-level array returns
131//! [`Error::UnexpectedSdkResult`](crate::Error::UnexpectedSdkResult); allocation
132//! failure returns [`Error::AllocationFailed`](crate::Error::AllocationFailed).
133//! A rejected
134//! event batch is freed and its events are lost.
135//!
136//! # Example
137//!
138//! ```no_run
139//! use grafton_ndi::{
140//!     discovery_server::{ListenerOptions, RecvListener},
141//!     Ndi,
142//! };
143//! use std::time::Duration;
144//!
145//! # fn main() -> Result<(), grafton_ndi::Error> {
146//! let ndi = Ndi::new()?;
147//! let options = ListenerOptions::default().server("127.0.0.1");
148//! let mut listener = RecvListener::new(&ndi, &options)?;
149//! // The listener connects in the background; give it time to hear from the
150//! // server before reading the registry.
151//! listener.wait_for_change(Duration::from_secs(2))?;
152//! if !listener.is_connected() {
153//!     println!("no answer from the Discovery Server yet");
154//! }
155//! for receiver in listener.current_receivers()? {
156//!     println!("{:?} at {:?}", receiver.name(), receiver.address());
157//! }
158//! # Ok(())
159//! # }
160//! ```
161//!
162//! See [discovery_server.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/discovery_server.rs)
163//! for a complete listener loop.
164
165#![warn(missing_docs)]
166
167mod advertiser;
168mod listener;
169pub use advertiser::{
170    AdvertiserOptions, RecvAdvertisement, RecvAdvertiser, RecvRegistration, SendAdvertisement,
171    SendAdvertiser, SendRegistration,
172};
173pub use listener::{
174    AdvertisedReceiver, AdvertisedSender, InputGroupId, ListenerEvent, ListenerOptions,
175    ReceiverCommand, ReceiverId, ReceiverStream, RecvListener, SendListener, SenderId,
176};
177
178/// The error for an advertiser or listener the SDK did not create.
179///
180/// The SDK creates these objects for any address it can parse, reachable or
181/// not. With no explicit `server`, refusal covers both no configured server
182/// and a configured server the SDK cannot use; the crate cannot tell them apart.
183fn not_created(object: &'static str, server: Option<&ServerEndpoint<'_>>) -> crate::Error {
184    crate::Error::InvalidInput(match server {
185        Some(server) => {
186            crate::InputDefect::DiscoveryAddressRejected(Box::new(crate::DiscoveryAddressFailure {
187                object,
188                address: match server.input {
189                    EndpointInput::Single(text) => text.into(),
190                    EndpointInput::List(values) => values.join(",").into(),
191                },
192            }))
193        }
194        None => crate::InputDefect::DiscoveryConfigurationRejected { object },
195    })
196}
197
198/// A native Discovery Server identity. Handles move between threads, while
199/// their owners determine every other auto trait and serialize native calls.
200trait Handle: Copy + Send {
201    fn is_null(self) -> bool;
202}
203
204/// The native string plus the original UTF-8 input, retained only during
205/// creation so a native refusal can describe it without decoding the CString.
206struct ServerEndpoint<'options> {
207    url: std::ffi::CString,
208    input: EndpointInput<'options>,
209}
210
211enum EndpointInput<'options> {
212    Single(&'options str),
213    List(&'options [String]),
214}
215
216trait ServerOptions {
217    fn server(&self) -> crate::Result<Option<ServerEndpoint<'_>>>;
218    #[cfg(feature = "advanced")]
219    fn config(&self) -> Option<&crate::advanced::AdvancedConfig>;
220}
221
222impl ServerOptions for AdvertiserOptions {
223    fn server(&self) -> crate::Result<Option<ServerEndpoint<'_>>> {
224        let Some(values) = self.configured_servers() else {
225            return Ok(None);
226        };
227        crate::list_setting::list_cstring(Some(values), "servers").map(|url| {
228            url.map(|url| ServerEndpoint {
229                url,
230                input: EndpointInput::List(values),
231            })
232        })
233    }
234    #[cfg(feature = "advanced")]
235    fn config(&self) -> Option<&crate::advanced::AdvancedConfig> {
236        self.configured_config()
237    }
238}
239
240impl ServerOptions for ListenerOptions {
241    fn server(&self) -> crate::Result<Option<ServerEndpoint<'_>>> {
242        self.configured_server()
243            .map(|text| {
244                Ok(ServerEndpoint {
245                    url: crate::list_setting::endpoint_cstring(text)?,
246                    input: EndpointInput::Single(text),
247                })
248            })
249            .transpose()
250    }
251    #[cfg(feature = "advanced")]
252    fn config(&self) -> Option<&crate::advanced::AdvancedConfig> {
253        self.configured_config()
254    }
255}
256
257/// The shared native lifecycle of all four Discovery Server object kinds.
258trait ServerApi: crate::sys::Table + Sync {
259    type Instance: Handle;
260    type Settings;
261    type Options: ServerOptions;
262    const OBJECT: &'static str;
263    #[cfg(feature = "advanced")]
264    type Configured: crate::sys::Table;
265
266    fn settings(url: *const std::ffi::c_char) -> Self::Settings;
267    /// # Safety
268    /// Settings point to a null URL or a terminated string kept alive through
269    /// native destruction. The result is null or a fresh, exclusively owned object.
270    unsafe fn create(&self, settings: &Self::Settings) -> sys::table::Called<Self::Instance>;
271    /// # Safety
272    /// As for `create`; configuration is terminated and also remains live
273    /// through destruction, and `table` belongs to the same runtime.
274    #[cfg(feature = "advanced")]
275    unsafe fn create_configured(
276        table: &Self::Configured,
277        settings: *const Self::Settings,
278        config: *const std::ffi::c_char,
279    ) -> sys::table::Called<Self::Instance>;
280    /// # Safety
281    /// The instance was created through this table, remains live, and is never
282    /// used after this call. No native call on the instance overlaps destruction.
283    unsafe fn destroy(&self, instance: Self::Instance);
284}
285
286macro_rules! server_api {
287    ($Table:ty, $Handle:ident, $Raw:ty, $Settings:ident, $Options:ty,
288     $object:literal, $create:ident, $destroy:ident,
289     $Configured:ident::$configured:ident) => {
290        #[derive(Clone, Copy)]
291        struct $Handle($Raw);
292        // SAFETY: the listener headers forbid overlapping membership snapshots
293        // on one instance. ServerObject has one owner and this raw handle
294        // withholds Sync; listeners require &mut self for membership calls, so
295        // these calls and destruction cannot overlap. Beyond the headers, we
296        // rely on no thread affinity for creation, use and destruction. The real
297        // vendor-server test discovery_server::owners_move_between_threads
298        // exercises all four owners across those threads; discovery.rs pins
299        // their lifecycle against a scripted runtime. Rust ownership of the
300        // surrounding state is checked separately by the compiler.
301        unsafe impl Send for $Handle {}
302        impl Handle for $Handle {
303            fn is_null(self) -> bool { self.0.is_null() }
304        }
305        impl ServerApi for $Table {
306            type Instance = $Handle;
307            type Settings = $Settings;
308            type Options = $Options;
309            const OBJECT: &'static str = $object;
310            #[cfg(feature = "advanced")]
311            type Configured = crate::sys::advanced::$Configured;
312            fn settings(url: *const std::ffi::c_char) -> Self::Settings {
313                $Settings { p_url_address: url }
314            }
315            unsafe fn create(&self, settings: &Self::Settings) -> sys::table::Called<Self::Instance> {
316                // SAFETY: forwarded to the caller's lifecycle contract.
317                unsafe { self.named().$create(settings) }.map($Handle)
318            }
319            #[cfg(feature = "advanced")]
320            unsafe fn create_configured(
321                table: &Self::Configured,
322                _settings: *const Self::Settings,
323                _config: *const std::ffi::c_char,
324            ) -> sys::table::Called<Self::Instance> {
325                crate::sys::advanced::native!($Configured, table => {
326                    // SAFETY: forwarded to the caller's lifecycle contract.
327                    unsafe { table.named().$configured(_settings, _config) }.map($Handle)
328                })
329            }
330            unsafe fn destroy(&self, instance: Self::Instance) {
331                // SAFETY: forwarded to the caller's lifecycle contract.
332                unsafe { self.$destroy(instance.0) }
333            }
334        }
335    };
336}
337
338use crate::sys::{self, bindings::*};
339server_api!(
340    sys::SenderAdvertising,
341    SendAdvertiserInstance,
342    NDIlib_send_advertiser_instance_t,
343    NDIlib_send_advertiser_create_t,
344    AdvertiserOptions,
345    "advertiser",
346    NDIlib_send_advertiser_create,
347    NDIlib_send_advertiser_destroy,
348    SenderAdvertiserConfiguration::NDIlib_send_advertiser_create_ex
349);
350server_api!(
351    sys::ReceiverAdvertising,
352    RecvAdvertiserInstance,
353    NDIlib_recv_advertiser_instance_t,
354    NDIlib_recv_advertiser_create_t,
355    AdvertiserOptions,
356    "advertiser",
357    NDIlib_recv_advertiser_create,
358    NDIlib_recv_advertiser_destroy,
359    ReceiverAdvertiserConfiguration::NDIlib_recv_advertiser_create_ex
360);
361server_api!(
362    sys::SenderDiscovery,
363    SendListenerInstance,
364    NDIlib_send_listener_instance_t,
365    NDIlib_send_listener_create_t,
366    ListenerOptions,
367    "listener",
368    NDIlib_send_listener_create,
369    NDIlib_send_listener_destroy,
370    SenderListenerConfiguration::NDIlib_send_listener_create_ex
371);
372server_api!(
373    sys::ReceiverDiscovery,
374    RecvListenerInstance,
375    NDIlib_recv_listener_instance_t,
376    NDIlib_recv_listener_create_t,
377    ListenerOptions,
378    "listener",
379    NDIlib_recv_listener_create,
380    NDIlib_recv_listener_destroy,
381    ReceiverListenerConfiguration::NDIlib_recv_listener_create_ex
382);
383
384/// State the SDK may read until its native object has been destroyed.
385/// The owner calls this hook while both the object and all retained values are
386/// live, then destroys the object before any retained value is dropped.
387///
388/// # Safety
389/// `Default` must start with no native registrations. An implementation must
390/// retain everything its native object can read until the owner destroys it.
391unsafe trait Retained<A: ServerApi>: Default {
392    /// # Safety
393    /// `instance` is this state's live owner, created through `api`. Every
394    /// retained registration belongs to that instance and remains live for
395    /// the call; no operation on the instance overlaps this hook or teardown.
396    unsafe fn before_destroy(&mut self, _api: &A, _instance: A::Instance) {}
397}
398// SAFETY: unit retains no native state and its hook does nothing.
399unsafe impl<A: ServerApi> Retained<A> for () {}
400
401/// Own every value the SDK may retain until its object is destroyed.
402struct ServerObject<A: ServerApi, R: Retained<A> = ()> {
403    instance: A::Instance,
404    retained: R,
405    api: crate::runtime::Bound<A>,
406    _url: Option<std::ffi::CString>,
407    #[cfg(feature = "advanced")]
408    _config: crate::advanced::RetainedConfig,
409}
410
411impl<A: ServerApi, R: Retained<A>> ServerObject<A, R> {
412    fn new(ndi: &crate::Ndi, options: &A::Options) -> crate::Result<Self> {
413        #[cfg(feature = "advanced")]
414        {
415            <Self as crate::advanced::Configurable>::create_from_options(ndi, options)
416        }
417        #[cfg(not(feature = "advanced"))]
418        {
419            Self::create_plain(ndi, options)
420        }
421    }
422
423    fn create_plain(ndi: &crate::Ndi, options: &A::Options) -> crate::Result<Self> {
424        // SAFETY: the plain entry point obeys the shared lifecycle.
425        unsafe {
426            Self::create(ndi, options, R::default(), |api, settings| {
427                crate::runtime::NativeCreation::plain(api.create(settings))
428            })
429        }
430    }
431
432    /// # Safety
433    /// `create` obeys ServerApi's fresh-instance and settings lifetime contract.
434    /// `retained` starts with no native registrations or is already paired
435    /// with the fresh returned instance under Retained's hook contract.
436    unsafe fn create(
437        ndi: &crate::Ndi,
438        options: &A::Options,
439        retained: R,
440        create: impl FnOnce(&A, &A::Settings) -> crate::runtime::NativeCreation<A::Instance>,
441    ) -> crate::Result<Self> {
442        // Configured gates run first and include this table's own capability.
443        let api = ndi.bind::<A>()?;
444        let endpoint = options.server()?;
445        let settings = A::settings(
446            endpoint
447                .as_ref()
448                .map_or(std::ptr::null(), |endpoint| endpoint.url.as_ptr()),
449        );
450        let created = create(&api, &settings);
451        let instance = created.call.into_value();
452        if instance.is_null() {
453            return Err(not_created(A::OBJECT, endpoint.as_ref()));
454        }
455        Ok(Self {
456            instance,
457            retained,
458            api,
459            _url: endpoint.map(|endpoint| endpoint.url),
460            #[cfg(feature = "advanced")]
461            _config: created.config,
462        })
463    }
464}
465
466impl<A: ServerApi, R: Retained<A>> ServerObject<A, R> {
467    fn instance(&self) -> A::Instance {
468        self.instance
469    }
470
471    fn retained(&self) -> &R {
472        &self.retained
473    }
474
475    fn retained_mut(&mut self) -> &mut R {
476        &mut self.retained
477    }
478}
479
480#[cfg(feature = "advanced")]
481impl<A: ServerApi, R: Retained<A>> crate::advanced::Configurable for ServerObject<A, R> {
482    type Options = A::Options;
483    type Settings = A::Settings;
484    type Instance = A::Instance;
485    fn config(options: &Self::Options) -> Option<&crate::advanced::AdvancedConfig> {
486        options.config()
487    }
488
489    fn create_plain(ndi: &crate::Ndi, options: &Self::Options) -> crate::Result<Self> {
490        Self::create_plain(ndi, options)
491    }
492
493    fn create_configured(
494        ndi: &crate::Ndi,
495        options: &Self::Options,
496        config: Option<&crate::advanced::AdvancedConfig>,
497    ) -> crate::Result<Self> {
498        // SAFETY: the configured entry point obeys the shared lifecycle.
499        unsafe {
500            Self::configured(
501                ndi,
502                options,
503                config,
504                |table: &A::Configured, settings, text| A::create_configured(table, settings, text),
505            )
506        }
507    }
508
509    unsafe fn create_with(
510        ndi: &crate::Ndi,
511        options: &Self::Options,
512        create: impl FnOnce(&Self::Settings) -> crate::runtime::NativeCreation<Self::Instance>,
513    ) -> crate::Result<Self> {
514        // SAFETY: forwarded to the caller's fresh-instance obligation.
515        unsafe { Self::create(ndi, options, R::default(), |_, settings| create(settings)) }
516    }
517}
518
519impl<A: ServerApi, R: Retained<A>> Drop for ServerObject<A, R> {
520    fn drop(&mut self) {
521        // SAFETY: creation starts with empty retained state, and all later
522        // registrations go through this owner's native instance and API.
523        // Exclusive ownership excludes overlapping operations. The hook keeps
524        // those registrations live until native destruction returns.
525        unsafe { self.retained.before_destroy(&self.api, self.instance) };
526        // SAFETY: this owner destroys its non-null instance exactly once. All
527        // retained state, creation strings and configuration are live
528        // throughout destruction. Fields are dropped only after this returns,
529        // so retained state never depends on field order for native teardown.
530        unsafe { self.api.destroy(self.instance) };
531    }
532}
533
534#[cfg(test)]
535mod endpoint_tests {
536    use super::*;
537
538    #[test]
539    fn listener_endpoint_checks_preserve_nul_before_multiple_servers() {
540        assert!(ServerOptions::server(&ListenerOptions::new())
541            .unwrap()
542            .is_none());
543        assert!(matches!(
544            ServerOptions::server(&ListenerOptions::new().server("")),
545            Err(crate::Error::InvalidInput(crate::InputDefect::Empty {
546                what: "server"
547            }))
548        ));
549        for text in ["café.local:5959", "127.0.0.1"] {
550            let options = ListenerOptions::new().server(text);
551            let endpoint = ServerOptions::server(&options).unwrap().unwrap();
552            assert_eq!(endpoint.url.to_bytes(), text.as_bytes());
553            assert!(matches!(endpoint.input, EndpointInput::Single(value) if value == text));
554        }
555        for text in ["a\0,b", "a,b\0"] {
556            let options = ListenerOptions::new().server(text);
557            assert!(matches!(
558                ServerOptions::server(&options),
559                Err(crate::Error::InvalidCString(_))
560            ));
561        }
562        assert!(matches!(
563            ServerOptions::server(&ListenerOptions::new().server("a,b")),
564            Err(crate::Error::InvalidInput(
565                crate::InputDefect::MultipleDiscoveryServers
566            ))
567        ));
568    }
569
570    #[test]
571    fn checked_endpoint_refusals_keep_original_utf8_and_list_text() {
572        let listener = ListenerOptions::new().server("café.local:5959");
573        let advertisers = AdvertiserOptions::new().servers(["café.local:5959", "127.0.0.1"]);
574        for (endpoint, expected) in [
575            (ServerOptions::server(&listener).unwrap(), "café.local:5959"),
576            (
577                ServerOptions::server(&advertisers).unwrap(),
578                "café.local:5959,127.0.0.1",
579            ),
580        ] {
581            let error = not_created("test", endpoint.as_ref());
582            assert!(matches!(
583                error,
584                crate::Error::InvalidInput(crate::InputDefect::DiscoveryAddressRejected(failure))
585                    if &*failure.address == expected
586            ));
587        }
588        assert!(ServerOptions::server(&AdvertiserOptions::new())
589            .unwrap()
590            .is_none());
591        assert!(matches!(
592            ServerOptions::server(&AdvertiserOptions::new().servers([""])),
593            Err(crate::Error::InvalidInput(
594                crate::InputDefect::ListElement { index: 0, .. }
595            ))
596        ));
597    }
598}