Skip to main content

Receiver

Struct Receiver 

Source
pub struct Receiver<M: ReceiverMode = RawCapture> { /* private fields */ }
Expand description

An owned NDI receiver. The default mode permits all raw capture kinds. FrameSync and the Advanced AvSync change the mode of the receiver they hold while retaining the same resource core. The Advanced PacketReceiver creates its receiver in PacketAttached mode; see ReceiverMode.

Dropping the receiver disconnects it from its source, unless a RecvAdvertiser registration still holds it: a registered receiver stays connected, and advertised, until that registration is removed or its advertiser is dropped.

§Waiting

Captures, events, source-name waits, getters, Self::is_connected and Self::connection_target never wait for a local connection change. Shared controls serialize briefly with one another. On Standard Windows, PTZ commands, upstream metadata and connection-metadata additions return Error::NotConnected during a local connection change; tally is retained and applied when that native request returns. These controls do not wait for the change. The Standard Windows SDK does not provide the native exclusion necessary for SDK-internal changes, so an advertiser refuses remote receiver control there. Other runtimes synchronize controls with local and SDK-internal changes through their native receiver lock. Local Self::connect_to, Self::disconnect and Self::reconnect requests serialize with one another and may wait for running allocator policies. Dropping the last owner destroys the native receiver on the dropping thread, including when the owner is an async adapter or registration.

Implementations§

Source§

impl Receiver

Source

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

Wait up to timeout for video, audio, metadata, or a receiver event, borrowing delivered media directly from the SDK without a payload copy or allocation. No Advanced feature or runtime is required.

A single native wait requests every media kind, so a silent stream does not delay other kinds behind its own timeout. All capture methods share the same wait-budget and zero-timeout behavior described by Self::capture_video_ref. The returned item borrows this receiver; media references may move to scoped worker threads while that borrow remains live.

Pending and native events are consumed once, competing with Self::next_event and other combined captures. They are coalesced invalidations, with no ordered history or broadcast guarantee. Typed media captures retain their events for these consumers. ReceiverEvent::SourceChanged requires the separate Self::wait_for_source_name_change query for the new name.

This operation exists only in ordinary raw-capture mode. FrameSync, AvSync and packet receivers reserve some or all native media slots.

§Errors

Error::InvalidInput when timeout exceeds crate::MAX_TIMEOUT, Error::ConnectionLost when the SDK reports a lost connection, and the same frame-validation errors as typed borrowed capture. Rejected frames are freed through their matching native free operation. Error::UnexpectedSdkResult reports a negative status connection count once per publication. That status stays pending for recovery; other events and subsequent media capture remain available.

Source

pub fn capture_any(&self, timeout: Duration) -> Result<Option<ReceiverItem>>

Wait up to timeout for any media or receiver event and return an owned item. See Self::capture_any_ref for delivery and wait rules.

Media is copied through the same validated paths as typed capture: active video rows are packed, audio channel padding is omitted, and timing and metadata are preserved. Video/audio allocate one payload buffer plus metadata when present; standalone metadata allocates its text. Events allocate nothing. Copying may finish after the wait budget expires. Use Self::capture_any_ref for in-place processing.

§Errors

The errors of Self::capture_any_ref.

Source

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

Create a receiver, requesting the configured source if one is set.

§Errors

Returns Error::UnsupportedCapability when the options need a mode the selected runtime lacks, or carry an Advanced configuration that the runtime or this build cannot take; Error::InvalidCString for a receiver name that contains a NUL byte; and Error::NativeOperationFailed when the SDK creates no receiver.

Source§

impl<M: VideoMode> Receiver<M>

Source

pub fn capture_video(&self, timeout: Duration) -> Result<Option<VideoFrame>>

Wait up to timeout for video and copy it into an owned frame.

A zero timeout makes one nonblocking SDK attempt. Early SDK status and source reports are retained for next_event, or, on an attached receiver, for the raw receiver that detaching returns; capture continues until a frame arrives or the budget expires. Each native attempt waits at most 100 ms; validation and copying can finish after the budget. None alone does not establish disconnection or freshness.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source

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

Wait up to timeout for video and borrow its native buffer.

The returned frame borrows the receiver and releases its SDK buffer when dropped. Capture retains status and source reports for next_event, or, on an attached receiver, for the raw receiver that detaching returns. A zero timeout makes one nonblocking attempt; each other attempt waits at most 100 ms within the shared budget.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source§

impl<M: AudioMode> Receiver<M>

Source

pub fn capture_audio(&self, timeout: Duration) -> Result<Option<AudioFrame>>

Wait up to timeout for audio and copy it into an owned frame.

A zero timeout makes one nonblocking SDK attempt. Early SDK status and source reports are retained for next_event, or, on an attached receiver, for the raw receiver that detaching returns; capture continues until a frame arrives or the budget expires. Each native attempt waits at most 100 ms; validation and copying can finish after the budget. None alone does not establish disconnection or freshness.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source

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

Wait up to timeout for audio and borrow its native buffer.

The returned frame borrows the receiver and releases its SDK buffer when dropped. Capture retains status and source reports for next_event, or, on an attached receiver, for the raw receiver that detaching returns. A zero timeout makes one nonblocking attempt; each other attempt waits at most 100 ms within the shared budget.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source§

impl<M: MetadataMode> Receiver<M>

Source

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

Wait up to timeout for metadata and copy it into an owned frame.

A zero timeout makes one nonblocking SDK attempt. Early SDK status and source reports are retained for next_event, or, on an attached receiver, for the raw receiver that detaching returns; capture continues until a frame arrives or the budget expires. Each native attempt waits at most 100 ms; validation and copying can finish after the budget. None alone does not establish disconnection or freshness.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source

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

Wait up to timeout for metadata and borrow its native buffer.

The returned frame borrows the receiver and releases its SDK buffer when dropped. Capture retains status and source reports for next_event, or, on an attached receiver, for the raw receiver that detaching returns. A zero timeout makes one nonblocking attempt; each other attempt waits at most 100 ms within the shared budget.

§Errors

Invalid timeouts, a lost connection, or invalid SDK frame data.

Source§

impl<M: ReceiverMode> Receiver<M>

Source

pub fn set_video_delay(&self, delay: ReceiveDelay) -> Result<SettingChange>

Set native video buffering.

SettingChange::Unchanged means the delay already had this value. Delay is independent of audio buffering and stacks with FrameSync correction.

§Errors

Error::UnsupportedCapability without RuntimeFeature::ReceiveDelay.

Source

pub fn video_delay(&self) -> Result<ReceiveDelay>

Return the effective native video delay. Requires receiver-delay support.

§Errors

Error::UnsupportedCapability without RuntimeFeature::ReceiveDelay, and Error::UnexpectedSdkResult when the SDK reports a delay outside 0 to 2000 ms.

Source

pub fn set_audio_delay(&self, delay: ReceiveDelay) -> Result<SettingChange>

Set native audio buffering independently of Self::set_video_delay.

Equal audio and video delays preserve their relative timing; different values deliberately offset the streams.

§Errors

As for Self::set_video_delay.

Source

pub fn audio_delay(&self) -> Result<ReceiveDelay>

Return the effective native audio delay. Requires receiver-delay support.

§Errors

As for Self::video_delay.

Source

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

Add validated metadata sent immediately and again on each connection.

Accepts owned or captured metadata. The receiver keeps its own copy, so the input need not outlive the registration.

On Windows x64, the Standard NDI 6.3.2.0 and 6.4.0.2 builds tested in issue #551 can omit automatic delivery. Applications that manage reconnects can send the payload explicitly with Self::send_metadata after confirming each connection is live. Use a single send path for the payload to avoid duplicates.

§Errors

Error::UnsupportedCapability without RuntimeFeature::ReceiverConnectionMetadata. Error::NotConnected during a local connection change on Standard Windows; no metadata is registered in that case.

Source

pub fn clear_connection_metadata(&self) -> Result<()>

Clear metadata registered for subsequent receiver connections.

§Errors

Error::UnsupportedCapability without RuntimeFeature::ReceiverConnectionMetadata.

Source

pub fn web_control_url(&self) -> Result<Option<String>>

Copy the optional device web-control URL. This does not open the URL.

§Errors

Error::UnsupportedCapability without RuntimeFeature::ReceiverWebControl, Error::InvalidUtf8 for an invalid URL encoding, and Error::UnexpectedSdkResult when the SDK does not terminate the URL within the bounded string scan.

Source

pub fn wait_for_source_name_change( &self, timeout: Duration, ) -> Result<Option<SourceNameChange>>

Observe a change to the actual connected source name.

None means no change within the wait budget; Disconnected is an observed change to no source. Concurrent pollers compete for notifications. This differs from Self::connection_target, the latest requested target.

The SDK reports each change once. This notification replaces invalid UTF-8 sequences with U+FFFD so the change remains visible.

§Errors

Error::InvalidInput when timeout exceeds crate::MAX_TIMEOUT, Error::UnsupportedCapability without RuntimeFeature::ConnectedSourceName, and Error::UnexpectedSdkResult when the SDK does not terminate the name within the bounded string scan.

Source

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

Request a different source and remember it as the connection target.

Serializes with other local connection changes, then issues the request and updates Self::connection_target together. Captures may continue while the SDK applies the change. Success means the request was issued, not that the source is available. The source was validated at construction. Existing FrameSync ownership remains. An empty name and an absent or empty address act like Self::disconnect, preserving any last target.

Source

pub fn disconnect(&self)

Disconnect while retaining the target for Self::reconnect.

Serializes with other local connection changes, as Self::reconnect does, while captures may continue.

Source

pub fn set_tally(&self, tally: Tally)

Publish this receiver’s program and preview tally to its source.

The SDK keeps the state and sends it to every source the receiver connects to, so it can be set before a connection and survives a reconnect. On Standard Windows a tally changed during a local connection request is retained and sent as that request finishes.

Source

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

Send metadata upstream, to the source this receiver is connected to.

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

§Errors

Error::NotConnected when the receiver is connected to no source, so nothing was sent, or during a local connection change on Standard Windows. See the waiting contract.

Source

pub fn ptz(&self) -> Ptz<'_>

Control the pan, tilt, zoom, focus, white balance and exposure of the connected source.

§Examples
let ptz = receiver.ptz();
if ptz.is_supported() {
    ptz.zoom(0.5)?;
    ptz.pan_tilt(-0.25, 0.1)?;
    ptz.auto_focus()?;
}
Source

pub fn is_connected(&self) -> bool

Check if the receiver is still connected to its source.

Returns true if there is at least one native connection to the source, false otherwise. A connection does not establish progress of any particular media stream; see the reception monitoring guide.

§Examples
if receiver.is_connected() {
    println!("Still connected to source");
} else {
    println!("Lost connection to source");
}

A negative native count reports no established connection; use Self::connection_stats to inspect that SDK contract error.

Source

pub fn reconnect(&self)

Re-establish this receiver’s connection to its latest requested target, in place.

Re-points the existing NDI receiver instance at the Source it most recently requested through Self::connect_to (or its initial source) without destroying and recreating the receiver. This is intended for mid-session recovery: when a source’s feed has gone silent (for example an encoder-bound NDI|HX camera that dropped its proxy stream under load), a reconnect forces a fresh connection attempt while avoiding the source-rediscovery round trip — and the discovery race — that tearing down and rebuilding the receiver would incur.

This requests the last local target again. If a Discovery Server client remotely changed this receiver’s source, reconnecting replaces that remote routing with the local target. Observe remote changes through Self::wait_for_source_name_change. Before a local target is selected, this call returns without issuing an SDK request.

Observe native connection state with Self::is_connected and progress of the expected media with Self::connection_stats. A reconnect alone does not establish that new media has arrived.

§Thread safety

Local connection changes serialize with one another. They may overlap captures, including FrameSync and AV sync, so this method does not wait for a Rust capture gate. Native synchronization and the request itself still run on the calling thread; async code should use AsyncReceiver::reconnect to run that work on its blocking pool.

Uses the retained, validated target without allocation or conversion. NDIlib_recv_connect reports no status. Confirm recovery through Self::connection_stats.

Source

pub fn connection_target(&self) -> Option<Source>

An owned snapshot of the latest locally requested connection target.

Initially the source specified in ReceiverOptions, or None when created disconnected. Self::connect_to remembers each selected source. Self::disconnect retains it, and Self::reconnect requests it again. A Discovery Server client’s remote connection change does not update this local target. Observe actual connection changes with Self::wait_for_source_name_change. The snapshot shares the source’s name and address. It never waits for captures or queued connection changes; a concurrent connect_to holds the target lock only while replacing the value after its request returns.

if let Some(target) = receiver.connection_target() {
    println!("Requested target: {target}");
}
Source

pub fn connection_stats(&self) -> Result<ConnectionStats>

Get connection and performance statistics for this receiver.

Provides detailed statistics including:

  • Number of active connections
  • Total frames received (video, audio, metadata)
  • Dropped frames (video, audio, metadata)
  • Queued frames waiting to be processed

The native received totals include frames later dropped from the receiver queue or processing. These three native calls do not form an atomic connection/performance/queue snapshot. Counters may reset on connection changes; see ConnectionStats and the reception monitoring guide.

§Errors

Error::UnexpectedSdkResult when any native count is negative.

§Examples
let stats = receiver.connection_stats()?;
println!("Connections: {connections}", connections = stats.connections());
println!("Video frames: {received} (dropped: {dropped})",
         received = stats.video_frames_received(),
         dropped = stats.video_frames_dropped());
println!("Frame drop rate: {rate:.2}%",
         rate = stats.video_drop_percentage());
Source§

impl<M: EventMode> Receiver<M>

Event polling is available only before a synchronizer takes the receiver.

Source

pub fn next_event(&self, timeout: Duration) -> Result<Option<ReceiverEvent>>

Wait up to timeout for a status or source change, or return None when none came.

Events are coalesced invalidations, including those that media capture passed over and kept, not an ordered history or broadcast stream. Concurrent pollers and combined captures compete to consume a pending one. The new source name is read with the SDK’s separate Self::wait_for_source_name_change API.

The timeout is spent as the typed capture methods spend it: in attempts of at most 100 ms, each of which first takes a pending event and otherwise waits in the SDK for the rest of the attempt. The SDK’s early returns are waited over, so None comes only once the whole timeout is spent, and Duration::ZERO makes one attempt without waiting. An event that a concurrent capture keeps is returned by the next attempt. Connection changes may run concurrently with these attempts.

§Errors

Error::InvalidInput when timeout exceeds crate::MAX_TIMEOUT (~49.7 days), and Error::ConnectionLost when the SDK reports a lost connection, or Error::UnexpectedSdkResult when a status snapshot contains a negative native connection count, once per publication. Its invalidation stays pending for recovery, without hiding other events or preventing subsequent native captures.

Source§

impl<M: ReceiverMode> Receiver<M>

Source

pub fn request_keyframe(&self) -> Result<()>

Ask the source for a keyframe. The request is advisory: the source decides whether and when to send one.

§Errors

Error::UnsupportedCapability without an Advanced runtime.

Source

pub fn set_stream_tier(&mut self, tier: StreamTier) -> Result<SettingChange>

Switch between the source’s program and preview streams.

SettingChange::Unchanged when the SDK did not switch: the tier was already in effect, the receiver was created without video, or the runtime is not licensed to switch. The SDK switches only under a vendor ID that licenses this function.

§Errors

Error::UnsupportedCapability without an Advanced runtime.

Source

pub fn set_streams(&mut self, streams: MediaTypes) -> Result<SettingChange>

Choose which streams the source sends to this receiver.

SettingChange::Unchanged when the enabled streams did not change: they were already the ones requested, the request asked for a stream the receiver was created without, or the runtime is not licensed to change them. The SDK applies the change only under a vendor ID that licenses this function.

§Errors

Error::UnsupportedCapability without an Advanced runtime.

Source§

impl<M: ReceiverMode> Receiver<M>

Source

pub fn kvm(&mut self) -> Result<KvmSession<'_, M>>

Start a remote-control session with the connected source.

§Errors

Error::UnsupportedCapability without an Advanced runtime (or in a build without the Advanced SDK).

The receiver stays borrowed for the session, so only one exists at a time; use KvmSession::receiver to keep using it meanwhile.

Trait Implementations§

Source§

impl<M: ReceiverMode> Debug for Receiver<M>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<M> Freeze for Receiver<M>

§

impl<M> RefUnwindSafe for Receiver<M>
where M: RefUnwindSafe,

§

impl<M> Send for Receiver<M>

§

impl<M> Sync for Receiver<M>

§

impl<M> Unpin for Receiver<M>
where M: Unpin,

§

impl<M> UnsafeUnpin for Receiver<M>

§

impl<M> UnwindSafe for Receiver<M>
where 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.