Skip to main content

grafton_ndi/framesync/
capture.rs

1//! The borrowed clocked capture view, publicly named only by `advanced`.
2
3use super::{
4    input_format, AudioCall, AudioInputFormat, FrameSyncAudioRef, FrameSyncAudioRequest,
5    FrameSyncResource, FrameSyncVideoRef,
6};
7#[cfg(feature = "advanced")]
8use crate::frames::{AudioFrame, VideoFrame};
9use crate::{
10    frames::ScanType, receiver::ReceiverIdentity, Error, FrameDefect, FrameSyncAttached, Result,
11};
12use std::fmt;
13
14/// Clocked capture access lent by [`FrameSync::split`](super::FrameSync::split).
15///
16/// This view borrows only the synchronizer, leaving its receiver available
17/// through a separate exclusive control view. A KVM session can therefore hold
18/// a button or key while video and audio continue. Creating or copying the
19/// view allocates nothing and makes no SDK call. Capture has the same costs,
20/// timing, validation and stale-output semantics as [`FrameSync`](super::FrameSync).
21///
22/// The split view stays on its borrowing thread (`!Send` and `!Sync`) so
23/// exclusive stream changes stay sequenced with split capture. Share the
24/// complete FrameSync for concurrent capture instead. Borrowed output frames
25/// also remain neither `Send` nor `Sync`, retaining the owner's borrow even
26/// if the view itself is dropped.
27#[derive(Clone, Copy)]
28pub struct FrameSyncCapture<'a> {
29    resource: &'a FrameSyncResource,
30    _thread: std::marker::PhantomData<*mut ()>,
31}
32
33impl fmt::Debug for FrameSyncCapture<'_> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        let receiver = ReceiverIdentity::new::<FrameSyncAttached>(self.resource.receiver());
36        f.debug_struct("FrameSyncCapture")
37            .field("receiver", &receiver)
38            .finish_non_exhaustive()
39    }
40}
41
42impl<'a> FrameSyncCapture<'a> {
43    pub(super) fn new(resource: &'a FrameSyncResource) -> Self {
44        Self {
45            resource,
46            _thread: std::marker::PhantomData,
47        }
48    }
49
50    /// Capture an owned clocked video frame; see [`FrameSync::capture_video`](super::FrameSync::capture_video).
51    ///
52    /// # Errors
53    ///
54    /// As for [`FrameSync::capture_video_ref`](super::FrameSync::capture_video_ref).
55    #[cfg(feature = "advanced")]
56    #[doc(alias = "NDIlib_framesync_capture_video")]
57    pub fn capture_video(&self, scan_type: ScanType) -> Result<Option<VideoFrame>> {
58        Ok(self
59            .capture_video_ref(scan_type)?
60            .map(|frame| frame.to_owned()))
61    }
62
63    /// Borrow clocked video without a wrapper payload copy or allocation.
64    /// The output can repeat previous input; see [`FrameSync::capture_video_ref`](super::FrameSync::capture_video_ref).
65    ///
66    /// # Errors
67    ///
68    /// As for [`FrameSync::capture_video_ref`](super::FrameSync::capture_video_ref).
69    #[doc(alias = "NDIlib_framesync_capture_video")]
70    pub fn capture_video_ref(&self, scan_type: ScanType) -> Result<Option<FrameSyncVideoRef<'a>>> {
71        let Some(guard) = self.resource.capture_video(scan_type) else {
72            return Ok(None);
73        };
74        Ok(Some(FrameSyncVideoRef::new(guard)?))
75    }
76
77    /// Capture owned resampled audio; see [`FrameSync::capture_audio`](super::FrameSync::capture_audio).
78    ///
79    /// # Errors
80    ///
81    /// As for [`FrameSync::capture_audio_ref`](super::FrameSync::capture_audio_ref).
82    #[cfg(feature = "advanced")]
83    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
84    pub fn capture_audio(&self, request: FrameSyncAudioRequest) -> Result<AudioFrame> {
85        Ok(self.capture_audio_ref(request)?.to_owned())
86    }
87
88    /// Borrow resampled audio without a wrapper payload copy or allocation.
89    /// The SDK can return silence; see [`FrameSync::capture_audio_ref`](super::FrameSync::capture_audio_ref).
90    ///
91    /// # Errors
92    ///
93    /// As for [`FrameSync::capture_audio_ref`](super::FrameSync::capture_audio_ref).
94    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
95    pub fn capture_audio_ref(
96        &self,
97        request: FrameSyncAudioRequest,
98    ) -> Result<FrameSyncAudioRef<'a>> {
99        let guard = self.resource.capture_audio(AudioCall::Samples(request));
100        let frame = FrameSyncAudioRef::new(guard)?;
101        if frame.sample_rate() != request.sample_rate()
102            || frame.num_channels() != request.num_channels()
103            || frame.num_samples() != request.num_samples()
104        {
105            return Err(Error::InvalidFrame(FrameDefect::FrameSyncAudioMismatch));
106        }
107        Ok(frame)
108    }
109
110    /// Query the cached input audio format; see [`FrameSync::audio_input_format`](super::FrameSync::audio_input_format).
111    /// This does not establish fresh reception and allocates nothing on success.
112    ///
113    /// # Errors
114    ///
115    /// As for [`FrameSync::audio_input_format`](super::FrameSync::audio_input_format).
116    #[doc(alias = "NDIlib_framesync_capture_audio_v2")]
117    pub fn audio_input_format(&self) -> Result<Option<AudioInputFormat>> {
118        let guard = self.resource.capture_audio(AudioCall::InputFormat);
119        input_format(guard.frame())
120    }
121
122    /// The approximate queued sample count; see [`FrameSync::audio_queue_depth`](super::FrameSync::audio_queue_depth).
123    /// This makes one native query without allocating or waiting for input.
124    ///
125    /// # Errors
126    ///
127    /// [`Error::UnexpectedSdkResult`](crate::Error::UnexpectedSdkResult) when the native queue depth is negative.
128    #[doc(alias = "NDIlib_framesync_audio_queue_depth")]
129    pub fn audio_queue_depth(&self) -> Result<u32> {
130        // SAFETY: the view borrows a live synchronizer for the call.
131        let depth = unsafe {
132            self.resource
133                .receiver()
134                .sdk()
135                .named()
136                .NDIlib_framesync_audio_queue_depth(self.resource.instance.0)
137        };
138        depth.count()
139    }
140}