Skip to main content

grafton_ndi/advanced/
receive.rs

1//! Receiving compressed packets instead of decoded frames.
2
3#[cfg(test)]
4use crate::capture::CaptureKind;
5use std::time::Duration;
6
7#[cfg(test)]
8use super::CompressedFrame;
9use super::{
10    AudioCodec, AudioPacketFormat, CompressedRef, PacketAttached, ReceivedPacket, ReceiverControls,
11    VideoCodec, VideoPacketFormat,
12};
13use crate::{
14    capture::{AllSlots, AudioKind, CaptureStrategy, Guard, Media, MetadataKind, VideoKind},
15    sys::bindings::*,
16    timeout::Deadline,
17    AudioFrame, AudioFrameRef, MetadataFrame, MetadataFrameRef, Ndi, Receiver, ReceiverEvent,
18    ReceiverOptions, Result, VideoFrame, VideoFrameRef,
19};
20
21/// Which compressed formats a [`PacketReceiver`] passes through.
22///
23/// A frame in a format the preset names is delivered as the source sent it;
24/// any other frame is delivered decoded, so every capture can yield either
25/// kind. Decoded video is 8-bit unless the preset is one of the "best" ones,
26/// which keep the source's bit depth.
27///
28/// Whether a preset can be used is
29/// [`RuntimeFeature::Passthrough`](crate::capabilities::RuntimeFeature::Passthrough):
30/// the headers of an older SDK may not declare every preset.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum PassthroughPreset {
34    /// SpeedHQ only.
35    SpeedHqOnly,
36    /// SpeedHQ; other sources are decoded.
37    SpeedHq,
38    /// As [`SpeedHq`](Self::SpeedHq), decoding to the source's bit depth.
39    SpeedHqBest,
40    /// SpeedHQ and H.264.
41    H264,
42    /// As [`H264`](Self::H264), decoding to the source's bit depth.
43    H264Best,
44    /// As [`H264`](Self::H264), with compressed audio.
45    H264WithAudio,
46    /// SpeedHQ, H.264 and HEVC.
47    Hevc,
48    /// As [`Hevc`](Self::Hevc), decoding to the source's bit depth.
49    HevcBest,
50    /// As [`Hevc`](Self::Hevc), with compressed audio.
51    HevcWithAudio,
52    /// SpeedHQ, H.264 and HEVC, including H.264 and HEVC with alpha.
53    Alpha,
54    /// As [`Alpha`](Self::Alpha), decoding to the source's bit depth.
55    AlphaBest,
56    /// As [`Alpha`](Self::Alpha), with compressed audio including Opus.
57    AlphaWithAudio,
58    /// As [`Alpha`](Self::Alpha), for protected streams as well.
59    Protected,
60    /// As [`Protected`](Self::Protected), decoding to the source's bit depth.
61    ProtectedBest,
62    /// As [`Protected`](Self::Protected), with compressed audio including Opus.
63    ProtectedWithAudio,
64}
65
66/// Video from a [`PacketReceiver`]: a codec packet when the source's format is
67/// one the preset passes through, a decoded frame otherwise.
68#[derive(Clone, Debug)]
69#[non_exhaustive]
70pub enum ReceivedVideo {
71    /// A decoded frame.
72    Decoded(VideoFrame),
73    /// A codec packet, exactly as the source sent it.
74    Compressed(ReceivedPacket<VideoPacketFormat>),
75}
76
77/// Audio from a [`PacketReceiver`]: a codec packet when the source's format is
78/// one the preset passes through, decoded samples otherwise.
79#[derive(Clone, Debug)]
80#[non_exhaustive]
81pub enum ReceivedAudio {
82    /// Decoded planar floating-point audio.
83    Decoded(AudioFrame),
84    /// A codec packet, exactly as the source sent it.
85    Compressed(ReceivedPacket<AudioPacketFormat>),
86}
87
88/// What one [`PacketReceiver::capture_any`] call produced.
89#[derive(Clone, Debug)]
90#[non_exhaustive]
91pub enum PacketItem {
92    /// A video frame.
93    Video(ReceivedVideo),
94    /// An audio frame.
95    Audio(ReceivedAudio),
96    /// A metadata frame.
97    Metadata(MetadataFrame),
98    /// A receiver invalidation, with the same status snapshot and semantics
99    /// as [`crate::ReceiverItem::Event`].
100    Event(ReceiverEvent),
101}
102
103/// Borrowed video returned by a packet receiver, retaining its native buffer.
104#[derive(Debug)]
105#[non_exhaustive]
106pub enum ReceivedVideoRef<'rx> {
107    /// Decoded pixels borrowed from the receiver.
108    Decoded(VideoFrameRef<'rx>),
109    /// Codec bytes borrowed in place.
110    Compressed(CompressedRef<'rx, VideoPacketFormat>),
111}
112
113impl ReceivedVideoRef<'_> {
114    /// Copy into the corresponding owned packet or decoded frame.
115    pub fn to_owned(&self) -> ReceivedVideo {
116        match self {
117            Self::Decoded(frame) => ReceivedVideo::Decoded(frame.to_owned()),
118            Self::Compressed(frame) => ReceivedVideo::Compressed(frame.to_owned()),
119        }
120    }
121}
122
123/// Borrowed audio returned by a packet receiver.
124#[derive(Debug)]
125#[non_exhaustive]
126pub enum ReceivedAudioRef<'rx> {
127    /// Decoded samples borrowed from the receiver.
128    Decoded(AudioFrameRef<'rx>),
129    /// Codec bytes borrowed in place.
130    Compressed(CompressedRef<'rx, AudioPacketFormat>),
131}
132
133impl ReceivedAudioRef<'_> {
134    /// Copy into the corresponding owned packet or decoded samples.
135    pub fn to_owned(&self) -> ReceivedAudio {
136        match self {
137            Self::Decoded(frame) => ReceivedAudio::Decoded(frame.to_owned()),
138            Self::Compressed(frame) => ReceivedAudio::Compressed(frame.to_owned()),
139        }
140    }
141}
142
143/// One borrowed packet, decoded frame, metadata frame, or receiver event.
144///
145/// Media retains its SDK or custom-allocator buffer until dropped. Each
146/// reference borrows the receiver, and may be moved or shared across threads.
147#[derive(Debug)]
148#[non_exhaustive]
149pub enum PacketItemRef<'rx> {
150    /// Video, decoded or compressed according to the preset.
151    Video(ReceivedVideoRef<'rx>),
152    /// Audio, decoded or compressed according to the preset.
153    Audio(ReceivedAudioRef<'rx>),
154    /// A standalone metadata frame.
155    Metadata(MetadataFrameRef<'rx>),
156    /// A coalesced receiver invalidation, as in owned capture.
157    Event(ReceiverEvent),
158}
159
160impl PacketItemRef<'_> {
161    /// Copy the item into independent owned storage. Events are copied directly.
162    pub fn to_owned(&self) -> PacketItem {
163        match self {
164            Self::Video(frame) => PacketItem::Video(frame.to_owned()),
165            Self::Audio(frame) => PacketItem::Audio(frame.to_owned()),
166            Self::Metadata(frame) => PacketItem::Metadata(frame.to_owned()),
167            Self::Event(event) => PacketItem::Event(*event),
168        }
169    }
170}
171
172/// A receiver that delivers compressed packets where it can.
173///
174/// One capture call returns whichever frame or event arrives first, as a
175/// [`PacketItem`] from [`capture_any`](Self::capture_any), or a borrowed
176/// [`PacketItemRef`] from [`capture_any_ref`](Self::capture_any_ref). It cannot feed a
177/// [`FrameSync`](crate::framesync::FrameSync), which needs decoded frames.
178///
179/// [`receiver`](Self::receiver) and [`controls`](Self::controls) reach
180/// the [`Receiver`] it holds, in the [`PacketAttached`] mode, for the common
181/// controls: tally, PTZ, statistics, upstream metadata, keyframe requests,
182/// stream selection, reconnecting and KVM. Its own frame and event capture is
183/// unavailable, because packet capture takes them.
184///
185/// # Threading
186///
187/// A packet receiver is [`Send`] and [`Sync`], as the [`Receiver`] it holds
188/// is: it can be created on one thread, capture on another and be dropped on a
189/// third. Both capture methods take a shared reference, so packet references
190/// coexist with shared receiver controls and connection changes. The receiver
191/// binds each native capture to one instance, runtime and bounded attempt.
192///
193/// # Examples
194///
195/// ```no_run
196/// use std::time::Duration;
197/// use grafton_ndi::{
198///     advanced::{PacketItem, PacketReceiver, PassthroughPreset, ReceivedVideo},
199///     ReceiverOptions, Source, Ndi, Tally,
200/// };
201///
202/// # fn main() -> Result<(), grafton_ndi::Error> {
203/// let ndi = Ndi::new()?;
204/// # let source = Source::new("ENCODER (HEVC)").unwrap();
205/// let mut receiver =
206///     PacketReceiver::new(&ndi, &ReceiverOptions::new(source), PassthroughPreset::Hevc)?;
207/// receiver.receiver().set_tally(Tally::new(true, false));
208/// if let Some(PacketItem::Video(ReceivedVideo::Compressed(packet))) =
209///     receiver.capture_any(Duration::from_secs(1))?
210/// {
211///     println!("{:?}: {} bytes", packet.format().codec(), packet.data().len());
212/// }
213/// # Ok(())
214/// # }
215/// ```
216pub struct PacketReceiver {
217    // Its Send and Sync are the receiver's. Nothing here ties a packet
218    // receiver to a thread: it is created as an ordinary receiver is, with a
219    // passthrough color format, and its capture is the receiver's
220    // NDIlib_recv_capture_v3, which the SDK lets several threads call at
221    // once (Processing.NDI.Recv.h). Connection changes may overlap those
222    // calls, as measured beside receiver::CaptureLock.
223    // Borrowed results retain their Guard until dropped; its lifetime keeps
224    // this owner alive. Owned capture copies through that same borrowed path.
225    pub(crate) receiver: Receiver<PacketAttached>,
226}
227
228impl std::fmt::Debug for PacketReceiver {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        f.debug_struct("PacketReceiver")
231            .field("receiver", &self.receiver)
232            .finish_non_exhaustive()
233    }
234}
235
236impl PacketReceiver {
237    /// Create a receiver that passes through the formats `preset` names,
238    /// with the options' Advanced SDK
239    /// [configuration](ReceiverOptions::config), or the SDK's default one when
240    /// they carry none.
241    ///
242    /// The options' color format is replaced by the preset, and is neither
243    /// used nor checked against the runtime; fielded video is always allowed,
244    /// because a compressed stream cannot be deinterlaced.
245    ///
246    /// # Errors
247    ///
248    /// As for [`Receiver::new`], with [`Error::UnsupportedCapability`]
249    /// without an Advanced runtime (or in a build without the Advanced SDK),
250    /// and reported for [`RuntimeFeature::Passthrough`] with this preset.
251    ///
252    /// [`Error::UnsupportedCapability`]: crate::Error::UnsupportedCapability
253    /// [`RuntimeFeature::Passthrough`]: crate::capabilities::RuntimeFeature::Passthrough
254    #[doc(alias = "NDIlib_recv_create_v4")]
255    pub fn new(ndi: &Ndi, options: &ReceiverOptions, preset: PassthroughPreset) -> Result<Self> {
256        let options = creation_options(options, ndi.passthrough_format(preset)?);
257        let receiver = <Receiver<PacketAttached> as super::Configurable>::create_configured(
258            ndi,
259            &options,
260            options.configured_config(),
261        )?;
262        Ok(Self::from_receiver(receiver))
263    }
264
265    pub(crate) fn from_receiver(receiver: Receiver<PacketAttached>) -> Self {
266        Self { receiver }
267    }
268
269    /// The receiver this holds, for the common controls: tally, PTZ,
270    /// statistics, upstream metadata, keyframe requests, delays, reconnecting
271    /// and source-name changes.
272    ///
273    /// Its own frame and event capture is unavailable in the
274    /// [`PacketAttached`] mode; [`capture_any`](Self::capture_any) delivers both.
275    pub fn receiver(&self) -> &Receiver<PacketAttached> {
276        &self.receiver
277    }
278
279    /// Borrow exclusive stream controls or start KVM, without permitting
280    /// receiver replacement. This allocates nothing and makes no SDK call.
281    /// During a KVM session, capture packets through the session's
282    /// [`receiver()`](super::KvmSession::receiver) view, with `capture_any` or
283    /// `capture_any_ref`.
284    pub fn controls(&mut self) -> ReceiverControls<'_, PacketAttached> {
285        ReceiverControls::new(&mut self.receiver)
286    }
287
288    /// Wait up to `timeout` for the next frame or event, or return `None`
289    /// when none arrived in time.
290    ///
291    /// A delivered packet may have been queued; a timeout alone does not
292    /// establish disconnection. Use the attached receiver's per-media
293    /// counters as described in the
294    /// [reception monitoring guide](https://github.com/GrantSparks/grafton-ndi/blob/main/docs/usage.md#monitor-reception-of-the-expected-media).
295    /// Notifications are coalesced [`ReceiverEvent`] invalidations, consumed
296    /// once. Status changes include the current connection count, as in raw
297    /// mixed capture; pending notifications are delivered before waiting.
298    ///
299    /// The timeout is spent as [`Receiver::capture_any`]
300    /// spends it. The SDK returns early, with neither a frame nor an event,
301    /// while a new connection synchronizes; this captures again until
302    /// something arrives, and returns `None` only once the whole timeout is
303    /// spent. [`Duration::ZERO`] makes one attempt without waiting. Each native
304    /// attempt waits at most 100 ms, and connection changes may run concurrently.
305    ///
306    /// # Errors
307    ///
308    /// [`Error::InvalidInput`] when `timeout` exceeds
309    /// [`crate::MAX_TIMEOUT`], [`Error::ConnectionLost`] when the SDK reports a
310    /// lost connection, [`Error::InvalidFrame`] when a delivered frame fails
311    /// validation, and [`Error::InvalidUtf8`] for standalone metadata that
312    /// is not valid UTF-8.
313    /// [`crate::Error::UnexpectedSdkResult`] reports a negative status
314    /// connection count once per publication. Its event stays pending for
315    /// recovery while other events and media remain available.
316    ///
317    /// [`Error::InvalidInput`]: crate::Error::InvalidInput
318    /// [`Error::ConnectionLost`]: crate::Error::ConnectionLost
319    /// [`Error::InvalidFrame`]: crate::Error::InvalidFrame
320    /// [`Error::InvalidUtf8`]: crate::Error::InvalidUtf8
321    #[doc(alias = "NDIlib_recv_capture_v3")]
322    pub fn capture_any(&self, timeout: Duration) -> Result<Option<PacketItem>> {
323        Self::capture_from(&self.receiver, timeout)
324    }
325
326    /// Borrow the next packet or decoded frame without copying its payload or
327    /// metadata. The item keeps its native buffer until dropped, including
328    /// application memory charged to a custom allocator's limits.
329    ///
330    /// Timeout, event and reconnect semantics are those of [`Self::capture_any`].
331    /// Shared receiver controls remain available while an item is borrowed.
332    ///
333    /// # Errors
334    ///
335    /// As for [`Self::capture_any`], including [`crate::Error::UnexpectedSdkResult`]
336    /// once per failed status publication, whose event remains pending.
337    #[doc(alias = "NDIlib_recv_capture_v3")]
338    pub fn capture_any_ref(&self, timeout: Duration) -> Result<Option<PacketItemRef<'_>>> {
339        Self::capture_ref_from(&self.receiver, timeout)
340    }
341
342    pub(crate) fn capture_from(
343        receiver: &Receiver<PacketAttached>,
344        timeout: Duration,
345    ) -> Result<Option<PacketItem>> {
346        Ok(Self::capture_ref_from(receiver, timeout)?.map(|item| item.to_owned()))
347    }
348
349    pub(crate) fn capture_ref_from(
350        receiver: &Receiver<PacketAttached>,
351        timeout: Duration,
352    ) -> Result<Option<PacketItemRef<'_>>> {
353        receiver.capture_any_until_with::<AllSlots, _>(
354            Deadline::after(timeout)?,
355            crate::timeout::NeverStop,
356            PacketItemRef::Event,
357            Self::capture_result_ref,
358        )
359    }
360
361    fn capture_result_ref(media: Media<'_>) -> Result<PacketItemRef<'_>> {
362        match media {
363            Media::Video(frame) => video_ref_event(frame),
364            Media::Audio(frame) => audio_ref_event(frame),
365            Media::Metadata(frame) => metadata_ref_event(frame),
366        }
367    }
368
369    #[cfg(test)]
370    fn capture_result<'rx>(
371        receiver: &'rx Receiver<PacketAttached>,
372        delivered: crate::capture::Delivered<'rx, AllSlots>,
373    ) -> Result<Option<PacketItem>> {
374        Ok(receiver
375            .core
376            .capture_any_result_with(delivered, PacketItemRef::Event, Self::capture_result_ref)?
377            .map(|item| item.to_owned()))
378    }
379}
380
381/// The options a packet receiver is created from: `options` with the preset's
382/// native `color_format` in place of their own, and with video fields
383/// allowed, because a compressed stream cannot be deinterlaced.
384///
385/// The creation path checks these against the runtime, so it checks what the
386/// SDK is given: a color format the preset replaces is never required of the
387/// runtime.
388fn creation_options(
389    options: &ReceiverOptions,
390    color_format: NDIlib_recv_color_format_e,
391) -> ReceiverOptions {
392    options
393        .clone()
394        .with_passthrough(color_format)
395        .allow_video_fields(true)
396}
397
398fn video_ref_event(frame: Guard<'_, VideoKind>) -> Result<PacketItemRef<'_>> {
399    let video = if VideoCodec::from_outer(frame.frame().FourCC).is_some() {
400        ReceivedVideoRef::Compressed(CompressedRef::<VideoPacketFormat>::new(frame)?)
401    } else {
402        ReceivedVideoRef::Decoded(VideoKind::make_ref(frame)?)
403    };
404    Ok(PacketItemRef::Video(video))
405}
406
407fn audio_ref_event(frame: Guard<'_, AudioKind>) -> Result<PacketItemRef<'_>> {
408    let audio = if AudioCodec::from_outer(frame.frame().FourCC).is_some() {
409        ReceivedAudioRef::Compressed(CompressedRef::<AudioPacketFormat>::new(frame)?)
410    } else {
411        ReceivedAudioRef::Decoded(AudioKind::make_ref(frame)?)
412    };
413    Ok(PacketItemRef::Audio(audio))
414}
415
416fn metadata_ref_event(frame: Guard<'_, MetadataKind>) -> Result<PacketItemRef<'_>> {
417    Ok(PacketItemRef::Metadata(MetadataKind::make_ref(frame)?))
418}
419
420#[cfg(test)]
421fn video_event(frame: Guard<'_, VideoKind>) -> Result<PacketItem> {
422    video_ref_event(frame).map(|frame| frame.to_owned())
423}
424#[cfg(test)]
425fn audio_event(frame: Guard<'_, AudioKind>) -> Result<PacketItem> {
426    audio_ref_event(frame).map(|frame| frame.to_owned())
427}
428#[cfg(test)]
429fn metadata_event(frame: Guard<'_, MetadataKind>) -> Result<PacketItem> {
430    metadata_ref_event(frame).map(|frame| frame.to_owned())
431}
432
433#[cfg(test)]
434mod tests {
435    use std::{
436        os::raw::c_char,
437        ptr,
438        sync::atomic::{AtomicUsize, Ordering},
439    };
440
441    use super::*;
442    use crate::{
443        advanced::{EnvelopeCodec, PacketEnvelope, VideoPacketFormat},
444        capture::{Delivered, Notification},
445        frames::{AudioPartsExt, MetadataPartsExt, PixelFormat},
446        Error, Timecode,
447    };
448
449    #[test]
450    fn packet_notifications_use_the_shared_receiver_event_payloads() {
451        let Some(ndi) = crate::test_support::ndi() else {
452            return;
453        };
454        let receiver = Receiver::new(&ndi, &ReceiverOptions::disconnected())
455            .unwrap()
456            .into_packet_for_test();
457        let Some(PacketItem::Event(ReceiverEvent::StatusChanged(status))) =
458            PacketReceiver::capture_result(
459                &receiver,
460                Delivered::Notification(Notification::StatusChanged),
461            )
462            .unwrap()
463        else {
464            panic!("status changes include a receiver status snapshot");
465        };
466        assert_eq!(
467            status.connections(),
468            receiver.connection_stats().unwrap().connections()
469        );
470        for (notification, expected) in [
471            (Notification::SourceChanged, ReceiverEvent::SourceChanged),
472            (Notification::Unknown(987), ReceiverEvent::Unknown(987)),
473        ] {
474            let Some(PacketItem::Event(event)) =
475                PacketReceiver::capture_result(&receiver, Delivered::Notification(notification))
476                    .unwrap()
477            else {
478                panic!("expected receiver event {expected:?}");
479            };
480            assert_eq!(event, expected);
481        }
482        assert!(PacketReceiver::capture_result(
483            &receiver,
484            Delivered::Notification(Notification::None),
485        )
486        .unwrap()
487        .is_none());
488    }
489
490    unsafe fn count_release<T>(instance: NDIlib_recv_instance_t, _frame: &mut T) {
491        // SAFETY: `deliver` keeps the counter alive through every guard.
492        unsafe { &*instance.cast::<AtomicUsize>() }.fetch_add(1, Ordering::SeqCst);
493    }
494
495    /// Hand `raw` to `event` as a delivered frame of kind `K`, and count how
496    /// often the frame is released.
497    fn deliver<K: CaptureKind>(
498        raw: K::RawFrame,
499        event: fn(Guard<'_, K>) -> Result<PacketItem>,
500    ) -> (Result<PacketItem>, usize) {
501        let releases = AtomicUsize::new(0);
502        let instance = (&releases as *const AtomicUsize).cast_mut().cast();
503        // SAFETY: every caller's descriptor refers to buffers it keeps alive
504        // past this call, and the release only counts.
505        let frame = unsafe { Guard::<K>::with_test_free(instance, raw, count_release) };
506        let result = event(frame);
507        (result, releases.load(Ordering::SeqCst))
508    }
509
510    const NOT_UTF8: &[u8] = b"\xff\0";
511
512    #[test]
513    fn delivered_video_is_copied_and_freed_once_even_when_invalid() {
514        let mut source = VideoFrame::builder()
515            .resolution(4, 2)
516            .pixel_format(PixelFormat::Bgra)
517            .timecode(Timecode::from_ticks(17))
518            .metadata("<frame/>")
519            .build()
520            .unwrap();
521        for (index, byte) in source.data_mut().iter_mut().enumerate() {
522            *byte = index as u8;
523        }
524        let (event, releases) = deliver::<VideoKind>(source.as_test_raw(), video_event);
525        assert_eq!(releases, 1);
526        let PacketItem::Video(ReceivedVideo::Decoded(frame)) = event.unwrap() else {
527            panic!("an uncompressed frame is decoded");
528        };
529        assert_eq!(frame.data(), source.data());
530        assert_eq!((frame.width(), frame.height()), (4, 2));
531        assert_eq!(frame.pixel_format(), PixelFormat::Bgra);
532        assert_eq!(frame.timecode(), Timecode::from_ticks(17));
533        assert_eq!(frame.metadata(), Some("<frame/>"));
534
535        let no_pixels = NDIlib_video_frame_v2_t {
536            p_data: ptr::null_mut(),
537            ..source.as_test_raw()
538        };
539        let bad_metadata = NDIlib_video_frame_v2_t {
540            p_metadata: NOT_UTF8.as_ptr().cast(),
541            ..source.as_test_raw()
542        };
543        let (event, releases) = deliver::<VideoKind>(bad_metadata, video_event);
544        let PacketItem::Video(ReceivedVideo::Decoded(frame)) = event.unwrap() else {
545            panic!("valid media survives unreadable optional metadata");
546        };
547        assert_eq!(frame.data(), source.data());
548        assert_eq!(frame.metadata(), None);
549        assert_eq!(releases, 1);
550        let (event, releases) = deliver::<VideoKind>(no_pixels, video_event);
551        assert!(event.is_err());
552        assert_eq!(releases, 1);
553
554        let format = VideoPacketFormat::new(VideoCodec::H264, 16, 16).unwrap();
555        let packet =
556            PacketEnvelope::encode(EnvelopeCodec::H264, 10, 9, true, &[1, 2, 3], &[4, 5]).unwrap();
557        let mut sent = CompressedFrame::<VideoPacketFormat>::new(format, packet.clone()).unwrap();
558        let (event, releases) = deliver::<VideoKind>(sent.raw(), video_event);
559        assert_eq!(releases, 1);
560        let PacketItem::Video(ReceivedVideo::Compressed(copied)) = event.unwrap() else {
561            panic!("a codec packet is passed through");
562        };
563        assert_eq!(copied.data(), packet);
564        assert_eq!(copied.format().codec(), VideoCodec::H264);
565
566        let mut truncated = sent.raw();
567        truncated.__bindgen_anon_1.data_size_in_bytes = 0;
568        let (event, releases) = deliver::<VideoKind>(truncated, video_event);
569        assert!(event.is_err());
570        assert_eq!(releases, 1);
571    }
572
573    #[test]
574    fn delivered_audio_is_copied_and_freed_once_even_when_invalid() {
575        let mut source = AudioFrame::builder()
576            .sample_rate(48_000)
577            .num_channels(2)
578            .num_samples(4)
579            .timecode(Timecode::from_ticks(23))
580            .build()
581            .unwrap();
582        for (index, sample) in source.data_mut().iter_mut().enumerate() {
583            *sample = index as f32;
584        }
585        let (event, releases) = deliver::<AudioKind>(source.audio_descriptor(), audio_event);
586        assert_eq!(releases, 1);
587        let PacketItem::Audio(ReceivedAudio::Decoded(frame)) = event.unwrap() else {
588            panic!("uncompressed audio is decoded");
589        };
590        assert_eq!(frame.data(), source.data());
591        assert_eq!((frame.sample_rate(), frame.num_channels()), (48_000, 2));
592        assert_eq!(frame.timecode(), Timecode::from_ticks(23));
593
594        let no_samples = NDIlib_audio_frame_v3_t {
595            p_data: ptr::null_mut(),
596            ..source.audio_descriptor()
597        };
598        let bad_metadata = NDIlib_audio_frame_v3_t {
599            p_metadata: NOT_UTF8.as_ptr().cast(),
600            ..source.audio_descriptor()
601        };
602        let (event, releases) = deliver::<AudioKind>(bad_metadata, audio_event);
603        let PacketItem::Audio(ReceivedAudio::Decoded(frame)) = event.unwrap() else {
604            panic!("valid media survives unreadable optional metadata");
605        };
606        assert_eq!(frame.data(), source.data());
607        assert_eq!(frame.metadata(), None);
608        assert_eq!(releases, 1);
609        let (event, releases) = deliver::<AudioKind>(no_samples, audio_event);
610        assert!(event.is_err());
611        assert_eq!(releases, 1);
612
613        let mut sent = CompressedFrame::<AudioPacketFormat>::new(
614            crate::advanced::AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
615            vec![1; 8],
616        )
617        .unwrap();
618        let (event, releases) = deliver::<AudioKind>(sent.raw(), audio_event);
619        assert_eq!(releases, 1);
620        let PacketItem::Audio(ReceivedAudio::Compressed(copied)) = event.unwrap() else {
621            panic!("a codec packet is passed through");
622        };
623        assert_eq!(copied.data(), &[1; 8]);
624        assert_eq!(copied.format().codec(), AudioCodec::Opus);
625
626        let mut truncated = sent.raw();
627        truncated.__bindgen_anon_1.data_size_in_bytes = 0;
628        let (event, releases) = deliver::<AudioKind>(truncated, audio_event);
629        assert!(event.is_err());
630        assert_eq!(releases, 1);
631    }
632
633    #[test]
634    fn delivered_metadata_is_copied_and_freed_once_even_when_invalid() {
635        let source = MetadataFrame::new("<tally/>")
636            .unwrap()
637            .with_timecode(Timecode::from_ticks(31));
638        let (event, releases) = deliver::<MetadataKind>(source.metadata_raw(), metadata_event);
639        assert_eq!(releases, 1);
640        let PacketItem::Metadata(frame) = event.unwrap() else {
641            panic!("metadata is copied");
642        };
643        assert_eq!(
644            (frame.data(), frame.timecode()),
645            ("<tally/>", Timecode::from_ticks(31))
646        );
647
648        let bad_text = NDIlib_metadata_frame_t {
649            length: NOT_UTF8.len() as i32,
650            timecode: 0,
651            p_data: NOT_UTF8.as_ptr().cast::<c_char>().cast_mut(),
652        };
653        let (event, releases) = deliver::<MetadataKind>(bad_text, metadata_event);
654        assert!(matches!(event, Err(Error::InvalidUtf8(_))));
655        assert_eq!(releases, 1);
656    }
657
658    /// A packet receiver is created from the preset's color format, so that is
659    /// the one checked against the runtime: options asking for Best444, which
660    /// a 6.3.2 runtime is too old for, still make a packet receiver there.
661    #[test]
662    fn packet_receivers_validate_the_color_format_the_sdk_is_given() {
663        use crate::{
664            capabilities::{RuntimeFeature, SdkEdition, SdkVersion},
665            sys::{table::ExportsWhere, Resolved},
666            ReceiverColorFormat,
667        };
668
669        // An Advanced 6.3.2 runtime that exports every function the crate
670        // knows, gated as the loader gates the runtime it selects.
671        let exports = ExportsWhere(|_: &str| true);
672        let gates = Resolved::load(&exports)
673            .unwrap()
674            .seal(
675                SdkVersion::parse("NDI SDK TEST 6.3.2.0"),
676                SdkEdition::Advanced,
677            )
678            .1;
679        let runtime = gates.evidence();
680        let capabilities = gates.capabilities();
681        let too_old = |result: Result<crate::receiver::ValidatedReceiveOptions<'_>>,
682                       wanted: RuntimeFeature| {
683            assert!(
684                matches!(
685                    result,
686                    Err(Error::UnsupportedCapability {
687                        capability: crate::Capability::Runtime(feature),
688                        refusal: crate::CapabilityRefusal::RuntimeTooOld { .. },
689                        ..
690                    }) if feature == wanted
691                ),
692                "expected the version-gated receive option to be refused"
693            );
694        };
695
696        let best = ReceiverOptions::disconnected()
697            .color_format(ReceiverColorFormat::Best444)
698            .allow_video_fields(false);
699        // An ordinary receiver would be given Best444.
700        too_old(
701            best.validate_runtime(runtime),
702            RuntimeFeature::ReceiveBest444,
703        );
704
705        let mut checked = 0;
706        for preset in PassthroughPreset::ALL {
707            let Ok(color_format) = runtime.passthrough_format(preset) else {
708                // Only a preset this build's headers do not declare.
709                assert!(!capabilities.supports(RuntimeFeature::Passthrough(preset)));
710                continue;
711            };
712            let packets = creation_options(&best, color_format);
713            let settings = packets
714                .validate_runtime(runtime)
715                .unwrap()
716                .settings(None, None);
717            let settings = settings.raw();
718            assert_eq!(settings.color_format, color_format, "{preset:?}");
719            assert!(settings.allow_video_fields);
720
721            // What the SDK is given is still checked: video-only bandwidth
722            // needs NDI 6.4 too.
723            let video_only = best
724                .clone()
725                .bandwidth(crate::ReceiverBandwidth::VideoOnlyHighest);
726            too_old(
727                creation_options(&video_only, color_format).validate_runtime(runtime),
728                RuntimeFeature::ReceiveVideoOnly,
729            );
730            checked += 1;
731        }
732        let declared = PassthroughPreset::ALL
733            .into_iter()
734            .filter(|&preset| capabilities.supports(RuntimeFeature::Passthrough(preset)))
735            .count();
736        assert_eq!(checked, declared);
737    }
738
739    /// Both packet receivers move between and are shared across threads, and
740    /// stay unwind safe.
741    #[test]
742    fn packet_receivers_are_send_sync_and_unwind_safe() {
743        fn traits<T: Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
744        traits::<PacketReceiver>();
745        traits::<crate::advanced::AllocatedReceiver<PacketAttached>>();
746    }
747}
748
749#[cfg(test)]
750#[path = "receive/borrowed_tests.rs"]
751mod borrowed_tests;