grafton_ndi/routing.rs
1//! Redirect source selection without receiving or forwarding media in Rust.
2//!
3//! A [`Router`] is an NDI source that carries no media of its own. Receivers
4//! connect to it by name and are redirected to whichever source it currently
5//! routes to, so one process can switch what many receivers see without
6//! touching a frame.
7//!
8//! ```no_run
9//! use grafton_ndi::{routing::{Router, RouterOptions}, Finder, FinderOptions, Ndi};
10//! use std::time::Duration;
11//!
12//! # fn main() -> Result<(), grafton_ndi::Error> {
13//! let ndi = Ndi::new()?;
14//! let mut router = Router::new(&ndi, &RouterOptions::new("Program"))?;
15//!
16//! let finder = Finder::new(&ndi, &FinderOptions::default())?;
17//! finder.watch().wait_for_change(Duration::from_secs(2))?;
18//! if let Some(camera) = finder.current_sources()?.first() {
19//! router.set_route(camera)?;
20//! }
21//! # Ok(())
22//! # }
23//! ```
24
25#![warn(missing_docs)]
26
27use crate::{
28 source_retention::RetainedSources,
29 sys::{self, bindings::*},
30 to_ms_checked, Ndi, Result, Source,
31};
32use std::{ffi::CString, fmt, num::NonZeroU32, ptr, time::Duration};
33
34/// A router's advertised name and optional discovery groups.
35#[derive(Debug, Clone, PartialEq, Eq, Hash)]
36pub struct RouterOptions {
37 name: String,
38 groups: Option<Vec<String>>,
39 #[cfg(feature = "advanced")]
40 config: Option<crate::advanced::AdvancedConfig>,
41}
42impl RouterOptions {
43 /// Replace the advertised routing-source name, preserving other settings.
44 #[must_use]
45 pub fn name(mut self, name: impl Into<String>) -> Self {
46 self.name = name.into();
47 self
48 }
49
50 /// Inherit discovery groups from the NDI configuration.
51 #[must_use]
52 pub fn clear_groups(mut self) -> Self {
53 self.groups = None;
54 self
55 }
56
57 /// Remove the per-instance Advanced configuration override.
58 #[cfg(feature = "advanced")]
59 #[must_use]
60 pub fn clear_config(mut self) -> Self {
61 self.config = None;
62 self
63 }
64
65 /// Requested advertised name.
66 #[must_use]
67 pub fn configured_name(&self) -> &str {
68 &self.name
69 }
70
71 /// Requested discovery groups, or `None` to inherit the NDI configuration.
72 #[must_use]
73 pub fn configured_groups(&self) -> Option<&[String]> {
74 self.groups.as_deref()
75 }
76
77 /// The stored Advanced configuration handle, if any.
78 #[cfg(feature = "advanced")]
79 #[must_use]
80 pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
81 self.config.as_ref()
82 }
83
84 /// Configure a named routing source. Creating the Router advertises it.
85 pub fn new(name: impl Into<String>) -> Self {
86 Self {
87 name: name.into(),
88 groups: None,
89 #[cfg(feature = "advanced")]
90 config: None,
91 }
92 }
93 /// Set a non-empty list of discovery groups the router is advertised in,
94 /// replacing the NDI configuration. Use [`Self::clear_groups`] to inherit
95 /// the configuration. Creation refuses empty elements and elements
96 /// containing a comma or NUL.
97 #[must_use]
98 pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
99 self.groups = Some(groups.into_iter().map(Into::into).collect());
100 self
101 }
102 /// Create the router with this per-instance Advanced SDK configuration,
103 /// which it keeps for as long as it lives.
104 ///
105 /// [`Router::new`] then needs an Advanced runtime, and a build with the
106 /// Advanced SDK.
107 #[cfg(feature = "advanced")]
108 #[must_use]
109 pub fn config(mut self, config: crate::advanced::AdvancedConfig) -> Self {
110 self.config = Some(config);
111 self
112 }
113}
114
115#[derive(Clone, Copy)]
116struct RoutingInstance(NDIlib_routing_instance_t);
117
118// SAFETY: routing handles have no thread affinity. Router owns this handle
119// exclusively and is not Sync, so its native calls and destruction cannot overlap.
120unsafe impl Send for RoutingInstance {}
121
122/// A native routing source. Dropping it removes its advertisement.
123///
124/// # Threading
125///
126/// A router is [`Send`] but not [`Sync`]: it may be moved to another thread,
127/// and is used by one thread at a time. To keep one in state that several
128/// threads share, put it in a [`Mutex`](std::sync::Mutex), which is `Sync`
129/// because the router is `Send`.
130pub struct Router {
131 instance: RoutingInstance,
132 routing: crate::runtime::Bound<sys::Routing>,
133 _name: CString,
134 _groups: Option<CString>,
135 // The SDK may retain both an effective route and its last refused request.
136 sources: RetainedSources,
137 #[cfg(feature = "advanced")]
138 pub(crate) connection_metadata: crate::connection_metadata::ConnectionMetadata,
139 #[cfg(feature = "advanced")]
140 _config: crate::advanced::RetainedConfig,
141}
142
143const_assert!({
144 const fn assert_send<T: Send>() {}
145 assert_send::<Router>();
146});
147
148impl fmt::Debug for Router {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.debug_struct("Router")
151 .field("name", &self._name)
152 .finish_non_exhaustive()
153 }
154}
155
156impl Router {
157 /// Create and advertise a routing source that routes to nothing yet.
158 ///
159 /// # Errors
160 ///
161 /// Returns [`crate::Error::UnsupportedCapability`] when the selected runtime has no
162 /// [routing support](crate::capabilities::RuntimeFeature::Routing), or the
163 /// options carry an Advanced configuration that the runtime or this build
164 /// cannot take; [`crate::Error::InvalidCString`] when the name contains a
165 /// NUL byte; [`crate::Error::InvalidInput`] when the group list is empty or
166 /// a group is empty or contains a comma or NUL; and
167 /// [`crate::Error::NativeOperationFailed`] when the SDK creates no source.
168 #[doc(alias = "NDIlib_routing_create")]
169 #[doc(alias = "NDIlib_routing_create_v2")]
170 pub fn new(ndi: &Ndi, options: &RouterOptions) -> Result<Self> {
171 #[cfg(feature = "advanced")]
172 {
173 <Self as crate::advanced::Configurable>::create_from_options(ndi, options)
174 }
175 #[cfg(not(feature = "advanced"))]
176 {
177 Self::create_plain(ndi, options)
178 }
179 }
180
181 pub(crate) fn create_plain(ndi: &Ndi, options: &RouterOptions) -> Result<Self> {
182 // SAFETY: the SDK's router creation returns null or a fresh router
183 // that nothing else owns, and the settings outlive the call.
184 unsafe {
185 Self::create(ndi, options, |routing, settings| {
186 crate::runtime::NativeCreation::plain(
187 routing.named().NDIlib_routing_create(settings),
188 )
189 })
190 }
191 }
192
193 /// The one creation path: create a router through `create`, which is handed the routing table and the native
194 /// settings for `options`, and keep `config` for as long as the router
195 /// lives.
196 ///
197 /// # Safety
198 ///
199 /// `create` returns null or a live router of `ndi`'s runtime, made from
200 /// the settings it was handed, that nothing else owns.
201 pub(crate) unsafe fn create(
202 ndi: &Ndi,
203 options: &RouterOptions,
204 create: impl FnOnce(
205 &sys::Routing,
206 &NDIlib_routing_create_t,
207 ) -> crate::runtime::NativeCreation<NDIlib_routing_instance_t>,
208 ) -> Result<Self> {
209 // A router with a configuration gets here only once its own
210 // capability, which requires routing, has been allowed, so it is
211 // never refused for `Routing`.
212 let routing = ndi.bind::<sys::Routing>()?;
213 let name = CString::new(options.name.as_str())?;
214 let groups = crate::list_setting::list_cstring(options.groups.as_deref(), "groups")?;
215 let created = create(
216 &routing,
217 &NDIlib_routing_create_t {
218 p_ndi_name: name.as_ptr(),
219 p_groups: groups.as_ref().map_or(ptr::null(), |v| v.as_ptr()),
220 },
221 );
222 let instance = created.call.created()?.as_ptr();
223 Ok(Self {
224 instance: RoutingInstance(instance),
225 routing,
226 _name: name,
227 _groups: groups,
228 sources: RetainedSources::default(),
229 #[cfg(feature = "advanced")]
230 connection_metadata: crate::connection_metadata::ConnectionMetadata::default(),
231 #[cfg(feature = "advanced")]
232 _config: created.config,
233 })
234 }
235
236 /// Split the gated metadata table, native instance and retained registrations.
237 #[cfg(feature = "advanced")]
238 pub(crate) fn connection_metadata_parts(
239 &mut self,
240 ) -> Result<(
241 &sys::advanced::RouterConnectionMetadata,
242 NDIlib_routing_instance_t,
243 &mut crate::connection_metadata::ConnectionMetadata,
244 )> {
245 let table = self.routing.ndi().table()?;
246 Ok((table, self.instance.0, &mut self.connection_metadata))
247 }
248
249 /// Route connected and future receivers to `source`.
250 ///
251 /// # Errors
252 ///
253 /// Returns [`crate::Error::NativeOperationFailed`] when the SDK rejects
254 /// the change.
255 #[doc(alias = "NDIlib_routing_change")]
256 pub fn set_route(&mut self, source: &Source) -> Result<()> {
257 self.sources.replace_if(Some(source), |source| {
258 // SAFETY: this router is live and the retention helper owns both
259 // the effective and replacement descriptors through the call.
260 unsafe {
261 self.routing
262 .named()
263 .NDIlib_routing_change(self.instance.0, source)
264 }
265 })
266 }
267 /// Stop routing to any source. Receivers stay connected to the router.
268 ///
269 /// # Errors
270 ///
271 /// Returns [`crate::Error::NativeOperationFailed`] when the SDK rejects the change.
272 #[doc(alias = "NDIlib_routing_clear")]
273 pub fn clear_route(&mut self) -> Result<()> {
274 self.sources.replace_if(None, |_| {
275 // SAFETY: this router is live and the retention helper keeps both
276 // previously retained descriptors alive until clear returns.
277 unsafe { self.routing.named().NDIlib_routing_clear(self.instance.0) }
278 })
279 }
280 /// Count the receivers currently connected to this router without waiting.
281 /// This count does not establish progress of their media streams.
282 ///
283 /// # Errors
284 ///
285 /// Returns [`crate::Error::UnexpectedSdkResult`] when the SDK reports a
286 /// negative count.
287 #[doc(alias = "NDIlib_routing_get_no_connections")]
288 pub fn connection_count(&self) -> Result<u32> {
289 self.connection_count_timeout(0)
290 }
291
292 /// Wait up to `timeout` for at least one receiver to connect.
293 ///
294 /// Returns the connected count, or `None` when the timeout expires.
295 /// A zero timeout checks the current count without waiting.
296 ///
297 /// # Errors
298 ///
299 /// Returns [`crate::Error::InvalidInput`] when `timeout` exceeds
300 /// [`crate::MAX_TIMEOUT`], and [`crate::Error::UnexpectedSdkResult`] when
301 /// the SDK reports a negative count.
302 #[doc(alias = "NDIlib_routing_get_no_connections")]
303 pub fn wait_for_connection(&self, timeout: Duration) -> Result<Option<NonZeroU32>> {
304 self.connection_count_timeout(to_ms_checked(timeout)?)
305 .map(NonZeroU32::new)
306 }
307
308 fn connection_count_timeout(&self, timeout_ms: u32) -> Result<u32> {
309 // SAFETY: the router instance is live for this borrow.
310 let count = unsafe {
311 self.routing
312 .named()
313 .NDIlib_routing_get_no_connections(self.instance.0, timeout_ms)
314 };
315 count.count()
316 }
317 /// The source descriptor this router is advertised under, which receivers
318 /// connect to.
319 ///
320 /// # Errors
321 ///
322 /// Returns [`crate::Error::NativeOperationFailed`] when the SDK supplies no
323 /// descriptor, or one that names neither a source nor an address, and
324 /// [`crate::Error::UnexpectedSdkResult`] when its name or address is longer than
325 /// the 4 MiB available for one SDK string, including its terminator.
326 /// [`crate::Error::InvalidUtf8`] reports an invalid name or address.
327 /// [`crate::Error::AllocationFailed`] reports a failed text buffer reservation.
328 /// See [`crate::Finder::current_sources`] for allocation behavior of
329 /// shared source owners.
330 #[doc(alias = "NDIlib_routing_get_source_name")]
331 pub fn source(&self) -> Result<Source> {
332 // SAFETY: the router is live, and the descriptor the SDK returns stays
333 // valid until the router is destroyed, after this copy completes.
334 unsafe {
335 Source::try_from_raw(
336 self.routing
337 .named()
338 .NDIlib_routing_get_source_name(self.instance.0),
339 )
340 }
341 }
342}
343
344impl Drop for Router {
345 fn drop(&mut self) {
346 // SAFETY: the instance was created by this table and is destroyed once.
347 unsafe { self.routing.NDIlib_routing_destroy(self.instance.0) };
348 }
349}