grafton_ndi/error.rs
1//! The crate's one error type.
2
3#[cfg(test)]
4mod allocation_tests;
5mod defects;
6#[cfg(test)]
7mod defects_tests;
8#[cfg(test)]
9mod production_tests;
10pub use crate::sys::table::NativeFunction;
11pub use defects::*;
12
13mod loading;
14pub use loading::{
15 LibraryKind, LoadAttempt, LoadFailure, LoadOrigin, LoadRefusal, SelectionConflict,
16 SelectionFailure, VersionTextDefect,
17};
18
19use thiserror::Error;
20
21use std::ffi::{CString, NulError};
22
23#[cfg(test)]
24use crate::capabilities::RuntimeFeature;
25use crate::capabilities::{Capability, CapabilityRefusal};
26
27/// Why an async blocking operation could not run.
28///
29/// Panics are resumed on the awaiting task rather than reported as spawn
30/// failures. This discriminator does not depend on diagnostic text.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
32#[non_exhaustive]
33#[cfg(any(feature = "tokio", feature = "smol"))]
34pub enum SpawnFailure {
35 /// The Tokio operation was polled outside a Tokio runtime.
36 #[error("no Tokio runtime is entered")]
37 NoRuntime,
38 /// The runtime cancelled the blocking task, its abandoned closure never started,
39 /// or a started worker observed that its future was dropped.
40 #[error("the blocking task was cancelled")]
41 TaskCancelled,
42}
43
44/// Why the selected native runtime could not initialize.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
46#[non_exhaustive]
47pub enum InitializationFailure {
48 /// The SDK refused initialization on a supported CPU.
49 #[error("NDIlib_initialize returned false on a CPU the runtime reports as supported")]
50 NotStarted,
51 /// Another runtime handle would overflow the reference count.
52 #[error("NDI runtime reference count exhausted")]
53 HandleCountExhausted,
54}
55
56/// The storage an operation could not allocate.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
58#[non_exhaustive]
59pub enum AllocationKind {
60 /// Finder or Discovery Server snapshot and discovery-result storage.
61 #[error("discovery results")]
62 DiscoveryResults,
63 /// A source descriptor copied from a single SDK query.
64 #[error("source descriptor storage")]
65 SourceDescriptor,
66 /// Reusable image encoder scratch storage.
67 #[error("image scratch storage")]
68 ImageScratch,
69 /// Custom allocator lease bookkeeping.
70 #[error("allocator lease storage")]
71 AllocatorLeases,
72 /// Queued sender descriptors and completion bookkeeping.
73 #[error("completion storage")]
74 QueuedCompletions,
75 /// A crate-owned custom receive buffer.
76 #[error("receive buffer")]
77 ReceiveBuffer,
78}
79
80/// An allocation failed after the operation passed its validation and budgets.
81///
82/// This describes storage exhaustion, rather than invalid input or malformed
83/// SDK data. It also covers a collection refusing an unrepresentable capacity.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
85#[error("could not allocate {kind}{requested}", requested = RequestedBytes(*.bytes))]
86pub struct AllocationFailure {
87 /// Which storage could not be supplied.
88 pub kind: AllocationKind,
89 /// The requested allocation size in bytes, when known.
90 pub bytes: Option<usize>,
91}
92
93struct RequestedBytes(Option<usize>);
94
95impl std::fmt::Display for RequestedBytes {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 if let Some(bytes) = self.0 {
98 write!(f, " ({bytes} bytes)")?;
99 }
100 Ok(())
101 }
102}
103
104pub(crate) fn allocation_failed(kind: AllocationKind, bytes: Option<usize>) -> Error {
105 Error::AllocationFailed(AllocationFailure { kind, bytes })
106}
107
108/// Every error this crate reports, from the core API, the `advanced` module
109/// and the File API alike.
110///
111/// Each variant says when it occurs. Its text is for diagnostics; match on
112/// the variant and its fields rather than on the text.
113///
114/// This enum is marked `#[non_exhaustive]` so that new error variants can be
115/// added as the NDI SDK surface evolves without constituting a breaking change.
116/// Match arms should include a wildcard `_` pattern.
117#[derive(Debug, Error)]
118#[non_exhaustive]
119pub enum Error {
120 /// No usable NDI library could be selected.
121 ///
122 /// [`LoadFailure`] records the library, attempted locations, their origins
123 /// and typed [`LoadRefusal`] causes. [`LoadFailure::loaded_any`] distinguishes
124 /// code that loaded and was refused from locations that could not be opened.
125 /// `Display` retains the diagnostic text for every attempt.
126 ///
127 /// * Selecting the NDI runtime ([`Runtime::select`] and every constructor
128 /// that selects one): no usable runtime library was found. The message
129 /// names every location tried and why each was rejected: the file was
130 /// absent, the operating system could not load it, or it lacks a
131 /// required entry point.
132 /// * Opening the File API (`file::FileApi::new`): no usable File library
133 /// was found, with every location tried and the reason for each. A
134 /// library that provides no family of File entry points is not usable.
135 ///
136 /// Nothing is selected, so the call can be repeated, for example once the
137 /// library is installed. A selected File library that lacks the entry
138 /// points of one family is reported as [`Error::UnsupportedCapability`]
139 /// instead, by every operation that needs that family.
140 ///
141 /// [`Runtime::select`]: crate::Runtime::select
142 #[error("Failed to load an NDI library: {0}")]
143 RuntimeLoadFailed(LoadFailure),
144
145 /// An operation needs a capability this build or the selected runtime
146 /// does not provide.
147 ///
148 /// `refusal` is the same typed evidence returned by
149 /// [`Capabilities::status`](crate::Capabilities::status) or
150 /// `file::FileApi::status`. Every operation
151 /// is refused before reaching the SDK, and [`Ndi::require_feature`](crate::Ndi::require_feature)
152 /// reports the same value in advance. This condition lasts for the process
153 /// lifetime: selecting another runtime or supplying missing build declarations
154 /// requires a new process or build.
155 #[error("NDI capability {capability} is unavailable: {refusal}")]
156 UnsupportedCapability {
157 /// The capability, the same whichever operation it gates.
158 capability: Capability,
159 /// Why it is unavailable, with the evidence recorded during detection.
160 refusal: CapabilityRefusal,
161 },
162
163 /// Runtime or File library selection conflicts with the process's native
164 /// libraries or a selection already in progress.
165 ///
166 /// [`SelectionFailure`] identifies the [`SelectionConflict`], library and
167 /// selected, requested or foreign module paths without parsing text.
168 ///
169 /// * The runtime options name a library file other than the selected one,
170 /// ask for the Advanced SDK when the selected runtime is not one, or
171 /// name any file when the SDK is linked into the program.
172 /// * On dynamically loaded, non-Apple ELF targets, an explicit runtime
173 /// path is refused while another NDI runtime occupies the process's
174 /// global symbol scope, with [`SelectionConflict::ForeignRuntimeInScope`].
175 /// * Loading a native library re-entered runtime or File library selection
176 /// on the same thread.
177 /// * The File API options name a File library other than the selected one,
178 /// or any library when the File library is linked into the program.
179 /// * The File library cannot accompany the selected runtime: on Linux,
180 /// macOS and Android it needs the Advanced SDK runtime, and it is
181 /// refused while the process's global symbol scope holds an NDI runtime
182 /// other than the selected one, which it would bind to.
183 #[error("Conflicting {0}")]
184 RuntimeConflict(SelectionFailure),
185
186 /// The native SDK did not perform an operation.
187 ///
188 /// It returned the failure value its header gives the operation: `false`
189 /// from an operation that reports success, or null from one that creates
190 /// an object (a finder, receiver, sender, router, FrameSync, AV sync or
191 /// genlock instance, or a File player or recorder) or returns a source
192 /// descriptor; or an internal-error status from AV synchronization.
193 /// A source descriptor with neither a name nor an address is
194 /// reported the same way. `operation` names the SDK function. A Discovery Server advertiser or listener the SDK does
195 /// not create is reported as [`Error::InvalidInput`] instead, because the
196 /// SDK refuses only the address it was given.
197 ///
198 /// The SDK gives no further reason. The File library may report one as
199 /// an event.
200 #[error("The NDI SDK did not perform {operation}")]
201 NativeOperationFailed {
202 /// The SDK function that failed.
203 operation: crate::NativeFunction,
204 },
205
206 /// NDI runtime initialization failed, with its [`InitializationFailure`].
207 ///
208 /// Returned only for the runtime itself: the SDK refused to start, or the
209 /// runtime handle reference count was exhausted. A finder, receiver,
210 /// sender or other object the SDK does not create is reported as
211 /// [`Error::NativeOperationFailed`], naming the creating function. A
212 /// runtime library that cannot be loaded is reported as
213 /// [`Error::RuntimeLoadFailed`] instead, and one that does not start
214 /// because of the CPU as [`Error::UnsupportedCpu`].
215 #[error("Failed to initialize the NDI runtime: {0}")]
216 InitializationFailed(InitializationFailure),
217
218 /// Storage could not be allocated for an otherwise valid operation.
219 ///
220 /// [`AllocationFailure`] identifies the storage and its requested size
221 /// when known. Discovery copies, image encoding scratch, queued sender
222 /// bookkeeping, allocator leases and crate-owned receive buffers all
223 /// report this condition here. The lossy WebP encoder's own storage is
224 /// the exception: its supported error API cannot classify allocation
225 /// failures, so they remain [`FrameDefect::EncodingFailed`] inside
226 /// [`Error::InvalidFrame`]. A configured budget refusal is instead
227 /// [`Error::ResourceLimit`].
228 #[error("Allocation failed: {0}")]
229 AllocationFailed(AllocationFailure),
230
231 /// The selected NDI runtime cannot run on this CPU.
232 ///
233 /// The runtime did not start and reports that the CPU lacks instructions
234 /// it requires. Which instructions those are depends on the SDK version
235 /// and the platform. [`Runtime::is_supported_cpu`](crate::Runtime::is_supported_cpu)
236 /// answers the same question without starting NDI.
237 #[error("The selected NDI runtime does not support this CPU")]
238 UnsupportedCpu,
239
240 /// The SDK sent nothing because nothing is connected.
241 ///
242 /// A receiver sends metadata upstream to the source it is connected to,
243 /// and `Processing.NDI.Recv.h` documents a refusal as meaning that it is
244 /// connected to none. A later attempt can succeed once it has connected.
245 #[error("Not connected: the NDI SDK sent nothing")]
246 NotConnected,
247
248 /// Text is not UTF-8; the original [`std::str::Utf8Error`] retains its offsets.
249 ///
250 /// Reported for standalone received metadata frames and strings a receiver
251 /// returns, such as its source's web-control URL, and for application metadata
252 /// passed as a [`std::ffi::CStr`] to borrowed audio and video frame builders.
253 /// Unreadable per-frame
254 /// video/audio metadata is withheld without discarding the media; inspect
255 /// [`crate::FrameMetadataStatus`] instead. Text a peer advertises through a Discovery Server is
256 /// decoded lossily instead.
257 #[error("Invalid UTF-8 string in data: {0}")]
258 InvalidUtf8(std::str::Utf8Error),
259
260 /// Text passed to the SDK contains a NUL byte, which a C string cannot
261 /// hold.
262 #[error("Invalid CString: {0}")]
263 InvalidCString(NulError),
264
265 /// A receiver reported the SDK error frame: its connection was lost.
266 #[error("Failed to capture frame: the SDK returned an error frame: the connection was lost")]
267 ConnectionLost,
268
269 /// A frame, or a value describing media, is invalid; [`FrameDefect`] identifies the cause.
270 /// Shared layout checks use [`FrameDefect::Layout`] with a [`LayoutDefect`].
271 ///
272 /// * A frame the SDK delivered (video, audio, metadata or a compressed
273 /// packet) fails validation: its dimensions, format, strides, sizes or
274 /// pointers are inconsistent, or a standalone metadata frame has no
275 /// terminator within the limit.
276 /// * A frame, packet or buffer being built, converted or sent does not
277 /// match its format: a buffer is too small, a dimension, stride or rate
278 /// is out of range, or a format cannot be used for the operation. This
279 /// includes a compressed frame the SDK would discard instead of
280 /// delivering it.
281 /// * A frame's colour description is malformed, conflicting or withheld
282 /// with its metadata; its HDR transfer is refused; its image dimensions
283 /// exceed the codec's limits; or an image encoder fails.
284 ///
285 /// Unreadable optional video/audio metadata is withheld instead of failing
286 /// capture; [`crate::FrameMetadataStatus`] reports its condition. Withheld
287 /// metadata can still fail a later colour-description read.
288 ///
289 /// A value that describes no one frame, such as a compressed audio or video
290 /// format, a FrameSync or AV sync audio request, or an allocation, clock or
291 /// remote-control value of the `advanced` module, is [`Error::InvalidInput`]
292 /// when it is out of range.
293 #[error("Invalid frame data: {0}")]
294 InvalidFrame(FrameDefect),
295
296 /// A value passed to the crate cannot be used; [`InputDefect`] identifies the cause.
297 /// Standalone aspect ratios, frame rates, compressed audio or video formats,
298 /// FrameSync and AV sync audio requests, clock requests and allocation strides
299 /// use [`InputDefect::Layout`] with a [`LayoutDefect`].
300 ///
301 /// It is out of range, malformed, or conflicts with another setting: for
302 /// example a timeout above [`MAX_TIMEOUT`](crate::MAX_TIMEOUT), a relative
303 /// library path, a receive delay above two seconds, a PTZ value outside
304 /// its range, malformed Advanced configuration JSON, more than one
305 /// Discovery Server for a listener, allocator limits that cannot all be
306 /// reached, a registration handed to an advertiser that did not issue it,
307 /// a compressed audio or video format, an allocation stride or buffer, a
308 /// FrameSync or AV sync audio request, a clock quantity or a remote control
309 /// value out of the range the SDK accepts, or a File API name, path or option the File library cannot
310 /// take. The message says which value and why, and nothing reaches the
311 /// SDK, with one exception: the SDK creates a Discovery Server advertiser
312 /// or listener for any address it can parse, so when it creates none, the
313 /// address it was given, or the lack of one, is reported here.
314 #[error("Invalid input: {0}")]
315 InvalidInput(InputDefect),
316
317 /// A bounded queue is full. The same call can succeed once queued work
318 /// has completed, with nothing else changed; the [`QueueLimit`] says
319 /// which queue and limit.
320 ///
321 /// * `advanced::QueuedSender::try_submit`, when the frame would take the
322 /// queue past its frame limit ([`QueueLimit::Frames`]) or the retained
323 /// frames leave insufficient byte capacity ([`QueueLimit::Bytes`]). A
324 /// frame exceeding the entire byte limit gets [`Error::InvalidInput`].
325 /// The frame comes back in the `Rejected`;
326 /// collect completed frames and submit it again.
327 /// * An operation of an async File handle, when the handle's command
328 /// queue is full ([`QueueLimit::FileCommands`]). A request to stop is
329 /// refused only when another one already waits beyond the full queue.
330 /// * A recorder's submitted `finish` and `wait_for_finish` operations,
331 /// when their separate pending-wait budget is full
332 /// ([`QueueLimit::FileFinishWaits`]). Ordinary commands remain available.
333 /// * `file::AsyncFilePlayer::probe`, when the probes waiting for the
334 /// process's probe thread fill its queue ([`QueueLimit::FileProbes`]).
335 #[error("Queue full: {0}")]
336 #[cfg(any(feature = "advanced", feature = "file-io"))]
337 QueueFull(QueueLimit),
338
339 /// A value the SDK returned, other than a frame, breaks the SDK's
340 /// documented contract.
341 /// [`SdkResultDefect`] identifies that contract breach.
342 ///
343 /// For example a negative connection count, a receive delay outside the
344 /// range the SDK accepts, a string without a terminator within its limit,
345 /// a finder or Discovery Server snapshot, or an event batch, that is malformed, a
346 /// send-completion callback for a frame the SDK
347 /// was not handed or had already returned, negative encoder guidance, an
348 /// unknown AV sync status, an AV sync format change to a sample rate or
349 /// channel count that is not positive, or a File SDK result that cannot
350 /// be represented. Malformed
351 /// frames are reported as [`Error::InvalidFrame`], and text that is not
352 /// UTF-8 as [`Error::InvalidUtf8`]. Ordinary resource-budget ceilings are
353 /// [`Error::ResourceLimit`] instead.
354 #[error("{prefix}{cause}", prefix = sdk_result_prefix(.0), cause = .0)]
355 UnexpectedSdkResult(SdkResultDefect),
356
357 /// Discovery data exceeded a per-copy or whole-discovery resource limit.
358 /// No partial result is returned. `resource` identifies the exhausted
359 /// count or byte budget; `limit` is its maximum.
360 #[error("NDI resource limit exceeded: {resource} (limit {limit})")]
361 ResourceLimit {
362 /// The resource whose budget was exhausted.
363 resource: ResourceKind,
364 /// Maximum number of entries or bytes for that resource.
365 limit: usize,
366 },
367
368 /// A Discovery Server listener did not send a request, because no receiver
369 /// it lists accepts it.
370 ///
371 /// Unlike [`Error::UnsupportedCapability`], this says nothing about the
372 /// build or the runtime. A listener lists nothing until it has connected
373 /// to its server, so a request made right after it was created can be
374 /// refused with `advertised` false and succeed later.
375 #[error("The Discovery Server listener sent no request: {}", request_refusal(.advertised))]
376 ReceiverRequestNotAccepted {
377 /// Whether a receiver with the identifier is listed. When it is not, it
378 /// may not have registered with the server yet, and a later request can
379 /// succeed; when it is, the receiver does not accept this command.
380 advertised: bool,
381 },
382
383 /// An async blocking operation could not run.
384 ///
385 /// [`SpawnFailure`] distinguishes a missing Tokio runtime context from a
386 /// cancelled blocking task. A panic in the operation or its callback is
387 /// resumed on the awaiting task with its original payload, after SDK frame
388 /// guards are released on the worker. Dropping the future discards its
389 /// result and any panic payload; it does not deliver an error to that caller.
390 ///
391 /// # Example
392 ///
393 /// ```
394 /// use grafton_ndi::{Error, SpawnFailure};
395 /// fn handle_error(error: Error) {
396 /// match error {
397 /// Error::SpawnFailed(SpawnFailure::NoRuntime) => {
398 /// eprintln!("Await this operation inside a Tokio runtime");
399 /// }
400 /// Error::SpawnFailed(SpawnFailure::TaskCancelled) => {
401 /// eprintln!("The runtime cancelled the blocking task");
402 /// }
403 /// error => eprintln!("{error}"),
404 /// }
405 /// }
406 /// ```
407 #[error("Could not run blocking task: {0}")]
408 #[cfg(any(feature = "tokio", feature = "smol"))]
409 SpawnFailed(SpawnFailure),
410
411 /// A File API operation is not permitted in the current state of its
412 /// recorder or async handle.
413 ///
414 /// The [`StateConflict`](crate::file::StateConflict) says which state forbids
415 /// it, and [`StateConflict::is_retryable`](crate::file::StateConflict::is_retryable)
416 /// whether the same call can succeed later without anything else changing.
417 #[cfg(feature = "file-io")]
418 #[error("Invalid File API state: {0}")]
419 InvalidState(crate::file::StateConflict),
420
421 /// An operating-system operation failed.
422 ///
423 /// * File API: resolving a relative path against the current directory,
424 /// which may be unavailable.
425 /// * File API: checking, before a recording starts or rolls over, that
426 /// the directory of its first file exists and can be written to, and
427 /// that an exact file name does not exist yet
428 /// ([`AlreadyExists`](std::io::ErrorKind::AlreadyExists)).
429 /// * File API: starting the thread of an async File handle or probe, or
430 /// the timer thread that async event waits share.
431 /// * Image encoding: the writer given to a frame's `encode_image_to`
432 /// failed. The error is the writer's own.
433 #[cfg(any(feature = "file-io", feature = "image-encoding"))]
434 #[error(transparent)]
435 Io(#[from] std::io::Error),
436}
437
438impl From<NulError> for Error {
439 fn from(error: NulError) -> Self {
440 Self::InvalidCString(error)
441 }
442}
443
444/// Report the first NUL's byte offset and retain only the prefix through it.
445pub(crate) fn nul_error_with_prefix(text: &str) -> Option<NulError> {
446 let position = text.find('\0')?;
447 #[expect(
448 clippy::expect_used,
449 reason = "the slice ends with the first NUL, and NulError has no public constructor"
450 )]
451 Some(CString::new(&text.as_bytes()[..=position]).expect_err("the prefix ends with a NUL"))
452}
453
454// The existing largest payload is NulError. Selection diagnostics must not
455// enlarge the error returned by hot capture/send paths (40 bytes on x86-64).
456const_assert!(
457 std::mem::size_of::<Error>()
458 <= std::mem::size_of::<NulError>() + std::mem::align_of::<NulError>()
459);
460
461// Preserve the compact nested causes on every 32-bit and 64-bit target,
462// including SDK allocator paths that return a LayoutDefect without allocating.
463#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
464const_assert!({
465 use std::mem::size_of;
466 assert!(size_of::<FrameDefect>() == 4 * size_of::<usize>());
467 assert!(size_of::<InputDefect>() == 4 * size_of::<usize>());
468 assert!(
469 size_of::<LayoutDefect>()
470 == if cfg!(target_pointer_width = "64") {
471 24
472 } else {
473 16
474 }
475 );
476});
477
478/// The resource budget exhausted by a discovery operation.
479///
480/// Each variant specifies both the scope and the unit of the `limit` field in
481/// [`Error::ResourceLimit`]. Byte budgets cover native data inspected and owned
482/// storage retained, as documented by the operation. Match this value rather
483/// than diagnostic text; additional budgets may be introduced in 3.x.
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
485#[non_exhaustive]
486pub enum ResourceKind {
487 /// Source descriptors in one plain or Advanced Finder snapshot; the limit
488 /// is a number of sources.
489 #[error("Finder snapshot sources")]
490 FinderSnapshotSources,
491 /// Aggregate bytes scanned or copied for one plain or Advanced Finder
492 /// snapshot; the limit is in bytes.
493 #[error("Finder snapshot bytes")]
494 FinderSnapshotBytes,
495 /// Distinct sources retained over one Finder discovery window; the limit
496 /// is a number of sources.
497 #[error("Finder discovery sources")]
498 FinderDiscoverySources,
499 /// Aggregate owned storage retained over one Finder discovery window;
500 /// the limit is in bytes.
501 #[error("Finder discovery bytes")]
502 FinderDiscoveryBytes,
503 /// Aggregate bytes scanned or copied for one Discovery Server snapshot or
504 /// event batch, including nested arrays and strings; the limit is in bytes.
505 #[error("Discovery Server snapshot or event batch bytes")]
506 DiscoveryServerCopyBytes,
507}
508
509/// Which bounded queue was full, carried by [`Error::QueueFull`].
510///
511/// Its `Display` text is for diagnostics; match on the variant rather than
512/// the text.
513#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
514#[non_exhaustive]
515#[cfg(any(feature = "advanced", feature = "file-io"))]
516pub enum QueueLimit {
517 /// An Advanced `QueuedSender` already holds as many frames as its
518 /// `QueueLimits::max_frames` allows.
519 #[error("queued video frame limit reached")]
520 Frames,
521 /// The frames an Advanced `QueuedSender` retains leave too little room
522 /// within `QueueLimits::max_bytes` for this frame. The frame itself fits
523 /// the limit, so collecting completions makes room.
524 #[error("queued video byte limit reached")]
525 Bytes,
526 /// An async File handle already has as many commands waiting as its
527 /// `AsyncFileOptions::command_capacity` allows, and, for a request to
528 /// stop, another request to stop waits beyond them.
529 #[error("File command queue is full")]
530 FileCommands,
531 /// An async recorder already has as many queued, registered or settling
532 /// finalization waits as `AsyncFileOptions::command_capacity` allows.
533 /// This budget is separate from ordinary command admission.
534 #[error("File finish-wait limit reached")]
535 FileFinishWaits,
536 /// The 64 async File probes that may wait for the process's probe thread
537 /// are already waiting.
538 #[error("File probe queue is full")]
539 FileProbes,
540}
541
542/// Why a listener refused to send a receiver request.
543fn request_refusal(advertised: &bool) -> &'static str {
544 if *advertised {
545 "the receiver it lists does not accept this request"
546 } else {
547 "it lists no receiver with this identifier, perhaps because it has not connected \
548 or the receiver has not registered yet"
549 }
550}
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555
556 #[test]
557 fn invalid_c_string_reports_its_cause_once() {
558 let error = Error::from(std::ffi::CString::new("a\0b").unwrap_err());
559 assert!(std::error::Error::source(&error).is_none());
560 assert_eq!(
561 error.to_string(),
562 "Invalid CString: nul byte found in provided data at position: 1"
563 );
564 }
565
566 #[test]
567 fn diagnostic_payloads_have_the_common_error_traits() {
568 fn error<T: std::error::Error + std::fmt::Debug + Clone + PartialEq>() {}
569 fn value<T: Copy + Eq + std::hash::Hash>() {}
570
571 error::<SelectionFailure>();
572 error::<LoadFailure>();
573 error::<LoadRefusal>();
574 error::<VersionTextDefect>();
575 value::<VersionTextDefect>();
576 error::<DiscoveryAddressFailure>();
577 error::<NativeFunction>();
578 error::<DiscoveryDefect>();
579 error::<ImageCodecKind>();
580 error::<ImageAxisKind>();
581 error::<AudioCountKind>();
582 error::<InputDefect>();
583 error::<FrameDefect>();
584 error::<LayoutDefect>();
585 error::<SdkResultDefect>();
586 error::<Capability>();
587 error::<CapabilityRefusal>();
588 error::<crate::CapabilityUnavailable>();
589 #[cfg(any(feature = "advanced", feature = "file-io"))]
590 error::<QueueLimit>();
591 error::<ResourceKind>();
592 error::<SelectionConflict>();
593 error::<LibraryKind>();
594 error::<ColorMetadataDefect>();
595 error::<FrameRateDefect>();
596 error::<VideoDimensionsDefect>();
597 error::<AudioLengthDefect>();
598 error::<PtzDefect>();
599 #[cfg(any(feature = "tokio", feature = "smol"))]
600 error::<SpawnFailure>();
601 error::<InitializationFailure>();
602 error::<AllocationFailure>();
603 error::<AllocationKind>();
604
605 value::<SdkResultDefect>();
606 value::<NativeFunction>();
607 value::<DiscoveryDefect>();
608 value::<ImageCodecKind>();
609 value::<ImageAxisKind>();
610 value::<AudioCountKind>();
611 value::<Capability>();
612 value::<CapabilityRefusal>();
613 value::<crate::CapabilityUnavailable>();
614 #[cfg(any(feature = "advanced", feature = "file-io"))]
615 value::<QueueLimit>();
616 value::<ResourceKind>();
617 value::<SelectionConflict>();
618 value::<LibraryKind>();
619 value::<ColorMetadataDefect>();
620 value::<FrameRateDefect>();
621 value::<VideoDimensionsDefect>();
622 value::<AudioLengthDefect>();
623 #[cfg(any(feature = "tokio", feature = "smol"))]
624 value::<SpawnFailure>();
625 value::<InitializationFailure>();
626 value::<AllocationFailure>();
627 value::<AllocationKind>();
628 }
629
630 #[test]
631 fn capability_errors_display_the_recorded_evidence() {
632 assert_eq!(
633 Capability::Runtime(RuntimeFeature::Routing).to_string(),
634 "source routing"
635 );
636 let required = RuntimeFeature::Planar444Video.minimum_version().unwrap();
637 for refusal in [
638 CapabilityRefusal::SymbolUnavailable(c"NDIlib_routing_create"),
639 CapabilityRefusal::BuildAbiUnavailable(c"NDIlib_routing_create_v2"),
640 CapabilityRefusal::WrongEdition(Some(c"NDIlib_routing_create_v2")),
641 CapabilityRefusal::WrongEdition(None),
642 CapabilityRefusal::RuntimeTooOld { required },
643 CapabilityRefusal::RuntimeVersionUnknown { required },
644 ] {
645 let error = Error::UnsupportedCapability {
646 capability: Capability::Runtime(RuntimeFeature::Routing),
647 refusal,
648 };
649 assert_eq!(
650 error.to_string(),
651 format!("NDI capability source routing is unavailable: {refusal}")
652 );
653 assert!(!error.to_string().ends_with(": "));
654 }
655 }
656
657 #[cfg(feature = "file-io")]
658 #[test]
659 fn file_family_errors_name_the_family_and_missing_entry_point() {
660 assert_eq!(
661 Capability::File(crate::file::FileFamily::Recording).to_string(),
662 "file recording"
663 );
664 let error = Error::UnsupportedCapability {
665 capability: Capability::File(crate::file::FileFamily::Recording),
666 refusal: CapabilityRefusal::SymbolUnavailable(c"NDIlib_file_recorder_rollover"),
667 };
668 assert_eq!(error.to_string(), "NDI capability file recording is unavailable: the selected library does not export a required function: NDIlib_file_recorder_rollover");
669 }
670
671 #[test]
672 fn a_refused_receiver_request_says_whether_the_receiver_is_listed() {
673 let listed = Error::ReceiverRequestNotAccepted { advertised: true }.to_string();
674 let unlisted = Error::ReceiverRequestNotAccepted { advertised: false }.to_string();
675 assert!(listed.ends_with("the receiver it lists does not accept this request"));
676 assert!(unlisted.contains("no receiver with this identifier"));
677 assert!(!listed.contains("capability") && !unlisted.contains("capability"));
678 }
679
680 #[test]
681 #[cfg(any(feature = "advanced", feature = "file-io"))]
682 fn a_full_queue_names_its_limit() {
683 for (limit, text) in [
684 (QueueLimit::Frames, "queued video frame limit reached"),
685 (QueueLimit::Bytes, "queued video byte limit reached"),
686 (QueueLimit::FileCommands, "File command queue is full"),
687 (
688 QueueLimit::FileFinishWaits,
689 "File finish-wait limit reached",
690 ),
691 (QueueLimit::FileProbes, "File probe queue is full"),
692 ] {
693 assert_eq!(
694 Error::QueueFull(limit).to_string(),
695 format!("Queue full: {text}")
696 );
697 }
698 }
699}
700
701#[cfg(test)]
702mod initialization_failure_tests {
703 use super::*;
704
705 #[test]
706 fn initialization_causes_preserve_their_diagnostics() {
707 for (cause, expected) in [
708 (
709 InitializationFailure::NotStarted,
710 "NDIlib_initialize returned false on a CPU the runtime reports as supported",
711 ),
712 (
713 InitializationFailure::HandleCountExhausted,
714 "NDI runtime reference count exhausted",
715 ),
716 ] {
717 assert_eq!(cause.to_string(), expected);
718 }
719 }
720
721 #[test]
722 fn utf8_errors_keep_the_offset_and_incomplete_sequence() {
723 let bytes = [b'a', 0xe2, 0x82];
724 let cause = std::str::from_utf8(std::hint::black_box(&bytes)).unwrap_err();
725 let error = Error::InvalidUtf8(cause);
726 assert!(
727 matches!(error, Error::InvalidUtf8(found) if found.valid_up_to() == 1 && found.error_len().is_none())
728 );
729 assert_eq!(
730 error.to_string(),
731 format!("Invalid UTF-8 string in data: {cause}")
732 );
733 }
734}
735
736// Preserve the sender capture diagnostic while exposing its typed SDK breach.
737fn sdk_result_prefix(cause: &SdkResultDefect) -> &'static str {
738 match cause {
739 SdkResultDefect::UnexpectedFrameType { .. } => "Failed to capture frame: ",
740 _ => "Unexpected NDI SDK result: ",
741 }
742}
743
744#[cfg(test)]
745mod full_diagnostic_tests {
746 use super::*;
747
748 #[test]
749 fn error_groups_preserve_their_complete_diagnostic_prefixes() {
750 for (error, expected) in [
751 (Error::InvalidFrame(FrameDefect::Layout(crate::LayoutDefect::AudioRate(0.into()))), "Invalid frame data: Invalid sample rate: 0"),
752 (Error::InvalidInput(InputDefect::RelativeLibraryPath), "Invalid input: an explicit NDI library path must be absolute"),
753 (Error::UnexpectedSdkResult(SdkResultDefect::NegativeCount {operation: crate::sys::table::for_test((), c"NDIlib_send_get_no_connections").function(),value:(-1).into()}), "Unexpected NDI SDK result: NDIlib_send_get_no_connections returned a negative count: -1"),
754 (Error::UnexpectedSdkResult(SdkResultDefect::UnexpectedFrameType {operation: crate::sys::table::for_test((), c"NDIlib_send_capture").function(),kind:17}), "Failed to capture frame: NDIlib_send_capture returned 17"),
755 (Error::ConnectionLost, "Failed to capture frame: the SDK returned an error frame: the connection was lost"),
756 (Error::InitializationFailed(InitializationFailure::NotStarted), "Failed to initialize the NDI runtime: NDIlib_initialize returned false on a CPU the runtime reports as supported"),
757 (Error::InitializationFailed(InitializationFailure::HandleCountExhausted), "Failed to initialize the NDI runtime: NDI runtime reference count exhausted"),
758 ] {
759 assert_eq!(error.to_string(), expected);
760 }
761 }
762}