Skip to main content

grafton_ndi/advanced/
sync.rs

1//! Audio matched to video timestamps, and clocks locked to a reference source.
2
3#[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/// What audio an [`AvSync::synchronize`] call asks for.
40///
41/// AVSync selects the samples that belong to a video frame; it does not
42/// resample. A request that names a sample rate states the rate its sample
43/// count was computed for, and a source at another rate is reported as
44/// [`AvSyncOutcome::FormatChanged`] rather than given audio. The audio always
45/// has the source's own channels.
46#[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    /// Take whatever audio belongs to the video frame, at the source's rate.
54    pub fn automatic() -> Self {
55        Self::default()
56    }
57
58    /// State the sample rate a request is computed for, and ask for an exact
59    /// number of samples per channel. Each `None` leaves that choice to the
60    /// SDK.
61    ///
62    /// With a video frame, the SDK returns the number asked for when it is
63    /// close to the audio that belongs to the frame; otherwise it returns
64    /// that audio and reports the count as adjusted.
65    ///
66    /// # Errors
67    ///
68    /// [`Error::InvalidInput`] with a shared [`crate::InputDefect::Layout`]
69    /// cause when a value is outside `1..=i32::MAX`, or a single channel's
70    /// sample payload exceeds 64 MiB.
71    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        // A frame has at least one channel.
88        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    /// The sample rate in hertz the request was computed for, if stated.
97    pub fn sample_rate(self) -> Option<u32> {
98        self.sample_rate.map(SdkQuantity::get)
99    }
100
101    /// The requested samples per channel, if any.
102    pub fn num_samples(self) -> Option<u32> {
103        self.num_samples.map(SdkQuantity::get)
104    }
105
106    /// The descriptor the SDK reads the request from and writes the audio to.
107    ///
108    /// The SDK reads zero as "not specified". It returns planar
109    /// floating-point audio and leaves the format as it found it, so the
110    /// descriptor must already name that format.
111    #[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        // Keep the SDK's default channel field: it does not constrain the
115        // source's channels, even when a rate is stated. The native regression
116        // `avsync_states_rates_for_non_stereo_sources` pins this for mono and
117        // four-channel sources on Advanced 6.3.2 and 6.4.
118        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/// The result of one [`AvSync::synchronize`] call.
127///
128/// These are successful audio or expected no-audio states. Native failures
129/// and unknown statuses are returned through [`crate::Error`].
130#[derive(Clone, Debug)]
131#[non_exhaustive]
132pub enum AvSyncOutcome {
133    /// The audio that belongs to the video frame, owned by the caller.
134    Audio {
135        /// The audio.
136        frame: AudioFrame,
137        /// The SDK returned a different number of samples than requested, to
138        /// keep a source whose audio and video clocks drift in sync.
139        samples_adjusted: bool,
140    },
141    /// The synchronization succeeded and there were no samples to return.
142    Empty {
143        /// As for [`Audio`](Self::Audio).
144        samples_adjusted: bool,
145    },
146    /// The source's audio is not at the sample rate the request stated.
147    /// Nothing was returned; ask again for the reported rate, or
148    /// automatically.
149    FormatChanged {
150        /// The source's sample rate in hertz.
151        sample_rate: u32,
152        /// The source's channel count.
153        num_channels: u32,
154    },
155    /// The source currently sends no audio.
156    NoAudioStream,
157    /// The source sends audio, but none of it matches the video frame's time.
158    NoMatchingSamples,
159}
160
161/// Audio borrowed from an [`AvSync`] synchronizer.
162///
163/// The samples and metadata remain in the SDK until this reference is dropped.
164/// It implements [`crate::AudioSource`] and can be sent or converted in place;
165/// `to_owned` retains a copy and `copy_into` reuses owned storage. Like
166/// FrameSync audio references, it stays on its capture thread (`!Send`, `!Sync`).
167/// Several references may be retained across later synchronizations and freed
168/// in any order. The synchronizer remains borrowed until all are released.
169pub struct AvSyncAudioRef<'a> {
170    pub(crate) inner: ValidatedAudio<Guard<'a, AvSyncAudioFree>>,
171}
172
173/// A synchronization outcome whose audio remains borrowed from the SDK.
174#[derive(Debug)]
175#[non_exhaustive]
176pub enum AvSyncOutcomeRef<'a> {
177    /// Matched samples, retained until `frame` is dropped.
178    Audio {
179        /// The borrowed samples, timing and metadata.
180        frame: AvSyncAudioRef<'a>,
181        /// Whether the SDK adjusted the requested sample count.
182        samples_adjusted: bool,
183    },
184    /// Synchronization succeeded without samples.
185    Empty {
186        /// Whether the SDK adjusted the requested sample count.
187        samples_adjusted: bool,
188    },
189    /// The source's format differs from the request.
190    FormatChanged {
191        /// The current sample rate in hertz.
192        sample_rate: u32,
193        /// The current channel count.
194        num_channels: u32,
195    },
196    /// The source currently sends no audio.
197    NoAudioStream,
198    /// No audio matches the requested video timestamp.
199    NoMatchingSamples,
200}
201
202impl AvSyncOutcomeRef<'_> {
203    /// Copy matched audio into an independently owned outcome. Status-only
204    /// outcomes allocate nothing.
205    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/// How the SDK classified one synchronization.
231#[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
243/// A native synchronizer, destroyed when dropped.
244pub(crate) struct AvSyncKind {
245    #[cfg(ndi_has_advanced_av_sync)]
246    handle: AvSyncInstance,
247    table: crate::runtime::Bound<AvSyncTable, std::sync::Arc<ReceiverCore>>,
248    // Keep the public Send + !Sync contract even without native declarations.
249    _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// SAFETY: this resource owns the synchronizer and its bound table retains the
258// creating receiver/runtime. The handle and release entry point are read from
259// that resource, and its borrow prevents destruction before the frame is freed.
260#[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// The bound table uses the receiver lease the resource already retained:
275// one handle, one table pointer and one receiver Arc, with no separate Ndi.
276#[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// SAFETY: a synchronizer belongs to no thread. Processing.NDI.AVSync.h and the
289// Advanced SDK manual (25.6.2) have it created from a receiver, used for as
290// long as it is needed and destroyed before that receiver, and state no
291// thread for any of its functions. Moving the handle changes only which
292// thread makes those calls. AvResource retains the receiver core through
293// destruction, and AvSync is not Sync, so its calls never overlap.
294// `an_avsync_moves_between_threads` in tests/advanced_runtime.rs creates,
295// synchronizes and destroys one on three threads against each runtime used.
296#[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
306// SAFETY: adoption retains the receiver from which this handle was created.
307// The view borrows the same resource and exposes no ownership transition.
308unsafe 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            // SAFETY: Resource retains the creating receiver and runtime, and
315            // invokes this destruction once for the uniquely owned handle.
316            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
332/// Audio matched to the timestamps of a receiver's video.
333///
334/// The synchronizer takes over the receiver's audio, so it owns the receiver:
335/// capture video through [`receiver`](Self::receiver), then ask
336/// [`synchronize`](Self::synchronize) for the audio that belongs to each
337/// frame. It matches audio to the frame's timestamp, so the frame is given
338/// as an [`AvSyncVideo`], which only a frame with a timestamp can be; the
339/// frame is read as it was captured, without copying it.
340/// [`into_receiver`](Self::into_receiver) returns the receiver.
341///
342/// The receiver is lent in the [`AvSyncAttached`] mode, with its video and
343/// metadata capture and every receiver control. Its audio capture and event
344/// polling are unavailable; use the capability, source-name and connection
345/// queries described on [`AvSyncAttached`].
346/// [`AvSyncOutcome`] distinguishes no audio stream, no samples matching a
347/// video's time, a changed format and successful output. These outcomes do
348/// not replace monitoring progress of the media the application expects;
349/// see the [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
350///
351/// # Threading
352///
353/// An `AvSync` is [`Send`] but not [`Sync`]. It can be created on one thread
354/// and synchronize and be dropped on another, but it synchronizes one call at
355/// a time: the SDK does not document two synchronizations of one
356/// synchronizer running at once. The receiver it lends is `Sync`, so scoped
357/// threads can capture video or metadata or reconnect through it
358/// while the thread that holds the `AvSync` synchronizes.
359///
360/// # Examples
361///
362/// ```no_run
363/// use std::time::Duration;
364/// use grafton_ndi::{
365///     advanced::{AvSync, AvSyncOutcome, AvSyncRequest, AvSyncVideo},
366///     Receiver, ReceiverOptions, Ndi,
367/// };
368///
369/// # fn main() -> Result<(), grafton_ndi::Error> {
370/// let ndi = Ndi::new()?;
371/// let receiver = Receiver::new(&ndi, &ReceiverOptions::disconnected())?;
372/// let sync = AvSync::new(receiver)?;
373///
374/// // The frame stays in the SDK's buffer: nothing is copied.
375/// if let Some(captured) = sync.receiver().capture_video_ref(Duration::from_secs(1))? {
376///     // The SDK may supply a timestamp for a captured frame.
377///     if let Some(video) = AvSyncVideo::new(&captured) {
378///         if let AvSyncOutcome::Audio { frame, .. } =
379///             sync.synchronize(video, AvSyncRequest::automatic())?
380///         {
381///             println!("{} samples belong to this frame", frame.num_samples());
382///         }
383///     }
384/// }
385/// # Ok(())
386/// # }
387/// ```
388pub 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    /// Start synchronizing the audio of `receiver`.
402    ///
403    /// # Errors
404    ///
405    /// Returns the receiver, untouched, with
406    /// [`Error::UnsupportedCapability`] without an Advanced runtime (or in a
407    /// build without the Advanced SDK), or [`Error::NativeOperationFailed`]
408    /// when the SDK creates no synchronizer.
409    #[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            // SAFETY: this creates a uniquely owned synchronizer from the
419            // supplied receiver, using that receiver's runtime table.
420            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    /// The receiver this holds, in the [`AvSyncAttached`] mode: its video and
435    /// metadata capture and the controls every receiver has:
436    /// tally, PTZ, statistics, upstream metadata, keyframe requests, delays,
437    /// connecting, reconnecting and source-name changes.
438    ///
439    /// Event polling is unavailable because native synchronization can consume
440    /// status notifications. Query `ptz().is_supported()`, `web_control_url()`
441    /// or Advanced KVM's `is_supported()` for capabilities, use
442    /// `wait_for_source_name_change()` for the connected source, and
443    /// `is_connected()` or `connection_stats()` for connection state.
444    ///
445    /// A video frame captured through it can be handed to
446    /// [`synchronize`](Self::synchronize) as it is, through [`AvSyncVideo`].
447    /// Its own audio capture does not exist in this mode, because the
448    /// synchronizer takes the audio:
449    ///
450    /// ```compile_fail,E0277
451    /// use grafton_ndi::advanced::AvSync;
452    /// fn capture(sync: &AvSync) {
453    ///     let _ = sync.receiver().capture_audio(std::time::Duration::ZERO);
454    /// }
455    /// ```
456    ///
457    /// The synchronizer retains this receiver's native core through its own
458    /// destruction. [`controls`](Self::controls) lends exclusive stream
459    /// controls and KVM; [`split`](Self::split) keeps synchronization usable
460    /// while a KVM session holds the receiver borrow.
461    pub fn receiver(&self) -> &Receiver<AvSyncAttached> {
462        self.inner.receiver()
463    }
464
465    /// Borrow exclusive receiver controls without permitting receiver replacement.
466    /// This allocates nothing and makes no SDK call. Use [`Self::split`] to
467    /// synchronize while a KVM session retains the receiver borrow.
468    pub fn controls(&mut self) -> ReceiverControls<'_, AvSyncAttached> {
469        self.inner.controls()
470    }
471
472    /// Lend synchronization and exclusive receiver controls independently.
473    ///
474    /// Both views borrow this owner without allocating or making SDK calls.
475    /// A session from the controls lends the receiver for video/metadata
476    /// capture while the synchronization view continues matching audio.
477    /// Release held inputs before changing source, and drop both views before
478    /// recovering the receiver.
479    pub fn split(&mut self) -> (AvSyncCapture<'_>, ReceiverControls<'_, AvSyncAttached>) {
480        self.inner.split()
481    }
482
483    /// Stop synchronizing and return the receiver, with its own audio
484    /// capture again.
485    pub fn into_receiver(self) -> Receiver {
486        self.inner.into_receiver()
487    }
488
489    /// Fetch the audio that belongs to `video`.
490    ///
491    /// The audio is matched to the frame's timestamp, which [`AvSyncVideo`]
492    /// guarantees the frame has; [`queued_audio`](Self::queued_audio) takes
493    /// the queued audio without a frame. The frame is read in place: a
494    /// [`VideoFrameRef`] captured through [`receiver`](Self::receiver) is
495    /// handed to the SDK as the SDK delivered it, and an owned copy of one as
496    /// it is, so no pixels are copied. One call makes one native request: a
497    /// changed format or missing audio is reported, never retried or
498    /// converted. Returning samples allocates their owned buffer, plus metadata
499    /// storage when present. [`Self::synchronize_ref`] borrows those samples
500    /// directly and offers allocation-free copying into reusable storage.
501    ///
502    /// Matching uses the video's timestamp and geometry, independently of
503    /// whether this runtime can send its pixel format. Owned and borrowed
504    /// planar 4:4:4 frames therefore follow the same rule on older runtimes.
505    ///
506    /// One call synchronizes at a time, on the thread that holds this
507    /// `AvSync`, which is not `Sync`. Other threads may meanwhile capture
508    /// video or metadata or use the controls through the receiver it lends.
509    /// Connection changes may overlap synchronization, as the native overlap
510    /// tests also exercise for [`FrameSync`](crate::FrameSync).
511    ///
512    /// # Errors
513    ///
514    /// [`Error::InvalidFrame`] when the audio the SDK returned fails
515    /// validation, [`Error::NativeOperationFailed`] when the SDK reports an
516    /// internal error, and [`Error::UnexpectedSdkResult`] for an unknown
517    /// status or a format change to a sample rate or channel count that is
518    /// not positive.
519    #[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    /// Borrow matched audio without allocating or copying samples. Timing,
529    /// statuses and errors are as for [`Self::synchronize`]. The returned
530    /// frame keeps this synchronizer borrowed until it is released.
531    #[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    /// Fetch whatever audio is currently queued, matched to no video frame.
541    ///
542    /// With [`AvSyncRequest::automatic`] this takes all the queued audio;
543    /// with a sample count, it requests that many samples. Inspect the returned
544    /// frame's sample count: a depleted queue can return a shorter tail even
545    /// when the SDK does not report `samples_adjusted`. Otherwise as for
546    /// [`synchronize`](Self::synchronize).
547    ///
548    /// # Errors
549    ///
550    /// As for [`synchronize`](Self::synchronize).
551    #[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    /// Borrow queued audio without copying; see [`Self::queued_audio`] for
557    /// request semantics and errors.
558    #[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    /// The synchronization view of this owner, which `&self` keeps on its
564    /// thread for as long as it is borrowed.
565    fn capture(&self) -> AvSyncCapture<'_> {
566        self.inner.capture()
567    }
568}
569
570/// Synchronization access lent by [`AvSync::split`].
571///
572/// The view borrows only the synchronizer, so a KVM session can hold the
573/// independently lent receiver while this continues matching audio to video.
574/// Creating or copying it allocates nothing and makes no SDK call. Like a
575/// shared `&AvSync`, it is neither `Send` nor `Sync`: overlapping native
576/// synchronizations are not documented as safe. Borrowed results retain the
577/// synchronizer's borrow even when this view is dropped.
578#[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    /// Match audio to `video`; see [`AvSync::synchronize`] for timing,
596    /// allocation costs, format changes and no-audio results.
597    ///
598    /// # Errors
599    ///
600    /// As for [`AvSync::synchronize`].
601    #[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    /// Borrow matched audio; see [`AvSync::synchronize_ref`] for ownership,
611    /// timing and errors. The result borrows the synchronizer itself.
612    #[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    /// Fetch the queued audio; see [`AvSync::queued_audio`].
622    ///
623    /// # Errors
624    ///
625    /// As for [`AvSync::synchronize`].
626    #[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    /// Borrow queued audio; see [`AvSync::queued_audio_ref`].
632    #[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    /// One native synchronization: for `video`, or with `None` for the
638    /// queued audio.
639    fn request(
640        &self,
641        _video: Option<AvSyncVideo<'_>>,
642        _request: AvSyncRequest,
643    ) -> Result<AvSyncOutcomeRef<'a>> {
644        native!(AvSync, self.resource.table => {
645            // A copy of the frame's descriptor, pointing into the frame's own
646            // buffers, which the borrow keeps allocated for the call, and
647            // carrying the timestamp `AvSyncVideo::new` checked.
648            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                // SAFETY: the synchronizer is live, and so is the receiver it
653                // reads, whose owner this view borrows. The video
654                // descriptor (if any) describes a frame borrowed for the call: an
655                // owned frame's buffers, or the SDK's own descriptor of a captured
656                // frame, whose guard keeps its buffers allocated. The SDK takes
657                // it as a const reference and only reads it
658                // (Processing.NDI.AVSync.h). The audio descriptor is writable.
659                //
660                // No other synchronization of this synchronizer runs, which the
661                // header does not document as safe: this takes `&self`, and an
662                // AvSync is not Sync. Captures through the lent
663                // receiver may run on other threads meanwhile. The synchronizer
664                // takes the receiver's audio as an audio capture of it would
665                // (Processing.NDI.AVSync.h), and the SDK lets video, audio and
666                // metadata be captured from one receiver on separate threads at
667                // once (Processing.NDI.Recv.h). The AvSyncAttached mode has no
668                // audio capture, so the synchronizer is the only audio consumer.
669                //
670                // Connection changes may overlap raw receiver and synchronizer
671                // captures. The native observations beside receiver::CaptureLock
672                // and tests/receiver_connect_overlap_sdk.rs cover both AV sync
673                // and FrameSync beside local connection changes; remote SDK
674                // connection requests likewise cannot be serialized by Rust.
675                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            // SAFETY: the synchronizer and runtime remain borrowed through
703            // the result; its guard returns this descriptor exactly once.
704            let guard = unsafe { Guard::new(self.resource, audio) };
705            outcome_with_call(status, guard)
706        })
707    }
708}
709
710/// Validate one synchronization while its guard owns every returned buffer.
711/// The guard retains every non-null sample or metadata extent, including
712/// empty request descriptors returned for statuses without audio.
713#[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                // The format of an empty result is not reported.
723                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    /// What [`AvSyncVideo`](super::AvSyncVideo) reads from a frame. The
780    /// supertraits let a borrowed frame cross threads as the frame itself can.
781    pub trait Sealed: Sync + std::panic::RefUnwindSafe {
782        /// A copy of the frame's SDK descriptor, which points into buffers
783        /// that the borrow of `self` keeps allocated and unchanged.
784        fn descriptor(&self) -> NDIlib_video_frame_v2_t;
785
786        /// The timestamp carried by the received frame, when present.
787        fn receive_timestamp(&self) -> Option<ReceivedTimestamp>;
788    }
789}
790
791/// A video frame [`AvSyncVideo::new`] accepts: a [`VideoFrameRef`] captured
792/// from a receiver, such as the one [`AvSync::receiver`] lends, or an owned
793/// [`VideoFrame`].
794///
795/// The trait is sealed; those two are the only video frames it covers.
796pub 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/// A video frame with a received timestamp for [`AvSync::synchronize`]
823/// to match audio to.
824///
825/// AV sync selects the audio whose timestamps belong to a video frame's
826/// timestamp (Advanced SDK manual, 25.6.1), so a frame without one gives it
827/// nothing to match. [`new`](Self::new) checks the timestamp once, and only
828/// this type is accepted, so synchronization is never given a frame without
829/// one. A captured frame carries the source-dependent timestamp supplied by
830/// the SDK, and an owned copy keeps it. A frame the application builds
831/// has none.
832///
833/// The value borrows the frame, whose pixels the SDK reads in place: making
834/// it copies nothing and makes no SDK call. Like the frames it borrows, it is
835/// `Send` and `Sync`.
836///
837/// # Examples
838///
839/// ```
840/// use grafton_ndi::{advanced::AvSyncVideo, VideoFrame};
841///
842/// # fn main() -> Result<(), grafton_ndi::Error> {
843/// // A frame the application builds was never sent, so it has no timestamp.
844/// let built = VideoFrame::builder().resolution(64, 32).build()?;
845/// assert!(AvSyncVideo::new(&built).is_none());
846/// # Ok(())
847/// # }
848/// ```
849#[derive(Clone, Copy)]
850pub struct AvSyncVideo<'a> {
851    // The borrow is held in every build, so the type has the same lifetime
852    // and auto traits in all of them; only the native synchronization reads
853    // the frame, and a build without the AV sync declarations has none.
854    #[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    /// Wrap a frame that carries a received timestamp.
864    ///
865    /// Returns `None` for a frame without one: a frame the application
866    /// built, or a captured frame with an undefined timestamp.
867    pub fn new<F: AvSyncFrame>(frame: &'a F) -> Option<Self> {
868        Some(Self {
869            timestamp: frame.receive_timestamp()?,
870            frame,
871        })
872    }
873
874    /// The source-dependent timestamp supplied by the SDK.
875    pub fn timestamp(&self) -> ReceivedTimestamp {
876        self.timestamp
877    }
878
879    /// The frame's descriptor, carrying the timestamp [`Self::new`] checked.
880    #[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/// What paced a completed [`VideoClock::wait`] or [`AudioClock::wait`].
898#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
899#[non_exhaustive]
900pub enum ClockSource {
901    /// The reference source's clock.
902    ReferenceSignal,
903    /// The local system clock, because no reference signal is being received.
904    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
918/// A native genlock, destroyed when dropped.
919struct 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// SAFETY: a genlock belongs to no thread. Processing.NDI.Genlock.h and the
932// Advanced SDK manual (25.5) state no thread for creating, connecting,
933// querying or destroying one, and let its two waits run on separate threads,
934// neither of which need be the one that created it. In the 6.3.2 and 6.4
935// Linux x86_64 runtimes, `NDIlib_genlock_connect` hands the source to
936// `NDIlib_recv_connect` on a receiver the genlock owns, a receiver operation
937// that this crate already makes from any thread. Moving the handle changes
938// only which thread makes the calls. GenResource retains its runtime, a
939// `Genlock` is not Sync, and connecting and destroying take it exclusively,
940// so neither overlaps a wait or a query. `a_genlock_moves_between_threads` in
941// tests/advanced_runtime.rs creates, connects, waits on and destroys one on
942// five threads against each runtime the tests use.
943#[cfg(ndi_has_advanced_genlock)]
944unsafe impl Send for GenlockInstance {}
945
946// SAFETY: the SDK allows the video wait and the audio wait to run on separate
947// threads at the same time. Those are the only operations that reach this
948// from another thread: one non-cloneable clock exists for each, and while the
949// clocks exist they borrow the genlock exclusively, so neither `is_active`,
950// reached through a `Genlock`, which is not Sync, nor connecting or
951// destroying overlaps them.
952#[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        // SAFETY: the handle was created by this table and is destroyed once.
963        // This resource still owns the source descriptor and configuration here.
964        native!(Genlock, self.table => unsafe { self.table.NDIlib_genlock_destroy(self.handle.0) });
965    }
966}
967
968/// Optional reference source and native configuration for a [`Genlock`].
969///
970/// An empty configuration starts on the system clock with the SDK defaults.
971#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
972pub struct GenlockOptions {
973    source: Option<Source>,
974    config: Option<AdvancedConfig>,
975}
976
977impl GenlockOptions {
978    /// Follow the system clock with the SDK's default configuration.
979    pub fn new() -> Self {
980        Self::default()
981    }
982
983    /// Follow `source` when the genlock is created.
984    #[must_use]
985    pub fn source(mut self, source: Source) -> Self {
986        self.source = Some(source);
987        self
988    }
989
990    /// The configured reference source, before any genlock is created.
991    pub fn configured_source(&self) -> Option<&Source> {
992        self.source.as_ref()
993    }
994
995    /// Restore the default system-clock source.
996    #[must_use]
997    pub fn clear_source(mut self) -> Self {
998        self.source = None;
999        self
1000    }
1001
1002    /// Use this native JSON configuration at creation.
1003    #[must_use]
1004    pub fn config(mut self, config: AdvancedConfig) -> Self {
1005        self.config = Some(config);
1006        self
1007    }
1008
1009    /// The exact configuration given to [`Self::config`].
1010    pub fn configured_config(&self) -> Option<&AdvancedConfig> {
1011        self.config.as_ref()
1012    }
1013
1014    /// Restore the SDK's default native configuration.
1015    #[must_use]
1016    pub fn clear_config(mut self) -> Self {
1017        self.config = None;
1018        self
1019    }
1020}
1021
1022/// Clocks locked to the timing of a reference NDI source.
1023///
1024/// A genlock paces a sender so that its frames leave in step with another
1025/// source instead of the local clock: take the two clocks with
1026/// [`clocks`](Self::clocks), wait on the matching one before submitting each
1027/// frame, and create the sender with its own clocking disabled. While no
1028/// reference signal arrives, the waits fall back to the system clock and say
1029/// so.
1030///
1031/// The waits block their thread and cannot be cancelled or given a deadline.
1032/// A completed paced wait does not prove live reference media; inspect the
1033/// returned [`ClockSource`] for reference versus system-clock fallback.
1034///
1035/// # Threading
1036///
1037/// A genlock is [`Send`] but not [`Sync`]: it can be created on one thread
1038/// and connected, waited on and dropped on others. Each of its two clocks
1039/// can be moved to a thread of its own while they borrow it, because the SDK
1040/// lets the video and the audio wait run on separate threads at once. The
1041/// SDK gives no such assurance for [`is_active`](Self::is_active), so a
1042/// shared reference to the genlock stays on one thread.
1043///
1044/// # Examples
1045///
1046/// ```no_run
1047/// use grafton_ndi::{advanced::{Genlock, GenlockOptions}, FrameRate, Ndi, ScanType, Source};
1048///
1049/// # fn main() -> Result<(), grafton_ndi::Error> {
1050/// let ndi = Ndi::new()?;
1051/// # let reference = Source::new("").unwrap();
1052/// let mut genlock = Genlock::new(&ndi, &GenlockOptions::new().source(reference))?;
1053/// let (mut video, _audio) = genlock.clocks();
1054/// let paced_by = video.wait(FrameRate::new(60_000, 1001)?, ScanType::Progressive);
1055/// println!("frame paced by {paced_by:?}");
1056/// # Ok(())
1057/// # }
1058/// ```
1059pub struct Genlock {
1060    resource: GenResource,
1061    // Through a shared reference only `is_active` is reached, and the SDK
1062    // documents only the two waits as safe on separate threads at once
1063    // (Processing.NDI.Genlock.h, Advanced SDK manual 25.5), not concurrent
1064    // queries, so Sync is withheld. The waits run through the clocks, which
1065    // borrow the genlock exclusively. Send comes from the fields.
1066    _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    /// Create a genlock with a reference source and native configuration from
1079    /// `options`. With no source it follows the system clock until
1080    /// [`connect_to`](Self::connect_to) names one.
1081    ///
1082    /// # Errors
1083    ///
1084    /// [`Error::UnsupportedCapability`] without an Advanced runtime or the
1085    /// corresponding Advanced SDK declarations, and
1086    /// [`Error::NativeOperationFailed`] when the SDK creates no genlock.
1087    #[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                    // SAFETY: the source helper and configuration owner retain
1095                    // both pointers at stable addresses through native destruction.
1096                    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    /// Follow the timing of `source`.
1113    ///
1114    /// No clock from [`clocks`](Self::clocks) can be in use while this exclusive
1115    /// borrow changes the reference. A [`Source`] is already validated.
1116    #[doc(alias = "NDIlib_genlock_connect")]
1117    pub fn connect_to(&mut self, source: &Source) {
1118        self.connect_source(Some(source));
1119    }
1120
1121    /// Stop following a reference source and use the system clock.
1122    #[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                // SAFETY: the genlock is live with no wait in progress, and
1132                // the retention helper owns both descriptors through this call.
1133                unsafe { table.NDIlib_genlock_connect(handle.0, source) };
1134            });
1135        })
1136    }
1137
1138    /// Whether a reference signal is being received.
1139    #[doc(alias = "NDIlib_genlock_is_active")]
1140    pub fn is_active(&self) -> bool {
1141        // SAFETY: the genlock is live for this borrow.
1142        native!(Genlock, self.resource.table => unsafe {
1143            self.resource.table.NDIlib_genlock_is_active(self.resource.handle.0)
1144        })
1145    }
1146
1147    /// The video clock and the audio clock.
1148    ///
1149    /// Each can be moved to its own thread; both borrow the genlock, so it can
1150    /// be neither reconnected nor dropped while they exist.
1151    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
1165/// The video clock of a [`Genlock`].
1166pub struct VideoClock<'a> {
1167    resource: &'a GenResource,
1168    // One thread at a time waits on a clock.
1169    _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    /// Block until the next frame of a stream with this frame rate and scan
1180    /// type is due, and report which clock timed it.
1181    #[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            // SAFETY: the genlock outlives this clock, and only this clock waits
1187            // for video.
1188            ClockSource::from_active(unsafe {
1189                table.NDIlib_genlock_wait_video(handle.0, &timing)
1190            })
1191        })
1192    }
1193}
1194
1195/// The audio clock of a [`Genlock`].
1196pub struct AudioClock<'a> {
1197    resource: &'a GenResource,
1198    // One thread at a time waits on a clock.
1199    _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/// A reusable, validated request for an [`AudioClock`].
1209///
1210/// Construct this once and pass it to each pacing call. Each call builds a
1211/// timing descriptor containing no sample or metadata storage.
1212#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1213pub struct AudioClockRequest {
1214    sample_rate: SdkQuantity,
1215    num_samples: SdkQuantity,
1216}
1217
1218impl AudioClockRequest {
1219    /// Ask for `num_samples` per channel at `sample_rate` hertz.
1220    ///
1221    /// # Errors
1222    ///
1223    /// [`Error::InvalidInput`] with a shared layout cause when either quantity
1224    /// is outside `1..=i32::MAX`.
1225    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    /// The requested sample rate in hertz.
1238    pub fn sample_rate(self) -> u32 {
1239        self.sample_rate.get()
1240    }
1241
1242    /// The requested samples per channel.
1243    pub fn num_samples(self) -> u32 {
1244        self.num_samples.get()
1245    }
1246}
1247
1248impl AudioClock<'_> {
1249    /// Block until the validated request's samples are due and report which
1250    /// clock timed them.
1251    #[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            // SAFETY: the genlock outlives this clock, and only this clock waits
1257            // for audio. The validated request supplies the stack descriptor's
1258            // timing, and its pointers are null.
1259            ClockSource::from_active(unsafe {
1260                table.NDIlib_genlock_wait_audio(handle.0, &timing)
1261            })
1262        })
1263    }
1264}
1265
1266/// The descriptor an audio clock reads its timing from.
1267#[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/// The descriptor a video clock reads its timing from.
1277#[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        // SAFETY: forwarded from each test; the no-op callback owns no storage.
1344        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        // SAFETY: none of these statuses reads the descriptor's buffers.
1368        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            // SAFETY: a format change reads no buffer.
1383            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        // SAFETY: failure statuses never read the descriptor's buffers.
1397        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            // SAFETY: an unknown status never reads a buffer.
1404            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        // SAFETY: an empty frame has no buffers to read.
1417        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    /// The SDK fills in the audio it returns but not its format, and reads
1501    /// the request from the same descriptor: every request starts as the
1502    /// descriptor the SDK itself would construct, with what it asks for set.
1503    #[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        // What the SDK returns for a successful request validates as audio.
1519        let returned = NDIlib_audio_frame_v3_t {
1520            no_samples: 0,
1521            sample_rate: 48_000,
1522            no_channels: 2,
1523            ..automatic
1524        };
1525        // SAFETY: an empty frame has no buffers to read.
1526        assert!(matches!(
1527            unsafe { inspect(Synchronized::Matched, &returned) }.unwrap(),
1528            AvSyncOutcome::Empty {
1529                samples_adjusted: false
1530            }
1531        ));
1532
1533        // The clocks read a rate from descriptors built the same way.
1534        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    /// A captured 64x32 UYVY frame with `timestamp`, over `pixels`.
1550    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        // SAFETY: `pixels` holds every row the descriptor describes and stays
1568        // borrowed for as long as the frame; the synthetic free owns nothing.
1569        VideoKind::make_ref(unsafe { Guard::with_test_free(ptr::null_mut(), raw, |_, _| {}) })
1570            .unwrap()
1571    }
1572
1573    /// Only a frame that carries a received timestamp can be synchronized,
1574    /// and the SDK is handed that frame, read in place, with exactly the
1575    /// timestamp that was checked.
1576    #[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            // An owned copy keeps the timestamp and is read in its own buffer.
1597            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    /// Native AV sync matches timestamps independently of the runtime's send
1609    /// formats. In particular Advanced 6.3.2 cannot send these four formats.
1610    #[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            // SAFETY: backing retains this descriptor's complete initialized
1635            // storage through both synthetic capture and synchronization.
1636            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    /// Supply real received timestamps with planar storage that the source
1662    /// runtime cannot send. Successful audio matching proves the ungated
1663    /// descriptors work beyond the no-audio outcome checked above.
1664    #[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                        // SAFETY: backing retains the full initialized planar
1765                        // allocation; the no-op free owns no native buffer.
1766                        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    /// Only `Sync` is withheld, as pinned in tests/public_auto_traits.rs.
1827    #[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    /// As for AvSync, tests/public_auto_traits.rs pins the withheld `Sync`.
1834    #[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    /// Every result and validation failure releases through the shared guard.
1841    #[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        // A misaligned buffer is rejected before reading but still released.
1866        let before = released.get();
1867        assert!(outcome(Synchronized::Matched, test_guard(descriptor(), &released)).is_err());
1868        assert_eq!(released.get(), before + 1);
1869        // Empty status may own metadata alone; that allocation is returned too.
1870        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    /// Poisoning the output field distinguishes a native unknown marker
1961    /// from the descriptor's default initialization.
1962    #[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;