Skip to main content

Sender

Struct Sender 

Source
pub struct Sender<M: SenderMode = RawSend> { /* private fields */ }
Expand description

An NDI source that sends video, audio and metadata.

Create one with Sender::new. Dropping the sender completes any in-flight asynchronous video and removes the source from the network, unless a SendAdvertiser registration still holds it: a registered sender stays on the network until that registration is removed or its advertiser is dropped.

The default mode, RawSend, has every operation. The Advanced CompressedSender and QueuedSender hold their sender in another SenderMode and lend it through their sender method: it keeps the operations every mode shares, but not the video sends its owner makes itself, and it cannot be registered with an advertiser.

A sender is Send and Sync. Its operations take &self and may run on several threads at once, except the asynchronous video operations, submit_video, submit_video_copy and reclaim_video, which take &mut self. Sender::split lends these video operations to a scoped thread alongside a shared sender for audio, metadata and controls. Tally polls preserve changes for a waiting thread; concurrent tally waits serialize and each change is consumed once.

Implementations§

Source§

impl<M: AudioSendMode> Sender<M>

Interleaved audio goes through the SDK’s audio send, so every mode that sends uncompressed audio has it.

Source

pub fn send_audio_interleaved_i16( &self, frame: &InterleavedAudioI16<'_>, ) -> Result<()>

Synchronously send validated interleaved audio using the selected SDK. Source samples may be reused when this method returns. The interleaved SDK descriptors do not carry metadata or receive timestamps.

§Errors

Returns Error::UnsupportedCapability when the runtime does not provide the complete interleaved-audio send group.

Source

pub fn send_audio_interleaved_i32( &self, frame: &InterleavedAudioI32<'_>, ) -> Result<()>

Synchronously send validated interleaved audio using the selected SDK. Source samples may be reused when this method returns. The interleaved SDK descriptors do not carry metadata or receive timestamps.

§Errors

Returns Error::UnsupportedCapability when the runtime does not provide the complete interleaved-audio send group.

Source

pub fn send_audio_interleaved_f32( &self, frame: &InterleavedAudioF32<'_>, ) -> Result<()>

Synchronously send validated interleaved audio using the selected SDK. Source samples may be reused when this method returns. The interleaved SDK descriptors do not carry metadata or receive timestamps.

§Errors

Returns Error::UnsupportedCapability when the runtime does not provide the complete interleaved-audio send group.

Source§

impl Sender

Source

pub fn new(ndi: &Ndi, options: &SenderOptions) -> Result<Self>

Creates a new NDI send instance.

§Errors

Returns Error::InvalidCString when the name contains a NUL byte, Error::InvalidInput when the group list is empty or a group is empty or contains a comma or NUL, Error::UnsupportedCapability when the options carry an Advanced configuration that the runtime or this build cannot take, and Error::NativeOperationFailed when the SDK creates no sender.

Source

pub fn split(&mut self) -> (RawVideo<'_>, &Sender)

Lend asynchronous video and shared sender operations to scoped threads.

The video view is Send, but neither Sync nor Clone, keeping one asynchronous video submitter. The shared sender supports audio, metadata and controls. Both halves borrow this sender; dropping the view leaves pending video with the owner for its next submission, reclamation or drop.

Video submissions through the view synchronize with shared Self::send_video and Self::flush_video calls. Audio and metadata do not take that video lock, including while clocking paces a submission.

Source

pub fn send_video(&self, frame: &(impl VideoSource + ?Sized)) -> Result<()>

Send a video frame synchronously.

Accepts every VideoSource: owned frames, checked external buffers, receiver captures and FrameSync captures, all by shared reference. Borrowed UYVY/UYVA frames are copied into packed storage with a zeroed tail wherever crate::PixelFormat::send_tail_room is nonzero, so padding and trailing bytes cannot affect the encoded picture. The sender reuses one staging allocation. Captures with padded rows also stage, since their guard guarantees only active pixels are initialized. Packed captures needing no trailing room send in place. Owned frames retain zeroed, scan-dependent tail room and always send in place. To permit direct sending from initialized caller padding and trailing memory, explicitly use crate::BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail; crate::BorrowedVideoFrame::sends_in_place tells which a frame is.

The SDK has released the input buffer when this returns; the caller may then reuse or release it. This also completes a previous async video send.

§Errors

Returns Error::UnsupportedCapability if this sender’s runtime cannot send the frame’s pixel format (the planar 4:4:4 formats need RuntimeFeature::Planar444Video). Nothing is sent and no pending send is changed.

§Example
// 64 pixels per row, padded to a 512-byte stride.
let mut buffer = vec![0u8; 512 * 32];
let frame = BorrowedVideoFrame::builder(&buffer, 64, 32, PixelFormat::Bgra)
    .line_stride_bytes(512)
    .build()?;
sender.send_video(&frame)?;
buffer.fill(0xff); // the SDK is done with the buffer
Source

pub fn submit_video( &mut self, frame: VideoFrame, ) -> Result<Option<VideoFrame>, Rejected<VideoFrame>>

Submit an owned frame without copying its pixel or metadata allocations.

The sender takes ownership before calling the SDK. The next async send synchronizes the previous send and returns its owned frame for reuse. The first send returns None. The returned frame may have been submitted by ownership or copying. A copied submission instead retains the frame it displaces for its next copy. Call Self::reclaim_video to recover the final frame.

Synchronous sends and explicit flushes complete the operation but retain the owned frame for recovery by the next async send or Self::reclaim_video. No SDK completion callback is registered, including with Advanced SDK.

The call can still block: with SenderOptions::clock_video enabled, the default, the SDK paces video inside the call. The first can return immediately; subsequent calls wait for the next frame time. Set clock_video(false) and pace sends in the application to avoid this frame-rate wait. SDK back-pressure can also block a call. Use Self::split to send audio from another thread during submission.

§Errors

Returns the frame, unsent, with Error::UnsupportedCapability if this sender’s runtime cannot send its pixel format (the planar 4:4:4 formats need RuntimeFeature::Planar444Video). No pending send is changed.

Source

pub fn reclaim_video(&mut self) -> Option<VideoFrame>

Drain the SDK and return the final owned frame, if any.

Frames submitted through either owned or copied sending are returned. Any spare storage retained for copying is released. Repeated calls return None.

Source

pub fn submit_video_copy( &mut self, frame: &(impl VideoSource + ?Sized), ) -> Result<()>

Copy borrowed pixels and metadata, then submit the owned copy asynchronously.

The caller may immediately reuse or release the source buffer and metadata. The sender keeps the previous completed frame as spare storage for its next copy, whether that frame was submitted by ownership or copying. Once both frames have enough pixel and metadata capacity, repeated copies reuse their allocations. Larger layouts or longer metadata grow each buffer as needed.

Recover the final copy with Self::reclaim_video, which also releases the spare. Owned submissions through Self::submit_video still return the frame they displace.

The call can still block: with SenderOptions::clock_video enabled, the default, the SDK paces video inside the call. The first can return immediately; subsequent calls wait for the next frame time. Set clock_video(false) and pace sends in the application to avoid this frame-rate wait. SDK back-pressure can also block a call. Use Self::split to send audio from another thread during submission.

§Errors

Returns Error::UnsupportedCapability if this sender’s runtime cannot send the frame’s pixel format, checked before anything is copied. No pending send is changed on failure.

Source

pub fn flush_video(&self)

Flush pending async video operations synchronously.

When the SDK may still read a pending frame, sends a null video frame pointer and blocks until that asynchronous operation completes. If no frame is in flight, returns without calling the SDK.

After this returns, the SDK has released the pending buffer. The sender retains the frame; use Self::reclaim_video or an owned submission through Self::submit_video to recover it without copying.

Source§

impl<M: AudioSendMode> Sender<M>

Source

pub fn send_audio(&self, frame: &(impl AudioSource + ?Sized))

Sends an audio frame synchronously.

Accepts every AudioSource, including receiver and FrameSync captures. Samples and metadata are submitted in place with the original channel stride; no intermediate planar copy or wrapper allocation is made. The SDK has released the input buffer when this returns, so the caller may then reuse or release it. This calls NDIlib_send_send_audio_v3. It is available in the modes that implement AudioSendMode: on an ordinary sender and on the one a QueuedSender lends.

See the NDI SDK documentation section on NDIlib_send_send_audio_v3 for more details.

§Example
let mut audio_buffer = vec![0.0f32; 48000 * 2]; // 1 second of stereo audio

// Fill buffer with audio data...
let frame = AudioFrame::builder()
    .sample_rate(48000)
    .num_channels(2)
    .num_samples(48000)
    .data(audio_buffer.clone())
    .build()?;
sender.send_audio(&frame);

// Buffer can be reused immediately
audio_buffer.fill(0.5);
let frame2 = AudioFrame::builder()
    .sample_rate(48000)
    .num_channels(2)
    .num_samples(48000)
    .data(audio_buffer)
    .build()?;
sender.send_audio(&frame2);
Source§

impl<M: SenderMode> Sender<M>

Source

pub fn capture_metadata( &self, timeout: Duration, ) -> Result<Option<MetadataFrame>>

Capture metadata sent back by connected receivers.

The result owns its data. The wait budget includes contention with other metadata captures and does not block the video-send synchronization lock. Captured text uses the SDK’s guaranteed NUL termination, bounded to 4 MiB, rather than assuming every positive native length is the exact UTF-8 byte count including its terminator. Invalid descriptor counts and invalid UTF-8 still return an error, and every captured frame is freed.

§Errors

Returns Error::UnsupportedCapability when the runtime lacks the sender metadata capture functions, Error::InvalidInput when the timeout exceeds crate::MAX_TIMEOUT, Error::InvalidFrame for an invalid metadata count, a positive count with null data, or a missing bounded terminator, Error::InvalidUtf8 for non-UTF-8 text, and Error::UnexpectedSdkResult when the SDK returns a frame type other than metadata or no frame.

Source

pub fn capture_metadata_ref( &self, timeout: Duration, ) -> Result<Option<MetadataFrameRef<'_>>>

Borrow metadata sent back by connected receivers without copying it.

The frame retains capture exclusion until it is dropped, after the SDK has freed its metadata. Another capture spends its timeout waiting for that release. Video sends use a separate synchronization path. The frame can move to a scoped worker thread; its borrow keeps this sender alive through the matching native free.

§Errors

As for Self::capture_metadata.

Source

pub fn send_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S)

Sends a metadata frame.

Accepts owned or captured metadata without copying its text in the wrapper. The SDK copies the text before returning.

Source

pub fn tally(&self) -> Tally

The tally this sender currently reports.

Polls without waiting and returns the most recent state the SDK reported to this sender, whether or not it has changed since the last query. Call Self::wait_for_tally_change to block until it changes. Never fails and may be called from any thread. While another thread waits, returns the cached state without a native query. That state may lag the change until the waiter wakes. Polling preserves a change for Self::wait_for_tally_change to report.

§Examples
let ndi = Ndi::new()?;
let options = SenderOptions::new("Test Sender");
let sender = grafton_ndi::Sender::new(&ndi, &options)?;

let tally = sender.tally();
println!("On program: {}, On preview: {}", tally.on_program(), tally.on_preview());
Source

pub fn wait_for_tally_change(&self, timeout: Duration) -> Result<Option<Tally>>

Wait up to timeout for the tally to change.

Returns Ok(Some(tally)) with the new state when the SDK reports a change, and Ok(None) when timeout elapses first. Use Self::tally to read the current state without waiting. A change observed by polling is kept for the next wait. Changes coalesce, and each report goes to one waiter, rather than broadcasting to every waiter. Concurrent waits serialize their native queries; contention spends the same timeout budget as the native wait.

§Errors

Returns Error::InvalidInput if timeout exceeds crate::MAX_TIMEOUT (about 49.7 days).

§Examples
let ndi = Ndi::new()?;
let options = SenderOptions::new("Test Sender");
let sender = grafton_ndi::Sender::new(&ndi, &options)?;

if let Some(tally) = sender.wait_for_tally_change(Duration::from_secs(1))? {
    println!("On program: {}, On preview: {}", tally.on_program(), tally.on_preview());
} else {
    println!("Tally did not change");
}
Source

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

The current number of active connections, without waiting.

§Errors

Error::UnexpectedSdkResult if the SDK returns a negative count.

Source

pub fn wait_for_connection( &self, timeout: Duration, ) -> Result<Option<NonZeroU32>>

Wait up to timeout for at least one connected receiver.

Returns the nonzero connection count as soon as a receiver is present, or None when the wait expires. A zero timeout reads the current count.

§Errors

Error::UnexpectedSdkResult for a negative native count, and Error::InvalidInput when timeout exceeds crate::MAX_TIMEOUT.

Source

pub fn clear_connection_metadata(&self)

Remove all metadata registered for delivery to each new connection.

Source

pub fn add_connection_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S)

Register metadata sent now and to every new connection.

Accepts owned or captured metadata. The SDK retains its own copy, so the input can be released as soon as this method returns.

Source

pub fn set_failover(&self, source: &Source)

Set the validated failover source.

Source

pub fn clear_failover(&self)

Clear the failover source previously configured with Self::set_failover.

Source

pub fn source(&self) -> Result<Source>

Get the source information for this sender.

§Errors

Returns Error::NativeOperationFailed when the SDK supplies no descriptor, or one that names neither a source nor an address, and Error::UnexpectedSdkResult when its name or address is longer than the 4 MiB available for one SDK string, including its terminator. Error::InvalidUtf8 reports an invalid name or address. Error::AllocationFailed reports a failed text buffer reservation. See crate::Finder::current_sources for allocation behavior of shared source owners.

§Examples
let ndi = Ndi::new()?;
let options = SenderOptions::new("Test Sender");
let sender = grafton_ndi::Sender::new(&ndi, &options)?;
let source = sender.source()?;
println!("Sender source: {source}");
Source§

impl<M: SenderMode> Sender<M>

Source

pub fn set_external_tally(&self, tally: Tally) -> Result<()>

Set this sender’s own contribution to its tally state, which is otherwise the combination of what its receivers report: for instance, that it is known to be on air. The SDK reflects the state to the sender’s receivers.

§Errors

Error::UnsupportedCapability without an Advanced runtime.

Source

pub fn target_frame_bytes(&self, format: VideoPacketFormat) -> Result<u32>

The compressed frame size, in bytes, an encoder should aim for when producing format for this sender’s connections.

§Errors

Error::UnsupportedCapability without an Advanced runtime, and Error::UnexpectedSdkResult when the SDK returns a negative size.

Source

pub fn target_bit_rate(&self, format: VideoPacketFormat) -> Result<u32>

The bit rate, in bits per second, an encoder should aim for when producing format for this sender’s connections.

§Errors

As for target_frame_bytes, with a negative bit rate.

Source

pub fn legacy_quality(&self, format: VideoPacketFormat) -> Result<u32>

The SpeedHQ quality factor for format, as the original quality query reports it. It says nothing about whether receivers accept the newer SpeedHQ format; quality_plan does.

§Errors

Error::UnsupportedCapability without an Advanced runtime, Error::InvalidInput when format is not SpeedHQ, and Error::UnexpectedSdkResult when the SDK returns a negative quality for one that is.

Source

pub fn quality_plan( &self, format: VideoPacketFormat, supports_new_format: bool, ) -> Result<QualityPlan>

The SpeedHQ quality for format and whether the connected receivers accept the newer SpeedHQ format. Pass supports_new_format as true when the encoder can produce it.

§Errors

As for legacy_quality.

Source

pub fn keyframe_required( &self, format: Option<VideoPacketFormat>, ) -> Result<bool>

Whether a connected receiver needs a keyframe: on the stream format names, or on any stream when format is None.

§Errors

Error::UnsupportedCapability without an Advanced runtime.

Source

pub fn wait_for_keyframe_change( &self, format: Option<VideoPacketFormat>, timeout: Duration, ) -> Result<bool>

Wait up to timeout for keyframe demand to change, on the stream format names or on any stream when it is None.

Returns whether a change was signalled; call keyframe_required for the new state. Concurrent waiters share one native update report. A format-specific waiter reports the update when the shared sample observes demand for that stream; otherwise it keeps waiting within the same timeout. Demand is sampled once per active stream selector before any observer is woken, so a send made by the first observer cannot erase another observer’s report. These are coalesced invalidations, not a per-stream event history: pending demand can be reported again, or a concurrent send can clear it before the shared sample. A zero timeout beside another native waiter only reads reports that waiter has already published.

§Errors

Error::UnsupportedCapability without an Advanced runtime, and Error::InvalidInput when timeout exceeds crate::MAX_TIMEOUT.

Source§

impl<M: CompressedAudioSendMode> Sender<M>

Source

pub fn send_compressed_audio( &self, frame: &mut CompressedFrame<AudioPacketFormat>, )

Send a compressed audio frame synchronously, alongside the owner’s video. The frame is borrowed exclusively because the SDK writes to its envelope. The compressed or queued mode proves runtime availability; the frame’s type proves send admission.

Source

pub fn send_scatter_audio( &self, frame: &mut ScatterFrame<AudioPacketFormat>, ) -> Result<()>

Send compressed audio held in separate blocks synchronously. The frame remains exclusively borrowed through native release.

§Errors

crate::Error::UnsupportedCapability when scatter sending is unavailable in the selected runtime or build headers.

Trait Implementations§

Source§

impl<M: SenderMode> Debug for Sender<M>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<M = RawSend> !Freeze for Sender<M>

§

impl<M> RefUnwindSafe for Sender<M>
where <M as Sealed>::Native: RefUnwindSafe, M: RefUnwindSafe,

§

impl<M> Send for Sender<M>

§

impl<M> Sync for Sender<M>

§

impl<M> Unpin for Sender<M>
where <M as Sealed>::Native: Unpin, M: Unpin,

§

impl<M> UnsafeUnpin for Sender<M>
where <M as Sealed>::Native: UnsafeUnpin,

§

impl<M> UnwindSafe for Sender<M>
where <M as Sealed>::Native: UnwindSafe, M: UnwindSafe,

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.