Skip to main content

grafton_ndi/advanced/
queued.rs

1//! Asynchronous video sending with a bounded queue and completion
2//! notification.
3
4use std::{
5    collections::VecDeque,
6    sync::{Condvar, Mutex},
7    time::Duration,
8};
9
10#[cfg(any(test, ndi_has_advanced_send_completion))]
11use std::ffi::c_void;
12
13use super::send::ScatterSendable;
14use super::{
15    reserved_map::ReservedMap,
16    send::PendingVideo,
17    send_slots::{DescriptorLease, Released, SlotKey},
18    CompressedFrame, QueueAttached, ScatterFrame, SubmittedVideo, VideoPacketFormat,
19};
20#[cfg(test)]
21use crate::sys::advanced::ScatterSend;
22use crate::{
23    frames::Sendable,
24    marker::NotSync,
25    sender::in_flight::{Destroyed, Lend, Lending, Lent, LoanPair, Loans},
26    sys::{
27        advanced::{native, SendCompletion},
28        bindings::*,
29    },
30    timeout::Deadline,
31    Error, Ndi, QueueLimit, Rejected, Result, Sender, SenderOptions, VideoFrame,
32};
33
34use super::aliasable::AliasableBox;
35#[cfg(any(test, ndi_has_advanced_send_completion))]
36use super::send_slots::DescriptorSlots;
37
38/// Limits on what a [`QueuedSender`] holds at once.
39///
40/// A frame counts from submission until the application takes it back, so a
41/// frame the SDK has finished with but that has not been collected still uses
42/// its share. The byte budget includes retained payload capacity, even when a
43/// compressed frame uses only part of a pooled vector. The defaults are 8 frames
44/// and 512 MiB. Construction reserves one stable frame descriptor per frame.
45/// Scatter frames own their scatter-list descriptors. Completed frames retain
46/// their slots until collected.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct QueueLimits {
49    frames: usize,
50    bytes: usize,
51}
52
53impl Default for QueueLimits {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl QueueLimits {
60    /// Requested maximum frame count.
61    #[must_use]
62    pub fn configured_max_frames(&self) -> usize {
63        self.frames
64    }
65
66    /// Requested maximum retained bytes.
67    #[must_use]
68    pub fn configured_max_bytes(&self) -> usize {
69        self.bytes
70    }
71
72    /// The default limits: 8 frames and 512 MiB.
73    pub fn new() -> Self {
74        Self {
75            frames: 8,
76            bytes: 512 * 1024 * 1024,
77        }
78    }
79
80    /// Set the maximum number of frames held, from 1 to 65 536.
81    #[must_use]
82    pub fn max_frames(mut self, frames: usize) -> Self {
83        self.frames = frames;
84        self
85    }
86
87    /// Set the maximum retained bytes of frame data and metadata, including
88    /// unused payload capacity reserved by pooled vectors. A frame larger
89    /// than this limit is refused with [`Error::InvalidInput`]; collecting
90    /// completions cannot make it fit.
91    #[must_use]
92    pub fn max_bytes(mut self, bytes: usize) -> Self {
93        self.bytes = bytes;
94        self
95    }
96
97    #[cfg(any(test, ndi_has_advanced_send_completion))]
98    fn validate(self) -> Result<Self> {
99        if self.frames == 0
100            || self.frames > 65_536
101            || self.bytes == 0
102            || self.bytes > isize::MAX as usize
103        {
104            return Err(Error::InvalidInput(crate::InputDefect::QueueLimits));
105        }
106        Ok(self)
107    }
108}
109/// Identifies one submission to a [`QueuedSender`]. Identifiers increase with
110/// each submission and are never reused by the same queue.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub struct SubmissionId(u64);
113
114impl SubmissionId {
115    /// The identifier as a number.
116    pub fn get(self) -> u64 {
117        self.0
118    }
119}
120
121/// A video frame a [`QueuedSender`] can send.
122///
123/// Each variant owns its complete, nonempty video storage. Cloning copies the
124/// bytes into independent allocations; submission moves that storage into the
125/// queue until it is collected. Scatter frames retain their separate blocks.
126#[derive(Clone, Debug)]
127#[non_exhaustive]
128pub enum QueuedVideoFrame {
129    /// An uncompressed frame.
130    Pixels(VideoFrame),
131    /// A compressed frame.
132    Compressed(CompressedFrame<VideoPacketFormat>),
133    /// A compressed frame held in separate owned blocks.
134    Scatter(ScatterFrame<VideoPacketFormat>),
135}
136
137impl From<VideoFrame> for QueuedVideoFrame {
138    fn from(v: VideoFrame) -> Self {
139        Self::Pixels(v)
140    }
141}
142
143impl From<CompressedFrame<VideoPacketFormat>> for QueuedVideoFrame {
144    fn from(v: CompressedFrame<VideoPacketFormat>) -> Self {
145        Self::Compressed(v)
146    }
147}
148
149impl From<ScatterFrame<VideoPacketFormat>> for QueuedVideoFrame {
150    fn from(frame: ScatterFrame<VideoPacketFormat>) -> Self {
151        Self::Scatter(frame)
152    }
153}
154
155impl QueuedVideoFrame {
156    fn retained_bytes(&self) -> usize {
157        match self {
158            Self::Pixels(v) => v.retained_bytes(),
159            Self::Compressed(v) => v.retained_bytes(),
160            Self::Scatter(v) => v.retained_bytes(),
161        }
162    }
163
164    /// Consume the input only after checking the capability its storage needs.
165    fn authorize(
166        self,
167        sender: &Sender<QueueAttached>,
168    ) -> std::result::Result<QueuedStorage, Rejected<Self>> {
169        self.authorize_with(
170            |frame| Sendable::new(frame, sender.runtime()),
171            |frame| ScatterSendable::checked(frame, sender.runtime()),
172        )
173    }
174
175    fn authorize_with(
176        self,
177        pixels: impl FnOnce(
178            VideoFrame,
179        ) -> std::result::Result<Sendable<VideoFrame>, Rejected<VideoFrame>>,
180        scatter: impl FnOnce(
181            ScatterFrame<VideoPacketFormat>,
182        ) -> std::result::Result<
183            ScatterSendable<ScatterFrame<VideoPacketFormat>>,
184            (Error, ScatterFrame<VideoPacketFormat>),
185        >,
186    ) -> std::result::Result<QueuedStorage, Rejected<Self>> {
187        match self {
188            Self::Pixels(frame) => pixels(frame)
189                .map(QueuedStorage::Pixels)
190                .map_err(|rejected| rejected.map(Self::Pixels)),
191            Self::Compressed(frame) => Ok(QueuedStorage::Packet(PendingVideo::Contiguous(frame))),
192            Self::Scatter(frame) => scatter(frame)
193                .map(|proof| QueuedStorage::Packet(PendingVideo::Scatter(proof)))
194                .map_err(|(error, frame)| Rejected::new(error, Self::Scatter(frame))),
195        }
196    }
197
198    #[cfg(test)]
199    fn authorize_for_test(self, scatter: Option<&ScatterSend>) -> QueuedStorage {
200        self.authorize_with(
201            |frame| Ok(Sendable::for_test(frame)),
202            |frame| ScatterSendable::for_test(frame, scatter),
203        )
204        .unwrap()
205    }
206}
207
208/// Every variant owns the exact capability its payload needs. Packet storage
209/// additionally owns the scatter dispatch and stable list when one is needed.
210enum QueuedStorage {
211    Pixels(Sendable<VideoFrame>),
212    Packet(PendingVideo),
213}
214
215impl QueuedStorage {
216    fn into_frame(self) -> QueuedVideoFrame {
217        let packet = match self {
218            Self::Pixels(frame) => return QueuedVideoFrame::Pixels(frame.into_frame()),
219            Self::Packet(packet) => packet,
220        };
221        match packet.into_submitted() {
222            SubmittedVideo::Contiguous(frame) => QueuedVideoFrame::Compressed(frame),
223            SubmittedVideo::Scatter(frame) => QueuedVideoFrame::Scatter(frame),
224        }
225    }
226}
227
228// SAFETY: Pixels owns initialized payload, terminated metadata and its matching
229// format proof; its owned loan reserves the complete scan-dependent SDK room
230// at descriptor construction. Packet delegates to PendingVideo, which owns its payload and
231// metadata and initializes its own stable scatter list before lending it. The
232// completion key points into its retained, nonempty first block. Moving this
233// value moves none of its allocations; Entry excludes access until completion
234// or destruction has ended the native loan.
235unsafe impl Lend for QueuedStorage {
236    fn lend(&mut self) -> Lent {
237        match self {
238            Self::Pixels(frame) => frame.lend(),
239            Self::Packet(frame) => {
240                let lent = frame.lend();
241                #[cfg(ndi_has_advanced_scatter_send)]
242                {
243                    let mut lent = lent;
244                    if let PendingVideo::Scatter(proof) = frame {
245                        let (pointer, length) = proof.completion_key();
246                        let descriptor = lent.descriptor_mut();
247                        descriptor.p_data = pointer;
248                        descriptor.__bindgen_anon_1.data_size_in_bytes = length;
249                    }
250                    lent
251                }
252                #[cfg(not(ndi_has_advanced_scatter_send))]
253                lent
254            }
255        }
256    }
257}
258/// A frame the SDK has finished with, ready to be reused.
259///
260/// It was either reported complete or reclaimed by [`QueuedSender::close`]
261/// after native destruction ended the SDK's access to it.
262#[derive(Clone, Debug)]
263pub struct CompletedVideo {
264    id: SubmissionId,
265    frame: QueuedVideoFrame,
266}
267
268impl CompletedVideo {
269    /// The identifier [`QueuedSender::try_submit`] returned for this frame.
270    pub fn id(&self) -> SubmissionId {
271        self.id
272    }
273
274    /// The frame.
275    pub fn frame(&self) -> &QueuedVideoFrame {
276        &self.frame
277    }
278
279    /// Take the frame.
280    pub fn into_frame(self) -> QueuedVideoFrame {
281        self.frame
282    }
283}
284
285/// One submitted frame and the descriptor the SDK was given for it.
286///
287/// The entry owns the frame it lent, so nothing can read the frame's bytes
288/// while the SDK may still write to them.
289struct Entry {
290    id: SubmissionId,
291    // Owns the fixed header slot until collection or proven destruction.
292    slot: DescriptorLease,
293    frame: QueuedStorage,
294    bytes: usize,
295}
296
297impl Entry {
298    fn release(self, proof: Released<'_>) -> (CompletedVideo, SlotKey) {
299        let Self {
300            id, slot, frame, ..
301        } = self;
302        // Native release covers the payload and its frame-owned scatter list
303        // before the header slot's key can reenter admission.
304        let completed = CompletedVideo {
305            id,
306            frame: frame.into_frame(),
307        };
308        (completed, slot.release(proof))
309    }
310}
311
312/// Minted only when the SDK identifies the exact in-flight entry as complete.
313/// Its private constructor stays in this module, and the token remains paired
314/// with that entry until collection releases both its payload and slot.
315pub(super) struct Completion {
316    _private: (),
317}
318
319const_assert!(std::mem::size_of::<Completion>() == 0);
320
321struct ReadyEntry {
322    entry: Entry,
323    completion: Completion,
324}
325
326const_assert!({
327    const fn assert_send_sync<T: Send + Sync>() {}
328    assert_send_sync::<Entry>();
329});
330
331pub(crate) struct Admitted {
332    pub(crate) id: SubmissionId,
333    pub(crate) lent: Lent,
334    pub(crate) pointer: *const NDIlib_video_frame_v2_t,
335}
336
337/// The frames a queue holds. Each is in exactly one place: in flight until
338/// the SDK reports it complete, then ready until it is collected.
339struct State {
340    // The frames the SDK may still read, by the address of their data.
341    in_flight: ReservedMap<usize, Entry>,
342    // The frames the SDK has finished with, in the order it reported them.
343    ready: VecDeque<ReadyEntry>,
344    bytes: usize,
345    next: u64,
346    options: QueueLimits,
347    // Free keys are the frame capacity. A lease dropped while unwinding
348    // retires its key, so the queue may have fewer usable slots than requested.
349    free: Vec<SlotKey>,
350    failed: bool,
351}
352
353impl State {
354    /// The frames held, in flight or ready.
355    fn retained(&self) -> usize {
356        self.in_flight.len() + self.ready.len()
357    }
358    /// Check all admission bounds before acquiring descriptor storage. Then
359    /// initialize a free stable slot and record ownership before dispatch.
360    fn admit(
361        &mut self,
362        frame: QueuedStorage,
363        bytes: usize,
364    ) -> std::result::Result<Admitted, Rejected<QueuedVideoFrame>> {
365        self.admit_with_lend(frame, bytes, |frame| frame.lend())
366    }
367
368    /// Derive the completion key from the very descriptor handed to the SDK.
369    /// Lending needs no header slot: scatter lists belong to their frames.
370    fn admit_with_lend(
371        &mut self,
372        frame: QueuedStorage,
373        bytes: usize,
374        lend: impl FnOnce(&mut QueuedStorage) -> Lent,
375    ) -> std::result::Result<Admitted, Rejected<QueuedVideoFrame>> {
376        if self.failed {
377            return Err(Rejected::new(
378                Error::UnexpectedSdkResult(crate::SdkResultDefect::UnknownCompletion),
379                frame.into_frame(),
380            ));
381        }
382        let Some(total) = self
383            .bytes
384            .checked_add(bytes)
385            .filter(|total| *total <= self.options.bytes)
386        else {
387            return Err(Rejected::new(
388                Error::QueueFull(QueueLimit::Bytes),
389                frame.into_frame(),
390            ));
391        };
392        debug_invariant!(self.free.len() + self.retained() <= self.options.frames);
393        let Some(slot_key) = self.free.pop() else {
394            return Err(Rejected::new(
395                Error::QueueFull(QueueLimit::Frames),
396                frame.into_frame(),
397            ));
398        };
399        let Some(next) = self.next.checked_add(1) else {
400            self.free.push(slot_key);
401            return Err(Rejected::new(
402                Error::InvalidInput(crate::InputDefect::QueueIdentifiersExhausted),
403                frame.into_frame(),
404            ));
405        };
406        let mut frame = frame;
407        let lent = lend(&mut frame);
408        let key = lent.descriptor().p_data as usize;
409        let id = SubmissionId(self.next);
410        let mut pointer = std::ptr::null();
411        let result = self
412            .in_flight
413            .insert_new_with(key, (slot_key, frame), |(slot_key, frame)| {
414                // All rejection checks and lending precede slot initialization.
415                // The move-only key can initialize this header only once.
416                let slot = slot_key.claim(*lent.descriptor());
417                pointer = slot.as_ptr();
418                Entry {
419                    id,
420                    slot,
421                    frame,
422                    bytes,
423                }
424            });
425        if let Err((slot_key, frame)) = result {
426            self.free.push(slot_key);
427            self.failed = true;
428            return Err(Rejected::new(
429                Error::UnexpectedSdkResult(crate::SdkResultDefect::UnknownCompletion),
430                frame.into_frame(),
431            ));
432        }
433        self.next = next;
434        self.bytes = total;
435        Ok(Admitted { id, lent, pointer })
436    }
437
438    /// Recognize and publish completion failure while admission is excluded.
439    #[cfg(any(test, ndi_has_advanced_send_completion))]
440    fn complete(&mut self, address: usize) {
441        match self.in_flight.remove(&address) {
442            Some(entry) => {
443                let completion = Completion { _private: () };
444                self.ready.push_back(ReadyEntry { entry, completion });
445            }
446            // Address matching relies on exactly one completion after the
447            // SDK's last access. A duplicate after resubmission cannot be
448            // distinguished, and an unknown address must stop admission.
449            None => self.failed = true,
450        }
451    }
452
453    /// Release every retained entry only after native destruction. Both
454    /// explicit close and implicit drop use this path, so even an unmatched
455    /// completion cannot release a frame while the SDK might still use it.
456    fn release_retained(&mut self, destroyed: &Destroyed, mut release: impl FnMut(CompletedVideo)) {
457        for ready in self.ready.drain(..) {
458            let (completed, key) = ready.entry.release(Released::Destroyed(destroyed));
459            release(completed);
460            self.free.push(key);
461        }
462        for (_, entry) in self.in_flight.drain() {
463            let (completed, key) = entry.release(Released::Destroyed(destroyed));
464            release(completed);
465            self.free.push(key);
466        }
467        self.bytes = 0;
468    }
469
470    fn take_retained(&mut self, destroyed: &Destroyed) -> Vec<CompletedVideo> {
471        let mut completed = Vec::with_capacity(self.retained());
472        let ready = self.ready.len();
473        self.release_retained(destroyed, |entry| completed.push(entry));
474        // The ready prefix already records completion order. Sorting only the
475        // unmatched suffix needs no allocation beyond the returned vector.
476        completed[ready..].sort_unstable_by_key(|entry| entry.id.get());
477        completed
478    }
479}
480
481pub(crate) struct CallbackState {
482    // Immutable, so permanent admission failures need neither the state lock
483    // nor a native descriptor allocation.
484    max_bytes: usize,
485    state: Mutex<State>,
486    changed: Condvar,
487}
488
489impl CallbackState {
490    /// Validate and retain one entry for this callback's owning sender.
491    pub(crate) fn prepare(
492        &self,
493        sender: &Sender<QueueAttached>,
494        frame: QueuedVideoFrame,
495    ) -> std::result::Result<Admitted, Rejected<QueuedVideoFrame>> {
496        let failure = Rejected::new;
497        let bytes = frame.retained_bytes();
498        let frame = frame.authorize(sender)?;
499        if let Err(error) = self.validate_frame_size(bytes) {
500            return Err(failure(error, frame.into_frame()));
501        }
502        {
503            let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
504            state.admit(frame, bytes)
505        }
506    }
507
508    #[cfg(any(test, ndi_has_advanced_send_completion))]
509    fn new(options: QueueLimits) -> Result<Box<Self>> {
510        let options = options.validate()?;
511        use super::send_slots::unavailable;
512        let in_flight = ReservedMap::try_with_capacity(options.frames).map_err(unavailable)?;
513        let mut ready = VecDeque::new();
514        ready
515            .try_reserve_exact(options.frames)
516            .map_err(unavailable)?;
517        let free = DescriptorSlots::allocate_keys(options.frames)?;
518        let state = Box::new(Self {
519            max_bytes: options.bytes,
520            state: Mutex::new(State {
521                in_flight,
522                ready,
523                bytes: 0,
524                next: 1,
525                options,
526                free,
527                failed: false,
528            }),
529            changed: Condvar::new(),
530        });
531        // Where the standard library allocates a mutex's or condition
532        // variable's operating-system object on first use, as it does on
533        // macOS, that first use must not be the SDK's thread reporting a
534        // completion, which would then allocate. Use both once here, on the
535        // thread creating the queue.
536        drop(state.state.lock());
537        state.changed.notify_all();
538        Ok(state)
539    }
540
541    fn retained_frames(&self) -> usize {
542        self.state
543            .lock()
544            .unwrap_or_else(|p| p.into_inner())
545            .retained()
546    }
547
548    fn completion_protocol_failed(&self) -> bool {
549        self.state.lock().unwrap_or_else(|p| p.into_inner()).failed
550    }
551
552    fn validate_frame_size(&self, bytes: usize) -> Result<()> {
553        if bytes > self.max_bytes {
554            return Err(Error::InvalidInput(
555                crate::InputDefect::QueueFrameTooLarge {
556                    bytes,
557                    limit: self.max_bytes,
558                },
559            ));
560        }
561        Ok(())
562    }
563
564    /// Publish an out-of-band callback failure. Recover poison because a
565    /// bookkeeping panic also reaches here.
566    #[cfg(any(test, ndi_has_advanced_send_completion))]
567    fn publish_protocol_failure(&self) {
568        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
569        state.failed = true;
570        self.changed.notify_all();
571    }
572
573    fn next_completed(&self, deadline: Deadline) -> Result<Option<CompletedVideo>> {
574        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
575        loop {
576            if let Some(frame) = take_completed(&mut state) {
577                return Ok(Some(frame));
578            }
579            if state.failed {
580                return Err(Error::UnexpectedSdkResult(
581                    crate::SdkResultDefect::UnknownCompletion,
582                ));
583            }
584            let remaining = deadline.remaining();
585            if remaining.is_zero() {
586                return Ok(None);
587            }
588            let (next, _) = self
589                .changed
590                .wait_timeout(state, remaining)
591                .unwrap_or_else(|p| p.into_inner());
592            state = next;
593        }
594    }
595
596    /// Record that the SDK has finished with the frame whose data is at
597    /// `address`. Runs on an SDK thread.
598    ///
599    /// No allocator or user code runs here. Removing the entry from the map
600    /// keeps the map's storage (std gives a map's storage back only through
601    /// `shrink_to` and `shrink_to_fit`), and `ready` was given room for every
602    /// frame the queue can hold before the callback was registered, while
603    /// `try_submit` keeps the queue within that many. The entry is moved, so
604    /// nothing is freed.
605    #[cfg(any(test, ndi_has_advanced_send_completion))]
606    fn complete(&self, address: usize) {
607        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
608        state.complete(address);
609        drop(state);
610        self.changed.notify_all();
611    }
612}
613/// The callback storage paired with an exclusive queue sender.
614pub(crate) type QueueLoans = AliasableBox<CallbackState>;
615
616/// The completion callback the SDK calls, on its own threads, when it has
617/// finished with an asynchronously sent frame.
618#[cfg(any(test, ndi_has_advanced_send_completion))]
619unsafe extern "C" fn completion(opaque: *mut c_void, frame: *const NDIlib_video_frame_v2_t) {
620    if opaque.is_null() {
621        return;
622    }
623    // SAFETY: `opaque` is the callback state registered with the sender. The
624    // SDK makes no call after the sender is destroyed, and the owning
625    // `QueuedSender` releases the state only after that.
626    let state = unsafe { &*opaque.cast::<CallbackState>() };
627    if frame.is_null() {
628        state.publish_protocol_failure();
629        return;
630    }
631    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
632        // The SDK may pass its own copy of the descriptor, so a submission is
633        // recognized by its data allocation, which is unique while retained.
634        // SAFETY: non-null was checked, and the SDK passes a readable descriptor.
635        // Releasing the matched loan relies on exactly one completion per
636        // submission, delivered after the SDK's last access to that frame.
637        state.complete(unsafe { (*frame).p_data } as usize);
638    }));
639    if result.is_err() {
640        state.publish_protocol_failure();
641    }
642}
643
644/// A sender that queues video frames and reports when each has been sent.
645///
646/// An ordinary asynchronous send must wait for the previous frame before it
647/// can accept the next. This sender instead keeps every submitted frame until
648/// the SDK reports it complete, so accepting another frame does not require
649/// waiting for an earlier completion, up to the limits in [`QueueLimits`].
650/// With [`SenderOptions::clock_video`] enabled, the default, the SDK still
651/// paces video inside each submission call: the first can return immediately,
652/// while later calls wait for the next frame time. Set `clock_video(false)`
653/// and pace submissions in the application, or use [`super::Genlock`], to
654/// avoid that frame-rate wait. Native back-pressure can also block a call.
655/// No application code runs
656/// on an SDK thread: completed frames are collected with
657/// [`try_next_completed`](Self::try_next_completed) or
658/// [`next_completed`](Self::next_completed) and can be reused.
659///
660/// It is [`Send`] and [`Sync`]: it can be moved to, and its read-only methods
661/// called from, any thread, while submitting and collecting frames takes it
662/// mutably. [`close`](Self::close) destroys the native sender and returns
663/// every retained frame with its submission id. Dropping it destroys the
664/// sender and frees those frames instead. Both wait, without a timeout, for
665/// the SDK to finish with every frame still queued, so run teardown on a
666/// blocking thread when using an async executor.
667///
668/// [`sender`](Self::sender) lends the native sender in the [`QueueAttached`]
669/// mode, which has the operations every sender shares (the source, metadata
670/// in both directions, tally, connections, failover, and the Advanced
671/// controls) and [`send_audio`](Sender::send_audio), but none of the video
672/// sends, and which cannot be registered with a
673/// [`SendAdvertiser`](crate::discovery_server::SendAdvertiser).
674///
675/// # Examples
676///
677/// ```no_run
678/// use std::time::Duration;
679/// use grafton_ndi::{
680///     advanced::{QueueLimits, QueuedSender},
681///     SenderOptions, VideoFrame, Ndi,
682/// };
683///
684/// # fn main() -> Result<(), grafton_ndi::Error> {
685/// let ndi = Ndi::new()?;
686/// let mut sender = QueuedSender::new(
687///     &ndi,
688///     // Completion-based sends are paced by the application.
689///     &SenderOptions::new("Queued").clock_video(false),
690///     &QueueLimits::default().max_frames(4),
691/// )?;
692/// let id = sender.try_submit(VideoFrame::builder().resolution(1920, 1080).build()?)?;
693/// if let Some(done) = sender.next_completed(Duration::from_secs(1))? {
694///     assert_eq!(done.id(), id);
695/// }
696/// # Ok(())
697/// # }
698/// ```
699pub struct QueuedSender {
700    lending: Lending<QueueAttached, AliasableBox<CallbackState>>,
701}
702
703impl Loans for AliasableBox<CallbackState> {
704    type Recovered = Vec<CompletedVideo>;
705
706    fn recover(self, destroyed: &Destroyed) -> Vec<CompletedVideo> {
707        self.state
708            .lock()
709            .unwrap_or_else(|p| p.into_inner())
710            .take_retained(destroyed)
711    }
712
713    fn release(self, destroyed: &Destroyed) {
714        self.state
715            .lock()
716            .unwrap_or_else(|p| p.into_inner())
717            .release_retained(destroyed, drop);
718    }
719}
720
721// `QueuedSender` is `Send` and `Sync` from its fields, with no impl of its
722// own. The Advanced SDK manual's section on asynchronous sending completions
723// (25.4.1.1) has the SDK call the handler on threads of its own, possibly
724// several at once, lets it be replaced at any time, and has
725// `NDIlib_send_destroy` call every outstanding completion before it returns;
726// it puts no thread requirement on the sender or on its completion
727// registration. The lent sender is the crate's ordinary `Send + Sync` native
728// sender. CallbackState keeps an immutable byte limit and shares mutable
729// state through one mutex and its condition variable. Application operations
730// that change the queue take `&mut self`.
731// The runtime test `a_queued_sender_moves_between_threads` sends, completes,
732// reads and drops one on threads other than the one that created it.
733const_assert!({
734    const fn send_and_sync<T: Send + Sync>() {}
735    send_and_sync::<QueuedSender>();
736});
737
738impl QueuedSender {
739    /// Create a sender, with the options' Advanced SDK
740    /// [configuration](SenderOptions::config) when they carry one.
741    ///
742    /// # Errors
743    ///
744    /// [`Error::UnsupportedCapability`] without an Advanced runtime (or in a
745    /// build without the Advanced SDK), [`Error::InvalidInput`] for
746    /// limits outside their range, [`Error::AllocationFailed`] when completion
747    /// storage cannot be reserved, and the errors of [`Sender::new`].
748    #[doc(alias = "NDIlib_send_set_video_async_completion")]
749    pub fn new(ndi: &Ndi, options: &SenderOptions, limits: &QueueLimits) -> Result<Self> {
750        let table = ndi.table::<SendCompletion>()?;
751        native!(SendCompletion, table, uses(options, limits) => {
752            let callback = CallbackState::new(*limits)?;
753            let sender = Sender::open(ndi, options)?;
754            Ok(Self::install(sender, callback, table.NDIlib_send_set_video_async_completion))
755        })
756    }
757
758    /// Turn an existing sender into a queued one.
759    ///
760    /// The sender's own asynchronous video send is finished first: the SDK is
761    /// drained, and the frame the sender was still holding, if any, is
762    /// returned beside the queue. The conversion is one-way.
763    ///
764    /// # Errors
765    ///
766    /// Returns the sender, unchanged, with [`Error::UnsupportedCapability`]
767    /// without an Advanced runtime, or [`Error::InvalidInput`] for
768    /// limits outside their range or a sender that is registered with an
769    /// advertiser (a registration keeps the native sender alive after this
770    /// value is dropped, when the completion state no longer exists).
771    /// [`Error::AllocationFailed`] when completion storage cannot be reserved.
772    #[doc(alias = "NDIlib_send_set_video_async_completion")]
773    pub fn from_sender(
774        sender: Sender,
775        limits: &QueueLimits,
776    ) -> std::result::Result<(Self, Option<VideoFrame>), Rejected<Sender>> {
777        let table = match sender.runtime().table::<SendCompletion>() {
778            Ok(table) => table,
779            Err(error) => return Err(Rejected::new(error, sender)),
780        };
781        native!(SendCompletion, table, uses(limits) => {
782            let register = table.NDIlib_send_set_video_async_completion;
783            let callback = match CallbackState::new(*limits) {
784                Ok(callback) => callback,
785                Err(error) => return Err(Rejected::new(error, sender)),
786            };
787            // The conversion takes the native sender only when no registration
788            // shares it, and retires the sender's asynchronous video pipeline.
789            match sender.into_attached() {
790                Ok((sender, earlier)) => Ok((Self::install(sender, callback, register), earlier)),
791                Err(sender) => Err(Rejected::new(
792                    Error::InvalidInput(crate::InputDefect::QueuedSenderRegistered),
793                    sender,
794                )),
795            }
796        })
797    }
798
799    /// Register the completion callback before anything can be submitted.
800    ///
801    /// The sender's mode owns its native sender exclusively and has no
802    /// asynchronous video pipeline, so nothing else is in flight on it: only
803    /// the queue sends video on it from now on.
804    #[cfg(ndi_has_advanced_send_completion)]
805    fn install(
806        sender: Sender<QueueAttached>,
807        callback: Box<CallbackState>,
808        register: unsafe extern "C" fn(
809            NDIlib_send_instance_t,
810            *mut c_void,
811            Option<unsafe extern "C" fn(*mut c_void, *const NDIlib_video_frame_v2_t)>,
812        ),
813    ) -> Self {
814        let callback = AliasableBox::new(callback);
815        let state = callback.as_ptr();
816        // SAFETY: the sender is live. The state is heap-allocated, the callback
817        // only reads it through a shared reference, and the returned value
818        // keeps it until after the sender has been destroyed.
819        unsafe {
820            register(
821                sender.handle().instance(),
822                state.cast_mut().cast(),
823                Some(completion),
824            )
825        };
826        Self {
827            lending: Lending::new(sender, callback),
828        }
829    }
830
831    /// The sender this queue sends through, for the operations that do not
832    /// send video: [`source`](Sender::source),
833    /// [`send_audio`](Sender::send_audio),
834    /// [`send_compressed_audio`](Sender::send_compressed_audio),
835    /// [`send_scatter_audio`](Sender::send_scatter_audio),
836    /// [`send_metadata`](Sender::send_metadata) and
837    /// [`capture_metadata`](Sender::capture_metadata),
838    /// [`tally`](Sender::tally), [`connection_count`](Sender::connection_count),
839    /// connection metadata, failover, and the Advanced controls.
840    ///
841    /// Its mode has none of the video sends, which would bypass the queue, and
842    /// it cannot be registered with an advertiser. Use [`split`](Self::split)
843    /// to send audio or metadata through it while another thread submits video.
844    pub fn sender(&self) -> &Sender<QueueAttached> {
845        self.lending.sender()
846    }
847
848    /// Lend video submission and completion collection separately from
849    /// uncompressed or compressed audio, metadata and controls. The halves can be moved to separate scoped
850    /// threads; dropping them restores access to this owner.
851    ///
852    /// Only the video half submits video, and it is neither `Sync` nor `Clone`.
853    pub fn split(&mut self) -> (QueuedVideo<'_>, &Sender<QueueAttached>) {
854        let pair = self.lending.parts().shared();
855        let sender = pair.sender();
856        let video = QueuedVideo {
857            pair,
858            _not_sync: NotSync::default(),
859        };
860        (video, sender)
861    }
862
863    fn video(&mut self) -> QueuedVideo<'_> {
864        self.split().0
865    }
866
867    /// Queue a frame without waiting for an earlier submission to complete.
868    ///
869    /// With [`SenderOptions::clock_video`] enabled, the default, the SDK paces
870    /// video to its frame rate inside this call. The first submission can
871    /// return immediately; subsequent calls wait for the next frame time.
872    /// Disable video clocking and pace the application, or use
873    /// [`super::Genlock`], to avoid this wait. SDK back-pressure can still block.
874    ///
875    /// The queue owns the frame until it is collected: the SDK writes to a
876    /// compressed frame's bytes while it sends them. A collected frame can be
877    /// submitted again.
878    /// Descriptor storage is reserved at construction, so accepted submission
879    /// allocates nothing. Pixels, blocks and metadata move without
880    /// copies or growth; owned uncompressed frames already hold all SDK tail
881    /// room their layout and scan type need.
882    ///
883    /// # Errors
884    ///
885    /// Returns the frame with [`Error::InvalidInput`] when its retained
886    /// allocation capacity alone exceeds [`QueueLimits::max_bytes`], or with
887    /// [`Error::QueueFull`] when the frames already retained leave no room
888    /// within [`QueueLimits`] ([`QueueLimit::Frames`] or
889    /// [`QueueLimit::Bytes`]; collect completed frames and submit it again),
890    /// with [`Error::UnexpectedSdkResult`] when the queue has failed (see
891    /// [`completion_protocol_failed`](Self::completion_protocol_failed)),
892    /// with [`Error::UnsupportedCapability`] when the runtime lacks scatter
893    /// sending or cannot send an uncompressed frame's pixel format
894    /// (as [`Sender::send_video`] checks).
895    #[doc(alias = "NDIlib_send_send_video_async_v2")]
896    #[doc(alias = "NDIlib_send_send_video_scatter_async")]
897    pub fn try_submit(
898        &mut self,
899        frame: impl Into<QueuedVideoFrame>,
900    ) -> std::result::Result<SubmissionId, Rejected<QueuedVideoFrame>> {
901        self.video().try_submit(frame)
902    }
903
904    /// Take one completed frame, if there is one.
905    pub fn try_next_completed(&mut self) -> Option<CompletedVideo> {
906        self.video().try_next_completed()
907    }
908
909    /// Wait up to `timeout` for a completed frame. `None` means none completed
910    /// in time; the queue is unchanged and can still be used.
911    ///
912    /// # Errors
913    ///
914    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
915    /// and [`Error::UnexpectedSdkResult`] when the queue has failed (see
916    /// [`completion_protocol_failed`](Self::completion_protocol_failed)).
917    pub fn next_completed(&mut self, timeout: Duration) -> Result<Option<CompletedVideo>> {
918        self.video().next_completed(timeout)
919    }
920
921    /// The number of frames held: those still being sent and those completed
922    /// but not yet collected.
923    pub fn retained_frames(&self) -> usize {
924        self.lending.loans().retained_frames()
925    }
926
927    /// Whether the SDK has reported a completion that matches no retained
928    /// submission, such as a frame it was never given, or one completed twice
929    /// before it was submitted again.
930    ///
931    /// The queue identifies a completion by the frame's data allocation and
932    /// relies on the SDK reporting exactly one completion per submission,
933    /// after its last access to the frame. A repeated completion after that
934    /// allocation is submitted again cannot be distinguished from its new
935    /// submission's completion.
936    ///
937    /// The queue then no longer knows which frames the SDK still reads, so it
938    /// accepts no more submissions; frames already completed can still be
939    /// collected. Use [`close`](Self::close) to destroy the native sender and
940    /// take back every frame still retained, including unmatched submissions.
941    pub fn completion_protocol_failed(&self) -> bool {
942        self.lending.loans().completion_protocol_failed()
943    }
944
945    /// Destroy the sender and take back every frame it still holds.
946    ///
947    /// The returned count equals [`retained_frames`](Self::retained_frames)
948    /// immediately before this call. Frames reported complete, including by
949    /// callbacks during destruction, come first in completion order. Any
950    /// unmatched frames follow in submission-id order. Each frame keeps its
951    /// original allocations and submission id, even after a
952    /// [completion-protocol failure](Self::completion_protocol_failed).
953    ///
954    /// Native destruction waits without a timeout for the SDK to finish with
955    /// every pending frame. Run this on a blocking thread when using an async
956    /// executor. Only the returned collection is allocated.
957    #[doc(alias = "NDIlib_send_destroy")]
958    pub fn close(self) -> Vec<CompletedVideo> {
959        self.lending.close()
960    }
961}
962
963/// Exclusive video operations borrowed from a [`QueuedSender`].
964///
965/// Move this half to a scoped video thread while the other half sends audio,
966/// metadata or controls. It is `Send`, but neither `Sync` nor `Clone`, and
967/// cannot outlive its owner. Dropping it leaves pending frames with the owner.
968pub struct QueuedVideo<'a> {
969    pair: LoanPair<'a, QueueAttached, &'a AliasableBox<CallbackState>>,
970    _not_sync: NotSync,
971}
972
973impl QueuedVideo<'_> {
974    /// See [`QueuedSender::try_submit`].
975    ///
976    /// # Errors
977    ///
978    /// As for [`QueuedSender::try_submit`].
979    #[doc(alias = "NDIlib_send_send_video_async_v2")]
980    #[doc(alias = "NDIlib_send_send_video_scatter_async")]
981    pub fn try_submit(
982        &mut self,
983        frame: impl Into<QueuedVideoFrame>,
984    ) -> std::result::Result<SubmissionId, Rejected<QueuedVideoFrame>> {
985        self.pair.try_submit_queued(frame)
986    }
987
988    /// See [`QueuedSender::try_next_completed`].
989    pub fn try_next_completed(&mut self) -> Option<CompletedVideo> {
990        let mut state = self
991            .pair
992            .loans()
993            .state
994            .lock()
995            .unwrap_or_else(|p| p.into_inner());
996        take_completed(&mut state)
997    }
998
999    /// See [`QueuedSender::next_completed`].
1000    ///
1001    /// # Errors
1002    ///
1003    /// As for [`QueuedSender::next_completed`].
1004    pub fn next_completed(&mut self, timeout: Duration) -> Result<Option<CompletedVideo>> {
1005        self.pair.loans().next_completed(Deadline::after(timeout)?)
1006    }
1007
1008    /// See [`QueuedSender::retained_frames`].
1009    pub fn retained_frames(&self) -> usize {
1010        self.pair.loans().retained_frames()
1011    }
1012
1013    /// See [`QueuedSender::completion_protocol_failed`].
1014    pub fn completion_protocol_failed(&self) -> bool {
1015        self.pair.loans().completion_protocol_failed()
1016    }
1017}
1018
1019fn take_completed(state: &mut State) -> Option<CompletedVideo> {
1020    let ReadyEntry { entry, completion } = state.ready.pop_front()?;
1021    state.bytes -= entry.bytes;
1022    let (completed, key) = entry.release(Released::Completed(completion));
1023    state.free.push(key);
1024    Some(completed)
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029    use super::*;
1030    use crate::frames::VideoPartsExt;
1031    use std::sync::atomic::{AtomicBool, Ordering};
1032
1033    #[test]
1034    fn completed_packet_debug_is_bounded_by_fields_not_payload() {
1035        use crate::advanced::{EnvelopeCodec, PacketEnvelope, VideoCodec, VideoPacketFormat};
1036        let summaries = |size| {
1037            let bytes =
1038                PacketEnvelope::encode(EnvelopeCodec::H264, 17, 13, true, &vec![7; size], &[1, 2])
1039                    .unwrap();
1040            let format = VideoPacketFormat::new(VideoCodec::H264, 16, 16).unwrap();
1041            [
1042                QueuedVideoFrame::Compressed(
1043                    CompressedFrame::<VideoPacketFormat>::new(format, bytes.clone()).unwrap(),
1044                ),
1045                QueuedVideoFrame::Scatter(
1046                    ScatterFrame::<VideoPacketFormat>::new(
1047                        format,
1048                        vec![bytes[..44].to_vec(), bytes[44..].to_vec()],
1049                    )
1050                    .unwrap(),
1051                ),
1052            ]
1053            .map(|frame| {
1054                format!(
1055                    "{:?}",
1056                    CompletedVideo {
1057                        id: SubmissionId(1),
1058                        frame
1059                    }
1060                )
1061            })
1062        };
1063        crate::test_support::assert_bounded_debug(&summaries(1024), &summaries(1024 * 1024));
1064    }
1065
1066    #[test]
1067    fn scatter_authorization_refusal_recovers_the_original_queued_frame() {
1068        let format =
1069            super::super::VideoPacketFormat::new(super::super::VideoCodec::SpeedHq422, 16, 16)
1070                .unwrap();
1071        let frame =
1072            ScatterFrame::<VideoPacketFormat>::new(format, vec![vec![1, 2, 3, 4], vec![5, 6]])
1073                .unwrap();
1074        let blocks: Vec<_> = frame.blocks().map(|block| block.as_ptr()).collect();
1075        let rejected = QueuedVideoFrame::Scatter(frame)
1076            .authorize_with(
1077                |_| panic!("a scatter frame must use the scatter proof"),
1078                |frame| ScatterSendable::for_test(frame, None),
1079            )
1080            .err()
1081            .unwrap();
1082        assert!(matches!(
1083            rejected.error(),
1084            Error::UnsupportedCapability {
1085                capability: crate::Capability::Runtime(crate::RuntimeFeature::ScatterSend),
1086                ..
1087            }
1088        ));
1089        let QueuedVideoFrame::Scatter(frame) = rejected.into_inner() else {
1090            panic!("the original scatter input is recovered")
1091        };
1092        assert_eq!(
1093            frame
1094                .blocks()
1095                .map(|block| block.as_ptr())
1096                .collect::<Vec<_>>(),
1097            blocks
1098        );
1099    }
1100
1101    #[test]
1102    fn split_submission_reuses_reserved_descriptors() {
1103        let Some(ndi) = crate::test_support::advanced_ndi() else {
1104            return;
1105        };
1106        let mut queue = QueuedSender::new(
1107            &ndi,
1108            &SenderOptions::new(crate::test_support::unique_name("split-allocation"))
1109                .clock_video(false),
1110            &QueueLimits::default(),
1111        )
1112        .unwrap();
1113        let frame = VideoFrame::builder().resolution(16, 16).build().unwrap();
1114        let ((mut video, _audio), allocations) =
1115            crate::test_alloc::allocation_count(|| queue.split());
1116        assert_eq!(allocations, 0);
1117        let (result, allocations) = crate::test_alloc::allocation_count(|| video.try_submit(frame));
1118        result.unwrap();
1119        assert_eq!(allocations, 0);
1120    }
1121
1122    /// Drive the same entry check with an already-retained key, while the
1123    /// rejected frame owns a different allocation and is never sent.
1124    fn reject_an_occupied_completion_key(callback: &CallbackState) -> (SubmissionId, usize) {
1125        let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1126        let bytes = frame.retained_bytes();
1127        let mut state = callback.state.lock().unwrap();
1128        let admitted = state
1129            .admit(
1130                QueuedVideoFrame::from(frame).authorize_for_test(None),
1131                bytes,
1132            )
1133            .unwrap();
1134        let key = admitted.lent.descriptor().p_data as usize;
1135        let before = (state.free.len(), state.retained(), state.bytes, state.next);
1136        let other = VideoFrame::builder().resolution(4, 2).build().unwrap();
1137        let other_pointer = other.data().as_ptr();
1138        let bytes = other.retained_bytes();
1139        let rejected = state
1140            .admit_with_lend(
1141                QueuedVideoFrame::from(other).authorize_for_test(None),
1142                bytes,
1143                |frame| {
1144                    Lent::Frame(NDIlib_video_frame_v2_t {
1145                        p_data: key as *mut u8,
1146                        ..*frame.lend().descriptor()
1147                    })
1148                },
1149            )
1150            .err()
1151            .expect("an occupied completion key is refused");
1152        assert!(matches!(rejected.error(), Error::UnexpectedSdkResult(_)));
1153        let QueuedVideoFrame::Pixels(other) = rejected.into_parts().1 else {
1154            panic!("the refused input is returned");
1155        };
1156        assert_eq!(other.data().as_ptr(), other_pointer);
1157        assert!(state.failed);
1158        assert_eq!(
1159            before,
1160            (state.free.len(), state.retained(), state.bytes, state.next)
1161        );
1162        let retained = state.in_flight.get(&key).unwrap();
1163        assert_eq!(retained.id, admitted.id);
1164        let QueuedStorage::Pixels(frame) = &retained.frame else {
1165            panic!("the retained entry is untouched");
1166        };
1167        assert_eq!(frame.video_descriptor().p_data as usize, key);
1168        (admitted.id, key)
1169    }
1170
1171    #[test]
1172    fn an_occupied_completion_key_preserves_every_retained_entry_and_free_slot() {
1173        let callback = CallbackState::new(QueueLimits::default().max_frames(2)).unwrap();
1174        let (id, key) = reject_an_occupied_completion_key(&callback);
1175        callback.complete(key);
1176        let mut state = callback.state.lock().unwrap();
1177        let completed = take_completed(&mut state).unwrap();
1178        assert_eq!(completed.id(), id);
1179        assert_eq!(state.free.len(), 2);
1180        assert_eq!(state.bytes, 0);
1181    }
1182
1183    #[test]
1184    fn close_recovers_the_entry_after_an_occupied_completion_key_was_refused() {
1185        let Some(ndi) = crate::test_support::advanced_ndi() else {
1186            return;
1187        };
1188        let queue = QueuedSender::new(
1189            &ndi,
1190            &SenderOptions::new(crate::test_support::unique_name("duplicate-key-close")),
1191            &QueueLimits::default().max_frames(2),
1192        )
1193        .unwrap();
1194        let (id, key) = reject_an_occupied_completion_key(queue.lending.loans());
1195        let completed = queue.close();
1196        assert_eq!(completed.len(), 1);
1197        assert_eq!(completed[0].id(), id);
1198        let QueuedVideoFrame::Pixels(frame) = completed[0].frame() else {
1199            panic!("close recovers the retained frame");
1200        };
1201        assert_eq!(frame.data().as_ptr() as usize, key);
1202    }
1203
1204    #[test]
1205    fn slots_are_retained_through_out_of_order_completion_and_reused_after_collection() {
1206        let callback = CallbackState::new(QueueLimits::default().max_frames(3)).unwrap();
1207        let mut admitted = Vec::new();
1208        for _ in 0..3 {
1209            let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1210            let bytes = frame.retained_bytes();
1211            admitted.push(
1212                callback
1213                    .state
1214                    .lock()
1215                    .unwrap()
1216                    .admit(
1217                        QueuedVideoFrame::from(frame).authorize_for_test(None),
1218                        bytes,
1219                    )
1220                    .unwrap(),
1221            );
1222        }
1223        assert!(callback.state.lock().unwrap().free.is_empty());
1224        std::thread::scope(|scope| {
1225            for index in [2, 0] {
1226                let callback = &callback;
1227                let key = admitted[index].lent.descriptor().p_data as usize;
1228                scope.spawn(move || callback.complete(key));
1229            }
1230        });
1231        let mut state = callback.state.lock().unwrap();
1232        assert_eq!(
1233            (state.in_flight.len(), state.ready.len(), state.free.len()),
1234            (1, 2, 0)
1235        );
1236        let (completed, allocations) =
1237            crate::test_alloc::allocation_count(|| take_completed(&mut state).unwrap());
1238        assert_eq!(allocations, 0);
1239        let prior = admitted
1240            .iter()
1241            .find(|entry| entry.id == completed.id())
1242            .unwrap();
1243        let frame = VideoFrame::builder().resolution(4, 2).build().unwrap();
1244        let bytes = frame.retained_bytes();
1245        let replacement = state
1246            .admit(
1247                QueuedVideoFrame::from(frame).authorize_for_test(None),
1248                bytes,
1249            )
1250            .unwrap();
1251        assert_eq!(replacement.pointer, prior.pointer);
1252        // SAFETY: the new synthetic header is initialized in the reclaimed
1253        // slot and has never been given to native code.
1254        assert_eq!(unsafe { (*replacement.pointer).xres }, 4);
1255        for other in admitted.iter().filter(|entry| entry.id != completed.id()) {
1256            assert_ne!(replacement.pointer, other.pointer);
1257            // SAFETY: these retained synthetic headers were never exposed to
1258            // native code, remain initialized, and their slots are not reused.
1259            assert_eq!(unsafe { (*other.pointer).xres }, 2);
1260        }
1261        assert!(state.free.is_empty());
1262    }
1263
1264    #[cfg(ndi_has_advanced_scatter_send)]
1265    #[test]
1266    fn native_admission_rejection_and_retry_use_only_reserved_descriptor_storage() {
1267        let Some(ndi) = crate::test_support::advanced_ndi() else {
1268            return;
1269        };
1270        let packet =
1271            super::super::VideoPacketFormat::new(super::super::VideoCodec::SpeedHq422, 16, 16)
1272                .unwrap();
1273        for variant in 0..3 {
1274            let make = || match variant {
1275                0 => QueuedVideoFrame::Pixels(
1276                    VideoFrame::builder().resolution(16, 16).build().unwrap(),
1277                ),
1278                1 => QueuedVideoFrame::Compressed(
1279                    CompressedFrame::<VideoPacketFormat>::new(packet, vec![1, 2, 3, 4]).unwrap(),
1280                ),
1281                _ => QueuedVideoFrame::Scatter(
1282                    ScatterFrame::<VideoPacketFormat>::new(
1283                        packet,
1284                        vec![vec![1, 2, 3, 4], vec![5, 6]],
1285                    )
1286                    .unwrap(),
1287                ),
1288            };
1289            for limit in [QueueLimit::Frames, QueueLimit::Bytes] {
1290                let first = make();
1291                let limits = if limit == QueueLimit::Frames {
1292                    QueueLimits::default().max_frames(1)
1293                } else {
1294                    QueueLimits::default()
1295                        .max_frames(2)
1296                        .max_bytes(first.retained_bytes())
1297                };
1298                let mut queue = QueuedSender::new(
1299                    &ndi,
1300                    &SenderOptions::new(crate::test_support::unique_name("reserved-admission"))
1301                        .clock_video(false),
1302                    &limits,
1303                )
1304                .unwrap();
1305                let (result, allocations) =
1306                    crate::test_alloc::allocation_count(|| queue.try_submit(first));
1307                let first_id = result.unwrap();
1308                assert_eq!(allocations, 0, "accepted variant {variant}");
1309                let second = make();
1310                let (result, allocations) =
1311                    crate::test_alloc::allocation_count(|| queue.try_submit(second));
1312                let rejected = result.unwrap_err();
1313                assert!(matches!(rejected.error(), Error::QueueFull(actual) if *actual == limit));
1314                assert_eq!(allocations, 1, "only the Rejected box, variant {variant}");
1315                assert_eq!(
1316                    queue
1317                        .next_completed(Duration::from_secs(5))
1318                        .unwrap()
1319                        .unwrap()
1320                        .id(),
1321                    first_id
1322                );
1323                let second = rejected.into_parts().1;
1324                let (result, allocations) =
1325                    crate::test_alloc::allocation_count(|| queue.try_submit(second));
1326                result.unwrap();
1327                assert_eq!(allocations, 0, "accepted retry variant {variant}");
1328                assert_eq!(queue.close().len(), 1);
1329            }
1330        }
1331    }
1332
1333    #[test]
1334    fn descriptor_admission_and_collection_stay_allocation_free_under_churn() {
1335        for capacity in [2, 4, 7, 8, 14, 16, 28, 56, 112] {
1336            let callback = CallbackState::new(QueueLimits::default().max_frames(capacity)).unwrap();
1337            let mut frames = (0..2304)
1338                .map(|_| VideoFrame::builder().resolution(2, 2).build().unwrap())
1339                .collect::<Vec<_>>();
1340            let mut keys = vec![0usize; capacity - 1];
1341            for key in keys.iter_mut() {
1342                let frame = frames.pop().unwrap();
1343                let bytes = frame.retained_bytes();
1344                let admitted = callback
1345                    .state
1346                    .lock()
1347                    .unwrap()
1348                    .admit(
1349                        QueuedVideoFrame::from(frame).authorize_for_test(None),
1350                        bytes,
1351                    )
1352                    .unwrap();
1353                *key = admitted.lent.descriptor().p_data as usize;
1354            }
1355            for index in 0..2000 {
1356                let frame = frames.pop().unwrap();
1357                let bytes = frame.retained_bytes();
1358                let authorized = QueuedVideoFrame::from(frame).authorize_for_test(None);
1359                let (admitted, allocations) = crate::test_alloc::allocation_count(|| {
1360                    callback.state.lock().unwrap().admit(authorized, bytes)
1361                });
1362                let admitted = admitted.unwrap();
1363                assert_eq!(
1364                    allocations, 0,
1365                    "accepted submission {index}, capacity {capacity}"
1366                );
1367                let completed = std::mem::replace(
1368                    &mut keys[index % (capacity - 1)],
1369                    admitted.lent.descriptor().p_data as usize,
1370                );
1371                callback.complete(completed);
1372                let (collected, allocations) = crate::test_alloc::allocation_count(|| {
1373                    take_completed(&mut callback.state.lock().unwrap())
1374                });
1375                assert!(collected.is_some());
1376                assert_eq!(allocations, 0);
1377            }
1378        }
1379    }
1380
1381    #[test]
1382    fn permanent_admission_check_needs_no_lock_or_descriptor() {
1383        let state = CallbackState::new(QueueLimits::default().max_bytes(4)).unwrap();
1384        // An occupied lock cannot delay this allocation-free refusal.
1385        let _locked = state.state.lock().unwrap();
1386        let (result, allocations) =
1387            crate::test_alloc::allocation_count(|| state.validate_frame_size(1024));
1388        let Error::InvalidInput(message) = result.unwrap_err() else {
1389            panic!("an oversized frame is not retryable");
1390        };
1391        assert_eq!(
1392            message,
1393            crate::InputDefect::QueueFrameTooLarge {
1394                bytes: 1024,
1395                limit: 4
1396            }
1397        );
1398        assert_eq!(allocations, 0);
1399        let (result, allocations) =
1400            crate::test_alloc::allocation_count(|| state.validate_frame_size(4));
1401        result.unwrap();
1402        assert_eq!(allocations, 0);
1403    }
1404
1405    #[test]
1406    fn queued_pixel_descriptor_fits_packed_copy_of_padded_source() {
1407        for (format, stride) in [
1408            (crate::PixelFormat::Bgra, 512),
1409            (crate::PixelFormat::Uyvy, 256),
1410            (crate::PixelFormat::P216, 256),
1411        ] {
1412            let planes = if format == crate::PixelFormat::P216 {
1413                2
1414            } else {
1415                1
1416            };
1417            let storage = vec![0u8; stride * 32 * planes];
1418            let borrowed = crate::BorrowedVideoFrame::builder(&storage, 64, 32, format)
1419                .line_stride_bytes(stride)
1420                .build()
1421                .unwrap();
1422            let pixels = borrowed.owned_copy();
1423            let readable = pixels.data().len() + pixels.tail_room();
1424            let pointer = pixels.data().as_ptr();
1425            let bytes = pixels.retained_bytes();
1426            let frame = QueuedVideoFrame::from(pixels).authorize_for_test(None);
1427            let callback = CallbackState::new(QueueLimits::default()).unwrap();
1428            let mut state = callback.state.lock().unwrap();
1429            let admitted = state.admit(frame, bytes).unwrap();
1430            crate::frames::descriptor_tests::assert_extent(
1431                admitted.lent.descriptor(),
1432                pointer,
1433                readable,
1434            );
1435        }
1436    }
1437
1438    #[test]
1439    fn every_authorized_storage_lends_its_original_completion_key() {
1440        let Some(ndi) = crate::test_support::advanced_ndi() else {
1441            return;
1442        };
1443        let table = ndi.table::<ScatterSend>().unwrap();
1444        let format =
1445            super::super::VideoPacketFormat::new(super::super::VideoCodec::SpeedHq422, 16, 16)
1446                .unwrap();
1447        for frame in [
1448            QueuedVideoFrame::Pixels(VideoFrame::builder().resolution(16, 16).build().unwrap()),
1449            QueuedVideoFrame::Compressed(
1450                CompressedFrame::<VideoPacketFormat>::new(format, vec![1, 2, 3, 4]).unwrap(),
1451            ),
1452            QueuedVideoFrame::Scatter(
1453                ScatterFrame::<VideoPacketFormat>::new(format, vec![vec![1, 2, 3, 4], vec![5, 6]])
1454                    .unwrap(),
1455            ),
1456        ] {
1457            let expected = match &frame {
1458                QueuedVideoFrame::Pixels(frame) => frame.data().as_ptr(),
1459                QueuedVideoFrame::Compressed(frame) => frame.data().as_ptr(),
1460                QueuedVideoFrame::Scatter(frame) => frame.blocks().next().unwrap().as_ptr(),
1461            };
1462            let bytes = frame.retained_bytes();
1463            let authorized = frame.authorize_for_test(Some(table));
1464            let callback = CallbackState::new(QueueLimits::default()).unwrap();
1465            let admitted = callback
1466                .state
1467                .lock()
1468                .unwrap()
1469                .admit(authorized, bytes)
1470                .unwrap();
1471            assert_eq!(admitted.lent.descriptor().p_data.cast_const(), expected);
1472        }
1473    }
1474
1475    fn insert(callback: &CallbackState, id: u64) -> usize {
1476        let pixels = VideoFrame::builder().resolution(2, 2).build().unwrap();
1477        let bytes = pixels.retained_bytes();
1478        let frame = QueuedVideoFrame::from(pixels).authorize_for_test(None);
1479        let mut state = callback.state.lock().unwrap();
1480        let admitted = state.admit(frame, bytes).unwrap();
1481        assert_eq!(admitted.id.get(), id);
1482        admitted.lent.descriptor().p_data as usize
1483    }
1484
1485    #[test]
1486    fn a_retired_slot_reduces_capacity_and_collection_still_allows_retry() {
1487        let callback = CallbackState::new(QueueLimits::default().max_frames(3)).unwrap();
1488        drop(
1489            callback
1490                .state
1491                .lock()
1492                .unwrap()
1493                .free
1494                .pop()
1495                .unwrap()
1496                .claim(Default::default()),
1497        );
1498        let first = insert(&callback, 1);
1499        insert(&callback, 2);
1500        let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1501        let pointer = frame.data().as_ptr();
1502        let bytes = frame.retained_bytes();
1503        let rejected = callback
1504            .state
1505            .lock()
1506            .unwrap()
1507            .admit(
1508                QueuedVideoFrame::from(frame).authorize_for_test(None),
1509                bytes,
1510            )
1511            .err()
1512            .unwrap();
1513        assert!(matches!(
1514            rejected.error(),
1515            Error::QueueFull(QueueLimit::Frames)
1516        ));
1517        let QueuedVideoFrame::Pixels(frame) = rejected.into_parts().1 else {
1518            panic!("the refused frame keeps its storage");
1519        };
1520        assert_eq!(frame.data().as_ptr(), pointer);
1521        callback.complete(first);
1522        let mut state = callback.state.lock().unwrap();
1523        assert_eq!(take_completed(&mut state).unwrap().id().get(), 1);
1524        let admitted = state
1525            .admit(
1526                QueuedVideoFrame::from(frame).authorize_for_test(None),
1527                bytes,
1528            )
1529            .unwrap();
1530        assert_eq!(admitted.id.get(), 3);
1531        assert_eq!(admitted.lent.descriptor().p_data.cast_const(), pointer);
1532        assert!(state.free.is_empty());
1533    }
1534
1535    #[test]
1536    fn failure_published_before_admission_preserves_the_frame_and_queue() {
1537        let callback = CallbackState::new(QueueLimits::default()).unwrap();
1538        callback.publish_protocol_failure();
1539        let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1540        let pointer = frame.data().as_ptr();
1541        let bytes = frame.retained_bytes();
1542        let mut state = callback.state.lock().unwrap();
1543        let before = (state.free.len(), state.retained(), state.next, state.bytes);
1544        let rejected = state
1545            .admit(
1546                QueuedVideoFrame::from(frame).authorize_for_test(None),
1547                bytes,
1548            )
1549            .err()
1550            .expect("a published completion failure prevents admission");
1551        assert!(matches!(
1552            rejected.error(),
1553            Error::UnexpectedSdkResult(crate::SdkResultDefect::UnknownCompletion)
1554        ));
1555        let QueuedVideoFrame::Pixels(frame) = rejected.into_inner() else {
1556            panic!("the refused frame keeps its storage");
1557        };
1558        assert_eq!(frame.data().as_ptr(), pointer);
1559        assert_eq!(
1560            (state.free.len(), state.retained(), state.next, state.bytes),
1561            before
1562        );
1563    }
1564
1565    #[test]
1566    fn an_unknown_completion_refuses_admission_under_the_same_guard() {
1567        let callback = CallbackState::new(QueueLimits::default()).unwrap();
1568        let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1569        let pointer = frame.data().as_ptr();
1570        let bytes = frame.retained_bytes();
1571        let mut state = callback.state.lock().unwrap();
1572        let before = (state.free.len(), state.retained(), state.next, state.bytes);
1573        state.complete(usize::MAX);
1574        let rejected = state
1575            .admit(
1576                QueuedVideoFrame::from(frame).authorize_for_test(None),
1577                bytes,
1578            )
1579            .err()
1580            .expect("failure is visible before the completion guard is released");
1581        assert!(matches!(
1582            rejected.error(),
1583            Error::UnexpectedSdkResult(crate::SdkResultDefect::UnknownCompletion)
1584        ));
1585        let QueuedVideoFrame::Pixels(frame) = rejected.into_inner() else {
1586            panic!("the rejected frame preserves storage");
1587        };
1588        assert_eq!(frame.data().as_ptr(), pointer);
1589        assert_eq!(
1590            (state.free.len(), state.retained(), state.next, state.bytes),
1591            before
1592        );
1593    }
1594
1595    #[test]
1596    fn concurrent_admissions_stop_after_failure_publication() {
1597        for via_completion in [false, true] {
1598            let callback = CallbackState::new(QueueLimits::default()).unwrap();
1599            let published = AtomicBool::new(false);
1600            let start = std::sync::Barrier::new(4);
1601            let attempts = if cfg!(miri) { 4 } else { 64 };
1602            std::thread::scope(|scope| {
1603                for _ in 0..3 {
1604                    scope.spawn(|| {
1605                        start.wait();
1606                        for _ in 0..attempts {
1607                            let frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
1608                            let bytes = frame.retained_bytes();
1609                            let mut state = callback.state.lock().unwrap();
1610                            let publication_observed = published.load(Ordering::Acquire);
1611                            let admission = state.admit(
1612                                QueuedVideoFrame::from(frame).authorize_for_test(None),
1613                                bytes,
1614                            );
1615                            match admission {
1616                                Ok(admitted) => {
1617                                    assert!(!publication_observed);
1618                                    let key = admitted.lent.descriptor().p_data as usize;
1619                                    drop(state);
1620                                    // No native call occurs: report the synthetic
1621                                    // loan complete before returning its storage.
1622                                    callback.complete(key);
1623                                    let mut state = callback.state.lock().unwrap();
1624                                    assert!(take_completed(&mut state).is_some());
1625                                }
1626                                Err(rejected) => assert!(matches!(
1627                                    rejected.error(),
1628                                    Error::UnexpectedSdkResult(
1629                                        crate::SdkResultDefect::UnknownCompletion
1630                                    )
1631                                )),
1632                            }
1633                            std::thread::yield_now();
1634                        }
1635                    });
1636                }
1637                start.wait();
1638                if via_completion {
1639                    callback.complete(usize::MAX);
1640                } else {
1641                    callback.publish_protocol_failure();
1642                }
1643                published.store(true, Ordering::Release);
1644            });
1645            assert!(published.load(Ordering::Acquire));
1646            let state = callback.state.lock().unwrap();
1647            assert_eq!(state.retained(), 0);
1648            assert_eq!(state.bytes, 0);
1649            assert_eq!(state.free.len(), QueueLimits::default().frames);
1650        }
1651    }
1652
1653    #[test]
1654    fn retired_slots_preserve_byte_frame_and_identifier_refusal_order() {
1655        let callback = CallbackState::new(QueueLimits::default().max_frames(1)).unwrap();
1656        let frame = || VideoFrame::builder().resolution(2, 2).build().unwrap();
1657        let mut state = callback.state.lock().unwrap();
1658        state.next = u64::MAX;
1659        let original_bytes = state.options.bytes;
1660        state.options.bytes = 0;
1661        let input = frame();
1662        let bytes = input.retained_bytes();
1663        let reject = |state: &mut State, input: VideoFrame| {
1664            state
1665                .admit(
1666                    QueuedVideoFrame::from(input).authorize_for_test(None),
1667                    bytes,
1668                )
1669                .err()
1670                .unwrap()
1671                .into_parts()
1672                .0
1673        };
1674        state.failed = true;
1675        assert!(matches!(
1676            reject(&mut state, input),
1677            Error::UnexpectedSdkResult(crate::SdkResultDefect::UnknownCompletion)
1678        ));
1679        state.failed = false;
1680        assert!(matches!(
1681            reject(&mut state, frame()),
1682            Error::QueueFull(QueueLimit::Bytes)
1683        ));
1684        state.options.bytes = original_bytes;
1685        assert!(matches!(
1686            reject(&mut state, frame()),
1687            Error::InvalidInput(crate::InputDefect::QueueIdentifiersExhausted)
1688        ));
1689        assert_eq!(state.free.len(), 1, "refusal returns the unused key");
1690        drop(state.free.pop().unwrap().claim(Default::default()));
1691        assert!(matches!(
1692            reject(&mut state, frame()),
1693            Error::QueueFull(QueueLimit::Frames)
1694        ));
1695    }
1696
1697    #[test]
1698    fn a_retired_slot_does_not_panic_on_close_or_drop() {
1699        let Some(ndi) = crate::test_support::advanced_ndi() else {
1700            return;
1701        };
1702        for close in [true, false] {
1703            let queue = QueuedSender::new(
1704                &ndi,
1705                &SenderOptions::new(crate::test_support::unique_name("retired-slot-teardown")),
1706                &QueueLimits::default().max_frames(4),
1707            )
1708            .unwrap();
1709            let callback = queue.lending.loans();
1710            drop(
1711                callback
1712                    .state
1713                    .lock()
1714                    .unwrap()
1715                    .free
1716                    .pop()
1717                    .unwrap()
1718                    .claim(Default::default()),
1719            );
1720            let first = insert(callback, 1);
1721            insert(callback, 2);
1722            let third = insert(callback, 3);
1723            callback.complete(third);
1724            callback.complete(first);
1725            if close {
1726                assert_eq!(
1727                    queue
1728                        .close()
1729                        .iter()
1730                        .map(|done| done.id().get())
1731                        .collect::<Vec<_>>(),
1732                    [3, 1, 2]
1733                );
1734            } else {
1735                drop(queue);
1736            }
1737        }
1738    }
1739
1740    #[test]
1741    fn close_recovers_ready_then_unmatched_frames_with_only_the_result_allocation() {
1742        let Some(ndi) = crate::test_support::advanced_ndi() else {
1743            return;
1744        };
1745        let queue = QueuedSender::new(
1746            &ndi,
1747            &SenderOptions::new(crate::test_support::unique_name("close-order")),
1748            &QueueLimits::default(),
1749        )
1750        .unwrap();
1751        let state = queue.lending.loans();
1752        // These entries were not sent, so the native sender cannot report
1753        // additional completions. They exercise both teardown collections.
1754        let original = [1, 2, 3, 4, 5].map(|id| (id, insert(state, id)));
1755        state.complete(original[3].1);
1756        state.complete(original[1].1);
1757        let retained = queue.retained_frames();
1758        let (completed, allocations) = crate::test_alloc::allocation_count(|| queue.close());
1759        assert_eq!(allocations, 1, "only the returned frame collection");
1760        assert_eq!(completed.len(), retained);
1761        assert_eq!(
1762            completed
1763                .iter()
1764                .map(|done| done.id().get())
1765                .collect::<Vec<_>>(),
1766            [4, 2, 1, 3, 5]
1767        );
1768        for done in completed {
1769            let QueuedVideoFrame::Pixels(frame) = done.frame() else {
1770                panic!("the frame changed type");
1771            };
1772            let expected = original
1773                .iter()
1774                .find(|(id, _)| *id == done.id().get())
1775                .unwrap()
1776                .1;
1777            assert_eq!(frame.data().as_ptr() as usize, expected);
1778        }
1779    }
1780
1781    #[test]
1782    fn drop_releases_retained_frames_without_allocating_a_recovery_collection() {
1783        let Some(ndi) = crate::test_support::advanced_ndi() else {
1784            return;
1785        };
1786        let queue = QueuedSender::new(
1787            &ndi,
1788            &SenderOptions::new(crate::test_support::unique_name("drop-allocation")),
1789            &QueueLimits::default(),
1790        )
1791        .unwrap();
1792        let state = queue.lending.loans();
1793        let first = insert(state, 1);
1794        insert(state, 2);
1795        state.complete(first);
1796        let ((), allocations) = crate::test_alloc::allocation_count(|| drop(queue));
1797        assert_eq!(allocations, 0);
1798    }
1799
1800    #[test]
1801    fn closing_an_empty_queue_needs_no_result_allocation() {
1802        let Some(ndi) = crate::test_support::advanced_ndi() else {
1803            return;
1804        };
1805        let queue = QueuedSender::new(
1806            &ndi,
1807            &SenderOptions::new(crate::test_support::unique_name("close-empty")),
1808            &QueueLimits::default(),
1809        )
1810        .unwrap();
1811        let (completed, allocations) = crate::test_alloc::allocation_count(|| queue.close());
1812        assert!(completed.is_empty());
1813        assert_eq!(allocations, 0);
1814    }
1815
1816    #[test]
1817    fn concurrent_and_out_of_order_callbacks_preserve_owned_frames() {
1818        let state = CallbackState::new(QueueLimits::default()).unwrap();
1819        let a = insert(&state, 1);
1820        let b = insert(&state, 2);
1821        state.complete(b);
1822        std::thread::scope(|scope| {
1823            scope.spawn(|| state.complete(a));
1824        });
1825        let mut s = state.state.lock().unwrap();
1826        assert_eq!((s.in_flight.len(), s.ready.len()), (0, 2));
1827        assert_eq!(take_completed(&mut s).unwrap().id().get(), 2);
1828        assert_eq!(take_completed(&mut s).unwrap().id().get(), 1);
1829        assert_eq!(s.bytes, 0);
1830    }
1831
1832    /// Conversion drains the sender and returns its frame beside the queue.
1833    #[test]
1834    fn converting_a_sender_returns_its_in_flight_frame() {
1835        let Some(ndi) = crate::test_support::advanced_ndi() else {
1836            return;
1837        };
1838        let options = SenderOptions::new(crate::test_support::unique_name("Queued conversion"))
1839            .clock_video(false);
1840        let mut sender = Sender::new(&ndi, &options).unwrap();
1841        let frame = VideoFrame::builder().resolution(16, 16).build().unwrap();
1842        let pixels = frame.data().as_ptr();
1843        assert!(sender.submit_video(frame).unwrap().is_none());
1844        let (mut queue, earlier) =
1845            QueuedSender::from_sender(sender, &QueueLimits::default()).unwrap();
1846        assert_eq!(earlier.unwrap().data().as_ptr(), pixels);
1847        // The queue sends on the converted sender.
1848        let next = VideoFrame::builder().resolution(16, 16).build().unwrap();
1849        let id = queue.try_submit(next).unwrap();
1850        let completed = queue.next_completed(Duration::from_secs(5)).unwrap();
1851        assert_eq!(completed.unwrap().id(), id);
1852    }
1853
1854    #[test]
1855    fn duplicate_and_unknown_completions_do_not_release_storage() {
1856        let state = CallbackState::new(QueueLimits::default()).unwrap();
1857        let a = insert(&state, 1);
1858        state.complete(a);
1859        state.complete(a);
1860        state.complete(0);
1861        let mut s = state.state.lock().unwrap();
1862        assert_eq!((s.in_flight.len(), s.ready.len()), (0, 1));
1863        assert!(s.failed);
1864        assert!(take_completed(&mut s).is_some());
1865        assert!(take_completed(&mut s).is_none());
1866    }
1867
1868    /// The SDK's thread neither allocates nor frees when it reports a
1869    /// completion, a duplicate or an unknown frame: the entry moves between
1870    /// storage reserved before the callback was registered, and neither
1871    /// collection gives any of it back.
1872    #[test]
1873    fn completion_moves_an_entry_without_allocating_or_freeing() {
1874        let state = CallbackState::new(QueueLimits::default().max_frames(3)).unwrap();
1875        let keys = [insert(&state, 1), insert(&state, 2), insert(&state, 3)];
1876        let capacities = |state: &CallbackState| {
1877            let s = state.state.lock().unwrap();
1878            (s.in_flight.capacity(), s.ready.capacity())
1879        };
1880        let reserved = capacities(&state);
1881        let ((), allocations) = crate::test_alloc::allocation_count(|| {
1882            for key in [keys[2], keys[0], keys[1], keys[0], 0] {
1883                state.complete(key);
1884            }
1885        });
1886        assert_eq!(allocations, 0);
1887        assert_eq!(capacities(&state), reserved);
1888        let mut s = state.state.lock().unwrap();
1889        assert_eq!((s.in_flight.len(), s.ready.len()), (0, 3));
1890        let order: Vec<_> = std::iter::from_fn(|| take_completed(&mut s))
1891            .map(|completed| completed.id().get())
1892            .collect();
1893        assert_eq!(order, [3, 1, 2]);
1894        assert!(s.failed);
1895    }
1896}
1897
1898#[cfg(test)]
1899#[path = "queued_boundary_tests.rs"]
1900mod boundary_tests;
1901
1902impl std::fmt::Debug for QueuedSender {
1903    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1904        f.debug_struct("QueuedSender")
1905            .field("sender", self.sender())
1906            .finish_non_exhaustive()
1907    }
1908}
1909
1910impl std::fmt::Debug for QueuedVideo<'_> {
1911    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1912        f.debug_struct("QueuedVideo")
1913            .field("sender", self.pair.sender())
1914            .finish_non_exhaustive()
1915    }
1916}