Skip to main content

grafton_ndi/
capabilities.rs

1//! Facts about the selected native SDK, separate from hardware and license availability.
2
3#![warn(missing_docs)]
4
5use std::{
6    ffi::CStr,
7    fmt,
8    path::{Path, PathBuf},
9};
10
11#[cfg(feature = "advanced")]
12use crate::advanced::PassthroughPreset;
13use crate::sys::{advanced::ResolvedAdvancedApi, ResolvedApi};
14
15/// NDI 6.4.0: the first runtime with the planar 4:4:4 formats and newer
16/// receiver modes, and the first whose Discovery Server advertisers and
17/// listeners can be destroyed safely.
18const NDI_6_4: SdkVersion = SdkVersion {
19    major: 6,
20    minor: 4,
21    patch: 0,
22    build: 0,
23};
24
25/// The edition of a native SDK implementation.
26///
27/// On dynamically loaded targets, the selected library's exports decide its
28/// edition, regardless of its file name or the caller's request.
29/// On statically linked targets (iOS, tvOS and visionOS), it is the edition of
30/// the archive linked at build time: the Advanced archive when `NDI_SDK_DIR`
31/// holds one, otherwise the Standard archive. See the
32/// [Apple mobile setup](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/setup.md#apple-mobile-targets).
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum SdkEdition {
36    /// The standard NDI SDK.
37    Standard,
38    /// The NDI Advanced SDK. This does not assert a license entitlement.
39    Advanced,
40}
41
42/// How the native SDK implementation is supplied.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[non_exhaustive]
45pub enum SdkLinkage {
46    /// An explicitly loaded shared library, retained for the process lifetime.
47    Shared,
48    /// The SDK implementation is linked into the application.
49    Static,
50}
51
52/// A parsed SDK version, distinct from its build timestamp and raw version text.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct SdkVersion {
55    major: u32,
56    minor: u32,
57    patch: u32,
58    build: u32,
59}
60
61impl SdkVersion {
62    /// Major version.
63    pub fn major(self) -> u32 {
64        self.major
65    }
66    /// Minor version.
67    pub fn minor(self) -> u32 {
68        self.minor
69    }
70    /// Patch version.
71    pub fn patch(self) -> u32 {
72        self.patch
73    }
74    /// SDK build component, or zero for a three-component version.
75    pub fn build(self) -> u32 {
76        self.build
77    }
78
79    /// Parse the final token of the SDK's version text.
80    ///
81    /// Observed strings end in the version after a platform name and a build
82    /// date, so numbers elsewhere in the text are never mistaken for it.
83    pub(crate) fn parse(text: &str) -> Option<Self> {
84        let token = text.split_whitespace().last()?;
85        let mut components = token.split('.');
86        let parse = |text: &str| {
87            if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
88                None
89            } else {
90                text.parse().ok()
91            }
92        };
93        let version = Self {
94            major: parse(components.next()?)?,
95            minor: parse(components.next()?)?,
96            patch: parse(components.next()?)?,
97            build: components.next().map_or(Some(0), parse)?,
98        };
99        components.next().is_none().then_some(version)
100    }
101}
102
103impl fmt::Display for SdkVersion {
104    /// Formats all four components, for example `6.4.0.2`.
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        let Self {
107            major,
108            minor,
109            patch,
110            build,
111        } = self;
112        write!(f, "{major}.{minor}.{patch}.{build}")
113    }
114}
115
116/// Identity of the implementation actually selected, rather than just build headers.
117#[derive(Debug, Clone, PartialEq, Eq, Hash)]
118pub struct RuntimeInfo {
119    pub(crate) edition: SdkEdition,
120    pub(crate) linkage: SdkLinkage,
121    pub(crate) library_path: Option<PathBuf>,
122    pub(crate) raw_version: String,
123    pub(crate) version: Option<SdkVersion>,
124}
125
126impl RuntimeInfo {
127    /// The edition of the selected implementation; see [`SdkEdition`] for
128    /// how it is decided.
129    ///
130    /// This does not establish a license entitlement.
131    pub fn edition(&self) -> SdkEdition {
132        self.edition
133    }
134
135    /// Whether the implementation is shared or statically linked.
136    pub fn linkage(&self) -> SdkLinkage {
137        self.linkage
138    }
139    /// Canonical loaded file, with links resolved, for a shared implementation.
140    /// Uses the platform's ordinary path form; Windows extended syntax is kept
141    /// only when needed to express the same file.
142    pub fn library_path(&self) -> Option<&Path> {
143        self.library_path.as_deref()
144    }
145    /// Unmodified native version text, including any build timestamp.
146    pub fn raw_version(&self) -> &str {
147        &self.raw_version
148    }
149    /// Parsed final version token, when recognized.
150    pub fn version(&self) -> Option<SdkVersion> {
151        self.version
152    }
153}
154
155/// Define [`RuntimeFeature`] from one entry for each variant without a field.
156///
157/// The list below is the only place a capability is declared. Each entry
158/// states its documentation, its variant, whether it belongs to the `core` or
159/// the `advanced` SDK and the name it is reported under, then any of:
160///
161/// - `since`, the first runtime version it may be used with;
162/// - `requires`, the capabilities whose tables its operations also take, each
163///   listed before it. Once its own gate passes, the capability reports the
164///   status, and the evidence, of the first of them that is unavailable, so
165///   its operations are refused under the capability itself rather than under
166///   the one they reach later;
167/// - `ungated`, with the reason, for a core capability that every runtime
168///   provides.
169///
170/// A core capability is gated by its table in `optional_tables!`, by `since`
171/// or by `requires`. One with none of them would be reported available on
172/// every runtime, so it fails to compile unless it says `ungated`, and only
173/// such a one may (see `Api::missing`).
174///
175/// The enum, its `name`, `minimum_version`, `requirements` and `is_advanced`,
176/// [`RuntimeFeature::UNIT`] and the place [`Capabilities`] keeps each status
177/// are all generated from the list, so none of them can leave a capability
178/// out. The variant with a field, `Passthrough`, is written out here.
179macro_rules! runtime_features {
180    (@advanced core) => {
181        false
182    };
183    (@advanced advanced) => {
184        true
185    };
186    (@minimum) => {
187        None
188    };
189    (@minimum $minimum:ident) => {
190        Some(&$minimum)
191    };
192    (@ungated $edition:ident) => {
193        false
194    };
195    (@ungated core $why:literal) => {
196        true
197    };
198    (@ungated advanced $why:literal) => {
199        compile_error!("an Advanced capability is always gated by its table")
200    };
201    ($(
202        $(#[$meta:meta])*
203        $edition:ident $Variant:ident as $name:literal
204            $(since $minimum:ident)?
205            $(requires $($required:ident),+)?
206            $(ungated $why:literal)?;
207    )+) => {
208        /// A capability that this build or the selected runtime may lack.
209        ///
210        /// [`Capabilities::status`] reports each one in advance, and every operation
211        /// that needs one that is unavailable fails with
212        /// [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
213        /// naming it, before anything reaches the SDK.
214        ///
215        /// A core capability depends on the functions the runtime exports and, for
216        /// some, on its version: an older runtime would misread newer input values, or
217        /// cannot destroy an object safely. Every capability from
218        /// [`AdvancedFinderConfiguration`](Self::AdvancedFinderConfiguration) on
219        /// belongs to the Advanced SDK: it also needs an Advanced SDK runtime and a
220        /// build with the `advanced` feature whose SDK headers declare it. A
221        /// capability whose operations go on to use another one's functions, such
222        /// as [`AdvancedRouterConfiguration`](Self::AdvancedRouterConfiguration)
223        /// with [`Routing`](Self::Routing), is also unavailable whenever that one
224        /// is: once its own requirements are met, it reports that one's reason,
225        /// and its operations are refused with that one's evidence.
226        /// Availability says nothing about hardware or licenses.
227        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228        #[non_exhaustive]
229        pub enum RuntimeFeature {
230            $(
231                $(#[$meta])*
232                $Variant,
233            )+
234            /// Receiving compressed packets with this preset.
235            ///
236            /// A packet receiver is created as a receiver with Advanced JSON
237            /// configuration is, so this needs everything
238            /// [`AdvancedReceiverConfiguration`](Self::AdvancedReceiverConfiguration)
239            /// does, and also that this build's headers declare the receiver color
240            /// format that selects the preset.
241            #[cfg(feature = "advanced")]
242            Passthrough(PassthroughPreset),
243        }
244
245        /// The variants of [`RuntimeFeature`] without a field, numbered in
246        /// declaration order from zero.
247        enum Index {
248            $($Variant,)+
249        }
250
251        // A capability requires only capabilities listed before it, so no
252        // requirement is circular and `Capabilities::detect` finds each
253        // requirement's status already derived.
254        $($($(
255            const_assert!(
256                (Index::$required as usize) < (Index::$Variant as usize),
257                concat!(
258                    stringify!($Variant), " requires ", stringify!($required),
259                    ", which must be listed before it"
260                ),
261            );
262        )+)?)+
263
264        /// Where [`Capabilities`] finds a feature's status.
265        enum Slot {
266            /// At this index of the statuses it keeps.
267            Unit(usize),
268            /// Derived from the configured receiver's, for a passthrough preset.
269            #[cfg(feature = "advanced")]
270            Passthrough(PassthroughPreset),
271        }
272
273        impl RuntimeFeature {
274            /// Every variant without a field, in declaration order: the
275            /// capabilities whose statuses [`Capabilities`] keeps.
276            pub(crate) const UNIT: [Self; [$(Index::$Variant),+].len()] = [$(Self::$Variant),+];
277
278            /// Every capability, including variants with a preset.
279            pub(crate) fn all() -> impl Iterator<Item = Self> {
280                let features = Self::UNIT.into_iter();
281                #[cfg(feature = "advanced")]
282                let features = features.chain(PassthroughPreset::ALL.map(Self::Passthrough));
283                features
284            }
285
286            /// Where [`Capabilities`] finds the capability's status. The
287            /// variant at each index of [`Self::UNIT`] is kept at that index.
288            fn slot(self) -> Slot {
289                match self {
290                    $(Self::$Variant => Slot::Unit(Index::$Variant as usize),)+
291                    #[cfg(feature = "advanced")]
292                    Self::Passthrough(preset) => Slot::Passthrough(preset),
293                }
294            }
295
296            /// The one name the capability is reported under.
297            pub(crate) fn name(self) -> &'static str {
298                match self {
299                    $(Self::$Variant => $name,)+
300                    #[cfg(feature = "advanced")]
301                    Self::Passthrough(_) => "compressed passthrough preset",
302                }
303            }
304
305            /// The first runtime version the capability may be used with, when the
306            /// functions a runtime exports are not evidence enough.
307            ///
308            /// The 6.4 formats and receiver modes are enum values an older runtime
309            /// would misread. The advertiser and listener functions exist in older
310            /// runtimes, but the vendor's change log records crashes when destroying
311            /// those objects that were fixed in 6.3.2 and again in 6.4.0. An object
312            /// created with Advanced configuration is destroyed the same way, so its
313            /// capability requires the core one and reports that one's version gate.
314            pub(crate) const fn minimum_version(self) -> Option<&'static SdkVersion> {
315                match self {
316                    $(Self::$Variant => runtime_features!(@minimum $($minimum)?),)+
317                    #[cfg(feature = "advanced")]
318                    Self::Passthrough(_) => None,
319                }
320            }
321
322            /// The capabilities whose tables the capability's operations also
323            /// take, in the order they are checked. The capability is
324            /// unavailable whenever one of them is, and then reports the status
325            /// of the first one that is.
326            pub(crate) const fn requirements(self) -> &'static [Self] {
327                match self {
328                    $(Self::$Variant => &[$($(Self::$required),+)?],)+
329                    #[cfg(feature = "advanced")]
330                    Self::Passthrough(_) => &[],
331                }
332            }
333
334            /// Whether the capability is declared `ungated`: a core capability
335            /// without a table, a minimum version or a requirement, which every
336            /// runtime provides.
337            pub(crate) const fn is_ungated(self) -> bool {
338                match self {
339                    $(Self::$Variant => runtime_features!(@ungated $edition $($why)?),)+
340                    #[cfg(feature = "advanced")]
341                    Self::Passthrough(_) => false,
342                }
343            }
344
345            /// Whether the capability belongs to the Advanced SDK.
346            ///
347            /// Each such capability is gated by a table of Advanced entry points,
348            /// which states, with the build's declarations, what the capability
349            /// needs.
350            pub(crate) const fn is_advanced(self) -> bool {
351                match self {
352                    $(Self::$Variant => runtime_features!(@advanced $edition),)+
353                    #[cfg(feature = "advanced")]
354                    Self::Passthrough(_) => true,
355                }
356            }
357        }
358    };
359}
360
361runtime_features! {
362    /// Submitting and receiving the NDI 6.4 planar 4:4:4 formats.
363    core Planar444Video as "planar 4:4:4 video" since NDI_6_4;
364    /// The Best444 receiver color mode.
365    core ReceiveBest444 as "Best444 receiver mode" since NDI_6_4;
366    /// Video-only highest and lowest receiver bandwidth modes.
367    core ReceiveVideoOnly as "video-only receiver bandwidth" since NDI_6_4;
368    /// Independent native audio/video receiver delays.
369    core ReceiveDelay as "receiver audio/video delay";
370    /// Metadata a receiver replays to every new connection.
371    core ReceiverConnectionMetadata as "receiver connection metadata";
372    /// The connected source's web-control URL.
373    core ReceiverWebControl as "receiver web control";
374    /// Notifications of the connected source's actual name.
375    core ConnectedSourceName as "connected source name";
376    /// Metadata a sender captures from its connected receivers.
377    core SenderMetadata as "sender metadata";
378    /// The SDK current-timestamp operation.
379    core SdkTimestamp as "SDK timestamp";
380    /// Conversion between planar and interleaved audio.
381    core InterleavedAudioConversion as "interleaved audio conversion";
382    /// Direct submission of interleaved audio to a sender.
383    core InterleavedAudioSend as "interleaved audio submission";
384    /// Conversion between the V210 and P216 video layouts.
385    core VideoConversion as "V210/P216 conversion";
386    /// Source routing, including its create/destroy and query operations.
387    core Routing as "source routing";
388    /// Discovery Server sender registration and removal. Needs NDI 6.4.0 or
389    /// later: earlier runtimes can crash when an advertiser is destroyed.
390    core SenderAdvertising as "sender advertising" since NDI_6_4;
391    /// Discovery Server receiver registration and removal. Needs NDI 6.4.0 or
392    /// later: earlier runtimes can crash when an advertiser is destroyed.
393    core ReceiverAdvertising as "receiver advertising" since NDI_6_4;
394    /// Letting Discovery Server clients change an advertised receiver's source.
395    /// On Windows this requires an Advanced runtime, whose connection lock
396    /// also protects controls from SDK-internal connection changes.
397    core RemoteReceiverControl as "remote receiver control" requires ReceiverAdvertising;
398    /// Sender snapshots, subscriptions and owned event batches. Needs NDI
399    /// 6.4.0 or later: earlier runtimes can crash when a listener is destroyed.
400    core SenderDiscovery as "sender discovery" since NDI_6_4;
401    /// Receiver snapshots, subscriptions, event batches and connection control.
402    /// Needs NDI 6.4.0 or later: earlier runtimes can crash when a listener is
403    /// destroyed.
404    core ReceiverDiscovery as "receiver discovery" since NDI_6_4;
405    /// Creating a finder with Advanced JSON configuration.
406    advanced AdvancedFinderConfiguration as "Advanced finder configuration";
407    /// Creating a sender with Advanced JSON configuration.
408    advanced AdvancedSenderConfiguration as "Advanced sender configuration";
409    /// Creating a receiver with Advanced JSON configuration.
410    advanced AdvancedReceiverConfiguration as "Advanced receiver configuration";
411    /// Creating a router with Advanced JSON configuration. Needs
412    /// [`Routing`](Self::Routing), whose functions the router goes on to use.
413    advanced AdvancedRouterConfiguration as "Advanced router configuration"
414        requires Routing;
415    /// Creating a Discovery Server sender advertiser with Advanced JSON
416    /// configuration. Needs [`SenderAdvertising`](Self::SenderAdvertising),
417    /// whose functions the advertiser goes on to use, and so NDI 6.4.0 or
418    /// later.
419    advanced AdvancedSenderAdvertiserConfiguration as "Advanced sender advertiser configuration"
420        requires SenderAdvertising;
421    /// Creating a Discovery Server receiver advertiser with Advanced JSON
422    /// configuration. Needs
423    /// [`ReceiverAdvertising`](Self::ReceiverAdvertising), whose functions
424    /// the advertiser goes on to use, and so NDI 6.4.0 or later.
425    advanced AdvancedReceiverAdvertiserConfiguration as "Advanced receiver advertiser configuration"
426        requires ReceiverAdvertising;
427    /// Creating a Discovery Server sender listener with Advanced JSON
428    /// configuration. Needs [`SenderDiscovery`](Self::SenderDiscovery), whose
429    /// functions the listener goes on to use, and so NDI 6.4.0 or later.
430    advanced AdvancedSenderListenerConfiguration as "Advanced sender listener configuration"
431        requires SenderDiscovery;
432    /// Creating a Discovery Server receiver listener with Advanced JSON
433    /// configuration. Needs [`ReceiverDiscovery`](Self::ReceiverDiscovery),
434    /// whose functions the listener goes on to use, and so NDI 6.4.0 or later.
435    advanced AdvancedReceiverListenerConfiguration as "Advanced receiver listener configuration"
436        requires ReceiverDiscovery;
437    /// Source snapshots that carry each source's metadata.
438    advanced SourceMetadata as "source metadata";
439    /// Metadata a router replays to each new connection.
440    advanced RouterConnectionMetadata as "router connection metadata";
441    /// A sender's own contribution to its tally state.
442    advanced SenderTally as "sender tally override";
443    /// The target frame size, bit rate and quality for an encoder feeding a
444    /// sender.
445    advanced EncoderGuidance as "encoder guidance";
446    /// Encoder quality together with the formats the connected receivers
447    /// accept.
448    advanced EncoderQualityPlanning as "encoder quality planning";
449    /// Whether the receivers connected to a sender need a keyframe, and
450    /// waiting for one to ask for it.
451    advanced KeyframeDemand as "keyframe demand";
452    /// A receiver's request for a keyframe from its source.
453    advanced KeyframeRequest as "keyframe request";
454    /// Sending compressed frames held in several blocks.
455    advanced ScatterSend as "scatter sending";
456    /// A receiver's choice between its source's program and preview streams.
457    advanced ReceiverStreamTier as "receiver stream tier";
458    /// A receiver's choice of which of its source's streams it receives.
459    advanced ReceiverStreamSelection as "receiver stream selection";
460    /// Application-supplied memory for the frames a receiver delivers.
461    advanced ReceiveAllocators as "custom receive allocators";
462    /// Notification that the SDK has finished with an asynchronously sent
463    /// video frame.
464    advanced SendCompletion as "asynchronous send completion";
465    /// Matching a receiver's audio to its video timestamps.
466    advanced AvSync as "AV synchronization";
467    /// Clocks locked to a reference source.
468    advanced Genlock as "genlock";
469    /// Keyboard, mouse, touch and clipboard control of a source.
470    advanced Kvm as "KVM control";
471}
472
473/// A runtime capability or a family of operations from the separate File library.
474///
475/// [`crate::Error::UnsupportedCapability`] uses this value to identify the
476/// unavailable operation group while retaining its [`CapabilityRefusal`].
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
478#[non_exhaustive]
479pub enum Capability {
480    /// An operation group provided by the selected NDI runtime.
481    #[error("{}", .0.name())]
482    Runtime(RuntimeFeature),
483    /// An operation family provided by the separate File library.
484    #[cfg(feature = "file-io")]
485    #[error("{}", .0.name())]
486    File(crate::file::FileFamily),
487}
488
489/// Why a capability cannot safely be used in this process.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
491#[non_exhaustive]
492pub enum CapabilityUnavailable {
493    /// The SDK version text is unrecognized, so new enum semantics cannot be assumed.
494    #[error("the selected runtime's version is not recognized")]
495    RuntimeVersionUnknown,
496    /// The selected runtime predates this capability.
497    #[error("the selected runtime is too old")]
498    RuntimeTooOld,
499    /// At least one required native function is absent.
500    #[error("the selected library does not export a required function")]
501    SymbolUnavailable,
502    /// This build lacks the locally generated ABI required by the optional feature.
503    #[error("this build lacks the Advanced SDK declarations this capability needs")]
504    BuildAbiUnavailable,
505    /// The selected native SDK edition does not implement this API family.
506    #[error("the selected runtime is not an Advanced SDK runtime")]
507    WrongEdition,
508}
509
510/// The evidence that prevents a capability from being used.
511///
512/// Detection records this value once. Capability queries and operation errors
513/// carry that same value, including when another capability requires it.
514/// Required versions borrow immutable registry values so this evidence stays
515/// small and allocation-free on both 32-bit and 64-bit targets.
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
517#[error("{}", CapabilityRefusalDiagnostic(self))]
518#[non_exhaustive]
519pub enum CapabilityRefusal {
520    /// The selected library does not export this required entry point.
521    SymbolUnavailable(&'static CStr),
522    /// This build's SDK declarations do not contain this entry point or constant.
523    BuildAbiUnavailable(&'static CStr),
524    /// The runtime is not Advanced, optionally naming an entry point it lacks.
525    WrongEdition(Option<&'static CStr>),
526    /// The runtime predates the required semantic version.
527    RuntimeTooOld {
528        /// The first version that may safely implement this capability.
529        required: &'static SdkVersion,
530    },
531    /// The runtime version cannot establish the required semantics.
532    RuntimeVersionUnknown {
533        /// The first version that may safely implement this capability.
534        required: &'static SdkVersion,
535    },
536}
537
538impl CapabilityRefusal {
539    /// The category of this refusal, without discarding its typed evidence.
540    pub const fn reason(self) -> CapabilityUnavailable {
541        match self {
542            Self::SymbolUnavailable(_) => CapabilityUnavailable::SymbolUnavailable,
543            Self::BuildAbiUnavailable(_) => CapabilityUnavailable::BuildAbiUnavailable,
544            Self::WrongEdition(_) => CapabilityUnavailable::WrongEdition,
545            Self::RuntimeTooOld { .. } => CapabilityUnavailable::RuntimeTooOld,
546            Self::RuntimeVersionUnknown { .. } => CapabilityUnavailable::RuntimeVersionUnknown,
547        }
548    }
549}
550
551struct CapabilityRefusalDiagnostic<'a>(&'a CapabilityRefusal);
552
553impl fmt::Display for CapabilityRefusalDiagnostic<'_> {
554    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555        write!(f, "{}", self.0.reason())?;
556        match self.0 {
557            CapabilityRefusal::SymbolUnavailable(symbol) => {
558                write!(f, ": {}", symbol.to_string_lossy())
559            }
560            CapabilityRefusal::BuildAbiUnavailable(symbol) => {
561                write!(f, ": it does not declare {}", symbol.to_string_lossy())
562            }
563            CapabilityRefusal::WrongEdition(Some(symbol)) => {
564                write!(f, ": it does not export {}", symbol.to_string_lossy())
565            }
566            CapabilityRefusal::WrongEdition(None) => Ok(()),
567            CapabilityRefusal::RuntimeTooOld { required }
568            | CapabilityRefusal::RuntimeVersionUnknown { required } => {
569                write!(f, ": it needs NDI {required} or later")
570            }
571        }
572    }
573}
574
575/// Availability established from the selected implementation.
576#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
577#[non_exhaustive]
578pub enum CapabilityStatus {
579    /// The wrapper has the required ABI/semantic evidence. Hardware and licenses are separate.
580    Available,
581    /// The operation must be rejected before calling the SDK, for this recorded evidence.
582    Unavailable(CapabilityRefusal),
583}
584
585impl CapabilityStatus {
586    /// The refusal category, when the capability is unavailable.
587    pub const fn reason(self) -> Option<CapabilityUnavailable> {
588        match self {
589            Self::Available => None,
590            Self::Unavailable(refusal) => Some(refusal.reason()),
591        }
592    }
593
594    fn from_decision(decision: std::result::Result<(), CapabilityRefusal>) -> Self {
595        match decision {
596            Ok(()) => Self::Available,
597            Err(refusal) => Self::Unavailable(refusal),
598        }
599    }
600}
601
602/// What the selected implementation, together with this build, provides:
603/// one recorded decision for every [`RuntimeFeature`].
604#[derive(Clone, PartialEq, Eq, Hash)]
605pub struct Capabilities {
606    native_receiver_connection_exclusion: bool,
607    decisions: [std::result::Result<(), CapabilityRefusal>; RuntimeFeature::UNIT.len()],
608    #[cfg(feature = "advanced")]
609    presets:
610        [std::result::Result<crate::sys::bindings::NDIlib_recv_color_format_e, CapabilityRefusal>;
611            PassthroughPreset::ALL.len()],
612}
613
614impl fmt::Debug for Capabilities {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        f.debug_map()
617            .entries(RuntimeFeature::all().map(|feature| (feature, self.status(feature))))
618            .finish()
619    }
620}
621
622impl Capabilities {
623    /// Decide each capability once, preserving its first refusal and evidence.
624    pub(crate) fn detect(
625        api: &ResolvedApi,
626        advanced: &ResolvedAdvancedApi,
627        version: Option<SdkVersion>,
628        edition: SdkEdition,
629    ) -> Self {
630        Self::detect_on(api, advanced, version, edition, cfg!(windows))
631    }
632
633    pub(crate) fn detect_on(
634        api: &ResolvedApi,
635        advanced: &ResolvedAdvancedApi,
636        version: Option<SdkVersion>,
637        edition: SdkEdition,
638        windows: bool,
639    ) -> Self {
640        let native_receiver_connection_exclusion = !windows || edition == SdkEdition::Advanced;
641        let versioned = |feature: RuntimeFeature| match (feature.minimum_version(), version) {
642            (None, _) => Ok(()),
643            (Some(required), Some(version)) if version >= *required => Ok(()),
644            (Some(required), Some(_)) => Err(CapabilityRefusal::RuntimeTooOld { required }),
645            (Some(required), None) => Err(CapabilityRefusal::RuntimeVersionUnknown { required }),
646        };
647        let own = |feature: RuntimeFeature| {
648            if feature.is_ungated() {
649                return Ok(());
650            }
651            if !feature.is_advanced() {
652                return api.missing(feature).map_or_else(|| versioned(feature), Err);
653            }
654            ResolvedAdvancedApi::declarations(feature)?;
655            let missing = advanced.missing(feature);
656            if edition != SdkEdition::Advanced {
657                return Err(CapabilityRefusal::WrongEdition(missing.and_then(
658                    |refusal| match refusal {
659                        CapabilityRefusal::SymbolUnavailable(symbol) => Some(symbol),
660                        _ => None,
661                    },
662                )));
663            }
664            missing.map_or_else(|| versioned(feature), Err)
665        };
666        let mut capabilities = Self {
667            native_receiver_connection_exclusion,
668            decisions: [Ok(()); RuntimeFeature::UNIT.len()],
669            #[cfg(feature = "advanced")]
670            presets: [Ok(0); PassthroughPreset::ALL.len()],
671        };
672        for (index, feature) in RuntimeFeature::UNIT.into_iter().enumerate() {
673            capabilities.decisions[index] = own(feature).and_then(|()| {
674                feature
675                    .requirements()
676                    .iter()
677                    .try_for_each(|&required| capabilities.decision(required))?;
678                if feature == RuntimeFeature::RemoteReceiverControl
679                    && !native_receiver_connection_exclusion
680                {
681                    return Err(CapabilityRefusal::WrongEdition(None));
682                }
683                Ok(())
684            });
685        }
686        #[cfg(feature = "advanced")]
687        {
688            // A preset first needs its own constant, then exactly the configured
689            // receiver's decision. Its usable format is retained beside it.
690            let receiver = capabilities.decision(RuntimeFeature::AdvancedReceiverConfiguration);
691            capabilities.presets = PassthroughPreset::ALL.map(|preset| {
692                crate::sys::advanced::passthrough_format(preset)
693                    .map_err(CapabilityRefusal::BuildAbiUnavailable)
694                    .and_then(|format| receiver.map(|()| format))
695            });
696        }
697        capabilities
698    }
699
700    /// Whether the runtime excludes connection replacement inside its controls.
701    /// This basis is independent of advertising's version and export gates.
702    pub(crate) fn has_native_receiver_connection_exclusion(&self) -> bool {
703        self.native_receiver_connection_exclusion
704    }
705
706    pub(crate) fn decision(
707        &self,
708        feature: RuntimeFeature,
709    ) -> std::result::Result<(), CapabilityRefusal> {
710        match feature.slot() {
711            Slot::Unit(index) => self.decisions[index],
712            #[cfg(feature = "advanced")]
713            Slot::Passthrough(preset) => self.presets[preset.index()].map(|_| ()),
714        }
715    }
716
717    /// Query a capability without changing native state.
718    pub fn status(&self, feature: RuntimeFeature) -> CapabilityStatus {
719        CapabilityStatus::from_decision(self.decision(feature))
720    }
721
722    /// Whether the wrapper has enough evidence to attempt the operation.
723    pub fn supports(&self, feature: RuntimeFeature) -> bool {
724        self.decision(feature).is_ok()
725    }
726
727    #[cfg(feature = "advanced")]
728    pub(crate) fn passthrough_format(
729        &self,
730        preset: PassthroughPreset,
731    ) -> std::result::Result<crate::sys::bindings::NDIlib_recv_color_format_e, CapabilityRefusal>
732    {
733        self.presets[preset.index()]
734    }
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740    use crate::{
741        sys::{Api, Evidence, Gates, Resolved, Table},
742        Error,
743    };
744
745    struct Fixture {
746        gates: Gates,
747    }
748
749    impl Fixture {
750        fn new(
751            exported: impl Fn(&str) -> bool,
752            version: Option<&str>,
753            edition: SdkEdition,
754        ) -> Self {
755            let resolver = crate::sys::table::ExportsWhere(exported);
756            let version = version.map(|text| SdkVersion::parse(text).unwrap());
757            Self {
758                gates: Resolved::load(&resolver).unwrap().seal(version, edition).1,
759            }
760        }
761
762        fn evidence(&self) -> Evidence<'_> {
763            self.gates.evidence()
764        }
765    }
766
767    fn refusal<T>(
768        result: crate::Result<T>,
769    ) -> std::result::Result<(), (RuntimeFeature, CapabilityRefusal)> {
770        match result {
771            Ok(_) => Ok(()),
772            Err(Error::UnsupportedCapability {
773                capability: Capability::Runtime(feature),
774                refusal,
775            }) => Err((feature, refusal)),
776            Err(other) => panic!("unexpected error: {other}"),
777        }
778    }
779
780    #[test]
781    fn parses_final_version_not_build_time() {
782        let v = SdkVersion::parse("NDI SDK LINUX 10:14:14 Nov 6 2026 6.4.0.2").unwrap();
783        assert_eq!((v.major(), v.minor(), v.patch(), v.build()), (6, 4, 0, 2));
784        assert_eq!(v.to_string(), "6.4.0.2");
785        for text in [
786            "",
787            "NDI 6.4",
788            "NDI 2026-11-06",
789            "NDI 6.4.0.2 trailing",
790            "6..4.0",
791            "6.4.0.-1",
792        ] {
793            assert!(SdkVersion::parse(text).is_none(), "{text}");
794        }
795    }
796
797    #[test]
798    fn version_parsing_preserves_components_without_allocating() {
799        let (version, allocations) = crate::test_alloc::allocation_count(|| {
800            SdkVersion::parse("NDI SDK TEST 4294967295.65536.4294967295.0")
801        });
802        assert_eq!(allocations, 0);
803        let version = version.unwrap();
804        assert_eq!(
805            (
806                version.major(),
807                version.minor(),
808                version.patch(),
809                version.build()
810            ),
811            (u32::MAX, 65536, u32::MAX, 0)
812        );
813        for text in ["1.2.3.4.5", "4294967296.2.3", "1.2.3."] {
814            assert!(SdkVersion::parse(text).is_none());
815        }
816    }
817
818    #[test]
819    fn every_feature_is_listed_once_under_its_own_name() {
820        use std::collections::HashSet;
821        let features: Vec<_> = RuntimeFeature::all().collect();
822        assert_eq!(
823            features.iter().copied().collect::<HashSet<_>>().len(),
824            features.len()
825        );
826        assert_eq!(
827            RuntimeFeature::UNIT
828                .map(RuntimeFeature::name)
829                .into_iter()
830                .collect::<HashSet<_>>()
831                .len(),
832            RuntimeFeature::UNIT.len()
833        );
834        for (index, feature) in RuntimeFeature::UNIT.into_iter().enumerate() {
835            assert!(matches!(feature.slot(), Slot::Unit(at) if at == index));
836        }
837        #[cfg(feature = "advanced")]
838        for (index, preset) in PassthroughPreset::ALL.into_iter().enumerate() {
839            assert_eq!(preset.index(), index);
840            assert_eq!(
841                RuntimeFeature::Passthrough(preset).name(),
842                "compressed passthrough preset"
843            );
844        }
845    }
846
847    #[test]
848    fn capabilities_debug_lists_every_feature_and_its_status() {
849        let fixture = Fixture::new(|_| true, Some("6.4.0.2"), SdkEdition::Advanced);
850        let capabilities = fixture.gates.capabilities();
851        let diagnostic = format!("{capabilities:?}");
852        for feature in RuntimeFeature::all() {
853            let expected = format!("{feature:?}: {:?}", capabilities.status(feature));
854            assert!(diagnostic.contains(&expected), "{diagnostic}");
855        }
856        assert_eq!(
857            CapabilityRefusal::BuildAbiUnavailable(c"NDIlib_recv_create_v4").to_string(),
858            "this build lacks the Advanced SDK declarations this capability needs: it does not declare NDIlib_recv_create_v4"
859        );
860    }
861
862    #[test]
863    fn every_recorded_refusal_is_the_gate_error_and_display_evidence() {
864        for (version, edition) in [
865            (Some("6.4.0.2"), SdkEdition::Advanced),
866            (Some("6.4.0.2"), SdkEdition::Standard),
867            (Some("6.3.2.0"), SdkEdition::Advanced),
868            (None, SdkEdition::Advanced),
869        ] {
870            // Complete exports, no optional exports, and one absent symbol at
871            // a time exercise each family and both first-refusal orderings.
872            let symbols: Vec<_> = Api::GATES
873                .iter()
874                .flat_map(|(_, names, _)| names.iter().copied())
875                .collect();
876            let symbols: Vec<_> = symbols
877                .into_iter()
878                .chain(
879                    crate::sys::advanced::GATES
880                        .iter()
881                        .flat_map(|(_, names, _)| names.iter().copied()),
882                )
883                .collect();
884            for missing in std::iter::once(None).chain(symbols.into_iter().map(Some)) {
885                let fixture = Fixture::new(
886                    |name| missing.is_none_or(|symbol| symbol.to_bytes() != name.as_bytes()),
887                    version,
888                    edition,
889                );
890                let evidence = fixture.evidence();
891                for feature in RuntimeFeature::all() {
892                    let expected = fixture
893                        .gates
894                        .capabilities()
895                        .decision(feature)
896                        .map_err(|refusal| (feature, refusal));
897                    assert_eq!(
898                        refusal(evidence.require(feature)),
899                        expected,
900                        "{feature:?} {version:?} {edition:?} {missing:?}"
901                    );
902                    assert_eq!(
903                        fixture.gates.capabilities().status(feature),
904                        CapabilityStatus::from_decision(expected.map_err(|(_, refusal)| refusal))
905                    );
906                    if let Err((_, refusal)) = expected {
907                        let error = Error::UnsupportedCapability {
908                            capability: Capability::Runtime(feature),
909                            refusal,
910                        };
911                        assert_eq!(
912                            error.to_string(),
913                            format!(
914                                "NDI capability {} is unavailable: {refusal}",
915                                feature.name()
916                            )
917                        );
918                    }
919                }
920                for &(feature, _, gate) in Api::GATES {
921                    assert_eq!(
922                        refusal(gate(evidence)),
923                        refusal(evidence.require(feature)),
924                        "{feature:?}"
925                    );
926                }
927                for &(feature, _, gate) in crate::sys::advanced::GATES {
928                    assert_eq!(
929                        refusal(gate(evidence)),
930                        refusal(evidence.require(feature)),
931                        "{feature:?}"
932                    );
933                }
934                assert_eq!(
935                    refusal(crate::sys::Planar444Video::within(evidence)),
936                    refusal(evidence.require(RuntimeFeature::Planar444Video))
937                );
938                assert_eq!(
939                    refusal(crate::sys::ReceiveBest444::within(evidence)),
940                    refusal(evidence.require(RuntimeFeature::ReceiveBest444))
941                );
942                assert_eq!(
943                    refusal(crate::sys::ReceiveVideoOnly::within(evidence)),
944                    refusal(evidence.require(RuntimeFeature::ReceiveVideoOnly))
945                );
946                #[cfg(feature = "advanced")]
947                for preset in PassthroughPreset::ALL {
948                    assert_eq!(
949                        refusal(evidence.passthrough_format(preset)),
950                        refusal(evidence.require(RuntimeFeature::Passthrough(preset)))
951                    );
952                }
953            }
954        }
955    }
956
957    #[test]
958    fn discovery_tables_are_refused_where_exported_before_6_4() {
959        let old = Fixture::new(|_| true, Some("6.3.2.0"), SdkEdition::Standard);
960        let current = Fixture::new(|_| true, Some("6.4.0.2"), SdkEdition::Standard);
961        let mut checked = 0;
962        for &(feature, _, gate) in Api::GATES {
963            if matches!(
964                feature,
965                RuntimeFeature::SenderAdvertising
966                    | RuntimeFeature::ReceiverAdvertising
967                    | RuntimeFeature::SenderDiscovery
968                    | RuntimeFeature::ReceiverDiscovery
969            ) {
970                checked += 1;
971                let expected = Err((
972                    feature,
973                    CapabilityRefusal::RuntimeTooOld { required: &NDI_6_4 },
974                ));
975                assert_eq!(refusal(gate(old.evidence())), expected);
976                assert_eq!(refusal(old.evidence().require(feature)), expected);
977                assert_eq!(refusal(gate(current.evidence())), Ok(()));
978                assert_eq!(refusal(current.evidence().require(feature)), Ok(()));
979            }
980        }
981        assert_eq!(checked, 4);
982    }
983
984    #[test]
985    fn core_gates_record_symbols_before_versions_and_copy_required_evidence() {
986        let old = Fixture::new(|_| true, Some("6.3.2.0"), SdkEdition::Standard);
987        let unknown = Fixture::new(|_| true, None, SdkEdition::Standard);
988        let current = Fixture::new(|_| true, Some("6.4.0.0"), SdkEdition::Standard);
989        for feature in RuntimeFeature::UNIT
990            .into_iter()
991            .filter(|feature| feature.minimum_version().is_some())
992        {
993            assert_eq!(
994                old.gates.capabilities().decision(feature),
995                Err(CapabilityRefusal::RuntimeTooOld { required: &NDI_6_4 })
996            );
997            assert_eq!(
998                unknown.gates.capabilities().decision(feature),
999                Err(CapabilityRefusal::RuntimeVersionUnknown { required: &NDI_6_4 })
1000            );
1001            assert!(current.gates.capabilities().supports(feature));
1002        }
1003        for &(feature, symbols, _) in Api::GATES {
1004            let missing = symbols[0];
1005            let fixture = Fixture::new(
1006                |name| name.as_bytes() != missing.to_bytes(),
1007                Some("6.3.2.0"),
1008                SdkEdition::Standard,
1009            );
1010            assert_eq!(
1011                fixture.gates.capabilities().decision(feature),
1012                Err(CapabilityRefusal::SymbolUnavailable(missing))
1013            );
1014        }
1015        for feature in [
1016            RuntimeFeature::ReceiverWebControl,
1017            RuntimeFeature::ConnectedSourceName,
1018        ] {
1019            let fixture = Fixture::new(
1020                |name| name != "NDIlib_recv_free_string",
1021                Some("6.4.0.2"),
1022                SdkEdition::Standard,
1023            );
1024            assert_eq!(
1025                fixture.gates.capabilities().decision(feature),
1026                Err(CapabilityRefusal::SymbolUnavailable(
1027                    c"NDIlib_recv_free_string"
1028                ))
1029            );
1030        }
1031    }
1032
1033    #[test]
1034    fn advanced_refusal_precedence_and_requirements_preserve_exact_evidence() {
1035        for &(feature, symbols, _) in crate::sys::advanced::GATES {
1036            let missing = symbols[0];
1037            for edition in [SdkEdition::Standard, SdkEdition::Advanced] {
1038                let fixture = Fixture::new(
1039                    |name| name.as_bytes() != missing.to_bytes(),
1040                    Some("6.4.0.2"),
1041                    edition,
1042                );
1043                let result = fixture.gates.capabilities().decision(feature);
1044                if ResolvedAdvancedApi::declarations(feature).is_ok() {
1045                    assert_eq!(
1046                        result,
1047                        Err(if edition == SdkEdition::Standard {
1048                            CapabilityRefusal::WrongEdition(Some(missing))
1049                        } else {
1050                            CapabilityRefusal::SymbolUnavailable(missing)
1051                        })
1052                    );
1053                } else {
1054                    assert!(
1055                        matches!(result, Err(CapabilityRefusal::BuildAbiUnavailable(symbol)) if symbols.contains(&symbol))
1056                    );
1057                }
1058            }
1059            for &required in feature.requirements() {
1060                let fixture = Fixture::new(
1061                    |name| !name.starts_with("NDIlib_routing_") || name.ends_with("_v2"),
1062                    Some("6.3.2.0"),
1063                    SdkEdition::Advanced,
1064                );
1065                if ResolvedAdvancedApi::declarations(feature).is_ok() {
1066                    assert_eq!(
1067                        fixture.gates.capabilities().decision(feature),
1068                        fixture.gates.capabilities().decision(required)
1069                    );
1070                }
1071
1072                // Both fail: the capability's own missing symbol must win
1073                // over a required family's symbol or version refusal.
1074                let both_refused = Fixture::new(
1075                    |name| {
1076                        name.as_bytes() != missing.to_bytes()
1077                            && (!name.starts_with("NDIlib_routing_") || name.ends_with("_v2"))
1078                    },
1079                    Some("6.1.1.0"),
1080                    SdkEdition::Advanced,
1081                );
1082                assert!(both_refused
1083                    .gates
1084                    .capabilities()
1085                    .decision(required)
1086                    .is_err());
1087                if ResolvedAdvancedApi::declarations(feature).is_ok() {
1088                    assert_eq!(
1089                        refusal(both_refused.evidence().require(feature)),
1090                        Err((feature, CapabilityRefusal::SymbolUnavailable(missing)))
1091                    );
1092                }
1093            }
1094        }
1095        #[cfg(feature = "advanced")]
1096        for preset in PassthroughPreset::ALL {
1097            for edition in [SdkEdition::Standard, SdkEdition::Advanced] {
1098                let fixture = Fixture::new(
1099                    |name| name != "NDIlib_recv_create_v4",
1100                    Some("6.4.0.2"),
1101                    edition,
1102                );
1103                let expected = crate::sys::advanced::passthrough_format(preset)
1104                    .map_err(CapabilityRefusal::BuildAbiUnavailable)
1105                    .and_then(|_| {
1106                        fixture
1107                            .gates
1108                            .capabilities()
1109                            .decision(RuntimeFeature::AdvancedReceiverConfiguration)
1110                    });
1111                assert_eq!(
1112                    fixture
1113                        .gates
1114                        .capabilities()
1115                        .decision(RuntimeFeature::Passthrough(preset)),
1116                    expected
1117                );
1118            }
1119        }
1120    }
1121
1122    #[test]
1123    fn undeclared_advanced_families_name_their_missing_declaration() {
1124        let fixture = Fixture::new(|_| true, Some("6.4.0.2"), SdkEdition::Advanced);
1125        assert_eq!(crate::sys::advanced::GATES.len(), 23);
1126        for &(feature, symbols, _) in crate::sys::advanced::GATES {
1127            if let Err(refusal) = ResolvedAdvancedApi::declarations(feature) {
1128                assert_eq!(fixture.gates.capabilities().decision(feature), Err(refusal));
1129                assert!(
1130                    matches!(refusal, CapabilityRefusal::BuildAbiUnavailable(symbol) if symbols.contains(&symbol))
1131                );
1132                #[cfg(not(feature = "advanced"))]
1133                assert_eq!(refusal, CapabilityRefusal::BuildAbiUnavailable(symbols[0]));
1134            }
1135        }
1136    }
1137
1138    #[test]
1139    fn capability_status_and_every_gate_allocate_nothing() {
1140        // Build the fixture and feature list before tracking. Exercise real
1141        // refusal paths, including declarations, edition, symbols and versions,
1142        // rather than only constructing the public refusal enum.
1143        let features: Vec<_> = RuntimeFeature::all().collect();
1144        let mut total_refused = 0;
1145        for (version, edition) in [
1146            (Some("6.4.0.2"), SdkEdition::Advanced),
1147            (Some("6.4.0.2"), SdkEdition::Standard),
1148            (Some("6.1.1.0"), SdkEdition::Advanced),
1149            (None, SdkEdition::Advanced),
1150        ] {
1151            for missing in [
1152                None,
1153                Some("NDIlib_routing_create"),
1154                Some("NDIlib_recv_create_v4"),
1155            ] {
1156                let fixture = Fixture::new(|name| Some(name) != missing, version, edition);
1157                let (refused, allocations) = crate::test_alloc::allocation_count(|| {
1158                    let evidence = fixture.evidence();
1159                    let mut refused = 0;
1160                    for &feature in &features {
1161                        refused += usize::from(evidence.require(feature).is_err());
1162                        let _ = fixture.gates.capabilities().status(feature);
1163                    }
1164                    for &(_, _, gate) in Api::GATES {
1165                        let _ = gate(evidence);
1166                    }
1167                    let _ = crate::sys::Planar444Video::within(evidence);
1168                    let _ = crate::sys::ReceiveBest444::within(evidence);
1169                    let _ = crate::sys::ReceiveVideoOnly::within(evidence);
1170                    for &(_, _, gate) in crate::sys::advanced::GATES {
1171                        let _ = gate(evidence);
1172                    }
1173                    #[cfg(feature = "advanced")]
1174                    for preset in PassthroughPreset::ALL {
1175                        let _ = evidence.passthrough_format(preset);
1176                    }
1177                    refused
1178                });
1179                assert_eq!(allocations, 0, "{version:?} {edition:?} {missing:?}");
1180                total_refused += refused;
1181            }
1182        }
1183        assert!(total_refused > 0);
1184    }
1185}