Skip to main content

FrameSync

Struct FrameSync 

Source
pub struct FrameSync { /* private fields */ }
Expand description

Frame synchronizer for clock-corrected capture.

Converts push-based NDI streams into pull-based capture with automatic time-base correction and dynamic audio resampling.

§Ownership

FrameSync takes ownership of the Receiver (similar to how BufWriter wraps a Write). Use receiver() to access the underlying receiver for tally, PTZ, or status operations. Use into_receiver() to recover the receiver when done.

§Thread Safety

FrameSync is Send + Sync like Receiver: it may move to another thread, and one FrameSync may be shared, for example by a video render thread and an audio callback, whose captures may overlap. The SDK does not document this; it rests on how the supported runtimes behave, measured as recorded beside the Sync implementation. Self::audio_queue_depth is read without the SDK’s lock and is approximate.

The capture_* methods return owned frames, which can move to another thread. Frames returned by the capture_*_ref methods borrow from the FrameSync and are neither Send nor Sync; their immutable video plane/row views can instead be moved or shared with scoped workers while the frame guard stays on its capture thread until those workers finish.

Raw video and audio capture through the underlying receiver are disabled while this FrameSync exists, because the synchronizer takes the receiver’s video and audio; see FrameSyncAttached. Self::into_receiver destroys the synchronizer and restores raw video and audio capture before returning the receiver.

§Example

let framesync = FrameSync::new(receiver)?;

// Sample available data without waiting for a new network frame
if let Some(video) = framesync.capture_video_ref(ScanType::Progressive)? {
    println!("Video: {}x{}", video.width(), video.height());
}

// Audio capture fixes the output dimensions before entering the SDK.
let audio = framesync.capture_audio_ref(FrameSyncAudioRequest::capture_at(48_000, 2, 1_024)?)?;
println!("Audio: {} samples", audio.num_samples());

Implementations§

Source§

impl FrameSync

Source

pub fn new(receiver: Receiver) -> Result<Self, Rejected<Receiver>>

Create a frame synchronizer from a receiver.

Takes ownership of the receiver. Use receiver() to access the underlying receiver for tally, PTZ, or status operations. Use into_receiver() to recover the receiver.

§Errors

Returns the receiver, unchanged, with Error::NativeOperationFailed if the NDI SDK does not create the frame-sync instance.

§Example
let receiver = Receiver::new(&ndi, &options)?;
let framesync = FrameSync::new(receiver)?;
Source

pub fn receiver(&self) -> &Receiver<FrameSyncAttached>

Access the underlying receiver.

Use this to access receiver functionality like tally, PTZ, status queries and metadata capture while FrameSync is active. Native synchronization can consume status notifications, so this receiver has no event polling. Query capabilities with ptz().is_supported(), web_control_url() and Advanced KVM’s is_supported(); observe the source with wait_for_source_name_change() and connection state with is_connected() or connection_stats(). Tally control publishes state upstream; it does not query incoming tally. Local connection changes may run while FrameSync captures; the native overlap tests exercise recovery and valid output through those changes.

This receiver mode has no raw video or audio capture, because the synchronizer takes the receiver’s video and audio: raw audio capture would take frames the FrameSync then replaces with silence (see FrameSyncAttached). Use the FrameSync capture methods, or recover the receiver with Self::into_receiver first.

ⓘ
use grafton_ndi::FrameSync;
fn capture(framesync: &FrameSync) {
    let _ = framesync.receiver().capture_audio(std::time::Duration::ZERO);
}
Source

pub fn controls(&mut self) -> ReceiverControls<'_, FrameSyncAttached>

Borrow the receiver’s exclusive Advanced controls without lending the receiver mutably. This allocates nothing and makes no native call. Use Self::split to capture while a KVM session holds this borrow.

Source

pub fn split( &mut self, ) -> (FrameSyncCapture<'_>, ReceiverControls<'_, FrameSyncAttached>)

Lend advanced::FrameSyncCapture and ReceiverControls independently.

Neither view can replace, recover or destroy either native resource. The synchronizer and receiver keep their original instances; creating the views allocates nothing and makes no SDK call. Drop held frames and both views before recovering the receiver. A source change must be preceded by successful KvmSession::release_all and session termination.

fn drag(sync: &mut FrameSync) -> Result<()> {
    let (capture, controls) = sync.split();
    let mut session = controls.kvm()?;
    session.mouse_down(MouseButton::Left)?;
    let frame = capture.capture_video_ref(ScanType::Progressive)?;
    session.move_pointer(0.5, 0.5)?;
    session.release_all()?;
    drop(frame);
    Ok(())
}
Source

pub fn into_receiver(self) -> Receiver

Consume the FrameSync and recover the underlying Receiver.

This destroys the frame synchronizer and returns the receiver for continued use with raw capture or for creating a new FrameSync.

Source

pub fn capture_video(&self, scan_type: ScanType) -> Result<Option<VideoFrame>>

Capture video with time-base correction, as an owned frame that can be sent across threads.

This does not wait for a new network frame. It returns the best frame for the current output timing, handling clock drift and jitter automatically. The same frame may be returned multiple times when capture rate exceeds source frame rate. SDK processing takes time; concurrent captures on one FrameSync serialize briefly inside the SDK. Self::capture_video_ref borrows the frame instead of copying it.

§Arguments
  • scan_type - The desired field format. Use ScanType::Progressive for most applications. For interlaced output, use the appropriate field type to maintain correct field ordering.
§Returns
  • Ok(Some(VideoFrame)) - An owned copy of the captured frame
  • Ok(None) - The SDK returned the documented all-zero “no video yet” state
§Errors

As for Self::capture_video_ref. The owned copy itself cannot fail.

§Example
let framesync = FrameSync::new(receiver)?;

// Capture loop - call at your output frame rate
loop {
    if let Some(frame) = framesync.capture_video(ScanType::Progressive)? {
        // Process/display frame
        let rate = frame.frame_rate();
        println!("{}x{} @ {}/{} fps",
            frame.width(), frame.height(),
            rate.numerator(), rate.denominator());
    } else {
        // No video received yet - display placeholder
        println!("Waiting for video...");
    }
}
Source

pub fn capture_video_ref( &self, scan_type: ScanType, ) -> Result<Option<FrameSyncVideoRef<'_>>>

Capture video with time-base correction, borrowing the SDK’s frame without copying it.

Timing is as for Self::capture_video.

§Returns
  • Ok(Some(FrameSyncVideoRef)) - A validated zero-copy output frame; it may repeat or retain earlier input and does not prove new reception
  • Ok(None) - The SDK returned the documented all-zero “no video yet” state
§Errors

Returns Error::InvalidFrame when the SDK returned an unsupported format or malformed frame descriptor, including invalid dimensions, stride, or buffers. Unreadable per-frame metadata is withheld; inspect VideoSource::metadata_status.

Source

pub fn capture_audio( &self, request: FrameSyncAudioRequest, ) -> Result<AudioFrame>

Capture audio with dynamic resampling, as an owned frame that can be sent across threads.

This does not wait for new network audio. Capture requests ask the NDI SDK to resample incoming audio to match the requested sample rate, channel count, and sample count. SDK processing and resampling take time; concurrent captures on one FrameSync serialize briefly inside the SDK. Self::capture_audio_ref borrows the samples instead of copying them.

Call this at the rate you need audio - the SDK will adapt the incoming signal to match your output timing using dynamic audio sampling.

§Arguments
§Returns

An owned copy of the captured samples at the requested sample rate, channel count, and samples per channel. The SDK can supply silence whenever current input is unavailable. To read the SDK’s known source format, use Self::audio_input_format.

§Errors

As for Self::capture_audio_ref.

§Example
let framesync = FrameSync::new(receiver)?;

// Audio callback - called by sound card at its rate
let request = FrameSyncAudioRequest::capture_at(48_000, 2, 1_024)?;

loop {
    // Request 1024 stereo samples at 48kHz
    let audio = framesync.capture_audio(request)?;
    // Process each channel.
    for samples in audio.channels() {
        println!("Got {} samples in a channel", samples.len());
    }
}
Source

pub fn capture_audio_ref( &self, request: FrameSyncAudioRequest, ) -> Result<FrameSyncAudioRef<'_>>

Capture audio with dynamic resampling, borrowing the SDK’s samples without copying them.

Resampling is as for Self::capture_audio. The frame has the requested sample rate, channel count, and samples per channel. The SDK can supply silence whenever current input is unavailable, including after input previously arrived. Successful output does not prove fresh reception. Output without a source timestamp reports timestamp() == None; without a source timecode it carries crate::Timecode::SYNTHESIZE. See the reception monitoring guide.

§Following the source’s format

A request names its sample rate and channel count explicitly. To capture in the source’s format, wait for Self::audio_input_format to return Some, then build a request with FrameSyncAudioRequest::for_input.

§Errors

Returns Error::InvalidFrame when the SDK returns malformed audio dimensions, sample layout, or buffers. For a valid frame with dimensions that differ from the request, the cause is crate::FrameDefect::FrameSyncAudioMismatch. Request dimensions are checked at construction. Use AudioSource::metadata_status to check whether the frame’s metadata could be read.

§Example
let framesync = FrameSync::new(receiver)?;

let format = loop {
    match framesync.audio_input_format()? {
        Some(format) => break format,
        None => std::thread::sleep(Duration::from_millis(10)),
    }
};
let request = FrameSyncAudioRequest::for_input(format, 1_024)?;

let audio = framesync.capture_audio_ref(request)?;
println!("{} channels at {} Hz", audio.num_channels(), audio.sample_rate());
Source

pub fn audio_input_format(&self) -> Result<Option<AudioInputFormat>>

Query the format of the audio this FrameSync is receiving, without capturing samples.

This makes the SDK’s input-format query: one native call that does not wait for network audio and frees what the SDK returned before returning. It allocates nothing unless it fails. Like the other FrameSync methods it may be called from any thread.

§Returns
  • Ok(Some(format)) - The SDK’s known source sample rate and channel count, both positive. This knowledge may persist across starvation, disconnect, reconnect or source changes; it is not a freshness signal.
  • Ok(None) - The SDK reports no known audio format
§Errors

Returns Error::InvalidFrame when the SDK’s answer is neither of those: samples, a data pointer or channel stride, a negative value, a zero sample rate with a positive channel count or the reverse, or an unsupported FourCC.

§Example
let framesync = FrameSync::new(receiver)?;

match framesync.audio_input_format()? {
    Some(format) => println!(
        "{} channels at {} Hz",
        format.num_channels(),
        format.sample_rate()
    ),
    None => println!("No audio yet"),
}
Source

pub fn audio_queue_depth(&self) -> Result<u32>

Query the current audio queue depth.

Returns the approximate number of audio samples currently buffered. This can be useful when using an inaccurate timer for audio playback.

Note: This value may change immediately after being read as new samples are continuously received, and the SDK reads it without the lock its captures take, so a capture on another thread may be under way. For most applications, simply call capture_audio at your desired rate and let the SDK handle timing. A positive depth does not establish fresh input; see the reception monitoring guide.

§Example
let framesync = FrameSync::new(receiver)?;

// Check available samples before capture
let available = framesync.audio_queue_depth()?;
println!("Audio samples available: {}", available);
§Errors

Error::UnexpectedSdkResult when the native queue depth is negative.

Trait Implementations§

Source§

impl Debug for FrameSync

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.