1#[cfg(test)]
4use std::cell::Cell;
5use std::marker::PhantomData;
6#[cfg(any(test, ndi_has_advanced_av_sync, ndi_has_advanced_genlock))]
7use std::ptr;
8
9use super::{invalid_input, AdvancedConfig, AvSyncAttached, ReceiverControls};
10use crate::{
11 capture::{AvSyncAudioFree, Guard},
12 frames::{checked_audio_extent, ValidatedAudio, VideoPartsExt},
13 marker::NotSync,
14 media::SdkQuantity,
15 receiver::{
16 attached::{sealed, Attached, Resource, Synchronizer},
17 ReceiverCore,
18 },
19 source_retention::RetainedSources,
20 sys::{
21 advanced::{native, AvSync as AvSyncTable, Genlock as GenlockTable},
22 bindings::*,
23 },
24 AudioFrame, FrameRate, Ndi, ReceivedTimestamp, Receiver, Rejected, Result, ScanType, Source,
25 VideoFrame, VideoFrameRef,
26};
27
28#[cfg(any(test, ndi_has_advanced_av_sync, ndi_has_advanced_genlock))]
29use super::descriptors;
30#[cfg(ndi_has_advanced_av_sync)]
31use crate::sys::advanced::AvSyncHandle;
32#[cfg(ndi_has_advanced_genlock)]
33use crate::sys::advanced::GenlockHandle;
34#[cfg(any(doc, test, ndi_has_advanced_av_sync, ndi_has_advanced_genlock))]
35use crate::Error;
36#[cfg(any(test, ndi_has_advanced_av_sync))]
37use crate::{capture::AvSyncAudioInstance, frames::ReturnedAudio};
38
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
47pub struct AvSyncRequest {
48 sample_rate: Option<SdkQuantity>,
49 num_samples: Option<SdkQuantity>,
50}
51
52impl AvSyncRequest {
53 pub fn automatic() -> Self {
55 Self::default()
56 }
57
58 pub fn new(sample_rate: Option<u32>, num_samples: Option<u32>) -> Result<Self> {
72 let request = Self {
73 sample_rate: sample_rate
74 .map(|rate| crate::frames::validate_audio_sample_rate(rate.into()))
75 .transpose()
76 .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?,
77 num_samples: num_samples
78 .map(|samples| {
79 crate::frames::validate_audio_count(
80 samples.into(),
81 crate::AudioCountKind::Samples,
82 )
83 })
84 .transpose()
85 .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?,
86 };
87 if let Some(samples) = request.num_samples {
89 const ONE_CHANNEL: SdkQuantity = SdkQuantity::new(1).unwrap();
90 checked_audio_extent(ONE_CHANNEL, samples, u64::from(samples.get()))
91 .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?;
92 }
93 Ok(request)
94 }
95
96 pub fn sample_rate(self) -> Option<u32> {
98 self.sample_rate.map(SdkQuantity::get)
99 }
100
101 pub fn num_samples(self) -> Option<u32> {
103 self.num_samples.map(SdkQuantity::get)
104 }
105
106 #[cfg(any(test, ndi_has_advanced_av_sync))]
112 fn raw(self) -> NDIlib_audio_frame_v3_t {
113 let field = |value: Option<SdkQuantity>| value.map_or(0, SdkQuantity::to_sdk);
114 NDIlib_audio_frame_v3_t {
119 sample_rate: field(self.sample_rate),
120 no_samples: field(self.num_samples),
121 ..descriptors::audio_frame()
122 }
123 }
124}
125
126#[derive(Clone, Debug)]
131#[non_exhaustive]
132pub enum AvSyncOutcome {
133 Audio {
135 frame: AudioFrame,
137 samples_adjusted: bool,
140 },
141 Empty {
143 samples_adjusted: bool,
145 },
146 FormatChanged {
150 sample_rate: u32,
152 num_channels: u32,
154 },
155 NoAudioStream,
157 NoMatchingSamples,
159}
160
161pub struct AvSyncAudioRef<'a> {
170 pub(crate) inner: ValidatedAudio<Guard<'a, AvSyncAudioFree>>,
171}
172
173#[derive(Debug)]
175#[non_exhaustive]
176pub enum AvSyncOutcomeRef<'a> {
177 Audio {
179 frame: AvSyncAudioRef<'a>,
181 samples_adjusted: bool,
183 },
184 Empty {
186 samples_adjusted: bool,
188 },
189 FormatChanged {
191 sample_rate: u32,
193 num_channels: u32,
195 },
196 NoAudioStream,
198 NoMatchingSamples,
200}
201
202impl AvSyncOutcomeRef<'_> {
203 pub fn to_owned(&self) -> AvSyncOutcome {
206 match self {
207 Self::Audio {
208 frame,
209 samples_adjusted,
210 } => AvSyncOutcome::Audio {
211 frame: frame.to_owned(),
212 samples_adjusted: *samples_adjusted,
213 },
214 Self::Empty { samples_adjusted } => AvSyncOutcome::Empty {
215 samples_adjusted: *samples_adjusted,
216 },
217 Self::FormatChanged {
218 sample_rate,
219 num_channels,
220 } => AvSyncOutcome::FormatChanged {
221 sample_rate: *sample_rate,
222 num_channels: *num_channels,
223 },
224 Self::NoAudioStream => AvSyncOutcome::NoAudioStream,
225 Self::NoMatchingSamples => AvSyncOutcome::NoMatchingSamples,
226 }
227 }
228}
229
230#[cfg(any(test, ndi_has_advanced_av_sync))]
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
233enum Synchronized {
234 Matched,
235 Adjusted,
236 NoAudioStream,
237 NoMatchingSamples,
238 FormatChanged,
239 InternalError,
240 Unknown(i32),
241}
242
243pub(crate) struct AvSyncKind {
245 #[cfg(ndi_has_advanced_av_sync)]
246 handle: AvSyncInstance,
247 table: crate::runtime::Bound<AvSyncTable, std::sync::Arc<ReceiverCore>>,
248 _not_sync: NotSync,
250}
251
252type AvResource = Resource<AvSyncKind>;
253
254#[cfg(ndi_has_advanced_av_sync)]
255impl crate::capture::source_sealed::Sealed for &AvResource {}
256
257#[cfg(ndi_has_advanced_av_sync)]
261unsafe impl<'owner> crate::capture::FrameSource<'owner, AvSyncAudioFree> for &'owner AvResource {
262 fn runtime(&self) -> &'owner Ndi {
263 self.table.ndi()
264 }
265
266 fn instance(&self) -> AvSyncAudioInstance {
267 AvSyncAudioInstance::Native {
268 handle: self.handle.0,
269 free: self.table.NDIlib_avsync_free_audio,
270 }
271 }
272}
273
274#[cfg(ndi_has_advanced_av_sync)]
277const_assert!(
278 std::mem::size_of::<AvResource>()
279 == std::mem::size_of::<AvSyncInstance>()
280 + std::mem::size_of::<&AvSyncTable>()
281 + std::mem::size_of::<std::sync::Arc<ReceiverCore>>()
282);
283
284#[cfg(ndi_has_advanced_av_sync)]
285#[derive(Clone, Copy)]
286struct AvSyncInstance(AvSyncHandle);
287
288#[cfg(ndi_has_advanced_av_sync)]
297unsafe impl Send for AvSyncInstance {}
298
299const_assert!({
300 const fn send<T: Send>() {}
301 send::<AvResource>();
302});
303
304impl sealed::Sealed for AvSyncKind {}
305
306unsafe impl Synchronizer for AvSyncKind {
309 type Mode = AvSyncAttached;
310 type Capture<'a> = AvSyncCapture<'a>;
311
312 unsafe fn destroy(&mut self) {
313 native!(AvSync, self.table => {
314 unsafe { self.table.NDIlib_avsync_destroy(self.handle.0) };
317 });
318 }
319
320 fn receiver(&self) -> &std::sync::Arc<ReceiverCore> {
321 self.table.owner()
322 }
323
324 fn capture(resource: &AvResource) -> AvSyncCapture<'_> {
325 AvSyncCapture {
326 resource,
327 _thread: PhantomData,
328 }
329 }
330}
331
332pub struct AvSync {
389 inner: Attached<AvSyncKind>,
390}
391
392impl std::fmt::Debug for AvSync {
393 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394 f.debug_struct("AvSync")
395 .field("receiver", self.receiver())
396 .finish_non_exhaustive()
397 }
398}
399
400impl AvSync {
401 #[doc(alias = "NDIlib_avsync_create")]
410 pub fn new(receiver: Receiver) -> std::result::Result<Self, Rejected<Receiver>> {
411 let table = match crate::runtime::Bound::<AvSyncTable, _>::with_owner(
412 std::sync::Arc::clone(&receiver.core),
413 ) {
414 Ok(table) => table,
415 Err(error) => return Err(Rejected::new(error, receiver)),
416 };
417 native!(AvSync, table => {
418 unsafe {
421 Attached::adopt(receiver, |adoption| {
422 let handle = table.named().NDIlib_avsync_create(adoption.instance())
423 .created()?.as_ptr();
424 Ok(AvSyncKind {
425 handle: AvSyncInstance(handle),
426 table,
427 _not_sync: NotSync::default(),
428 })
429 })
430 }.map(|inner| Self { inner })
431 })
432 }
433
434 pub fn receiver(&self) -> &Receiver<AvSyncAttached> {
462 self.inner.receiver()
463 }
464
465 pub fn controls(&mut self) -> ReceiverControls<'_, AvSyncAttached> {
469 self.inner.controls()
470 }
471
472 pub fn split(&mut self) -> (AvSyncCapture<'_>, ReceiverControls<'_, AvSyncAttached>) {
480 self.inner.split()
481 }
482
483 pub fn into_receiver(self) -> Receiver {
486 self.inner.into_receiver()
487 }
488
489 #[doc(alias = "NDIlib_avsync_synchronize")]
520 pub fn synchronize(
521 &self,
522 video: AvSyncVideo<'_>,
523 request: AvSyncRequest,
524 ) -> Result<AvSyncOutcome> {
525 Ok(self.synchronize_ref(video, request)?.to_owned())
526 }
527
528 #[doc(alias = "NDIlib_avsync_synchronize")]
532 pub fn synchronize_ref(
533 &self,
534 video: AvSyncVideo<'_>,
535 request: AvSyncRequest,
536 ) -> Result<AvSyncOutcomeRef<'_>> {
537 self.capture().synchronize_ref(video, request)
538 }
539
540 #[doc(alias = "NDIlib_avsync_synchronize")]
552 pub fn queued_audio(&self, request: AvSyncRequest) -> Result<AvSyncOutcome> {
553 Ok(self.queued_audio_ref(request)?.to_owned())
554 }
555
556 #[doc(alias = "NDIlib_avsync_synchronize")]
559 pub fn queued_audio_ref(&self, request: AvSyncRequest) -> Result<AvSyncOutcomeRef<'_>> {
560 self.capture().queued_audio_ref(request)
561 }
562
563 fn capture(&self) -> AvSyncCapture<'_> {
566 self.inner.capture()
567 }
568}
569
570#[derive(Clone, Copy)]
579pub struct AvSyncCapture<'a> {
580 resource: &'a AvResource,
581 _thread: PhantomData<*mut ()>,
582}
583
584impl std::fmt::Debug for AvSyncCapture<'_> {
585 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
586 let receiver =
587 crate::receiver::ReceiverIdentity::new::<AvSyncAttached>(self.resource.receiver());
588 f.debug_struct("AvSyncCapture")
589 .field("receiver", &receiver)
590 .finish_non_exhaustive()
591 }
592}
593
594impl<'a> AvSyncCapture<'a> {
595 #[doc(alias = "NDIlib_avsync_synchronize")]
602 pub fn synchronize(
603 &self,
604 video: AvSyncVideo<'_>,
605 request: AvSyncRequest,
606 ) -> Result<AvSyncOutcome> {
607 Ok(self.synchronize_ref(video, request)?.to_owned())
608 }
609
610 #[doc(alias = "NDIlib_avsync_synchronize")]
613 pub fn synchronize_ref(
614 &self,
615 video: AvSyncVideo<'_>,
616 request: AvSyncRequest,
617 ) -> Result<AvSyncOutcomeRef<'a>> {
618 self.request(Some(video), request)
619 }
620
621 #[doc(alias = "NDIlib_avsync_synchronize")]
627 pub fn queued_audio(&self, request: AvSyncRequest) -> Result<AvSyncOutcome> {
628 Ok(self.queued_audio_ref(request)?.to_owned())
629 }
630
631 #[doc(alias = "NDIlib_avsync_synchronize")]
633 pub fn queued_audio_ref(&self, request: AvSyncRequest) -> Result<AvSyncOutcomeRef<'a>> {
634 self.request(None, request)
635 }
636
637 fn request(
640 &self,
641 _video: Option<AvSyncVideo<'_>>,
642 _request: AvSyncRequest,
643 ) -> Result<AvSyncOutcomeRef<'a>> {
644 native!(AvSync, self.resource.table => {
645 let video = _video.map(|video| video.descriptor());
649 let (handle, table) = (self.resource.handle, &self.resource.table);
650 let mut audio = _request.raw();
651 let status = {
652 let code = unsafe {
676 table.named().NDIlib_avsync_synchronize(
677 handle.0,
678 video.as_ref().map_or(ptr::null(), |video| video),
679 &mut audio,
680 )
681 };
682 code.map(|code| match code {
683 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_success => Synchronized::Matched,
684 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_success_num_samples_not_matched => {
685 Synchronized::Adjusted
686 }
687 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_no_audio_stream_received => {
688 Synchronized::NoAudioStream
689 }
690 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_no_samples_found => {
691 Synchronized::NoMatchingSamples
692 }
693 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_format_changed => {
694 Synchronized::FormatChanged
695 }
696 crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_internal_error => {
697 Synchronized::InternalError
698 }
699 other => Synchronized::Unknown(other),
700 })
701 };
702 let guard = unsafe { Guard::new(self.resource, audio) };
705 outcome_with_call(status, guard)
706 })
707 }
708}
709
710#[cfg(any(test, ndi_has_advanced_av_sync))]
714fn outcome_with_call<'a>(
715 called: crate::sys::table::Called<Synchronized>,
716 audio: Guard<'a, AvSyncAudioFree>,
717) -> Result<AvSyncOutcomeRef<'a>> {
718 Ok(match *called.value() {
719 Synchronized::Matched | Synchronized::Adjusted => {
720 let samples_adjusted = *called.value() == Synchronized::Adjusted;
721 match ValidatedAudio::returned_audio(audio)? {
722 ReturnedAudio::Empty(_) => AvSyncOutcomeRef::Empty { samples_adjusted },
724 ReturnedAudio::Samples(validated) => AvSyncOutcomeRef::Audio {
725 frame: AvSyncAudioRef::from_validated(validated),
726 samples_adjusted,
727 },
728 }
729 }
730 Synchronized::NoAudioStream => AvSyncOutcomeRef::NoAudioStream,
731 Synchronized::NoMatchingSamples => AvSyncOutcomeRef::NoMatchingSamples,
732 Synchronized::FormatChanged => {
733 match (
734 SdkQuantity::new(audio.frame().sample_rate.into()),
735 SdkQuantity::new(audio.frame().no_channels.into()),
736 ) {
737 (Some(sample_rate), Some(num_channels)) => AvSyncOutcomeRef::FormatChanged {
738 sample_rate: sample_rate.get(),
739 num_channels: num_channels.get(),
740 },
741 _ => {
742 return Err(Error::UnexpectedSdkResult(
743 crate::SdkResultDefect::AvSyncFormatChange {
744 sample_rate: audio.frame().sample_rate,
745 channels: audio.frame().no_channels,
746 },
747 ))
748 }
749 }
750 }
751 Synchronized::InternalError => {
752 return Err(called.failed());
753 }
754 Synchronized::Unknown(code) => {
755 return Err(Error::UnexpectedSdkResult(
756 crate::SdkResultDefect::UnknownStatus {
757 operation: called.function(),
758 code,
759 },
760 ));
761 }
762 })
763}
764
765#[cfg(test)]
766fn outcome<'a>(
767 status: Synchronized,
768 audio: Guard<'a, AvSyncAudioFree>,
769) -> Result<AvSyncOutcomeRef<'a>> {
770 outcome_with_call(
771 crate::sys::table::for_test(status, c"NDIlib_avsync_synchronize"),
772 audio,
773 )
774}
775
776mod video_sealed {
777 use crate::{sys::bindings::NDIlib_video_frame_v2_t, ReceivedTimestamp};
778
779 pub trait Sealed: Sync + std::panic::RefUnwindSafe {
782 fn descriptor(&self) -> NDIlib_video_frame_v2_t;
785
786 fn receive_timestamp(&self) -> Option<ReceivedTimestamp>;
788 }
789}
790
791pub trait AvSyncFrame: video_sealed::Sealed {}
797
798impl video_sealed::Sealed for VideoFrame {
799 fn descriptor(&self) -> NDIlib_video_frame_v2_t {
800 self.video_descriptor()
801 }
802
803 fn receive_timestamp(&self) -> Option<ReceivedTimestamp> {
804 self.timestamp()
805 }
806}
807
808impl AvSyncFrame for VideoFrame {}
809
810impl video_sealed::Sealed for VideoFrameRef<'_> {
811 fn descriptor(&self) -> NDIlib_video_frame_v2_t {
812 self.video_descriptor()
813 }
814
815 fn receive_timestamp(&self) -> Option<ReceivedTimestamp> {
816 self.timestamp()
817 }
818}
819
820impl AvSyncFrame for VideoFrameRef<'_> {}
821
822#[derive(Clone, Copy)]
850pub struct AvSyncVideo<'a> {
851 #[cfg_attr(
855 not(any(test, ndi_has_advanced_av_sync)),
856 expect(dead_code, reason = "only the native synchronization reads the frame")
857 )]
858 frame: &'a dyn video_sealed::Sealed,
859 timestamp: ReceivedTimestamp,
860}
861
862impl<'a> AvSyncVideo<'a> {
863 pub fn new<F: AvSyncFrame>(frame: &'a F) -> Option<Self> {
868 Some(Self {
869 timestamp: frame.receive_timestamp()?,
870 frame,
871 })
872 }
873
874 pub fn timestamp(&self) -> ReceivedTimestamp {
876 self.timestamp
877 }
878
879 #[cfg(any(test, ndi_has_advanced_av_sync))]
881 fn descriptor(&self) -> NDIlib_video_frame_v2_t {
882 NDIlib_video_frame_v2_t {
883 timestamp: self.timestamp.ticks(),
884 ..self.frame.descriptor()
885 }
886 }
887}
888
889impl std::fmt::Debug for AvSyncVideo<'_> {
890 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891 f.debug_struct("AvSyncVideo")
892 .field("timestamp", &self.timestamp)
893 .finish_non_exhaustive()
894 }
895}
896
897#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
899#[non_exhaustive]
900pub enum ClockSource {
901 ReferenceSignal,
903 SystemClock,
905}
906
907impl ClockSource {
908 #[cfg(any(test, ndi_has_advanced_genlock))]
909 fn from_active(active: bool) -> Self {
910 if active {
911 Self::ReferenceSignal
912 } else {
913 Self::SystemClock
914 }
915 }
916}
917
918struct GenResource {
920 #[cfg(ndi_has_advanced_genlock)]
921 handle: GenlockInstance,
922 table: crate::runtime::Bound<GenlockTable>,
923 source: RetainedSources,
924 _config: super::RetainedConfig,
925}
926
927#[cfg(ndi_has_advanced_genlock)]
928#[derive(Clone, Copy)]
929struct GenlockInstance(GenlockHandle);
930
931#[cfg(ndi_has_advanced_genlock)]
944unsafe impl Send for GenlockInstance {}
945
946#[cfg(ndi_has_advanced_genlock)]
953unsafe impl Sync for GenlockInstance {}
954
955const_assert!({
956 const fn send_and_sync<T: Send + Sync>() {}
957 send_and_sync::<GenResource>();
958});
959
960impl Drop for GenResource {
961 fn drop(&mut self) {
962 native!(Genlock, self.table => unsafe { self.table.NDIlib_genlock_destroy(self.handle.0) });
965 }
966}
967
968#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
972pub struct GenlockOptions {
973 source: Option<Source>,
974 config: Option<AdvancedConfig>,
975}
976
977impl GenlockOptions {
978 pub fn new() -> Self {
980 Self::default()
981 }
982
983 #[must_use]
985 pub fn source(mut self, source: Source) -> Self {
986 self.source = Some(source);
987 self
988 }
989
990 pub fn configured_source(&self) -> Option<&Source> {
992 self.source.as_ref()
993 }
994
995 #[must_use]
997 pub fn clear_source(mut self) -> Self {
998 self.source = None;
999 self
1000 }
1001
1002 #[must_use]
1004 pub fn config(mut self, config: AdvancedConfig) -> Self {
1005 self.config = Some(config);
1006 self
1007 }
1008
1009 pub fn configured_config(&self) -> Option<&AdvancedConfig> {
1011 self.config.as_ref()
1012 }
1013
1014 #[must_use]
1016 pub fn clear_config(mut self) -> Self {
1017 self.config = None;
1018 self
1019 }
1020}
1021
1022pub struct Genlock {
1060 resource: GenResource,
1061 _not_sync: NotSync,
1067}
1068
1069impl std::fmt::Debug for Genlock {
1070 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1071 f.debug_struct("Genlock")
1072 .field("source", &self.resource.source.current())
1073 .finish_non_exhaustive()
1074 }
1075}
1076
1077impl Genlock {
1078 #[doc(alias = "NDIlib_genlock_create")]
1088 pub fn new(ndi: &Ndi, options: &GenlockOptions) -> Result<Self> {
1089 let table = ndi.bind::<GenlockTable>()?;
1090 native!(Genlock, table, uses(options) => {
1091 let mut source = RetainedSources::default();
1092 let (call, config) = AdvancedConfig::lend(options.configured_config(), |config| {
1093 source.replace(options.source.as_ref(), |source| {
1094 unsafe { table.named().NDIlib_genlock_create(source, config) }
1097 })
1098 });
1099 let handle = call.created()?.as_ptr();
1100 Ok(Self {
1101 resource: GenResource {
1102 handle: GenlockInstance(handle),
1103 table,
1104 source,
1105 _config: config,
1106 },
1107 _not_sync: NotSync::default(),
1108 })
1109 })
1110 }
1111
1112 #[doc(alias = "NDIlib_genlock_connect")]
1117 pub fn connect_to(&mut self, source: &Source) {
1118 self.connect_source(Some(source));
1119 }
1120
1121 #[doc(alias = "NDIlib_genlock_connect")]
1123 pub fn disconnect(&mut self) {
1124 self.connect_source(None);
1125 }
1126
1127 fn connect_source(&mut self, source: Option<&Source>) {
1128 native!(Genlock, self.resource.table, uses(source) => {
1129 let GenResource { handle, table, source: retained, .. } = &mut self.resource;
1130 retained.replace(source, |source| {
1131 unsafe { table.NDIlib_genlock_connect(handle.0, source) };
1134 });
1135 })
1136 }
1137
1138 #[doc(alias = "NDIlib_genlock_is_active")]
1140 pub fn is_active(&self) -> bool {
1141 native!(Genlock, self.resource.table => unsafe {
1143 self.resource.table.NDIlib_genlock_is_active(self.resource.handle.0)
1144 })
1145 }
1146
1147 pub fn clocks(&mut self) -> (VideoClock<'_>, AudioClock<'_>) {
1152 (
1153 VideoClock {
1154 resource: &self.resource,
1155 _not_sync: NotSync::default(),
1156 },
1157 AudioClock {
1158 resource: &self.resource,
1159 _not_sync: NotSync::default(),
1160 },
1161 )
1162 }
1163}
1164
1165pub struct VideoClock<'a> {
1167 resource: &'a GenResource,
1168 _not_sync: NotSync,
1170}
1171
1172impl std::fmt::Debug for VideoClock<'_> {
1173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1174 f.debug_struct("VideoClock").finish_non_exhaustive()
1175 }
1176}
1177
1178impl VideoClock<'_> {
1179 #[doc(alias = "NDIlib_genlock_wait_video")]
1182 pub fn wait(&mut self, frame_rate: FrameRate, scan_type: ScanType) -> ClockSource {
1183 native!(Genlock, self.resource.table, uses(frame_rate, scan_type) => {
1184 let timing = video_timing(frame_rate, scan_type);
1185 let GenResource { handle, table, .. } = self.resource;
1186 ClockSource::from_active(unsafe {
1189 table.NDIlib_genlock_wait_video(handle.0, &timing)
1190 })
1191 })
1192 }
1193}
1194
1195pub struct AudioClock<'a> {
1197 resource: &'a GenResource,
1198 _not_sync: NotSync,
1200}
1201
1202impl std::fmt::Debug for AudioClock<'_> {
1203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1204 f.debug_struct("AudioClock").finish_non_exhaustive()
1205 }
1206}
1207
1208#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1213pub struct AudioClockRequest {
1214 sample_rate: SdkQuantity,
1215 num_samples: SdkQuantity,
1216}
1217
1218impl AudioClockRequest {
1219 pub fn new(sample_rate: u32, num_samples: u32) -> Result<Self> {
1226 let sample_rate = crate::frames::validate_audio_sample_rate(sample_rate.into())
1227 .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?;
1228 let num_samples =
1229 crate::frames::validate_audio_count(num_samples.into(), crate::AudioCountKind::Samples)
1230 .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?;
1231 Ok(Self {
1232 sample_rate,
1233 num_samples,
1234 })
1235 }
1236
1237 pub fn sample_rate(self) -> u32 {
1239 self.sample_rate.get()
1240 }
1241
1242 pub fn num_samples(self) -> u32 {
1244 self.num_samples.get()
1245 }
1246}
1247
1248impl AudioClock<'_> {
1249 #[doc(alias = "NDIlib_genlock_wait_audio")]
1252 pub fn wait(&mut self, request: AudioClockRequest) -> ClockSource {
1253 native!(Genlock, self.resource.table, uses(request) => {
1254 let timing = audio_timing(request);
1255 let GenResource { handle, table, .. } = self.resource;
1256 ClockSource::from_active(unsafe {
1260 table.NDIlib_genlock_wait_audio(handle.0, &timing)
1261 })
1262 })
1263 }
1264}
1265
1266#[cfg(any(test, ndi_has_advanced_genlock))]
1268fn audio_timing(request: AudioClockRequest) -> NDIlib_audio_frame_v3_t {
1269 NDIlib_audio_frame_v3_t {
1270 sample_rate: request.sample_rate.to_sdk(),
1271 no_samples: request.num_samples.to_sdk(),
1272 ..descriptors::audio_frame()
1273 }
1274}
1275
1276#[cfg(any(test, ndi_has_advanced_genlock))]
1278fn video_timing(frame_rate: FrameRate, scan_type: ScanType) -> NDIlib_video_frame_v2_t {
1279 let (numerator, denominator) = frame_rate.to_sdk();
1280 NDIlib_video_frame_v2_t {
1281 frame_rate_N: numerator,
1282 frame_rate_D: denominator,
1283 frame_format_type: scan_type.to_sdk(),
1284 ..descriptors::video_frame()
1285 }
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290 use super::*;
1291 use crate::frames::{AudioPartsExt, MAX_AUDIO_BYTES};
1292
1293 #[test]
1294 fn avsync_requests_share_the_audio_extent_limit_and_cause() {
1295 let limit = (MAX_AUDIO_BYTES / size_of::<f32>()) as u32;
1296 let expected = crate::LayoutDefect::AudioBytes(67_108_868_u64.into());
1297 let cause = |error| match error {
1298 Error::InvalidInput(crate::InputDefect::Layout(cause)) => cause,
1299 other => panic!("expected the shared audio layout cause, got {other:?}"),
1300 };
1301 for rate in [None, Some(48_000)] {
1302 assert!(AvSyncRequest::new(rate, Some(limit)).is_ok());
1303 assert_eq!(
1304 cause(AvSyncRequest::new(rate, Some(limit + 1)).unwrap_err()),
1305 expected
1306 );
1307 assert!(matches!(
1308 AvSyncRequest::new(rate, Some(i32::MAX as u32 + 1)),
1309 Err(Error::InvalidInput(crate::InputDefect::Layout(
1310 crate::LayoutDefect::AudioCount {
1311 kind: crate::AudioCountKind::Samples,
1312 ..
1313 }
1314 )))
1315 ));
1316 }
1317 let framesync = crate::FrameSyncAudioRequest::capture_at(48_000, 1, limit + 1).unwrap_err();
1318 assert_eq!(cause(framesync), expected);
1319 }
1320
1321 #[test]
1322 fn genlock_options_roundtrip_and_clear_without_a_runtime() {
1323 let source = Source::new("HOST (Reference)").unwrap();
1324 let config = AdvancedConfig::parse(r#"{"genlock":{"marker":"retained"}}"#).unwrap();
1325 let defaults = GenlockOptions::new();
1326 assert_eq!(defaults, GenlockOptions::default());
1327 assert!(defaults.configured_source().is_none());
1328 assert!(defaults.configured_config().is_none());
1329 let options = defaults
1330 .clone()
1331 .source(source.clone())
1332 .config(config.clone());
1333 assert_eq!(options.configured_source(), Some(&source));
1334 assert_eq!(options.configured_config(), Some(&config));
1335 assert_eq!(options, options.clone());
1336 assert_eq!(options.clear_source().clear_config(), defaults);
1337 }
1338
1339 unsafe fn inspect(
1340 status: Synchronized,
1341 audio: &NDIlib_audio_frame_v3_t,
1342 ) -> Result<AvSyncOutcome> {
1343 let guard = unsafe {
1345 Guard::<AvSyncAudioFree>::with_test_free(
1346 AvSyncAudioInstance::Synthetic(ptr::null()),
1347 *audio,
1348 |_, _| {},
1349 )
1350 };
1351 outcome(status, guard).map(|outcome| outcome.to_owned())
1352 }
1353
1354 fn descriptor() -> NDIlib_audio_frame_v3_t {
1355 NDIlib_audio_frame_v3_t {
1356 p_data: ptr::dangling_mut::<u8>(),
1357 sample_rate: 48_000,
1358 no_channels: 2,
1359 no_samples: 1,
1360 ..Default::default()
1361 }
1362 }
1363
1364 #[test]
1365 fn distinguishes_native_outcomes() {
1366 let audio = descriptor();
1367 let classify = |status| unsafe { inspect(status, &audio) }.unwrap();
1369 assert!(matches!(
1370 classify(Synchronized::FormatChanged),
1371 AvSyncOutcome::FormatChanged {
1372 sample_rate: 48_000,
1373 num_channels: 2
1374 }
1375 ));
1376 for (sample_rate, no_channels) in [(0, 2), (48_000, -1), (-48_000, 2)] {
1377 let changed = NDIlib_audio_frame_v3_t {
1378 sample_rate,
1379 no_channels,
1380 ..audio
1381 };
1382 assert!(matches!(
1384 unsafe { inspect(Synchronized::FormatChanged, &changed) },
1385 Err(Error::UnexpectedSdkResult(_))
1386 ));
1387 }
1388 assert!(matches!(
1389 classify(Synchronized::NoAudioStream),
1390 AvSyncOutcome::NoAudioStream
1391 ));
1392 assert!(matches!(
1393 classify(Synchronized::NoMatchingSamples),
1394 AvSyncOutcome::NoMatchingSamples
1395 ));
1396 assert!(matches!(
1398 unsafe { inspect(Synchronized::InternalError, &audio) },
1399 Err(Error::NativeOperationFailed {
1400 operation}) if operation.name() == c"NDIlib_avsync_synchronize"
1401 ));
1402 for code in [-99, 99] {
1403 assert!(matches!(
1405 unsafe { inspect(Synchronized::Unknown(code), &audio) },
1406 Err(Error::UnexpectedSdkResult(message)) if matches!(message,crate::SdkResultDefect::UnknownStatus {code:found,..} if found==code)
1407 ));
1408 }
1409
1410 let empty = NDIlib_audio_frame_v3_t {
1411 p_data: ptr::null_mut(),
1412 no_samples: 0,
1413 FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
1414 ..audio
1415 };
1416 assert!(matches!(
1418 unsafe { inspect(Synchronized::Adjusted, &empty) }.unwrap(),
1419 AvSyncOutcome::Empty {
1420 samples_adjusted: true
1421 }
1422 ));
1423 }
1424
1425 #[test]
1426 fn rejects_invalid_clock_and_request_values_before_native_wait() {
1427 let refused = |result: Result<AvSyncRequest>| {
1428 assert!(matches!(result, Err(Error::InvalidInput(_))), "{result:?}");
1429 };
1430 refused(AvSyncRequest::new(Some(0), None));
1431 refused(AvSyncRequest::new(None, Some(0)));
1432 refused(AvSyncRequest::new(Some(u32::MAX), None));
1433 refused(AvSyncRequest::new(Some(i32::MAX.unsigned_abs() + 1), None));
1434 let most = (MAX_AUDIO_BYTES / 4) as u32;
1435 assert!(AvSyncRequest::new(None, Some(most)).is_ok());
1436 refused(AvSyncRequest::new(None, Some(most + 1)));
1437 assert_eq!(AvSyncRequest::automatic().num_samples(), None);
1438 assert_eq!(AvSyncRequest::automatic().sample_rate(), None);
1439 let request = AvSyncRequest::new(Some(48_000), Some(1600)).unwrap();
1440 assert_eq!(
1441 (request.sample_rate(), request.num_samples()),
1442 (Some(48_000), Some(1600))
1443 );
1444 for (sample_rate, num_samples) in [(48_000, 0), (0, 1600), (u32::MAX, 1600)] {
1445 assert!(matches!(
1446 AudioClockRequest::new(sample_rate, num_samples),
1447 Err(Error::InvalidInput(_))
1448 ));
1449 }
1450 let raw = video_timing(FrameRate::new(60_000, 1001).unwrap(), ScanType::Progressive);
1451 assert_eq!((raw.frame_rate_N, raw.frame_rate_D), (60_000, 1001));
1452 assert_eq!(ClockSource::from_active(false), ClockSource::SystemClock);
1453 fn send<T: Send>() {}
1454 send::<VideoClock<'_>>();
1455 send::<AudioClock<'_>>();
1456 }
1457
1458 #[test]
1459 fn audio_clock_requests_validate_once_and_keep_value_traits() {
1460 use std::hash::{Hash, Hasher};
1461
1462 fn value_traits<T: Copy + Eq + std::hash::Hash + Send + Sync>() {}
1463 fn hash(value: impl Hash) -> u64 {
1464 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1465 value.hash(&mut hasher);
1466 hasher.finish()
1467 }
1468 value_traits::<AudioClockRequest>();
1469 let mut distinct = std::collections::HashSet::new();
1470 for rate in [1, 48_000, i32::MAX as u32] {
1471 for samples in [1, 800, i32::MAX as u32] {
1472 let request = AudioClockRequest::new(rate, samples).unwrap();
1473 assert_eq!(
1474 (request.sample_rate(), request.num_samples()),
1475 (rate, samples)
1476 );
1477 assert_eq!(request, AudioClockRequest::new(rate, samples).unwrap());
1478 assert_eq!(hash(request), hash((rate, samples)));
1479 assert!(distinct.insert(request));
1480 assert_eq!(
1481 format!("{request:?}"),
1482 format!("AudioClockRequest {{ sample_rate: {rate}, num_samples: {samples} }}")
1483 );
1484 }
1485 }
1486 assert_eq!(distinct.len(), 9);
1487 for value in [0, i32::MAX as u32 + 1, u32::MAX] {
1488 assert!(matches!(AudioClockRequest::new(value, 800),
1489 Err(Error::InvalidInput(crate::InputDefect::Layout(crate::LayoutDefect::AudioRate(n))))
1490 if n.get() == i64::from(value)));
1491 assert!(matches!(AudioClockRequest::new(48_000, value),
1492 Err(Error::InvalidInput(crate::InputDefect::Layout(crate::LayoutDefect::AudioCount { kind: crate::AudioCountKind::Samples, value: n })))
1493 if n.get() == i64::from(value)));
1494 }
1495 assert!(matches!(AvSyncRequest::new(Some(0), None),
1496 Err(Error::InvalidInput(crate::InputDefect::Layout(crate::LayoutDefect::AudioRate(n))))
1497 if n.get() == 0));
1498 }
1499
1500 #[test]
1504 fn a_request_is_the_sdk_default_descriptor_with_what_it_asks_for() {
1505 let planar_float = crate::FourCc::from(crate::AudioFormat::Fltp).raw();
1506 let automatic = AvSyncRequest::automatic().raw();
1507 assert_eq!(automatic.FourCC, planar_float);
1508 assert_eq!(automatic.no_channels, 2);
1509 assert_eq!((automatic.no_samples, automatic.sample_rate), (0, 0));
1510 assert_eq!(automatic.timecode, NDIlib_send_timecode_synthesize);
1511 assert!(automatic.p_data.is_null() && automatic.p_metadata.is_null());
1512
1513 let explicit = AvSyncRequest::new(Some(44_100), Some(1601)).unwrap().raw();
1514 assert_eq!(explicit.FourCC, planar_float);
1515 assert_eq!(explicit.no_channels, 2);
1516 assert_eq!((explicit.no_samples, explicit.sample_rate), (1601, 44_100));
1517
1518 let returned = NDIlib_audio_frame_v3_t {
1520 no_samples: 0,
1521 sample_rate: 48_000,
1522 no_channels: 2,
1523 ..automatic
1524 };
1525 assert!(matches!(
1527 unsafe { inspect(Synchronized::Matched, &returned) }.unwrap(),
1528 AvSyncOutcome::Empty {
1529 samples_adjusted: false
1530 }
1531 ));
1532
1533 let video = video_timing(FrameRate::new(60_000, 1001).unwrap(), ScanType::Interlaced);
1535 assert_eq!(
1536 video.FourCC,
1537 NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVY
1538 );
1539 assert_eq!(
1540 video.frame_format_type,
1541 NDIlib_frame_format_type_e_NDIlib_frame_format_type_interleaved
1542 );
1543 let audio = audio_timing(AudioClockRequest::new(48_000, 1600).unwrap());
1544 assert_eq!(audio.FourCC, planar_float);
1545 assert_eq!((audio.sample_rate, audio.no_samples), (48_000, 1600));
1546 assert!(audio.p_data.is_null() && audio.p_metadata.is_null());
1547 }
1548
1549 fn captured(pixels: &mut [u8], timestamp: i64) -> VideoFrameRef<'_> {
1551 use crate::capture::{CaptureStrategy, Guard, VideoKind};
1552 assert_eq!(pixels.len(), 128 * 32);
1553 let raw = NDIlib_video_frame_v2_t {
1554 xres: 64,
1555 yres: 32,
1556 FourCC: NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVY,
1557 frame_rate_N: 30_000,
1558 frame_rate_D: 1001,
1559 frame_format_type: NDIlib_frame_format_type_e_NDIlib_frame_format_type_progressive,
1560 p_data: pixels.as_mut_ptr(),
1561 __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
1562 line_stride_in_bytes: 128,
1563 },
1564 timestamp,
1565 ..Default::default()
1566 };
1567 VideoKind::make_ref(unsafe { Guard::with_test_free(ptr::null_mut(), raw, |_, _| {}) })
1570 .unwrap()
1571 }
1572
1573 #[test]
1577 fn only_a_frame_with_a_timestamp_can_be_synchronized() {
1578 let built = VideoFrame::builder().resolution(64, 32).build().unwrap();
1579 assert!(AvSyncVideo::new(&built).is_none());
1580
1581 let mut unstamped = vec![16; 128 * 32];
1582 let unstamped = captured(&mut unstamped, NDIlib_recv_timestamp_undefined);
1583 assert!(AvSyncVideo::new(&unstamped).is_none());
1584
1585 for ticks in [0, -1, 17_946_474_843_047_964] {
1586 let mut pixels = vec![16; 128 * 32];
1587 let start = pixels.as_ptr();
1588 let frame = captured(&mut pixels, ticks);
1589 let video = AvSyncVideo::new(&frame).unwrap();
1590 assert_eq!(video.timestamp().ticks(), ticks);
1591 let descriptor = video.descriptor();
1592 assert_eq!(descriptor.timestamp, ticks);
1593 assert_eq!(descriptor.p_data.cast_const(), start);
1594 assert!(format!("{video:?}").contains("timestamp"));
1595
1596 let owned = frame.to_owned();
1598 let video = AvSyncVideo::new(&owned).unwrap();
1599 assert_eq!(video.timestamp().ticks(), ticks);
1600 assert_eq!(video.descriptor().timestamp, ticks);
1601 assert_eq!(
1602 video.descriptor().p_data.cast_const(),
1603 owned.data().as_ptr()
1604 );
1605 }
1606 }
1607
1608 #[test]
1611 fn avsync_accepts_owned_and_borrowed_planar_444_without_a_send_gate() {
1612 use crate::{
1613 capture::{CaptureStrategy, Guard, VideoKind},
1614 PixelFormat, ReceiverOptions,
1615 };
1616 let Some(ndi) = crate::test_support::advanced_ndi() else {
1617 return;
1618 };
1619 let receiver = Receiver::new(&ndi, &ReceiverOptions::disconnected()).unwrap();
1620 let mut sync = AvSync::new(receiver).unwrap();
1621 for format in [
1622 PixelFormat::Na48,
1623 PixelFormat::Nb48,
1624 PixelFormat::Na4g,
1625 PixelFormat::Nb4g,
1626 ] {
1627 let backing = VideoFrame::builder()
1628 .resolution(64, 32)
1629 .pixel_format(format)
1630 .build()
1631 .unwrap();
1632 let mut raw = backing.as_test_raw();
1633 raw.timestamp = 1234;
1634 let captured = VideoKind::make_ref(unsafe {
1637 Guard::with_test_free(ptr::null_mut(), raw, |_, _| {})
1638 })
1639 .unwrap();
1640 let owned = captured.to_owned();
1641 for video in [
1642 AvSyncVideo::new(&captured).unwrap(),
1643 AvSyncVideo::new(&owned).unwrap(),
1644 ] {
1645 assert_eq!(video.descriptor().FourCC, raw.FourCC);
1646 for result in [
1647 sync.synchronize(video, AvSyncRequest::automatic()),
1648 sync.split()
1649 .0
1650 .synchronize(video, AvSyncRequest::automatic()),
1651 ] {
1652 assert!(
1653 matches!(result, Ok(AvSyncOutcome::NoAudioStream)),
1654 "{format:?}: {result:?}"
1655 );
1656 }
1657 }
1658 }
1659 }
1660
1661 #[test]
1665 fn avsync_matches_live_audio_for_owned_and_borrowed_planar_frames() {
1666 use crate::{
1667 capture::{CaptureStrategy, VideoKind},
1668 Finder, FinderOptions, PixelFormat, ReceiverOptions, Sender, SenderOptions,
1669 SourceAddress,
1670 };
1671 use std::{
1672 sync::atomic::{AtomicBool, Ordering},
1673 time::{Duration, Instant},
1674 };
1675 let Some(ndi) = crate::test_support::advanced_ndi() else {
1676 return;
1677 };
1678 let sender = Sender::new(
1679 &ndi,
1680 &SenderOptions::new(crate::test_support::unique_name("planar AV-sync"))
1681 .clock_video(true)
1682 .clock_audio(false),
1683 )
1684 .unwrap();
1685 let name = sender.source().unwrap().name().to_owned();
1686 let finder = Finder::new(&ndi, &FinderOptions::new().extra_ips(["127.0.0.1"])).unwrap();
1687 let deadline = Instant::now() + Duration::from_secs(15);
1688 let source = loop {
1689 if let Some((source, port)) = finder
1690 .current_sources()
1691 .unwrap()
1692 .into_iter()
1693 .filter(|source| source.name() == name)
1694 .find_map(|source| {
1695 source
1696 .address()
1697 .and_then(|address| address.port())
1698 .map(|port| (source, port))
1699 })
1700 {
1701 break source
1702 .with_address(SourceAddress::new(format!("127.0.0.1:{port}")).unwrap());
1703 }
1704 assert!(
1705 Instant::now() < deadline,
1706 "local planar AV-sync sender not discovered"
1707 );
1708 std::thread::sleep(Duration::from_millis(20));
1709 };
1710 let sync =
1711 AvSync::new(Receiver::new(&ndi, &ReceiverOptions::new(source)).unwrap()).unwrap();
1712 let video = VideoFrame::builder()
1713 .resolution(64, 32)
1714 .frame_rate(FrameRate::new(30, 1).unwrap())
1715 .build()
1716 .unwrap();
1717 let audio = AudioFrame::builder()
1718 .sample_rate(48_000)
1719 .num_channels(2)
1720 .num_samples(1600)
1721 .build()
1722 .unwrap();
1723 let stop = AtomicBool::new(false);
1724 std::thread::scope(|scope| {
1725 let _stop = crate::test_support::StopOnDrop(&stop);
1726 scope.spawn(|| {
1727 while !stop.load(Ordering::Acquire) {
1728 sender.send_video(&video).unwrap();
1729 sender.send_audio(&audio);
1730 }
1731 });
1732 for format in [
1733 PixelFormat::Na48,
1734 PixelFormat::Nb48,
1735 PixelFormat::Na4g,
1736 PixelFormat::Nb4g,
1737 ] {
1738 let backing = VideoFrame::builder()
1739 .resolution(64, 32)
1740 .frame_rate(FrameRate::new(30, 1).unwrap())
1741 .pixel_format(format)
1742 .build()
1743 .unwrap();
1744 for owned in [false, true] {
1745 let deadline = Instant::now() + Duration::from_secs(15);
1746 loop {
1747 assert!(
1748 Instant::now() < deadline,
1749 "no audio for {format:?}, owned={owned}"
1750 );
1751 let Some(received) = sync
1752 .receiver()
1753 .capture_video_ref(Duration::from_millis(100))
1754 .unwrap()
1755 else {
1756 continue;
1757 };
1758 let mut raw = backing.as_test_raw();
1759 raw.timestamp = received
1760 .timestamp()
1761 .expect("native sender timestamp")
1762 .ticks();
1763 raw.timecode = received.timecode().ticks();
1764 let captured = VideoKind::make_ref(unsafe {
1767 Guard::with_test_free(ptr::null_mut(), raw, |_, _| {})
1768 })
1769 .unwrap();
1770 let copied = captured.to_owned();
1771 let video = if owned {
1772 AvSyncVideo::new(&copied)
1773 } else {
1774 AvSyncVideo::new(&captured)
1775 }
1776 .unwrap();
1777 match sync.synchronize(video, AvSyncRequest::automatic()).unwrap() {
1778 AvSyncOutcome::Audio { frame, .. } => {
1779 assert_eq!(
1780 (frame.sample_rate(), frame.num_channels()),
1781 (48_000, 2)
1782 );
1783 assert!(frame.num_samples() > 0);
1784 break;
1785 }
1786 AvSyncOutcome::NoAudioStream
1787 | AvSyncOutcome::NoMatchingSamples
1788 | AvSyncOutcome::Empty { .. } => {}
1789 other => panic!(
1790 "unexpected outcome for {format:?}, owned={owned}: {other:?}"
1791 ),
1792 }
1793 }
1794 }
1795 }
1796 });
1797 }
1798
1799 #[test]
1800 fn avsync_descriptors_fit_owned_copies_of_padded_sources() {
1801 for (format, stride) in [
1802 (crate::PixelFormat::Bgra, 512),
1803 (crate::PixelFormat::Uyvy, 256),
1804 (crate::PixelFormat::P216, 256),
1805 ] {
1806 let planes = if format == crate::PixelFormat::P216 {
1807 2
1808 } else {
1809 1
1810 };
1811 let storage = vec![0u8; stride * 32 * planes];
1812 let borrowed = crate::BorrowedVideoFrame::builder(&storage, 64, 32, format)
1813 .line_stride_bytes(stride)
1814 .build()
1815 .unwrap();
1816 let frame = crate::VideoSource::to_owned(&borrowed);
1817 let raw = video_sealed::Sealed::descriptor(&frame);
1818 crate::frames::descriptor_tests::assert_extent(
1819 &raw,
1820 frame.data().as_ptr(),
1821 frame.data().len() + frame.tail_room(),
1822 );
1823 }
1824 }
1825
1826 #[test]
1828 fn av_sync_is_send_and_unwind_safe() {
1829 fn traits<T: Send + std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
1830 traits::<AvSync>();
1831 }
1832
1833 #[test]
1835 fn genlock_is_send_and_unwind_safe() {
1836 fn traits<T: Send + std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
1837 traits::<Genlock>();
1838 }
1839
1840 #[test]
1842 fn returned_audio_is_released_whatever_the_result() {
1843 let released = Cell::new(0);
1844 let samples = AudioFrame::builder().num_samples(2).build().unwrap();
1845 for status in [
1846 Synchronized::Matched,
1847 Synchronized::Adjusted,
1848 Synchronized::NoAudioStream,
1849 Synchronized::NoMatchingSamples,
1850 Synchronized::FormatChanged,
1851 Synchronized::InternalError,
1852 Synchronized::Unknown(99),
1853 ] {
1854 let before = released.get();
1855 let guard = test_guard(samples.audio_descriptor(), &released);
1856 let result = outcome(status, guard);
1857 if matches!(status, Synchronized::Matched | Synchronized::Adjusted) {
1858 assert_eq!(released.get(), before);
1859 } else {
1860 assert_eq!(released.get(), before + 1);
1861 }
1862 drop(result);
1863 assert_eq!(released.get(), before + 1);
1864 }
1865 let before = released.get();
1867 assert!(outcome(Synchronized::Matched, test_guard(descriptor(), &released)).is_err());
1868 assert_eq!(released.get(), before + 1);
1869 let raw = NDIlib_audio_frame_v3_t {
1871 p_metadata: c"<empty/>".as_ptr(),
1872 ..descriptors::audio_frame()
1873 };
1874 let before = released.get();
1875 assert!(matches!(
1876 outcome(Synchronized::Matched, test_guard(raw, &released)).unwrap(),
1877 AvSyncOutcomeRef::Empty { .. }
1878 ));
1879 assert_eq!(released.get(), before + 1);
1880 drop(test_guard(NDIlib_audio_frame_v3_t::default(), &released));
1881 assert_eq!(released.get(), before + 1);
1882 }
1883
1884 fn test_guard<'a>(
1885 raw: NDIlib_audio_frame_v3_t,
1886 released: &'a Cell<usize>,
1887 ) -> Guard<'a, AvSyncAudioFree> {
1888 unsafe {
1889 Guard::<AvSyncAudioFree>::with_test_free(
1890 AvSyncAudioInstance::Synthetic(released),
1891 raw,
1892 |instance, raw| {
1893 #[cfg(ndi_has_advanced_av_sync)]
1894 let AvSyncAudioInstance::Synthetic(released) = instance
1895 else {
1896 unreachable!()
1897 };
1898 #[cfg(not(ndi_has_advanced_av_sync))]
1899 let AvSyncAudioInstance::Synthetic(released) = instance;
1900 if !raw.p_data.is_null() || !raw.p_metadata.is_null() {
1901 (*released).set((*released).get() + 1);
1902 }
1903 },
1904 )
1905 }
1906 }
1907
1908 #[test]
1909 fn borrowed_avsync_audio_reuses_owned_storage_without_allocating() {
1910 let source = AudioFrame::builder()
1911 .num_samples(16)
1912 .metadata("<audio/>")
1913 .build()
1914 .unwrap();
1915 let released = Cell::new(0);
1916 let result = outcome(
1917 Synchronized::Matched,
1918 test_guard(source.audio_descriptor(), &released),
1919 )
1920 .unwrap();
1921 let AvSyncOutcomeRef::Audio { frame, .. } = &result else {
1922 panic!("matched samples")
1923 };
1924 assert_eq!(frame.data(), Some(source.data()));
1925 let mut destination = frame.to_owned();
1926 let ((), allocations) =
1927 crate::test_alloc::allocation_count(|| frame.copy_into(&mut destination));
1928 assert_eq!(allocations, 0);
1929 assert_eq!(destination.data(), source.data());
1930 assert_eq!(destination.metadata(), source.metadata());
1931 assert_eq!(released.get(), 0);
1932 drop(result);
1933 assert_eq!(released.get(), 1);
1934 }
1935
1936 #[test]
1937 fn avsync_audio_normalizes_its_measured_unknown_timestamp_marker() {
1938 let source = AudioFrame::builder().num_samples(2).build().unwrap();
1939 let released = Cell::new(0);
1940 for timestamp in [0, NDIlib_recv_timestamp_undefined, -1, 12345] {
1941 let raw = NDIlib_audio_frame_v3_t {
1942 timestamp,
1943 ..source.audio_descriptor()
1944 };
1945 let result = outcome(Synchronized::Matched, test_guard(raw, &released)).unwrap();
1946 let AvSyncOutcomeRef::Audio { frame, .. } = result else {
1947 panic!("matched samples")
1948 };
1949 let expected = (timestamp != 0 && timestamp != NDIlib_recv_timestamp_undefined)
1950 .then_some(timestamp);
1951 assert_eq!(frame.timestamp().map(ReceivedTimestamp::ticks), expected);
1952 let raw = frame.to_owned().audio_descriptor();
1953 assert_eq!(
1954 raw.timestamp,
1955 expected.unwrap_or(NDIlib_recv_timestamp_undefined)
1956 );
1957 }
1958 }
1959
1960 #[cfg(ndi_has_advanced_av_sync)]
1963 #[test]
1964 fn avsync_native_unknown_timestamp_overwrites_the_request() {
1965 use crate::frames::HoldsDescriptor;
1966 let Some(ndi) = crate::test_support::advanced_ndi() else {
1967 return;
1968 };
1969 let receiver = Receiver::new(&ndi, &crate::ReceiverOptions::disconnected()).unwrap();
1970 let sync = AvSync::new(receiver).unwrap();
1971 let resource = sync.inner.resource();
1972 let (handle, table) = (resource.handle, &resource.table);
1973 let mut raw = AvSyncRequest::automatic().raw();
1974 raw.timestamp = 12345;
1975 let status = unsafe {
1976 table
1977 .named()
1978 .NDIlib_avsync_synchronize(handle.0, ptr::null(), &mut raw)
1979 };
1980 assert_eq!(status.into_value(), crate::sys::advanced_bindings::NDIlib_avsync_ret_e_NDIlib_avsync_ret_no_audio_stream_received);
1981 assert_eq!(raw.timestamp, 0);
1982 let guard = unsafe { Guard::<AvSyncAudioFree>::new(resource, raw) };
1983 assert_eq!(guard.normalize_timestamp(raw.timestamp), None);
1984 assert!(matches!(
1985 outcome(Synchronized::NoAudioStream, guard).unwrap(),
1986 AvSyncOutcomeRef::NoAudioStream
1987 ));
1988 }
1989}
1990
1991#[cfg(all(ndi_test_frame_source, ndi_has_advanced_av_sync))]
1992#[path = "../../tests/ui/internal/av_frame_source.rs"]
1993mod frame_source_contract;