Skip to main content

grafton_ndi/
sender.rs

1//! NDI sending functionality for video, audio, and metadata.
2
3#[cfg(test)]
4use std::ffi::CStr;
5
6#[cfg(test)]
7use crate::{
8    frames::{BorrowedVideoFrame, PixelFormat, ScanType, ValidatedVideoLayout},
9    pixels::send_room,
10    FrameRate, PictureAspectRatio, Timecode,
11};
12
13use std::{
14    ffi::CString,
15    fmt,
16    marker::PhantomData,
17    num::NonZeroU32,
18    ptr,
19    sync::{
20        atomic::{AtomicBool, AtomicU8, Ordering},
21        Arc,
22    },
23    time::{Duration, Instant},
24};
25
26use crate::{
27    finder::Source,
28    frames::{AudioPartsExt, MetadataPartsExt},
29    frames::{
30        AudioSource, MetadataFrame, MetadataFrameRef, MetadataSource, Sendable, VideoFrame,
31        VideoParts, VideoPartsExt, VideoSource,
32    },
33    marker::NotSync,
34    pixels::VideoStorage,
35    receiver::Tally,
36    source_retention::RetainedSources,
37    sys::{self, bindings::*},
38    timeout::Deadline,
39    to_ms_checked, Error, Ndi, Rejected, Result,
40};
41
42#[cfg(feature = "advanced")]
43use crate::advanced::{CompressedAttached, CompressedAudioSendMode, QueueAttached};
44
45#[cfg(not(target_has_atomic = "ptr"))]
46compile_error!(
47    "This crate requires atomic pointer support. Please use a target with atomics enabled."
48);
49
50/// Flush the async video pipeline by passing a true NULL pointer.
51///
52/// The NDI SDK documentation specifies that calling
53/// `NDIlib_send_send_video_async_v2(instance, NULL)` (where the *frame pointer*
54/// is NULL, not merely a frame whose `p_data` is NULL) waits for any in-flight
55/// async buffer to be released and then returns.
56fn async_flush_frame_ptr() -> *const NDIlib_video_frame_v2_t {
57    ptr::null()
58}
59
60/// The handle of a native sender: the one value through which this crate
61/// reaches an SDK sender, and the one place where the sender types' thread
62/// safety rests on the SDK's contract rather than on their Rust fields.
63///
64/// A copy is a borrowed handle. [`SenderResource`] owns the sender and
65/// destroys it.
66#[derive(Clone, Copy, Debug)]
67struct SendInstance(NDIlib_send_instance_t);
68
69// SAFETY: the handle is an opaque pointer with no thread affinity, and the SDK
70// lets one sender be used from several threads at once. Its documentation of
71// sending (the NDI-Send section) allows video, audio and metadata to be sent
72// at any time, from any thread and in any order, and `Processing.NDI.Send.h`
73// allows for audio and video submitted from separate threads when it
74// describes their clocking. Nothing requires a sender to be destroyed on the
75// thread that created it. A copy grants nothing by itself: every use is an
76// `unsafe` SDK call made through an owner that keeps the sender alive, and
77// `SenderResource` destroys it only when the last owner is released, so no
78// call overlaps `NDIlib_send_destroy`. The operations this crate does not
79// overlap are serialized by the Rust state around the handle, whose own types
80// decide the auto traits of the types that hold it: the ownership and
81// synchronization of asynchronous video (`VideoPipeline` and the
82// `in_flight` slots), metadata capture with its matching free
83// (`Inner::metadata_capture`), and the Advanced queue's completion state,
84// which `QueuedSender` registers before it returns.
85unsafe impl Send for SendInstance {}
86// SAFETY: as for `Send`.
87unsafe impl Sync for SendInstance {}
88
89/// A live native sender and the entry points of the runtime that created
90/// it: what every SDK call on a sender is made through.
91///
92/// A copy is a borrowed handle, valid while an owner of the native sender
93/// (`Shared` or `Exclusive`) keeps it alive.
94#[derive(Clone, Copy)]
95pub(crate) struct SendHandle<'a> {
96    instance: SendInstance,
97    core: &'a sys::Core,
98    _owner: PhantomData<&'a SenderResource>,
99}
100
101impl<'a> SendHandle<'a> {
102    pub(crate) fn instance(self) -> NDIlib_send_instance_t {
103        self.instance.0
104    }
105
106    pub(crate) fn core(self) -> &'a sys::Core {
107        self.core
108    }
109}
110
111/// Sender-side bookkeeping that need not outlive the sender itself.
112struct Inner {
113    metadata_capture: SenderMetadataGate,
114    tally: TallyState,
115    #[cfg(ndi_has_advanced_keyframe_demand)]
116    keyframe_changes: crate::keyframe_changes::KeyframeChanges,
117}
118
119// The metadata gate's mutex protects a capture-lease bit that changes whole,
120// and native capture runs outside that mutex. The tally query mutex serializes
121// native queries. Neither lock holds application code. The change feed uses
122// unwind-safe standard locks.
123impl std::panic::RefUnwindSafe for Inner {}
124
125/// Exclusion spans capture through matching free, including a borrowed frame's
126/// lifetime. The mutex itself is held only while changing the occupancy bit,
127/// so the release token can safely move to a scoped worker thread.
128#[derive(Default)]
129struct SenderMetadataGate {
130    occupied: parking_lot::Mutex<bool>,
131    available: parking_lot::Condvar,
132}
133
134// Only the private acquisition/release paths change the occupancy bit, with
135// no application code under its lock. SenderMetadataGuard::drop sequences the
136// native free and lease release, including on unwind, so a panic cannot leave
137// capture state half-mutated. This preserves the captured frame's unwind traits.
138impl std::panic::RefUnwindSafe for SenderMetadataGate {}
139
140impl SenderMetadataGate {
141    fn acquire_until(&self, end: Instant) -> Option<SenderMetadataLease<'_>> {
142        let mut occupied = self.occupied.try_lock_until(end)?;
143        while *occupied {
144            if self.available.wait_until(&mut occupied, end).timed_out() && *occupied {
145                return None;
146            }
147        }
148        *occupied = true;
149        Some(SenderMetadataLease { gate: self })
150    }
151}
152
153/// A movable permit retaining a sender's capture/free exclusion. It borrows
154/// the sender-owned gate, so neither the gate nor native sender can disappear
155/// while a captured frame retains it. The frame drops before this token.
156pub(crate) struct SenderMetadataLease<'a> {
157    gate: &'a SenderMetadataGate,
158}
159
160impl Drop for SenderMetadataLease<'_> {
161    fn drop(&mut self) {
162        *self.gate.occupied.lock() = false;
163        self.gate.available.notify_one();
164    }
165}
166
167/// Polling must preserve the SDK's consumable change report for a later wait.
168#[derive(Default)]
169struct TallyState {
170    query: parking_lot::Mutex<()>,
171    value: AtomicU8,
172    pending: AtomicBool,
173}
174
175impl TallyState {
176    fn current(&self) -> Tally {
177        let bits = self.value.load(Ordering::Acquire);
178        Tally::new(bits & 1 != 0, bits & 2 != 0)
179    }
180
181    fn remember(&self, tally: Tally) {
182        self.value.store(
183            u8::from(tally.on_program()) | (u8::from(tally.on_preview()) << 1),
184            Ordering::Release,
185        );
186    }
187}
188
189/// A sender metadata capture source obtains its table through its own owner.
190#[derive(Clone, Copy)]
191struct SenderMetadataSource<'owner> {
192    resource: &'owner ownership::SenderResource,
193    table: &'owner sys::SenderMetadata,
194}
195
196impl<'owner> SenderMetadataSource<'owner> {
197    fn new(resource: &'owner ownership::SenderResource) -> Result<Self> {
198        Ok(Self {
199            resource,
200            table: resource.ndi().table::<sys::SenderMetadata>()?,
201        })
202    }
203}
204
205impl crate::capture::source_sealed::Sealed for SenderMetadataSource<'_> {}
206
207// SAFETY: construction gets the table from this sender's own runtime. The
208// resource borrow retains the sender and bound core until matching free.
209unsafe impl<'owner> crate::capture::FrameSource<'owner, crate::capture::SenderMetadataFree>
210    for SenderMetadataSource<'owner>
211{
212    fn runtime(&self) -> &'owner Ndi {
213        self.resource.ndi()
214    }
215
216    fn instance(&self) -> crate::capture::SenderMetadataInstance {
217        crate::capture::SenderMetadataInstance {
218            instance: self.resource.handle().instance(),
219            free: self.table.NDIlib_send_free_metadata,
220        }
221    }
222}
223
224mod ownership {
225    use super::*;
226
227    /// The owner of a native sender, which destroys it when dropped:
228    /// advertisements retain one without access to sends.
229    ///
230    /// Nominally public only so that [`NativeOwner`] can name it; its implementation stays private.
231    pub struct SenderResource {
232        instance: SendInstance,
233        pub(super) _name: CString,
234        pub(super) _groups: Option<CString>,
235        // A registration may keep this native sender alive after Sender drops.
236        pub(super) failover: parking_lot::Mutex<RetainedSources>,
237        #[cfg(feature = "advanced")]
238        pub(super) _config: crate::advanced::RetainedConfig,
239        sdk: crate::runtime::Bound<sys::Core>,
240    }
241
242    // No application code runs under the failover lock. A replacement keeps
243    // both descriptors alive through the native call, then commits one swap;
244    // unwinding cannot leave a dangling native source descriptor.
245    impl std::panic::RefUnwindSafe for SenderResource {}
246
247    impl fmt::Debug for SenderResource {
248        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249            f.debug_struct("SenderResource")
250                .field("name", &self._name)
251                .finish_non_exhaustive()
252        }
253    }
254
255    impl SenderResource {
256        pub(super) fn new(
257            instance: SendInstance,
258            name: CString,
259            groups: Option<CString>,
260            #[cfg(feature = "advanced")] config: crate::advanced::RetainedConfig,
261            sdk: crate::runtime::Bound<sys::Core>,
262        ) -> Self {
263            Self {
264                instance,
265                _name: name,
266                _groups: groups,
267                failover: parking_lot::Mutex::new(RetainedSources::default()),
268                #[cfg(feature = "advanced")]
269                _config: config,
270                sdk,
271            }
272        }
273
274        /// The runtime whose native instance this resource owns.
275        pub(super) fn ndi(&self) -> &Ndi {
276            self.sdk.ndi()
277        }
278
279        /// Lend the native identity with the runtime that created it.
280        pub(crate) fn handle(&self) -> SendHandle<'_> {
281            SendHandle {
282                instance: self.instance,
283                core: &self.sdk,
284                _owner: PhantomData,
285            }
286        }
287    }
288
289    impl Drop for SenderResource {
290        fn drop(&mut self) {
291            // SAFETY: this token is the instance's final owner.
292            unsafe { self.sdk.NDIlib_send_destroy(self.instance.0) };
293        }
294    }
295
296    /// How a [`Sender`] owns its native sender: [`Shared`] or `Exclusive`, as
297    /// the associated type of its sealed mode trait says.
298    ///
299    /// The trait and both owners are nominally public, so that the sealed mode
300    /// trait can name them, but their implementation stays private.
301    pub trait NativeOwner: Send + Sync + fmt::Debug {
302        /// Own a native sender that was just created.
303        fn new(resource: SenderResource) -> Self;
304        /// The resource shared by this sender's common operations.
305        fn resource(&self) -> &SenderResource;
306    }
307
308    /// The native sender of a [`RawSend`] sender, which advertiser registrations
309    /// may share, and the asynchronous video pipeline that sends through it.
310    pub struct Shared {
311        pub(super) video: VideoPipeline,
312    }
313
314    impl NativeOwner for Shared {
315        fn resource(&self) -> &SenderResource {
316            self.video.resource()
317        }
318
319        fn new(resource: SenderResource) -> Self {
320            Self {
321                video: VideoPipeline::new(Arc::new(resource)),
322            }
323        }
324    }
325
326    impl Shared {
327        pub(super) fn native_owner(&self) -> Arc<SenderResource> {
328            self.video.native_owner()
329        }
330
331        #[cfg(all(feature = "advanced", ndi_has_advanced_send_completion))]
332        #[allow(clippy::result_large_err)]
333        pub(super) fn into_exclusive(
334            self,
335        ) -> std::result::Result<(SenderResource, Option<VideoFrame>), Self> {
336            let this = std::mem::ManuallyDrop::new(self);
337            // SAFETY: Shared has exactly one field. Suppressing its destructor
338            // transfers that field exactly once, without flushing it. The
339            // pipeline either becomes Shared again on refusal, or synchronizes
340            // all native loans before returning its exclusive resource.
341            let video = unsafe { ptr::read(&this.video) };
342            video.into_exclusive().map_err(|video| Self { video })
343        }
344    }
345
346    impl Drop for Shared {
347        fn drop(&mut self) {
348            // Advertisements may retain the native resource, so drain this
349            // pipeline while its owner and every pointee remain live.
350            self.video.flush_on_drop();
351        }
352    }
353
354    impl fmt::Debug for Shared {
355        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356            f.debug_struct("Shared").finish_non_exhaustive()
357        }
358    }
359
360    /// The native sender of a sender in one of the modes the Advanced senders
361    /// hold, which nothing else owns: dropping it destroys the native sender.
362    ///
363    /// A sender is created in such a mode, or converted into one only when no
364    /// registration shares its native sender (`Sender::into_attached`), and
365    /// such a mode hands out no other owner. So the frames an Advanced sender
366    /// keeps for the SDK are never freed while a registration keeps its native
367    /// sender alive.
368    #[cfg(feature = "advanced")]
369    pub struct Exclusive(pub(super) SenderResource);
370
371    #[cfg(feature = "advanced")]
372    impl NativeOwner for Exclusive {
373        fn resource(&self) -> &SenderResource {
374            &self.0
375        }
376
377        fn new(resource: SenderResource) -> Self {
378            Self(resource)
379        }
380    }
381
382    #[cfg(feature = "advanced")]
383    impl fmt::Debug for Exclusive {
384        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385            f.debug_struct("Exclusive").finish_non_exhaustive()
386        }
387    }
388}
389
390#[cfg(feature = "advanced")]
391use ownership::Exclusive;
392pub(crate) use ownership::SenderResource;
393use ownership::{NativeOwner, Shared};
394
395mod mode_sealed {
396    /// The sealed half of [`SenderMode`](super::SenderMode).
397    pub trait Sealed {
398        /// How a sender in this mode owns its native sender, and what it
399        /// keeps beside it: [`Shared`](super::Shared) for the mode that sends
400        /// uncompressed video, `Exclusive` for the modes
401        /// the Advanced senders hold.
402        type Native: super::NativeOwner;
403    }
404}
405
406/// Sealed sender capability mode.
407///
408/// Every mode has the operations that do not depend on how video is sent:
409/// the source, metadata in both directions, tally, connection count and
410/// metadata, failover, and the Advanced encoder guidance, keyframe and tally
411/// controls. [`RawSend`] alone sends uncompressed video; the modes that also
412/// send uncompressed audio implement [`AudioSendMode`].
413pub trait SenderMode: mode_sealed::Sealed + Send + Sync {}
414
415/// Sealed sender modes that send uncompressed audio with
416/// [`Sender::send_audio`]: [`RawSend`] and the queued mode.
417pub trait AudioSendMode: SenderMode {}
418
419/// Ordinary sender mode: uncompressed video, including the owned asynchronous
420/// pipeline, audio and metadata. Only a sender in this mode can be registered
421/// with a [`SendAdvertiser`](crate::discovery_server::SendAdvertiser).
422#[derive(Debug)]
423pub enum RawSend {}
424
425impl mode_sealed::Sealed for RawSend {
426    type Native = Shared;
427}
428impl SenderMode for RawSend {}
429impl AudioSendMode for RawSend {}
430#[cfg(feature = "advanced")]
431impl mode_sealed::Sealed for CompressedAttached {
432    type Native = Exclusive;
433}
434#[cfg(feature = "advanced")]
435impl SenderMode for CompressedAttached {}
436#[cfg(feature = "advanced")]
437impl CompressedAudioSendMode for CompressedAttached {}
438#[cfg(feature = "advanced")]
439impl mode_sealed::Sealed for QueueAttached {
440    type Native = Exclusive;
441}
442#[cfg(feature = "advanced")]
443impl SenderMode for QueueAttached {}
444#[cfg(feature = "advanced")]
445impl AudioSendMode for QueueAttached {}
446#[cfg(feature = "advanced")]
447impl CompressedAudioSendMode for QueueAttached {}
448
449/// An NDI source that sends video, audio and metadata.
450///
451/// Create one with [`Sender::new`]. Dropping the sender completes any
452/// in-flight asynchronous video and removes the source from the network,
453/// unless a [`SendAdvertiser`](crate::discovery_server::SendAdvertiser) registration
454/// still holds it: a registered sender stays on the network until that
455/// registration is removed or its advertiser is dropped.
456///
457/// The default mode, [`RawSend`], has every operation. The Advanced
458/// `CompressedSender` and `QueuedSender` hold their sender in another
459/// [`SenderMode`] and lend it through their `sender` method: it keeps the
460/// operations every mode shares, but not the video sends its owner makes
461/// itself, and it cannot be registered with an advertiser.
462///
463/// A sender is `Send` and `Sync`. Its operations take `&self` and may run on
464/// several threads at once, except the asynchronous video operations,
465/// `submit_video`, `submit_video_copy` and `reclaim_video`, which
466/// take `&mut self`. [`Sender::split`] lends these video operations to a
467/// scoped thread alongside a shared sender for audio, metadata and controls.
468/// Tally polls preserve changes for a waiting thread;
469/// concurrent tally waits serialize and each change is consumed once.
470pub struct Sender<M: SenderMode = RawSend> {
471    inner: Inner,
472    // The owner of the native sender, with the video pipeline of a mode that
473    // sends uncompressed video.
474    native: <M as mode_sealed::Sealed>::Native,
475    _mode: PhantomData<M>,
476}
477
478// SAFETY: The descriptor borrows this frame's initialized owned storage and
479// terminated metadata; moving it does not move its allocations. The loan's
480// reserved tail remains inaccessible until the owning stream releases it.
481unsafe impl in_flight::Lend for Sendable<VideoFrame> {
482    fn lend(&mut self) -> in_flight::Lent {
483        in_flight::Lent::Frame(self.video_descriptor())
484    }
485}
486
487/// Frames an asynchronous video send lends to the SDK, and the SDK calls that
488/// end the loan.
489///
490/// `Processing.NDI.Send.h` lets the SDK keep reading an asynchronous frame
491/// until a later video send (asynchronous or synchronous, including a null
492/// synchronous frame) or sender destruction synchronizes it. The [NDI-Send]
493/// documentation additionally specifies the null asynchronous flush used here.
494/// `Processing.NDI.Advanced.h` gives scatter submission the same lifetime rules.
495/// A [`CompressedSender`](crate::advanced::CompressedSender) conservatively
496/// retains each stream's frame until a replacement on that stream returns,
497/// even when another stream's video send has already synchronized the SDK.
498///
499/// [`in_flight::InFlight`] retains a stream's frame. Native synchronization and release
500/// happen together through a private [`in_flight::Stream`] paired by its owner
501/// with that owner's live sender. No synchronization token or independently
502/// supplied handle can release another sender's loan. Exclusive senders use
503/// [`in_flight::Lending`] to destroy the sender before releasing all its loans.
504/// A slot dropped without release leaks its frame rather than freeing it.
505///
506/// [NDI-Send]: https://docs.ndi.video/all/developing-with-ndi/sdk/ndi-send
507pub(crate) mod in_flight {
508    use std::mem;
509
510    #[cfg(feature = "advanced")]
511    use super::Exclusive;
512    use super::VideoStaging;
513    use super::{async_flush_frame_ptr, PreparedVideo, SendHandle, SenderResource};
514    #[cfg(all(feature = "advanced", ndi_has_advanced_scatter_send))]
515    use crate::advanced::ScatterVideoLoan;
516    use crate::frames::VideoSource;
517    #[cfg(feature = "advanced")]
518    use crate::Result;
519    use crate::{frames::Sendable, sys::bindings::NDIlib_video_frame_v2_t, VideoFrame};
520    use std::sync::{Arc, Mutex};
521
522    /// A slot paired by its owning pipeline or loan owner with its sender.
523    /// Fields are private and there is no constructor accepting a free slot
524    /// and handle, so synchronizing callers cannot exchange either half.
525    pub(crate) struct Stream<'a, T> {
526        slot: &'a mut InFlight<T>,
527        sender: SendHandle<'a>,
528    }
529
530    /// An uncompressed sender's native owner and all of its video storage.
531    /// Pairing stays in this module, including during destruction.
532    pub(super) struct VideoPipeline {
533        owner: Arc<SenderResource>,
534        state: Mutex<VideoState>,
535    }
536
537    #[derive(Default)]
538    pub(super) struct VideoState {
539        pub(super) in_flight: InFlight<Sendable<VideoFrame>>,
540        pub(super) staging: VideoStaging,
541        pub(super) spare: Option<VideoFrame>,
542    }
543
544    struct VideoPair<'a> {
545        stream: Stream<'a, Sendable<VideoFrame>>,
546        staging: &'a mut VideoStaging,
547        spare: &'a mut Option<VideoFrame>,
548    }
549
550    impl VideoPipeline {
551        pub(super) fn new(owner: Arc<SenderResource>) -> Self {
552            Self {
553                owner,
554                state: Mutex::new(VideoState::default()),
555            }
556        }
557
558        pub(super) fn resource(&self) -> &SenderResource {
559            &self.owner
560        }
561
562        pub(super) fn native_owner(&self) -> Arc<SenderResource> {
563            Arc::clone(&self.owner)
564        }
565
566        fn synchronize<R>(&self, call: impl FnOnce(VideoPair<'_>) -> R) -> R {
567            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
568            call(state.paired(self.owner.handle()))
569        }
570
571        fn exclusive(&mut self) -> VideoPair<'_> {
572            self.state
573                .get_mut()
574                .unwrap_or_else(|e| e.into_inner())
575                .paired(self.owner.handle())
576        }
577
578        pub(super) fn send(&self, frame: Sendable<&(impl VideoSource + ?Sized)>) {
579            self.synchronize(|mut pair| {
580                let prepared = PreparedVideo::authorized(frame, pair.staging);
581                pair.stream.send(prepared);
582            });
583        }
584
585        pub(super) fn submit(&mut self, frame: Sendable<VideoFrame>) -> Option<VideoFrame> {
586            self.exclusive().submit(frame)
587        }
588
589        pub(super) fn submit_shared(&self, frame: Sendable<VideoFrame>) -> Option<VideoFrame> {
590            self.synchronize(|pair| pair.submit(frame))
591        }
592
593        pub(super) fn copy(&mut self, frame: Sendable<&(impl VideoSource + ?Sized)>) {
594            self.exclusive().copy(frame);
595        }
596
597        pub(super) fn copy_shared(&self, frame: Sendable<&(impl VideoSource + ?Sized)>) {
598            self.synchronize(|pair| pair.copy(frame));
599        }
600
601        pub(super) fn flush(&self) {
602            self.synchronize(|mut pair| pair.stream.flush());
603        }
604
605        pub(super) fn finish(&mut self) -> Option<VideoFrame> {
606            self.exclusive().finish()
607        }
608
609        pub(super) fn finish_shared(&self) -> Option<VideoFrame> {
610            self.synchronize(|pair| pair.finish())
611        }
612
613        #[cfg(test)]
614        pub(super) fn test_state(&self) -> std::sync::MutexGuard<'_, VideoState> {
615            self.state.lock().unwrap()
616        }
617
618        #[cfg(all(feature = "advanced", ndi_has_advanced_send_completion))]
619        #[allow(clippy::result_large_err)]
620        pub(super) fn into_exclusive(
621            self,
622        ) -> std::result::Result<(SenderResource, Option<VideoFrame>), Self> {
623            let Self { owner, state } = self;
624            match Arc::try_unwrap(owner) {
625                Ok(resource) => {
626                    let mut state = state.into_inner().unwrap_or_else(|e| e.into_inner());
627                    let retained = state.paired(resource.handle()).finish();
628                    Ok((resource, retained))
629                }
630                Err(owner) => Err(Self { owner, state }),
631            }
632        }
633
634        pub(super) fn flush_on_drop(&mut self) {
635            self.exclusive().stream.flush();
636        }
637    }
638
639    impl VideoState {
640        fn paired<'a>(&'a mut self, sender: SendHandle<'a>) -> VideoPair<'a> {
641            let Self {
642                in_flight,
643                staging,
644                spare,
645            } = self;
646            VideoPair {
647                stream: Stream {
648                    slot: in_flight,
649                    sender,
650                },
651                staging,
652                spare,
653            }
654        }
655    }
656
657    impl VideoPair<'_> {
658        fn submit(mut self, frame: Sendable<VideoFrame>) -> Option<VideoFrame> {
659            self.stream.submit(frame).map(Sendable::into_frame)
660        }
661
662        fn copy(mut self, frame: Sendable<&(impl VideoSource + ?Sized)>) {
663            let owned = frame.copied(self.spare.take());
664            *self.spare = self.stream.submit(owned).map(Sendable::into_frame);
665        }
666
667        fn finish(mut self) -> Option<VideoFrame> {
668            self.stream.flush();
669            *self.spare = None;
670            self.stream.slot.take_retained().map(Sendable::into_frame)
671        }
672    }
673
674    /// Proof that a native sender has been destroyed, which ends the SDK's
675    /// access to every frame it was lent, on every stream.
676    ///
677    /// [`destroy`] makes it; [`InFlight::into_released`] takes it by
678    /// reference, since it releases any number of the destroyed sender's
679    /// slots.
680    #[cfg(feature = "advanced")]
681    #[must_use = "the proof releases the frames of the destroyed sender"]
682    pub(crate) struct Destroyed {
683        _private: (),
684    }
685
686    #[cfg(feature = "advanced")]
687    const_assert!(std::mem::size_of::<Destroyed>() == 0);
688
689    /// The loan storage attached to one exclusive native sender.
690    #[cfg(feature = "advanced")]
691    pub(crate) trait Loans {
692        type Recovered;
693        fn recover(self, destroyed: &Destroyed) -> Self::Recovered;
694        fn release(self, destroyed: &Destroyed);
695    }
696
697    /// One owner for an exclusive sender and every native loan it retains.
698    ///
699    /// The fields stay live until this module takes them exactly once during
700    /// close or Drop. Native destruction happens while loans remain owned.
701    #[cfg(feature = "advanced")]
702    pub(crate) struct Lending<M, L: Loans>
703    where
704        M: super::SenderMode + super::mode_sealed::Sealed<Native = Exclusive>,
705    {
706        sender: mem::ManuallyDrop<super::Sender<M>>,
707        loans: mem::ManuallyDrop<L>,
708    }
709
710    #[cfg(feature = "advanced")]
711    impl<M, L: Loans> Lending<M, L>
712    where
713        M: super::SenderMode + super::mode_sealed::Sealed<Native = Exclusive>,
714    {
715        pub(crate) fn new(sender: super::Sender<M>, loans: L) -> Self {
716            Self {
717                sender: mem::ManuallyDrop::new(sender),
718                loans: mem::ManuallyDrop::new(loans),
719            }
720        }
721
722        pub(crate) fn sender(&self) -> &super::Sender<M> {
723            &self.sender
724        }
725        pub(crate) fn loans(&self) -> &L {
726            &self.loans
727        }
728        pub(crate) fn parts(&mut self) -> LoanPair<'_, M, &mut L> {
729            LoanPair {
730                sender: &self.sender,
731                loans: &mut self.loans,
732            }
733        }
734
735        pub(crate) fn close(self) -> L::Recovered {
736            let mut this = mem::ManuallyDrop::new(self);
737            // SAFETY: consuming self suppresses Drop, and neither field is
738            // accessed after being taken. Loans remain live during destruction.
739            let sender = unsafe { mem::ManuallyDrop::take(&mut this.sender) };
740            let destroyed = destroy(sender);
741            // SAFETY: sender destruction returned, and this field is taken once.
742            let loans = unsafe { mem::ManuallyDrop::take(&mut this.loans) };
743            loans.recover(&destroyed)
744        }
745    }
746
747    /// A loan view paired by its owner with that owner's live sender.
748    /// Neither field can be supplied independently by a synchronizing caller.
749    #[cfg(feature = "advanced")]
750    pub(crate) struct LoanPair<'a, M: super::SenderMode, L> {
751        sender: &'a super::Sender<M>,
752        loans: L,
753    }
754
755    #[cfg(feature = "advanced")]
756    impl<'a, M: super::SenderMode, L> LoanPair<'a, M, L> {
757        pub(crate) fn sender(&self) -> &'a super::Sender<M> {
758            self.sender
759        }
760
761        pub(crate) fn loans(&self) -> &L {
762            &self.loans
763        }
764    }
765
766    #[cfg(feature = "advanced")]
767    impl<'a, M: super::SenderMode, L> LoanPair<'a, M, &'a mut L> {
768        /// Queues synchronize their own shared callback state internally.
769        pub(crate) fn shared(self) -> LoanPair<'a, M, &'a L> {
770            LoanPair {
771                sender: self.sender,
772                loans: self.loans,
773            }
774        }
775    }
776
777    #[cfg(feature = "advanced")]
778    impl<'a>
779        LoanPair<'a, crate::advanced::CompressedAttached, &'a mut crate::advanced::PendingStreams>
780    {
781        /// Submit a frame whose type already proves send admission.
782        pub(crate) fn submit_pending(
783            &mut self,
784            frame: crate::advanced::CompressedFrame<crate::advanced::VideoPacketFormat>,
785        ) -> Option<crate::advanced::SubmittedVideo> {
786            self.submit_prepared(crate::advanced::PendingVideo::Contiguous(frame))
787        }
788
789        // Rejection preserves every block of the caller's owned frame.
790        #[allow(clippy::result_large_err)]
791        pub(crate) fn submit_scatter(
792            &mut self,
793            frame: crate::advanced::ScatterFrame<crate::advanced::VideoPacketFormat>,
794        ) -> std::result::Result<
795            Option<crate::advanced::SubmittedVideo>,
796            crate::Rejected<crate::advanced::ScatterFrame<crate::advanced::VideoPacketFormat>>,
797        > {
798            let proof = crate::advanced::ScatterSendable::new(frame, self.sender.runtime())?;
799            Ok(self.submit_prepared(crate::advanced::PendingVideo::Scatter(proof)))
800        }
801
802        fn submit_prepared(
803            &mut self,
804            next: crate::advanced::PendingVideo,
805        ) -> Option<crate::advanced::SubmittedVideo> {
806            let tier = next.tier();
807            Stream {
808                slot: self.loans.slot(tier),
809                sender: self.sender.handle(),
810            }
811            .submit(next)
812            .map(crate::advanced::PendingVideo::into_submitted)
813        }
814
815        /// A synchronous video send ends both native loans. The frames stay
816        /// in their original slots for reclamation or same-stream replacement.
817        pub(crate) fn send_video(
818            &mut self,
819            frame: &mut crate::advanced::CompressedFrame<crate::advanced::VideoPacketFormat>,
820        ) {
821            let descriptor = frame.raw();
822            // SAFETY: this descriptor lends exclusively borrowed storage
823            // through the synchronous call.
824            self.synchronize_video(|sender| unsafe { send_video_native(sender, &descriptor) });
825        }
826
827        pub(crate) fn send_scatter_video(
828            &mut self,
829            frame: &mut crate::advanced::ScatterFrame<crate::advanced::VideoPacketFormat>,
830        ) -> Result<()> {
831            let admitted =
832                crate::advanced::ScatterSendable::borrowed(frame, self.sender.runtime())?;
833            self.synchronize_video(|sender| admitted.send_video(sender));
834            Ok(())
835        }
836
837        fn synchronize_video(&mut self, submit: impl FnOnce(SendHandle<'_>)) {
838            Stream {
839                slot: self.loans.slot(crate::StreamTier::Program),
840                sender: self.sender.handle(),
841            }
842            .synchronize(submit);
843            self.loans.slot(crate::StreamTier::Preview).mark_released();
844        }
845
846        /// Flush when the SDK still owns a loan, then recover both slots.
847        pub(crate) fn finish(&mut self) -> crate::advanced::ReclaimedVideo {
848            use crate::StreamTier::{Preview, Program};
849            if self.loans.slot(Program).is_in_flight() || self.loans.slot(Preview).is_in_flight() {
850                self.synchronize_video(flush_video_native);
851            }
852            self.loans.take_retained()
853        }
854    }
855
856    #[cfg(feature = "advanced")]
857    impl<'a> LoanPair<'a, crate::advanced::QueueAttached, &'a crate::advanced::QueueLoans> {
858        /// Admission and native dispatch use this pair's own callback and sender.
859        /// No caller can supply an entry prepared by another queue.
860        pub(crate) fn try_submit_queued(
861            &mut self,
862            frame: impl Into<crate::advanced::QueuedVideoFrame>,
863        ) -> std::result::Result<
864            crate::advanced::SubmissionId,
865            crate::Rejected<crate::advanced::QueuedVideoFrame>,
866        > {
867            let admitted = self.loans.prepare(self.sender, frame.into())?;
868            // SAFETY: this owner pair derived both the live handle and the
869            // admission from its own sender and callback. Admission retains
870            // every descriptor and pointee before dispatch; the callback may
871            // complete synchronously after its state lock has been released.
872            unsafe { admitted.lent.submit(self.sender.handle(), admitted.pointer) };
873            Ok(admitted.id)
874        }
875    }
876
877    #[cfg(feature = "advanced")]
878    impl<M, L: Loans> Drop for Lending<M, L>
879    where
880        M: super::SenderMode + super::mode_sealed::Sealed<Native = Exclusive>,
881    {
882        fn drop(&mut self) {
883            // SAFETY: Drop runs once, with no remaining borrower of either
884            // field. The loan storage is held until destruction supplies proof.
885            let sender = unsafe { mem::ManuallyDrop::take(&mut self.sender) };
886            let destroyed = destroy(sender);
887            // SAFETY: destruction ended every loan and the field is taken once.
888            let loans = unsafe { mem::ManuallyDrop::take(&mut self.loans) };
889            loans.release(&destroyed);
890        }
891    }
892
893    /// A frame an asynchronous video send can lend to the SDK.
894    ///
895    /// # Safety
896    ///
897    /// The descriptors [`lend`](Self::lend) returns point only into
898    /// allocations the frame owns, which moving the frame does not move: the
899    /// SDK goes on using them after the frame has moved into its slot, and
900    /// the slot gives no access to a frame in flight.
901    pub(crate) unsafe trait Lend {
902        fn lend(&mut self) -> Lent;
903    }
904
905    /// What an asynchronous video send hands the SDK.
906    pub(crate) enum Lent {
907        /// A frame descriptor, which the SDK reads during the call, for
908        /// `NDIlib_send_send_video_async_v2`.
909        Frame(NDIlib_video_frame_v2_t),
910        /// A frame descriptor without data, and the scatter list of the
911        /// frame's blocks, for `NDIlib_send_send_video_scatter_async`. No
912        /// header says the SDK copies the list, so the frame owns it too.
913        #[cfg(all(feature = "advanced", ndi_has_advanced_scatter_send))]
914        Scatter(ScatterVideoLoan),
915    }
916
917    impl Lent {
918        pub(crate) fn descriptor(&self) -> &NDIlib_video_frame_v2_t {
919            match self {
920                Self::Frame(frame) => frame,
921                #[cfg(all(feature = "advanced", ndi_has_advanced_scatter_send))]
922                Self::Scatter(proof) => proof.descriptor(),
923            }
924        }
925
926        #[cfg(all(feature = "advanced", ndi_has_advanced_scatter_send))]
927        pub(crate) fn descriptor_mut(&mut self) -> &mut NDIlib_video_frame_v2_t {
928            match self {
929                Self::Frame(frame) => frame,
930                Self::Scatter(proof) => proof.descriptor_mut(),
931            }
932        }
933
934        /// Submit through the one native dispatch used by ordinary and queued
935        /// asynchronous sending. Null-frame flushing is a distinct operation.
936        ///
937        /// # Safety
938        /// `sender` is live and owns the stream. `descriptor` describes this
939        /// loan and stays readable through the native call; with completion
940        /// callbacks it stays readable until completion. Every pointee,
941        /// including metadata, scatter list, arrays and payload, stays allocated
942        /// and inaccessible until native synchronization or completion ends
943        /// the loan. Any displaced loan stays live through this call's return.
944        unsafe fn submit(
945            &self,
946            sender: SendHandle<'_>,
947            descriptor: *const NDIlib_video_frame_v2_t,
948        ) {
949            match self {
950                Self::Frame(_) => {
951                    // SAFETY: the caller guarantees descriptor and loan lifetimes.
952                    unsafe {
953                        sender
954                            .core()
955                            .NDIlib_send_send_video_async_v2(sender.instance(), descriptor)
956                    };
957                }
958                #[cfg(all(feature = "advanced", ndi_has_advanced_scatter_send))]
959                Self::Scatter(proof) => {
960                    // SAFETY: the same lifetime contract also covers the stable
961                    // scatter list and the arrays and payload it names.
962                    unsafe { proof.submit(sender, descriptor) };
963                }
964            }
965        }
966    }
967
968    /// One stream's retained storage. Only its private owner-bound Stream
969    /// can synchronize native access and mark an in-flight frame released.
970    pub(crate) struct InFlight<T>(State<T>);
971
972    #[derive(Default)]
973    enum State<T> {
974        /// No frame is held.
975        #[default]
976        Idle,
977        /// The SDK has released the frame; it awaits recovery.
978        Retained(T),
979        /// The SDK may still be reading the frame.
980        InFlight(T),
981    }
982
983    impl<T> Default for InFlight<T> {
984        fn default() -> Self {
985            Self(State::Idle)
986        }
987    }
988
989    impl<T> InFlight<T> {
990        pub(crate) fn is_in_flight(&self) -> bool {
991            matches!(self.0, State::InFlight(_))
992        }
993
994        fn mark_released(&mut self) -> Option<&T> {
995            match mem::take(&mut self.0) {
996                State::InFlight(frame) => {
997                    self.0 = State::Retained(frame);
998                    self.retained()
999                }
1000                other => {
1001                    self.0 = other;
1002                    None
1003                }
1004            }
1005        }
1006
1007        /// Remove the retained frame, leaving the slot idle. A frame in
1008        /// flight stays held: it can be taken only once it has completed.
1009        pub(crate) fn take_retained(&mut self) -> Option<T> {
1010            match mem::take(&mut self.0) {
1011                State::Retained(frame) => Some(frame),
1012                other => {
1013                    self.0 = other;
1014                    None
1015                }
1016            }
1017        }
1018
1019        /// The frame, whatever its state, once the native sender it was lent
1020        /// to has been destroyed.
1021        #[cfg(feature = "advanced")]
1022        pub(crate) fn into_released(mut self, _destroyed: &Destroyed) -> Option<T> {
1023            match mem::take(&mut self.0) {
1024                State::Idle => None,
1025                State::Retained(frame) | State::InFlight(frame) => Some(frame),
1026            }
1027        }
1028
1029        fn retained(&self) -> Option<&T> {
1030            match &self.0 {
1031                State::Retained(frame) => Some(frame),
1032                _ => None,
1033            }
1034        }
1035
1036        #[cfg(test)]
1037        pub(crate) fn frame(&self) -> Option<&T> {
1038            match &self.0 {
1039                State::Idle => None,
1040                State::Retained(frame) | State::InFlight(frame) => Some(frame),
1041            }
1042        }
1043    }
1044
1045    impl<T> Drop for InFlight<T> {
1046        fn drop(&mut self) {
1047            if let State::InFlight(frame) = mem::take(&mut self.0) {
1048                // Retain native pointees even if a future owner forgets proof.
1049                mem::forget(frame);
1050                if !std::thread::panicking() {
1051                    debug_invariant!(
1052                        false,
1053                        "in-flight frame dropped without synchronization or destruction"
1054                    );
1055                }
1056            }
1057        }
1058    }
1059
1060    impl<T: Lend> Stream<'_, T> {
1061        /// Install the new loan before dispatch and return displaced storage
1062        /// only after this same sender's synchronizing call has returned.
1063        fn submit(&mut self, mut next: T) -> Option<T> {
1064            let lent = next.lend();
1065            let mut displaced = InFlight(mem::replace(&mut self.slot.0, State::InFlight(next)));
1066            // SAFETY: pairing is private to the slot's owning pipeline or
1067            // LoanPair. Both new and displaced allocations remain owned
1068            // through dispatch; Lend's contract retains every stable pointee.
1069            unsafe { lent.submit(self.sender, lent.descriptor()) };
1070            displaced.mark_released();
1071            displaced.take_retained()
1072        }
1073    }
1074
1075    fn flush_video_native(sender: SendHandle<'_>) {
1076        // SAFETY: the handle retains the sender and its runtime. A true null
1077        // descriptor drains that sender's asynchronous loans.
1078        unsafe {
1079            sender
1080                .core()
1081                .NDIlib_send_send_video_async_v2(sender.instance(), async_flush_frame_ptr())
1082        };
1083    }
1084
1085    /// # Safety
1086    /// The caller retains the descriptor and all bytes it names through the
1087    /// synchronous SDK call.
1088    unsafe fn send_video_native(sender: SendHandle<'_>, frame: &NDIlib_video_frame_v2_t) {
1089        // SAFETY: the handle retains the sender and its runtime. The caller
1090        // keeps the descriptor and storage live.
1091        unsafe {
1092            sender
1093                .core()
1094                .NDIlib_send_send_video_v2(sender.instance(), frame)
1095        };
1096    }
1097
1098    impl<T> Stream<'_, T> {
1099        /// Dispatch a synchronizing call through the handle paired with this
1100        /// slot and release its loan after the call returns.
1101        fn synchronize(&mut self, submit: impl FnOnce(SendHandle<'_>)) {
1102            submit(self.sender);
1103            self.slot.mark_released();
1104        }
1105
1106        fn flush(&mut self) {
1107            if self.slot.is_in_flight() {
1108                self.synchronize(flush_video_native);
1109            }
1110        }
1111    }
1112
1113    impl Stream<'_, Sendable<VideoFrame>> {
1114        fn send(&mut self, frame: PreparedVideo<'_>) {
1115            // SAFETY: PreparedVideo borrows initialized input or padded
1116            // staging through the synchronous call.
1117            self.synchronize(|sender| unsafe { send_video_native(sender, &frame.raw) });
1118        }
1119    }
1120
1121    /// Destroy `sender`'s native sender, which nothing else owns in its mode,
1122    /// and return the proof that the SDK no longer reads any frame it was
1123    /// lent.
1124    ///
1125    /// `Processing.NDI.Send.h` lists destruction among the synchronizing
1126    /// events, and the Advanced SDK documentation has `NDIlib_send_destroy`
1127    /// deliver every outstanding completion before it returns.
1128    #[cfg(feature = "advanced")]
1129    fn destroy<M>(sender: super::Sender<M>) -> Destroyed
1130    where
1131        M: super::SenderMode + super::mode_sealed::Sealed<Native = Exclusive>,
1132    {
1133        let super::Sender {
1134            native: Exclusive(resource),
1135            ..
1136        } = sender;
1137        // The only owner: dropping it calls `NDIlib_send_destroy`.
1138        drop(resource);
1139        Destroyed { _private: () }
1140    }
1141
1142    #[cfg(test)]
1143    mod tests {
1144        use super::*;
1145
1146        /// The split path locks this state and runs these same kernels. Every
1147        /// synthetic native call rereads the previous loan before releasing it,
1148        /// so Miri observes descriptor/pixel lifetimes through submit and reclaim.
1149        #[test]
1150        fn split_video_kernels_retain_loans_and_reuse_warm_storage() {
1151            use super::super::SendInstance;
1152            use crate::{sys::table::Resolver, LoadRefusal};
1153            use std::{
1154                ffi::{c_void, CStr},
1155                ptr::NonNull,
1156                sync::LazyLock,
1157            };
1158
1159            #[derive(Default)]
1160            struct Observation {
1161                pending: Option<(crate::sys::bindings::NDIlib_video_frame_v2_t, u8)>,
1162                releases: usize,
1163            }
1164            unsafe extern "C" fn unused() {}
1165            unsafe extern "C" fn submit(
1166                instance: crate::sys::bindings::NDIlib_send_instance_t,
1167                frame: *const crate::sys::bindings::NDIlib_video_frame_v2_t,
1168            ) {
1169                // SAFETY: the instance borrows this live test mutex. The
1170                // previous loan must still own its bytes until this call returns.
1171                let state = unsafe { &*instance.cast::<Mutex<Observation>>() };
1172                let mut state = state.lock().unwrap();
1173                if let Some((previous, byte)) = state.pending.take() {
1174                    assert_eq!(unsafe { previous.p_data.read() }, byte);
1175                    assert_eq!(unsafe { CStr::from_ptr(previous.p_metadata) }, c"<loan/>");
1176                    state.releases += 1;
1177                }
1178                if !frame.is_null() {
1179                    let frame = unsafe { *frame };
1180                    state.pending = Some((frame, unsafe { frame.p_data.read() }));
1181                }
1182            }
1183            struct Synthetic;
1184            impl Resolver for Synthetic {
1185                fn resolve(
1186                    &self,
1187                    name: &'static CStr,
1188                ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal> {
1189                    // Only the video entry is called. Other entries have valid
1190                    // code addresses but are intentionally outside this fixture.
1191                    let address = if name == c"NDIlib_send_send_video_async_v2" {
1192                        submit as *mut c_void
1193                    } else {
1194                        unused as *mut c_void
1195                    };
1196                    Ok(NonNull::new(address))
1197                }
1198            }
1199            static CORE: LazyLock<crate::sys::Core> =
1200                LazyLock::new(|| crate::sys::Core::load(&Synthetic).unwrap().ok().unwrap());
1201            let observed = Mutex::new(Observation::default());
1202            let sender = SendHandle {
1203                instance: SendInstance(std::ptr::from_ref(&observed).cast_mut().cast()),
1204                core: &CORE,
1205                _owner: std::marker::PhantomData,
1206            };
1207            let frame = |value| {
1208                crate::VideoFrame::builder()
1209                    .resolution(2, 2)
1210                    .metadata("<loan/>")
1211                    .data(vec![value; 16])
1212                    .build()
1213                    .unwrap()
1214            };
1215            let source = frame(3);
1216            let state = Mutex::new(VideoState::default());
1217            let submit = |frame| {
1218                state
1219                    .lock()
1220                    .unwrap()
1221                    .paired(sender)
1222                    .submit(Sendable::for_test(frame))
1223            };
1224            let mut spare = frame(1);
1225            assert!(submit(frame(2)).is_none());
1226            let (_, allocations) = crate::test_alloc::allocation_count(|| {
1227                for _ in 0..4 {
1228                    spare = submit(spare).unwrap();
1229                }
1230            });
1231            assert_eq!(allocations, 0);
1232            let copy = || {
1233                state
1234                    .lock()
1235                    .unwrap()
1236                    .paired(sender)
1237                    .copy(Sendable::for_test(&source))
1238            };
1239            copy();
1240            copy();
1241            let (_, allocations) = crate::test_alloc::allocation_count(|| {
1242                copy();
1243                copy();
1244            });
1245            assert_eq!(allocations, 0);
1246            let finish = || state.lock().unwrap().paired(sender).finish();
1247            assert_eq!(finish().unwrap().data(), source.data());
1248            assert!(finish().is_none());
1249            let observed = observed.lock().unwrap();
1250            assert!(observed.pending.is_none());
1251            assert_eq!(observed.releases, 9);
1252        }
1253
1254        /// Read the borrowed frame and its tail through the native descriptor,
1255        /// exercising the same synchronous dispatch kernel as Sender::send_video.
1256        #[test]
1257        fn synchronous_native_send_reads_the_whole_borrowed_buffer() {
1258            use super::super::{BorrowedVideoFrame, SendInstance};
1259            use crate::{
1260                frames::ValidatedVideoLayout, pixels::send_room, sys::table::Resolver, LoadRefusal,
1261                PixelFormat, ScanType,
1262            };
1263            use std::{
1264                cell::Cell,
1265                ffi::{c_void, CStr},
1266                marker::PhantomData,
1267                ptr::NonNull,
1268                sync::LazyLock,
1269            };
1270
1271            struct Observation {
1272                len: usize,
1273                calls: Cell<usize>,
1274            }
1275            unsafe extern "C" fn unused() {}
1276            unsafe extern "C" fn read_video(
1277                instance: crate::sys::bindings::NDIlib_send_instance_t,
1278                frame: *const NDIlib_video_frame_v2_t,
1279            ) {
1280                // SAFETY: this synchronous call borrows the live observation
1281                // and PreparedVideo retains its descriptor and all readable bytes.
1282                let observed = unsafe { &*instance.cast::<Observation>() };
1283                let frame = unsafe { &*frame };
1284                let bytes = unsafe { std::slice::from_raw_parts(frame.p_data, observed.len) };
1285                for (index, &byte) in bytes.iter().enumerate() {
1286                    assert_eq!(byte, (index % 251) as u8);
1287                }
1288                observed.calls.set(observed.calls.get() + 1);
1289            }
1290            struct Synthetic;
1291            impl Resolver for Synthetic {
1292                fn resolve(
1293                    &self,
1294                    name: &'static CStr,
1295                ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal> {
1296                    // Only synchronous video dispatch is exercised here.
1297                    let address = if name == c"NDIlib_send_send_video_v2" {
1298                        read_video as *mut c_void
1299                    } else {
1300                        unused as *mut c_void
1301                    };
1302                    Ok(NonNull::new(address))
1303                }
1304            }
1305            static CORE: LazyLock<crate::sys::Core> =
1306                LazyLock::new(|| crate::sys::Core::load(&Synthetic).unwrap().ok().unwrap());
1307            for (height, scan) in [(4, ScanType::Progressive), (6, ScanType::Interlaced)] {
1308                let layout =
1309                    ValidatedVideoLayout::new_uncompressed(PixelFormat::Uyvy, 18, height, None)
1310                        .unwrap();
1311                let len = layout.data_len_bytes() + send_room(&layout, scan);
1312                let buffer: Vec<u8> = (0..len).map(|index| (index % 251) as u8).collect();
1313                let frame = BorrowedVideoFrame::builder(&buffer, 18, height, PixelFormat::Uyvy)
1314                    .scan_type(scan)
1315                    .allow_send_from_padding_and_tail(true)
1316                    .build()
1317                    .unwrap();
1318                assert!(frame.sends_in_place());
1319                let observed = Observation {
1320                    len,
1321                    calls: Cell::new(0),
1322                };
1323                let sender = SendHandle {
1324                    instance: SendInstance(std::ptr::from_ref(&observed).cast_mut().cast()),
1325                    core: &CORE,
1326                    _owner: PhantomData,
1327                };
1328                let mut state = VideoState::default();
1329                let mut pair = state.paired(sender);
1330                let prepared = PreparedVideo::new(&frame, pair.staging);
1331                assert_eq!(prepared.raw.p_data.cast_const(), buffer.as_ptr());
1332                pair.stream.send(prepared);
1333                assert_eq!(observed.calls.get(), 1);
1334            }
1335        }
1336
1337        #[test]
1338        fn an_unproven_drop_leaks_the_native_loan() {
1339            use std::sync::atomic::{AtomicUsize, Ordering};
1340            static DROPS: AtomicUsize = AtomicUsize::new(0);
1341            struct Counted;
1342            impl Drop for Counted {
1343                fn drop(&mut self) {
1344                    DROPS.fetch_add(1, Ordering::Relaxed);
1345                }
1346            }
1347            DROPS.store(0, Ordering::Relaxed);
1348            let slot = InFlight(State::InFlight(Counted));
1349            let result = std::panic::catch_unwind(|| drop(slot));
1350            assert_eq!(result.is_err(), cfg!(debug_assertions));
1351            assert_eq!(
1352                DROPS.load(Ordering::Relaxed),
1353                0,
1354                "native pointees must remain allocated"
1355            );
1356        }
1357
1358        /// A frame in flight comes out of its slot only with a proof, and is
1359        /// completed only once.
1360        #[test]
1361        fn a_slot_releases_its_frame_only_with_proof() {
1362            let mut slot = InFlight(State::InFlight(1u8));
1363            assert!(slot.take_retained().is_none());
1364            assert!(slot.is_in_flight());
1365            assert_eq!(slot.mark_released(), Some(&1));
1366            assert!(!slot.is_in_flight());
1367            assert_eq!(slot.mark_released(), None);
1368            assert_eq!(slot.take_retained(), Some(1));
1369            assert!(slot.take_retained().is_none());
1370            assert!(slot.frame().is_none());
1371        }
1372
1373        #[cfg(feature = "advanced")]
1374        #[test]
1375        fn a_displaced_or_destroyed_slot_hands_back_what_it_held() {
1376            let release = |state| {
1377                let mut slot = InFlight(state);
1378                slot.mark_released();
1379                slot.take_retained()
1380            };
1381            assert_eq!(release(State::InFlight(1u8)), Some(1));
1382            assert_eq!(release(State::Retained(2)), Some(2));
1383            assert_eq!(release(State::Idle), None);
1384            let destroyed = Destroyed { _private: () };
1385            let unsent = |state| InFlight(state).into_released(&destroyed);
1386            assert_eq!(unsent(State::InFlight(3u8)), Some(3));
1387            assert_eq!(unsent(State::Retained(4)), Some(4));
1388            assert_eq!(unsent(State::Idle), None);
1389        }
1390    }
1391}
1392
1393use in_flight::VideoPipeline;
1394
1395impl<M: SenderMode> fmt::Debug for Sender<M> {
1396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397        f.debug_struct("Sender")
1398            .field("name", &self.native.resource()._name)
1399            .field("mode", &std::any::type_name::<M>())
1400            .finish_non_exhaustive()
1401    }
1402}
1403
1404/// Asynchronous video operations borrowed from a [`Sender`] through [`Sender::split`].
1405///
1406/// This view is `Send`, but neither `Sync` nor `Clone`. Dropping it leaves
1407/// pending frames with the sender; its next submission, reclamation or drop
1408/// synchronizes them.
1409pub struct RawVideo<'a> {
1410    sender: &'a Sender,
1411    _not_sync: NotSync,
1412}
1413
1414impl RawVideo<'_> {
1415    /// Submit owned video; see [`Sender::submit_video`] for ownership and pacing.
1416    ///
1417    /// # Errors
1418    ///
1419    /// Returns the unsent frame with [`Error::UnsupportedCapability`] when its
1420    /// pixel format is unavailable. Pending video is unchanged.
1421    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1422    pub fn submit_video(
1423        &mut self,
1424        frame: VideoFrame,
1425    ) -> std::result::Result<Option<VideoFrame>, Rejected<VideoFrame>> {
1426        let authorized = Sendable::new(frame, self.sender.runtime())?;
1427        Ok(self.sender.native.video.submit_shared(authorized))
1428    }
1429
1430    /// Copy and submit video; see [`Sender::submit_video_copy`] for reuse and pacing.
1431    ///
1432    /// # Errors
1433    ///
1434    /// Returns [`Error::UnsupportedCapability`] when the pixel format is
1435    /// unavailable, before copying or changing pending video.
1436    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1437    pub fn submit_video_copy(&mut self, frame: &(impl VideoSource + ?Sized)) -> Result<()> {
1438        let authorized = Sendable::borrowed(frame, self.sender.resource().ndi())?;
1439        self.sender.native.video.copy_shared(authorized);
1440        Ok(())
1441    }
1442
1443    /// Drain and recover the final frame; see [`Sender::reclaim_video`].
1444    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1445    pub fn reclaim_video(&mut self) -> Option<VideoFrame> {
1446        self.sender.native.video.finish_shared()
1447    }
1448}
1449
1450impl fmt::Debug for RawVideo<'_> {
1451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1452        f.debug_struct("RawVideo")
1453            .field("sender", self.sender)
1454            .finish_non_exhaustive()
1455    }
1456}
1457
1458#[cfg(test)]
1459trait StagingTestAccess {
1460    fn as_ptr(&self) -> *const u8;
1461    fn bytes(&self) -> &[u8];
1462    fn len(&self) -> usize;
1463    fn room(&self) -> usize;
1464    fn capacity(&self) -> usize;
1465    fn room_bytes(&self) -> &[u8];
1466}
1467#[cfg(test)]
1468impl StagingTestAccess for VideoStaging {
1469    fn as_ptr(&self) -> *const u8 {
1470        self.as_ref().map_or(std::ptr::null(), VideoStorage::as_ptr)
1471    }
1472    fn bytes(&self) -> &[u8] {
1473        self.as_ref().map_or(&[], VideoStorage::as_slice)
1474    }
1475    fn len(&self) -> usize {
1476        self.bytes().len()
1477    }
1478    fn room(&self) -> usize {
1479        self.as_ref().map_or(0, VideoStorage::room)
1480    }
1481    fn capacity(&self) -> usize {
1482        self.as_ref().map_or(0, VideoStorage::capacity)
1483    }
1484    fn room_bytes(&self) -> &[u8] {
1485        self.as_ref().map_or(&[], VideoStorage::room_bytes)
1486    }
1487}
1488
1489type VideoStaging = Option<VideoStorage>;
1490
1491/// A descriptor borrowing either a proven direct input or initialized packed
1492/// staging. Its lifetime keeps both input metadata and staging alive until the
1493/// synchronous native call returns. It never forms slices over capture padding.
1494pub(crate) struct PreparedVideo<'a> {
1495    raw: NDIlib_video_frame_v2_t,
1496    _borrow: PhantomData<&'a ()>,
1497}
1498
1499impl<'a> PreparedVideo<'a> {
1500    #[cfg(test)]
1501    fn new(frame: &'a (impl VideoParts + ?Sized), staging: &'a mut VideoStaging) -> Self {
1502        Self::authorized(Sendable::for_test(frame), staging)
1503    }
1504
1505    fn authorized(
1506        frame: Sendable<&'a (impl VideoParts + ?Sized)>,
1507        staging: &'a mut VideoStaging,
1508    ) -> Self {
1509        let raw = if frame.frame().can_send_direct() {
1510            frame.video_descriptor()
1511        } else {
1512            frame.packed(staging).video_descriptor()
1513        };
1514        Self {
1515            raw,
1516            _borrow: PhantomData,
1517        }
1518    }
1519}
1520
1521impl<M: SenderMode> Sender<M> {
1522    /// Create a sender in this mode, through the creation path of
1523    /// [`Sender::new`]: the configured entry point when the options carry an
1524    /// Advanced configuration, the plain one otherwise.
1525    pub(crate) fn open(ndi: &Ndi, options: &SenderOptions) -> Result<Self> {
1526        #[cfg(feature = "advanced")]
1527        {
1528            <Self as crate::advanced::Configurable>::create_from_options(ndi, options)
1529        }
1530        #[cfg(not(feature = "advanced"))]
1531        {
1532            Self::create_plain(ndi, options)
1533        }
1534    }
1535
1536    pub(crate) fn create_plain(ndi: &Ndi, options: &SenderOptions) -> Result<Self> {
1537        // SAFETY: the SDK's sender creation returns null or a fresh sender
1538        // that nothing else owns, and the settings outlive the call.
1539        unsafe {
1540            Self::create(ndi, options, |core, raw| {
1541                crate::runtime::NativeCreation::plain(core.named().NDIlib_send_create(raw))
1542            })
1543        }
1544    }
1545
1546    /// The one creation path: create a sender through `create`, which is handed the core table and the native
1547    /// settings for `options`, and keep `config` for as long as the native
1548    /// sender lives. The new sender is owned as its mode owns one.
1549    ///
1550    /// # Safety
1551    ///
1552    /// `create` returns null or a live sender of `ndi`'s runtime, made from
1553    /// the settings it was handed, that nothing else owns.
1554    pub(crate) unsafe fn create(
1555        ndi: &Ndi,
1556        options: &SenderOptions,
1557        create: impl FnOnce(
1558            &sys::Core,
1559            &NDIlib_send_create_t,
1560        ) -> crate::runtime::NativeCreation<NDIlib_send_instance_t>,
1561    ) -> Result<Self> {
1562        let name = CString::new(options.name.as_str())?;
1563        let groups = crate::list_setting::list_cstring(options.groups.as_deref(), "groups")?;
1564        let core = ndi.bind_core();
1565        let created = create(
1566            &core,
1567            &NDIlib_send_create_t {
1568                p_ndi_name: name.as_ptr(),
1569                p_groups: groups.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1570                clock_video: options.clock_video,
1571                clock_audio: options.clock_audio,
1572            },
1573        );
1574        let instance = created.call.created()?.as_ptr();
1575        let instance = SendInstance(instance);
1576        Ok(Self {
1577            inner: Inner {
1578                metadata_capture: SenderMetadataGate::default(),
1579                tally: TallyState::default(),
1580                #[cfg(ndi_has_advanced_keyframe_demand)]
1581                keyframe_changes: crate::keyframe_changes::KeyframeChanges::default(),
1582            },
1583            native: NativeOwner::new(SenderResource::new(
1584                instance,
1585                name,
1586                groups,
1587                #[cfg(feature = "advanced")]
1588                created.config,
1589                core,
1590            )),
1591            _mode: PhantomData,
1592        })
1593    }
1594}
1595
1596impl Sender {
1597    /// Creates a new NDI send instance.
1598    ///
1599    /// # Errors
1600    ///
1601    /// Returns [`Error::InvalidCString`] when the name contains a NUL byte,
1602    /// [`Error::InvalidInput`] when the group list is empty or a group is empty
1603    /// or contains a comma or NUL, [`Error::UnsupportedCapability`] when the
1604    /// options carry an Advanced configuration that the runtime or this build cannot take, and
1605    /// [`Error::NativeOperationFailed`] when the SDK creates no sender.
1606    #[doc(alias = "NDIlib_send_create")]
1607    pub fn new(ndi: &Ndi, options: &SenderOptions) -> Result<Self> {
1608        Self::open(ndi, options)
1609    }
1610
1611    /// A new owner of the native sender, which keeps it alive after this
1612    /// value is dropped. Only an ordinary sender hands one out: the wrappers
1613    /// that hold a sender in another mode free what the SDK reads once their
1614    /// native sender is gone, so it must not outlive them.
1615    pub(crate) fn native_owner(&self) -> Arc<SenderResource> {
1616        self.native.native_owner()
1617    }
1618
1619    /// The same native sender in mode `T`, which owns it exclusively, and the
1620    /// frame this sender's asynchronous video pipeline still held.
1621    ///
1622    /// The pipeline is retired: the SDK is drained, so nothing this sender
1623    /// submitted is in flight once the sender is in mode `T`, which has no
1624    /// pipeline. Returns the sender unchanged, with nothing synchronized,
1625    /// when an advertiser registration shares its native sender: the
1626    /// registration could keep it alive after the frames an Advanced sender
1627    /// lends the SDK are freed.
1628    #[cfg(all(feature = "advanced", ndi_has_advanced_send_completion))]
1629    // The refusal hands the sender back, so it is as large as the sender, as
1630    // the errors of the Advanced module that return their input are.
1631    #[allow(clippy::result_large_err)]
1632    pub(crate) fn into_attached<T>(
1633        self,
1634    ) -> std::result::Result<(Sender<T>, Option<VideoFrame>), Self>
1635    where
1636        T: SenderMode + mode_sealed::Sealed<Native = Exclusive>,
1637    {
1638        let Self {
1639            inner,
1640            native,
1641            _mode,
1642        } = self;
1643        let (resource, retained) = match native.into_exclusive() {
1644            Ok(exclusive) => exclusive,
1645            Err(native) => {
1646                return Err(Self {
1647                    inner,
1648                    native,
1649                    _mode,
1650                });
1651            }
1652        };
1653        let sender = Sender {
1654            inner,
1655            native: Exclusive(resource),
1656            _mode: PhantomData,
1657        };
1658        Ok((sender, retained))
1659    }
1660
1661    /// Lend asynchronous video and shared sender operations to scoped threads.
1662    ///
1663    /// The video view is `Send`, but neither `Sync` nor `Clone`, keeping one
1664    /// asynchronous video submitter. The shared sender supports audio,
1665    /// metadata and controls. Both halves borrow this sender; dropping the
1666    /// view leaves pending video with the owner for its next submission,
1667    /// reclamation or drop.
1668    ///
1669    /// Video submissions through the view synchronize with shared
1670    /// [`Self::send_video`] and [`Self::flush_video`] calls. Audio and metadata
1671    /// do not take that video lock, including while clocking paces a submission.
1672    pub fn split(&mut self) -> (RawVideo<'_>, &Sender) {
1673        let sender = &*self;
1674        (
1675            RawVideo {
1676                sender,
1677                _not_sync: NotSync::default(),
1678            },
1679            sender,
1680        )
1681    }
1682
1683    /// Send a video frame synchronously.
1684    ///
1685    /// Accepts every [`VideoSource`]: owned frames, checked external buffers,
1686    /// receiver captures and FrameSync captures, all by shared reference.
1687    /// Borrowed UYVY/UYVA frames are copied into packed storage with a zeroed
1688    /// tail wherever [`crate::PixelFormat::send_tail_room`] is nonzero, so padding
1689    /// and trailing bytes cannot affect the encoded picture. The sender
1690    /// reuses one staging allocation. Captures with padded rows also stage,
1691    /// since their guard guarantees only active pixels are initialized. Packed
1692    /// captures needing no trailing room send in place. Owned
1693    /// frames retain zeroed, scan-dependent tail room and always send in place.
1694    /// To permit direct sending from initialized caller padding
1695    /// and trailing memory, explicitly use
1696    /// [`crate::BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`];
1697    /// [`crate::BorrowedVideoFrame::sends_in_place`] tells which a frame is.
1698    ///
1699    /// The SDK has released the input buffer when this returns; the caller may
1700    /// then reuse or release it. This also completes a previous async video send.
1701    ///
1702    /// # Errors
1703    ///
1704    /// Returns [`Error::UnsupportedCapability`] if this sender's runtime
1705    /// cannot send the frame's pixel format (the planar 4:4:4 formats need
1706    /// [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video)).
1707    /// Nothing is sent and no pending send is changed.
1708    ///
1709    /// # Example
1710    ///
1711    /// ```no_run
1712    /// # use grafton_ndi::{BorrowedVideoFrame, Ndi, PixelFormat, Sender, SenderOptions};
1713    /// # fn main() -> Result<(), grafton_ndi::Error> {
1714    /// # let ndi = Ndi::new()?;
1715    /// # let sender = Sender::new(&ndi, &SenderOptions::new("Padded"))?;
1716    /// // 64 pixels per row, padded to a 512-byte stride.
1717    /// let mut buffer = vec![0u8; 512 * 32];
1718    /// let frame = BorrowedVideoFrame::builder(&buffer, 64, 32, PixelFormat::Bgra)
1719    ///     .line_stride_bytes(512)
1720    ///     .build()?;
1721    /// sender.send_video(&frame)?;
1722    /// buffer.fill(0xff); // the SDK is done with the buffer
1723    /// # Ok(())
1724    /// # }
1725    /// ```
1726    #[doc(alias = "NDIlib_send_send_video_v2")]
1727    pub fn send_video(&self, frame: &(impl VideoSource + ?Sized)) -> Result<()> {
1728        let authorized = Sendable::borrowed(frame, self.resource().ndi())?;
1729        self.native.video.send(authorized);
1730        Ok(())
1731    }
1732
1733    /// Submit an owned frame without copying its pixel or metadata allocations.
1734    ///
1735    /// The sender takes ownership before calling the SDK. The next async send
1736    /// synchronizes the previous send and returns its owned frame for reuse.
1737    /// The first send returns `None`. The returned frame may have been submitted
1738    /// by ownership or copying. A copied submission instead retains the frame
1739    /// it displaces for its next copy. Call [`Self::reclaim_video`] to
1740    /// recover the final frame.
1741    ///
1742    /// Synchronous sends and explicit flushes complete the operation but retain
1743    /// the owned frame for recovery by the next async send or [`Self::reclaim_video`].
1744    /// No SDK completion callback is registered, including with Advanced SDK.
1745    ///
1746    /// The call can still block: with [`SenderOptions::clock_video`] enabled,
1747    /// the default, the SDK paces video inside the call. The first can return
1748    /// immediately; subsequent calls wait for the next frame time. Set
1749    /// `clock_video(false)` and pace sends in the application to avoid this
1750    /// frame-rate wait. SDK back-pressure can also block a call. Use
1751    /// [`Self::split`] to send audio from another thread during submission.
1752    ///
1753    /// # Errors
1754    ///
1755    /// Returns the frame, unsent, with [`Error::UnsupportedCapability`] if
1756    /// this sender's runtime cannot send its pixel format (the planar 4:4:4
1757    /// formats need
1758    /// [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video)).
1759    /// No pending send is changed.
1760    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1761    pub fn submit_video(
1762        &mut self,
1763        frame: VideoFrame,
1764    ) -> std::result::Result<Option<VideoFrame>, Rejected<VideoFrame>> {
1765        let authorized = Sendable::new(frame, self.runtime())?;
1766        Ok(self.native.video.submit(authorized))
1767    }
1768
1769    /// Drain the SDK and return the final owned frame, if any.
1770    ///
1771    /// Frames submitted through either owned or copied sending are returned.
1772    /// Any spare storage retained for copying is released. Repeated calls
1773    /// return `None`.
1774    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1775    pub fn reclaim_video(&mut self) -> Option<VideoFrame> {
1776        self.native.video.finish()
1777    }
1778
1779    /// Copy borrowed pixels and metadata, then submit the owned copy asynchronously.
1780    ///
1781    /// The caller may immediately reuse or release the source buffer and metadata.
1782    /// The sender keeps the previous completed frame as spare storage for its
1783    /// next copy, whether that frame was submitted by ownership or copying.
1784    /// Once both frames have enough pixel and metadata capacity, repeated
1785    /// copies reuse their allocations. Larger layouts or longer metadata grow
1786    /// each buffer as needed.
1787    ///
1788    /// Recover the final copy with [`Self::reclaim_video`], which also
1789    /// releases the spare. Owned submissions through [`Self::submit_video`]
1790    /// still return the frame they displace.
1791    ///
1792    /// The call can still block: with [`SenderOptions::clock_video`] enabled,
1793    /// the default, the SDK paces video inside the call. The first can return
1794    /// immediately; subsequent calls wait for the next frame time. Set
1795    /// `clock_video(false)` and pace sends in the application to avoid this
1796    /// frame-rate wait. SDK back-pressure can also block a call. Use
1797    /// [`Self::split`] to send audio from another thread during submission.
1798    ///
1799    /// # Errors
1800    ///
1801    /// Returns [`Error::UnsupportedCapability`] if this sender's runtime
1802    /// cannot send the frame's pixel format, checked before anything is
1803    /// copied. No pending send is changed on failure.
1804    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1805    pub fn submit_video_copy(&mut self, frame: &(impl VideoSource + ?Sized)) -> Result<()> {
1806        let authorized = Sendable::borrowed(frame, self.resource().ndi())?;
1807        self.native.video.copy(authorized);
1808        Ok(())
1809    }
1810
1811    /// Flush pending async video operations synchronously.
1812    ///
1813    /// When the SDK may still read a pending frame, sends a null video frame
1814    /// pointer and blocks until that asynchronous operation completes. If no
1815    /// frame is in flight, returns without calling the SDK.
1816    ///
1817    /// After this returns, the SDK has released the pending buffer. The sender
1818    /// retains the frame; use [`Self::reclaim_video`] or an owned
1819    /// submission through [`Self::submit_video`] to recover it without copying.
1820    #[doc(alias = "NDIlib_send_send_video_async_v2")]
1821    pub fn flush_video(&self) {
1822        self.native.video.flush();
1823    }
1824}
1825
1826impl<M: AudioSendMode> Sender<M> {
1827    /// Sends an audio frame synchronously.
1828    ///
1829    /// Accepts every [`AudioSource`], including receiver and FrameSync captures.
1830    /// Samples and metadata are submitted in place with the original channel
1831    /// stride; no intermediate planar copy or wrapper allocation is made.
1832    /// The SDK has released the input buffer when this returns, so the caller
1833    /// may then reuse or release it. This calls `NDIlib_send_send_audio_v3`.
1834    /// It is available in the modes that implement [`AudioSendMode`]: on an
1835    /// ordinary sender and on the one a `QueuedSender` lends.
1836    ///
1837    /// See the NDI SDK documentation section on `NDIlib_send_send_audio_v3` for more details.
1838    ///
1839    /// # Example
1840    ///
1841    /// ```no_run
1842    /// # use grafton_ndi::{Ndi, SenderOptions, AudioFrame};
1843    /// # fn main() -> Result<(), grafton_ndi::Error> {
1844    /// # let ndi = Ndi::new()?;
1845    /// # let options = SenderOptions::new("Test");
1846    /// # let sender = grafton_ndi::Sender::new(&ndi, &options)?;
1847    /// let mut audio_buffer = vec![0.0f32; 48000 * 2]; // 1 second of stereo audio
1848    ///
1849    /// // Fill buffer with audio data...
1850    /// let frame = AudioFrame::builder()
1851    ///     .sample_rate(48000)
1852    ///     .num_channels(2)
1853    ///     .num_samples(48000)
1854    ///     .data(audio_buffer.clone())
1855    ///     .build()?;
1856    /// sender.send_audio(&frame);
1857    ///
1858    /// // Buffer can be reused immediately
1859    /// audio_buffer.fill(0.5);
1860    /// let frame2 = AudioFrame::builder()
1861    ///     .sample_rate(48000)
1862    ///     .num_channels(2)
1863    ///     .num_samples(48000)
1864    ///     .data(audio_buffer)
1865    ///     .build()?;
1866    /// sender.send_audio(&frame2);
1867    /// # Ok(())
1868    /// # }
1869    /// ```
1870    #[doc(alias = "NDIlib_send_send_audio_v3")]
1871    pub fn send_audio(&self, frame: &(impl AudioSource + ?Sized)) {
1872        let handle = self.handle();
1873        // SAFETY: this borrow reaches the instance's owning resource, and every
1874        // pointer passed outlives the synchronous call.
1875        unsafe {
1876            handle
1877                .core()
1878                .NDIlib_send_send_audio_v3(handle.instance(), &frame.audio_descriptor());
1879        }
1880    }
1881}
1882
1883impl<M: SenderMode> Sender<M> {
1884    pub(crate) fn handle(&self) -> SendHandle<'_> {
1885        self.resource().handle()
1886    }
1887
1888    /// All selectors consume the SDK's same one-shot report, including a
1889    /// null selector beside a format-specific selector. Share the native wait
1890    /// across them and filter the current demand at each caller.
1891    #[cfg(ndi_has_advanced_keyframe_demand)]
1892    pub(crate) fn keyframe_changes(&self) -> &crate::keyframe_changes::KeyframeChanges {
1893        &self.inner.keyframe_changes
1894    }
1895
1896    /// The single owner of this sender's native instance and runtime.
1897    fn resource(&self) -> &SenderResource {
1898        self.native.resource()
1899    }
1900
1901    pub(crate) fn runtime(&self) -> &Ndi {
1902        self.resource().ndi()
1903    }
1904
1905    /// Capture metadata sent back by connected receivers.
1906    ///
1907    /// The result owns its data. The wait budget includes contention with other
1908    /// metadata captures and does not block the video-send synchronization lock.
1909    /// Captured text uses the SDK's guaranteed NUL termination, bounded to
1910    /// 4 MiB, rather than assuming every positive native length is the exact
1911    /// UTF-8 byte count including its terminator. Invalid descriptor counts and
1912    /// invalid UTF-8 still return an error, and every captured frame is freed.
1913    ///
1914    /// # Errors
1915    ///
1916    /// Returns [`Error::UnsupportedCapability`] when the runtime lacks the
1917    /// sender metadata capture functions, [`Error::InvalidInput`] when the
1918    /// timeout exceeds [`crate::MAX_TIMEOUT`], [`Error::InvalidFrame`] for an
1919    /// invalid metadata count, a positive count with null data, or a missing
1920    /// bounded terminator,
1921    /// [`Error::InvalidUtf8`] for non-UTF-8 text, and [`Error::UnexpectedSdkResult`]
1922    /// when the SDK returns a frame type other than metadata or no frame.
1923    #[doc(alias = "NDIlib_send_capture")]
1924    pub fn capture_metadata(&self, timeout: Duration) -> Result<Option<MetadataFrame>> {
1925        Ok(self
1926            .capture_metadata_ref(timeout)?
1927            .map(|frame| frame.to_owned()))
1928    }
1929
1930    /// Borrow metadata sent back by connected receivers without copying it.
1931    ///
1932    /// The frame retains capture exclusion until it is dropped, after the SDK
1933    /// has freed its metadata. Another capture spends its timeout waiting for
1934    /// that release. Video sends use a separate synchronization path.
1935    /// The frame can move to a scoped worker thread; its borrow keeps this
1936    /// sender alive through the matching native free.
1937    ///
1938    /// # Errors
1939    ///
1940    /// As for [`Self::capture_metadata`].
1941    #[doc(alias = "NDIlib_send_capture")]
1942    pub fn capture_metadata_ref(&self, timeout: Duration) -> Result<Option<MetadataFrameRef<'_>>> {
1943        let handle = self.handle();
1944        let source = SenderMetadataSource::new(self.resource())?;
1945        let metadata = source.table;
1946        let deadline = Deadline::after(timeout)?;
1947        let Some(lease) = self.inner.metadata_capture.acquire_until(deadline.end()) else {
1948            return Ok(None);
1949        };
1950        let mut raw = NDIlib_metadata_frame_t {
1951            length: 0,
1952            timecode: 0,
1953            p_data: ptr::null_mut(),
1954        };
1955        let remaining = deadline.remaining_ms();
1956        // SAFETY: this borrowed sender is live, the lease serializes capture
1957        // through matching free, and raw is writable descriptor storage.
1958        let called = unsafe {
1959            metadata
1960                .named()
1961                .NDIlib_send_capture(handle.instance(), &mut raw, remaining)
1962        };
1963        let kind = *called.value();
1964        if kind == NDIlib_frame_type_e_NDIlib_frame_type_metadata {
1965            // SAFETY: this exact sender/runtime just delivered raw and the
1966            // lease retains its capture/free exclusion until the borrowed
1967            // view releases the guard. Sender metadata follows the SDK's
1968            // bounded NUL-terminated string contract; from_sender validates
1969            // that contract before exposing any text.
1970            let guard = unsafe {
1971                crate::capture::Guard::<crate::capture::SenderMetadataFree>::new(source, raw)
1972            };
1973            MetadataFrameRef::from_sender(guard, lease).map(Some)
1974        } else if kind == NDIlib_frame_type_e_NDIlib_frame_type_none {
1975            Ok(None)
1976        } else {
1977            Err(Error::UnexpectedSdkResult(
1978                crate::SdkResultDefect::UnexpectedFrameType {
1979                    operation: called.function(),
1980                    kind,
1981                },
1982            ))
1983        }
1984    }
1985
1986    /// Sends a metadata frame.
1987    ///
1988    /// Accepts owned or captured metadata without copying its text in the
1989    /// wrapper. The SDK copies the text before returning.
1990    #[doc(alias = "NDIlib_send_send_metadata")]
1991    pub fn send_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S) {
1992        let handle = self.handle();
1993        let raw = metadata.metadata_raw();
1994        // The borrowed C string remains live through this synchronous SDK call.
1995        // SAFETY: this borrow reaches the instance's owning resource, and every
1996        // pointer passed outlives the synchronous call.
1997        unsafe {
1998            handle
1999                .core()
2000                .NDIlib_send_send_metadata(handle.instance(), &raw);
2001        }
2002    }
2003
2004    /// The tally this sender currently reports.
2005    ///
2006    /// Polls without waiting and returns the most recent state the SDK reported
2007    /// to this sender, whether or not it has changed since the last query. Call
2008    /// [`Self::wait_for_tally_change`] to block until it changes. Never fails
2009    /// and may be called from any thread.
2010    /// While another thread waits, returns the cached state without a native
2011    /// query. That state may lag the change until the waiter wakes. Polling
2012    /// preserves a change for [`Self::wait_for_tally_change`] to report.
2013    ///
2014    /// # Examples
2015    ///
2016    /// ```no_run
2017    /// # use grafton_ndi::{Ndi, SenderOptions};
2018    /// # fn main() -> Result<(), grafton_ndi::Error> {
2019    /// let ndi = Ndi::new()?;
2020    /// let options = SenderOptions::new("Test Sender");
2021    /// let sender = grafton_ndi::Sender::new(&ndi, &options)?;
2022    ///
2023    /// let tally = sender.tally();
2024    /// println!("On program: {}, On preview: {}", tally.on_program(), tally.on_preview());
2025    /// # Ok(())
2026    /// # }
2027    /// ```
2028    #[doc(alias = "NDIlib_send_get_tally")]
2029    pub fn tally(&self) -> Tally {
2030        let state = &self.inner.tally;
2031        let Some(_query) = state.query.try_lock() else {
2032            return state.current();
2033        };
2034        let (changed, tally) = self.get_tally(0);
2035        state.remember(tally);
2036        if changed {
2037            state.pending.store(true, Ordering::Release);
2038        }
2039        tally
2040    }
2041
2042    /// Wait up to `timeout` for the tally to change.
2043    ///
2044    /// Returns `Ok(Some(tally))` with the new state when the SDK reports a
2045    /// change, and `Ok(None)` when `timeout` elapses first. Use
2046    /// [`Self::tally`] to read the current state without waiting.
2047    /// A change observed by polling is kept for the next wait. Changes
2048    /// coalesce, and each report goes to one waiter, rather than broadcasting
2049    /// to every waiter. Concurrent waits serialize their native queries;
2050    /// contention spends the same timeout budget as the native wait.
2051    ///
2052    /// # Errors
2053    ///
2054    /// Returns [`Error::InvalidInput`] if `timeout` exceeds [`crate::MAX_TIMEOUT`]
2055    /// (about 49.7 days).
2056    ///
2057    /// # Examples
2058    ///
2059    /// ```no_run
2060    /// # use grafton_ndi::{Ndi, SenderOptions};
2061    /// # use std::time::Duration;
2062    /// # fn main() -> Result<(), grafton_ndi::Error> {
2063    /// let ndi = Ndi::new()?;
2064    /// let options = SenderOptions::new("Test Sender");
2065    /// let sender = grafton_ndi::Sender::new(&ndi, &options)?;
2066    ///
2067    /// if let Some(tally) = sender.wait_for_tally_change(Duration::from_secs(1))? {
2068    ///     println!("On program: {}, On preview: {}", tally.on_program(), tally.on_preview());
2069    /// } else {
2070    ///     println!("Tally did not change");
2071    /// }
2072    /// # Ok(())
2073    /// # }
2074    /// ```
2075    #[doc(alias = "NDIlib_send_get_tally")]
2076    pub fn wait_for_tally_change(&self, timeout: Duration) -> Result<Option<Tally>> {
2077        let deadline = Deadline::after(timeout)?;
2078        let state = &self.inner.tally;
2079        let Some(_query) = state.query.try_lock_until(deadline.end()) else {
2080            return Ok(None);
2081        };
2082        if state.pending.swap(false, Ordering::AcqRel) {
2083            return Ok(Some(state.current()));
2084        }
2085        let (changed, tally) = self.get_tally(deadline.remaining_ms());
2086        state.remember(tally);
2087        Ok(changed.then_some(tally))
2088    }
2089
2090    /// Query the SDK's tally, waiting up to `timeout_ms`; returns whether it
2091    /// changed, and the tally.
2092    fn get_tally(&self, timeout_ms: u32) -> (bool, Tally) {
2093        let handle = self.handle();
2094        let mut raw_tally = Tally::default().to_sdk();
2095        // SAFETY: this borrow reaches the instance's owning resource, and every
2096        // pointer passed outlives the synchronous call.
2097        let changed = unsafe {
2098            handle
2099                .core()
2100                .NDIlib_send_get_tally(handle.instance(), &mut raw_tally, timeout_ms)
2101        };
2102        (
2103            changed,
2104            Tally::new(raw_tally.on_program, raw_tally.on_preview),
2105        )
2106    }
2107
2108    /// The current number of active connections, without waiting.
2109    ///
2110    /// # Errors
2111    ///
2112    /// [`Error::UnexpectedSdkResult`] if the SDK returns a negative count.
2113    #[doc(alias = "NDIlib_send_get_no_connections")]
2114    pub fn connection_count(&self) -> Result<u32> {
2115        self.connection_count_with_timeout(0)
2116    }
2117
2118    /// Wait up to `timeout` for at least one connected receiver.
2119    ///
2120    /// Returns the nonzero connection count as soon as a receiver is present,
2121    /// or `None` when the wait expires. A zero timeout reads the current count.
2122    ///
2123    /// # Errors
2124    ///
2125    /// [`Error::UnexpectedSdkResult`] for a negative native count, and
2126    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`].
2127    #[doc(alias = "NDIlib_send_get_no_connections")]
2128    pub fn wait_for_connection(&self, timeout: Duration) -> Result<Option<NonZeroU32>> {
2129        self.connection_count_with_timeout(to_ms_checked(timeout)?)
2130            .map(NonZeroU32::new)
2131    }
2132
2133    fn connection_count_with_timeout(&self, timeout_ms: u32) -> Result<u32> {
2134        let handle = self.handle();
2135        // SAFETY: this borrow keeps the sender and its runtime alive through
2136        // the bounded query, which writes no Rust-owned state.
2137        let count = unsafe {
2138            handle
2139                .core()
2140                .named()
2141                .NDIlib_send_get_no_connections(handle.instance(), timeout_ms)
2142        };
2143        count.count()
2144    }
2145
2146    /// Remove all metadata registered for delivery to each new connection.
2147    #[doc(alias = "NDIlib_send_clear_connection_metadata")]
2148    pub fn clear_connection_metadata(&self) {
2149        let handle = self.handle();
2150        // SAFETY: this borrow reaches the instance's owning resource, and every
2151        // pointer passed outlives the synchronous call.
2152        unsafe {
2153            handle
2154                .core()
2155                .NDIlib_send_clear_connection_metadata(handle.instance())
2156        }
2157    }
2158
2159    /// Register metadata sent now and to every new connection.
2160    ///
2161    /// Accepts owned or captured metadata. The SDK retains its own copy, so
2162    /// the input can be released as soon as this method returns.
2163    #[doc(alias = "NDIlib_send_add_connection_metadata")]
2164    pub fn add_connection_metadata<S: MetadataSource + ?Sized>(&self, metadata: &S) {
2165        let handle = self.handle();
2166        let raw = metadata.metadata_raw();
2167        // The borrowed C string remains live through this synchronous SDK call.
2168        // SAFETY: this borrow reaches the instance's owning resource, and every
2169        // pointer passed outlives the synchronous call.
2170        unsafe {
2171            handle
2172                .core()
2173                .NDIlib_send_add_connection_metadata(handle.instance(), &raw)
2174        }
2175    }
2176
2177    /// Set the validated failover source.
2178    #[doc(alias = "NDIlib_send_set_failover")]
2179    pub fn set_failover(&self, source: &Source) {
2180        let handle = self.handle();
2181        self.resource()
2182            .failover
2183            .lock()
2184            .replace(Some(source), |source| {
2185                // SAFETY: the native owner and its locked retention slot keep the
2186                // previous and replacement descriptors live through this request.
2187                unsafe {
2188                    handle
2189                        .core()
2190                        .NDIlib_send_set_failover(handle.instance(), source)
2191                }
2192            });
2193    }
2194
2195    /// Clear the failover source previously configured with [`Self::set_failover`].
2196    #[doc(alias = "NDIlib_send_set_failover")]
2197    pub fn clear_failover(&self) {
2198        let handle = self.handle();
2199        self.resource().failover.lock().replace(None, |source| {
2200            // SAFETY: the sender is live and the retention helper keeps the
2201            // previous descriptor until this null replacement returns.
2202            unsafe {
2203                handle
2204                    .core()
2205                    .NDIlib_send_set_failover(handle.instance(), source)
2206            }
2207        });
2208    }
2209
2210    /// Get the source information for this sender.
2211    ///
2212    /// # Errors
2213    ///
2214    /// Returns [`Error::NativeOperationFailed`] when the SDK supplies no
2215    /// descriptor, or one that names neither a source nor an address, and
2216    /// [`Error::UnexpectedSdkResult`] when its name or address is longer than
2217    /// the 4 MiB available for one SDK string, including its terminator.
2218    /// [`Error::InvalidUtf8`] reports an invalid name or address.
2219    /// [`Error::AllocationFailed`] reports a failed text buffer reservation.
2220    /// See [`crate::Finder::current_sources`] for allocation behavior of
2221    /// shared source owners.
2222    ///
2223    /// # Examples
2224    ///
2225    /// ```no_run
2226    /// # use grafton_ndi::{Ndi, SenderOptions};
2227    /// # fn main() -> Result<(), grafton_ndi::Error> {
2228    /// let ndi = Ndi::new()?;
2229    /// let options = SenderOptions::new("Test Sender");
2230    /// let sender = grafton_ndi::Sender::new(&ndi, &options)?;
2231    /// let source = sender.source()?;
2232    /// println!("Sender source: {source}");
2233    /// # Ok(())
2234    /// # }
2235    /// ```
2236    #[doc(alias = "NDIlib_send_get_source_name")]
2237    pub fn source(&self) -> Result<Source> {
2238        let handle = self.handle();
2239        // SAFETY: this borrow reaches the instance's owning resource, and every
2240        // pointer passed outlives the synchronous call.
2241        let source_ptr = unsafe {
2242            handle
2243                .core()
2244                .named()
2245                .NDIlib_send_get_source_name(handle.instance())
2246        };
2247        // SAFETY: the SDK sender owns this live descriptor and its strings
2248        // through the synchronous copy performed here.
2249        unsafe { Source::try_from_raw(source_ptr) }
2250    }
2251}
2252
2253/// Configuration for creating a [`Sender`].
2254///
2255/// The defaults pace video and audio submissions to their frame and sample
2256/// rates, in the groups of the NDI configuration.
2257///
2258/// # Examples
2259///
2260/// ```no_run
2261/// # use grafton_ndi::{Ndi, SenderOptions, Sender};
2262/// # fn main() -> Result<(), grafton_ndi::Error> {
2263/// # let ndi = Ndi::new()?;
2264/// let options = SenderOptions::new("My Sender").groups(["Studio"]);
2265/// let sender = Sender::new(&ndi, &options)?;
2266/// # Ok(())
2267/// # }
2268/// ```
2269#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2270pub struct SenderOptions {
2271    name: String,
2272    groups: Option<Vec<String>>,
2273    clock_video: bool,
2274    clock_audio: bool,
2275    #[cfg(feature = "advanced")]
2276    pub(crate) config: Option<crate::advanced::AdvancedConfig>,
2277}
2278
2279impl SenderOptions {
2280    /// Replace the advertised name; an empty name lets the SDK choose.
2281    #[must_use]
2282    pub fn name(mut self, name: impl Into<String>) -> Self {
2283        self.name = name.into();
2284        self
2285    }
2286
2287    /// Inherit discovery groups from the NDI configuration.
2288    #[must_use]
2289    pub fn clear_groups(mut self) -> Self {
2290        self.groups = None;
2291        self
2292    }
2293
2294    /// Remove the per-instance Advanced configuration override.
2295    #[cfg(feature = "advanced")]
2296    #[must_use]
2297    pub fn clear_config(mut self) -> Self {
2298        self.config = None;
2299        self
2300    }
2301
2302    /// Requested advertised name; an empty name lets the SDK choose.
2303    #[must_use]
2304    pub fn configured_name(&self) -> &str {
2305        &self.name
2306    }
2307
2308    /// Requested discovery groups, or `None` to inherit the NDI configuration.
2309    #[must_use]
2310    pub fn configured_groups(&self) -> Option<&[String]> {
2311        self.groups.as_deref()
2312    }
2313
2314    /// Whether video clocking was requested.
2315    #[must_use]
2316    pub fn configured_clock_video(&self) -> bool {
2317        self.clock_video
2318    }
2319
2320    /// Whether audio clocking was requested.
2321    #[must_use]
2322    pub fn configured_clock_audio(&self) -> bool {
2323        self.clock_audio
2324    }
2325
2326    /// The stored Advanced configuration handle, if any.
2327    #[cfg(feature = "advanced")]
2328    #[must_use]
2329    pub fn configured_config(&self) -> Option<&crate::advanced::AdvancedConfig> {
2330        self.config.as_ref()
2331    }
2332
2333    /// A sender advertised as `name`, which the SDK chooses when it is empty,
2334    /// with the default settings.
2335    pub fn new(name: impl Into<String>) -> Self {
2336        Self {
2337            name: name.into(),
2338            groups: None,
2339            clock_video: true,
2340            clock_audio: true,
2341            #[cfg(feature = "advanced")]
2342            config: None,
2343        }
2344    }
2345
2346    /// Set a non-empty list of discovery groups the sender is advertised in,
2347    /// replacing the NDI configuration. Use [`Self::clear_groups`] to inherit
2348    /// the configuration. Creation refuses empty elements and elements
2349    /// containing a comma or NUL.
2350    #[must_use]
2351    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
2352        self.groups = Some(groups.into_iter().map(Into::into).collect());
2353        self
2354    }
2355
2356    /// Set whether video submissions are paced to the frame rate, rather
2357    /// than returning at once.
2358    #[must_use]
2359    pub fn clock_video(mut self, clock: bool) -> Self {
2360        self.clock_video = clock;
2361        self
2362    }
2363
2364    /// Set whether audio submissions are paced to the sample rate, rather
2365    /// than returning at once.
2366    #[must_use]
2367    pub fn clock_audio(mut self, clock: bool) -> Self {
2368        self.clock_audio = clock;
2369        self
2370    }
2371
2372    /// Create the sender with this per-instance Advanced SDK configuration,
2373    /// which it keeps for as long as it lives.
2374    ///
2375    /// [`Sender::new`] then needs an Advanced runtime, and a build with the
2376    /// Advanced SDK.
2377    #[cfg(feature = "advanced")]
2378    #[must_use]
2379    pub fn config(mut self, config: crate::advanced::AdvancedConfig) -> Self {
2380        self.config = Some(config);
2381        self
2382    }
2383}
2384
2385#[cfg(test)]
2386mod tests {
2387    use super::*;
2388    use crate::RuntimeFeature;
2389
2390    mod shared_ownership {
2391        include!("sender_shared_tests.rs");
2392    }
2393
2394    #[test]
2395    fn metadata_capture_lease_moves_threads_and_retains_the_wait_budget() {
2396        let gate = SenderMetadataGate::default();
2397        let lease = gate
2398            .acquire_until(Instant::now() + Duration::from_secs(1))
2399            .unwrap();
2400        std::thread::scope(|scope| {
2401            let (release, released) = std::sync::mpsc::channel();
2402            let worker = scope.spawn(move || {
2403                released.recv().unwrap();
2404                drop(lease);
2405            });
2406            let started = Instant::now();
2407            // parking_lot_core 0.9.12's Linux futex ABI is rejected by Miri
2408            // (Amanieu/parking_lot#542). An expired deadline still exercises
2409            // occupied refusal and queue cleanup; native runs cover timed parking.
2410            #[cfg(miri)]
2411            let end = started;
2412            #[cfg(not(miri))]
2413            let end = started + Duration::from_millis(25);
2414            assert!(gate.acquire_until(end).is_none());
2415            #[cfg(not(miri))]
2416            assert!(started.elapsed() >= Duration::from_millis(20));
2417            release.send(()).unwrap();
2418            worker.join().unwrap();
2419            let (_, allocations) = crate::test_alloc::allocation_count(|| {
2420                let lease = gate.acquire_until(Instant::now()).unwrap();
2421                drop(lease);
2422            });
2423            assert_eq!(allocations, 0, "capture permits must not allocate");
2424        });
2425    }
2426
2427    #[test]
2428    fn metadata_capture_lease_releases_during_unwind() {
2429        fn traits<T: Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
2430        traits::<SenderMetadataLease<'static>>();
2431        let gate = SenderMetadataGate::default();
2432        let panic = std::panic::catch_unwind(|| {
2433            let _lease = gate.acquire_until(Instant::now()).unwrap();
2434            panic!("unwind with an outstanding metadata lease");
2435        });
2436        assert!(panic.is_err());
2437        assert!(gate.acquire_until(Instant::now()).is_some());
2438    }
2439
2440    fn check_metadata_free_before_capture_release(path: &str) {
2441        use crate::capture::{Guard, SenderMetadataFree, SenderMetadataInstance};
2442        use std::sync::{atomic::AtomicUsize, OnceLock};
2443
2444        struct Observation {
2445            gate: SenderMetadataGate,
2446            frees: AtomicUsize,
2447            released_early: AtomicBool,
2448        }
2449
2450        unsafe fn observe_free(instance: SenderMetadataInstance, _: &mut NDIlib_metadata_frame_t) {
2451            // SAFETY: the synthetic instance borrows this observation until
2452            // the metadata guard has invoked its sole release callback.
2453            let observation = unsafe { &*instance.instance.cast::<Observation>() };
2454            observation.frees.fetch_add(1, Ordering::Relaxed);
2455            observation.released_early.store(
2456                observation.gate.acquire_until(Instant::now()).is_some(),
2457                Ordering::Relaxed,
2458            );
2459        }
2460
2461        static TABLE: OnceLock<sys::SenderMetadata> = OnceLock::new();
2462        let table = TABLE.get_or_init(|| {
2463            // Synthetic release uses observe_free, never these placeholder
2464            // entry points. The table only completes the instance's type.
2465            sys::SenderMetadata::load(&sys::table::ExportsWhere(|_| true))
2466                .unwrap()
2467                .unwrap()
2468        });
2469        let observation = Observation {
2470            gate: SenderMetadataGate::default(),
2471            frees: AtomicUsize::new(0),
2472            released_early: AtomicBool::new(false),
2473        };
2474        let text = if path == "validation" {
2475            c"\xff"
2476        } else {
2477            c"<held/>"
2478        };
2479        let raw = NDIlib_metadata_frame_t {
2480            length: text.to_bytes().len() as i32,
2481            p_data: text.as_ptr().cast_mut(),
2482            timecode: 0,
2483        };
2484        let lease = observation.gate.acquire_until(Instant::now()).unwrap();
2485        // SAFETY: the observation and terminated text outlive the guard; the
2486        // synthetic callback observes release and does not free either one.
2487        let guard = unsafe {
2488            Guard::<SenderMetadataFree>::with_test_free(
2489                SenderMetadataInstance {
2490                    instance: (&observation as *const Observation).cast_mut().cast(),
2491                    free: table.NDIlib_send_free_metadata,
2492                },
2493                raw,
2494                observe_free,
2495            )
2496        };
2497        let frame = MetadataFrameRef::from_sender(guard, lease);
2498        match path {
2499            "validation" => assert!(matches!(frame, Err(Error::InvalidUtf8(_)))),
2500            "unwind" => {
2501                let frame = frame.unwrap();
2502                let panic = std::panic::catch_unwind(|| {
2503                    let _frame = frame;
2504                    panic!("unwind while upstream metadata is borrowed");
2505                });
2506                assert!(panic.is_err());
2507            }
2508            "normal" => drop(frame.unwrap()),
2509            _ => panic!("unknown metadata guard test path"),
2510        }
2511        assert_eq!(observation.frees.load(Ordering::Relaxed), 1);
2512        assert!(!observation.released_early.load(Ordering::Relaxed));
2513        assert!(observation.gate.acquire_until(Instant::now()).is_some());
2514    }
2515
2516    #[test]
2517    fn sender_metadata_guard_frees_before_releasing_capture() {
2518        check_metadata_free_before_capture_release("normal");
2519    }
2520
2521    #[test]
2522    fn sender_metadata_validation_failure_frees_before_releasing_capture() {
2523        check_metadata_free_before_capture_release("validation");
2524    }
2525
2526    #[test]
2527    fn sender_metadata_unwind_frees_before_releasing_capture() {
2528        check_metadata_free_before_capture_release("unwind");
2529    }
2530
2531    #[test]
2532    fn initialized_extents_preserve_direct_sending_for_every_format_and_scan() {
2533        use crate::frames::Initialized;
2534        for format in PixelFormat::ALL {
2535            for scan in ScanType::ALL {
2536                for height in [4, 6] {
2537                    let owned = VideoFrame::builder()
2538                        .resolution(18, height)
2539                        .pixel_format(format)
2540                        .scan_type(scan)
2541                        .build()
2542                        .unwrap();
2543                    assert!(owned.can_send_direct(), "owned {format:?} {scan:?}");
2544                    assert_eq!(owned.initialized(), Initialized::PackedSendReady);
2545                    assert_eq!(
2546                        <&VideoFrame as VideoParts>::initialized(&&owned),
2547                        owned.initialized()
2548                    );
2549                    for padding in [0, 8] {
2550                        let stride = format.line_stride_bytes(18).unwrap() + padding;
2551                        let layout = ValidatedVideoLayout::new_uncompressed(
2552                            format,
2553                            18,
2554                            height,
2555                            Some(stride),
2556                        )
2557                        .unwrap();
2558                        let room = send_room(&layout, scan);
2559                        for extra in [0, room] {
2560                            let bytes = vec![0; layout.data_len_bytes() + extra];
2561                            for allow in [false, true] {
2562                                let borrowed =
2563                                    BorrowedVideoFrame::builder(&bytes, 18, height, format)
2564                                        .line_stride_bytes(stride)
2565                                        .scan_type(scan)
2566                                        .allow_send_from_padding_and_tail(allow)
2567                                        .build()
2568                                        .unwrap();
2569                                let expected = room == 0
2570                                    || (allow && layout.trailing_padding() + extra >= room);
2571                                assert_eq!(borrowed.sends_in_place(), expected,
2572                                    "{format:?} {scan:?} height={height} padding={padding} extra={extra} allow={allow}");
2573                                assert_eq!(borrowed.sends_in_place(), expected);
2574                                assert_eq!(
2575                                    <&BorrowedVideoFrame<'_> as VideoParts>::initialized(
2576                                        &&borrowed
2577                                    ),
2578                                    borrowed.initialized()
2579                                );
2580                                let mut storage = VideoStaging::default();
2581                                let packed = crate::pixels::stage_video(&borrowed, &mut storage);
2582                                assert!(packed.can_send_direct(), "staging {format:?} {scan:?}");
2583                            }
2584                        }
2585                    }
2586                }
2587            }
2588        }
2589    }
2590
2591    #[test]
2592    fn owned_send_keeps_allocation_and_capacity_when_lending() {
2593        use crate::frames::descriptor_tests::assert_extent;
2594        let mut pixels = Vec::with_capacity(18 * 6 * 2 + 1024);
2595        pixels.resize(18 * 6 * 2, 128);
2596        let capacity = pixels.capacity();
2597        let frame = VideoFrame::builder()
2598            .resolution(18, 6)
2599            .pixel_format(PixelFormat::Uyvy)
2600            .scan_type(ScanType::Interlaced)
2601            .data(pixels)
2602            .build()
2603            .unwrap();
2604        let extent = frame.data().len() + frame.tail_room();
2605        let pointer = frame.data().as_ptr();
2606        let mut staging = VideoStaging::default();
2607        let raw = PreparedVideo::new(&frame, &mut staging).raw;
2608        assert_extent(&raw, pointer, extent);
2609        assert!(staging.is_none());
2610        let mut owned = Sendable::for_test(frame);
2611        let (lent, allocations) =
2612            crate::test_alloc::allocation_count(|| in_flight::Lend::lend(&mut owned));
2613        assert_eq!(allocations, 0);
2614        assert_extent(lent.descriptor(), pointer, extent);
2615        assert_eq!(owned.into_frame().into_data().capacity(), capacity);
2616    }
2617
2618    #[test]
2619    fn captured_video_sending_uses_initialized_active_rows_and_preserves_descriptors() {
2620        use crate::capture::{FrameSyncVideoFree, Guard, VideoKind};
2621        use crate::{FrameSyncVideoRef, VideoFrameRef};
2622        use std::{
2623            mem::MaybeUninit,
2624            sync::atomic::{AtomicUsize, Ordering},
2625        };
2626
2627        fn verify(source: &(impl VideoSource + ?Sized), original: &NDIlib_video_frame_v2_t) {
2628            let expected = source.owned_copy();
2629            let mut staging = VideoStaging::default();
2630            let (raw, allocations) = crate::test_alloc::allocation_count(|| {
2631                PreparedVideo::new(source, &mut staging).raw
2632            });
2633            let direct = source.sends_in_place();
2634            assert_eq!(allocations, usize::from(!direct));
2635            assert_eq!(raw.p_metadata, original.p_metadata);
2636            assert_eq!(raw.timestamp, original.timestamp);
2637            assert_eq!(raw.timecode, original.timecode);
2638            assert_eq!(raw.picture_aspect_ratio, original.picture_aspect_ratio);
2639            assert_eq!(raw.frame_format_type, original.frame_format_type);
2640            assert_eq!(
2641                (raw.xres, raw.yres, raw.FourCC),
2642                (original.xres, original.yres, original.FourCC)
2643            );
2644            assert_eq!(
2645                (raw.frame_rate_N, raw.frame_rate_D),
2646                (original.frame_rate_N, original.frame_rate_D)
2647            );
2648            if direct {
2649                assert_eq!(raw.p_data, original.p_data);
2650                assert!(staging.bytes().is_empty());
2651            } else {
2652                assert_eq!(raw.p_data, staging.as_ptr().cast_mut());
2653                assert_ne!(raw.p_data, original.p_data);
2654                assert_eq!(staging.bytes(), expected.data());
2655                assert!(staging.room_bytes().iter().all(|&byte| byte == 0));
2656                assert_eq!(
2657                    staging.room(),
2658                    send_room(
2659                        source.layout().packed().as_layout(),
2660                        source.header().scan_type()
2661                    )
2662                );
2663            }
2664            let pointer = raw.p_data;
2665            let (next, allocations) = crate::test_alloc::allocation_count(|| {
2666                PreparedVideo::new(source, &mut staging).raw
2667            });
2668            assert_eq!(allocations, 0);
2669            assert_eq!(next.p_data, pointer);
2670        }
2671
2672        for format in PixelFormat::ALL {
2673            for scan in ScanType::ALL {
2674                for padding in [0, 8] {
2675                    let stride = format.line_stride_bytes(4).unwrap() + padding;
2676                    let len = ValidatedVideoLayout::new_uncompressed(format, 4, 6, Some(stride))
2677                        .unwrap()
2678                        .data_len_bytes();
2679                    let initialized = vec![71; len];
2680                    let template = BorrowedVideoFrame::builder(&initialized, 4, 6, format)
2681                        .line_stride_bytes(stride)
2682                        .scan_type(scan)
2683                        .frame_rate(FrameRate::new(30_000, 1_001).unwrap())
2684                        .picture_aspect_ratio(PictureAspectRatio::new(1.25).unwrap())
2685                        .timecode(Timecode::from_ticks(12345))
2686                        .metadata(c"<captured/>")
2687                        .build()
2688                        .unwrap();
2689                    // Only active rows are initialized. Reading any capture padding
2690                    // or unproven SDK tail is invalid under Miri as well as Rust.
2691                    let mut storage = vec![MaybeUninit::<u8>::uninit(); len];
2692                    for plane in template.planes() {
2693                        for row in plane.rows() {
2694                            let start = row.as_ptr() as usize - initialized.as_ptr() as usize;
2695                            for byte in &mut storage[start..start + row.len()] {
2696                                byte.write(71);
2697                            }
2698                        }
2699                    }
2700                    let raw = NDIlib_video_frame_v2_t {
2701                        p_data: storage.as_mut_ptr().cast(),
2702                        timestamp: 912,
2703                        ..template.to_raw()
2704                    };
2705                    let frees = AtomicUsize::new(0);
2706                    let instance = (&frees as *const AtomicUsize).cast_mut().cast();
2707                    // SAFETY: each guard borrows the still-live storage and static
2708                    // metadata. Its callback counts release and frees no memory.
2709                    let receiver = unsafe {
2710                        VideoFrameRef::new(Guard::<VideoKind>::with_test_free(
2711                            instance,
2712                            raw,
2713                            |instance, _| {
2714                                (*(instance as *const AtomicUsize)).fetch_add(1, Ordering::SeqCst);
2715                            },
2716                        ))
2717                    }
2718                    .unwrap();
2719                    let framesync = unsafe {
2720                        FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
2721                            instance.cast(),
2722                            raw,
2723                            |instance, _| {
2724                                (*(instance as *const AtomicUsize)).fetch_add(1, Ordering::SeqCst);
2725                            },
2726                        ))
2727                    }
2728                    .unwrap();
2729                    let eligible = padding == 0 && send_room(receiver.layout(), scan) == 0;
2730                    assert_eq!(
2731                        receiver.initialized(),
2732                        crate::frames::Initialized::ActiveRows
2733                    );
2734                    assert_eq!(
2735                        framesync.initialized(),
2736                        crate::frames::Initialized::ActiveRows
2737                    );
2738                    assert_eq!(
2739                        receiver.sends_in_place(),
2740                        eligible,
2741                        "{format:?} {scan:?} padding={padding}"
2742                    );
2743                    verify(&receiver, &raw);
2744                    verify(&framesync, &raw);
2745                    assert_eq!(frees.load(Ordering::SeqCst), 0);
2746                    drop(receiver);
2747                    drop(framesync);
2748                    assert_eq!(frees.load(Ordering::SeqCst), 2);
2749                }
2750            }
2751        }
2752    }
2753
2754    #[test]
2755    fn padded_prepared_and_copied_descriptors_fit_their_own_storage() {
2756        use crate::{capture::Guard, frames::descriptor_tests::assert_extent, VideoFrameRef};
2757        for (format, stride) in [
2758            (PixelFormat::Bgra, 512),
2759            (PixelFormat::Uyvy, 256),
2760            (PixelFormat::P216, 256),
2761        ] {
2762            let planes = if format == PixelFormat::P216 { 2 } else { 1 };
2763            let storage = vec![0u8; stride * 32 * planes];
2764            let frame = BorrowedVideoFrame::builder(&storage, 64, 32, format)
2765                .line_stride_bytes(stride)
2766                .build()
2767                .unwrap();
2768            // Captured rows are padded and need staging even for BGRA.
2769            // SAFETY: the guard borrows the initialized, still-live storage;
2770            // the synthetic release callback owns and frees nothing.
2771            let captured = unsafe {
2772                VideoFrameRef::new(Guard::with_test_free(
2773                    ptr::null_mut(),
2774                    frame.video_descriptor(),
2775                    |_, _| {},
2776                ))
2777            }
2778            .unwrap();
2779            let mut staging = VideoStaging::default();
2780            let prepared = PreparedVideo::authorized(Sendable::for_test(&captured), &mut staging);
2781            let raw = prepared.raw;
2782            assert_ne!(raw.p_data.cast_const(), storage.as_ptr());
2783            assert_extent(&raw, staging.as_ptr(), staging.len() + staging.room());
2784            // This is the packed copy submitted by submit_video_copy;
2785            // its authorization is still that of the padded source.
2786            let mut owned = Sendable::for_test(&frame).copied(None);
2787            #[allow(irrefutable_let_patterns)]
2788            let in_flight::Lent::Frame(raw) = in_flight::Lend::lend(&mut owned) else {
2789                panic!("pixels")
2790            };
2791            assert_eq!(
2792                unsafe { raw.__bindgen_anon_1.line_stride_in_bytes } as usize,
2793                64 * if format == PixelFormat::Bgra { 4 } else { 2 }
2794            );
2795            assert_extent(
2796                &raw,
2797                owned.data().as_ptr(),
2798                owned.data().len() + owned.tail_room(),
2799            );
2800            if let Some(mut sender) = test_sender() {
2801                sender.submit_video_copy(&frame).unwrap();
2802                {
2803                    let state = sender.native.video.test_state();
2804                    let retained = state.in_flight.frame().unwrap();
2805                    assert_extent(
2806                        &retained.as_test_raw(),
2807                        retained.data().as_ptr(),
2808                        retained.data().len() + retained.tail_room(),
2809                    );
2810                }
2811                sender.reclaim_video();
2812            }
2813        }
2814    }
2815
2816    fn test_owned_frame(value: u8) -> VideoFrame {
2817        let mut frame = VideoFrame::builder()
2818            .resolution(16, 16)
2819            .pixel_format(PixelFormat::Bgra)
2820            .frame_rate(FrameRate::new(30, 1).unwrap())
2821            .metadata(format!("<frame value='{value}'/>"))
2822            .build()
2823            .unwrap();
2824        frame.data_mut().fill(value);
2825        frame
2826    }
2827
2828    /// A sender on the real runtime, or `None` when the test must be skipped.
2829    fn test_sender() -> Option<Sender> {
2830        use std::sync::atomic::{AtomicUsize, Ordering};
2831        static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
2832        let name = crate::test_support::unique_name(&format!(
2833            "Owned async regression {}",
2834            NEXT_ID.fetch_add(1, Ordering::Relaxed)
2835        ));
2836        let ndi = crate::test_support::ndi()?;
2837        Some(
2838            Sender::new(
2839                &ndi,
2840                &SenderOptions::new(name)
2841                    .clock_video(false)
2842                    .clock_audio(false),
2843            )
2844            .unwrap(),
2845        )
2846    }
2847
2848    #[test]
2849    fn metadata_send_methods_reuse_validated_text_with_sdk() {
2850        let Some(sender) = test_sender() else {
2851            return;
2852        };
2853        let frame = MetadataFrame::new("<ndi_text>é</ndi_text>")
2854            .unwrap()
2855            .with_timecode(Timecode::from_ticks(42));
2856        let expected_ptr = frame.metadata_raw().p_data;
2857        for _ in 0..3 {
2858            sender.send_metadata(&frame);
2859            assert_eq!(frame.metadata_raw().p_data, expected_ptr);
2860        }
2861        sender.add_connection_metadata(&frame);
2862        sender.clear_connection_metadata();
2863    }
2864
2865    #[test]
2866    fn owned_async_recycles_original_pixel_and_metadata_allocations() {
2867        let Some(mut sender) = test_sender() else {
2868            return;
2869        };
2870        let first = test_owned_frame(11);
2871        let pixels = first.data().as_ptr();
2872        let metadata = first.metadata_cstr().unwrap().as_ptr();
2873        assert!(sender.submit_video(first).unwrap().is_none());
2874        {
2875            let video = sender.native.video.test_state();
2876            let Some(frame) = video.in_flight.frame() else {
2877                panic!("missing owned frame")
2878            };
2879            assert_eq!(frame.as_test_raw().p_data, pixels as *mut u8);
2880            assert_eq!(frame.as_test_raw().p_metadata, metadata);
2881        }
2882        let second = test_owned_frame(22);
2883        let second_pixels = second.data().as_ptr();
2884        let recycled = sender.submit_video(second).unwrap().unwrap();
2885        assert_eq!(recycled.data().as_ptr(), pixels);
2886        assert_eq!(recycled.metadata_cstr().unwrap().as_ptr(), metadata);
2887        assert_eq!(recycled.metadata(), Some("<frame value='11'/>"));
2888        let final_frame = sender.reclaim_video().unwrap();
2889        assert_eq!(final_frame.data().as_ptr(), second_pixels);
2890        assert!(sender.reclaim_video().is_none());
2891    }
2892
2893    #[test]
2894    fn synchronous_send_of_a_padded_borrowed_frame_allocates_nothing() {
2895        let Some(sender) = test_sender() else {
2896            return;
2897        };
2898        // 16 pixels per row, padded to a 96-byte stride.
2899        let data = vec![5u8; 96 * 16];
2900        let metadata = c"<padded/>";
2901        let borrowed = BorrowedVideoFrame::builder(&data, 16, 16, PixelFormat::Bgra)
2902            .line_stride_bytes(96)
2903            .metadata(metadata)
2904            .build()
2905            .unwrap();
2906        // Warm any lazily created SDK or runtime state before counting.
2907        sender.send_video(&borrowed).unwrap();
2908        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2909            sender.send_video(&borrowed).unwrap();
2910            // Lint allowed: the by-reference form is what is under test.
2911            #[allow(clippy::needless_borrows_for_generic_args)]
2912            sender.send_video(&borrowed).unwrap();
2913        });
2914        assert_eq!(allocations, 0);
2915        // An owned frame is lent the same way.
2916        let owned = test_owned_frame(3);
2917        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2918            sender.send_video(&owned).unwrap();
2919        });
2920        assert_eq!(allocations, 0);
2921    }
2922
2923    #[test]
2924    fn split_video_submissions_reuse_storage_without_allocating() {
2925        let Some(mut sender) = test_sender() else {
2926            return;
2927        };
2928        let source = test_owned_frame(3);
2929        let (mut video, shared) = sender.split();
2930        video.submit_video_copy(&source).unwrap();
2931        video.submit_video_copy(&source).unwrap();
2932        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2933            for _ in 0..4 {
2934                video.submit_video_copy(&source).unwrap();
2935            }
2936        });
2937        assert_eq!(allocations, 0);
2938        let spare = source.clone();
2939        let (recovered, allocations) =
2940            crate::test_alloc::allocation_count(|| video.submit_video(spare).unwrap());
2941        assert_eq!(allocations, 0);
2942        assert_eq!(recovered.unwrap().data(), source.data());
2943        shared.flush_video();
2944        assert_eq!(video.reclaim_video().unwrap().data(), source.data());
2945        assert!(video.reclaim_video().is_none());
2946    }
2947
2948    #[test]
2949    fn copied_async_sends_reuse_pixels_and_metadata_after_warmup() {
2950        let Some(mut sender) = test_sender() else {
2951            return;
2952        };
2953        let pixels = vec![128; 16 * 16 * 4];
2954        let source = BorrowedVideoFrame::builder(&pixels, 16, 16, PixelFormat::Bgra)
2955            .frame_rate(FrameRate::new(30, 1).unwrap())
2956            .picture_aspect_ratio(PictureAspectRatio::new(1.25).unwrap())
2957            .timecode(Timecode::from_ticks(1234))
2958            .metadata(c"<metadata/>")
2959            .build()
2960            .unwrap();
2961        let shorter = BorrowedVideoFrame::builder(&pixels, 16, 16, PixelFormat::Bgra)
2962            .metadata(c"<short/>")
2963            .build()
2964            .unwrap();
2965        sender.submit_video_copy(&source).unwrap();
2966        sender.submit_video_copy(&source).unwrap();
2967        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2968            for _ in 0..4 {
2969                sender.submit_video_copy(&shorter).unwrap();
2970                sender.submit_video_copy(&shorter).unwrap();
2971                sender.submit_video_copy(&source).unwrap();
2972                sender.submit_video_copy(&source).unwrap();
2973            }
2974        });
2975        assert_eq!(allocations, 0);
2976        let copy = sender.reclaim_video().unwrap();
2977        assert_eq!(copy.data(), pixels);
2978        assert_eq!(copy.frame_rate(), source.frame_rate());
2979        assert_eq!(copy.picture_aspect_ratio().get(), 1.25);
2980        assert_eq!(copy.timecode(), Timecode::from_ticks(1234));
2981        assert_eq!(copy.metadata(), Some("<metadata/>"));
2982        assert!(sender.native.video.test_state().spare.is_none());
2983        assert!(sender.reclaim_video().is_none());
2984    }
2985
2986    #[test]
2987    fn copied_async_sends_reuse_metadata_across_absent_and_empty_frames() {
2988        let Some(mut sender) = test_sender() else {
2989            return;
2990        };
2991        let pixels = vec![128; 16 * 16 * 4];
2992        let absent = BorrowedVideoFrame::builder(&pixels, 16, 16, PixelFormat::Bgra)
2993            .build()
2994            .unwrap();
2995        let empty = BorrowedVideoFrame::builder(&pixels, 16, 16, PixelFormat::Bgra)
2996            .metadata(c"")
2997            .build()
2998            .unwrap();
2999        let present = BorrowedVideoFrame::builder(&pixels, 16, 16, PixelFormat::Bgra)
3000            .metadata(c"<metadata/>")
3001            .build()
3002            .unwrap();
3003        sender.submit_video_copy(&present).unwrap();
3004        sender.submit_video_copy(&present).unwrap();
3005        // Exclusive async sends do not lock the state. Warm this test's
3006        // inspection lock, whose first use may allocate on some platforms.
3007        drop(sender.native.video.test_state());
3008        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3009            for _ in 0..4 {
3010                for (source, expected) in [
3011                    (&absent, None),
3012                    (&empty, Some("")),
3013                    (&present, Some("<metadata/>")),
3014                ] {
3015                    sender.submit_video_copy(source).unwrap();
3016                    let state = sender.native.video.test_state();
3017                    assert_eq!(state.in_flight.frame().unwrap().metadata(), expected);
3018                }
3019            }
3020        });
3021        assert_eq!(allocations, 0);
3022        assert_eq!(
3023            sender.reclaim_video().unwrap().metadata(),
3024            Some("<metadata/>")
3025        );
3026    }
3027
3028    #[test]
3029    fn copied_async_storage_grows_once_per_buffer_then_reuses_capacity() {
3030        let Some(mut sender) = test_sender() else {
3031            return;
3032        };
3033        let small_pixels = vec![128; 16 * 16 * 4];
3034        let large_pixels = vec![128; 64 * 16 * 4];
3035        let small = BorrowedVideoFrame::builder(&small_pixels, 16, 16, PixelFormat::Bgra)
3036            .metadata(c"<a/>")
3037            .build()
3038            .unwrap();
3039        let large = BorrowedVideoFrame::builder(&large_pixels, 64, 16, PixelFormat::Bgra)
3040            .metadata(c"<a/>")
3041            .build()
3042            .unwrap();
3043        let metadata = CString::new("x".repeat(256)).unwrap();
3044        let longer = BorrowedVideoFrame::builder(&large_pixels, 64, 16, PixelFormat::Bgra)
3045            .metadata(&metadata)
3046            .build()
3047            .unwrap();
3048        sender.submit_video_copy(&small).unwrap();
3049        sender.submit_video_copy(&small).unwrap();
3050        // Each of the two reusable pixel buffers grows once, with no new
3051        // metadata storage needed. No further growth is needed afterward.
3052        for _ in 0..2 {
3053            let ((), allocations) = crate::test_alloc::allocation_count(|| {
3054                sender.submit_video_copy(&large).unwrap();
3055            });
3056            assert_eq!(allocations, 1);
3057        }
3058        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3059            sender.submit_video_copy(&large).unwrap();
3060            sender.submit_video_copy(&large).unwrap();
3061        });
3062        assert_eq!(allocations, 0);
3063        // Longer metadata likewise grows each reusable metadata buffer once.
3064        for _ in 0..2 {
3065            let ((), allocations) = crate::test_alloc::allocation_count(|| {
3066                sender.submit_video_copy(&longer).unwrap();
3067            });
3068            assert_eq!(allocations, 1);
3069        }
3070        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3071            for _ in 0..4 {
3072                sender.submit_video_copy(&longer).unwrap();
3073                sender.submit_video_copy(&large).unwrap();
3074            }
3075        });
3076        assert_eq!(allocations, 0);
3077        sender.reclaim_video();
3078    }
3079
3080    #[test]
3081    fn owned_video_preparation_preserves_storage_for_every_scan_type() {
3082        for format in PixelFormat::ALL {
3083            for height in [4, 6] {
3084                for scan in ScanType::ALL {
3085                    let frame = VideoFrame::builder()
3086                        .resolution(18, height)
3087                        .pixel_format(format)
3088                        .scan_type(scan)
3089                        .metadata("<owned/>")
3090                        .build()
3091                        .unwrap();
3092                    let mut staging = VideoStaging::default();
3093                    let (raw, allocations) = crate::test_alloc::allocation_count(|| {
3094                        PreparedVideo::new(&frame, &mut staging).raw
3095                    });
3096                    assert_eq!(allocations, 0, "{format:?} {height} {scan:?}");
3097                    assert_eq!(raw.p_data.cast_const(), frame.data().as_ptr());
3098                    assert_eq!(raw.p_metadata, frame.as_test_raw().p_metadata);
3099                    assert_eq!(raw.frame_format_type, scan.to_sdk());
3100                    assert!(staging.bytes().is_empty());
3101                }
3102            }
3103        }
3104    }
3105
3106    #[test]
3107    fn default_yuv_staging_ignores_all_caller_padding_and_tail_room() {
3108        for format in [PixelFormat::Uyvy, PixelFormat::Uyva] {
3109            if format.send_tail_room() == 0 {
3110                continue;
3111            }
3112            for scan in [
3113                ScanType::Progressive,
3114                ScanType::Interlaced,
3115                ScanType::Field1,
3116            ] {
3117                for stride in [36, 40, 164] {
3118                    let layout =
3119                        ValidatedVideoLayout::new_uncompressed(format, 18, 6, Some(stride))
3120                            .unwrap();
3121                    let len = layout.data_len_bytes();
3122                    let room = send_room(&layout, scan);
3123                    let mut staging = VideoStaging::default();
3124                    let mut expected = None;
3125                    for extra in [0, room] {
3126                        for offered in [0, room] {
3127                            for padding in [16, 235] {
3128                                let mut buffer = vec![padding; len + extra + offered];
3129                                let ranges: Vec<_> = {
3130                                    let frame = BorrowedVideoFrame::builder(&buffer, 18, 6, format)
3131                                        .line_stride_bytes(stride)
3132                                        .build()
3133                                        .unwrap();
3134                                    frame
3135                                        .planes()
3136                                        .flat_map(|plane| {
3137                                            plane
3138                                                .rows()
3139                                                .map(|row| {
3140                                                    let start = row.as_ptr() as usize
3141                                                        - buffer.as_ptr() as usize;
3142                                                    start..start + row.len()
3143                                                })
3144                                                .collect::<Vec<_>>()
3145                                        })
3146                                        .collect()
3147                                };
3148                                for range in ranges {
3149                                    buffer[range].fill(128);
3150                                }
3151                                let builder = BorrowedVideoFrame::builder(&buffer, 18, 6, format)
3152                                    .line_stride_bytes(stride)
3153                                    .scan_type(scan);
3154                                let frame = builder.build().unwrap();
3155                                assert!(!frame.sends_in_place());
3156                                let raw = PreparedVideo::new(&frame, &mut staging).raw;
3157                                assert_eq!(
3158                                    unsafe { raw.__bindgen_anon_1.line_stride_in_bytes },
3159                                    36
3160                                );
3161                                assert_eq!(raw.frame_format_type, scan.to_sdk());
3162                                assert_eq!(staging.bytes(), frame.to_owned().data());
3163                                if let Some(expected) = &expected {
3164                                    assert_eq!(staging.bytes(), expected);
3165                                } else {
3166                                    expected = Some(staging.bytes().to_vec());
3167                                }
3168                                assert_eq!(
3169                                    staging.room(),
3170                                    send_room(layout.packed().as_layout(), scan)
3171                                );
3172                                assert!(staging.room_bytes().iter().all(|&byte| byte == 0));
3173                                let address = staging.as_ptr();
3174                                let ((), allocations) = crate::test_alloc::allocation_count(|| {
3175                                    let _ = PreparedVideo::new(&frame, &mut staging);
3176                                });
3177                                assert_eq!(allocations, 0);
3178                                assert_eq!(staging.as_ptr(), address);
3179                            }
3180                        }
3181                    }
3182                }
3183            }
3184        }
3185    }
3186
3187    /// The room the SDK reads after a UYVY or UYVA frame is whatever follows
3188    /// the last pixel in the caller's buffer: the last row's padding, the
3189    /// bytes after the frame included in the builder's slice. Other
3190    /// formats need none, and an interlaced or single-field frame whose
3191    /// height is not a multiple of four needs two rows more.
3192    #[test]
3193    fn a_borrowed_frame_sends_in_place_when_room_follows_its_last_pixel() {
3194        let buffer = vec![0u8; 8192];
3195        let in_place = |format, height, scan, stride: Option<usize>, len: usize| {
3196            let mut builder = BorrowedVideoFrame::builder(&buffer[..len], 18, height, format)
3197                .scan_type(scan)
3198                .allow_send_from_padding_and_tail(true);
3199            if let Some(stride) = stride {
3200                builder = builder.line_stride_bytes(stride);
3201            }
3202            builder.build().unwrap().sends_in_place()
3203        };
3204        let progressive = ScanType::Progressive;
3205        // No format but UYVY and UYVA is read past.
3206        for format in PixelFormat::ALL {
3207            if !matches!(format, PixelFormat::Uyvy | PixelFormat::Uyva) {
3208                assert_eq!(format.send_tail_room(), 0, "{format:?}");
3209                let len = format.buffer_len(18, 4, None).unwrap();
3210                for scan in ScanType::ALL {
3211                    assert!(in_place(format, 4, scan, None, len), "{format:?} {scan:?}");
3212                }
3213            }
3214        }
3215        let (uyvy, uyva) = (PixelFormat::Uyvy, PixelFormat::Uyva);
3216        let room = uyvy.send_tail_room();
3217        assert_eq!(room, uyva.send_tail_room());
3218        if room == 0 {
3219            // The SDK reads frames exactly here: nothing needs room.
3220            for scan in ScanType::ALL {
3221                assert!(in_place(uyvy, 6, scan, None, 216), "{scan:?}");
3222                assert!(in_place(uyva, 6, scan, None, 324), "{scan:?}");
3223            }
3224            return;
3225        }
3226        assert_eq!(room, 64);
3227        // Packed rows of 36 bytes, four rows: the frame is 144 bytes.
3228        assert!(!in_place(uyvy, 4, progressive, None, 144));
3229        assert!(!in_place(uyvy, 4, progressive, None, 144 + 63));
3230        assert!(in_place(uyvy, 4, progressive, None, 144 + 64));
3231        // Row padding counts: 64 bytes of it, or 60 and four more bytes.
3232        assert!(in_place(uyvy, 4, progressive, Some(100), 400));
3233        assert!(!in_place(uyvy, 4, progressive, Some(96), 384));
3234        assert!(!in_place(uyvy, 4, progressive, Some(96), 384 + 3));
3235        assert!(in_place(uyvy, 4, progressive, Some(96), 384 + 4));
3236
3237        // UYVA ends with its alpha plane, whose rows are half the stride.
3238        assert!(!in_place(uyva, 4, progressive, None, 216));
3239        assert!(!in_place(uyva, 4, progressive, None, 216 + 63));
3240        assert!(in_place(uyva, 4, progressive, None, 216 + 64));
3241        assert!(in_place(uyva, 4, progressive, Some(164), 984));
3242        assert!(!in_place(uyva, 4, progressive, Some(160), 960));
3243        assert!(in_place(uyva, 4, progressive, Some(160), 960 + 2));
3244        // Interlaced and single-field frames need the same room when their
3245        // height is a multiple of four, and two line strides more when not.
3246        for scan in [ScanType::Interlaced, ScanType::Field0, ScanType::Field1] {
3247            assert!(!in_place(uyvy, 4, scan, None, 144 + 63), "{scan:?}");
3248            assert!(in_place(uyvy, 4, scan, None, 144 + 64), "{scan:?}");
3249            // Six rows of 36 bytes: 216 bytes, and 72 + 64 of room.
3250            assert!(!in_place(uyvy, 6, scan, None, 216 + 64), "{scan:?}");
3251            assert!(!in_place(uyvy, 6, scan, None, 216 + 135), "{scan:?}");
3252            assert!(in_place(uyvy, 6, scan, None, 216 + 136), "{scan:?}");
3253            assert!(in_place(uyvy, 5, scan, None, 180 + 136), "{scan:?}");
3254            // With a 100-byte stride the rows are 200 bytes, less the 64 of
3255            // padding that already follow the last pixel.
3256            assert!(!in_place(uyvy, 6, scan, Some(100), 600 + 199), "{scan:?}");
3257            assert!(in_place(uyvy, 6, scan, Some(100), 600 + 200), "{scan:?}");
3258            assert!(in_place(uyva, 6, scan, None, 324 + 136), "{scan:?}");
3259            assert!(!in_place(uyva, 6, scan, None, 324 + 135), "{scan:?}");
3260        }
3261        assert!(in_place(uyvy, 6, progressive, None, 216 + 64));
3262    }
3263
3264    /// Miri must observe the SDK's complete read, including bytes outside the
3265    /// frame storage that were included in the builder's original borrow.
3266    #[test]
3267    fn borrowed_video_descriptor_can_read_the_whole_buffer() {
3268        for (height, scan) in [(4, ScanType::Progressive), (6, ScanType::Interlaced)] {
3269            let layout =
3270                ValidatedVideoLayout::new_uncompressed(PixelFormat::Uyvy, 18, height, None)
3271                    .unwrap();
3272            let data_len = layout.data_len_bytes();
3273            let read_len = data_len + send_room(&layout, scan);
3274            let buffer: Vec<u8> = (0..read_len).map(|index| (index % 251) as u8).collect();
3275            let frame = BorrowedVideoFrame::builder(&buffer, 18, height, PixelFormat::Uyvy)
3276                .scan_type(scan)
3277                .allow_send_from_padding_and_tail(true)
3278                .build()
3279                .unwrap();
3280            assert!(frame.sends_in_place());
3281            assert_eq!(frame.storage(), &buffer[..data_len]);
3282            assert_eq!(frame.data(), Some(&buffer[..data_len]));
3283            let mut staging = VideoStaging::default();
3284            let raw = PreparedVideo::new(&frame, &mut staging).raw;
3285            assert_eq!(raw.p_data.cast_const(), buffer.as_ptr());
3286            // SAFETY: the frame's whole buffer borrow covers the layout and
3287            // reported send room. This models the native SDK's actual read.
3288            let read = unsafe { std::slice::from_raw_parts(raw.p_data, read_len) };
3289            assert_eq!(read, buffer);
3290            assert!(staging.bytes().is_empty());
3291        }
3292    }
3293
3294    /// Staging packs active pixels, preserves headers and metadata, reuses
3295    /// its allocation, and leaves explicitly direct frames alone.
3296    #[test]
3297    fn staging_packs_active_pixels_preserves_headers_and_reuses_storage() {
3298        // 18 pixels per row, padded to a 40-byte stride.
3299        let buffer: Vec<u8> = (0..160).map(|i| i as u8).collect();
3300        let metadata = c"<staged/>";
3301        let frame = BorrowedVideoFrame::builder(&buffer, 18, 4, PixelFormat::Uyvy)
3302            .line_stride_bytes(40)
3303            .frame_rate(FrameRate::new(30000, 1001).unwrap())
3304            .picture_aspect_ratio(PictureAspectRatio::new(1.25).unwrap())
3305            .scan_type(ScanType::Interlaced)
3306            .timecode(Timecode::from_ticks(12345))
3307            .metadata(metadata)
3308            .build()
3309            .unwrap();
3310        if frame.sends_in_place() {
3311            // The SDK reads frames exactly here, so nothing is ever staged.
3312            assert_eq!(PixelFormat::Uyvy.send_tail_room(), 0);
3313            return;
3314        }
3315        let original = frame.to_raw();
3316
3317        let mut staging = VideoStaging::default();
3318        let raw = PreparedVideo::new(&frame, &mut staging).raw;
3319        assert_eq!(raw.p_data, staging.as_ptr().cast_mut());
3320        assert_ne!(raw.p_data, original.p_data);
3321        assert_eq!(staging.bytes(), frame.to_owned().data());
3322        assert_eq!(staging.room_bytes(), [0; 64]);
3323        assert_eq!(staging.capacity(), 144 + 64);
3324        // Everything but the pixel pointer describes the caller's frame.
3325        // SAFETY: both descriptors are uncompressed, so the union holds the stride.
3326        let strides = unsafe {
3327            (
3328                raw.__bindgen_anon_1.line_stride_in_bytes,
3329                original.__bindgen_anon_1.line_stride_in_bytes,
3330            )
3331        };
3332        assert_eq!(strides, (36, 40));
3333        assert_eq!(
3334            (raw.xres, raw.yres, raw.FourCC, raw.timecode, raw.p_metadata),
3335            (
3336                original.xres,
3337                original.yres,
3338                original.FourCC,
3339                original.timecode,
3340                original.p_metadata
3341            )
3342        );
3343        assert_eq!(
3344            (raw.frame_rate_N, raw.frame_rate_D, raw.frame_format_type),
3345            (
3346                original.frame_rate_N,
3347                original.frame_rate_D,
3348                original.frame_format_type
3349            )
3350        );
3351        assert_eq!(raw.picture_aspect_ratio, original.picture_aspect_ratio);
3352
3353        // The next frame of the same size reuses the allocation.
3354        let other = vec![9u8; 160];
3355        let next = BorrowedVideoFrame::builder(&other, 18, 4, PixelFormat::Uyvy)
3356            .line_stride_bytes(40)
3357            .build()
3358            .unwrap();
3359        let address = staging.as_ptr();
3360        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3361            let _ = PreparedVideo::new(&next, &mut staging);
3362        });
3363        assert_eq!(allocations, 0);
3364        assert_eq!(
3365            (staging.as_ptr(), staging.bytes()),
3366            (address, next.to_owned().data())
3367        );
3368
3369        // A frame with room is sent from its own buffer: nothing is staged.
3370        let roomy = vec![1u8; 160 + 64];
3371        let direct = BorrowedVideoFrame::builder(&roomy, 18, 4, PixelFormat::Uyvy)
3372            .allow_send_from_padding_and_tail(true)
3373            .line_stride_bytes(40)
3374            .build()
3375            .unwrap();
3376        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3377            let raw = PreparedVideo::new(&direct, &mut staging).raw;
3378            assert_eq!(raw.p_data.cast_const(), roomy.as_ptr());
3379        });
3380        assert_eq!(allocations, 0);
3381        assert_eq!(staging.bytes(), next.to_owned().data());
3382    }
3383
3384    /// A UYVY frame over a buffer that ends with it reaches the SDK from the
3385    /// sender's own copy, made in one buffer that later sends reuse.
3386    #[test]
3387    fn synchronous_send_copies_a_frame_without_room_into_one_reused_buffer() {
3388        let Some(sender) = test_sender() else {
3389            return;
3390        };
3391        let staging = |sender: &Sender| {
3392            let state = sender.native.video.test_state();
3393            (
3394                state.staging.as_ptr(),
3395                state.staging.bytes().to_vec(),
3396                state.staging.room_bytes().to_vec(),
3397            )
3398        };
3399        assert!(staging(&sender).1.is_empty());
3400
3401        let exact: Vec<u8> = (0..18 * 2 * 16)
3402            .map(|i| (64 + (i >> 4) % 128) as u8)
3403            .collect();
3404        let frame = BorrowedVideoFrame::builder(&exact, 18, 16, PixelFormat::Uyvy)
3405            .build()
3406            .unwrap();
3407        if frame.sends_in_place() {
3408            // The SDK reads frames exactly here, so the sender copies none.
3409            assert_eq!(PixelFormat::Uyvy.send_tail_room(), 0);
3410            sender.send_video(&frame).unwrap();
3411            assert!(staging(&sender).1.is_empty());
3412            return;
3413        }
3414        sender.send_video(&frame).unwrap();
3415        let (address, copy, room) = staging(&sender);
3416        assert_eq!(copy, exact);
3417        assert_eq!(room, [0; 64]);
3418
3419        // The steady state: the same buffer, and no allocation.
3420        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3421            sender.send_video(&frame).unwrap();
3422        });
3423        assert_eq!(allocations, 0);
3424        assert_eq!(staging(&sender).0, address);
3425
3426        // Frames that send in place leave the copy alone.
3427        let mut roomy = exact.clone();
3428        roomy.reverse();
3429        roomy.resize(exact.len() + PixelFormat::Uyvy.send_tail_room(), 0);
3430        let direct = BorrowedVideoFrame::builder(&roomy, 18, 16, PixelFormat::Uyvy)
3431            .allow_send_from_padding_and_tail(true)
3432            .build()
3433            .unwrap();
3434        assert!(direct.sends_in_place());
3435        let owned = direct.to_owned();
3436        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3437            sender.send_video(&direct).unwrap();
3438            sender.send_video(&owned).unwrap();
3439        });
3440        assert_eq!(allocations, 0);
3441        assert_eq!(staging(&sender), (address, copy, room));
3442
3443        // A larger frame replaces the buffer once.
3444        let larger = vec![128u8; 34 * 2 * 16];
3445        let frame = BorrowedVideoFrame::builder(&larger, 34, 16, PixelFormat::Uyvy)
3446            .build()
3447            .unwrap();
3448        let ((), allocations) = crate::test_alloc::allocation_count(|| {
3449            sender.send_video(&frame).unwrap();
3450        });
3451        assert_eq!(allocations, 1);
3452        assert_eq!(staging(&sender).1, larger);
3453    }
3454
3455    #[test]
3456    fn synchronous_send_describes_an_owned_frame_as_the_frame_itself() {
3457        let owned = test_owned_frame(8);
3458        let mut staging = VideoStaging::default();
3459        let (expected, lent) = (
3460            owned.as_test_raw(),
3461            PreparedVideo::new(&owned, &mut staging).raw,
3462        );
3463        assert_eq!(lent.p_data, expected.p_data);
3464        assert_eq!(lent.p_metadata, expected.p_metadata);
3465        // SAFETY: both descriptors are uncompressed, so the union holds the stride.
3466        let strides = unsafe {
3467            (
3468                lent.__bindgen_anon_1.line_stride_in_bytes,
3469                expected.__bindgen_anon_1.line_stride_in_bytes,
3470            )
3471        };
3472        assert_eq!(strides.0, strides.1);
3473        assert_eq!(
3474            (lent.xres, lent.yres, lent.FourCC, lent.timecode),
3475            (
3476                expected.xres,
3477                expected.yres,
3478                expected.FourCC,
3479                expected.timecode
3480            )
3481        );
3482        assert_eq!(
3483            (lent.frame_rate_N, lent.frame_rate_D, lent.frame_format_type),
3484            (
3485                expected.frame_rate_N,
3486                expected.frame_rate_D,
3487                expected.frame_format_type
3488            )
3489        );
3490        assert_eq!(lent.picture_aspect_ratio, expected.picture_aspect_ratio);
3491    }
3492
3493    #[test]
3494    fn mixed_sync_flush_and_copy_sends_preserve_recovery() {
3495        let Some(mut sender) = test_sender() else {
3496            return;
3497        };
3498        let frame = test_owned_frame(1);
3499        let pixels = frame.data().as_ptr();
3500        sender.submit_video(frame).unwrap();
3501        sender.send_video(&test_owned_frame(9)).unwrap();
3502        sender.flush_video();
3503        assert_eq!(sender.reclaim_video().unwrap().data().as_ptr(), pixels);
3504
3505        // A copied send retains the released owned frame for its next copy.
3506        let owned = test_owned_frame(2);
3507        let owned_pixels = owned.data().as_ptr();
3508        sender.submit_video(owned).unwrap();
3509        let data = vec![3; 1024];
3510        let metadata = CString::new("<copy/>").unwrap();
3511        {
3512            let borrowed = BorrowedVideoFrame::builder(&data, 16, 16, PixelFormat::Bgra)
3513                .metadata(&metadata)
3514                .build()
3515                .unwrap();
3516            sender.submit_video_copy(&borrowed).unwrap();
3517        }
3518        {
3519            let video = sender.native.video.test_state();
3520            let Some(copy) = video.in_flight.frame() else {
3521                panic!("missing copied snapshot")
3522            };
3523            assert_ne!(copy.data().as_ptr(), data.as_ptr());
3524            assert_ne!(copy.metadata_cstr().unwrap().as_ptr(), metadata.as_ptr());
3525            let spare = video.spare.as_ref().unwrap();
3526            assert_eq!(spare.data().as_ptr(), owned_pixels);
3527            assert_eq!(spare.data()[0], 2);
3528        }
3529        drop(data);
3530        drop(metadata);
3531        {
3532            let video = sender.native.video.test_state();
3533            let Some(copy) = video.in_flight.frame() else {
3534                panic!("missing copied snapshot")
3535            };
3536            assert_eq!(copy.data(), vec![3; 1024]);
3537            assert_eq!(copy.metadata().unwrap(), "<copy/>");
3538        }
3539        // Copies are ordinary owned frames and are returned for reuse too.
3540        let copied = sender.submit_video(test_owned_frame(4)).unwrap().unwrap();
3541        assert_eq!(copied.data()[0], 3);
3542        assert_eq!(copied.metadata(), Some("<copy/>"));
3543        sender.reclaim_video().unwrap();
3544        sender.flush_video();
3545    }
3546
3547    #[test]
3548    fn every_synchronizing_call_completes_a_frame_once_and_recovery_keeps_its_identity() {
3549        let Some(mut sender) = test_sender() else {
3550            return;
3551        };
3552        let in_flight = |sender: &Sender| sender.native.video.test_state().in_flight.is_in_flight();
3553        let frame = |value| {
3554            let frame = test_owned_frame(value);
3555            let pixels = frame.data().as_ptr();
3556            (frame, pixels)
3557        };
3558
3559        // A synchronous send completes the frame in flight; the next
3560        // submission returns that original allocation.
3561        let (a, a_pixels) = frame(1);
3562        assert!(sender.submit_video(a).unwrap().is_none());
3563        assert!(in_flight(&sender));
3564        sender.send_video(&test_owned_frame(9)).unwrap();
3565        assert!(!in_flight(&sender));
3566        let (b, b_pixels) = frame(2);
3567        let previous = sender.submit_video(b).unwrap().unwrap();
3568        assert_eq!(previous.data().as_ptr(), a_pixels);
3569
3570        // A flush does the same, and a second flush finds nothing in flight.
3571        sender.flush_video();
3572        assert!(!in_flight(&sender));
3573        sender.flush_video();
3574        let (c, c_pixels) = frame(3);
3575        let previous = sender.submit_video(c).unwrap().unwrap();
3576        assert_eq!(previous.data().as_ptr(), b_pixels);
3577
3578        // A submission completes the in-flight frame it displaces.
3579        let (d, d_pixels) = frame(4);
3580        let previous = sender.submit_video(d).unwrap().unwrap();
3581        assert_eq!(previous.data().as_ptr(), c_pixels);
3582        assert!(in_flight(&sender));
3583
3584        // Finishing recovers a frame a synchronous send already completed.
3585        sender.send_video(&test_owned_frame(9)).unwrap();
3586        assert_eq!(sender.reclaim_video().unwrap().data().as_ptr(), d_pixels);
3587        assert!(sender.reclaim_video().is_none());
3588
3589        // A sender can also be dropped after an explicit flush.
3590        sender.submit_video(frame(5).0).unwrap();
3591        sender.flush_video();
3592        drop(sender);
3593    }
3594
3595    #[test]
3596    fn test_async_flush_uses_null_frame_pointer() {
3597        assert!(async_flush_frame_ptr().is_null());
3598    }
3599
3600    #[test]
3601    fn planar_444_sends_check_the_senders_runtime_before_the_sdk() {
3602        let Some(mut sender) = test_sender() else {
3603            return;
3604        };
3605        let supported = sender
3606            .runtime()
3607            .require_feature(RuntimeFeature::Planar444Video)
3608            .is_ok();
3609        let frame = VideoFrame::builder()
3610            .resolution(16, 16)
3611            .pixel_format(PixelFormat::Nb4g)
3612            .build()
3613            .unwrap();
3614        let pixels = frame.data().as_ptr();
3615        let data = frame.data().to_vec();
3616        let borrowed = BorrowedVideoFrame::builder(&data, 16, 16, PixelFormat::Nb4g)
3617            .build()
3618            .unwrap();
3619        // An earlier frame stays in flight through every rejection.
3620        assert!(sender.submit_video(test_owned_frame(1)).unwrap().is_none());
3621        if supported {
3622            sender.send_video(&frame).unwrap();
3623            let previous = sender.submit_video(frame).unwrap().unwrap();
3624            assert_eq!(previous.data()[0], 1);
3625            sender.submit_video_copy(&borrowed).unwrap();
3626            assert_eq!(
3627                sender
3628                    .native
3629                    .video
3630                    .test_state()
3631                    .spare
3632                    .as_ref()
3633                    .unwrap()
3634                    .data()
3635                    .as_ptr(),
3636                pixels
3637            );
3638        } else {
3639            let unsupported = |error: &Error| {
3640                matches!(
3641                    error,
3642                    Error::UnsupportedCapability {
3643                        capability: crate::Capability::Runtime(RuntimeFeature::Planar444Video),
3644                        ..
3645                    }
3646                )
3647            };
3648            assert!(unsupported(&sender.send_video(&frame).unwrap_err()));
3649            let rejected = sender.submit_video(frame).unwrap_err();
3650            assert!(unsupported(rejected.error()));
3651            assert_eq!(rejected.into_inner().data().as_ptr(), pixels);
3652            assert!(unsupported(
3653                &sender.submit_video_copy(&borrowed).unwrap_err()
3654            ));
3655            assert!(sender.native.video.test_state().in_flight.is_in_flight());
3656        }
3657        assert!(sender.reclaim_video().is_some());
3658    }
3659
3660    #[test]
3661    fn borrowed_builder_validates_padded_layouts_and_preserves_headers_without_allocating() {
3662        for format in [
3663            PixelFormat::Bgra,
3664            PixelFormat::Bgrx,
3665            PixelFormat::Rgba,
3666            PixelFormat::Rgbx,
3667            PixelFormat::Uyvy,
3668            PixelFormat::Uyva,
3669            PixelFormat::P216,
3670            PixelFormat::Pa16,
3671            PixelFormat::I420,
3672            PixelFormat::Yv12,
3673            PixelFormat::Nv12,
3674        ] {
3675            for stride in [
3676                None,
3677                Some(format.line_stride_bytes(4).unwrap()),
3678                Some(format.line_stride_bytes(4).unwrap() + 8),
3679            ] {
3680                let layout = ValidatedVideoLayout::new_uncompressed(format, 4, 4, stride).unwrap();
3681                // A longer buffer is accepted; the frame is its layout's extent.
3682                let data = vec![19; layout.data_len_bytes() + 3];
3683                let metadata = c"<pixels>é</pixels>";
3684                let rate = FrameRate::new(30000, 1001).unwrap();
3685                let (borrowed, allocations) = crate::test_alloc::allocation_count(|| {
3686                    let builder = BorrowedVideoFrame::builder(&data, 4, 4, format);
3687                    let builder = match stride {
3688                        Some(stride) => builder.line_stride_bytes(stride),
3689                        None => builder,
3690                    };
3691                    let frame = builder
3692                        .frame_rate(rate)
3693                        .picture_aspect_ratio(PictureAspectRatio::new(1.25).unwrap())
3694                        .scan_type(ScanType::Interlaced)
3695                        .timecode(Timecode::from_ticks(0))
3696                        .metadata(metadata)
3697                        .build()
3698                        .unwrap();
3699                    for _ in 0..3 {
3700                        assert_eq!(frame.metadata(), Some("<pixels>é</pixels>"));
3701                        assert_eq!(frame.storage(), &data[..layout.data_len_bytes()]);
3702                        assert_eq!(frame.pixel_format(), format);
3703                    }
3704                    frame
3705                });
3706                assert_eq!(allocations, 0);
3707                let (owned, allocations) =
3708                    crate::test_alloc::allocation_count(|| borrowed.to_owned());
3709                assert_eq!(allocations, 2);
3710                assert_eq!(owned.frame_rate(), rate);
3711                assert_eq!(owned.picture_aspect_ratio().get(), 1.25);
3712                assert_eq!(owned.scan_type(), ScanType::Interlaced);
3713                assert_eq!(
3714                    (owned.timecode(), owned.timestamp()),
3715                    (Timecode::from_ticks(0), None)
3716                );
3717                assert_eq!(owned.metadata(), borrowed.metadata());
3718                let mut staging = VideoStaging::default();
3719                let (raw, allocations) = crate::test_alloc::allocation_count(|| {
3720                    PreparedVideo::new(&owned, &mut staging).raw
3721                });
3722                assert_eq!(allocations, 0);
3723                assert_eq!(raw.p_metadata, owned.as_test_raw().p_metadata);
3724                assert_eq!(raw.p_data, owned.as_test_raw().p_data);
3725                let short =
3726                    BorrowedVideoFrame::builder(&data[..layout.data_len_bytes() - 1], 4, 4, format);
3727                let short = match stride {
3728                    Some(stride) => short.line_stride_bytes(stride),
3729                    None => short,
3730                };
3731                assert!(short.build().is_err());
3732            }
3733            for stride in [0, 1, i32::MAX.unsigned_abs() as usize, usize::MAX] {
3734                let expected = ValidatedVideoLayout::new_uncompressed(format, 4, 4, Some(stride));
3735                let result = BorrowedVideoFrame::builder(&[], 4, 4, format)
3736                    .line_stride_bytes(stride)
3737                    .build();
3738                assert!(expected.is_err());
3739                assert!(result.is_err());
3740            }
3741        }
3742    }
3743
3744    #[test]
3745    fn borrowed_metadata_is_bounded_utf8_and_preserves_empty_presence() {
3746        let data = [0; 16];
3747        for metadata in [None, Some(c"")] {
3748            let mut builder = BorrowedVideoFrame::builder(&data, 2, 2, PixelFormat::Bgra);
3749            if let Some(metadata) = metadata {
3750                builder = builder.metadata(metadata);
3751            }
3752            let frame = builder.build().unwrap();
3753            let (owned, allocations) = crate::test_alloc::allocation_count(|| frame.to_owned());
3754            assert_eq!(allocations, 1 + usize::from(metadata.is_some()));
3755            assert_eq!(owned.metadata(), metadata.map(|_| ""));
3756        }
3757        let invalid = c"\xff";
3758        assert!(matches!(
3759            BorrowedVideoFrame::builder(&data, 2, 2, PixelFormat::Bgra)
3760                .metadata(invalid)
3761                .build(),
3762            Err(Error::InvalidUtf8(_))
3763        ));
3764        for len in [
3765            crate::frames::MAX_METADATA_BYTES,
3766            crate::frames::MAX_METADATA_BYTES + 1,
3767        ] {
3768            let mut bytes = vec![b'x'; len];
3769            bytes[len - 1] = 0;
3770            let metadata = CStr::from_bytes_with_nul(&bytes).unwrap();
3771            let result = BorrowedVideoFrame::builder(&data, 2, 2, PixelFormat::Bgra)
3772                .metadata(metadata)
3773                .build();
3774            assert_eq!(result.is_ok(), len == crate::frames::MAX_METADATA_BYTES);
3775        }
3776    }
3777
3778    #[test]
3779    fn test_borrowed_frame_timecode_and_aspect_ratio() {
3780        let buffer = vec![0u8; 64 * 36 * 2];
3781        let frame = BorrowedVideoFrame::builder(&buffer, 64, 36, PixelFormat::Uyvy)
3782            .build()
3783            .unwrap();
3784        assert_eq!(frame.timecode(), Timecode::SYNTHESIZE);
3785        assert_eq!(frame.picture_aspect_ratio().get(), 0.0);
3786
3787        let frame = BorrowedVideoFrame::builder(&buffer, 64, 36, PixelFormat::Uyvy)
3788            .picture_aspect_ratio(PictureAspectRatio::SQUARE_PIXELS)
3789            .build()
3790            .unwrap()
3791            .with_timecode(Timecode::from_ticks(1234));
3792        assert_eq!(frame.timecode(), Timecode::from_ticks(1234));
3793        assert_eq!(frame.picture_aspect_ratio().get(), 0.0);
3794        let raw = frame.to_raw();
3795        assert_eq!((raw.timecode, raw.picture_aspect_ratio), (1234, 0.0));
3796        assert_eq!(raw.timestamp, NDIlib_recv_timestamp_undefined);
3797
3798        for bad in [-1.0, f32::NAN, f32::INFINITY] {
3799            assert!(PictureAspectRatio::new(bad).is_err(), "{bad}");
3800        }
3801    }
3802
3803    #[test]
3804    fn borrowed_video_aspect_defaults_and_copies_preserve_the_sdk_sentinel() {
3805        for (width, height) in [(640, 480), (1920, 1080), (1080, 1920), (64, 64)] {
3806            let pixels = vec![0; width as usize * height as usize * 4];
3807            for ratio in [None, Some(0.0), Some(1.25)] {
3808                let mut builder =
3809                    BorrowedVideoFrame::builder(&pixels, width, height, PixelFormat::Bgra);
3810                if let Some(ratio) = ratio {
3811                    builder = builder.picture_aspect_ratio(PictureAspectRatio::new(ratio).unwrap());
3812                }
3813                let frame = builder.build().unwrap();
3814                let expected = ratio.unwrap_or(0.0);
3815                assert_eq!(frame.picture_aspect_ratio().get(), expected);
3816                assert_eq!(frame.to_raw().picture_aspect_ratio, expected);
3817                let mut copied = frame.to_owned();
3818                assert_eq!(copied.picture_aspect_ratio().get(), expected);
3819                copied.set_picture_aspect_ratio(PictureAspectRatio::new(2.0).unwrap());
3820                frame.copy_into(&mut copied);
3821                assert_eq!(copied.picture_aspect_ratio().get(), expected);
3822            }
3823        }
3824    }
3825
3826    /// Build a borrowed frame of `format` over `buffer` at 60 frames per second.
3827    fn borrowed(
3828        buffer: &[u8],
3829        width: u32,
3830        height: u32,
3831        format: PixelFormat,
3832    ) -> Result<BorrowedVideoFrame<'_>> {
3833        BorrowedVideoFrame::builder(buffer, width, height, format).build()
3834    }
3835
3836    #[test]
3837    fn test_borrowed_builder_exact_size() {
3838        // BGRA format: 1920x1080x4 bytes
3839        let buffer = vec![0u8; 1920 * 1080 * 4];
3840        assert!(borrowed(&buffer, 1920, 1080, PixelFormat::Bgra).is_ok());
3841    }
3842
3843    #[test]
3844    fn test_borrowed_builder_oversized_buffer() {
3845        // Buffer larger than needed should succeed
3846        let buffer = vec![0u8; 1920 * 1080 * 4 + 1000];
3847        let frame = borrowed(&buffer, 1920, 1080, PixelFormat::Bgra).unwrap();
3848        assert_eq!(frame.data().unwrap().len(), 1920 * 1080 * 4);
3849    }
3850
3851    #[test]
3852    fn test_borrowed_builder_undersized_buffer() {
3853        // Buffer too small should fail
3854        let buffer = vec![0u8; 1920 * 1080 * 4 - 1];
3855        let result = borrowed(&buffer, 1920, 1080, PixelFormat::Bgra);
3856        assert!(result.is_err());
3857        if let Err(Error::InvalidFrame(msg)) = result {
3858            assert!(matches!(
3859                msg,
3860                crate::FrameDefect::VideoBufferTooSmall { .. }
3861            ));
3862            assert!(matches!(
3863                msg,
3864                crate::FrameDefect::VideoBufferTooSmall {
3865                    format: PixelFormat::Bgra,
3866                    ..
3867                }
3868            ));
3869        }
3870    }
3871
3872    #[test]
3873    fn test_borrowed_builder_uyvy() {
3874        // UYVY format: 1920x1080x2 bytes
3875        let buffer = vec![0u8; 1920 * 1080 * 2];
3876        assert!(borrowed(&buffer, 1920, 1080, PixelFormat::Uyvy).is_ok());
3877    }
3878
3879    #[test]
3880    fn test_borrowed_builder_nv12() {
3881        // NV12 planar format: Y plane + UV plane
3882        let expected_size = PixelFormat::Nv12.buffer_len(1920, 1080, None).unwrap();
3883        let buffer = vec![0u8; expected_size];
3884        assert!(borrowed(&buffer, 1920, 1080, PixelFormat::Nv12).is_ok());
3885    }
3886
3887    #[test]
3888    fn test_borrowed_builder_i420() {
3889        // I420 planar format
3890        let expected_size = PixelFormat::I420.buffer_len(640, 480, None).unwrap();
3891        let buffer = vec![0u8; expected_size];
3892        assert!(borrowed(&buffer, 640, 480, PixelFormat::I420).is_ok());
3893    }
3894
3895    #[test]
3896    fn test_borrowed_builder_rejects_invalid_layout() {
3897        let buffer = vec![0u8; 4096];
3898
3899        assert!(matches!(
3900            borrowed(&buffer, 0, 480, PixelFormat::Bgra),
3901            Err(Error::InvalidFrame(_))
3902        ));
3903        assert!(matches!(
3904            borrowed(&buffer, 640, 0, PixelFormat::Bgra),
3905            Err(Error::InvalidFrame(_))
3906        ));
3907        assert!(matches!(
3908            borrowed(&buffer, 641, 480, PixelFormat::I420),
3909            Err(Error::InvalidFrame(_))
3910        ));
3911    }
3912
3913    #[test]
3914    fn test_getters() {
3915        let buffer = vec![0u8; 1920 * 1080 * 4];
3916        let frame = BorrowedVideoFrame::builder(&buffer, 1920, 1080, PixelFormat::Bgra)
3917            .frame_rate(FrameRate::new(60, 1).unwrap())
3918            .build()
3919            .unwrap();
3920
3921        assert_eq!(frame.width(), 1920);
3922        assert_eq!(frame.height(), 1080);
3923        assert_eq!(frame.pixel_format(), PixelFormat::Bgra);
3924        assert_eq!(frame.frame_rate(), FrameRate::new(60, 1).unwrap());
3925        assert_eq!(frame.picture_aspect_ratio().get(), 0.0);
3926        assert_eq!(frame.scan_type(), ScanType::Progressive);
3927        assert_eq!(frame.timecode(), Timecode::SYNTHESIZE);
3928        assert_eq!(frame.data().unwrap().len(), buffer.len());
3929        assert_eq!(frame.line_stride_bytes(), 1920 * 4);
3930        assert!(frame.metadata().is_none());
3931        // Copies share the borrow, and Debug summarizes rather than dumps pixels.
3932        let copy = frame;
3933        assert_eq!(
3934            copy.data().unwrap().as_ptr(),
3935            frame.data().unwrap().as_ptr()
3936        );
3937        assert!(format!("{frame:?}").contains("data (bytes): 8294400"));
3938        assert_eq!(
3939            borrowed(&buffer, 1920, 1080, PixelFormat::Bgra)
3940                .unwrap()
3941                .frame_rate(),
3942            FrameRate::new(60, 1).unwrap()
3943        );
3944    }
3945
3946    #[test]
3947    fn test_all_pixel_formats_validation() {
3948        // Test that validation works correctly for all pixel formats
3949        let test_cases = vec![
3950            (PixelFormat::Bgra, 1920, 1080, 1920 * 1080 * 4),
3951            (PixelFormat::Rgba, 1920, 1080, 1920 * 1080 * 4),
3952            (PixelFormat::Bgrx, 1920, 1080, 1920 * 1080 * 4),
3953            (PixelFormat::Rgbx, 1920, 1080, 1920 * 1080 * 4),
3954            (PixelFormat::Uyvy, 1920, 1080, 1920 * 1080 * 2),
3955            (PixelFormat::Uyva, 1920, 1080, 1920 * 1080 * 3),
3956            (PixelFormat::P216, 1920, 1080, 1920 * 1080 * 4),
3957            (PixelFormat::Pa16, 1920, 1080, 1920 * 1080 * 6),
3958        ];
3959
3960        for (format, width, height, expected_min_size) in test_cases {
3961            // Exact size should work
3962            let buffer = vec![0u8; expected_min_size];
3963            let result = borrowed(&buffer, width, height, format);
3964            assert!(result.is_ok(), "Failed for format {:?}", format);
3965
3966            // One byte too small should fail
3967            if expected_min_size > 0 {
3968                let buffer = vec![0u8; expected_min_size - 1];
3969                let result = borrowed(&buffer, width, height, format);
3970                assert!(result.is_err(), "Should fail for undersized {:?}", format);
3971            }
3972        }
3973    }
3974
3975    #[test]
3976    fn test_planar_formats() {
3977        // Test planar 4:2:0 formats (NV12, I420, YV12)
3978        let width = 1920;
3979        let height = 1080;
3980
3981        for format in [PixelFormat::Nv12, PixelFormat::I420, PixelFormat::Yv12] {
3982            let expected_size = format.buffer_len(width, height, None).unwrap();
3983
3984            let buffer = vec![0u8; expected_size];
3985            let result = borrowed(&buffer, width, height, format);
3986            assert!(result.is_ok(), "Failed for planar format {:?}", format);
3987
3988            // One byte too small should fail
3989            if expected_size > 0 {
3990                let buffer = vec![0u8; expected_size - 1];
3991                let result = borrowed(&buffer, width, height, format);
3992                assert!(result.is_err(), "Should fail for undersized {:?}", format);
3993            }
3994        }
3995    }
3996}
3997
3998#[cfg(any(
3999    ndi_test_send_ownership,
4000    ndi_test_send_ownership_control,
4001    ndi_test_send_ownership_types
4002))]
4003#[path = "../tests/ui/internal/send_ownership.rs"]
4004mod ownership_contract;