Skip to main content

grafton_ndi/advanced/
send.rs

1//! Sending compressed frames, held in one buffer or in several.
2
3#[cfg(any(test, ndi_has_advanced_scatter_send))]
4use std::ptr;
5
6use super::{
7    aliasable::AliasableVec,
8    invalid_frame,
9    packets::{EnvelopeExtents, PacketBytes, PacketLen},
10    AudioPacketFormat, CompressedAttached, CompressedAudioSendMode, CompressedFrame, ScatterFrame,
11    VideoPacketFormat,
12};
13use crate::{
14    marker::NotSync,
15    sender::{
16        in_flight::{Destroyed, InFlight, Lend, Lending, Lent, LoanPair, Loans},
17        SendHandle,
18    },
19    sys::advanced::{native, ScatterSend},
20    Ndi, Rejected, Result, Sender, SenderOptions, StreamTier,
21};
22
23#[cfg(any(test, ndi_has_advanced_scatter_send))]
24use super::aliasable::AliasableBox;
25#[cfg(ndi_has_advanced_scatter_send)]
26use crate::sys::{advanced::FrameScatter, bindings::*};
27
28/// Maximum number of blocks in one scatter frame.
29pub const MAX_SCATTER_BLOCKS: usize = 65_536;
30
31#[cfg(all(test, ndi_has_advanced_scatter_send, ndi_has_advanced_send_completion))]
32#[path = "scatter_completion_tests.rs"]
33mod scatter_completion_tests;
34
35/// The blocks of one frame and the null-terminated arrays that describe them
36/// to the SDK.
37///
38/// The SDK writes to the blocks it sends, as it does to a contiguous frame,
39/// and keeps the addresses of the blocks and of both arrays while an
40/// asynchronous send is pending.
41pub(super) struct ScatterStorage {
42    first: AliasableVec<u8>,
43    rest: Box<[AliasableVec<u8>]>,
44    #[cfg(any(test, ndi_has_advanced_scatter_send))]
45    pointers: BlockPointers,
46    #[cfg(any(test, ndi_has_advanced_scatter_send))]
47    // Option preserves NonZeroU32's guaranteed niche layout: each positive
48    // PacketLen is its SDK int, and None is the terminating zero. The SDK
49    // reads this array; it writes only the packet blocks.
50    sizes: AliasableBox<[Option<PacketLen>]>,
51    total: PacketLen,
52}
53
54/// The exact blocks and extents established together by the shape check.
55pub(super) struct CheckedScatter<'a> {
56    pub(super) first: &'a mut Vec<u8>,
57    pub(super) rest: &'a mut [Vec<u8>],
58    pub(super) total: PacketLen,
59    #[cfg(any(test, ndi_has_advanced_scatter_send))]
60    sizes: Box<[Option<PacketLen>]>,
61}
62
63impl CheckedScatter<'_> {
64    /// Move the accepted blocks without copying their contents.
65    pub(super) fn into_storage(self) -> ScatterStorage {
66        ScatterStorage::new(
67            AliasableVec::new(std::mem::take(self.first)),
68            self.rest
69                .iter_mut()
70                .map(std::mem::take)
71                .map(AliasableVec::new)
72                .collect(),
73            self.total,
74            #[cfg(any(test, ndi_has_advanced_scatter_send))]
75            self.sizes,
76        )
77    }
78}
79
80/// A scatter frame always starts with one block followed by at most
81/// `MAX_SCATTER_BLOCKS - 1` more, so the combined iterator has an exact size.
82struct ScatterBlocks<'a> {
83    first: Option<&'a [u8]>,
84    rest: std::slice::Iter<'a, AliasableVec<u8>>,
85}
86
87impl<'a> Iterator for ScatterBlocks<'a> {
88    type Item = &'a [u8];
89
90    fn next(&mut self) -> Option<Self::Item> {
91        self.first
92            .take()
93            .or_else(|| self.rest.next().map(|block| &**block))
94    }
95
96    fn size_hint(&self) -> (usize, Option<usize>) {
97        let remaining = usize::from(self.first.is_some()) + self.rest.len();
98        (remaining, Some(remaining))
99    }
100}
101
102impl ExactSizeIterator for ScatterBlocks<'_> {}
103
104/// Addresses lent to the SDK, never dereferenced by Rust.
105#[cfg(any(test, ndi_has_advanced_scatter_send))]
106struct BlockPointers {
107    array: AliasableBox<[*const u8]>,
108    #[cfg(ndi_has_advanced_scatter_send)]
109    list: AliasableBox<FrameScatter>,
110}
111
112// SAFETY: moving these owners moves neither the list nor the array nor the
113// blocks they describe. Rust never dereferences their pointers;
114// ScatterStorage::descriptor lends them to the SDK
115// only under exclusive access, and the send slot owns the lent frame.
116#[cfg(any(test, ndi_has_advanced_scatter_send))]
117unsafe impl Send for BlockPointers {}
118// SAFETY: shared access only reads the pointer values. The SDK receives them
119// through ScatterStorage::descriptor(&mut self), whose exclusive loan lasts
120// until the slot has synchronized or the sender has been destroyed.
121#[cfg(any(test, ndi_has_advanced_scatter_send))]
122unsafe impl Sync for BlockPointers {}
123
124const_assert!({
125    assert!(size_of::<Option<PacketLen>>() == size_of::<i32>());
126    assert!(std::mem::align_of::<Option<PacketLen>>() == std::mem::align_of::<i32>());
127    const fn send_and_sync<T: Send + Sync>() {}
128    send_and_sync::<ScatterStorage>();
129});
130
131impl Clone for ScatterStorage {
132    /// Copies of the blocks, with arrays that describe the copies.
133    fn clone(&self) -> Self {
134        Self::new(
135            self.first.clone(),
136            self.rest.clone(),
137            self.total,
138            #[cfg(any(test, ndi_has_advanced_scatter_send))]
139            Box::from(&*self.sizes),
140        )
141    }
142}
143
144impl ScatterStorage {
145    pub(super) fn retained_bytes(&self) -> usize {
146        let block_headers = (self.rest.len() + 1) * size_of::<AliasableVec<u8>>();
147        let bytes = self.rest.iter().fold(
148            block_headers.saturating_add(self.first.capacity()),
149            |total, block| total.saturating_add(block.capacity()),
150        );
151        #[cfg(any(test, ndi_has_advanced_scatter_send))]
152        let bytes = bytes
153            .saturating_add(self.pointers.array.len() * size_of::<*const u8>())
154            .saturating_add(self.sizes.len() * size_of::<i32>());
155        #[cfg(ndi_has_advanced_scatter_send)]
156        let bytes = bytes.saturating_add(size_of::<FrameScatter>());
157        bytes
158    }
159
160    /// Check each block and the sum once, retaining every checked extent.
161    pub(super) fn check(blocks: &mut [Vec<u8>], header_bytes: usize) -> Result<CheckedScatter<'_>> {
162        let count = blocks.len();
163        let (first, rest) = blocks
164            .split_first_mut()
165            .filter(|_| count <= MAX_SCATTER_BLOCKS)
166            .ok_or_else(|| invalid_frame(crate::FrameDefect::ScatterBlockCount))?;
167        let checked = |block: &Vec<u8>| {
168            PacketLen::new(block.len()).ok_or_else(|| {
169                invalid_frame(if block.is_empty() {
170                    crate::FrameDefect::EmptyScatterBlock
171                } else {
172                    crate::FrameDefect::ScatterSize
173                })
174            })
175        };
176        let first_size = checked(first)?;
177        let mut total = first_size;
178        #[cfg(any(test, ndi_has_advanced_scatter_send))]
179        let mut sizes = Vec::with_capacity(count + 1);
180        #[cfg(any(test, ndi_has_advanced_scatter_send))]
181        sizes.push(Some(first_size));
182        for block in rest.iter() {
183            let size = checked(block)?;
184            total = total
185                .checked_add(size)
186                .ok_or_else(|| invalid_frame(crate::FrameDefect::ScatterSize))?;
187            #[cfg(any(test, ndi_has_advanced_scatter_send))]
188            sizes.push(Some(size));
189        }
190        if first.len() < header_bytes {
191            return Err(invalid_frame(crate::FrameDefect::ScatterHeader));
192        }
193        #[cfg(any(test, ndi_has_advanced_scatter_send))]
194        sizes.push(None);
195        Ok(CheckedScatter {
196            first,
197            rest,
198            total,
199            #[cfg(any(test, ndi_has_advanced_scatter_send))]
200            sizes: sizes.into_boxed_slice(),
201        })
202    }
203
204    /// Take ownership of exactly the blocks and extents admitted together.
205    fn new(
206        first: AliasableVec<u8>,
207        rest: Box<[AliasableVec<u8>]>,
208        total: PacketLen,
209        #[cfg(any(test, ndi_has_advanced_scatter_send))] sizes: Box<[Option<PacketLen>]>,
210    ) -> Self {
211        #[cfg(any(test, ndi_has_advanced_scatter_send))]
212        let (mut first, mut rest) = (first, rest);
213        // The SDK writes through these, whatever its declaration says.
214        #[cfg(any(test, ndi_has_advanced_scatter_send))]
215        let pointers = AliasableBox::new(
216            std::iter::once(&mut first)
217                .chain(rest.iter_mut())
218                .map(|block| block.as_mut_ptr().cast_const())
219                .chain(std::iter::once(ptr::null()))
220                .collect(),
221        );
222        #[cfg(any(test, ndi_has_advanced_scatter_send))]
223        let sizes = AliasableBox::new(sizes);
224        #[cfg(ndi_has_advanced_scatter_send)]
225        let list = AliasableBox::new(Box::new(FrameScatter {
226            p_data_blocks: pointers.as_ptr().cast(),
227            p_data_blocks_size: sizes.as_ptr().cast(),
228        }));
229        Self {
230            first,
231            rest,
232            #[cfg(any(test, ndi_has_advanced_scatter_send))]
233            pointers: BlockPointers {
234                array: pointers,
235                #[cfg(ndi_has_advanced_scatter_send)]
236                list,
237            },
238            #[cfg(any(test, ndi_has_advanced_scatter_send))]
239            sizes,
240            total,
241        }
242    }
243
244    /// The native description of the blocks, which lends them to the SDK.
245    /// The SDK may write to the blocks for as long as it holds the
246    /// description, so the caller keeps the storage exclusively for that long.
247    #[cfg(ndi_has_advanced_scatter_send)]
248    pub(super) fn descriptor(&mut self) -> *const FrameScatter {
249        self.pointers.list.as_ptr()
250    }
251
252    pub(super) fn total_bytes(&self) -> usize {
253        self.total.to_usize()
254    }
255
256    #[cfg(ndi_has_advanced_scatter_send)]
257    pub(super) fn lend_first_block(&mut self) -> (*mut u8, i32) {
258        // SAFETY: construction always supplies one positive size for the
259        // first block and the allocated, aligned array containing that size
260        // stays live. The SDK only reads this array, in the native i32 layout.
261        let size = unsafe { self.sizes.as_ptr().cast::<i32>().read() };
262        (self.first.as_mut_ptr(), size)
263    }
264
265    pub(super) fn blocks(&self) -> impl ExactSizeIterator<Item = &[u8]> {
266        ScatterBlocks {
267            first: Some(&self.first),
268            rest: self.rest.iter(),
269        }
270    }
271
272    pub(super) fn into_blocks(self) -> Vec<Vec<u8>> {
273        let mut blocks = Vec::with_capacity(self.rest.len() + 1);
274        blocks.push(self.first.into_vec());
275        blocks.extend(self.rest.into_vec().into_iter().map(AliasableVec::into_vec));
276        blocks
277    }
278
279    pub(super) fn copy_contiguous(&self, extents: Option<EnvelopeExtents>) -> PacketBytes {
280        PacketBytes::with_len(self.total, extents, |bytes| {
281            for block in self.blocks() {
282                bytes.extend_from_slice(block);
283            }
284        })
285    }
286}
287
288/// The `N` bytes at `offset` of a frame held in several blocks.
289pub(super) fn bytes_at<const N: usize>(
290    first: &[u8],
291    rest: &[Vec<u8>],
292    offset: usize,
293) -> Option<[u8; N]> {
294    let mut bytes = first
295        .iter()
296        .chain(rest.iter().flatten())
297        .skip(offset)
298        .copied();
299    let mut value = [0; N];
300    for byte in &mut value {
301        *byte = bytes.next()?;
302    }
303    Some(value)
304}
305
306/// A video frame that was submitted asynchronously and that the SDK has
307/// finished with.
308#[derive(Clone, Debug)]
309#[non_exhaustive]
310pub enum SubmittedVideo {
311    /// A frame submitted with [`CompressedSender::submit_video`].
312    Contiguous(CompressedFrame<VideoPacketFormat>),
313    /// A frame submitted with [`CompressedSender::submit_scatter_video`].
314    Scatter(ScatterFrame<VideoPacketFormat>),
315}
316
317impl SubmittedVideo {
318    /// The frame's format.
319    pub fn format(&self) -> VideoPacketFormat {
320        match self {
321            Self::Contiguous(frame) => frame.format(),
322            Self::Scatter(frame) => frame.format(),
323        }
324    }
325}
326
327/// Frames returned by [`CompressedSender::reclaim_video`] or [`CompressedSender::close`].
328///
329/// The SDK has finished accessing these frames, so their storage can be reused.
330/// Reclaiming them does not report whether they were delivered to a receiver.
331#[derive(Clone, Debug, Default)]
332pub struct ReclaimedVideo {
333    /// The last frame submitted asynchronously on the program stream.
334    pub program: Option<SubmittedVideo>,
335    /// The last frame submitted asynchronously on the preview stream.
336    pub preview: Option<SubmittedVideo>,
337}
338
339/// A scatter input together with the exact native capability that admits it.
340/// Its dispatch capability is uninhabited without scatter declarations, so
341/// successful construction also proves the native send methods are compiled.
342pub(crate) struct ScatterSendable<F, T = ScatterDispatch> {
343    frame: F,
344    table: T,
345}
346
347/// Admission's dispatch capability. Native calls also require a live sender
348/// handle, so retaining a frame needs no separate runtime lease.
349pub(crate) struct ScatterDispatch {
350    #[cfg(ndi_has_advanced_scatter_send)]
351    send: unsafe extern "C" fn(
352        NDIlib_send_instance_t,
353        *const NDIlib_video_frame_v2_t,
354        *const FrameScatter,
355    ),
356    #[cfg(not(ndi_has_advanced_scatter_send))]
357    unavailable: ScatterSend,
358}
359
360#[cfg(ndi_has_advanced_scatter_send)]
361const_assert!(size_of::<ScatterDispatch>() == size_of::<&ScatterSend>());
362
363impl ScatterDispatch {
364    #[cfg(ndi_has_advanced_scatter_send)]
365    fn of(table: &ScatterSend) -> Self {
366        Self {
367            send: table.NDIlib_send_send_video_scatter_async,
368        }
369    }
370}
371
372impl<F> ScatterSendable<F> {
373    fn with_table(
374        frame: F,
375        table: Result<&ScatterSend>,
376    ) -> std::result::Result<Self, (crate::Error, F)> {
377        match table {
378            Ok(table) => {
379                #[cfg(ndi_has_advanced_scatter_send)]
380                {
381                    Ok(Self {
382                        frame,
383                        table: ScatterDispatch::of(table),
384                    })
385                }
386                #[cfg(not(ndi_has_advanced_scatter_send))]
387                {
388                    let _ = frame;
389                    match *table {}
390                }
391            }
392            Err(error) => Err((error, frame)),
393        }
394    }
395
396    pub(super) fn checked(frame: F, ndi: &Ndi) -> std::result::Result<Self, (crate::Error, F)> {
397        Self::with_table(frame, ndi.table::<ScatterSend>())
398    }
399
400    pub(crate) fn new(frame: F, ndi: &Ndi) -> std::result::Result<Self, Rejected<F>> {
401        Self::checked(frame, ndi).map_err(|(error, frame)| Rejected::new(error, frame))
402    }
403
404    fn into_frame(self) -> F {
405        self.frame
406    }
407
408    #[cfg(test)]
409    pub(super) fn for_test(
410        frame: F,
411        table: Option<&ScatterSend>,
412    ) -> std::result::Result<Self, (crate::Error, F)> {
413        let table = table.ok_or(crate::Error::UnsupportedCapability {
414            capability: crate::Capability::Runtime(crate::RuntimeFeature::ScatterSend),
415            refusal: crate::CapabilityRefusal::SymbolUnavailable(c"NDIlib_send_send_video_scatter"),
416        });
417        Self::with_table(frame, table)
418    }
419}
420
421impl<'a, F> ScatterSendable<&'a mut F, &'a ScatterSend> {
422    pub(crate) fn borrowed(frame: &'a mut F, ndi: &'a Ndi) -> Result<Self> {
423        Ok(Self {
424            frame,
425            table: ndi.table::<ScatterSend>()?,
426        })
427    }
428}
429
430impl ScatterSendable<&mut ScatterFrame<VideoPacketFormat>, &ScatterSend> {
431    pub(crate) fn send_video(self, sender: SendHandle<'_>) {
432        native!(ScatterSend, self.table, uses(self, sender) => {
433            let (descriptor, scatter) = self.frame.lend_scatter();
434            // SAFETY: the caller's live sender borrows this frame exclusively
435            // through the synchronous call, including its stable scatter list.
436            unsafe { self.table.NDIlib_send_send_video_scatter(sender.instance(), &descriptor, scatter) };
437        })
438    }
439}
440
441impl ScatterSendable<&mut ScatterFrame<AudioPacketFormat>, &ScatterSend> {
442    fn send_audio(self, sender: SendHandle<'_>) {
443        native!(ScatterSend, self.table, uses(self, sender) => {
444            let (descriptor, scatter) = self.frame.lend_scatter();
445            // SAFETY: the caller retains its live sender and this exclusive
446            // frame borrow, including every block and list, until return.
447            unsafe { self.table.NDIlib_send_send_audio_scatter(sender.instance(), &descriptor, scatter) };
448        })
449    }
450}
451
452/// Call-scoped descriptors derived from an owned scatter proof. The owning
453/// frame retains every pointee until its stream's native loan has ended.
454#[cfg(ndi_has_advanced_scatter_send)]
455pub(crate) struct ScatterVideoLoan {
456    descriptor: NDIlib_video_frame_v2_t,
457    scatter: *const FrameScatter,
458    send: unsafe extern "C" fn(
459        NDIlib_send_instance_t,
460        *const NDIlib_video_frame_v2_t,
461        *const FrameScatter,
462    ),
463}
464
465impl ScatterSendable<ScatterFrame<VideoPacketFormat>> {
466    fn lend(&mut self) -> Lent {
467        #[cfg(ndi_has_advanced_scatter_send)]
468        {
469            let (descriptor, scatter) = self.frame.lend_scatter();
470            Lent::Scatter(ScatterVideoLoan {
471                descriptor,
472                scatter,
473                send: self.table.send,
474            })
475        }
476        #[cfg(not(ndi_has_advanced_scatter_send))]
477        {
478            match self.table.unavailable {}
479        }
480    }
481
482    #[cfg(ndi_has_advanced_scatter_send)]
483    pub(super) fn completion_key(&mut self) -> (*mut u8, i32) {
484        self.frame.lend_first_block()
485    }
486}
487
488#[cfg(ndi_has_advanced_scatter_send)]
489impl ScatterVideoLoan {
490    pub(crate) fn descriptor(&self) -> &NDIlib_video_frame_v2_t {
491        &self.descriptor
492    }
493
494    pub(crate) fn descriptor_mut(&mut self) -> &mut NDIlib_video_frame_v2_t {
495        &mut self.descriptor
496    }
497
498    /// # Safety
499    /// The live sender owns the native loan. The descriptor and all of this
500    /// proof's pointees remain initialized and retained through native release.
501    pub(crate) unsafe fn submit(
502        &self,
503        sender: crate::sender::SendHandle<'_>,
504        descriptor: *const NDIlib_video_frame_v2_t,
505    ) {
506        // SAFETY: the handle borrows the live native resource and its runtime;
507        // the caller supplies the complete native-loan lifetime contract.
508        unsafe { (self.send)(sender.instance(), descriptor, self.scatter) };
509    }
510}
511
512/// A frame the SDK may still be using, with what it accesses through the
513/// descriptor it was given.
514///
515/// `NDIlib_send_send_video_async_v2` (Processing.NDI.Send.h), whose rules the
516/// scatter variant (Processing.NDI.Advanced.h) follows, reads the video
517/// descriptor during the call: the SDK's own asynchronous sending example
518/// rewrites one descriptor while the previous frame is still in flight. What
519/// the descriptor points to must not be freed or reused until the next
520/// synchronizing event. For a contiguous frame that is its bytes and
521/// metadata. For a scatter frame it is also the scatter list, which no header
522/// says is copied: the `NDIlib_frame_scatter_t` and the pointer and size
523/// arrays it refers to.
524///
525/// The entry owns all of these, so nothing can read the frame's bytes while
526/// the SDK may still write to them.
527pub(crate) enum PendingVideo {
528    /// A frame submitted with [`CompressedSender::submit_video`].
529    Contiguous(CompressedFrame<VideoPacketFormat>),
530    /// A frame submitted with [`CompressedSender::submit_scatter_video`].
531    Scatter(ScatterSendable<ScatterFrame<VideoPacketFormat>>),
532}
533
534const_assert!({
535    const fn assert_send_sync<T: Send + Sync>() {}
536    assert_send_sync::<PendingVideo>();
537});
538
539impl PendingVideo {
540    /// The stream the frame is sent on.
541    pub(crate) fn tier(&self) -> StreamTier {
542        match self {
543            Self::Contiguous(frame) => frame.format().tier(),
544            Self::Scatter(proof) => proof.frame.format().tier(),
545        }
546    }
547
548    pub(crate) fn into_submitted(self) -> SubmittedVideo {
549        match self {
550            Self::Contiguous(frame) => SubmittedVideo::Contiguous(frame),
551            Self::Scatter(proof) => SubmittedVideo::Scatter(proof.into_frame()),
552        }
553    }
554}
555
556// SAFETY: Each variant owns the initialized payload and terminated metadata;
557// Scatter additionally owns its stable list's allocation with the frame's
558// pointer and size arrays. Moving PendingVideo
559// moves none of those allocations. InFlight prevents access until release.
560unsafe impl Lend for PendingVideo {
561    fn lend(&mut self) -> Lent {
562        match self {
563            Self::Contiguous(frame) => Lent::Frame(frame.raw()),
564            Self::Scatter(proof) => proof.lend(),
565        }
566    }
567}
568
569/// The frame most recently submitted asynchronously on each stream.
570///
571/// The loan kernel marks both slots released after synchronous video
572/// dispatch. Each frame remains in its own slot until that stream replaces it
573/// or the owner reclaims it. Sender destruction releases any outstanding loan.
574#[derive(Default)]
575pub(crate) struct PendingStreams {
576    program: InFlight<PendingVideo>,
577    preview: InFlight<PendingVideo>,
578}
579
580impl PendingStreams {
581    /// Recover only frames whose native loans have already ended.
582    pub(crate) fn take_retained(&mut self) -> ReclaimedVideo {
583        ReclaimedVideo {
584            program: self
585                .program
586                .take_retained()
587                .map(PendingVideo::into_submitted),
588            preview: self
589                .preview
590                .take_retained()
591                .map(PendingVideo::into_submitted),
592        }
593    }
594
595    /// Select the retained slot; only its owning protocol can synchronize it.
596    pub(crate) fn slot(&mut self, tier: StreamTier) -> &mut InFlight<PendingVideo> {
597        match tier {
598            StreamTier::Program => &mut self.program,
599            StreamTier::Preview => &mut self.preview,
600        }
601    }
602
603    /// Both streams' frames, once their native sender has been destroyed.
604    fn into_reclaimed(self, destroyed: &Destroyed) -> ReclaimedVideo {
605        let release = |slot: InFlight<PendingVideo>| {
606            slot.into_released(destroyed)
607                .map(PendingVideo::into_submitted)
608        };
609        ReclaimedVideo {
610            program: release(self.program),
611            preview: release(self.preview),
612        }
613    }
614}
615
616impl Loans for PendingStreams {
617    type Recovered = ReclaimedVideo;
618
619    fn recover(self, destroyed: &Destroyed) -> ReclaimedVideo {
620        self.into_reclaimed(destroyed)
621    }
622
623    fn release(self, destroyed: &Destroyed) {
624        drop(self.into_reclaimed(destroyed));
625    }
626}
627
628/// A sender of compressed video and audio.
629///
630/// Each stream keeps the frame of its last asynchronous send until the next
631/// asynchronous send on that stream returns it, or
632/// [`reclaim_video`](Self::reclaim_video) or [`close`](Self::close) reclaims it.
633/// The SDK has one asynchronous send outstanding per sender, so
634/// a send on either stream may wait for the SDK to finish with the other
635/// stream's frame. The crate still returns each frame through its own stream.
636/// Which streams a codec needs, and how they must relate, is defined by the
637/// NDI Advanced SDK documentation.
638///
639/// The native sender is owned exclusively by this value.
640/// [`sender`](Self::sender) lends it in the [`CompressedAttached`] mode, which
641/// has the operations every sender shares (the source, metadata in both
642/// directions, tally, connections, failover, and the Advanced encoder
643/// guidance, keyframe and tally controls) but none of the uncompressed sends,
644/// and which cannot be registered with a
645/// [`SendAdvertiser`](crate::discovery_server::SendAdvertiser).
646///
647/// # Threading
648///
649/// [`split`](Self::split) lends independent video and audio views to scoped
650/// threads without an external lock. The exclusive video view is `Send` but
651/// neither `Sync` nor `Clone`, so video submissions remain serialized. The
652/// shared `Send + Sync` sender supports compressed audio, metadata and controls
653/// while video is being submitted.
654///
655/// # Sending lends the frame
656///
657/// The SDK writes to the frames it sends: it stamps the reserved field of
658/// their packet envelope. A synchronous send therefore borrows its frame
659/// exclusively and an asynchronous one takes it, so no reference to a frame's
660/// bytes exists while the SDK may change them, and a frame can be sent again
661/// afterwards.
662/// [`reclaim_video`](Self::reclaim_video) waits for pending video
663/// and returns both streams' frames while keeping the source available.
664///
665/// ```compile_fail,E0502
666/// use grafton_ndi::advanced::{CompressedSender, CompressedFrame, VideoPacketFormat};
667///
668/// fn send(sender: &mut CompressedSender, frame: &mut CompressedFrame<VideoPacketFormat>) {
669///     let bytes = frame.data();
670///     let _ = sender.send_video(frame);
671///     // The SDK may have written to what `bytes` refers to.
672///     let _ = bytes.len();
673/// }
674/// ```
675///
676/// # What a receiver gets
677///
678/// The SDK reports nothing about a frame it does not deliver. The frames it
679/// would discard for what they are (see [`VideoCodec`](super::VideoCodec) and
680/// [`AudioCodec`](super::AudioCodec)) are refused when they are built or converted. Contiguous
681/// sends are infallible; scatter sends can fail only when scatter sending is
682/// unavailable.
683/// Every other frame is delivered, subject to two rules about the stream it
684/// belongs to:
685///
686/// * A program-tier frame reaches the receivers that asked for the
687///   full-quality stream, and a preview-tier frame those that asked for the
688///   low-bandwidth one. The SDK documentation asks a source to send both.
689/// * An H.264 or HEVC stream starts with a keyframe. Until a receiver has had
690///   one, the frames that depend on it are not delivered;
691///   [`keyframe_required`](Sender::keyframe_required) on
692///   [`sender`](Self::sender) says when a receiver is waiting.
693///
694/// # Examples
695///
696/// ```no_run
697/// use grafton_ndi::{
698///     advanced::{
699///         CompressedFrame, CompressedSender, EnvelopeCodec, PacketEnvelope, VideoCodec,
700///         VideoPacketFormat,
701///     },
702///     FrameRate, Ndi, SenderOptions,
703/// };
704///
705/// # fn encoded_access_unit() -> (Vec<u8>, Vec<u8>) { (vec![0], vec![0]) }
706/// # fn main() -> Result<(), grafton_ndi::Error> {
707/// let ndi = Ndi::new()?;
708/// let mut sender = CompressedSender::new(&ndi, &SenderOptions::new("Encoder"))?;
709/// let format = VideoPacketFormat::new(VideoCodec::H264, 1920, 1080)?
710///     .with_frame_rate(FrameRate::new(60, 1)?);
711///
712/// let (payload, parameter_sets) = encoded_access_unit();
713/// let packet =
714///     PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, true, &payload, &parameter_sets)?;
715/// let mut frame = CompressedFrame::<VideoPacketFormat>::new(format, packet)?;
716/// sender.send_video(&mut frame);
717/// # Ok(())
718/// # }
719/// ```
720pub struct CompressedSender {
721    lending: Lending<CompressedAttached, PendingStreams>,
722}
723
724impl CompressedSender {
725    /// Create a sender with the options' Advanced SDK
726    /// [configuration](SenderOptions::config), or the SDK's default one when
727    /// they carry none.
728    ///
729    /// # Errors
730    ///
731    /// As for [`Sender::new`], and
732    /// [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
733    /// without an Advanced runtime (or in a build without the Advanced SDK).
734    #[doc(alias = "NDIlib_send_create_v2")]
735    pub fn new(ndi: &Ndi, options: &SenderOptions) -> Result<Self> {
736        let pending = PendingStreams::default();
737        let sender = <Sender<CompressedAttached> as super::Configurable>::create_configured(
738            ndi,
739            options,
740            options.configured_config(),
741        )?;
742        Ok(Self {
743            lending: Lending::new(sender, pending),
744        })
745    }
746
747    /// The sender this value sends through, for compressed audio and the
748    /// operations that do not send video: [`source`](Sender::source),
749    /// [`send_compressed_audio`](Sender::send_compressed_audio),
750    /// [`send_scatter_audio`](Sender::send_scatter_audio),
751    /// [`send_metadata`](Sender::send_metadata) and
752    /// [`capture_metadata`](Sender::capture_metadata),
753    /// [`tally`](Sender::tally), [`connection_count`](Sender::connection_count),
754    /// connection metadata, failover, and the Advanced controls such as
755    /// [`keyframe_required`](Sender::keyframe_required) and
756    /// [`set_external_tally`](Sender::set_external_tally).
757    ///
758    /// Its mode has none of the uncompressed sends, and it cannot be
759    /// registered with an advertiser. Use [`split`](Self::split) to reach
760    /// these controls through the audio half while video is being sent.
761    pub fn sender(&self) -> &Sender<CompressedAttached> {
762        self.lending.sender()
763    }
764
765    /// Lend video and audio operations to separate scoped threads.
766    ///
767    /// Video keeps exclusive access to the pending streams and is `Send`
768    /// but neither `Sync` nor `Clone`. The shared sender supports compressed
769    /// audio, metadata and controls and is `Send + Sync`. Both halves borrow
770    /// this owner.
771    pub fn split(&mut self) -> (CompressedVideo<'_>, &Sender<CompressedAttached>) {
772        let pair = self.lending.parts();
773        let sender = pair.sender();
774        (
775            CompressedVideo {
776                pair,
777                _not_sync: NotSync::default(),
778            },
779            sender,
780        )
781    }
782
783    /// Send a video frame and return when the SDK has finished with it.
784    ///
785    /// The frame is borrowed exclusively because the SDK writes to its bytes.
786    #[doc(alias = "NDIlib_send_send_video_v2")]
787    pub fn send_video(&mut self, frame: &mut CompressedFrame<VideoPacketFormat>) {
788        self.split().0.send_video(frame)
789    }
790
791    /// Submit a video frame without waiting for it to be sent.
792    ///
793    /// The sender keeps the frame until the next asynchronous send on the same
794    /// stream, and returns the frame that this one replaces. The call can
795    /// still block: with [`SenderOptions::clock_video`] enabled, the default,
796    /// the SDK paces video inside the call. The first can return immediately;
797    /// subsequent calls wait for the next frame time. Set `clock_video(false)`
798    /// and pace sends in the application, or use [`super::Genlock`], to avoid
799    /// this frame-rate wait. SDK back-pressure can also block a call.
800    #[doc(alias = "NDIlib_send_send_video_async_v2")]
801    pub fn submit_video(
802        &mut self,
803        frame: CompressedFrame<VideoPacketFormat>,
804    ) -> Option<SubmittedVideo> {
805        self.split().0.submit_video(frame)
806    }
807
808    /// Drain asynchronous video and return both streams' final frames.
809    ///
810    /// If the SDK still owns a loan, one null asynchronous flush waits for
811    /// it without a timeout. A preceding synchronous video send already
812    /// ends both loans and needs no flush. The source stays available and
813    /// the next asynchronous send on either drained stream returns `None`.
814    /// Reclamation does not report whether receivers received the frames.
815    #[doc(alias = "NDIlib_send_send_video_async_v2")]
816    pub fn reclaim_video(&mut self) -> ReclaimedVideo {
817        self.split().0.reclaim_video()
818    }
819
820    /// Send a video frame held in several blocks and return when the SDK has
821    /// finished with it.
822    ///
823    /// The frame is borrowed exclusively because the SDK writes to its blocks.
824    ///
825    /// # Errors
826    ///
827    /// [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
828    /// when the runtime has no scatter sending.
829    #[doc(alias = "NDIlib_send_send_video_scatter")]
830    pub fn send_scatter_video(
831        &mut self,
832        frame: &mut ScatterFrame<VideoPacketFormat>,
833    ) -> Result<()> {
834        self.split().0.send_scatter_video(frame)
835    }
836
837    /// Submit a video frame held in several blocks without waiting for it to
838    /// be sent; see [`submit_video`](Self::submit_video).
839    ///
840    /// # Errors
841    ///
842    /// Returns the frame when the runtime has no scatter sending.
843    #[doc(alias = "NDIlib_send_send_video_scatter_async")]
844    pub fn submit_scatter_video(
845        &mut self,
846        frame: ScatterFrame<VideoPacketFormat>,
847    ) -> std::result::Result<Option<SubmittedVideo>, Rejected<ScatterFrame<VideoPacketFormat>>>
848    {
849        self.split().0.submit_scatter_video(frame)
850    }
851
852    /// Destroy the sender and take back the frames it still held.
853    ///
854    /// Destroying the native sender waits for the SDK to finish with every
855    /// pending frame, without a timeout.
856    #[doc(alias = "NDIlib_send_destroy")]
857    pub fn close(self) -> ReclaimedVideo {
858        self.lending.close()
859    }
860}
861
862/// Exclusive video operations borrowed from a [`CompressedSender`].
863///
864/// It is `Send`, but neither `Sync` nor `Clone`. Pending frames stay with the
865/// owner when the view is dropped; closing or dropping the owner drains them.
866pub struct CompressedVideo<'a> {
867    pair: LoanPair<'a, CompressedAttached, &'a mut PendingStreams>,
868    _not_sync: NotSync,
869}
870
871impl CompressedVideo<'_> {
872    /// See [`CompressedSender::send_video`].
873    #[doc(alias = "NDIlib_send_send_video_v2")]
874    pub fn send_video(&mut self, frame: &mut CompressedFrame<VideoPacketFormat>) {
875        self.pair.send_video(frame);
876    }
877
878    /// See [`CompressedSender::submit_video`].
879    #[doc(alias = "NDIlib_send_send_video_async_v2")]
880    pub fn submit_video(
881        &mut self,
882        frame: CompressedFrame<VideoPacketFormat>,
883    ) -> Option<SubmittedVideo> {
884        self.pair.submit_pending(frame)
885    }
886
887    /// See [`CompressedSender::reclaim_video`].
888    #[doc(alias = "NDIlib_send_send_video_async_v2")]
889    pub fn reclaim_video(&mut self) -> ReclaimedVideo {
890        self.pair.finish()
891    }
892
893    /// See [`CompressedSender::send_scatter_video`].
894    ///
895    /// # Errors
896    ///
897    /// As for [`CompressedSender::send_scatter_video`].
898    #[doc(alias = "NDIlib_send_send_video_scatter")]
899    pub fn send_scatter_video(
900        &mut self,
901        frame: &mut ScatterFrame<VideoPacketFormat>,
902    ) -> Result<()> {
903        self.pair.send_scatter_video(frame)
904    }
905
906    /// See [`CompressedSender::submit_scatter_video`].
907    ///
908    /// # Errors
909    ///
910    /// As for [`CompressedSender::submit_scatter_video`].
911    #[doc(alias = "NDIlib_send_send_video_scatter_async")]
912    pub fn submit_scatter_video(
913        &mut self,
914        frame: ScatterFrame<VideoPacketFormat>,
915    ) -> std::result::Result<Option<SubmittedVideo>, Rejected<ScatterFrame<VideoPacketFormat>>>
916    {
917        self.pair.submit_scatter(frame)
918    }
919}
920
921impl<M: CompressedAudioSendMode> Sender<M> {
922    /// Send a compressed audio frame synchronously, alongside the owner's
923    /// video. The frame is borrowed exclusively because the SDK writes to its
924    /// envelope. The compressed or queued mode proves runtime availability;
925    /// the frame's type proves send admission.
926    #[doc(alias = "NDIlib_send_send_audio_v3")]
927    pub fn send_compressed_audio(&self, frame: &mut CompressedFrame<AudioPacketFormat>) {
928        let descriptor = frame.raw();
929        let handle = self.handle();
930        // SAFETY: this live Advanced sender lends the exclusively borrowed
931        // frame for the whole synchronous call, after which the SDK releases it.
932        unsafe {
933            handle
934                .core()
935                .NDIlib_send_send_audio_v3(handle.instance(), &descriptor)
936        };
937    }
938
939    /// Send compressed audio held in separate blocks synchronously.
940    /// The frame remains exclusively borrowed through native release.
941    ///
942    /// # Errors
943    ///
944    /// [`crate::Error::UnsupportedCapability`] when scatter sending is
945    /// unavailable in the selected runtime or build headers.
946    #[doc(alias = "NDIlib_send_send_audio_scatter")]
947    pub fn send_scatter_audio(&self, frame: &mut ScatterFrame<AudioPacketFormat>) -> Result<()> {
948        ScatterSendable::borrowed(frame, self.runtime())?.send_audio(self.handle());
949        Ok(())
950    }
951}
952
953impl std::fmt::Debug for CompressedSender {
954    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
955        f.debug_struct("CompressedSender")
956            .field("sender", self.sender())
957            .finish_non_exhaustive()
958    }
959}
960
961impl std::fmt::Debug for CompressedVideo<'_> {
962    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
963        f.debug_struct("CompressedVideo")
964            .field("sender", self.pair.sender())
965            .finish_non_exhaustive()
966    }
967}
968
969#[cfg(test)]
970mod tests {
971    use super::*;
972    use crate::advanced::AudioCodec;
973    use crate::advanced::{
974        packets::testing::{aac_config, aac_packet},
975        EnvelopeCodec, PacketEnvelope, VideoCodec,
976    };
977    use crate::Timecode;
978
979    #[test]
980    fn split_audio_adds_no_allocation_to_a_send() {
981        let Some(ndi) = crate::test_support::advanced_ndi() else {
982            return;
983        };
984        let mut sender = CompressedSender::new(
985            &ndi,
986            &SenderOptions::new(crate::test_support::unique_name("split-audio-allocation"))
987                .clock_audio(false),
988        )
989        .unwrap();
990        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
991            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
992            vec![1; 64],
993        )
994        .unwrap();
995        let ((_video, audio), allocations) = crate::test_alloc::allocation_count(|| sender.split());
996        assert_eq!(allocations, 0);
997        let ((), allocations) =
998            crate::test_alloc::allocation_count(|| audio.send_compressed_audio(&mut frame));
999        assert_eq!(allocations, 0);
1000    }
1001
1002    #[test]
1003    fn queued_compressed_audio_send_adds_no_allocation() {
1004        let Some(ndi) = crate::test_support::advanced_ndi() else {
1005            return;
1006        };
1007        let queue = super::super::QueuedSender::new(
1008            &ndi,
1009            &SenderOptions::new(crate::test_support::unique_name("queued-compressed-audio"))
1010                .clock_audio(false),
1011            &super::super::QueueLimits::default(),
1012        )
1013        .unwrap();
1014        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
1015            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
1016            vec![1; 64],
1017        )
1018        .unwrap();
1019        let ((), allocations) = crate::test_alloc::allocation_count(|| {
1020            queue.sender().send_compressed_audio(&mut frame)
1021        });
1022        assert_eq!(allocations, 0);
1023    }
1024
1025    fn h264() -> (VideoPacketFormat, Vec<u8>) {
1026        (
1027            VideoPacketFormat::new(VideoCodec::H264, 16, 16).unwrap(),
1028            PacketEnvelope::encode(EnvelopeCodec::H264, 10, 9, true, &[1, 2, 3], &[4, 5]).unwrap(),
1029        )
1030    }
1031
1032    /// `bytes` cut into blocks at each of `cuts`.
1033    fn split(bytes: &[u8], cuts: &[usize]) -> Vec<Vec<u8>> {
1034        let mut blocks = Vec::new();
1035        let mut start = 0;
1036        for end in cuts.iter().copied().chain([bytes.len()]) {
1037            blocks.push(bytes[start..end].to_vec());
1038            start = end;
1039        }
1040        blocks
1041    }
1042
1043    fn scatter_audio(
1044        codec: AudioCodec,
1045        sample_rate: u32,
1046        channels: u32,
1047        samples: u32,
1048        blocks: Vec<Vec<u8>>,
1049    ) -> Result<ScatterFrame<AudioPacketFormat>> {
1050        ScatterFrame::<AudioPacketFormat>::new(
1051            AudioPacketFormat::new(codec, sample_rate, channels, samples)?,
1052            blocks,
1053        )
1054        .map_err(Rejected::into_error)
1055    }
1056
1057    #[test]
1058    fn a_scatter_check_retains_every_extent_and_the_terminator() {
1059        let mut blocks = vec![vec![1; 44], vec![2; 3], vec![3; 2]];
1060        let first_pointer = blocks[0].as_ptr();
1061        let checked = ScatterStorage::check(&mut blocks, 44).unwrap();
1062        assert_eq!(checked.total.to_usize(), 49);
1063        assert_eq!(
1064            checked
1065                .sizes
1066                .iter()
1067                .map(|size| size.map(PacketLen::to_usize))
1068                .collect::<Vec<_>>(),
1069            [Some(44), Some(3), Some(2), None]
1070        );
1071        assert_eq!(checked.first.len(), 44);
1072        assert_eq!(checked.first.as_ptr(), first_pointer);
1073        for (mut blocks, cause) in [
1074            (vec![], crate::FrameDefect::ScatterBlockCount),
1075            (vec![vec![]], crate::FrameDefect::EmptyScatterBlock),
1076            (vec![vec![1], vec![]], crate::FrameDefect::EmptyScatterBlock),
1077            (vec![vec![1], vec![2]], crate::FrameDefect::ScatterHeader),
1078        ] {
1079            assert!(
1080                matches!(ScatterStorage::check(&mut blocks, 44), Err(crate::Error::InvalidFrame(actual)) if actual == cause)
1081            );
1082        }
1083        let max = PacketLen::new(super::super::MAX_PACKET_BYTES).unwrap();
1084        assert_eq!(max.checked_add(PacketLen::new(1).unwrap()), None);
1085    }
1086
1087    #[test]
1088    #[cfg_attr(
1089        miri,
1090        ignore = "the full packet extent is checked by the native test run"
1091    )]
1092    fn a_scatter_check_refuses_an_oversized_sum() {
1093        let mut blocks = vec![vec![0; super::super::MAX_PACKET_BYTES], vec![1]];
1094        assert!(matches!(
1095            ScatterStorage::check(&mut blocks, 44),
1096            Err(crate::Error::InvalidFrame(crate::FrameDefect::ScatterSize))
1097        ));
1098    }
1099
1100    #[test]
1101    fn joining_three_blocks_keeps_video_and_audio_extents_paired() {
1102        let (format, bytes) = h264();
1103        let mut video = ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44, 47]))
1104            .unwrap()
1105            .into_contiguous_copy();
1106        let raw = video.raw();
1107        // SAFETY: compressed descriptors use the data-size member of the union.
1108        assert_eq!(
1109            unsafe { raw.__bindgen_anon_1.data_size_in_bytes } as usize,
1110            video.data().len()
1111        );
1112        assert_eq!(video.data(), bytes);
1113        assert!(PacketEnvelope::parse(video.data()).is_ok());
1114
1115        let bytes = aac_packet(48_000, 2, &[1; 8]);
1116        let mut audio = scatter_audio(AudioCodec::Aac, 48_000, 2, 1024, split(&bytes, &[44, 46]))
1117            .unwrap()
1118            .into_contiguous_copy();
1119        let raw = audio.raw();
1120        // SAFETY: as for the video descriptor.
1121        assert_eq!(
1122            unsafe { raw.__bindgen_anon_1.data_size_in_bytes } as usize,
1123            audio.data().len()
1124        );
1125        assert_eq!(audio.data(), bytes);
1126        assert!(PacketEnvelope::parse(audio.data()).is_ok());
1127    }
1128
1129    #[test]
1130    fn validates_complete_first_header_and_segmented_total() {
1131        let (format, bytes) = h264();
1132        assert!(ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[43])).is_err());
1133        assert!(ScatterFrame::<VideoPacketFormat>::new(
1134            format,
1135            vec![bytes[..44].to_vec(), bytes[44..48].to_vec()]
1136        )
1137        .is_err());
1138        assert!(
1139            ScatterFrame::<VideoPacketFormat>::new(format, vec![bytes.clone(), vec![0]]).is_err()
1140        );
1141        assert!(
1142            ScatterFrame::<VideoPacketFormat>::new(format, vec![bytes.clone(), vec![]]).is_err()
1143        );
1144        let frame =
1145            ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44, 47])).unwrap();
1146        assert_eq!(frame.total_bytes(), bytes.len());
1147        assert_eq!(frame.storage_for_test().pointers.array.len(), 4);
1148        assert!(frame.storage_for_test().pointers.array[3].is_null());
1149        // SAFETY: the transparent NonZeroU32 niche and the layout assertions
1150        // guarantee the SDK's int representation, including the zero terminator.
1151        // The frame retains this initialized array through the borrowed read.
1152        let sdk_sizes = unsafe {
1153            std::slice::from_raw_parts(
1154                frame.storage_for_test().sizes.as_ptr().cast::<i32>(),
1155                frame.storage_for_test().sizes.len(),
1156            )
1157        };
1158        assert_eq!(sdk_sizes, &[44, 3, 2, 0]);
1159        let moved = Box::new(frame);
1160        for (block, pointer) in moved
1161            .storage_for_test()
1162            .blocks()
1163            .zip(moved.storage_for_test().pointers.array.iter())
1164        {
1165            assert_eq!(block.as_ptr().cast::<u8>(), *pointer);
1166        }
1167        assert_eq!(moved.into_contiguous_copy().data(), bytes);
1168        fn send_sync<T: Send + Sync>() {}
1169        send_sync::<ScatterFrame<VideoPacketFormat>>();
1170        send_sync::<ScatterFrame<AudioPacketFormat>>();
1171        send_sync::<CompressedFrame<VideoPacketFormat>>();
1172        send_sync::<CompressedFrame<AudioPacketFormat>>();
1173        // With and without the Advanced headers alike.
1174        send_sync::<CompressedSender>();
1175    }
1176
1177    #[test]
1178    fn scatter_video_is_admitted_on_the_same_terms_as_contiguous_video() {
1179        let reason = |result: std::result::Result<
1180            ScatterFrame<VideoPacketFormat>,
1181            Rejected<Vec<Vec<u8>>>,
1182        >| match result.map_err(Rejected::into_error) {
1183            Err(crate::Error::InvalidFrame(reason)) => reason,
1184            other => panic!("expected an invalid frame, got {other:?}"),
1185        };
1186        let speedhq = VideoPacketFormat::new(VideoCodec::SpeedHq422, 1920, 1080).unwrap();
1187        ScatterFrame::<VideoPacketFormat>::new(speedhq, vec![vec![99, 0, 0, 0], vec![1; 8]])
1188            .unwrap();
1189        let refused =
1190            ScatterFrame::<VideoPacketFormat>::new(speedhq, vec![vec![100, 0, 0, 0], vec![1; 8]]);
1191        assert!(matches!(
1192            reason(refused),
1193            crate::FrameDefect::SpeedHqQuality
1194        ));
1195        let refused =
1196            ScatterFrame::<VideoPacketFormat>::new(speedhq, vec![vec![0, 0, 0], vec![1; 8]]);
1197        assert!(matches!(reason(refused), crate::FrameDefect::ScatterHeader));
1198
1199        let (format, bytes) = h264();
1200        let preview = |width, height| {
1201            let format = VideoPacketFormat::new(VideoCodec::H264, width, height)
1202                .unwrap()
1203                .with_tier(StreamTier::Preview);
1204            ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44]))
1205        };
1206        preview(640, 640).unwrap();
1207        assert!(matches!(
1208            reason(preview(641, 360)),
1209            crate::FrameDefect::PreviewVideoDimensions
1210        ));
1211        assert!(matches!(
1212            reason(preview(640, 641)),
1213            crate::FrameDefect::PreviewVideoDimensions
1214        ));
1215        assert!(matches!(
1216            reason(ScatterFrame::<VideoPacketFormat>::new(
1217                format,
1218                split(&bytes, &[43])
1219            )),
1220            crate::FrameDefect::ScatterHeader
1221        ));
1222
1223        // A keyframe needs its parameter sets here too.
1224        let bare =
1225            PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, true, &[1, 2, 3], &[]).unwrap();
1226        let refused = ScatterFrame::<VideoPacketFormat>::new(format, split(&bare, &[44]));
1227        assert!(matches!(
1228            reason(refused),
1229            crate::FrameDefect::KeyframeConfigurationMissing
1230        ));
1231    }
1232
1233    #[test]
1234    fn rejected_blocks_are_returned_in_order() {
1235        let (format, bytes) = h264();
1236        let blocks = split(&bytes, &[43]);
1237        let rejected = ScatterFrame::<VideoPacketFormat>::new(format, blocks.clone()).unwrap_err();
1238        assert_eq!(rejected.into_inner(), blocks);
1239
1240        let rejected = ScatterFrame::<AudioPacketFormat>::new(
1241            AudioPacketFormat::new(AudioCodec::Opus, 44_100, 2, 960).unwrap(),
1242            vec![vec![1], vec![2]],
1243        )
1244        .unwrap_err();
1245        assert_eq!(rejected.into_inner(), [[1], [2]]);
1246    }
1247
1248    /// A clone owns copies of the blocks, and its arrays describe the copies.
1249    #[test]
1250    fn a_cloned_scatter_frame_describes_its_own_blocks() {
1251        let (format, bytes) = h264();
1252        let mut frame =
1253            ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44, 47])).unwrap();
1254        frame.set_timecode(Timecode::from_ticks(3));
1255        frame.set_metadata("<scatter/>").unwrap();
1256        let copy = frame.clone();
1257        assert_eq!(
1258            (copy.timecode(), copy.metadata()),
1259            (Timecode::from_ticks(3), Some("<scatter/>"))
1260        );
1261        let blocks = copy
1262            .storage_for_test()
1263            .blocks()
1264            .zip(copy.storage_for_test().pointers.array.iter());
1265        for ((block, pointer), original) in blocks.zip(frame.storage_for_test().blocks()) {
1266            assert_eq!(block.as_ptr().cast::<u8>(), *pointer);
1267            assert_ne!(block.as_ptr(), original.as_ptr());
1268            assert_eq!(block, original);
1269        }
1270        assert_eq!(
1271            &*copy.storage_for_test().sizes,
1272            &*frame.storage_for_test().sizes
1273        );
1274        assert!(copy.storage_for_test().pointers.array[3].is_null());
1275        #[cfg(ndi_has_advanced_scatter_send)]
1276        {
1277            assert_ne!(
1278                copy.storage_for_test().pointers.list.as_ptr(),
1279                frame.storage_for_test().pointers.list.as_ptr()
1280            );
1281            let list = &*copy.storage_for_test().pointers.list;
1282            assert_eq!(
1283                list.p_data_blocks.cast::<*const u8>(),
1284                copy.storage_for_test()
1285                    .pointers
1286                    .array
1287                    .as_ptr()
1288                    .cast::<*const u8>()
1289            );
1290            assert_eq!(
1291                list.p_data_blocks_size.cast::<i32>(),
1292                copy.storage_for_test().sizes.as_ptr().cast::<i32>()
1293            );
1294        }
1295
1296        let audio = ScatterFrame::new(
1297            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960)
1298                .unwrap()
1299                .with_protected(true),
1300            vec![vec![1], vec![2]],
1301        )
1302        .unwrap();
1303        let copy = audio.clone();
1304        assert!(copy.format().is_protected());
1305        assert_eq!(
1306            (
1307                copy.format().sample_rate(),
1308                copy.format().num_channels(),
1309                copy.format().num_samples()
1310            ),
1311            (48_000, 2, 960)
1312        );
1313        assert_eq!(copy.into_contiguous_copy().data(), &[1, 2]);
1314    }
1315
1316    /// The SDK stamps the reserved field of the envelope in the first block
1317    /// through the pointer the block array gives it, after the frame has
1318    /// moved to wherever the pending send keeps it.
1319    #[test]
1320    fn a_scatter_frame_the_sdk_has_written_to_is_read_back_and_sendable() {
1321        let (format, bytes) = h264();
1322        let frame = ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44])).unwrap();
1323        let first = frame.storage_for_test().pointers.array[0].cast_mut();
1324        let moved = Box::new(frame);
1325        // SAFETY: the pointer was created to be written through, the block
1326        // holds a complete header, and no reference to it exists.
1327        unsafe { first.add(24).cast::<u64>().write_unaligned(7) };
1328        let stamped = moved.blocks().next().unwrap().to_vec();
1329        assert_eq!(stamped[24..32], 7u64.to_ne_bytes());
1330        assert_eq!(stamped[..24], bytes[..24]);
1331
1332        let joined = moved.into_contiguous_copy();
1333        super::super::ReceivedPacket::<super::super::VideoPacketFormat>::from(joined.clone())
1334            .validate_for_send()
1335            .unwrap();
1336        assert_eq!(joined.data()[24..32], 7u64.to_ne_bytes());
1337    }
1338
1339    #[test]
1340    fn scatter_audio_is_admitted_on_the_same_terms_as_contiguous_audio() {
1341        let packet = aac_packet(48_000, 2, &[1, 2]);
1342        let config_at = packet.len() - 2;
1343        // The configuration may lie in any block, or across two.
1344        for cuts in [
1345            &[][..],
1346            &[44][..],
1347            &[44, config_at][..],
1348            &[44, config_at + 1][..],
1349        ] {
1350            let aac = scatter_audio(AudioCodec::Aac, 48_000, 2, 1024, split(&packet, cuts))
1351                .unwrap()
1352                .into_contiguous_copy();
1353            assert_eq!(aac.data(), packet);
1354            super::super::ReceivedPacket::<super::super::AudioPacketFormat>::from(aac.clone())
1355                .validate_for_send()
1356                .unwrap();
1357        }
1358
1359        let reason = |result: Result<ScatterFrame<AudioPacketFormat>>| match result {
1360            Err(crate::Error::InvalidFrame(reason)) => reason,
1361            other => panic!("expected an invalid frame, got {other:?}"),
1362        };
1363        let aac = |sample_rate, channels, samples, packet: &[u8]| {
1364            reason(scatter_audio(
1365                AudioCodec::Aac,
1366                sample_rate,
1367                channels,
1368                samples,
1369                split(packet, &[44, config_at + 1]),
1370            ))
1371        };
1372        assert!(matches!(
1373            aac(48_000, 2, 960, &packet),
1374            crate::FrameDefect::AacSampleCount
1375        ));
1376        assert!(matches!(
1377            aac(44_100, 2, 1024, &packet),
1378            crate::FrameDefect::AacRateMismatch
1379        ));
1380        assert!(matches!(
1381            aac(48_000, 1, 1024, &packet),
1382            crate::FrameDefect::AacChannelsMismatch
1383        ));
1384
1385        let mut unflagged = packet.clone();
1386        unflagged[32..36].copy_from_slice(&0u32.to_ne_bytes());
1387        assert!(matches!(
1388            aac(48_000, 2, 1024, &unflagged),
1389            crate::FrameDefect::AacKeyframeMissing
1390        ));
1391
1392        let config = aac_config(48_000, 2);
1393        for config in [&[][..], &config[..1]] {
1394            let bare =
1395                PacketEnvelope::encode(EnvelopeCodec::Aac, 0, 0, true, &[1, 2], config).unwrap();
1396            let result = scatter_audio(AudioCodec::Aac, 48_000, 2, 1024, split(&bare, &[44]));
1397            assert!(matches!(
1398                reason(result),
1399                crate::FrameDefect::AacConfigurationMissing
1400            ));
1401        }
1402
1403        let opus = |sample_rate, samples| {
1404            scatter_audio(
1405                AudioCodec::Opus,
1406                sample_rate,
1407                2,
1408                samples,
1409                vec![vec![1], vec![2]],
1410            )
1411        };
1412        let frame = opus(48_000, 960).unwrap().into_contiguous_copy();
1413        assert_eq!(frame.data(), &[1, 2]);
1414        super::super::ReceivedPacket::<super::super::AudioPacketFormat>::from(frame.clone())
1415            .validate_for_send()
1416            .unwrap();
1417        assert!(matches!(
1418            reason(opus(44_100, 882)),
1419            crate::FrameDefect::OpusSampleRate
1420        ));
1421        assert!(matches!(
1422            reason(opus(48_000, 1440)),
1423            crate::FrameDefect::OpusDuration
1424        ));
1425        assert!(matches!(
1426            opus(0, 960),
1427            Err(crate::Error::InvalidInput(crate::InputDefect::Layout(
1428                crate::LayoutDefect::AudioRate(_)
1429            )))
1430        ));
1431    }
1432
1433    #[test]
1434    fn bytes_are_found_wherever_the_blocks_put_them() {
1435        let blocks = [vec![0, 1], vec![2], vec![3, 4, 5]];
1436        let (first, rest) = blocks.split_first().unwrap();
1437        assert_eq!(bytes_at(first, rest, 0), Some([0, 1]));
1438        assert_eq!(bytes_at(first, rest, 1), Some([1, 2, 3]));
1439        assert_eq!(bytes_at(first, rest, 4), Some([4, 5]));
1440        assert_eq!(bytes_at::<2>(first, rest, 5), None);
1441        assert_eq!(bytes_at::<1>(first, rest, 6), None);
1442    }
1443
1444    #[test]
1445    fn refused_scatter_proofs_return_every_original_block() {
1446        let (format, bytes) = h264();
1447        let video = ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44])).unwrap();
1448        let video_blocks: Vec<_> = video
1449            .blocks()
1450            .map(|block| (block.as_ptr(), block.len()))
1451            .collect();
1452        let (error, video) = ScatterSendable::for_test(video, None).err().unwrap();
1453        assert!(matches!(
1454            error,
1455            crate::Error::UnsupportedCapability {
1456                capability: crate::Capability::Runtime(crate::RuntimeFeature::ScatterSend),
1457                ..
1458            }
1459        ));
1460        assert_eq!(
1461            video
1462                .blocks()
1463                .map(|block| (block.as_ptr(), block.len()))
1464                .collect::<Vec<_>>(),
1465            video_blocks
1466        );
1467
1468        let audio = ScatterFrame::<AudioPacketFormat>::new(
1469            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
1470            vec![vec![1, 2], vec![3, 4]],
1471        )
1472        .unwrap();
1473        let audio_blocks: Vec<_> = audio
1474            .blocks()
1475            .map(|block| (block.as_ptr(), block.len()))
1476            .collect();
1477        let audio = ScatterSendable::for_test(audio, None).err().unwrap().1;
1478        assert_eq!(
1479            audio
1480                .blocks()
1481                .map(|block| (block.as_ptr(), block.len()))
1482                .collect::<Vec<_>>(),
1483            audio_blocks
1484        );
1485    }
1486
1487    #[test]
1488    fn missing_scatter_capability_preserves_owned_and_borrowed_inputs() {
1489        let Some(ndi) = crate::test_support::ndi() else {
1490            return;
1491        };
1492        if ndi.table::<ScatterSend>().is_ok() {
1493            return;
1494        }
1495        let (format, bytes) = h264();
1496        let mut video =
1497            ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44])).unwrap();
1498        let pointers: Vec<_> = video.blocks().map(|block| block.as_ptr()).collect();
1499        let (result, allocations) =
1500            crate::test_alloc::allocation_count(|| ScatterSendable::borrowed(&mut video, &ndi));
1501        assert!(matches!(
1502            result,
1503            Err(crate::Error::UnsupportedCapability { .. })
1504        ));
1505        assert_eq!(allocations, 0, "borrowed refusal does not box its input");
1506        let rejected = ScatterSendable::new(video, &ndi).err().unwrap();
1507        assert!(matches!(
1508            rejected.error(),
1509            crate::Error::UnsupportedCapability { .. }
1510        ));
1511        let video = rejected.into_inner();
1512        assert_eq!(
1513            video
1514                .blocks()
1515                .map(|block| block.as_ptr())
1516                .collect::<Vec<_>>(),
1517            pointers
1518        );
1519
1520        let mut audio = ScatterFrame::<AudioPacketFormat>::new(
1521            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
1522            vec![vec![1, 2], vec![3, 4]],
1523        )
1524        .unwrap();
1525        assert!(matches!(
1526            ScatterSendable::borrowed(&mut audio, &ndi),
1527            Err(crate::Error::UnsupportedCapability { .. })
1528        ));
1529        assert_eq!(
1530            audio.blocks().collect::<Vec<_>>(),
1531            [&[1, 2][..], &[3, 4][..]]
1532        );
1533    }
1534
1535    /// The SDK reads an asynchronous send's video descriptor during the call,
1536    /// so a submission lends what the descriptor points to and not the
1537    /// descriptor: the frame, and for a scatter frame its scatter list, all of
1538    /// which the pending entry owns.
1539    #[test]
1540    fn async_submission_lends_what_the_pending_entry_owns() {
1541        let (format, bytes) = h264();
1542        let frame = CompressedFrame::<VideoPacketFormat>::new(format, bytes.clone()).unwrap();
1543        let data = frame.data().as_ptr();
1544        let mut pending = PendingVideo::Contiguous(frame);
1545        let (lent, allocations) = crate::test_alloc::allocation_count(|| pending.lend());
1546        assert_eq!(allocations, 0);
1547        #[cfg(not(ndi_has_advanced_scatter_send))]
1548        let Lent::Frame(descriptor) = lent;
1549        #[cfg(ndi_has_advanced_scatter_send)]
1550        let Lent::Frame(descriptor) = lent
1551        else {
1552            panic!("a contiguous frame is lent through one descriptor");
1553        };
1554        assert_eq!(descriptor.p_data.cast_const(), data);
1555    }
1556
1557    #[test]
1558    #[cfg(ndi_has_advanced_scatter_send)]
1559    fn async_scatter_submission_lends_what_the_pending_entry_owns() {
1560        let (format, bytes) = h264();
1561        let Some(ndi) = crate::test_support::advanced_ndi() else {
1562            return;
1563        };
1564        let table = ndi.table::<ScatterSend>().unwrap();
1565        let frame = ScatterFrame::<VideoPacketFormat>::new(format, split(&bytes, &[44])).unwrap();
1566        let pointers = frame
1567            .storage_for_test()
1568            .pointers
1569            .array
1570            .as_ptr()
1571            .cast::<*const u8>();
1572        let sizes = frame.storage_for_test().sizes.as_ptr().cast::<i32>();
1573        let (mut pending, allocations) = crate::test_alloc::allocation_count(|| {
1574            PendingVideo::Scatter(ScatterSendable::for_test(frame, Some(table)).unwrap())
1575        });
1576        assert_eq!(allocations, 0, "the list already belongs to the frame");
1577        let Lent::Scatter(lent) = pending.lend() else {
1578            panic!("a scatter frame is lent with its scatter list");
1579        };
1580        let scatter = lent.scatter;
1581        // Moving the entry, as its stream's slot does, leaves the list where
1582        // the SDK was told it is, still naming the frame's arrays.
1583        let mut moved = Box::new(pending);
1584        let Lent::Scatter(lent) = moved.lend() else {
1585            panic!("a scatter frame is lent with its scatter list");
1586        };
1587        assert_eq!(lent.scatter, scatter);
1588        native!(ScatterSend, table => {
1589            // SAFETY: the moved entry owns the list.
1590            let list = unsafe { &*scatter };
1591            assert_eq!(list.p_data_blocks.cast::<*const u8>(), pointers);
1592            assert_eq!(list.p_data_blocks_size.cast::<i32>(), sizes);
1593        });
1594    }
1595
1596    #[cfg(ndi_has_advanced_scatter_send)]
1597    #[test]
1598    fn compressed_scatter_streams_lend_frame_owned_lists_without_allocating() {
1599        let Some(ndi) = crate::test_support::advanced_ndi() else {
1600            return;
1601        };
1602        let (format, bytes) = h264();
1603        let make = |tier| {
1604            ScatterFrame::<VideoPacketFormat>::new(format.with_tier(tier), split(&bytes, &[44]))
1605                .unwrap()
1606        };
1607        let mut sender = CompressedSender::new(
1608            &ndi,
1609            &SenderOptions::new(crate::test_support::unique_name("scatter-double-buffer"))
1610                .clock_video(false),
1611        )
1612        .unwrap();
1613        let list = |stream: &InFlight<PendingVideo>| match stream.frame().unwrap() {
1614            PendingVideo::Scatter(proof) => proof.frame.storage_for_test().pointers.list.as_ptr(),
1615            _ => panic!("scatter stream"),
1616        };
1617        let mut first = make(StreamTier::Program);
1618        let original = first.blocks().next().unwrap().as_ptr();
1619        let original_list = first.lend_scatter().1;
1620        sender.send_scatter_video(&mut first).unwrap();
1621        assert_eq!(first.lend_scatter().1, original_list);
1622        sender.submit_scatter_video(first).unwrap();
1623        let program = list(&sender.lending.loans().program);
1624        assert_eq!(program, original_list);
1625        sender
1626            .submit_scatter_video(make(StreamTier::Preview))
1627            .unwrap();
1628        let preview = list(&sender.lending.loans().preview);
1629        assert_ne!(program, preview);
1630        let replacement = make(StreamTier::Program);
1631        let (returned, allocations) =
1632            crate::test_alloc::allocation_count(|| sender.submit_scatter_video(replacement));
1633        assert_eq!(allocations, 0);
1634        let SubmittedVideo::Scatter(returned_program) = returned.unwrap().unwrap() else {
1635            panic!("scatter")
1636        };
1637        assert_eq!(returned_program.blocks().next().unwrap().as_ptr(), original);
1638        let next_program = list(&sender.lending.loans().program);
1639        assert_ne!(next_program, program);
1640        assert_ne!(next_program, preview);
1641        assert_eq!(list(&sender.lending.loans().preview), preview);
1642        let replacement = make(StreamTier::Preview);
1643        let (returned, allocations) =
1644            crate::test_alloc::allocation_count(|| sender.submit_scatter_video(replacement));
1645        let SubmittedVideo::Scatter(returned_preview) = returned.unwrap().unwrap() else {
1646            panic!("scatter")
1647        };
1648        assert_eq!(allocations, 0);
1649        let next_preview = list(&sender.lending.loans().preview);
1650        assert_ne!(next_preview, preview);
1651        assert_ne!(next_preview, next_program);
1652        sender.submit_scatter_video(returned_program).unwrap();
1653        assert_eq!(list(&sender.lending.loans().program), program);
1654        assert_eq!(list(&sender.lending.loans().preview), next_preview);
1655        // The recovered frame keeps its original list even across a
1656        // contiguous replacement and a later asynchronous submission.
1657        sender
1658            .submit_video(
1659                CompressedFrame::<VideoPacketFormat>::new(
1660                    format.with_tier(StreamTier::Preview),
1661                    bytes.clone(),
1662                )
1663                .unwrap(),
1664            )
1665            .unwrap();
1666        sender.submit_scatter_video(returned_preview).unwrap();
1667        assert_eq!(list(&sender.lending.loans().preview), preview);
1668        let reclaimed = sender.close();
1669        assert!(reclaimed.program.is_some());
1670        assert!(reclaimed.preview.is_some());
1671    }
1672
1673    #[cfg(ndi_has_advanced_scatter_send)]
1674    #[test]
1675    fn scatter_construction_allocates_only_block_headers_and_native_descriptors() {
1676        let (format, bytes) = h264();
1677        for (cuts, allocations) in [(&[][..], 3), (&[44][..], 4)] {
1678            let blocks = split(&bytes, cuts);
1679            let pointers: Vec<_> = blocks.iter().map(Vec::as_ptr).collect();
1680            let (frame, called) =
1681                crate::test_alloc::allocation_count(|| ScatterFrame::new(format, blocks).unwrap());
1682            assert_eq!(
1683                called, allocations,
1684                "two arrays, one stable list, and the remaining block headers"
1685            );
1686            assert_eq!(frame.total_bytes(), bytes.len());
1687            assert!(frame.blocks().map(<[u8]>::as_ptr).eq(pointers));
1688        }
1689    }
1690
1691    #[test]
1692    fn finishing_reclaims_both_one_or_no_stream_without_allocating() {
1693        let Some(ndi) = crate::test_support::advanced_ndi() else {
1694            return;
1695        };
1696        for scatter in [false, true]
1697            .into_iter()
1698            .filter(|scatter| !scatter || cfg!(ndi_has_advanced_scatter_send))
1699        {
1700            for active in 0..4 {
1701                let mut sender = CompressedSender::new(
1702                    &ndi,
1703                    &SenderOptions::new(crate::test_support::unique_name("finish-streams"))
1704                        .clock_video(false),
1705                )
1706                .unwrap();
1707                let mut expected = [None; 2];
1708                for (index, tier) in [StreamTier::Program, StreamTier::Preview]
1709                    .into_iter()
1710                    .enumerate()
1711                {
1712                    if active & (1 << index) == 0 {
1713                        continue;
1714                    }
1715                    let format = VideoPacketFormat::new(VideoCodec::SpeedHq422, 16, 16)
1716                        .unwrap()
1717                        .with_tier(tier);
1718                    expected[index] = Some(if scatter {
1719                        let frame = ScatterFrame::<VideoPacketFormat>::new(
1720                            format,
1721                            vec![vec![1; 16], vec![2; 8]],
1722                        )
1723                        .unwrap();
1724                        let pointer = frame.blocks().next().unwrap().as_ptr();
1725                        assert!(sender.submit_scatter_video(frame).unwrap().is_none());
1726                        pointer
1727                    } else {
1728                        let frame =
1729                            CompressedFrame::<VideoPacketFormat>::new(format, vec![1; 16]).unwrap();
1730                        let pointer = frame.data().as_ptr();
1731                        assert!(sender.submit_video(frame).is_none());
1732                        pointer
1733                    });
1734                }
1735                let (reclaimed, allocations) =
1736                    crate::test_alloc::allocation_count(|| sender.reclaim_video());
1737                assert_eq!(allocations, 0);
1738                for (returned, expected) in [reclaimed.program, reclaimed.preview]
1739                    .into_iter()
1740                    .zip(expected)
1741                {
1742                    let pointer = returned.map(|frame| match frame {
1743                        SubmittedVideo::Contiguous(frame) => {
1744                            assert!(!scatter);
1745                            frame.data().as_ptr()
1746                        }
1747                        SubmittedVideo::Scatter(frame) => {
1748                            assert!(scatter);
1749                            frame.blocks().next().unwrap().as_ptr()
1750                        }
1751                    });
1752                    assert_eq!(pointer, expected);
1753                }
1754                let empty = sender.split().0.reclaim_video();
1755                assert!(empty.program.is_none() && empty.preview.is_none());
1756                let closed = sender.close();
1757                assert!(closed.program.is_none() && closed.preview.is_none());
1758            }
1759        }
1760    }
1761
1762    /// Each stream keeps its own frame in flight: a submission hands back the
1763    /// earlier frame of its own stream, the very allocation the SDK was lent,
1764    /// and closing hands back the frame each stream still held.
1765    #[test]
1766    fn async_frames_are_retained_per_stream_until_synchronized() {
1767        let Some(ndi) = crate::test_support::advanced_ndi() else {
1768            return;
1769        };
1770        let (format, bytes) = h264();
1771        let make = |tier| {
1772            CompressedFrame::<VideoPacketFormat>::new(format.with_tier(tier), bytes.clone())
1773                .unwrap()
1774        };
1775        let options = SenderOptions::new(crate::test_support::unique_name("Per-stream retention"))
1776            .clock_video(false);
1777        let mut sender = CompressedSender::new(&ndi, &options).unwrap();
1778        let program = make(StreamTier::Program);
1779        let program_data = program.data().as_ptr();
1780        assert!(sender.submit_video(program).is_none());
1781        // A preview submission leaves the program frame in flight.
1782        let preview = sender.submit_video(make(StreamTier::Preview));
1783        assert!(preview.is_none());
1784        assert!(sender.lending.loans().program.is_in_flight());
1785        let returned = sender.submit_video(make(StreamTier::Program)).unwrap();
1786        let SubmittedVideo::Contiguous(returned) = returned else {
1787            panic!("a contiguous frame was submitted");
1788        };
1789        assert_eq!(returned.format().tier(), StreamTier::Program);
1790        assert_eq!(returned.data().as_ptr(), program_data);
1791        // The SDK may have stamped the reserved field, and nothing else.
1792        assert_eq!(returned.data()[..24], bytes[..24]);
1793        assert_eq!(returned.data()[32..], bytes[32..]);
1794        super::super::ReceivedPacket::<super::super::VideoPacketFormat>::from(returned.clone())
1795            .validate_for_send()
1796            .unwrap();
1797        let reclaimed = sender.close();
1798        assert_eq!(
1799            reclaimed.program.unwrap().format().tier(),
1800            StreamTier::Program
1801        );
1802        assert_eq!(
1803            reclaimed.preview.unwrap().format().tier(),
1804            StreamTier::Preview
1805        );
1806    }
1807}