pub struct AsyncReceiver<R: AsyncRuntime> { /* private fields */ }Expand description
An async wrapper over a Receiver that runs its blocking NDI operations
on the blocking thread pool of the runtime R, so that they do not block
the async runtime.
tokio::AsyncReceiver names it for Tokio.
smol::AsyncReceiver names it for smol.
§Thread Safety
The underlying Receiver is shared through an Arc. The SDK documents
concurrent capture calls in Processing.NDI.Recv.h. Local connection
changes serialize with one another and may overlap captures, as described
by Receiver::reconnect. Source-name waits serialize with one another;
waiting for another poller counts against the caller’s wait budget.
§Events and controls
A capture that the SDK answers with a status or source change instead of
a frame keeps that change for next_event, as the
synchronous captures keep it for Receiver::next_event: both read the
same pending events. receiver lends the receiver for
shared controls, such as tally, PTZ and upstream metadata; see
Receiver’s waiting contract.
§Error Handling
Error::SpawnFailed carries a typed SpawnFailure for a missing Tokio
context or a cancelled task. A panic on the worker is resumed on the awaiting
task with its original payload, after SDK guards are released on the worker.
An abandoned operation discards media and any caught panic payload;
undelivered events and source-name changes are retained for later waits.
A source-name or unknown-event report is redelivered only while no newer
report has superseded it; replay never waits for a native query.
§Example
use grafton_ndi::{Ndi, ReceiverOptions, asynchronous::tokio::AsyncReceiver};
#[tokio::main]
async fn main() -> Result<(), grafton_ndi::Error> {
let ndi = Ndi::new()?;
// ... obtain source ...
let options = ReceiverOptions::snapshot_preset(source);
let receiver = grafton_ndi::Receiver::new(&ndi, &options)?;
let async_receiver = AsyncReceiver::new(receiver);
// Capture without blocking the runtime
match async_receiver.capture_video_with(std::time::Duration::from_millis(100), |frame| {
(frame.width(), frame.height())
}).await? {
Some(size) => println!("Got dimensions: {size:?}"),
None => println!("No frame available"),
}
Ok(())
}Implementations§
Source§impl<R: AsyncRuntime> AsyncReceiver<R>
impl<R: AsyncRuntime> AsyncReceiver<R>
Sourcepub fn new(receiver: Receiver) -> Self
pub fn new(receiver: Receiver) -> Self
Create a new async receiver wrapper.
The receiver is wrapped in an Arc to allow sharing across async tasks.
Sourcepub fn receiver(&self) -> &Receiver
pub fn receiver(&self) -> &Receiver
The receiver this wraps, lent for its controls: tally, PTZ, upstream
and connection metadata, delays, the web-control URL and the latest
connection_target.
The receiver is shared with every clone of this AsyncReceiver and
with the async operations they have in flight. Its methods run on the
calling thread, and those that wait block it: captures with a timeout,
next_event,
wait_for_source_name_change,
connect_to,
disconnect and
reconnect. Connection changes serialize with
one another and run native work on the calling thread. Async code should use this
type’s async methods for those instead.
§Example
let async_receiver = AsyncReceiver::new(receiver);
async_receiver.receiver().set_tally(Tally::new(true, false));
if async_receiver.receiver().ptz().is_supported() {
async_receiver.receiver().ptz().zoom(0.5)?;
}Sourcepub async fn capture_any(
&self,
timeout: Duration,
) -> Result<Option<ReceiverItem>>
pub async fn capture_any( &self, timeout: Duration, ) -> Result<Option<ReceiverItem>>
Async version of Receiver::capture_any, delivering owned video,
audio, metadata, or a receiver event through the shared capture loop on the
runtime’s blocking pool. Borrowed native frames remain on that worker
and are freed after their validated owned copy has been made. Video/audio
copy active pixels/samples and present metadata into new allocations;
standalone metadata copies its text. Use
capture_any_with for immediate inspection
without these payload allocations and copies.
The wait budget starts at first poll and includes blocking-pool queue
delay and SDK waits. A spent or zero budget makes one non-waiting
attempt. Scheduling and copying can finish after the budget.
Events compete with all other event and combined consumers;
see Receiver::capture_any_ref for their coalescing contract.
§Errors
The errors of Receiver::capture_any, including Error::UnexpectedSdkResult
once per failed status publication with its event retained, and Error::SpawnFailed
when no runtime context is entered or the blocking task is cancelled. Oversize timeouts
are rejected before submitting work.
§Cancellation
Dropping the future skips queued work and stops a started wait before its next attempt. The attempt already in flight can still consume media whose result is discarded; each native wait lasts at most 100 ms. An undelivered event is retained for the next event or combined capture, including when the worker completed before the future was dropped. An unknown event is redelivered only if no newer unknown event was reported.
Sourcepub async fn capture_any_with<F, T>(
&self,
timeout: Duration,
process: F,
) -> Result<Option<T>>
pub async fn capture_any_with<F, T>( &self, timeout: Duration, process: F, ) -> Result<Option<T>>
Process the next video, audio, metadata or receiver event on the blocking worker, without copying its payload into an owned item.
process synchronously borrows the validated ReceiverItemRef. It
runs once for a delivered item; timeouts and capture errors do not
call it. The wrapper keeps the native frame guard until the callback
returns (or unwinds), then frees it on the same worker. Only the
returned T crosses the task
boundary. Borrowed frames, planes, rows, channels and text cannot escape.
Use an owned result, or explicitly call ReceiverItemRef::to_owned,
to retain data across awaits.
The callback and its captures must be Send + 'static, as must T.
Keep processing bounded: it occupies a blocking worker and retains an
SDK buffer throughout. No wrapper payload allocation or copy is made;
runtime/task allocations and allocations by the callback still apply.
The wait budget, event delivery and cancellation rules are those of
capture_any. Callback execution time and side
effects are not cancelled by the timeout or by dropping the future.
An item delivered by the attempt in flight still runs its callback
even if the future was dropped. An event passed to the callback has
reached application code and is not re-published.
§Errors
The errors of Receiver::capture_any_ref, including Error::UnexpectedSdkResult
once per failed status publication with its event retained, and Error::SpawnFailed
for a missing runtime context or cancelled task. Oversize timeouts are
rejected before submitting work.
§Panics
A callback or blocking-operation panic is resumed on the awaiting task with its original payload, after the native frame is freed on the worker.
Sourcepub async fn next_event(
&self,
timeout: Duration,
) -> Result<Option<ReceiverEvent>>
pub async fn next_event( &self, timeout: Duration, ) -> Result<Option<ReceiverEvent>>
Async version of Receiver::next_event: wait up to timeout for a
status or source change, or return None when none came, running on
the blocking pool.
The events include those that typed async captures and the
receiver’s synchronous captures passed over and kept. They are
coalesced invalidations, not an ordered history; concurrent pollers,
through this type, its clones or the lent receiver,
compete to consume a pending one.
§Arguments
timeout- Total budget to wait for an event, starting when the future is first polled and spent asReceiver::next_eventspends it. Blocking-pool queue delay and SDK waits count against the same budget, andNonecomes only once all of it is spent.Duration::ZERO, like a budget that queue delay has already spent, makes one attempt without waiting. Completion can occur after this budget because scheduling is not bounded by it. Must not exceedcrate::MAX_TIMEOUT(~49.7 days).
§Errors
The errors of Receiver::next_event, and Error::SpawnFailed
when no runtime context is entered or the blocking task is cancelled.
§Cancellation
Dropping the future skips queued work and stops a started wait before its next attempt. An event taken by an in-flight or completed worker is retained for the next event or combined capture if this future never receives it. An unknown event is redelivered only if no newer unknown event was reported. Each native wait lasts at most 100 ms.
Sourcepub async fn wait_for_source_name_change(
&self,
timeout: Duration,
) -> Result<Option<SourceNameChange>>
pub async fn wait_for_source_name_change( &self, timeout: Duration, ) -> Result<Option<SourceNameChange>>
Async version of Receiver::wait_for_source_name_change: wait up to
timeout for a change to the name of the source the receiver is
actually connected to, running on the blocking pool.
None means no change within the budget; see
Receiver::wait_for_source_name_change for what a change reports.
Concurrent pollers compete for changes.
§Arguments
timeout- Total budget to wait for a change, starting when the future is first polled. Blocking-pool queue delay and waiting for a concurrent poller count against the same budget. Completion can occur after this budget because scheduling is not bounded by it. Must not exceedcrate::MAX_TIMEOUT(~49.7 days).
§Errors
The errors of Receiver::wait_for_source_name_change, and
Error::SpawnFailed for a missing runtime context or cancelled
blocking task.
Input and capability errors are reported before work is submitted.
§Cancellation
Dropping the future skips queued work and stops a started wait before its next attempt. A one-shot change taken by an in-flight or completed worker is retained for the next name-change wait if this future never receives it, unless a newer source-name change has been reported. Replay never waits for a native query. The newest retained change is taken before another native query; each native wait lasts at most 100 ms.
Sourcepub async fn connect_to(&self, source: &Source) -> Result<()>
pub async fn connect_to(&self, source: &Source) -> Result<()>
Point the underlying receiver at a different source and remember it as
the target that Self::reconnect retries. See
Receiver::connect_to.
Like Self::reconnect, this serializes with other local connection
changes and runs the native request on the blocking pool. Captures may
continue while the SDK applies it. Success means the request was
issued, not that the source is available; watch
Self::wait_for_source_name_change or Receiver::connection_stats.
The source was validated when constructed. The calling task prepares
its owned target when the future is first polled. An empty name and an
absent or empty address act like Self::disconnect.
§Errors
Error::SpawnFailed for a missing runtime context or cancelled
blocking task. The source was validated when it was constructed.
§Cancellation
Dropping this future skips work if the blocking closure observes the cancellation flag at its entry gate. After passing that gate, the connection change continues, including waiting for earlier connection changes, and may take effect after this future is dropped.
Sourcepub async fn disconnect(&self) -> Result<()>
pub async fn disconnect(&self) -> Result<()>
Disconnect the underlying receiver from its source, retaining the
latest target that Self::reconnect retries. See
Receiver::disconnect.
Like Self::reconnect, this serializes with local connection changes
and runs the native request on the blocking pool while captures continue.
§Errors
Error::SpawnFailed for a missing runtime context or
cancelled blocking task; Receiver::disconnect itself does not fail.
§Cancellation
Dropping this future skips work if the blocking closure observes the cancellation flag at its entry gate. After passing that gate, disconnect continues, including waiting for earlier connection changes, and may disconnect after this future is dropped.
Sourcepub async fn reconnect(&self) -> Result<()>
pub async fn reconnect(&self) -> Result<()>
Re-establish the underlying receiver’s connection to its source
in place. See Receiver::reconnect.
Reconnect serializes with other local connection changes and runs the
native request on the blocking pool. Captures may continue meanwhile.
Confirm recovery via Receiver::connection_stats. A Discovery Server
source change does not update the local target this requests. Before a
local target is selected, the worker completes without an SDK request.
§Errors
Error::SpawnFailed for a missing runtime context or cancelled
blocking task. The synchronous Receiver::reconnect cannot fail.
§Cancellation
Dropping this future skips work if the blocking closure observes the cancellation flag at its entry gate. After passing that gate, reconnect continues, including waiting for earlier connection changes, and may reconnect after this future is dropped.
Source§impl<R: AsyncRuntime> AsyncReceiver<R>
impl<R: AsyncRuntime> AsyncReceiver<R>
Sourcepub async fn capture_video(
&self,
timeout: Duration,
) -> Result<Option<VideoFrame>>
pub async fn capture_video( &self, timeout: Duration, ) -> Result<Option<VideoFrame>>
Capture owned video on the runtime’s blocking pool.
The budget starts at first poll and includes blocking-pool queue delay. A zero or spent budget makes one nonblocking SDK attempt. Dropping the future stops waiting before its next attempt; an attempt already running can consume an item that is discarded.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.
Sourcepub async fn capture_video_with<F, T>(
&self,
timeout: Duration,
process: F,
) -> Result<Option<T>>
pub async fn capture_video_with<F, T>( &self, timeout: Duration, process: F, ) -> Result<Option<T>>
Process borrowed video on the blocking worker without copying its payload.
process runs once for a delivered frame and retains its SDK
guard until it returns or unwinds. Only T crosses back to the
awaiting task; native frames and their borrowed slices cannot
escape. The callback and result must be Send + 'static.
The budget includes blocking-pool queue delay and SDK waits;
callback execution can finish after it and continues when the
future is dropped. Panics resume on the awaiting task after
the native guard has been released on the worker.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.
Source§impl<R: AsyncRuntime> AsyncReceiver<R>
impl<R: AsyncRuntime> AsyncReceiver<R>
Sourcepub async fn capture_audio(
&self,
timeout: Duration,
) -> Result<Option<AudioFrame>>
pub async fn capture_audio( &self, timeout: Duration, ) -> Result<Option<AudioFrame>>
Capture owned audio on the runtime’s blocking pool.
The budget starts at first poll and includes blocking-pool queue delay. A zero or spent budget makes one nonblocking SDK attempt. Dropping the future stops waiting before its next attempt; an attempt already running can consume an item that is discarded.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.
Sourcepub async fn capture_audio_with<F, T>(
&self,
timeout: Duration,
process: F,
) -> Result<Option<T>>
pub async fn capture_audio_with<F, T>( &self, timeout: Duration, process: F, ) -> Result<Option<T>>
Process borrowed audio on the blocking worker without copying its payload.
process runs once for a delivered frame and retains its SDK
guard until it returns or unwinds. Only T crosses back to the
awaiting task; native frames and their borrowed slices cannot
escape. The callback and result must be Send + 'static.
The budget includes blocking-pool queue delay and SDK waits;
callback execution can finish after it and continues when the
future is dropped. Panics resume on the awaiting task after
the native guard has been released on the worker.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.
Source§impl<R: AsyncRuntime> AsyncReceiver<R>
impl<R: AsyncRuntime> AsyncReceiver<R>
Sourcepub async fn capture_metadata(
&self,
timeout: Duration,
) -> Result<Option<MetadataFrame>>
pub async fn capture_metadata( &self, timeout: Duration, ) -> Result<Option<MetadataFrame>>
Capture owned metadata on the runtime’s blocking pool.
The budget starts at first poll and includes blocking-pool queue delay. A zero or spent budget makes one nonblocking SDK attempt. Dropping the future stops waiting before its next attempt; an attempt already running can consume an item that is discarded.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.
Sourcepub async fn capture_metadata_with<F, T>(
&self,
timeout: Duration,
process: F,
) -> Result<Option<T>>
pub async fn capture_metadata_with<F, T>( &self, timeout: Duration, process: F, ) -> Result<Option<T>>
Process borrowed metadata on the blocking worker without copying its payload.
process runs once for a delivered frame and retains its SDK
guard until it returns or unwinds. Only T crosses back to the
awaiting task; native frames and their borrowed slices cannot
escape. The callback and result must be Send + 'static.
The budget includes blocking-pool queue delay and SDK waits;
callback execution can finish after it and continues when the
future is dropped. Panics resume on the awaiting task after
the native guard has been released on the worker.
§Errors
Invalid timeouts, capture errors, or blocking-worker spawn failure.