Skip to main content

grafton_ndi/
framesync.rs

1//! Frame synchronization for clock-corrected video/audio capture.
2//!
3//! The [`FrameSync`] type provides a "pull" interface for receiving NDI streams with
4//! automatic time-base correction. This transforms the NDI SDK's push-based capture
5//! model into a pull model suitable for:
6//!
7//! - Video playback synced to GPU v-sync
8//! - Audio playback synced to sound card clock
9//! - Multi-source mixing with a common output clock
10//!
11//! # When to Use FrameSync vs Raw Capture
12//!
13//! | Use Case | Raw Receiver | FrameSync |
14//! |----------|-------------|-----------|
15//! | Recording (preserving timing) | ✓ | |
16//! | Playback to GPU | | ✓ |
17//! | Playback to sound card | | ✓ |
18//! | Multi-source mixing | | ✓ |
19//! | Analysis/processing pipeline | ✓ | |
20//! | Low-latency monitoring | | ✓ |
21//!
22//! # Why FrameSync Exists
23//!
24//! Computer clocks drift. The NDI SDK documentation explains:
25//!
26//! > Computer clocks rely on crystals which while all rated for the same frequency
27//! > are still not exact. If your sending computer has an audio clock that it "thinks"
28//! > is 48000Hz, to the receiver computer that has a different audio clock this might
29//! > be 48001Hz or 47998Hz.
30//!
31//! Without time-base correction, this causes:
32//! - **Video jitter**: When sender/receiver clocks are nearly aligned, naive frame
33//!   buffering causes visible jitter as frames occasionally repeat or skip.
34//! - **Audio drift**: Accumulated clock difference causes audio to fall out of sync
35//!   or cause glitches as the receiver runs out of or accumulates too many samples.
36//!
37//! FrameSync solves these by:
38//! - Using hysteresis-based video timing to determine optimal frame repeat/skip points
39//! - Dynamically resampling audio with high-order filters to track clock differences
40//!
41//! # Example
42//!
43//! ```no_run
44//! use grafton_ndi::{
45//!     Ndi, Finder, FinderOptions, ReceiverOptions, Receiver, FrameSync,
46//!     FrameSyncAudioRequest, ScanType,
47//! };
48//! use std::time::Duration;
49//!
50//! fn main() -> Result<(), grafton_ndi::Error> {
51//!     let ndi = Ndi::new()?;
52//!     let finder = Finder::new(&ndi, &FinderOptions::default())?;
53//!     let Some(source) = finder.find_source_by_name("CAMERA (Program)", Duration::from_secs(5))?
54//!     else {
55//!         eprintln!("Camera source not found");
56//!         return Ok(());
57//!     };
58//!
59//!     let options = ReceiverOptions::new(source);
60//!     let receiver = Receiver::new(&ndi, &options)?;
61//!
62//!     // Create frame-sync from receiver
63//!     let framesync = FrameSync::new(receiver)?;
64//!
65//!     // Capture video synced to your output timing
66//!     if let Some(frame) = framesync.capture_video_ref(ScanType::Progressive)? {
67//!         println!("{}x{} frame", frame.width(), frame.height());
68//!     }
69//!
70//!     // Capture audio at your sound card's rate
71//!     let request = FrameSyncAudioRequest::capture_at(48_000, 2, 1_024)?;
72//!     let audio = framesync.capture_audio_ref(request)?;
73//!     println!("{} audio samples", audio.num_samples());
74//!
75//!     Ok(())
76//! }
77//! ```
78//!
79//! See [receive_framesync.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/receive_framesync.rs)
80//! for a runnable synchronized capture loop.
81
82pub(crate) mod capture;
83
84use self::capture::FrameSyncCapture;
85use crate::media::SdkQuantity;
86use std::fmt;
87
88use crate::{
89    capture::{FrameSyncAudioFree, FrameSyncVideoFree, Guard},
90    frames::{
91        validate_returned_audio, AudioFrame, ReturnedAudio, ScanType, ValidatedAudio,
92        ValidatedAudioLayout, ValidatedVideo, VideoFrame,
93    },
94    receiver::{
95        attached::{sealed, Attached, Resource, Synchronizer},
96        FrameSyncAttached, Receiver, ReceiverCore,
97    },
98    sys::bindings::*,
99    Error, Rejected, Result,
100};
101
102/// A zero-copy borrowed video frame from a [`FrameSync`] capture.
103///
104/// The [`Receiver`] equivalent is [`VideoFrameRef`](crate::VideoFrameRef). Both share one accessor
105/// and `Debug` implementation. The frame is automatically freed when dropped via
106/// `NDIlib_framesync_free_video`.
107/// This owning reference is neither `Send` nor `Sync`; its immutable plane/row
108/// views support scoped worker reads while it stays borrowed on this thread.
109pub struct FrameSyncVideoRef<'fs> {
110    pub(crate) inner: ValidatedVideo<Guard<'fs, FrameSyncVideoFree>>,
111}
112
113/// A zero-copy borrowed audio frame from a [`FrameSync`] capture.
114///
115/// The [`Receiver`] equivalent is [`AudioFrameRef`](crate::AudioFrameRef). Both share one accessor
116/// and `Debug` implementation, and both always hold samples. The frame is
117/// automatically freed when dropped via `NDIlib_framesync_free_audio_v2`.
118/// This owning reference is neither `Send` nor `Sync`.
119pub struct FrameSyncAudioRef<'fs> {
120    pub(crate) inner: ValidatedAudio<Guard<'fs, FrameSyncAudioFree>>,
121}
122
123/// The format of the audio a [`FrameSync`] is receiving, as reported by
124/// [`FrameSync::audio_input_format`].
125///
126/// Both values are positive. The sample rate is at most `i32::MAX`, so
127/// [`FrameSyncAudioRequest::capture_at`] accepts it. This is a plain value: it
128/// is `Copy`, `Send` and `Sync`, and holds no SDK resource.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
130pub struct AudioInputFormat {
131    sample_rate: SdkQuantity,
132    num_channels: SdkQuantity,
133}
134
135impl AudioInputFormat {
136    /// A format the SDK reported, with values already checked positive.
137    pub(crate) const fn new(sample_rate: SdkQuantity, num_channels: SdkQuantity) -> Self {
138        Self {
139            sample_rate,
140            num_channels,
141        }
142    }
143
144    /// The incoming audio's sample rate in Hz: positive.
145    pub fn sample_rate(&self) -> u32 {
146        self.sample_rate.get()
147    }
148
149    /// The incoming audio's channel count: positive.
150    pub fn num_channels(&self) -> u32 {
151        self.num_channels.get()
152    }
153}
154
155/// A validated, reusable audio capture for [`FrameSync::capture_audio`] and
156/// [`FrameSync::capture_audio_ref`].
157///
158/// [`capture_at`](Self::capture_at) and [`for_input`](Self::for_input) require
159/// an explicit positive sample rate, output channels and samples per channel.
160/// Construction checks the SDK's signed byte stride and the 64 MiB packed
161/// sample payload limit before any native work. This bounds requested samples, not SDK internal memory use.
162/// Successful construction and request reuse allocate nothing in the wrapper;
163/// submitting a request performs no dimension checks, locks, or extra SDK queries.
164/// Returned descriptors and metadata are still validated after each capture.
165///
166/// Every request captures samples. To follow the source's format, call
167/// [`FrameSync::audio_input_format`] until it returns `Some`, then build a
168/// request with [`for_input`](Self::for_input). Query again and rebuild when
169/// the application chooses to follow format changes. The SDK converts to the
170/// request's rate and channel count even if the source changes meanwhile.
171///
172/// # Example
173///
174/// ```no_run
175/// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, FrameSyncAudioRequest, Source};
176/// # use std::time::Duration;
177/// # fn main() -> Result<(), grafton_ndi::Error> {
178/// # let ndi = Ndi::new()?;
179/// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("Test").unwrap()))?;
180/// let framesync = FrameSync::new(receiver)?;
181///
182/// // Wait until the source's audio format is known.
183/// let format = loop {
184///     if let Some(format) = framesync.audio_input_format()? {
185///         break format;
186///     }
187///     std::thread::sleep(Duration::from_millis(10));
188/// };
189///
190/// // 1024 samples per channel, in the source's channels, at 48 kHz.
191/// let request = FrameSyncAudioRequest::capture_at(48_000, format.num_channels(), 1_024)?;
192/// let audio = framesync.capture_audio(request)?;
193/// assert_eq!(audio.num_channels(), format.num_channels());
194///
195/// // Or in the source's rate and channels.
196/// let request = FrameSyncAudioRequest::for_input(format, 1_024)?;
197/// # Ok(())
198/// # }
199/// ```
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
201pub struct FrameSyncAudioRequest {
202    layout: ValidatedAudioLayout,
203}
204
205impl FrameSyncAudioRequest {
206    /// Requested output sample rate in Hz.
207    #[must_use]
208    pub fn sample_rate(&self) -> u32 {
209        self.layout.sample_rate()
210    }
211
212    /// Requested number of output channels.
213    #[must_use]
214    pub fn num_channels(&self) -> u32 {
215        self.layout.num_channels()
216    }
217
218    /// Requested number of output samples per channel.
219    #[must_use]
220    pub fn num_samples(&self) -> u32 {
221        self.layout.num_samples()
222    }
223
224    /// Capture samples resampled to `sample_rate` Hz, converted to
225    /// `num_channels` channels of `num_samples` samples each.
226    ///
227    /// To follow the source's format, use [`for_input`](Self::for_input).
228    ///
229    /// A request can be copied and reused across borrowed and owned captures.
230    ///
231    /// # Errors
232    ///
233    /// Returns [`Error::InvalidInput`] with an [`crate::InputDefect::Layout`]
234    /// cause for a rate or count outside `1..=i32::MAX`, or a sample payload
235    /// exceeding 64 MiB.
236    /// Validation does not allocate sample storage.
237    pub fn capture_at(sample_rate: u32, num_channels: u32, num_samples: u32) -> Result<Self> {
238        Ok(Self {
239            layout: ValidatedAudioLayout::new_uncompressed_checked(
240                crate::AudioFormat::Fltp,
241                sample_rate,
242                num_channels,
243                num_samples,
244                None,
245            )
246            .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))?,
247        })
248    }
249
250    /// Capture samples at the sample rate and channel count of `format`, with
251    /// `num_samples` samples per channel.
252    ///
253    /// `format` comes from [`FrameSync::audio_input_format`], which returns
254    /// `None` until the source's audio has arrived. The request fixes the
255    /// format it was built from: if the source changes later the SDK converts
256    /// to the request's rate and channels. To follow such changes, query the
257    /// format again and build a new request.
258    ///
259    /// # Errors
260    ///
261    /// As for [`capture_at`](Self::capture_at): [`Error::InvalidInput`] for a
262    /// zero or oversized `num_samples`, or a payload exceeding 64 MiB.
263    ///
264    /// # Example
265    ///
266    /// ```no_run
267    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, FrameSyncAudioRequest, Source};
268    /// # use std::time::Duration;
269    /// # fn main() -> Result<(), grafton_ndi::Error> {
270    /// # let ndi = Ndi::new()?;
271    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("Test").unwrap()))?;
272    /// let framesync = FrameSync::new(receiver)?;
273    ///
274    /// // Wait until the source's audio format is known.
275    /// let format = loop {
276    ///     if let Some(format) = framesync.audio_input_format()? {
277    ///         break format;
278    ///     }
279    ///     std::thread::sleep(Duration::from_millis(10));
280    /// };
281    ///
282    /// let request = FrameSyncAudioRequest::for_input(format, 1_024)?;
283    /// let audio = framesync.capture_audio(request)?;
284    /// assert_eq!(audio.sample_rate(), format.sample_rate());
285    /// // To follow a source change, call `audio_input_format` again and
286    /// // build a new request.
287    /// # Ok(())
288    /// # }
289    /// ```
290    pub fn for_input(format: AudioInputFormat, num_samples: u32) -> Result<Self> {
291        let num_samples =
292            crate::frames::validate_audio_count(num_samples.into(), crate::AudioCountKind::Samples)
293                .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))?;
294        Ok(Self {
295            layout: ValidatedAudioLayout::from_quantities(
296                crate::AudioFormat::Fltp,
297                format.sample_rate,
298                format.num_channels,
299                num_samples,
300                None,
301            )
302            .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))?,
303        })
304    }
305}
306
307/// Frame synchronizer for clock-corrected capture.
308///
309/// Converts push-based NDI streams into pull-based capture with automatic
310/// time-base correction and dynamic audio resampling.
311///
312/// # Ownership
313///
314/// `FrameSync` takes ownership of the [`Receiver`] (similar to how `BufWriter`
315/// wraps a `Write`). Use [`receiver()`](Self::receiver) to access the underlying
316/// receiver for tally, PTZ, or status operations. Use
317/// [`into_receiver()`](Self::into_receiver) to recover the receiver when done.
318///
319/// # Thread Safety
320///
321/// `FrameSync` is `Send + Sync` like `Receiver`: it may move to another
322/// thread, and one FrameSync may be shared, for example by a video render
323/// thread and an audio callback, whose captures may overlap. The SDK does not
324/// document this; it rests on how the supported runtimes behave, measured as
325/// recorded beside the `Sync` implementation. [`Self::audio_queue_depth`] is
326/// read without the SDK's lock and is approximate.
327///
328/// The `capture_*` methods return owned frames, which can move to another
329/// thread. Frames returned by the `capture_*_ref` methods borrow from the
330/// FrameSync and are neither `Send` nor `Sync`; their immutable video
331/// plane/row views can instead be moved or shared with scoped workers while
332/// the frame guard stays on its capture thread until those workers finish.
333///
334/// Raw video and audio capture through the underlying receiver are disabled
335/// while this FrameSync exists, because the synchronizer takes the receiver's
336/// video and audio; see [`FrameSyncAttached`]. [`Self::into_receiver`]
337/// destroys the synchronizer and restores raw video and audio capture before
338/// returning the receiver.
339///
340/// # Example
341///
342/// ```no_run
343/// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, FrameSyncAudioRequest, Source, SourceAddress, ScanType};
344/// # fn main() -> Result<(), grafton_ndi::Error> {
345/// # let ndi = Ndi::new()?;
346/// # let source = Source::new("Test").unwrap();
347/// # let options = ReceiverOptions::new(source);
348/// # let receiver = Receiver::new(&ndi, &options)?;
349/// let framesync = FrameSync::new(receiver)?;
350///
351/// // Sample available data without waiting for a new network frame
352/// if let Some(video) = framesync.capture_video_ref(ScanType::Progressive)? {
353///     println!("Video: {}x{}", video.width(), video.height());
354/// }
355///
356/// // Audio capture fixes the output dimensions before entering the SDK.
357/// let audio = framesync.capture_audio_ref(FrameSyncAudioRequest::capture_at(48_000, 2, 1_024)?)?;
358/// println!("Audio: {} samples", audio.num_samples());
359/// # Ok(())
360/// # }
361/// ```
362pub struct FrameSync {
363    inner: Attached<FrameSyncKind>,
364}
365
366const_assert!({
367    const fn send_and_sync<T: Send + Sync>() {}
368    send_and_sync::<FrameSync>();
369    send_and_sync::<FrameSyncResource>();
370});
371
372#[derive(Clone, Copy, Debug, PartialEq, Eq)]
373struct FrameSyncInstance(NDIlib_framesync_instance_t);
374
375/// # Safety
376///
377/// The FrameSync instance has no affinity to the thread that created it: the
378/// SDK's own FrameSync audio examples create it on one thread and capture
379/// from an audio device's callback thread. FrameSyncResource owns this handle
380/// and retains the receiver core and its runtime through native destruction.
381/// Split views only borrow that resource. Borrowed frame guards cannot move
382/// between threads and keep the resource borrowed until their buffers are
383/// freed; destruction requires exclusive ownership.
384unsafe impl Send for FrameSyncInstance {}
385
386/// # Safety
387///
388/// Every `&self` method may run on several threads at once: video and audio
389/// capture, the input-format query, the queue depth, and the frees of
390/// borrowed frames. Neither `Processing.NDI.FrameSync.h` nor the SDK
391/// documentation of NDI 6.1.1, 6.3.2 or 6.4 says whether that is safe (the
392/// one threading statement, in `Processing.NDI.Recv.h`, covers receiver
393/// capture). The safety argument relies on these native implementation
394/// observations and concurrent capture tests:
395///
396/// - In the Linux x86_64 runtimes of all three versions, video capture, audio
397///   capture (and with it the input-format query) and the video free take the
398///   instance's exclusive lock, and the audio free returns its buffer through
399///   atomic operations. The queue depth is read without the lock, so it is
400///   approximate, which [`FrameSync::audio_queue_depth`] documents.
401/// - Under helgrind, four threads making all of these calls on one FrameSync
402///   of a live source show no conflict between two of them other than those
403///   two lock-free paths, on 6.3.2 and 6.4.
404/// - Sixteen threads making them for 120 s on each of 6.1.1, 6.3.2 and 6.4
405///   receive no torn video frame, no invalid audio and no error.
406///
407/// `one_framesync_serves_captures_from_several_threads_at_once` in
408/// tests/framesync_capture_boundary.rs repeats the last check briefly with
409/// every runtime the tests run against. The enclosing FrameSync's
410/// Receiver<FrameSyncAttached> contributes its own auto traits; attachment
411/// disables raw video and audio capture until this resource is destroyed,
412/// including when the receiver is accessed through [`FrameSync::receiver`].
413unsafe impl Sync for FrameSyncInstance {}
414
415pub(crate) struct FrameSyncKind {
416    instance: FrameSyncInstance,
417    receiver: std::sync::Arc<ReceiverCore>,
418}
419
420type FrameSyncResource = Resource<FrameSyncKind>;
421
422// Moving the receiver lease into the kind adds no storage to the resource.
423const_assert!(
424    std::mem::size_of::<FrameSyncResource>()
425        == std::mem::size_of::<FrameSyncInstance>()
426            + std::mem::size_of::<std::sync::Arc<ReceiverCore>>()
427);
428
429impl sealed::Sealed for FrameSyncKind {}
430
431// SAFETY: adoption pairs this native handle with its creating receiver. The
432// capture view borrows that resource and cannot replace either owned field.
433unsafe impl Synchronizer for FrameSyncKind {
434    type Mode = FrameSyncAttached;
435    type Capture<'a> = FrameSyncCapture<'a>;
436
437    unsafe fn destroy(&mut self) {
438        let receiver = &self.receiver;
439        // SAFETY: the uniquely owned handle is live, and Resource retains its
440        // creating receiver and runtime until this destruction returns.
441        unsafe { receiver.sdk().NDIlib_framesync_destroy(self.instance.0) };
442    }
443
444    fn receiver(&self) -> &std::sync::Arc<ReceiverCore> {
445        &self.receiver
446    }
447
448    fn capture(resource: &FrameSyncResource) -> FrameSyncCapture<'_> {
449        FrameSyncCapture::new(resource)
450    }
451}
452
453/// What one `NDIlib_framesync_capture_audio_v2` call asks the SDK for.
454#[derive(Clone, Copy)]
455enum AudioCall {
456    /// Samples in a validated request's rate, channels and sample count.
457    Samples(FrameSyncAudioRequest),
458    /// The input-format query: a zero sample rate, channel count and sample
459    /// count.
460    InputFormat,
461}
462
463impl crate::capture::source_sealed::Sealed for &FrameSyncResource {}
464
465macro_rules! framesync_frame_source {
466    ($strategy:ty) => {
467        // SAFETY: this resource owns the synchronizer and retains its creating
468        // receiver/runtime. Its borrow prevents destruction until frame free.
469        unsafe impl<'owner> crate::capture::FrameSource<'owner, $strategy>
470            for &'owner FrameSyncResource
471        {
472            fn runtime(&self) -> &'owner crate::Ndi {
473                self.receiver().ndi()
474            }
475
476            fn instance(&self) -> NDIlib_framesync_instance_t {
477                self.instance.0
478            }
479        }
480    };
481}
482framesync_frame_source!(FrameSyncVideoFree);
483framesync_frame_source!(FrameSyncAudioFree);
484
485impl FrameSyncResource {
486    /// Capture video for `scan_type`: the guard of the frame the SDK
487    /// returned, or `None` for the documented all-zero "no video yet" state,
488    /// which holds nothing to free. The one place a FrameSync video guard is
489    /// made.
490    fn capture_video(&self, scan_type: ScanType) -> Option<Guard<'_, FrameSyncVideoFree>> {
491        let mut frame = NDIlib_video_frame_v2_t::default();
492        // SAFETY: the FrameSync instance is live for this borrow and `frame` is
493        // writable storage the SDK fills or leaves zeroed.
494        unsafe {
495            self.receiver().sdk().NDIlib_framesync_capture_video(
496                self.instance.0,
497                &mut frame,
498                scan_type.to_sdk(),
499            );
500        }
501        if is_framesync_video_empty(&frame) {
502            return None;
503        }
504        // SAFETY: the call above filled `frame` through this instance, which
505        // was created through this receiver's runtime. The guard borrows this resource, which
506        // destroys the instance only when dropped, so the instance outlives
507        // the guard, which frees the frame exactly once through
508        // NDIlib_framesync_free_video, including when validation fails.
509        Some(unsafe { Guard::new(self, frame) })
510    }
511
512    /// Make `call`: the guard of what the SDK returned, which it returns
513    /// whether or not audio has arrived. The one place a FrameSync audio
514    /// guard is made.
515    fn capture_audio(&self, call: AudioCall) -> Guard<'_, FrameSyncAudioFree> {
516        let (sample_rate, num_channels, num_samples) = match call {
517            AudioCall::Samples(request) => (
518                request.layout.sdk_sample_rate(),
519                request.layout.sdk_num_channels(),
520                request.layout.sdk_num_samples(),
521            ),
522            AudioCall::InputFormat => (0, 0, 0),
523        };
524        let mut frame = NDIlib_audio_frame_v3_t::default();
525
526        // SAFETY: the FrameSync instance is live for this borrow and `frame` is
527        // writable storage. Processing.NDI.FrameSync.h defines both calls:
528        // - A request's private fields were checked at construction: positive
529        //   channels and samples, the packed FLTP payload and the signed byte
530        //   stride, and a positive sample rate. The SDK permits an output rate
531        //   and channel count independent of the input, and supplies silence
532        //   before audio arrives, so no source-format sentinel can race a
533        //   format change here.
534        // - A zero sample rate, channel count and sample count is a query
535        //   that returns the current input format, or a zero sample rate and
536        //   channel count when there is none, without capturing samples.
537        // Either way the SDK owns what it returned until it is freed through
538        // this same instance.
539        unsafe {
540            self.receiver().sdk().NDIlib_framesync_capture_audio_v2(
541                self.instance.0,
542                &mut frame,
543                sample_rate,
544                num_channels,
545                num_samples,
546            );
547        }
548
549        // SAFETY: the call above filled `frame` through this instance, which
550        // was created through this receiver's runtime. The guard borrows this resource, which
551        // destroys the instance only when dropped, so the instance outlives
552        // the guard, which frees the frame exactly once through
553        // NDIlib_framesync_free_audio_v2, including when validation fails.
554        unsafe { Guard::new(self, frame) }
555    }
556}
557
558impl FrameSync {
559    /// Create a frame synchronizer from a receiver.
560    ///
561    /// Takes ownership of the receiver. Use [`receiver()`](Self::receiver)
562    /// to access the underlying receiver for tally, PTZ, or status operations.
563    /// Use [`into_receiver()`](Self::into_receiver) to recover the receiver.
564    ///
565    /// # Errors
566    ///
567    /// Returns the receiver, unchanged, with
568    /// [`Error::NativeOperationFailed`] if the NDI SDK does not create the
569    /// frame-sync instance.
570    ///
571    /// # Example
572    ///
573    /// ```no_run
574    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, Source, SourceAddress};
575    /// # fn main() -> Result<(), grafton_ndi::Error> {
576    /// # let ndi = Ndi::new()?;
577    /// # let source = Source::new("Test").unwrap();
578    /// # let options = ReceiverOptions::new(source);
579    /// let receiver = Receiver::new(&ndi, &options)?;
580    /// let framesync = FrameSync::new(receiver)?;
581    /// # Ok(())
582    /// # }
583    /// ```
584    #[doc(alias = "NDIlib_framesync_create")]
585    pub fn new(receiver: Receiver) -> std::result::Result<Self, Rejected<Receiver>> {
586        // SAFETY: this call creates a uniquely owned synchronizer from the
587        // supplied live receiver, through that receiver's runtime.
588        unsafe {
589            Attached::adopt(receiver, |adoption| {
590                let core = adoption.core();
591                let instance = core
592                    .sdk()
593                    .named()
594                    .NDIlib_framesync_create(adoption.instance())
595                    .created()?
596                    .as_ptr();
597                Ok(FrameSyncKind {
598                    instance: FrameSyncInstance(instance),
599                    receiver: std::sync::Arc::clone(core),
600                })
601            })
602        }
603        .map(|inner| Self { inner })
604    }
605
606    /// Access the underlying receiver.
607    ///
608    /// Use this to access receiver functionality like tally, PTZ, status
609    /// queries and metadata capture while FrameSync is active. Native
610    /// synchronization can consume status notifications, so this receiver has
611    /// no event polling. Query capabilities with `ptz().is_supported()`,
612    /// `web_control_url()` and Advanced KVM's `is_supported()`; observe the
613    /// source with `wait_for_source_name_change()` and connection state with
614    /// `is_connected()` or `connection_stats()`.
615    /// Tally control publishes state upstream; it does not query incoming tally.
616    /// Local connection changes may run while FrameSync captures; the native
617    /// overlap tests exercise recovery and valid output through those changes.
618    ///
619    /// This receiver mode has no raw video or audio capture, because the
620    /// synchronizer takes the receiver's video and audio: raw audio capture
621    /// would take frames the FrameSync then replaces with silence (see
622    /// [`FrameSyncAttached`]). Use the FrameSync capture methods, or recover
623    /// the receiver with [`Self::into_receiver`] first.
624    ///
625    /// ```compile_fail,E0277
626    /// use grafton_ndi::FrameSync;
627    /// fn capture(framesync: &FrameSync) {
628    ///     let _ = framesync.receiver().capture_audio(std::time::Duration::ZERO);
629    /// }
630    /// ```
631    pub fn receiver(&self) -> &Receiver<FrameSyncAttached> {
632        self.inner.receiver()
633    }
634
635    /// Borrow the receiver's exclusive Advanced controls without lending the
636    /// receiver mutably. This allocates nothing and makes no native call.
637    /// Use [`Self::split`] to capture while a KVM session holds this borrow.
638    #[cfg(feature = "advanced")]
639    pub fn controls(&mut self) -> crate::advanced::ReceiverControls<'_, FrameSyncAttached> {
640        self.inner.controls()
641    }
642
643    /// Lend [`advanced::FrameSyncCapture`](crate::advanced::FrameSyncCapture) and
644    /// [`ReceiverControls`](crate::advanced::ReceiverControls) independently.
645    ///
646    /// Neither view can replace, recover or destroy either native resource.
647    /// The synchronizer and receiver keep their original instances; creating
648    /// the views allocates nothing and makes no SDK call. Drop held frames
649    /// and both views before recovering the receiver. A source change must be
650    /// preceded by successful [`KvmSession::release_all`](crate::advanced::KvmSession::release_all)
651    /// and session termination.
652    ///
653    /// ```no_run
654    /// # use grafton_ndi::{FrameSync, ScanType, Result};
655    /// # use grafton_ndi::advanced::MouseButton;
656    /// fn drag(sync: &mut FrameSync) -> Result<()> {
657    ///     let (capture, controls) = sync.split();
658    ///     let mut session = controls.kvm()?;
659    ///     session.mouse_down(MouseButton::Left)?;
660    ///     let frame = capture.capture_video_ref(ScanType::Progressive)?;
661    ///     session.move_pointer(0.5, 0.5)?;
662    ///     session.release_all()?;
663    ///     drop(frame);
664    ///     Ok(())
665    /// }
666    /// ```
667    #[cfg(feature = "advanced")]
668    pub fn split(
669        &mut self,
670    ) -> (
671        crate::advanced::FrameSyncCapture<'_>,
672        crate::advanced::ReceiverControls<'_, FrameSyncAttached>,
673    ) {
674        self.inner.split()
675    }
676
677    /// Consume the FrameSync and recover the underlying Receiver.
678    ///
679    /// This destroys the frame synchronizer and returns the receiver for
680    /// continued use with raw capture or for creating a new FrameSync.
681    pub fn into_receiver(self) -> Receiver {
682        self.inner.into_receiver()
683    }
684
685    /// Capture video with time-base correction, as an owned frame that can
686    /// be sent across threads.
687    ///
688    /// This does not wait for a new network frame. It returns the best frame for
689    /// the current output timing, handling clock drift and jitter automatically.
690    /// The same frame may be returned multiple times when capture rate exceeds
691    /// source frame rate. SDK processing takes time; concurrent captures on
692    /// one FrameSync serialize briefly inside the SDK.
693    /// [`Self::capture_video_ref`] borrows the frame instead of copying it.
694    ///
695    /// # Arguments
696    ///
697    /// * `scan_type` - The desired field format. Use `ScanType::Progressive` for
698    ///   most applications. For interlaced output, use the appropriate field type
699    ///   to maintain correct field ordering.
700    ///
701    /// # Returns
702    ///
703    /// * `Ok(Some(VideoFrame))` - An owned copy of the captured frame
704    /// * `Ok(None)` - The SDK returned the documented all-zero "no video yet" state
705    ///
706    /// # Errors
707    ///
708    /// As for [`Self::capture_video_ref`]. The owned copy itself cannot
709    /// fail.
710    ///
711    /// # Example
712    ///
713    /// ```no_run
714    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, Source, SourceAddress, ScanType};
715    /// # fn main() -> Result<(), grafton_ndi::Error> {
716    /// # let ndi = Ndi::new()?;
717    /// # let source = Source::new("Test").unwrap();
718    /// # let options = ReceiverOptions::new(source);
719    /// # let receiver = Receiver::new(&ndi, &options)?;
720    /// let framesync = FrameSync::new(receiver)?;
721    ///
722    /// // Capture loop - call at your output frame rate
723    /// loop {
724    ///     if let Some(frame) = framesync.capture_video(ScanType::Progressive)? {
725    ///         // Process/display frame
726    ///         let rate = frame.frame_rate();
727    ///         println!("{}x{} @ {}/{} fps",
728    ///             frame.width(), frame.height(),
729    ///             rate.numerator(), rate.denominator());
730    ///     } else {
731    ///         // No video received yet - display placeholder
732    ///         println!("Waiting for video...");
733    ///     }
734    ///     # break;
735    /// }
736    /// # Ok(())
737    /// # }
738    /// ```
739    #[doc(alias = "NDIlib_framesync_capture_video")]
740    pub fn capture_video(&self, scan_type: ScanType) -> Result<Option<VideoFrame>> {
741        Ok(self
742            .capture_video_ref(scan_type)?
743            .map(|frame| frame.to_owned()))
744    }
745
746    /// Capture video with time-base correction, borrowing the SDK's frame
747    /// without copying it.
748    ///
749    /// Timing is as for [`Self::capture_video`].
750    ///
751    /// # Returns
752    ///
753    /// * `Ok(Some(FrameSyncVideoRef))` - A validated zero-copy output frame; it
754    ///   may repeat or retain earlier input and does not prove new reception
755    /// * `Ok(None)` - The SDK returned the documented all-zero "no video yet" state
756    ///
757    /// # Errors
758    ///
759    /// Returns [`Error::InvalidFrame`] when the SDK returned an unsupported
760    /// format or malformed frame descriptor, including invalid dimensions,
761    /// stride, or buffers. Unreadable per-frame metadata is withheld; inspect
762    /// [`VideoSource::metadata_status`](crate::VideoSource::metadata_status).
763    #[doc(alias = "NDIlib_framesync_capture_video")]
764    pub fn capture_video_ref(&self, scan_type: ScanType) -> Result<Option<FrameSyncVideoRef<'_>>> {
765        self.inner.capture().capture_video_ref(scan_type)
766    }
767
768    /// Capture audio with dynamic resampling, as an owned frame that can be
769    /// sent across threads.
770    ///
771    /// This does not wait for new network audio. Capture requests ask the NDI
772    /// SDK to resample incoming audio to match the requested sample rate,
773    /// channel count, and sample count. SDK processing and resampling take
774    /// time; concurrent captures on one FrameSync serialize briefly inside
775    /// the SDK. [`Self::capture_audio_ref`] borrows the samples
776    /// instead of copying them.
777    ///
778    /// Call this at the rate you need audio - the SDK will adapt the incoming
779    /// signal to match your output timing using dynamic audio sampling.
780    ///
781    /// # Arguments
782    ///
783    /// * `request` - The output sample rate, channels and samples per
784    ///   channel; see [`FrameSyncAudioRequest`].
785    ///
786    /// # Returns
787    ///
788    /// An owned copy of the captured samples at the requested sample rate,
789    /// channel count, and samples per channel. The SDK can supply silence
790    /// whenever current input is unavailable. To read the SDK's known source
791    /// format, use [`Self::audio_input_format`].
792    ///
793    /// # Errors
794    ///
795    /// As for [`Self::capture_audio_ref`].
796    ///
797    /// # Example
798    ///
799    /// ```no_run
800    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, FrameSyncAudioRequest, Source, SourceAddress};
801    /// # fn main() -> Result<(), grafton_ndi::Error> {
802    /// # let ndi = Ndi::new()?;
803    /// # let source = Source::new("Test").unwrap();
804    /// # let options = ReceiverOptions::new(source);
805    /// # let receiver = Receiver::new(&ndi, &options)?;
806    /// let framesync = FrameSync::new(receiver)?;
807    ///
808    /// // Audio callback - called by sound card at its rate
809    /// let request = FrameSyncAudioRequest::capture_at(48_000, 2, 1_024)?;
810    ///
811    /// loop {
812    ///     // Request 1024 stereo samples at 48kHz
813    ///     let audio = framesync.capture_audio(request)?;
814    ///     // Process each channel.
815    ///     for samples in audio.channels() {
816    ///         println!("Got {} samples in a channel", samples.len());
817    ///     }
818    ///     # break;
819    /// }
820    /// # Ok(())
821    /// # }
822    /// ```
823    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
824    pub fn capture_audio(&self, request: FrameSyncAudioRequest) -> Result<AudioFrame> {
825        Ok(self.capture_audio_ref(request)?.to_owned())
826    }
827
828    /// Capture audio with dynamic resampling, borrowing the SDK's samples
829    /// without copying them.
830    ///
831    /// Resampling is as for [`Self::capture_audio`]. The frame has the
832    /// requested sample rate, channel count, and samples per channel. The SDK
833    /// can supply silence whenever current input is unavailable, including
834    /// after input previously arrived. Successful output does not prove fresh
835    /// reception.
836    /// Output without a source timestamp reports `timestamp() == None`; without
837    /// a source timecode it carries [`crate::Timecode::SYNTHESIZE`].
838    /// See the [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
839    ///
840    /// # Following the source's format
841    ///
842    /// A request names its sample rate and channel count explicitly. To
843    /// capture in the source's format, wait for [`Self::audio_input_format`]
844    /// to return `Some`, then build a request with
845    /// [`FrameSyncAudioRequest::for_input`].
846    ///
847    /// # Errors
848    ///
849    /// Returns [`Error::InvalidFrame`] when the SDK returns malformed audio
850    /// dimensions, sample layout, or buffers. For a valid frame with dimensions
851    /// that differ from the request, the cause is
852    /// [`crate::FrameDefect::FrameSyncAudioMismatch`].
853    /// Request dimensions are checked at construction.
854    /// Use [`AudioSource::metadata_status`](crate::AudioSource::metadata_status)
855    /// to check whether the frame's metadata could be read.
856    ///
857    /// # Example
858    ///
859    /// ```no_run
860    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, FrameSyncAudioRequest, Source, SourceAddress};
861    /// # use std::time::Duration;
862    /// # fn main() -> Result<(), grafton_ndi::Error> {
863    /// # let ndi = Ndi::new()?;
864    /// # let source = Source::new("Test").unwrap();
865    /// # let options = ReceiverOptions::new(source);
866    /// # let receiver = Receiver::new(&ndi, &options)?;
867    /// let framesync = FrameSync::new(receiver)?;
868    ///
869    /// let format = loop {
870    ///     match framesync.audio_input_format()? {
871    ///         Some(format) => break format,
872    ///         None => std::thread::sleep(Duration::from_millis(10)),
873    ///     }
874    /// };
875    /// let request = FrameSyncAudioRequest::for_input(format, 1_024)?;
876    ///
877    /// let audio = framesync.capture_audio_ref(request)?;
878    /// println!("{} channels at {} Hz", audio.num_channels(), audio.sample_rate());
879    /// # Ok(())
880    /// # }
881    /// ```
882    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
883    pub fn capture_audio_ref(
884        &self,
885        request: FrameSyncAudioRequest,
886    ) -> Result<FrameSyncAudioRef<'_>> {
887        self.inner.capture().capture_audio_ref(request)
888    }
889
890    /// Query the format of the audio this FrameSync is receiving, without
891    /// capturing samples.
892    ///
893    /// This makes the SDK's input-format query: one native call that does not
894    /// wait for network audio and frees what the SDK returned before
895    /// returning. It allocates nothing unless it fails. Like the other
896    /// FrameSync methods it may be called from any thread.
897    ///
898    /// # Returns
899    ///
900    /// * `Ok(Some(format))` - The SDK's known source sample rate and channel
901    ///   count, both positive. This knowledge may persist across starvation,
902    ///   disconnect, reconnect or source changes; it is not a freshness signal.
903    /// * `Ok(None)` - The SDK reports no known audio format
904    ///
905    /// # Errors
906    ///
907    /// Returns [`Error::InvalidFrame`] when the SDK's answer is neither of
908    /// those: samples, a data pointer or channel stride, a negative value, a
909    /// zero sample rate with a positive channel count or the reverse, or an
910    /// unsupported FourCC.
911    ///
912    /// # Example
913    ///
914    /// ```no_run
915    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, Source};
916    /// # fn main() -> Result<(), grafton_ndi::Error> {
917    /// # let ndi = Ndi::new()?;
918    /// # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(Source::new("Test").unwrap()))?;
919    /// let framesync = FrameSync::new(receiver)?;
920    ///
921    /// match framesync.audio_input_format()? {
922    ///     Some(format) => println!(
923    ///         "{} channels at {} Hz",
924    ///         format.num_channels(),
925    ///         format.sample_rate()
926    ///     ),
927    ///     None => println!("No audio yet"),
928    /// }
929    /// # Ok(())
930    /// # }
931    /// ```
932    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
933    pub fn audio_input_format(&self) -> Result<Option<AudioInputFormat>> {
934        self.inner.capture().audio_input_format()
935    }
936
937    /// Query the current audio queue depth.
938    ///
939    /// Returns the approximate number of audio samples currently buffered.
940    /// This can be useful when using an inaccurate timer for audio playback.
941    ///
942    /// **Note:** This value may change immediately after being read as new
943    /// samples are continuously received, and the SDK reads it without the
944    /// lock its captures take, so a capture on another thread may be under
945    /// way. For most applications, simply call `capture_audio` at your desired
946    /// rate and let the SDK handle timing.
947    /// A positive depth does not establish fresh input; see the
948    /// [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
949    ///
950    /// # Example
951    ///
952    /// ```no_run
953    /// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, FrameSync, Source, SourceAddress};
954    /// # fn main() -> Result<(), grafton_ndi::Error> {
955    /// # let ndi = Ndi::new()?;
956    /// # let source = Source::new("Test").unwrap();
957    /// # let options = ReceiverOptions::new(source);
958    /// # let receiver = Receiver::new(&ndi, &options)?;
959    /// let framesync = FrameSync::new(receiver)?;
960    ///
961    /// // Check available samples before capture
962    /// let available = framesync.audio_queue_depth()?;
963    /// println!("Audio samples available: {}", available);
964    /// # Ok(())
965    /// # }
966    /// ```
967    ///
968    /// # Errors
969    ///
970    /// [`Error::UnexpectedSdkResult`] when the native queue depth is negative.
971    #[doc(alias = "NDIlib_framesync_audio_queue_depth")]
972    pub fn audio_queue_depth(&self) -> Result<u32> {
973        self.inner.capture().audio_queue_depth()
974    }
975}
976
977impl fmt::Debug for FrameSync {
978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979        f.debug_struct("FrameSync")
980            .field("receiver", self.receiver())
981            .finish_non_exhaustive()
982    }
983}
984
985pub(crate) fn is_framesync_video_empty(frame: &NDIlib_video_frame_v2_t) -> bool {
986    frame.xres == 0
987        && frame.yres == 0
988        && frame.FourCC == 0
989        && frame.frame_rate_N == 0
990        && frame.frame_rate_D == 0
991        && frame.picture_aspect_ratio == 0.0
992        && frame.frame_format_type == 0
993        && frame.timecode == 0
994        && frame.p_data.is_null()
995        // SAFETY: both members of the descriptor's union are `int`s at the
996        // same offset, so reading either one reads the four bytes the SDK
997        // wrote as a valid `i32`. The SDK's zeroed "no video" state has zero
998        // there whichever member `Processing.NDI.structs.h` makes it.
999        && unsafe { frame.__bindgen_anon_1.data_size_in_bytes } == 0
1000        && frame.p_metadata.is_null()
1001        && frame.timestamp == 0
1002}
1003
1004/// The answer to an input-format query: the format, or `None` when no source
1005/// format is known. Samples in the answer, or any other shape
1006/// [`validate_returned_audio`] rejects, are an error. The metadata pointer is
1007/// not read: the answer exposes no metadata.
1008fn input_format(returned: &NDIlib_audio_frame_v3_t) -> Result<Option<AudioInputFormat>> {
1009    match validate_returned_audio(returned)? {
1010        ReturnedAudio::Empty(format) => Ok(format),
1011        ReturnedAudio::Samples(layout) => Err(Error::InvalidFrame(
1012            crate::FrameDefect::FrameSyncAudioInput {
1013                channels: layout.no_channels(),
1014                samples: layout.no_samples(),
1015            },
1016        )),
1017    }
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022    use super::*;
1023
1024    #[test]
1025    fn debug_prints_identity_without_pointers_or_queue_queries() {
1026        let Some(ndi) = crate::test_support::ndi() else {
1027            return;
1028        };
1029        let receiver = Receiver::new(&ndi, &crate::ReceiverOptions::disconnected()).unwrap();
1030        let sync = FrameSync::new(receiver).unwrap();
1031        assert_eq!(
1032            format!("{sync:?}"),
1033            format!("FrameSync {{ receiver: {:?}, .. }}", sync.receiver())
1034        );
1035        let capture = sync.inner.capture();
1036        assert_eq!(
1037            format!("{capture:?}"),
1038            format!("FrameSyncCapture {{ receiver: {:?}, .. }}", sync.receiver())
1039        );
1040    }
1041
1042    #[cfg(feature = "advanced")]
1043    #[test]
1044    fn exclusive_control_views_allocate_nothing_and_keep_the_native_owners() {
1045        let Some(ndi) = crate::test_support::advanced_ndi() else {
1046            return;
1047        };
1048        let receiver = Receiver::new(&ndi, &crate::ReceiverOptions::disconnected()).unwrap();
1049        let mut sync = FrameSync::new(receiver).unwrap();
1050        let original = (
1051            sync.inner.resource().instance,
1052            std::sync::Arc::as_ptr(&sync.receiver().core),
1053        );
1054        let (results, allocations) = crate::test_alloc::allocation_count(|| {
1055            let tier = sync.controls().set_stream_tier(crate::StreamTier::Preview);
1056            let streams = sync.controls().set_streams(crate::MediaTypes::ALL);
1057            let (_capture, controls) = sync.split();
1058            let session = controls.kvm();
1059            (tier, streams, session.map(drop))
1060        });
1061        assert_eq!(allocations, 0);
1062        assert!(results.0.is_ok() && results.1.is_ok() && results.2.is_ok());
1063        assert_eq!(
1064            (
1065                sync.inner.resource().instance,
1066                std::sync::Arc::as_ptr(&sync.receiver().core)
1067            ),
1068            original
1069        );
1070    }
1071    use crate::{
1072        frames::{AudioFormat, PixelFormat},
1073        FourCc,
1074    };
1075    use std::ptr;
1076
1077    #[test]
1078    fn audio_request_errors_describe_reusable_input_and_keep_layout_causes() {
1079        use crate::{AudioCountKind, InputDefect, LayoutDefect};
1080
1081        let cause = |error| match error {
1082            Error::InvalidInput(InputDefect::Layout(cause)) => cause,
1083            other => panic!("expected InvalidInput(Layout), got {other:?}"),
1084        };
1085        for rate in [0, 1 << 31, u32::MAX] {
1086            assert_eq!(
1087                cause(FrameSyncAudioRequest::capture_at(rate, 0, 0).unwrap_err()),
1088                LayoutDefect::AudioRate(rate.into())
1089            );
1090        }
1091        for count in [0, 1 << 31, u32::MAX] {
1092            assert_eq!(
1093                cause(FrameSyncAudioRequest::capture_at(48_000, count, 0).unwrap_err()),
1094                LayoutDefect::AudioCount {
1095                    kind: AudioCountKind::Channels,
1096                    value: count.into(),
1097                }
1098            );
1099            assert_eq!(
1100                cause(FrameSyncAudioRequest::capture_at(48_000, 1, count).unwrap_err()),
1101                LayoutDefect::AudioCount {
1102                    kind: AudioCountKind::Samples,
1103                    value: count.into(),
1104                }
1105            );
1106        }
1107        let format = AudioInputFormat::new(
1108            SdkQuantity::new(48_000).unwrap(),
1109            SdkQuantity::new(1).unwrap(),
1110        );
1111        for (samples, expected) in [
1112            (
1113                0,
1114                LayoutDefect::AudioCount {
1115                    kind: AudioCountKind::Samples,
1116                    value: 0.into(),
1117                },
1118            ),
1119            (16_777_217, LayoutDefect::AudioBytes(67_108_868u64.into())),
1120        ] {
1121            assert_eq!(
1122                cause(FrameSyncAudioRequest::capture_at(48_000, 1, samples).unwrap_err()),
1123                expected
1124            );
1125            assert_eq!(
1126                cause(FrameSyncAudioRequest::for_input(format, samples).unwrap_err()),
1127                expected
1128            );
1129        }
1130    }
1131
1132    #[cfg(feature = "advanced")]
1133    #[test]
1134    fn synchronizer_requests_share_rate_and_sample_range_errors() {
1135        use crate::advanced::{AudioClockRequest, AvSyncRequest};
1136
1137        let cause = |error| match error {
1138            Error::InvalidInput(crate::InputDefect::Layout(cause)) => cause,
1139            other => panic!("expected InvalidInput(Layout), got {other:?}"),
1140        };
1141
1142        // These are the quantities all three requests carry. AV sync has no
1143        // requested channel count, and a clock query allocates no audio payload.
1144        for rate in [0, 1 << 31, u32::MAX] {
1145            let expected = cause(FrameSyncAudioRequest::capture_at(rate, 1, 8).unwrap_err());
1146            assert_eq!(
1147                cause(AvSyncRequest::new(Some(rate), Some(8)).unwrap_err()),
1148                expected
1149            );
1150            assert_eq!(
1151                cause(AudioClockRequest::new(rate, 8).unwrap_err()),
1152                expected
1153            );
1154        }
1155        for samples in [0, 1 << 31, u32::MAX] {
1156            let expected =
1157                cause(FrameSyncAudioRequest::capture_at(48_000, 1, samples).unwrap_err());
1158            assert_eq!(
1159                cause(AvSyncRequest::new(Some(48_000), Some(samples)).unwrap_err()),
1160                expected
1161            );
1162            assert_eq!(
1163                cause(AudioClockRequest::new(48_000, samples).unwrap_err()),
1164                expected
1165            );
1166        }
1167    }
1168
1169    #[test]
1170    fn audio_requests_reject_invalid_rates_and_dimensions_at_construction() {
1171        for rate in [0, 1 << 31, u32::MAX] {
1172            assert!(FrameSyncAudioRequest::capture_at(rate, 2, 1024).is_err());
1173        }
1174        assert!(FrameSyncAudioRequest::capture_at(i32::MAX.unsigned_abs(), 2, 1024).is_ok());
1175        for (channels, samples) in [
1176            (0, 1024),
1177            (u32::MAX, 1024),
1178            (2, 0),
1179            (2, u32::MAX),
1180            (0, 0),
1181            (2, 8_388_609),
1182            (2, 536_870_912),
1183            (1, 1_073_741_825),
1184            (i32::MAX.unsigned_abs(), 1),
1185            (u32::MAX, u32::MAX),
1186        ] {
1187            assert!(FrameSyncAudioRequest::capture_at(48_000, channels, samples).is_err());
1188        }
1189        // Exact cap, with no sample allocation or native call.
1190        assert!(FrameSyncAudioRequest::capture_at(48_000, 2, 8_388_608).is_ok());
1191        assert!(FrameSyncAudioRequest::capture_at(48_000, 1, 16_777_216).is_ok());
1192        assert!(FrameSyncAudioRequest::capture_at(48_000, 1, 16_777_217).is_err());
1193        let format = AudioInputFormat::new(
1194            SdkQuantity::new(44_100).unwrap(),
1195            SdkQuantity::new(6).unwrap(),
1196        );
1197        assert_eq!(
1198            FrameSyncAudioRequest::for_input(format, 480).unwrap(),
1199            FrameSyncAudioRequest::capture_at(44_100, 6, 480).unwrap()
1200        );
1201        assert!(FrameSyncAudioRequest::for_input(format, 0).is_err());
1202        assert!(FrameSyncAudioRequest::for_input(format, 536_870_912).is_err());
1203    }
1204
1205    #[test]
1206    fn audio_request_reuse_and_rejection_at_both_sdk_entry_points() {
1207        let Some(ndi) = crate::test_support::ndi() else {
1208            return;
1209        };
1210        let receiver = Receiver::new(&ndi, &crate::ReceiverOptions::disconnected()).unwrap();
1211        let fs = FrameSync::new(receiver).unwrap();
1212        for (channels, samples) in [
1213            (2, 8_388_609),
1214            (2, 536_870_912),
1215            (1, 1_073_741_825),
1216            (i32::MAX.unsigned_abs(), 1),
1217        ] {
1218            assert!(FrameSyncAudioRequest::capture_at(48_000, channels, samples)
1219                .and_then(|request| fs.capture_audio_ref(request).map(drop))
1220                .is_err());
1221            assert!(FrameSyncAudioRequest::capture_at(48_000, channels, samples)
1222                .and_then(|request| fs.capture_audio(request))
1223                .is_err());
1224        }
1225
1226        let ((), allocations) = crate::test_alloc::allocation_count(|| {
1227            for _ in 0..1000 {
1228                std::hint::black_box(
1229                    FrameSyncAudioRequest::capture_at(48_000, 2, 8_388_608).unwrap(),
1230                );
1231            }
1232        });
1233        assert_eq!(allocations, 0);
1234        let (request, allocations) = crate::test_alloc::allocation_count(|| {
1235            FrameSyncAudioRequest::capture_at(48_000, 2, 1024).unwrap()
1236        });
1237        assert_eq!(allocations, 0);
1238        for _ in 0..3 {
1239            let ((), allocations) = crate::test_alloc::allocation_count(|| {
1240                let frame = fs.capture_audio_ref(std::hint::black_box(request)).unwrap();
1241                assert_eq!(
1242                    (
1243                        frame.sample_rate(),
1244                        frame.num_channels(),
1245                        frame.num_samples()
1246                    ),
1247                    (48_000, 2, 1024)
1248                );
1249                assert!(frame
1250                    .channels()
1251                    .all(|channel| channel.iter().all(|&s| s == 0.0)));
1252                assert_eq!(frame.timestamp(), None);
1253            });
1254            assert_eq!(allocations, 0);
1255            let owned = fs.capture_audio(request).unwrap();
1256            assert_eq!(owned.timestamp(), None);
1257            assert_eq!((owned.num_channels(), owned.num_samples()), (2, 1024));
1258        }
1259
1260        // No audio has arrived: a request at any explicit shape still gets
1261        // silence in exactly that shape from both entry points, and each
1262        // capture frees the SDK descriptor exactly once.
1263        let shaped = FrameSyncAudioRequest::capture_at(44_100, 6, 480).unwrap();
1264        let frame = fs.capture_audio_ref(shaped).unwrap();
1265        assert_eq!(
1266            (
1267                frame.sample_rate(),
1268                frame.num_channels(),
1269                frame.num_samples()
1270            ),
1271            (44_100, 6, 480)
1272        );
1273        assert_eq!(frame.channels().count(), 6);
1274        assert!(frame
1275            .channels()
1276            .all(|channel| channel.len() == 480 && channel.iter().all(|&s| s == 0.0)));
1277        drop(frame);
1278        let owned = fs.capture_audio(shaped).unwrap();
1279        assert_eq!(
1280            (
1281                owned.sample_rate(),
1282                owned.num_channels(),
1283                owned.num_samples()
1284            ),
1285            (44_100, 6, 480)
1286        );
1287
1288        // The input-format query reports that no source format is known, frees
1289        // what the SDK returned exactly once, and allocates nothing.
1290        for _ in 0..3 {
1291            let (format, allocations) =
1292                crate::test_alloc::allocation_count(|| fs.audio_input_format());
1293            assert_eq!(format.unwrap(), None);
1294            assert_eq!(allocations, 0);
1295        }
1296    }
1297
1298    #[test]
1299    fn test_video_empty_classifier_accepts_only_all_zero() {
1300        let empty = NDIlib_video_frame_v2_t::default();
1301        assert!(is_framesync_video_empty(&empty));
1302
1303        let mut partial = NDIlib_video_frame_v2_t {
1304            xres: 1920,
1305            ..NDIlib_video_frame_v2_t::default()
1306        };
1307        assert!(!is_framesync_video_empty(&partial));
1308
1309        let mut byte = 0u8;
1310        partial = NDIlib_video_frame_v2_t {
1311            p_data: &mut byte as *mut u8,
1312            ..NDIlib_video_frame_v2_t::default()
1313        };
1314        assert!(!is_framesync_video_empty(&partial));
1315    }
1316
1317    #[test]
1318    fn test_framesync_video_ref_uses_validated_layout() {
1319        let width = 16;
1320        let height = 8;
1321        let stride = width * 4;
1322        let expected_len = (stride * height) as usize;
1323        let mut data = vec![0u8; expected_len];
1324        let mut metadata = b"framesync video\0".to_vec();
1325
1326        let raw = NDIlib_video_frame_v2_t {
1327            xres: width,
1328            yres: height,
1329            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
1330            frame_rate_N: 60,
1331            frame_rate_D: 1,
1332            picture_aspect_ratio: 16.0 / 9.0,
1333            frame_format_type: ScanType::Progressive.to_sdk(),
1334            timecode: 0,
1335            p_data: data.as_mut_ptr(),
1336            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
1337                line_stride_in_bytes: stride,
1338            },
1339            p_metadata: metadata.as_mut_ptr().cast(),
1340            timestamp: 0,
1341        };
1342
1343        let guard =
1344            unsafe { Guard::<FrameSyncVideoFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
1345        let frame = FrameSyncVideoRef::new(guard).expect("valid video frame");
1346
1347        assert_eq!(frame.metadata(), Some("framesync video"));
1348        assert_eq!(frame.data().unwrap().len(), expected_len);
1349        assert_eq!(frame.line_stride_bytes(), stride as usize);
1350        let owned = frame.to_owned();
1351        assert_eq!(owned.metadata(), Some("framesync video"));
1352        assert!(format!("{frame:?}").contains("FrameSyncVideoRef"));
1353    }
1354
1355    #[test]
1356    fn test_framesync_video_ref_withholds_malformed_metadata() {
1357        let width = 16;
1358        let height = 8;
1359        let stride = width * 4;
1360        let expected_len = (stride * height) as usize;
1361        let mut data = vec![0u8; expected_len];
1362        let mut metadata = vec![b'x'; crate::frames::MAX_METADATA_BYTES];
1363
1364        let raw = NDIlib_video_frame_v2_t {
1365            xres: width,
1366            yres: height,
1367            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
1368            frame_rate_N: 60,
1369            frame_rate_D: 1,
1370            picture_aspect_ratio: 16.0 / 9.0,
1371            frame_format_type: ScanType::Progressive.to_sdk(),
1372            timecode: 0,
1373            p_data: data.as_mut_ptr(),
1374            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
1375                line_stride_in_bytes: stride,
1376            },
1377            p_metadata: metadata.as_mut_ptr().cast(),
1378            timestamp: 0,
1379        };
1380
1381        let guard =
1382            unsafe { Guard::<FrameSyncVideoFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
1383        let frame = FrameSyncVideoRef::new(guard).unwrap();
1384        assert_eq!(frame.metadata(), None);
1385        assert_eq!(
1386            frame.metadata_status(),
1387            crate::FrameMetadataStatus::Unterminated
1388        );
1389        assert_eq!(frame.to_owned().metadata(), None);
1390    }
1391
1392    #[test]
1393    fn test_framesync_video_ref_rejects_partial_empty() {
1394        let raw = NDIlib_video_frame_v2_t {
1395            xres: 16,
1396            yres: 8,
1397            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
1398            frame_rate_N: 60,
1399            frame_rate_D: 1,
1400            picture_aspect_ratio: 16.0 / 9.0,
1401            frame_format_type: ScanType::Progressive.to_sdk(),
1402            timecode: 0,
1403            p_data: ptr::null_mut(),
1404            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
1405                line_stride_in_bytes: 16 * 4,
1406            },
1407            p_metadata: ptr::null(),
1408            timestamp: 0,
1409        };
1410
1411        let guard =
1412            unsafe { Guard::<FrameSyncVideoFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
1413        let result = FrameSyncVideoRef::new(guard);
1414        assert!(matches!(result, Err(Error::InvalidFrame(_))));
1415    }
1416
1417    /// The answer to an input-format query maps to `None` for the no-source
1418    /// state and to the format otherwise; samples in the answer are refused.
1419    #[test]
1420    fn input_format_maps_no_source_and_format_states() {
1421        let fltp = crate::FourCc::from(crate::AudioFormat::Fltp).raw();
1422        // No source yet, with the FourCC unset or set.
1423        let no_source = NDIlib_audio_frame_v3_t::default();
1424        assert_eq!(input_format(&no_source).unwrap(), None);
1425        let no_source_fltp = NDIlib_audio_frame_v3_t {
1426            FourCC: fltp,
1427            ..no_source
1428        };
1429        assert_eq!(input_format(&no_source_fltp).unwrap(), None);
1430
1431        let format = NDIlib_audio_frame_v3_t {
1432            sample_rate: 48_000,
1433            no_channels: 2,
1434            FourCC: fltp,
1435            ..no_source
1436        };
1437        let format = input_format(&format).unwrap().expect("a reported format");
1438        assert_eq!((format.sample_rate(), format.num_channels()), (48_000, 2));
1439        let widest = NDIlib_audio_frame_v3_t {
1440            sample_rate: i32::MAX,
1441            no_channels: i32::MAX,
1442            FourCC: fltp,
1443            ..no_source
1444        };
1445        let widest = input_format(&widest).unwrap().expect("a reported format");
1446        assert_eq!(widest.sample_rate(), i32::MAX.unsigned_abs());
1447        assert_eq!(widest.num_channels(), i32::MAX.unsigned_abs());
1448        assert!(FrameSyncAudioRequest::capture_at(widest.sample_rate(), 2, 1).is_ok());
1449
1450        // Well-formed samples are still not an answer to a query.
1451        let mut samples = [0.0f32; 8];
1452        let with_samples = NDIlib_audio_frame_v3_t {
1453            sample_rate: 48_000,
1454            no_channels: 2,
1455            no_samples: 4,
1456            FourCC: fltp,
1457            p_data: samples.as_mut_ptr().cast(),
1458            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
1459                channel_stride_in_bytes: 16,
1460            },
1461            ..no_source
1462        };
1463        match input_format(&with_samples) {
1464            Err(Error::InvalidFrame(message)) => {
1465                assert!(
1466                    matches!(
1467                        message,
1468                        crate::FrameDefect::FrameSyncAudioInput {
1469                            channels: 2,
1470                            samples: 4
1471                        }
1472                    ),
1473                    "{message}"
1474                )
1475            }
1476            other => panic!("expected InvalidFrame, got {other:?}"),
1477        }
1478        // A partial state is neither answer.
1479        for (sample_rate, no_channels) in [(48_000, 0), (0, 2), (-1, 2), (48_000, -1)] {
1480            let partial = NDIlib_audio_frame_v3_t {
1481                sample_rate,
1482                no_channels,
1483                FourCC: fltp,
1484                ..no_source
1485            };
1486            assert!(matches!(
1487                input_format(&partial),
1488                Err(Error::InvalidFrame(_))
1489            ));
1490        }
1491    }
1492
1493    /// A capture always holds samples: neither SDK state without samples is a
1494    /// FrameSync audio frame.
1495    #[test]
1496    fn test_framesync_audio_ref_capture_rejects_empty() {
1497        let no_source = NDIlib_audio_frame_v3_t::default();
1498        let format_only = NDIlib_audio_frame_v3_t {
1499            sample_rate: 48_000,
1500            no_channels: 2,
1501            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
1502            ..no_source
1503        };
1504        for raw in [no_source, format_only] {
1505            let released = std::cell::Cell::new(0usize);
1506            // SAFETY: both descriptors have null storage. The callback's
1507            // synthetic instance retains this live release counter only.
1508            let guard = unsafe {
1509                Guard::<FrameSyncAudioFree>::with_test_free(
1510                    ptr::from_ref(&released).cast_mut().cast(),
1511                    raw,
1512                    |instance, _| {
1513                        let released = &*instance.cast::<std::cell::Cell<usize>>();
1514                        released.set(released.get() + 1);
1515                    },
1516                )
1517            };
1518            let result = FrameSyncAudioRef::new(guard);
1519
1520            assert!(matches!(result, Err(Error::InvalidFrame(_))));
1521            assert_eq!(released.get(), 1, "empty input-format guard releases once");
1522        }
1523    }
1524
1525    #[test]
1526    fn test_framesync_audio_ref_supports_strided_planar_data() {
1527        let no_samples = 4;
1528        let no_channels = 2;
1529        let stride_samples = 6;
1530        let mut data = vec![0.0f32; 10];
1531        let mut metadata = b"framesync audio\0".to_vec();
1532        data[0..4].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
1533        data[6..10].copy_from_slice(&[10.0, 20.0, 30.0, 40.0]);
1534
1535        let raw = NDIlib_audio_frame_v3_t {
1536            sample_rate: 48000,
1537            no_channels,
1538            no_samples,
1539            timecode: 0,
1540            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
1541            p_data: data.as_mut_ptr() as *mut u8,
1542            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
1543                channel_stride_in_bytes: stride_samples * 4,
1544            },
1545            p_metadata: metadata.as_mut_ptr().cast(),
1546            timestamp: 0,
1547        };
1548
1549        let guard =
1550            unsafe { Guard::<FrameSyncAudioFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
1551        let frame = FrameSyncAudioRef::new(guard).expect("strided audio frame");
1552
1553        assert_eq!(frame.metadata(), Some("framesync audio"));
1554        assert!(frame.data().is_none());
1555        assert_eq!(frame.format(), AudioFormat::Fltp);
1556        assert_eq!(frame.channel_data(0), Some(&[1.0, 2.0, 3.0, 4.0][..]));
1557        assert_eq!(frame.channel_data(1), Some(&[10.0, 20.0, 30.0, 40.0][..]));
1558        assert_eq!(frame.channel_stride_bytes(), stride_samples as usize * 4);
1559        assert!(format!("{frame:?}").contains("FrameSyncAudioRef"));
1560
1561        let owned = frame.to_owned();
1562        assert_eq!(owned.metadata(), Some("framesync audio"));
1563        assert_eq!(owned.data().len(), 8);
1564        assert_eq!(owned.channel_stride_bytes(), 16);
1565        assert_eq!(owned.channel_data(1), Some(&[10.0, 20.0, 30.0, 40.0][..]));
1566    }
1567
1568    #[test]
1569    fn test_framesync_audio_ref_withholds_invalid_utf8_metadata() {
1570        let no_samples = 4;
1571        let no_channels = 2;
1572        let mut data = vec![0.0f32; (no_samples * no_channels) as usize];
1573        let mut metadata = vec![0xFF, 0];
1574
1575        let raw = NDIlib_audio_frame_v3_t {
1576            sample_rate: 48000,
1577            no_channels,
1578            no_samples,
1579            timecode: 0,
1580            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
1581            p_data: data.as_mut_ptr() as *mut u8,
1582            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
1583                channel_stride_in_bytes: no_samples * 4,
1584            },
1585            p_metadata: metadata.as_mut_ptr().cast(),
1586            timestamp: 0,
1587        };
1588
1589        let guard =
1590            unsafe { Guard::<FrameSyncAudioFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
1591        let frame = FrameSyncAudioRef::new(guard).unwrap();
1592        assert_eq!(frame.metadata(), None);
1593        assert_eq!(frame.metadata_status(), crate::FrameMetadataStatus::NotUtf8);
1594        assert_eq!(frame.to_owned().metadata(), None);
1595    }
1596}