grafton_ndi/asynchronous.rs
1//! Async discovery and receivers for Tokio and smol.
2//!
3//! [`AsyncReceiver`] wraps the synchronous NDI receiver API for an async
4//! runtime, with `capture_video`, `capture_audio` and `capture_metadata`
5//! methods for owned media and matching `capture_*_with` scoped callbacks.
6//! [`AsyncReceiver::capture_any`] returns whichever owned media item or receiver
7//! event arrives next. The adapter selects the [`AsyncRuntime`] whose blocking
8//! thread pool runs the NDI operations:
9#![cfg_attr(
10 feature = "tokio",
11 doc = "Use [`Tokio`] with the `tokio` Cargo feature; the [`tokio`] submodule names its adapters."
12)]
13#![cfg_attr(
14 feature = "smol",
15 doc = "Use [`Smol`] with the `smol` Cargo feature; the [`smol`] submodule names its adapters."
16)]
17//! This module exists when either feature is enabled, and each runtime only
18//! with its own feature; the crate root does not re-export any of it.
19//!
20//! [`AsyncFinder`] owns a [`crate::Finder`] or [`crate::SourceCache`] for async
21//! selection and complete discovery windows. Its owned [`AsyncSourceWatch`]
22//! retains a consumer's generation across awaits without borrowing a finder.
23//! Runtime submodules also provide the `AsyncSourceCache` alias for cached
24//! discovery. Dropped lookups stop their workers using the same rule as receivers.
25//!
26//! The NDI SDK operations are synchronous and blocking. Tokio runs them through
27//! `tokio::task::spawn_blocking`; smol uses `smol::unblock`, keeping the work off
28//! the async runtime's executor threads. Besides capture, [`AsyncReceiver`] has async
29//! versions of the receiver's other waiting calls:
30//! [`next_event`](AsyncReceiver::next_event), which returns the status and
31//! source changes that captures pass over and keep,
32//! [`wait_for_source_name_change`](AsyncReceiver::wait_for_source_name_change),
33//! [`connect_to`](AsyncReceiver::connect_to),
34//! [`disconnect`](AsyncReceiver::disconnect) and
35//! [`reconnect`](AsyncReceiver::reconnect). It lends the [`Receiver`] itself,
36//! through [`receiver`](AsyncReceiver::receiver), for shared controls. See
37//! [`Receiver`'s waiting contract](Receiver#waiting), including native destruction
38//! on the thread dropping the last owner.
39//!
40//! For owned/scoped captures, `next_event` and `wait_for_source_name_change`, the timeout
41//! budget starts when the future is first polled, rather than when it is
42//! constructed. The same deadline covers blocking-pool queue delay and SDK waits.
43//! This is a wait budget, not a hard completion deadline: scheduling, frame copying,
44//! and other processing can delay the result beyond it.
45//!
46//! [`AsyncReceiver::capture_video_with`] and [`AsyncReceiver::capture_any_with`] run a
47//! synchronous callback over validated borrowed media on the same blocking
48//! worker that captures it, without wrapper payload allocations or copies.
49//! Only its `Send + 'static` result crosses the task boundary. The callback
50//! holds an SDK buffer and occupies a worker until it returns; keep processing
51//! bounded. Use owned capture or explicitly copy in the callback to keep media
52//! across awaits. Owned capture copies all active pixels/samples and present
53//! metadata into new allocations (33,177,600 pixel bytes for 4K BGRA).
54//!
55//! Dropping a future sets a cancellation flag. Work is skipped if the blocking
56//! closure observes that flag at its entry gate. A budgeted wait also checks
57//! it before each subsequent attempt. An attempt already in flight, lasting at
58//! most 100 ms in the SDK, can still consume media and run its scoped callback
59//! after the future was dropped. Undelivered receiver events and source-name
60//! changes are retained for a later wait, including when a completed worker
61//! was never polled again. Source names and unknown events are redelivered only
62//! if no newer report superseded them. Replay takes a short bookkeeping lock,
63//! never a native-query permit. Callback time and side effects are not cancelled
64//! by the wait timeout either. A panic is caught on the worker, where SDK guards
65//! are released, then resumed on the awaiting task with its original payload.
66//! It unwinds through `select!` or `join!` as any other task panic does. If the
67//! future was dropped, its panic payload is discarded with the result.
68//!
69//! # Features
70//!
71//! - `tokio` - Enable Tokio runtime support
72//! - `smol` - Enable smol runtime support
73//!
74//! # Example with Tokio
75//!
76//! ```no_run
77//! # #[cfg(feature = "tokio")]
78//! # {
79//! use grafton_ndi::{Finder, FinderOptions, Ndi, ReceiverOptions,
80//! asynchronous::tokio::{AsyncFinder, AsyncReceiver}};
81//!
82//! #[tokio::main]
83//! async fn main() -> Result<(), grafton_ndi::Error> {
84//! let ndi = Ndi::new()?;
85//! let finder = AsyncFinder::new(Finder::new(&ndi, &FinderOptions::new())?);
86//! let Some(source) = finder.find_source_by_name("CAMERA (Program)",
87//! std::time::Duration::from_secs(5)).await? else { return Ok(()); };
88//!
89//! let options = ReceiverOptions::snapshot_preset(source);
90//! let receiver = grafton_ndi::Receiver::new(&ndi, &options)?;
91//!
92//! let async_receiver = AsyncReceiver::new(receiver);
93//!
94//! if let Some(size) = async_receiver.capture_video_with(std::time::Duration::from_secs(5), |frame| {
95//! (frame.width(), frame.height())
96//! }).await? {
97//! println!("Captured dimensions: {size:?}");
98//! }
99//!
100//! Ok(())
101//! }
102//! # }
103//! ```
104//!
105//! See [mixed_media_async.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/mixed_media_async.rs)
106//! for a runnable async discovery and capture loop.
107
108use std::{
109 future::Future,
110 marker::PhantomData,
111 sync::{
112 atomic::{AtomicBool, Ordering},
113 Arc,
114 },
115 time::Duration,
116};
117
118use crate::{
119 capture::{AllSlots, AudioKind, CaptureKind, MetadataKind, NoSlots, VideoKind},
120 receiver::{prepare_receiver_target, ReceiverCore, ReceiverReport},
121 timeout::Deadline,
122 Error, Receiver, ReceiverEvent, ReceiverItem, ReceiverItemRef, Result, Source,
123 SourceNameChange, SpawnFailure,
124};
125
126mod discovery;
127pub use discovery::{AsyncFinder, AsyncSourceWatch, SourceDiscovery};
128
129mod private {
130 use std::{future::Future, sync::atomic::AtomicBool};
131
132 use crate::Result;
133
134 /// Proof that the caller is this crate.
135 ///
136 /// A bound on [`AsyncRuntime`](super::AsyncRuntime) makes [`Spawn::spawn_blocking`]
137 /// reachable from other crates even though they cannot name [`Spawn`];
138 /// they cannot name this type either, so they cannot call it.
139 #[derive(Debug)]
140 pub struct Token;
141
142 /// How a runtime runs blocking work on its thread pool.
143 ///
144 /// It is not nameable outside the crate, which keeps it out of the API
145 /// and seals [`AsyncRuntime`](super::AsyncRuntime).
146 pub trait Spawn {
147 /// Run `f` on the runtime's blocking thread pool and return its result.
148 ///
149 /// # Errors
150 ///
151 /// [`Error::SpawnFailed`](crate::Error::SpawnFailed) when the work
152 /// has no runtime context or its task is cancelled. Panics are resumed
153 /// on the awaiting task after worker-owned resources are released.
154 fn spawn_blocking<F, T>(token: Token, f: F) -> impl Future<Output = Result<T>> + Send
155 where
156 F: FnOnce() -> T + Send + 'static,
157 T: Send + 'static,
158 {
159 Self::spawn_stoppable(token, move |_| f())
160 }
161
162 fn spawn_stoppable<F, T>(token: Token, f: F) -> impl Future<Output = Result<T>> + Send
163 where
164 F: FnOnce(&AtomicBool) -> T + Send + 'static,
165 T: Send + 'static;
166 }
167}
168
169// Dropping a future skips queued work and stops budgeted receiver waits
170// before their next attempt. An attempt or callback already in flight finishes.
171struct CancelOnDrop(Arc<AtomicBool>);
172
173impl Drop for CancelOnDrop {
174 fn drop(&mut self) {
175 self.0.store(true, Ordering::Release);
176 }
177}
178
179#[cfg(test)]
180fn blocking_operation<F, T>(operation: F) -> (CancelOnDrop, impl FnOnce() -> Result<T> + Send)
181where
182 F: FnOnce() -> T + Send,
183{
184 let (guard, work) = blocking_operation_with_stop(move |_| operation());
185 (guard, move || work().map(resume_work))
186}
187
188fn blocking_operation_with_stop<F, T>(
189 operation: F,
190) -> (
191 CancelOnDrop,
192 impl FnOnce() -> Result<std::thread::Result<T>> + Send,
193)
194where
195 F: FnOnce(&AtomicBool) -> T + Send,
196{
197 let cancelled = Arc::new(AtomicBool::new(false));
198 let guard = CancelOnDrop(Arc::clone(&cancelled));
199 let work = move || {
200 if cancelled.load(Ordering::Acquire) {
201 return discovery_result(Ok(Err(crate::timeout::Stopped)));
202 }
203 Ok(std::panic::catch_unwind(std::panic::AssertUnwindSafe(
204 || operation(&cancelled),
205 )))
206 };
207 (guard, work)
208}
209
210// Discovery reports cancellation as control flow; this adapter owns its public error.
211fn discovery_result<T>(outcome: crate::timeout::StopResult<T, &AtomicBool>) -> Result<T> {
212 outcome?.map_err(|crate::timeout::Stopped| Error::SpawnFailed(SpawnFailure::TaskCancelled))
213}
214
215fn resume_work<T>(outcome: std::thread::Result<T>) -> T {
216 match outcome {
217 Ok(value) => value,
218 Err(payload) => std::panic::resume_unwind(payload),
219 }
220}
221
222#[cfg(feature = "tokio")]
223fn tokio_join_error(error: ::tokio::task::JoinError) -> Error {
224 if error.is_panic() {
225 std::panic::resume_unwind(error.into_panic());
226 }
227 Error::SpawnFailed(SpawnFailure::TaskCancelled)
228}
229
230/// An async runtime whose blocking thread pool runs the NDI operations of an
231/// [`AsyncReceiver`], [`AsyncFinder`] and [`AsyncSourceWatch`].
232#[cfg_attr(feature = "tokio", doc = "[`Tokio`] selects the Tokio runtime.")]
233#[cfg_attr(feature = "smol", doc = "[`Smol`] selects the smol runtime.")]
234///
235/// The trait is sealed and has no items of its own; it only selects the
236/// runtime.
237pub trait AsyncRuntime: private::Spawn + Send + Sync {}
238
239/// The Tokio runtime, which runs blocking work with
240/// `tokio::task::spawn_blocking`.
241///
242/// The work runs on the runtime of the task that awaits it; awaiting outside
243/// a Tokio runtime fails with [`Error::SpawnFailed`]. Only a type, never a
244/// value. Requires the `tokio` feature.
245#[cfg(feature = "tokio")]
246#[derive(Debug)]
247pub enum Tokio {}
248
249#[cfg(feature = "tokio")]
250impl AsyncRuntime for Tokio {}
251
252#[cfg(feature = "tokio")]
253impl private::Spawn for Tokio {
254 // Using `impl Future` instead of `async fn` in trait because we need explicit
255 // Send bounds on the returned future. This pattern is intentional.
256 #[allow(clippy::manual_async_fn)]
257 fn spawn_stoppable<F, T>(_: private::Token, f: F) -> impl Future<Output = Result<T>> + Send
258 where
259 F: FnOnce(&AtomicBool) -> T + Send + 'static,
260 T: Send + 'static,
261 {
262 async {
263 let handle = ::tokio::runtime::Handle::try_current()
264 .map_err(|_| Error::SpawnFailed(SpawnFailure::NoRuntime))?;
265 let (_cancellation, work) = blocking_operation_with_stop(f);
266 let outcome = handle
267 .spawn_blocking(work)
268 .await
269 .map_err(tokio_join_error)??;
270 Ok(resume_work(outcome))
271 }
272 }
273}
274
275/// The smol runtime, which runs blocking work with `smol::unblock`.
276///
277/// Only a type, never a value. Requires the `smol` feature.
278#[cfg(feature = "smol")]
279#[derive(Debug)]
280pub enum Smol {}
281
282#[cfg(feature = "smol")]
283impl AsyncRuntime for Smol {}
284
285#[cfg(feature = "smol")]
286impl private::Spawn for Smol {
287 // Using `impl Future` instead of `async fn` in trait because we need explicit
288 // Send bounds on the returned future. This pattern is intentional.
289 #[allow(clippy::manual_async_fn)]
290 fn spawn_stoppable<F, T>(_: private::Token, f: F) -> impl Future<Output = Result<T>> + Send
291 where
292 F: FnOnce(&AtomicBool) -> T + Send + 'static,
293 T: Send + 'static,
294 {
295 async {
296 let (_cancellation, work) = blocking_operation_with_stop(f);
297 Ok(resume_work(::smol::unblock(work).await?))
298 }
299 }
300}
301
302/// An async wrapper over a [`Receiver`] that runs its blocking NDI operations
303/// on the blocking thread pool of the runtime `R`, so that they do not block
304/// the async runtime.
305///
306#[cfg_attr(
307 feature = "tokio",
308 doc = "[`tokio::AsyncReceiver`] names it for Tokio."
309)]
310#[cfg_attr(feature = "smol", doc = "[`smol::AsyncReceiver`] names it for smol.")]
311///
312/// # Thread Safety
313///
314/// The underlying [`Receiver`] is shared through an [`Arc`]. The SDK documents
315/// concurrent capture calls in `Processing.NDI.Recv.h`. Local connection
316/// changes serialize with one another and may overlap captures, as described
317/// by [`Receiver::reconnect`]. Source-name waits serialize with one another;
318/// waiting for another poller counts against the caller's wait budget.
319///
320/// # Events and controls
321///
322/// A capture that the SDK answers with a status or source change instead of
323/// a frame keeps that change for [`next_event`](Self::next_event), as the
324/// synchronous captures keep it for [`Receiver::next_event`]: both read the
325/// same pending events. [`receiver`](Self::receiver) lends the receiver for
326/// shared controls, such as tally, PTZ and upstream metadata; see
327/// [`Receiver`'s waiting contract](Receiver#waiting).
328///
329/// # Error Handling
330///
331/// [`Error::SpawnFailed`] carries a typed [`SpawnFailure`] for a missing Tokio
332/// context or a cancelled task. A panic on the worker is resumed on the awaiting
333/// task with its original payload, after SDK guards are released on the worker.
334/// An abandoned operation discards media and any caught panic payload;
335/// undelivered events and source-name changes are retained for later waits.
336/// A source-name or unknown-event report is redelivered only while no newer
337/// report has superseded it; replay never waits for a native query.
338///
339/// # Example
340///
341/// ```no_run
342/// # #[cfg(feature = "tokio")]
343/// # {
344/// use grafton_ndi::{Ndi, ReceiverOptions, asynchronous::tokio::AsyncReceiver};
345///
346/// #[tokio::main]
347/// async fn main() -> Result<(), grafton_ndi::Error> {
348/// let ndi = Ndi::new()?;
349/// // ... obtain source ...
350/// # let source = grafton_ndi::Source::new("CAMERA (Program)").unwrap();
351///
352/// let options = ReceiverOptions::snapshot_preset(source);
353/// let receiver = grafton_ndi::Receiver::new(&ndi, &options)?;
354/// let async_receiver = AsyncReceiver::new(receiver);
355///
356/// // Capture without blocking the runtime
357/// match async_receiver.capture_video_with(std::time::Duration::from_millis(100), |frame| {
358/// (frame.width(), frame.height())
359/// }).await? {
360/// Some(size) => println!("Got dimensions: {size:?}"),
361/// None => println!("No frame available"),
362/// }
363///
364/// Ok(())
365/// }
366/// # }
367/// ```
368pub struct AsyncReceiver<R: AsyncRuntime> {
369 inner: Arc<Receiver>,
370 _runtime: PhantomData<R>,
371}
372
373impl<R: AsyncRuntime> std::fmt::Debug for AsyncReceiver<R> {
374 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
375 f.debug_struct("AsyncReceiver")
376 .field("receiver", &self.inner)
377 .field("runtime", &std::any::type_name::<R>())
378 .finish_non_exhaustive()
379 }
380}
381
382// Starts the budget on the future's first poll, so that blocking-pool queue
383// delay is spent from it.
384async fn with_timeout_budget<R, F, T>(timeout: Duration, operation: F) -> Result<T>
385where
386 R: AsyncRuntime,
387 F: FnOnce(Deadline, &AtomicBool) -> Result<T> + Send + 'static,
388 T: Send + 'static,
389{
390 with_deadline_budget::<R, _, _>(Deadline::after(timeout)?, operation).await
391}
392
393// Validated discovery inputs keep the deadline started before their conversion.
394async fn with_deadline_budget<R, F, T>(deadline: Deadline, operation: F) -> Result<T>
395where
396 R: AsyncRuntime,
397 F: FnOnce(Deadline, &AtomicBool) -> Result<T> + Send + 'static,
398 T: Send + 'static,
399{
400 R::spawn_stoppable(private::Token, move |stop| operation(deadline, stop)).await?
401}
402
403// Keep ownership of the validated guard throughout application processing.
404// Only the result leaves this scope, including when a task is abandoned.
405fn process_captured<V, T>(captured: Option<V>, process: impl FnOnce(&V) -> T) -> Option<T> {
406 captured.as_ref().map(process)
407}
408
409/// A completed notification is either delivered to its future or returned to
410/// the receiver when the runtime drops an abandoned worker's output.
411struct ReceiverDelivery<T: ReplayReceiverValue<R>, R = Receiver> {
412 receiver: Arc<R>,
413 value: Option<T>,
414}
415
416impl<T: ReplayReceiverValue<R>, R> ReceiverDelivery<T, R> {
417 fn new(receiver: Arc<R>, value: Option<T>) -> Self {
418 Self { receiver, value }
419 }
420
421 fn take(mut self) -> Option<T::Value> {
422 self.value.take().map(ReplayReceiverValue::into_value)
423 }
424}
425
426impl<T: ReplayReceiverValue<R>, R> Drop for ReceiverDelivery<T, R> {
427 fn drop(&mut self) {
428 if let Some(value) = self.value.take() {
429 value.replay(&self.receiver);
430 }
431 }
432}
433
434trait ReplayReceiverValue<R = Receiver> {
435 type Value;
436 fn into_value(self) -> Self::Value;
437 fn replay(self, receiver: &R);
438}
439
440impl ReplayReceiverValue for ReceiverReport<ReceiverEvent> {
441 type Value = ReceiverEvent;
442 fn into_value(self) -> Self::Value {
443 self.value
444 }
445 fn replay(self, receiver: &Receiver) {
446 receiver.core.retain_event(self);
447 }
448}
449
450impl ReplayReceiverValue for ReceiverReport<SourceNameChange> {
451 type Value = SourceNameChange;
452 fn into_value(self) -> Self::Value {
453 self.value
454 }
455 fn replay(self, receiver: &Receiver) {
456 receiver.core.retain_source_name_change(self);
457 }
458}
459
460impl ReplayReceiverValue for ReceiverReport<ReceiverItem> {
461 type Value = ReceiverItem;
462 fn into_value(self) -> Self::Value {
463 self.value
464 }
465 fn replay(self, receiver: &Receiver) {
466 if let ReceiverItem::Event(event) = &self.value {
467 let event = *event;
468 receiver.core.retain_event(self.map(|_| event));
469 }
470 }
471}
472
473impl<R: AsyncRuntime> AsyncReceiver<R> {
474 /// Create a new async receiver wrapper.
475 ///
476 /// The receiver is wrapped in an [`Arc`] to allow sharing across async tasks.
477 pub fn new(receiver: Receiver) -> Self {
478 Self {
479 inner: Arc::new(receiver),
480 _runtime: PhantomData,
481 }
482 }
483
484 /// The receiver this wraps, lent for its controls: tally, PTZ, upstream
485 /// and connection metadata, delays, the web-control URL and the latest
486 /// [`connection_target`](Receiver::connection_target).
487 ///
488 /// The receiver is shared with every clone of this `AsyncReceiver` and
489 /// with the async operations they have in flight. Its methods run on the
490 /// calling thread, and those that wait block it: captures with a timeout,
491 /// [`next_event`](Receiver::next_event),
492 /// [`wait_for_source_name_change`](Receiver::wait_for_source_name_change),
493 /// [`connect_to`](Receiver::connect_to),
494 /// [`disconnect`](Receiver::disconnect) and
495 /// [`reconnect`](Receiver::reconnect). Connection changes serialize with
496 /// one another and run native work on the calling thread. Async code should use this
497 /// type's async methods for those instead.
498 ///
499 /// # Example
500 ///
501 /// ```no_run
502 /// # #[cfg(feature = "tokio")]
503 /// # {
504 /// # use grafton_ndi::{Ndi, ReceiverOptions, Tally, asynchronous::tokio::AsyncReceiver};
505 /// # fn main() -> Result<(), grafton_ndi::Error> {
506 /// # let ndi = Ndi::new()?;
507 /// # let source = grafton_ndi::Source::new("CAMERA (Program)").unwrap();
508 /// # let receiver = grafton_ndi::Receiver::new(&ndi, &ReceiverOptions::new(source))?;
509 /// let async_receiver = AsyncReceiver::new(receiver);
510 /// async_receiver.receiver().set_tally(Tally::new(true, false));
511 /// if async_receiver.receiver().ptz().is_supported() {
512 /// async_receiver.receiver().ptz().zoom(0.5)?;
513 /// }
514 /// # Ok(())
515 /// # }
516 /// # }
517 /// ```
518 pub fn receiver(&self) -> &Receiver {
519 &self.inner
520 }
521
522 /// Async version of [`Receiver::capture_any`], delivering owned video,
523 /// audio, metadata, or a receiver event through the shared capture loop on the
524 /// runtime's blocking pool. Borrowed native frames remain on that worker
525 /// and are freed after their validated owned copy has been made. Video/audio
526 /// copy active pixels/samples and present metadata into new allocations;
527 /// standalone metadata copies its text. Use
528 /// [`capture_any_with`](Self::capture_any_with) for immediate inspection
529 /// without these payload allocations and copies.
530 ///
531 /// The wait budget starts at first poll and includes blocking-pool queue
532 /// delay and SDK waits. A spent or zero budget makes one non-waiting
533 /// attempt. Scheduling and copying can finish after the budget.
534 /// Events compete with all other event and combined consumers;
535 /// see [`Receiver::capture_any_ref`] for their coalescing contract.
536 ///
537 /// # Errors
538 ///
539 /// The errors of [`Receiver::capture_any`], including [`Error::UnexpectedSdkResult`]
540 /// once per failed status publication with its event retained, and [`Error::SpawnFailed`]
541 /// when no runtime context is entered or the blocking task is cancelled. Oversize timeouts
542 /// are rejected before submitting work.
543 ///
544 /// # Cancellation
545 ///
546 /// Dropping the future skips queued work and stops a started wait before
547 /// its next attempt. The attempt already in flight can still consume media
548 /// whose result is discarded; each native wait lasts at most 100 ms.
549 /// An undelivered event is retained for the next event or combined capture,
550 /// including when the worker completed before the future was dropped.
551 /// An unknown event is redelivered only if no newer unknown event was reported.
552 #[doc(alias = "NDIlib_recv_capture_v3")]
553 pub async fn capture_any(&self, timeout: Duration) -> Result<Option<ReceiverItem>> {
554 let receiver = Arc::clone(&self.inner);
555 Ok(
556 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
557 let value = receiver.capture_any_report_until::<AllSlots, _>(
558 deadline,
559 stop,
560 |report| report.map(ReceiverItem::Event),
561 |media| {
562 ReceiverCore::combined_result(media)
563 .map(|item| ReceiverReport::unsequenced(item.to_owned()))
564 },
565 )?;
566 Ok(ReceiverDelivery::new(receiver, value))
567 })
568 .await?
569 .take(),
570 )
571 }
572
573 /// Process the next video, audio, metadata or receiver event on the
574 /// blocking worker, without copying its payload into an owned item.
575 ///
576 /// `process` synchronously borrows the validated [`ReceiverItemRef`]. It
577 /// runs once for a delivered item; timeouts and capture errors do not
578 /// call it. The wrapper keeps the native frame guard until the callback
579 /// returns (or unwinds), then frees it on the same worker. Only the
580 /// returned `T` crosses the task
581 /// boundary. Borrowed frames, planes, rows, channels and text cannot escape.
582 /// Use an owned result, or explicitly call [`ReceiverItemRef::to_owned`],
583 /// to retain data across awaits.
584 ///
585 /// The callback and its captures must be `Send + 'static`, as must `T`.
586 /// Keep processing bounded: it occupies a blocking worker and retains an
587 /// SDK buffer throughout. No wrapper payload allocation or copy is made;
588 /// runtime/task allocations and allocations by the callback still apply.
589 ///
590 /// The wait budget, event delivery and cancellation rules are those of
591 /// [`capture_any`](Self::capture_any). Callback execution time and side
592 /// effects are not cancelled by the timeout or by dropping the future.
593 /// An item delivered by the attempt in flight still runs its callback
594 /// even if the future was dropped. An event passed to the callback has
595 /// reached application code and is not re-published.
596 ///
597 /// # Errors
598 ///
599 /// The errors of [`Receiver::capture_any_ref`], including [`Error::UnexpectedSdkResult`]
600 /// once per failed status publication with its event retained, and [`Error::SpawnFailed`]
601 /// for a missing runtime context or cancelled task. Oversize timeouts are
602 /// rejected before submitting work.
603 ///
604 /// # Panics
605 ///
606 /// A callback or blocking-operation panic is resumed on the awaiting task
607 /// with its original payload, after the native frame is freed on the worker.
608 #[doc(alias = "NDIlib_recv_capture_v3")]
609 pub async fn capture_any_with<F, T>(&self, timeout: Duration, process: F) -> Result<Option<T>>
610 where
611 F: for<'frame> FnOnce(&ReceiverItemRef<'frame>) -> T + Send + 'static,
612 T: Send + 'static,
613 {
614 let receiver = Arc::clone(&self.inner);
615 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
616 Ok(process_captured(
617 receiver.capture_any_ref_until(deadline, stop)?,
618 process,
619 ))
620 })
621 .await
622 }
623
624 /// Async version of [`Receiver::next_event`]: wait up to `timeout` for a
625 /// status or source change, or return `None` when none came, running on
626 /// the blocking pool.
627 ///
628 /// The events include those that typed async captures and the
629 /// receiver's synchronous captures passed over and kept. They are
630 /// coalesced invalidations, not an ordered history; concurrent pollers,
631 /// through this type, its clones or the lent [`receiver`](Self::receiver),
632 /// compete to consume a pending one.
633 ///
634 /// # Arguments
635 ///
636 /// * `timeout` - Total budget to wait for an event, starting when the
637 /// future is first polled and spent as [`Receiver::next_event`] spends
638 /// it. Blocking-pool queue delay and SDK waits count
639 /// against the same budget, and `None` comes only once all of it is
640 /// spent. [`Duration::ZERO`], like a budget that queue delay has
641 /// already spent, makes one attempt without waiting. Completion can
642 /// occur after this budget because scheduling is not bounded by it.
643 /// Must not exceed [`crate::MAX_TIMEOUT`] (~49.7 days).
644 ///
645 /// # Errors
646 ///
647 /// The errors of [`Receiver::next_event`], and [`Error::SpawnFailed`]
648 /// when no runtime context is entered or the blocking task is cancelled.
649 ///
650 /// # Cancellation
651 ///
652 /// Dropping the future skips queued work and stops a started wait before
653 /// its next attempt. An event taken by an in-flight or completed worker
654 /// is retained for the next event or combined capture if this future never
655 /// receives it. An unknown event is redelivered only if no newer unknown
656 /// event was reported. Each native wait lasts at most 100 ms.
657 #[doc(alias = "NDIlib_recv_capture_v3")]
658 pub async fn next_event(&self, timeout: Duration) -> Result<Option<ReceiverEvent>> {
659 let receiver = Arc::clone(&self.inner);
660 Ok(
661 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
662 let value = receiver.capture_any_report_until::<NoSlots, _>(
663 deadline,
664 stop,
665 |report| report,
666 |media| match media {},
667 )?;
668 Ok(ReceiverDelivery::new(receiver, value))
669 })
670 .await?
671 .take(),
672 )
673 }
674
675 /// Async version of [`Receiver::wait_for_source_name_change`]: wait up to
676 /// `timeout` for a change to the name of the source the receiver is
677 /// actually connected to, running on the blocking pool.
678 ///
679 /// `None` means no change within the budget; see
680 /// [`Receiver::wait_for_source_name_change`] for what a change reports.
681 /// Concurrent pollers compete for changes.
682 ///
683 /// # Arguments
684 ///
685 /// * `timeout` - Total budget to wait for a change, starting when the
686 /// future is first polled. Blocking-pool queue delay and waiting for a
687 /// concurrent poller count against the same budget. Completion can
688 /// occur after this budget because scheduling is not bounded by it.
689 /// Must not exceed [`crate::MAX_TIMEOUT`] (~49.7 days).
690 ///
691 /// # Errors
692 ///
693 /// The errors of [`Receiver::wait_for_source_name_change`], and
694 /// [`Error::SpawnFailed`] for a missing runtime context or cancelled
695 /// blocking task.
696 ///
697 /// Input and capability errors are reported before work is submitted.
698 ///
699 /// # Cancellation
700 ///
701 /// Dropping the future skips queued work and stops a started wait before
702 /// its next attempt. A one-shot change taken by an in-flight or completed
703 /// worker is retained for the next name-change wait if this future never
704 /// receives it, unless a newer source-name change has been reported.
705 /// Replay never waits for a native query. The newest retained change is
706 /// taken before another native query; each native wait lasts at most 100 ms.
707 #[doc(alias = "NDIlib_recv_get_source_name")]
708 pub async fn wait_for_source_name_change(
709 &self,
710 timeout: Duration,
711 ) -> Result<Option<SourceNameChange>> {
712 let deadline = Deadline::after(timeout)?;
713 // The task owns the gated tables together with the receiver core
714 // that keeps their runtime initialized for the entire native wait.
715 let tables = crate::runtime::Bound::<
716 (crate::sys::ReceiverSourceName, crate::sys::ReceiverStrings),
717 Arc<crate::receiver::ReceiverCore>,
718 >::with_owner(Arc::clone(&self.inner.core))?;
719 let receiver = Arc::clone(&self.inner);
720 Ok(R::spawn_stoppable(private::Token, move |stop| {
721 let (source_name, strings) = &*tables;
722 let value = tables.owner().wait_for_source_name_change_with(
723 source_name,
724 strings,
725 deadline,
726 stop,
727 )?;
728 Ok::<_, Error>(ReceiverDelivery::new(receiver, value))
729 })
730 .await??
731 .take())
732 }
733
734 /// Point the underlying receiver at a different source and remember it as
735 /// the target that [`Self::reconnect`] retries. See
736 /// [`Receiver::connect_to`].
737 ///
738 /// Like [`Self::reconnect`], this serializes with other local connection
739 /// changes and runs the native request on the blocking pool. Captures may
740 /// continue while the SDK applies it. Success means the request was
741 /// issued, not that the source is available; watch
742 /// [`Self::wait_for_source_name_change`] or [`Receiver::connection_stats`].
743 /// The source was validated when constructed. The calling task prepares
744 /// its owned target when the future is first polled. An empty name and an
745 /// absent or empty address act like [`Self::disconnect`].
746 ///
747 /// # Errors
748 ///
749 /// [`Error::SpawnFailed`] for a missing runtime context or cancelled
750 /// blocking task. The source was validated when it was constructed.
751 ///
752 /// # Cancellation
753 ///
754 /// Dropping this future skips work if the blocking closure observes the
755 /// cancellation flag at its entry gate. After passing that gate, the
756 /// connection change continues, including waiting for earlier connection changes,
757 /// and may take effect after this future is dropped.
758 #[doc(alias = "NDIlib_recv_connect")]
759 pub async fn connect_to(&self, source: &Source) -> Result<()> {
760 let target = prepare_receiver_target(source);
761 let receiver = Arc::clone(&self.inner);
762 R::spawn_blocking(private::Token, move || receiver.connect_target(target)).await
763 }
764
765 /// Disconnect the underlying receiver from its source, retaining the
766 /// latest target that [`Self::reconnect`] retries. See
767 /// [`Receiver::disconnect`].
768 ///
769 /// Like [`Self::reconnect`], this serializes with local connection changes
770 /// and runs the native request on the blocking pool while captures continue.
771 ///
772 /// # Errors
773 ///
774 /// [`Error::SpawnFailed`] for a missing runtime context or
775 /// cancelled blocking task; [`Receiver::disconnect`] itself does not fail.
776 ///
777 /// # Cancellation
778 ///
779 /// Dropping this future skips work if the blocking closure observes the
780 /// cancellation flag at its entry gate. After passing that gate,
781 /// disconnect continues, including waiting for earlier connection changes, and may
782 /// disconnect after this future is dropped.
783 #[doc(alias = "NDIlib_recv_connect")]
784 pub async fn disconnect(&self) -> Result<()> {
785 let receiver = Arc::clone(&self.inner);
786 R::spawn_blocking(private::Token, move || receiver.disconnect()).await
787 }
788
789 /// Re-establish the underlying receiver's connection to its source
790 /// in place. See [`Receiver::reconnect`].
791 ///
792 /// Reconnect serializes with other local connection changes and runs the
793 /// native request on the blocking pool. Captures may continue meanwhile.
794 /// Confirm recovery via [`Receiver::connection_stats`]. A Discovery Server
795 /// source change does not update the local target this requests. Before a
796 /// local target is selected, the worker completes without an SDK request.
797 ///
798 /// # Errors
799 ///
800 /// [`Error::SpawnFailed`] for a missing runtime context or cancelled
801 /// blocking task. The synchronous [`Receiver::reconnect`] cannot fail.
802 ///
803 /// # Cancellation
804 ///
805 /// Dropping this future skips work if the blocking closure observes the
806 /// cancellation flag at its entry gate. After passing that gate, reconnect
807 /// continues, including waiting for earlier connection changes, and may reconnect
808 /// after this future is dropped.
809 #[doc(alias = "NDIlib_recv_connect")]
810 pub async fn reconnect(&self) -> Result<()> {
811 let receiver = Arc::clone(&self.inner);
812 R::spawn_blocking(private::Token, move || receiver.reconnect()).await
813 }
814}
815
816impl<R: AsyncRuntime> Clone for AsyncReceiver<R> {
817 fn clone(&self) -> Self {
818 Self {
819 inner: Arc::clone(&self.inner),
820 _runtime: PhantomData,
821 }
822 }
823}
824
825macro_rules! async_receiver_capture_methods {
826 ($(($mode:ident, $kind:ident, $owned:ident, $borrowed:ident,
827 $capture:ident, $capture_ref:ident, $capture_with:ident, $label:literal)),* $(,)?) => {
828 $(
829 impl<R: AsyncRuntime> AsyncReceiver<R> {
830 #[doc = concat!("Capture owned ", $label, " on the runtime's blocking pool.")]
831 ///
832 /// The budget starts at first poll and includes blocking-pool queue
833 /// delay. A zero or spent budget makes one nonblocking SDK attempt.
834 /// Dropping the future stops waiting before its next attempt;
835 /// an attempt already running can consume an item that is discarded.
836 ///
837 /// # Errors
838 ///
839 /// Invalid timeouts, capture errors, or blocking-worker spawn failure.
840 #[doc(alias = "NDIlib_recv_capture_v3")]
841 pub async fn $capture(&self, timeout: Duration) -> Result<Option<crate::$owned>> {
842 self.$capture_with(timeout, |frame| frame.to_owned()).await
843 }
844
845 #[doc = concat!("Process borrowed ", $label, " on the blocking worker without copying its payload.")]
846 ///
847 /// `process` runs once for a delivered frame and retains its SDK
848 /// guard until it returns or unwinds. Only `T` crosses back to the
849 /// awaiting task; native frames and their borrowed slices cannot
850 /// escape. The callback and result must be `Send + 'static`.
851 /// The budget includes blocking-pool queue delay and SDK waits;
852 /// callback execution can finish after it and continues when the
853 /// future is dropped. Panics resume on the awaiting task after
854 /// the native guard has been released on the worker.
855 ///
856 /// # Errors
857 ///
858 /// Invalid timeouts, capture errors, or blocking-worker spawn failure.
859 #[doc(alias = "NDIlib_recv_capture_v3")]
860 pub async fn $capture_with<F, T>(&self, timeout: Duration, process: F) -> Result<Option<T>>
861 where
862 F: for<'frame> FnOnce(&crate::$borrowed<'frame>) -> T + Send + 'static,
863 T: Send + 'static,
864 {
865 self.capture_kind_with::<$kind, _, _>(timeout, process).await
866 }
867 }
868 )*
869 };
870}
871crate::capture::capture_method_kinds!(async_receiver_capture_methods);
872
873impl<R: AsyncRuntime> AsyncReceiver<R> {
874 async fn capture_kind_with<K, F, T>(&self, timeout: Duration, process: F) -> Result<Option<T>>
875 where
876 K: CaptureKind,
877 F: for<'frame> FnOnce(&K::Ref<'frame>) -> T + Send + 'static,
878 T: Send + 'static,
879 {
880 let receiver = Arc::clone(&self.inner);
881 with_timeout_budget::<R, _, _>(timeout, move |deadline, stop| {
882 Ok(process_captured(
883 receiver.capture_ref_until::<K>(deadline, stop)?,
884 process,
885 ))
886 })
887 .await
888 }
889}
890
891#[cfg(feature = "tokio")]
892pub mod tokio {
893 //! [`AsyncReceiver`] on the Tokio runtime: the
894 //! generic [`asynchronous::AsyncReceiver`](super::AsyncReceiver) with
895 //! [`Tokio`](super::Tokio), which run blocking work with
896 //! `tokio::task::spawn_blocking`.
897 //!
898 //! # Example
899 //!
900 //! ```no_run
901 //! use grafton_ndi::{Ndi, ReceiverOptions, asynchronous::tokio::AsyncReceiver};
902 //!
903 //! #[tokio::main]
904 //! async fn main() -> Result<(), grafton_ndi::Error> {
905 //! let ndi = Ndi::new()?;
906 //! // ... obtain source ...
907 //! # let source = grafton_ndi::Source::new("CAMERA (Program)").unwrap();
908 //!
909 //! let options = ReceiverOptions::snapshot_preset(source);
910 //! let receiver = grafton_ndi::Receiver::new(&ndi, &options)?;
911 //! let async_receiver = AsyncReceiver::new(receiver);
912 //!
913 //! // Capture without blocking the runtime
914 //! match async_receiver.capture_video_with(std::time::Duration::from_millis(100), |frame| {
915 //! (frame.width(), frame.height())
916 //! }).await? {
917 //! Some(size) => println!("Got dimensions: {size:?}"),
918 //! None => println!("No frame available"),
919 //! }
920 //!
921 //! Ok(())
922 //! }
923 //! ```
924 //!
925 //! See [mixed_media_async.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/mixed_media_async.rs)
926 //! for a complete Tokio example.
927
928 /// An [`AsyncReceiver`](super::AsyncReceiver) on the Tokio runtime.
929 pub type AsyncReceiver = super::AsyncReceiver<super::Tokio>;
930 /// Source discovery on the Tokio runtime, owning a finder or source cache.
931 pub type AsyncFinder<D = crate::Finder> = super::AsyncFinder<super::Tokio, D>;
932 /// Cached discovery on the Tokio runtime.
933 pub type AsyncSourceCache = AsyncFinder<crate::SourceCache>;
934 /// An owned discovery cursor on the Tokio runtime.
935 pub type AsyncSourceWatch<D = crate::Finder> = super::AsyncSourceWatch<super::Tokio, D>;
936}
937
938#[cfg(feature = "smol")]
939pub mod smol {
940 //! [`AsyncReceiver`] on the smol runtime: the
941 //! generic [`asynchronous::AsyncReceiver`](super::AsyncReceiver) with
942 //! [`Smol`](super::Smol), which run blocking work with `smol::unblock`.
943 //!
944 //! # Example
945 //!
946 //! ```no_run
947 //! use grafton_ndi::{Ndi, ReceiverOptions, asynchronous::smol::AsyncReceiver};
948 //!
949 //! fn main() -> Result<(), grafton_ndi::Error> {
950 //! ::smol::block_on(async {
951 //! let ndi = Ndi::new()?;
952 //! // ... obtain source ...
953 //! # let source = grafton_ndi::Source::new("CAMERA (Program)").unwrap();
954 //!
955 //! let options = ReceiverOptions::snapshot_preset(source);
956 //! let receiver = grafton_ndi::Receiver::new(&ndi, &options)?;
957 //! let async_receiver = AsyncReceiver::new(receiver);
958 //!
959 //! // Capture without blocking the runtime
960 //! match async_receiver.capture_video_with(std::time::Duration::from_millis(100), |frame| {
961 //! (frame.width(), frame.height())
962 //! }).await? {
963 //! Some(size) => println!("Got dimensions: {size:?}"),
964 //! None => println!("No frame available"),
965 //! }
966 //!
967 //! Ok(())
968 //! })
969 //! }
970 //! ```
971 //!
972 //! See [mixed_media_async.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/mixed_media_async.rs)
973 //! for a complete smol example.
974
975 /// An [`AsyncReceiver`](super::AsyncReceiver) on the smol runtime.
976 pub type AsyncReceiver = super::AsyncReceiver<super::Smol>;
977 /// Source discovery on the smol runtime, owning a finder or source cache.
978 pub type AsyncFinder<D = crate::Finder> = super::AsyncFinder<super::Smol, D>;
979 /// Cached discovery on the smol runtime.
980 pub type AsyncSourceCache = AsyncFinder<crate::SourceCache>;
981 /// An owned discovery cursor on the smol runtime.
982 pub type AsyncSourceWatch<D = crate::Finder> = super::AsyncSourceWatch<super::Smol, D>;
983}
984
985#[cfg(all(test, feature = "tokio"))]
986mod timeout_tests {
987 use super::*;
988 use std::{
989 sync::mpsc,
990 task::{Context, Poll, Waker},
991 };
992
993 fn runtime() -> ::tokio::runtime::Runtime {
994 ::tokio::runtime::Builder::new_current_thread()
995 .max_blocking_threads(1)
996 .build()
997 .unwrap()
998 }
999
1000 #[test]
1001 fn queued_work_uses_remaining_budget() {
1002 let runtime = runtime();
1003 runtime.block_on(async {
1004 let (started_tx, started_rx) = mpsc::channel();
1005 let (release_tx, release_rx) = mpsc::channel();
1006 let blocker = ::tokio::task::spawn_blocking(move || {
1007 started_tx.send(()).unwrap();
1008 release_rx.recv().unwrap();
1009 });
1010 started_rx.recv().unwrap();
1011
1012 let budget = Duration::from_millis(20);
1013 let mut capture =
1014 Box::pin(with_timeout_budget::<Tokio, _, _>(budget, |deadline, _| {
1015 Ok((deadline.remaining(), deadline.remaining_ms()))
1016 }));
1017 let mut context = Context::from_waker(Waker::noop());
1018 assert!(matches!(capture.as_mut().poll(&mut context), Poll::Pending));
1019 // Keep the sole worker occupied until the whole budget has elapsed.
1020 std::thread::sleep(budget + Duration::from_millis(5));
1021 release_tx.send(()).unwrap();
1022 // The queue delay spent the budget: the work starts with none left.
1023 let (remaining, remaining_ms) = capture.await.unwrap();
1024 assert_eq!((remaining, remaining_ms), (Duration::ZERO, 0));
1025 blocker.await.unwrap();
1026 });
1027 }
1028
1029 #[test]
1030 fn budgeted_work_resumes_the_original_panic() {
1031 let panic = std::panic::catch_unwind(|| {
1032 runtime().block_on(with_timeout_budget::<Tokio, _, ()>(
1033 Duration::ZERO,
1034 |_, _| std::panic::panic_any(42_u32),
1035 ))
1036 })
1037 .expect_err("a worker panic must unwind the awaiting caller");
1038 assert_eq!(*panic.downcast::<u32>().unwrap(), 42);
1039 }
1040
1041 #[test]
1042 fn invalid_budget_is_rejected_before_spawning() {
1043 // No entered runtime: trying to submit work would panic.
1044 let mut capture = Box::pin(with_timeout_budget::<Tokio, _, ()>(
1045 crate::MAX_TIMEOUT + Duration::from_nanos(1),
1046 |_, _| panic!("invalid timeout must not execute blocking work"),
1047 ));
1048 let mut context = Context::from_waker(Waker::noop());
1049 assert!(matches!(
1050 capture.as_mut().poll(&mut context),
1051 Poll::Ready(Err(_))
1052 ));
1053 }
1054}
1055
1056#[cfg(all(test, feature = "smol"))]
1057mod smol_tests {
1058 use super::{
1059 private::{Spawn, Token},
1060 *,
1061 };
1062 use std::{
1063 sync::mpsc,
1064 task::{Context, Poll, Waker},
1065 time::Instant,
1066 };
1067
1068 #[test]
1069 fn dropping_unpolled_future_starts_no_work() {
1070 let called = Arc::new(AtomicBool::new(false));
1071 let worker_called = Arc::clone(&called);
1072 let operation = Smol::spawn_blocking(Token, move || {
1073 worker_called.store(true, Ordering::Release);
1074 });
1075 drop(operation);
1076 assert!(!called.load(Ordering::Acquire));
1077 }
1078
1079 #[test]
1080 fn dropping_started_future_allows_work_to_finish() {
1081 let (started_tx, started_rx) = mpsc::channel();
1082 let (release_tx, release_rx) = mpsc::channel();
1083 let (finished_tx, finished_rx) = mpsc::channel();
1084 let mut operation = Box::pin(Smol::spawn_blocking(Token, move || {
1085 started_tx.send(()).unwrap();
1086 release_rx.recv().unwrap();
1087 finished_tx.send(42).unwrap();
1088 }));
1089 let mut context = Context::from_waker(Waker::noop());
1090 assert!(matches!(
1091 operation.as_mut().poll(&mut context),
1092 Poll::Pending
1093 ));
1094 started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1095 drop(operation);
1096 release_tx.send(()).unwrap();
1097 assert_eq!(
1098 finished_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
1099 42
1100 );
1101 }
1102
1103 #[test]
1104 fn invalid_budget_does_not_start_work() {
1105 let called = Arc::new(AtomicBool::new(false));
1106 let worker_called = Arc::clone(&called);
1107 let result = ::smol::block_on(with_timeout_budget::<Smol, _, _>(
1108 crate::MAX_TIMEOUT + Duration::from_nanos(1),
1109 move |_, _| {
1110 worker_called.store(true, Ordering::Release);
1111 Ok(())
1112 },
1113 ));
1114 assert!(result.is_err());
1115 assert!(!called.load(Ordering::Acquire));
1116 }
1117
1118 #[test]
1119 fn budgeted_work_resumes_the_original_panic() {
1120 let panic = std::panic::catch_unwind(|| {
1121 ::smol::block_on(with_timeout_budget::<Smol, _, ()>(
1122 Duration::ZERO,
1123 |_, _| std::panic::panic_any(42_u32),
1124 ))
1125 })
1126 .expect_err("a worker panic must unwind the awaiting caller");
1127 assert_eq!(*panic.downcast::<u32>().unwrap(), 42);
1128 }
1129
1130 #[test]
1131 fn budget_starts_on_first_poll_and_keeps_one_deadline() {
1132 let budget = Duration::from_millis(20);
1133 let (started_tx, started_rx) = mpsc::channel();
1134 let (release_tx, release_rx) = mpsc::channel();
1135 let mut operation = Box::pin(with_timeout_budget::<Smol, _, _>(
1136 budget,
1137 move |deadline: Deadline, _: &AtomicBool| {
1138 started_tx.send(deadline.end()).unwrap();
1139 release_rx.recv().unwrap();
1140 Ok(deadline.remaining())
1141 },
1142 ));
1143 // Construction must not consume the wait budget.
1144 std::thread::sleep(budget);
1145 let before_poll = Instant::now();
1146 let mut context = Context::from_waker(Waker::noop());
1147 assert!(matches!(
1148 operation.as_mut().poll(&mut context),
1149 Poll::Pending
1150 ));
1151 let after_poll = Instant::now();
1152 let deadline = started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1153 assert!(deadline >= before_poll + budget);
1154 assert!(deadline <= after_poll + budget);
1155 // A wait inside blocking work must not reset the shared capture deadline.
1156 std::thread::sleep(deadline.saturating_duration_since(Instant::now()));
1157 release_tx.send(()).unwrap();
1158 assert_eq!(::smol::block_on(operation).unwrap(), Duration::ZERO);
1159 }
1160}
1161
1162#[cfg(test)]
1163mod executor_tests {
1164 use super::{
1165 private::{Spawn, Token},
1166 *,
1167 };
1168
1169 #[test]
1170 fn cancellation_skips_queued_operation() {
1171 let (guard, work) = blocking_operation(|| panic!("cancelled work must not run"));
1172 drop(guard);
1173 assert!(matches!(
1174 work(),
1175 Err(Error::SpawnFailed(SpawnFailure::TaskCancelled))
1176 ));
1177 }
1178
1179 #[test]
1180 fn cancellation_allows_started_operation_to_finish() {
1181 let (started_tx, started_rx) = std::sync::mpsc::channel();
1182 let (finish_tx, finish_rx) = std::sync::mpsc::channel();
1183 let (guard, work) = blocking_operation(move || {
1184 started_tx.send(()).unwrap();
1185 finish_rx.recv().unwrap();
1186 42
1187 });
1188 let worker = std::thread::spawn(work);
1189 started_rx.recv().unwrap();
1190 drop(guard);
1191 finish_tx.send(()).unwrap();
1192 assert_eq!(worker.join().unwrap().unwrap(), 42);
1193 }
1194
1195 #[cfg(feature = "tokio")]
1196 #[test]
1197 fn missing_tokio_context_returns_error() {
1198 use std::task::{Context, Poll, Waker};
1199 let mut operation = Box::pin(Tokio::spawn_blocking(Token, || 42));
1200 let mut context = Context::from_waker(Waker::noop());
1201 assert!(matches!(
1202 operation.as_mut().poll(&mut context),
1203 Poll::Ready(Err(Error::SpawnFailed(SpawnFailure::NoRuntime)))
1204 ));
1205 }
1206
1207 #[cfg(feature = "tokio")]
1208 #[test]
1209 fn validated_connect_requires_a_runtime_without_changing_the_target() {
1210 use std::task::{Context, Poll, Waker};
1211 let Some(ndi) = crate::test_support::ndi() else {
1212 return;
1213 };
1214 let receiver = AsyncReceiver::<Tokio>::new(
1215 Receiver::new(&ndi, &crate::ReceiverOptions::disconnected()).unwrap(),
1216 );
1217 assert!(matches!(
1218 Source::new("NUL\0name"),
1219 Err(Error::InvalidCString(_))
1220 ));
1221 let source = Source::new("validated target").unwrap();
1222 let mut connect = std::pin::pin!(receiver.connect_to(&source));
1223 assert!(matches!(
1224 connect
1225 .as_mut()
1226 .poll(&mut Context::from_waker(Waker::noop())),
1227 Poll::Ready(Err(Error::SpawnFailed(SpawnFailure::NoRuntime)))
1228 ));
1229 assert!(receiver.receiver().connection_target().is_none());
1230 }
1231
1232 #[cfg(feature = "tokio")]
1233 #[test]
1234 fn tokio_resumes_blocking_panic() {
1235 let runtime = ::tokio::runtime::Builder::new_current_thread()
1236 .build()
1237 .unwrap();
1238 let panic = std::panic::catch_unwind(|| {
1239 runtime.block_on(Tokio::spawn_blocking(Token, || panic!("test panic")))
1240 })
1241 .unwrap_err();
1242 assert_eq!(panic.downcast_ref::<&str>(), Some(&"test panic"));
1243 }
1244
1245 #[cfg(feature = "smol")]
1246 #[test]
1247 fn smol_resumes_blocking_panic() {
1248 let panic = std::panic::catch_unwind(|| {
1249 ::smol::block_on(Smol::spawn_blocking(Token, || panic!("test panic")))
1250 })
1251 .unwrap_err();
1252 assert_eq!(panic.downcast_ref::<&str>(), Some(&"test panic"));
1253 }
1254
1255 #[cfg(feature = "tokio")]
1256 #[test]
1257 fn cancelled_tokio_task_reports_a_typed_reason() {
1258 let runtime = ::tokio::runtime::Builder::new_current_thread()
1259 .build()
1260 .unwrap();
1261 runtime.block_on(async {
1262 let task = ::tokio::spawn(std::future::pending::<()>());
1263 task.abort();
1264 assert!(matches!(
1265 tokio_join_error(task.await.unwrap_err()),
1266 Error::SpawnFailed(SpawnFailure::TaskCancelled)
1267 ));
1268 });
1269 }
1270
1271 #[cfg(feature = "tokio")]
1272 #[test]
1273 fn dropping_tokio_future_skips_queued_work() {
1274 use std::task::{Context, Poll, Waker};
1275 let runtime = ::tokio::runtime::Builder::new_current_thread()
1276 .max_blocking_threads(1)
1277 .build()
1278 .unwrap();
1279 runtime.block_on(async {
1280 let (started_tx, started_rx) = std::sync::mpsc::channel();
1281 let (release_tx, release_rx) = std::sync::mpsc::channel();
1282 let blocker = ::tokio::task::spawn_blocking(move || {
1283 started_tx.send(()).unwrap();
1284 release_rx.recv().unwrap();
1285 });
1286 started_rx.recv().unwrap();
1287 let called = Arc::new(AtomicBool::new(false));
1288 let worker_called = Arc::clone(&called);
1289 let mut operation = Box::pin(Tokio::spawn_blocking(Token, move || {
1290 worker_called.store(true, Ordering::Release)
1291 }));
1292 let mut context = Context::from_waker(Waker::noop());
1293 assert!(matches!(
1294 operation.as_mut().poll(&mut context),
1295 Poll::Pending
1296 ));
1297 drop(operation);
1298 release_tx.send(()).unwrap();
1299 blocker.await.unwrap();
1300 // The single worker processes the cancelled closure before this sentinel.
1301 ::tokio::task::spawn_blocking(|| ()).await.unwrap();
1302 assert!(!called.load(Ordering::Acquire));
1303 });
1304 }
1305}
1306
1307#[cfg(test)]
1308mod receiver_tests {
1309 use super::*;
1310 use crate::{receiver::PendingEvents, Ndi, ReceiverOptions, RuntimeFeature};
1311
1312 /// An async receiver of `ndi` that starts without a target.
1313 fn unconnected<R: AsyncRuntime>(ndi: &Ndi) -> AsyncReceiver<R> {
1314 AsyncReceiver::new(Receiver::new(ndi, &ReceiverOptions::disconnected()).unwrap())
1315 }
1316
1317 impl ReplayReceiverValue<PendingEvents> for ReceiverReport<ReceiverEvent> {
1318 type Value = ReceiverEvent;
1319 fn into_value(self) -> Self::Value {
1320 self.value
1321 }
1322 fn replay(self, pending: &PendingEvents) {
1323 pending.replay(self);
1324 }
1325 }
1326
1327 #[test]
1328 fn receiver_delivery_replays_only_while_armed() {
1329 let pending = Arc::new(PendingEvents::default());
1330 let take = || {
1331 pending
1332 .take(|| Ok(crate::ReceiverStatus::default()))
1333 .unwrap()
1334 .map(ReceiverReport::into_value)
1335 };
1336 let event = ReceiverEvent::SourceChanged;
1337 drop(ReceiverDelivery::new(
1338 Arc::clone(&pending),
1339 Some(ReceiverReport::unsequenced(event)),
1340 ));
1341 assert_eq!(take(), Some(event));
1342 assert_eq!(
1343 ReceiverDelivery::new(
1344 Arc::clone(&pending),
1345 Some(ReceiverReport::unsequenced(event))
1346 )
1347 .take(),
1348 Some(event)
1349 );
1350 assert_eq!(take(), None);
1351 drop(ReceiverDelivery::<ReceiverReport<ReceiverEvent>, _>::new(
1352 Arc::clone(&pending),
1353 None,
1354 ));
1355 assert_eq!(
1356 ReceiverDelivery::<ReceiverReport<ReceiverEvent>, _>::new(Arc::clone(&pending), None)
1357 .take(),
1358 None
1359 );
1360 assert_eq!(take(), None);
1361 }
1362
1363 // Scoped entry points keep capturing while local connection changes are
1364 // locked. A disconnected source can still deliver connection events.
1365 #[allow(clippy::await_holding_lock)] // Verify captures do not take the connection lock.
1366 async fn scoped_captures_during_connection_changes<R: AsyncRuntime>(
1367 receiver: &AsyncReceiver<R>,
1368 ) {
1369 let _exclusive = receiver.inner.core.reconnect_lock();
1370 for timeout in [Duration::ZERO, Duration::from_millis(25)] {
1371 assert!(receiver
1372 .capture_video_with(timeout, |_| panic!("no video"))
1373 .await
1374 .unwrap()
1375 .is_none());
1376 receiver
1377 .capture_any_with(timeout, |item| {
1378 assert!(matches!(item, ReceiverItemRef::Event(_)));
1379 })
1380 .await
1381 .unwrap();
1382 }
1383 }
1384
1385 /// Lending the receiver adds no field and preserves its auto traits.
1386 /// Receiver and both runtime-specific AsyncReceiver types are UnwindSafe
1387 /// and RefUnwindSafe, as tests/public_auto_traits.rs asserts.
1388 #[test]
1389 fn async_receivers_keep_their_auto_traits() {
1390 fn shared<T: Send + Sync + Clone + 'static>() {}
1391 #[cfg(feature = "tokio")]
1392 shared::<AsyncReceiver<Tokio>>();
1393 #[cfg(feature = "smol")]
1394 shared::<AsyncReceiver<Smol>>();
1395 }
1396
1397 /// Every future can be spawned on a multi-threaded executor.
1398 fn futures_are_send<R: AsyncRuntime>(receiver: &AsyncReceiver<R>, source: &Source) {
1399 fn send<T: Send>(_: T) {}
1400 send(receiver.capture_video(Duration::ZERO));
1401 send(receiver.capture_video_with(Duration::ZERO, |frame| frame.width()));
1402 send(receiver.capture_audio_with(Duration::ZERO, |frame| frame.num_samples()));
1403 send(receiver.capture_metadata_with(Duration::ZERO, |frame| frame.data().len()));
1404 send(receiver.capture_any(Duration::ZERO));
1405 send(receiver.capture_any_with(Duration::ZERO, |_| ()));
1406 send(receiver.next_event(Duration::ZERO));
1407 send(receiver.wait_for_source_name_change(Duration::ZERO));
1408 send(receiver.connect_to(source));
1409 send(receiver.disconnect());
1410 send(receiver.reconnect());
1411 }
1412
1413 #[test]
1414 fn async_receiver_futures_are_send() {
1415 // Type checking is the test: the function is never called.
1416 #[cfg(feature = "tokio")]
1417 let _: fn(&AsyncReceiver<Tokio>, &Source) = futures_are_send::<Tokio>;
1418 #[cfg(feature = "smol")]
1419 let _: fn(&AsyncReceiver<Smol>, &Source) = futures_are_send::<Smol>;
1420 }
1421
1422 /// Every async operation of `receiver`, which `unconnected` made.
1423 async fn operations_of_an_unconnected_receiver<R: AsyncRuntime>(
1424 ndi: &Ndi,
1425 receiver: &AsyncReceiver<R>,
1426 ) {
1427 // The lent receiver is the one the operations use.
1428 assert!(std::ptr::eq(receiver.receiver(), &*receiver.inner));
1429 assert!(receiver.receiver().connection_target().is_none());
1430
1431 let excessive = crate::MAX_TIMEOUT + Duration::from_nanos(1);
1432 assert!(matches!(
1433 receiver.next_event(excessive).await,
1434 Err(Error::InvalidInput(_))
1435 ));
1436 assert!(matches!(
1437 receiver.capture_any(excessive).await,
1438 Err(Error::InvalidInput(_))
1439 ));
1440 assert!(matches!(
1441 receiver.wait_for_source_name_change(excessive).await,
1442 Err(Error::InvalidInput(_))
1443 ));
1444 assert!(receiver.next_event(Duration::ZERO).await.unwrap().is_none());
1445 assert!(receiver
1446 .capture_any(Duration::ZERO)
1447 .await
1448 .unwrap()
1449 .is_none());
1450 let change = receiver.wait_for_source_name_change(Duration::ZERO).await;
1451 if ndi
1452 .require_feature(RuntimeFeature::ConnectedSourceName)
1453 .is_ok()
1454 {
1455 assert!(change.is_ok(), "{change:?}");
1456 } else {
1457 assert!(
1458 matches!(change, Err(Error::UnsupportedCapability { .. })),
1459 "{change:?}"
1460 );
1461 }
1462
1463 assert!(matches!(
1464 Source::new("NUL\0in name"),
1465 Err(Error::InvalidCString(_))
1466 ));
1467 assert!(receiver.receiver().connection_target().is_none());
1468 let target = Source::new("changed target").unwrap();
1469 receiver.connect_to(&target).await.unwrap();
1470 receiver.disconnect().await.unwrap();
1471 receiver.reconnect().await.unwrap();
1472 // Disconnect and reconnect retain the latest requested target.
1473 assert_eq!(
1474 receiver.receiver().connection_target().as_ref(),
1475 Some(&target)
1476 );
1477 }
1478
1479 #[cfg(feature = "smol")]
1480 #[test]
1481 fn smol_operations_of_an_unconnected_receiver() {
1482 let Some(ndi) = crate::test_support::ndi() else {
1483 return;
1484 };
1485 let receiver = unconnected::<Smol>(&ndi);
1486 ::smol::block_on(operations_of_an_unconnected_receiver(&ndi, &receiver));
1487 ::smol::block_on(scoped_captures_during_connection_changes(&receiver));
1488 }
1489
1490 #[cfg(feature = "tokio")]
1491 mod tokio_runtime {
1492 use super::*;
1493 use std::{
1494 sync::mpsc,
1495 task::{Context, Poll, Waker},
1496 };
1497
1498 /// A runtime with one blocking thread, so that work queues behind a
1499 /// blocker, and every native capture is made, and counted, on that
1500 /// one thread.
1501 fn runtime() -> ::tokio::runtime::Runtime {
1502 ::tokio::runtime::Builder::new_current_thread()
1503 .max_blocking_threads(1)
1504 .build()
1505 .unwrap()
1506 }
1507
1508 /// Occupy the one blocking thread until the returned sender is used.
1509 fn occupy_worker() -> (mpsc::Sender<()>, ::tokio::task::JoinHandle<()>) {
1510 let (started_tx, started_rx) = mpsc::channel();
1511 let (release_tx, release_rx) = mpsc::channel::<()>();
1512 let blocker = ::tokio::task::spawn_blocking(move || {
1513 started_tx.send(()).unwrap();
1514 release_rx.recv().unwrap();
1515 });
1516 started_rx.recv().unwrap();
1517 (release_tx, blocker)
1518 }
1519
1520 #[test]
1521 fn tokio_operations_of_an_unconnected_receiver() {
1522 let Some(ndi) = crate::test_support::ndi() else {
1523 return;
1524 };
1525 let receiver = unconnected::<Tokio>(&ndi);
1526 runtime().block_on(operations_of_an_unconnected_receiver(&ndi, &receiver));
1527 runtime().block_on(scoped_captures_during_connection_changes(&receiver));
1528 }
1529
1530 #[test]
1531 fn async_connect_allocates_only_preparation_and_dispatch() {
1532 let Some(ndi) = crate::test_support::ndi() else {
1533 return;
1534 };
1535 let receiver = unconnected::<Tokio>(&ndi);
1536 let runtime = runtime();
1537 runtime.block_on(receiver.reconnect()).unwrap();
1538 for source in [
1539 Source::new("allocation target").unwrap(),
1540 Source::new("allocation target")
1541 .unwrap()
1542 .with_address(crate::SourceAddress::new("192.0.2.1:5960").unwrap()),
1543 ] {
1544 runtime.block_on(receiver.connect_to(&source)).unwrap();
1545 let ((), synchronous) =
1546 crate::test_alloc::allocation_count(|| receiver.receiver().connect_to(&source));
1547 let (result, dispatch) =
1548 crate::test_alloc::allocation_count(|| runtime.block_on(receiver.reconnect()));
1549 result.unwrap();
1550 let (result, asynchronous) = crate::test_alloc::allocation_count(|| {
1551 runtime.block_on(receiver.connect_to(&source))
1552 });
1553 result.unwrap();
1554 assert_eq!(asynchronous, synchronous + dispatch, "source {source:?}");
1555 }
1556 assert!(matches!(
1557 Source::new("NUL\0target"),
1558 Err(Error::InvalidCString(_))
1559 ));
1560 }
1561
1562 #[test]
1563 fn dropping_a_queued_connect_preserves_the_target() {
1564 let Some(ndi) = crate::test_support::ndi() else {
1565 return;
1566 };
1567 let receiver = unconnected::<Tokio>(&ndi);
1568 runtime().block_on(async {
1569 let initial = receiver.receiver().connection_target();
1570 let (release, blocker) = occupy_worker();
1571 let target = Source::new("cancelled target").unwrap();
1572 let mut connect = Box::pin(receiver.connect_to(&target));
1573 let mut context = Context::from_waker(Waker::noop());
1574 assert!(matches!(connect.as_mut().poll(&mut context), Poll::Pending));
1575 drop(connect);
1576 release.send(()).unwrap();
1577 blocker.await.unwrap();
1578 // A sentinel on the sole worker follows the cancelled closure.
1579 ::tokio::task::spawn_blocking(|| {}).await.unwrap();
1580 assert_eq!(receiver.receiver().connection_target(), initial);
1581 });
1582 }
1583 }
1584}
1585
1586#[cfg(test)]
1587mod scoped_tests;
1588
1589#[cfg(test)]
1590mod source_name_cancellation_sdk_tests;