Skip to main content

grafton_ndi/
lib.rs

1//! Discover NDI sources and send and receive video, audio and metadata.
2//!
3//! Supports NDI 6 with optional async adapters, image encoding, Advanced SDK
4//! operations, and recording/playback. Default desktop and Android builds need
5//! no SDK at build time. Advanced native operations need Advanced headers and
6//! libclang; Apple mobile targets link an SDK archive.
7//!
8//! # Quick Start
9//!
10//! ```no_run
11//! use grafton_ndi::{Ndi, FinderOptions, Finder};
12//! use std::time::Duration;
13//!
14//! # fn main() -> Result<(), grafton_ndi::Error> {
15//! // Select the default NDI runtime and start it
16//! let ndi = Ndi::new()?;
17//!
18//! // Find sources on the network
19//! let finder = Finder::new(&ndi, &FinderOptions::new())?;
20//!
21//! // Discover sources
22//! let sources = finder.find_sources(Duration::from_secs(5))?;
23//!
24//! for source in sources {
25//!     println!("Found: {}", source);
26//! }
27//! # Ok(())
28//! # }
29//! ```
30//!
31//! # Choose a workflow
32//!
33//! - [`runtime`]: runtime selection, initialization and lifetime.
34//! - [`finder`]: source discovery and caching.
35//! - [`receiver`] and [`sender`]: capture and publish media.
36//! - [`frames`] and [`framesync`]: frame layouts and clock-driven capture.
37//! - [`capabilities`]: check optional runtime operations.
38//! - [`routing`] and [`discovery_server`]: redirect connections and use Discovery Servers.
39//! - [`audio_conversion`] and [`video_conversion`]: checked media conversions.
40//!
41//! Cargo features enable `asynchronous` (`tokio` or `smol`), `advanced`,
42//! `file` (`file-io`), and image encoders (`image-encoding`). None is on by default.
43//!
44//! See the [user guides](https://github.com/GrantSparks/grafton-ndi/blob/main/README.md#guides-and-examples)
45//! for setup, platform support, examples, limitations and migration instructions.
46
47#![deny(missing_debug_implementations)]
48#![warn(clippy::return_self_not_must_use)]
49#![cfg_attr(
50    not(test),
51    deny(
52        clippy::unwrap_used,
53        clippy::expect_used,
54        clippy::unreachable,
55        clippy::panic,
56        clippy::disallowed_macros
57    )
58)]
59// Android has no native thread-locals, so std expands `thread_local!` through
60// its OS-key implementation, which wraps even a `const { .. }` initializer in
61// an ordinary function; clippy then asks for the `const` the test-only
62// thread-locals already have. Plain `allow`: an expectation would go unfulfilled
63// in an Android build without tests.
64#![cfg_attr(
65    all(test, target_os = "android"),
66    allow(
67        clippy::missing_const_for_thread_local,
68        reason = "false positive: the OS-key thread_local! expansion hides the const initializer"
69    )
70)]
71
72macro_rules! const_assert {
73    (@value $body:block) => {{
74        #[allow(clippy::disallowed_macros, reason = "checks evaluated only at compile time")]
75        let value = const $body;
76        value
77    }};
78    ($body:block) => {
79        #[allow(clippy::disallowed_macros, reason = "checks evaluated only at compile time")]
80        const _: () = $body;
81    };
82    ($($assertion:tt)+) => {
83        const_assert!({ assert!($($assertion)+) });
84    };
85}
86
87macro_rules! debug_invariant {
88    ($($args:tt)+) => {{
89        // Clippy sees the release assert macro inside std's debug expansion.
90        #[allow(clippy::disallowed_macros, reason = "this check runs only with debug assertions enabled")]
91        {
92            std::debug_assert!($($args)+);
93        }
94    }};
95}
96
97mod capture;
98mod change_feed;
99mod color_info;
100mod connection_metadata;
101mod error;
102#[cfg(any(ndi_has_advanced_keyframe_demand, all(test, feature = "advanced")))]
103mod keyframe_changes;
104mod list_setting;
105mod marker;
106mod media;
107mod pixels;
108mod rejected;
109mod sdk_copy;
110mod source_retention;
111mod sys;
112mod time;
113mod timeout;
114
115pub mod framesync;
116
117pub mod audio_conversion;
118pub mod finder;
119pub mod frames;
120pub mod receiver;
121pub mod runtime;
122pub mod sender;
123pub mod video_conversion;
124
125pub mod capabilities;
126#[path = "discovery/mod.rs"]
127pub mod discovery_server;
128pub mod routing;
129
130#[cfg(feature = "advanced")]
131pub mod advanced;
132
133#[cfg(feature = "file-io")]
134pub mod file;
135
136#[cfg(any(feature = "tokio", feature = "smol"))]
137pub mod asynchronous;
138
139#[cfg(feature = "image-encoding")]
140#[path = "image/mod.rs"]
141pub mod image_encoding;
142
143pub use {
144    capabilities::{
145        Capabilities, Capability, CapabilityRefusal, CapabilityStatus, CapabilityUnavailable,
146        RuntimeFeature, RuntimeInfo, SdkEdition, SdkLinkage, SdkVersion,
147    },
148    error::*,
149    finder::{Finder, FinderOptions, Source, SourceAddress, SourceCache, SourceWatch},
150    frames::{
151        AudioChannels, AudioFormat, AudioFrame, AudioFrameBuilder, AudioFrameRef, AudioSource,
152        BorrowedAudioFrame, BorrowedAudioFrameBuilder, BorrowedVideoFrame,
153        BorrowedVideoFrameBuilder, FormatCategory, FrameMetadataStatus, MetadataFrame,
154        MetadataFrameRef, MetadataSource, PixelFormat, PixelFormatInfo, ScanType, VideoFrame,
155        VideoFrameBuilder, VideoFrameRef, VideoPlane, VideoPlanes, VideoRows, VideoSource,
156    },
157    framesync::{
158        AudioInputFormat, FrameSync, FrameSyncAudioRef, FrameSyncAudioRequest, FrameSyncVideoRef,
159    },
160    receiver::{
161        AudioMode, ConnectionStats, EventMode, FrameSyncAttached, MetadataMode, Ptz, RawCapture,
162        ReceiveDelay, Receiver, ReceiverBandwidth, ReceiverColorFormat, ReceiverEvent,
163        ReceiverItem, ReceiverItemRef, ReceiverMode, ReceiverOptions, ReceiverStatus,
164        SettingChange, SourceNameChange, Tally, VideoMode,
165    },
166    runtime::{Ndi, ProcessLifetimeRuntime, Runtime, RuntimeOptions},
167    sender::{AudioSendMode, RawSend, RawVideo, Sender, SenderMode, SenderOptions},
168};
169
170pub use color_info::{ColorInfo, ColorPrimaries, TransferFunction, YuvMatrix};
171pub use media::{FourCc, FrameRate, MediaTypes, PictureAspectRatio, StreamTier};
172pub use rejected::Rejected;
173pub use time::{ReceivedTimestamp, SdkTimestamp, Timecode};
174
175/// Alias for Result with our Error type
176pub type Result<T> = std::result::Result<T, crate::error::Error>;
177
178/// The largest finite timeout: `u32::MAX - 1` milliseconds (~49.7 days).
179///
180/// The NDI SDK takes every timeout as a `uint32_t` count of milliseconds and
181/// reserves the largest value, 0xFFFFFFFF, for a wait without a limit (see
182/// the event functions in `Processing.NDI.RecvListener.h`). A finite wait is
183/// therefore never passed to the SDK as `u32::MAX`. A longer timeout is
184/// refused with [`Error::InvalidInput`].
185///
186/// A timeout is rounded up to whole milliseconds, so a non-zero wait shorter
187/// than a millisecond becomes one millisecond, and only [`Duration::ZERO`]
188/// polls without blocking.
189///
190/// [`Duration::ZERO`]: std::time::Duration::ZERO
191pub const MAX_TIMEOUT: std::time::Duration =
192    std::time::Duration::from_millis(timeout::MAX_MILLIS as u64);
193
194pub(crate) use timeout::to_ms_checked;
195
196#[cfg(test)]
197#[path = "tests.rs"]
198mod tests;
199
200#[cfg(test)]
201mod test_alloc;
202
203#[cfg(test)]
204mod test_support;
205
206#[cfg(ndi_test_receiver_proofs)]
207#[path = "../tests/ui/internal/receiver_proofs.rs"]
208mod receiver_proofs;
209
210#[cfg(any(
211    ndi_test_runtime_binding,
212    ndi_test_runtime_binding_control,
213    ndi_test_runtime_binding_privacy
214))]
215#[path = "../tests/ui/internal/runtime_binding.rs"]
216mod runtime_binding_contract;
217
218#[cfg(ndi_test_frame_source)]
219#[path = "../tests/ui/internal/frame_source.rs"]
220mod frame_source_contract;
221
222#[cfg(ndi_test_assertion_policy)]
223#[path = "../tests/ui/internal/assertion_policy.rs"]
224mod assertion_policy_contract;