1#![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
15const NDI_6_4: SdkVersion = SdkVersion {
19 major: 6,
20 minor: 4,
21 patch: 0,
22 build: 0,
23};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum SdkEdition {
36 Standard,
38 Advanced,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[non_exhaustive]
45pub enum SdkLinkage {
46 Shared,
48 Static,
50}
51
52#[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 pub fn major(self) -> u32 {
64 self.major
65 }
66 pub fn minor(self) -> u32 {
68 self.minor
69 }
70 pub fn patch(self) -> u32 {
72 self.patch
73 }
74 pub fn build(self) -> u32 {
76 self.build
77 }
78
79 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 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#[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 pub fn edition(&self) -> SdkEdition {
132 self.edition
133 }
134
135 pub fn linkage(&self) -> SdkLinkage {
137 self.linkage
138 }
139 pub fn library_path(&self) -> Option<&Path> {
143 self.library_path.as_deref()
144 }
145 pub fn raw_version(&self) -> &str {
147 &self.raw_version
148 }
149 pub fn version(&self) -> Option<SdkVersion> {
151 self.version
152 }
153}
154
155macro_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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228 #[non_exhaustive]
229 pub enum RuntimeFeature {
230 $(
231 $(#[$meta])*
232 $Variant,
233 )+
234 #[cfg(feature = "advanced")]
242 Passthrough(PassthroughPreset),
243 }
244
245 enum Index {
248 $($Variant,)+
249 }
250
251 $($($(
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 enum Slot {
266 Unit(usize),
268 #[cfg(feature = "advanced")]
270 Passthrough(PassthroughPreset),
271 }
272
273 impl RuntimeFeature {
274 pub(crate) const UNIT: [Self; [$(Index::$Variant),+].len()] = [$(Self::$Variant),+];
277
278 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 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 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 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 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 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 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 core Planar444Video as "planar 4:4:4 video" since NDI_6_4;
364 core ReceiveBest444 as "Best444 receiver mode" since NDI_6_4;
366 core ReceiveVideoOnly as "video-only receiver bandwidth" since NDI_6_4;
368 core ReceiveDelay as "receiver audio/video delay";
370 core ReceiverConnectionMetadata as "receiver connection metadata";
372 core ReceiverWebControl as "receiver web control";
374 core ConnectedSourceName as "connected source name";
376 core SenderMetadata as "sender metadata";
378 core SdkTimestamp as "SDK timestamp";
380 core InterleavedAudioConversion as "interleaved audio conversion";
382 core InterleavedAudioSend as "interleaved audio submission";
384 core VideoConversion as "V210/P216 conversion";
386 core Routing as "source routing";
388 core SenderAdvertising as "sender advertising" since NDI_6_4;
391 core ReceiverAdvertising as "receiver advertising" since NDI_6_4;
394 core RemoteReceiverControl as "remote receiver control" requires ReceiverAdvertising;
398 core SenderDiscovery as "sender discovery" since NDI_6_4;
401 core ReceiverDiscovery as "receiver discovery" since NDI_6_4;
405 advanced AdvancedFinderConfiguration as "Advanced finder configuration";
407 advanced AdvancedSenderConfiguration as "Advanced sender configuration";
409 advanced AdvancedReceiverConfiguration as "Advanced receiver configuration";
411 advanced AdvancedRouterConfiguration as "Advanced router configuration"
414 requires Routing;
415 advanced AdvancedSenderAdvertiserConfiguration as "Advanced sender advertiser configuration"
420 requires SenderAdvertising;
421 advanced AdvancedReceiverAdvertiserConfiguration as "Advanced receiver advertiser configuration"
426 requires ReceiverAdvertising;
427 advanced AdvancedSenderListenerConfiguration as "Advanced sender listener configuration"
431 requires SenderDiscovery;
432 advanced AdvancedReceiverListenerConfiguration as "Advanced receiver listener configuration"
436 requires ReceiverDiscovery;
437 advanced SourceMetadata as "source metadata";
439 advanced RouterConnectionMetadata as "router connection metadata";
441 advanced SenderTally as "sender tally override";
443 advanced EncoderGuidance as "encoder guidance";
446 advanced EncoderQualityPlanning as "encoder quality planning";
449 advanced KeyframeDemand as "keyframe demand";
452 advanced KeyframeRequest as "keyframe request";
454 advanced ScatterSend as "scatter sending";
456 advanced ReceiverStreamTier as "receiver stream tier";
458 advanced ReceiverStreamSelection as "receiver stream selection";
460 advanced ReceiveAllocators as "custom receive allocators";
462 advanced SendCompletion as "asynchronous send completion";
465 advanced AvSync as "AV synchronization";
467 advanced Genlock as "genlock";
469 advanced Kvm as "KVM control";
471}
472
473#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
478#[non_exhaustive]
479pub enum Capability {
480 #[error("{}", .0.name())]
482 Runtime(RuntimeFeature),
483 #[cfg(feature = "file-io")]
485 #[error("{}", .0.name())]
486 File(crate::file::FileFamily),
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
491#[non_exhaustive]
492pub enum CapabilityUnavailable {
493 #[error("the selected runtime's version is not recognized")]
495 RuntimeVersionUnknown,
496 #[error("the selected runtime is too old")]
498 RuntimeTooOld,
499 #[error("the selected library does not export a required function")]
501 SymbolUnavailable,
502 #[error("this build lacks the Advanced SDK declarations this capability needs")]
504 BuildAbiUnavailable,
505 #[error("the selected runtime is not an Advanced SDK runtime")]
507 WrongEdition,
508}
509
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
517#[error("{}", CapabilityRefusalDiagnostic(self))]
518#[non_exhaustive]
519pub enum CapabilityRefusal {
520 SymbolUnavailable(&'static CStr),
522 BuildAbiUnavailable(&'static CStr),
524 WrongEdition(Option<&'static CStr>),
526 RuntimeTooOld {
528 required: &'static SdkVersion,
530 },
531 RuntimeVersionUnknown {
533 required: &'static SdkVersion,
535 },
536}
537
538impl CapabilityRefusal {
539 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
577#[non_exhaustive]
578pub enum CapabilityStatus {
579 Available,
581 Unavailable(CapabilityRefusal),
583}
584
585impl CapabilityStatus {
586 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#[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 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 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 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 pub fn status(&self, feature: RuntimeFeature) -> CapabilityStatus {
719 CapabilityStatus::from_decision(self.decision(feature))
720 }
721
722 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 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 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 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}