Skip to main content

grafton_ndi/advanced/
allocators.rs

1//! Application-supplied memory for received frames.
2//!
3//! The SDK calls an allocator and its matching free function on its own
4//! threads, with an opaque value chosen at registration. Here that value is a
5//! token naming one registered policy (a "generation"), never a pointer, and
6//! every allocation is recorded as a lease under the token that made it. A
7//! lease, and through it the policy, lives until the SDK frees that
8//! allocation, however long after the policy was replaced that happens.
9
10use std::{
11    alloc::{alloc_zeroed, dealloc, Layout},
12    collections::HashMap,
13    mem::ManuallyDrop,
14    panic::{catch_unwind, AssertUnwindSafe},
15    ptr::NonNull,
16    sync::{
17        atomic::{AtomicUsize, Ordering},
18        Arc, Mutex, MutexGuard, OnceLock,
19    },
20};
21
22use super::{
23    invalid_input, PacketAttached, PacketItem, PacketItemRef, PacketReceiver, ReceiverControls,
24};
25#[cfg(any(test, ndi_has_advanced_receive_allocators))]
26use super::{packets::PacketLen, AudioCodec, VideoCodec};
27#[cfg(any(test, ndi_has_advanced_receive_allocators))]
28use crate::sys::bindings::*;
29#[cfg(any(test, ndi_has_advanced_receive_allocators))]
30use crate::AudioFormat;
31use crate::{
32    frames::{ValidatedAudioLayout, ValidatedVideoLayout},
33    runtime::ProcessLifetimeRuntime,
34    sys::advanced::ReceiveAllocators,
35    FourCc, PixelFormat, RawCapture, Receiver, ReceiverMode, Rejected, Result,
36};
37#[cfg(any(test, ndi_has_advanced_receive_allocators))]
38use std::ffi::c_void;
39
40const MIB: usize = 1024 * 1024;
41
42pub use crate::media::MAX_ALLOCATION_BYTES;
43
44/// Process-wide limits on custom receive allocation.
45///
46/// The limits cover every receiver in the process, including allocations made
47/// by policies that have since been replaced and buffers whose release is
48/// still in progress. Memory a policy allocates for its own bookkeeping is not
49/// counted. A request the limits do not admit is declined, and the SDK then
50/// drops that frame. [`AllocatorService::usage`] reports these declines through
51/// [`AllocatorUsage::declined`] and [`AllocatorUsage::declined_allocations`].
52///
53/// The defaults are 256 generations, 1024 allocations, 1 GiB in total, 16
54/// concurrent calls and 64 MiB per allocation, which holds a packed
55/// 7680×4320 8-bit 4:2:2 frame.
56///
57/// # How the limits combine
58///
59/// A policy may return a larger buffer than the frame needs, so each call is
60/// granted its buffer before the policy runs: the largest single allocation,
61/// or what is left of the byte budget when that is less. A call is declined
62/// only when its grant cannot hold the frame, and it counts as an allocation
63/// while it runs. Limits are therefore accepted only when the stated number of
64/// concurrent calls can each be granted a largest allocation:
65/// `max_concurrent_calls` may not exceed `max_allocations`, and
66/// `max_concurrent_calls * max_allocation_bytes` may not exceed `max_bytes`.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
68pub struct AllocatorLimits {
69    max_generations: usize,
70    max_allocations: usize,
71    max_bytes: usize,
72    max_concurrent_calls: usize,
73    max_allocation_bytes: usize,
74}
75
76impl Default for AllocatorLimits {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl AllocatorLimits {
83    /// Requested maximum number of live policy generations.
84    #[must_use]
85    pub fn configured_max_generations(&self) -> usize {
86        self.max_generations
87    }
88
89    /// Requested maximum allocation count, including policy calls in progress.
90    #[must_use]
91    pub fn configured_max_allocations(&self) -> usize {
92        self.max_allocations
93    }
94
95    /// Requested maximum retained and granted bytes in total.
96    #[must_use]
97    pub fn configured_max_bytes(&self) -> usize {
98        self.max_bytes
99    }
100
101    /// Requested maximum number of concurrent policy calls.
102    #[must_use]
103    pub fn configured_max_concurrent_calls(&self) -> usize {
104        self.max_concurrent_calls
105    }
106
107    /// Requested maximum bytes granted to one allocation.
108    #[must_use]
109    pub fn configured_max_allocation_bytes(&self) -> usize {
110        self.max_allocation_bytes
111    }
112
113    /// The default limits: 256 generations, 1024 allocations, 1 GiB in total,
114    /// 16 concurrent calls and 64 MiB per allocation.
115    pub fn new() -> Self {
116        Self {
117            max_generations: 256,
118            max_allocations: 1024,
119            max_bytes: 1024 * MIB,
120            max_concurrent_calls: 16,
121            max_allocation_bytes: 64 * MIB,
122        }
123    }
124
125    /// The number of policies that may exist at once. A replaced policy
126    /// counts until the SDK has freed its last allocation.
127    #[must_use]
128    pub fn max_generations(mut self, value: usize) -> Self {
129        self.max_generations = value;
130        self
131    }
132
133    /// The number of allocations the SDK may hold at once, counting the
134    /// policy calls in progress.
135    #[must_use]
136    pub fn max_allocations(mut self, value: usize) -> Self {
137        self.max_allocations = value;
138        self
139    }
140
141    /// The total bytes the SDK may hold at once, counting what the policy
142    /// calls in progress have been granted.
143    #[must_use]
144    pub fn max_bytes(mut self, value: usize) -> Self {
145        self.max_bytes = value;
146        self
147    }
148
149    /// The number of policy calls that may run at the same time.
150    #[must_use]
151    pub fn max_concurrent_calls(mut self, value: usize) -> Self {
152        self.max_concurrent_calls = value;
153        self
154    }
155
156    /// The largest single allocation, at most [`MAX_ALLOCATION_BYTES`].
157    #[must_use]
158    pub fn max_allocation_bytes(mut self, value: usize) -> Self {
159        self.max_allocation_bytes = value;
160        self
161    }
162
163    fn validate(self) -> Result<Self> {
164        let limits_error = |cause| crate::Error::InvalidInput(cause);
165        if self.max_generations == 0
166            || self.max_allocations == 0
167            || self.max_concurrent_calls == 0
168            || self.max_allocation_bytes == 0
169        {
170            return Err(limits_error(crate::InputDefect::AllocatorPositiveLimits));
171        }
172        if self.max_allocation_bytes > MAX_ALLOCATION_BYTES {
173            return Err(limits_error(crate::InputDefect::AllocatorAllocationLimit));
174        }
175        if self.max_concurrent_calls > self.max_allocations {
176            return Err(limits_error(crate::InputDefect::AllocatorConcurrentLimit));
177        }
178        if self
179            .max_concurrent_calls
180            .checked_mul(self.max_allocation_bytes)
181            .is_none_or(|granted| granted > self.max_bytes)
182        {
183            return Err(limits_error(crate::InputDefect::AllocatorByteLimit));
184        }
185        Ok(self)
186    }
187}
188
189/// What the SDK needs memory for: one frame it is about to receive.
190///
191/// Planar audio is laid out as a picture is, one channel to a line: its
192/// [`width`](Self::width) is the number of samples per channel, its
193/// [`height`](Self::height) the number of channels, and its
194/// [`stride_bytes`](Self::stride_bytes) the distance between channels in bytes.
195#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
196pub struct AllocationRequest {
197    bytes: usize,
198    stride: usize,
199    layout: RequestLayout,
200    width: u32,
201    height: u32,
202    capacity_limit: usize,
203}
204
205/// The format and, for audio, its validated channel layout are one value.
206#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
207#[cfg_attr(
208    not(any(test, ndi_has_advanced_receive_allocators)),
209    expect(
210        dead_code,
211        reason = "only native allocator callbacks construct requests"
212    )
213)]
214enum RequestLayout {
215    Video(PixelFormat),
216    Audio(ValidatedAudioLayout),
217    Compressed(AllocationFormat),
218}
219
220/// The kind of frame an [`AllocationRequest`] is for.
221#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
222#[non_exhaustive]
223pub enum AllocationFormat {
224    /// Uncompressed video in this pixel format.
225    Video(PixelFormat),
226    /// Uncompressed planar 32-bit floating-point audio.
227    AudioPlanarF32,
228    /// Compressed video with this FourCC.
229    CompressedVideo(FourCc),
230    /// Compressed audio with this FourCC.
231    CompressedAudio(FourCc),
232}
233
234impl AllocationRequest {
235    /// The largest buffer, in bytes, a policy may return for this request:
236    /// [`AllocatorLimits::max_allocation_bytes`], or what is left of
237    /// [`AllocatorLimits::max_bytes`] when that is less.
238    pub fn capacity_limit(self) -> usize {
239        self.capacity_limit
240    }
241
242    /// The smallest buffer, in bytes, that holds the frame at this request's
243    /// stride.
244    pub fn minimum_bytes(self) -> usize {
245        self.bytes
246    }
247
248    /// Bytes per video line or per audio channel. For a compressed frame,
249    /// which has no stride, this is its size.
250    pub fn stride_bytes(self) -> usize {
251        self.stride
252    }
253
254    /// The kind of frame.
255    pub fn format(self) -> AllocationFormat {
256        match self.layout {
257            RequestLayout::Video(pixel) => AllocationFormat::Video(pixel),
258            RequestLayout::Audio(_) => AllocationFormat::AudioPlanarF32,
259            RequestLayout::Compressed(format) => format,
260        }
261    }
262
263    /// Width in pixels of video; samples per channel of audio.
264    pub fn width(self) -> u32 {
265        self.width
266    }
267
268    /// Height in pixels of video; channels of audio.
269    pub fn height(self) -> u32 {
270        self.height
271    }
272
273    /// The same request with the chosen line or channel stride, for buffers
274    /// that need padding or alignment. The minimum size changes to match.
275    ///
276    /// A new choice replaces an earlier stride. It may be narrower when the
277    /// frame layout allows it; the SDK's original request uses the packed minimum.
278    ///
279    /// # Errors
280    ///
281    /// [`Error::InvalidInput`](crate::Error::InvalidInput) when the stride is
282    /// not one the frame's layout allows (video follows the
283    /// [video stride rules](crate::PixelFormat::buffer_len); an audio
284    /// stride is a multiple of four bytes),
285    /// a compressed frame is given a stride other than its size, or the buffer would exceed
286    /// the [`capacity_limit`](Self::capacity_limit).
287    pub fn with_stride_bytes(self, stride: usize) -> Result<Self> {
288        let (bytes, layout) = match self.layout {
289            // The stored extent and layout already describe this stride.
290            // Check their size against the current grant below.
291            _ if stride == self.stride => (self.bytes, self.layout),
292            RequestLayout::Video(pixel) => {
293                let layout = ValidatedVideoLayout::new_uncompressed_checked(
294                    pixel,
295                    self.width,
296                    self.height,
297                    Some(stride),
298                )
299                .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?;
300                (layout.data_len_bytes(), self.layout)
301            }
302            RequestLayout::Audio(layout) => {
303                let layout = layout
304                    .with_channel_stride_bytes(stride)
305                    .map_err(|cause| invalid_input(crate::InputDefect::Layout(cause)))?;
306                // The layout caps its active extent at 64 MiB and its stride at
307                // i32::MAX. Including final channel padding still fits usize.
308                (
309                    layout.channel_stride_bytes() * layout.no_channels(),
310                    RequestLayout::Audio(layout),
311                )
312            }
313            RequestLayout::Compressed(_) => {
314                return Err(invalid_input(
315                    crate::InputDefect::CompressedAllocationStride,
316                ));
317            }
318        };
319        if bytes > self.capacity_limit {
320            return Err(invalid_input(crate::InputDefect::AllocationTooLarge {
321                bytes,
322                limit: self.capacity_limit,
323            }));
324        }
325        Ok(Self {
326            bytes,
327            stride,
328            layout,
329            ..self
330        })
331    }
332}
333
334/// Memory from the application's own pool, lent to the SDK for one frame.
335///
336/// The value is dropped, on whichever thread the SDK frees the frame from,
337/// when the SDK no longer needs the memory. See the
338/// [`ReceiveAllocator` callback contract](ReceiveAllocator#callback-contract).
339///
340/// # Safety
341///
342/// From creation until the value is dropped:
343///
344/// * [`pointer`](Self::pointer) and [`capacity`](Self::capacity) never change;
345/// * the memory is initialized, writable from any thread, addressable by the
346///   CPU, aligned to at least 64 bytes and valid for `capacity` bytes;
347/// * nothing else reads, writes, frees or remaps it.
348///
349/// Dropping the value must not panic.
350pub unsafe trait ExternalAllocation: Send + 'static {
351    /// The start of the memory.
352    fn pointer(&self) -> NonNull<u8>;
353
354    /// The size of the memory in bytes.
355    fn capacity(&self) -> usize;
356}
357
358/// An address, capacity and pool-defined slot tag, without ownership of memory.
359///
360/// Copying this descriptor grants no permission to access or lend its memory.
361/// Each successful [`AllocationBuffer::from_pool`] call establishes one exclusive
362/// loan, and requires the caller to uphold that constructor's safety contract.
363#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
364pub struct PoolBlock {
365    pointer: NonNull<u8>,
366    capacity: usize,
367    tag: usize,
368}
369impl PoolBlock {
370    /// Describe a pool slot without accessing or lending its memory.
371    pub const fn new(pointer: NonNull<u8>, capacity: usize, tag: usize) -> Self {
372        Self {
373            pointer,
374            capacity,
375            tag,
376        }
377    }
378    /// The slot's address; this descriptor grants no access to it.
379    pub const fn pointer(self) -> NonNull<u8> {
380        self.pointer
381    }
382    /// The described capacity in bytes.
383    pub const fn capacity(self) -> usize {
384        self.capacity
385    }
386    /// The pool-defined slot identifier returned unchanged at release.
387    pub const fn tag(self) -> usize {
388        self.tag
389    }
390}
391// SAFETY: This is a copyable address descriptor, not a memory view or owning
392// handle. Moving/sharing it never dereferences the address; lending it to the
393// SDK requires from_pool's explicit unsafe per-loan validity/exclusivity proof.
394unsafe impl Send for PoolBlock {}
395// SAFETY: Sharing a descriptor grants no read/write/release operation on memory.
396unsafe impl Sync for PoolBlock {}
397
398/// A pool that reclaims exclusive blocks lent through [`AllocationBuffer::from_pool`].
399///
400/// # Safety
401///
402/// For each valid loan, the pool must keep its initialized, CPU-addressable,
403/// 64-byte-aligned memory stable and valid for the block's capacity until release,
404/// with no other access, remapping or reclamation. Release must not panic. It and
405/// the pool's last destructor may run on any SDK free thread, or on the SDK's
406/// allocating thread when publication refuses a block, without registry locks.
407/// The [`ReceiveAllocator` callback contract](ReceiveAllocator#callback-contract)
408/// also covers release during a connection change.
409/// See [`ExternalAllocation`] for the equivalent arbitrary-handle contract.
410pub unsafe trait ExternalPool: Send + Sync + 'static {
411    /// Return a block after the SDK's exclusive access has ended, or after
412    /// publication refused it before any SDK access.
413    ///
414    /// # Safety
415    ///
416    /// The block must name one unreleased loan from this pool. Its SDK access
417    /// must have ended, and this call must be the only release of that loan.
418    unsafe fn release(&self, block: PoolBlock);
419}
420
421struct PoolStorage {
422    pool: Arc<dyn ExternalPool>,
423    block: PoolBlock,
424}
425impl Drop for PoolStorage {
426    fn drop(&mut self) {
427        // SAFETY: from_pool's caller establishes one valid matching-pool loan.
428        // This storage is moved, never cloned, and dropped exactly once after
429        // SDK access ends or publication is refused. Registry reclamation runs
430        // outside its locks and contains a misbehaving pool's panic.
431        unsafe { self.pool.release(self.block) };
432    }
433}
434
435/// Zeroed memory from the global allocator.
436struct OwnedStorage {
437    pointer: NonNull<u8>,
438    layout: Layout,
439}
440
441// Rounding a valid request up to its 64-byte alignment remains representable
442// in Layout's signed allocation-size bound on every supported target.
443const_assert!(MAX_ALLOCATION_BYTES <= isize::MAX as usize - 63);
444
445impl OwnedStorage {
446    /// Allocate this validated, non-zero request aligned to 64.
447    fn zeroed(request: AllocationRequest) -> Result<Self> {
448        let bytes = request.minimum_bytes();
449        let failed =
450            || crate::error::allocation_failed(crate::AllocationKind::ReceiveBuffer, Some(bytes));
451        let layout = Layout::from_size_align(bytes, 64).map_err(|_| failed())?;
452        // SAFETY: every AllocationRequest describes a validated non-zero
453        // extent; its constructors and stride changes keep that invariant.
454        let pointer = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or_else(failed)?;
455        Ok(Self { pointer, layout })
456    }
457}
458
459// SAFETY: the value owns its allocation and nothing else refers to it, so it
460// can be released, as it can be used, from any thread.
461unsafe impl Send for OwnedStorage {}
462
463// SAFETY: the memory was allocated zeroed with 64-byte alignment for exactly
464// `layout.size()` bytes, is owned by this value alone, and is released only
465// when it is dropped.
466unsafe impl ExternalAllocation for OwnedStorage {
467    fn pointer(&self) -> NonNull<u8> {
468        self.pointer
469    }
470
471    fn capacity(&self) -> usize {
472        self.layout.size()
473    }
474}
475
476impl Drop for OwnedStorage {
477    fn drop(&mut self) {
478        // SAFETY: the pointer came from `alloc_zeroed` with this layout and is
479        // released exactly once.
480        unsafe { dealloc(self.pointer.as_ptr(), self.layout) };
481    }
482}
483
484/// The memory a [`ReceiveAllocator`] returns for one [`AllocationRequest`].
485///
486/// # Threading
487///
488/// A buffer is [`Send`]: a policy returns it on an SDK thread, and the SDK
489/// may free it on another. It is not [`Sync`], because it can hold an
490/// [`ExternalAllocation`], which needs only to be `Send`, and
491/// [`capacity`](Self::capacity) asks that allocation through a shared
492/// reference.
493pub struct AllocationBuffer {
494    // `ExternalAllocation` asks only for Send, so that a pool whose handle is
495    // not Sync can lend memory, and `capacity` calls into it through `&self`;
496    // Sync would let two threads make that call at once. Nothing needs it:
497    // the registry keeps each buffer behind its mutex, which needs only Send,
498    // and frees it by value.
499    storage: AllocationStorage,
500    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
501    request: AllocationRequest,
502}
503
504enum AllocationStorage {
505    Owned(OwnedStorage),
506    External(Box<dyn ExternalAllocation>),
507    Pool(PoolStorage),
508}
509
510impl AllocationStorage {
511    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
512    fn pointer(&self) -> NonNull<u8> {
513        match self {
514            Self::Owned(storage) => storage.pointer(),
515            Self::External(storage) => storage.pointer(),
516            Self::Pool(storage) => storage.block.pointer,
517        }
518    }
519
520    fn capacity(&self) -> usize {
521        match self {
522            Self::Owned(storage) => storage.capacity(),
523            Self::External(storage) => storage.capacity(),
524            Self::Pool(storage) => storage.block.capacity,
525        }
526    }
527}
528
529impl std::fmt::Debug for AllocationBuffer {
530    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531        let storage = match &self.storage {
532            AllocationStorage::Owned(_) => "owned",
533            AllocationStorage::External(_) => "external",
534            AllocationStorage::Pool(_) => "pool",
535        };
536        f.debug_struct("AllocationBuffer")
537            .field("storage", &storage)
538            .finish_non_exhaustive()
539    }
540}
541
542impl AllocationBuffer {
543    /// Allocate zeroed, 64-byte-aligned memory of the request's minimum size.
544    ///
545    /// # Errors
546    ///
547    /// [`Error::AllocationFailed`](crate::Error::AllocationFailed) when the global
548    /// allocator cannot supply that much memory.
549    pub fn zeroed(request: AllocationRequest) -> Result<Self> {
550        Ok(Self {
551            storage: AllocationStorage::Owned(OwnedStorage::zeroed(request)?),
552            #[cfg(any(test, ndi_has_advanced_receive_allocators))]
553            request,
554        })
555    }
556
557    /// Lend memory through an arbitrary application-owned handle.
558    ///
559    /// Boxes the handle once per buffer. For a pool whose block can be
560    /// described as plain data, [`from_pool`](Self::from_pool) avoids that allocation.
561    ///
562    /// # Errors
563    ///
564    /// Returns the memory with [`Error::InvalidInput`](crate::Error::InvalidInput)
565    /// when it is smaller than the request's minimum, larger than its capacity
566    /// limit, or not aligned to 64 bytes, so that a pool gets its buffer back.
567    pub fn from_external<S: ExternalAllocation>(
568        request: AllocationRequest,
569        storage: S,
570    ) -> std::result::Result<Self, Rejected<S>> {
571        let problem = external_problem(request, storage.capacity(), || storage.pointer());
572        match problem {
573            Some(problem) => Err(Rejected::new(invalid_input(problem), storage)),
574            None => Ok(Self {
575                storage: AllocationStorage::External(Box::new(storage)),
576                #[cfg(any(test, ndi_has_advanced_receive_allocators))]
577                request,
578            }),
579        }
580    }
581
582    /// Lend a plain pool block without allocating or calling pool accessors.
583    ///
584    /// Clones the pool's `Arc`; the buffer releases the block exactly once on
585    /// drop, including when registry publication refuses it. Constructor failure
586    /// returns the block in [`Rejected`] without releasing it.
587    ///
588    /// # Safety
589    ///
590    /// If validation succeeds, `block` must name an initialized, writable,
591    /// CPU-addressable allocation from `pool`, aligned to 64 bytes and valid
592    /// for its stated capacity. Until `pool.release(block)`, nothing else may
593    /// read, write, free or remap it, or lend another copy of this descriptor.
594    /// The block must remain valid even if the caller drops its own pool Arc.
595    /// A `PoolBlock` is Copy and can be forged; validation checks geometry only,
596    /// so this per-loan ownership obligation cannot be proved by a safe constructor.
597    ///
598    /// # Errors
599    ///
600    /// Returns the unchanged block with [`Error::InvalidInput`](crate::Error::InvalidInput)
601    /// for insufficient/excessive capacity or misalignment, as `from_external` does.
602    pub unsafe fn from_pool<P: ExternalPool>(
603        request: AllocationRequest,
604        pool: &Arc<P>,
605        block: PoolBlock,
606    ) -> std::result::Result<Self, Rejected<PoolBlock>> {
607        if let Some(problem) = external_problem(request, block.capacity, || block.pointer) {
608            return Err(Rejected::new(invalid_input(problem), block));
609        }
610        let pool: Arc<dyn ExternalPool> = pool.clone();
611        Ok(Self {
612            storage: AllocationStorage::Pool(PoolStorage { pool, block }),
613            #[cfg(any(test, ndi_has_advanced_receive_allocators))]
614            request,
615        })
616    }
617
618    /// The size of the memory in bytes.
619    pub fn capacity(&self) -> usize {
620        self.storage.capacity()
621    }
622}
623
624/// Shared validation preserves capacity-before-pointer inspection for arbitrary
625/// external handles. Pool storage supplies those same quantities as plain data.
626fn external_problem(
627    request: AllocationRequest,
628    capacity: usize,
629    pointer: impl FnOnce() -> NonNull<u8>,
630) -> Option<crate::InputDefect> {
631    if capacity < request.bytes {
632        Some(crate::InputDefect::ExternalAllocationTooSmall)
633    } else if capacity > request.capacity_limit {
634        Some(crate::InputDefect::ExternalAllocationTooLarge)
635    } else if !(pointer().as_ptr() as usize).is_multiple_of(64) {
636        Some(crate::InputDefect::ExternalAllocationAlignment)
637    } else {
638        None
639    }
640}
641
642/// A policy that supplies the memory received frames are written into.
643///
644/// Any closure `Fn(AllocationRequest) -> Result<AllocationBuffer>` that is
645/// `Send + Sync` is a policy.
646///
647/// The SDK calls the policy on its own threads, possibly several at once, and
648/// stalls video or audio while a call blocks. An error or a panic makes that
649/// one allocation fail; the SDK then drops the frame. Inspect
650/// [`AllocatorService::usage`] for process-wide [`AllocationDecline`] counts,
651/// including distinct policy-error and contained-panic counts.
652/// Invalid media layouts are declined before calling the policy, including
653/// planar audio requests above capture's 64 MiB frame limit.
654///
655/// # Callback contract
656///
657/// Allocator code, including policy calls, allocation destructors and pool
658/// releases, can run on SDK decoder/free threads or on the thread inside
659/// [`Receiver::connect_to`], [`Receiver::disconnect`] or [`Receiver::reconnect`].
660/// Connection changes and allocator replacement wait for running policies.
661/// Allocator code may capture and use shared controls on its own receiver.
662/// It must not change that receiver's connection or release the last
663/// [`AllocatedReceiver`] owner: either operation can wait for the callback
664/// itself and deadlock.
665///
666/// A replaced policy is destroyed only after its replacement is installed.
667/// With no outstanding allocations or policy calls, the replacing call drops
668/// it. Otherwise the last call or allocation to release it does, possibly on
669/// an SDK thread inside a free callback. Its destructor must not wait for
670/// frames from that receiver.
671pub trait ReceiveAllocator: Send + Sync + 'static {
672    /// Supply memory for one frame.
673    ///
674    /// # Errors
675    ///
676    /// Any error declines the allocation.
677    fn allocate(&self, request: AllocationRequest) -> Result<AllocationBuffer>;
678}
679
680impl<F: Fn(AllocationRequest) -> Result<AllocationBuffer> + Send + Sync + 'static> ReceiveAllocator
681    for F
682{
683    fn allocate(&self, request: AllocationRequest) -> Result<AllocationBuffer> {
684        self(request)
685    }
686}
687
688/// One registered policy.
689struct Generation {
690    policy: ManuallyDrop<Box<dyn ReceiveAllocator>>,
691    count: Arc<AtomicUsize>,
692}
693
694impl Drop for Generation {
695    fn drop(&mut self) {
696        // The generation stays counted while the policy's own destructor
697        // runs, and for good if that panics: its cleanup may be incomplete.
698        // SAFETY: the policy is taken exactly once, here.
699        let policy = unsafe { ManuallyDrop::take(&mut self.policy) };
700        if catch_unwind(AssertUnwindSafe(|| drop(policy))).is_ok() {
701            self.count.fetch_sub(1, Ordering::AcqRel);
702        }
703    }
704}
705
706/// One allocation the SDK holds, and the generation that made it.
707struct Lease {
708    _buffer: AllocationBuffer,
709    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
710    bytes: usize,
711    _generation: Arc<Generation>,
712}
713
714#[cfg(any(test, ndi_has_advanced_receive_allocators))]
715type Leases = super::reserved_map::ReservedMap<(usize, usize), Lease>;
716// Without allocator callbacks no lease can be published, so retain the empty
717// table without reserving a workspace that this build can never use.
718#[cfg(not(any(test, ndi_has_advanced_receive_allocators)))]
719type Leases = HashMap<(usize, usize), Lease>;
720
721#[derive(Default)]
722struct State {
723    active: HashMap<usize, Arc<Generation>>,
724    /// Outstanding allocations by (generation token, address).
725    ///
726    /// The SDK frees every allocation through the allocator pair that made
727    /// it, passing that pair's opaque value, even after the pair has been
728    /// replaced; the token therefore identifies the lease's generation at the
729    /// free as it did at the allocation. Keeping it in the key means a free
730    /// can release only an allocation of the generation it names, so a
731    /// repeated free cannot release a later allocation that happens to reuse
732    /// the address under another generation.
733    leases: Leases,
734    bytes: usize,
735    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
736    reserved_bytes: usize,
737    calls: usize,
738    reclaiming: usize,
739    declines: [u64; AllocationDecline::COUNT],
740}
741
742#[cfg(any(test, ndi_has_advanced_receive_allocators))]
743impl State {
744    fn decline(&mut self, reason: AllocationDecline) {
745        let count = &mut self.declines[reason.index()];
746        *count = count.saturating_add(1);
747    }
748}
749
750/// Every generation and lease in the process.
751struct Registry {
752    limits: AllocatorLimits,
753    state: Mutex<State>,
754    generations: Arc<AtomicUsize>,
755    next: AtomicUsize,
756}
757
758fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
759    m.lock().unwrap_or_else(|p| p.into_inner())
760}
761
762/// Replace the value of `counter` with `next(value)` and return the value
763/// that was replaced, or leave it alone and return `None` when `next`
764/// declines the value it is shown.
765fn advance(counter: &AtomicUsize, next: impl Fn(usize) -> Option<usize>) -> Option<usize> {
766    let mut current = counter.load(Ordering::Acquire);
767    loop {
768        let replacement = next(current)?;
769        match counter.compare_exchange_weak(
770            current,
771            replacement,
772            Ordering::AcqRel,
773            Ordering::Acquire,
774        ) {
775            Ok(replaced) => return Some(replaced),
776            Err(actual) => current = actual,
777        }
778    }
779}
780
781/// The policy call that an admission covers: its count and the bytes it was
782/// granted stay charged until the call ends or its buffer is published.
783#[cfg(any(test, ndi_has_advanced_receive_allocators))]
784struct Reservation<'a> {
785    registry: &'a Registry,
786    bytes: usize,
787}
788
789#[cfg(any(test, ndi_has_advanced_receive_allocators))]
790impl Reservation<'_> {
791    /// End the call under a lock the caller already holds, so that the
792    /// buffer it publishes is never charged beside its own grant.
793    fn release(self, state: &mut State) {
794        self.uncharge(state);
795        std::mem::forget(self);
796    }
797
798    fn uncharge(&self, state: &mut State) {
799        state.calls -= 1;
800        state.reserved_bytes -= self.bytes;
801    }
802}
803
804#[cfg(any(test, ndi_has_advanced_receive_allocators))]
805impl Drop for Reservation<'_> {
806    fn drop(&mut self) {
807        self.uncharge(&mut lock(&self.registry.state));
808    }
809}
810
811impl Registry {
812    fn new(limits: AllocatorLimits) -> Result<Self> {
813        let unavailable =
814            |_| crate::error::allocation_failed(crate::AllocationKind::AllocatorLeases, None);
815        #[cfg(any(test, ndi_has_advanced_receive_allocators))]
816        let leases = Leases::try_with_capacity(limits.max_allocations).map_err(unavailable)?;
817        #[cfg(not(any(test, ndi_has_advanced_receive_allocators)))]
818        let leases = {
819            let mut leases = Leases::new();
820            leases
821                .try_reserve(limits.max_allocations)
822                .map_err(unavailable)?;
823            leases
824        };
825        Ok(Self {
826            limits,
827            state: Mutex::new(State {
828                leases,
829                ..State::default()
830            }),
831            generations: Arc::new(AtomicUsize::new(0)),
832            next: AtomicUsize::new(1),
833        })
834    }
835
836    fn usage(&self) -> AllocatorUsage {
837        let state = lock(&self.state);
838        AllocatorUsage {
839            generations: self.generations.load(Ordering::Acquire),
840            active_generations: state.active.len(),
841            retained_allocations: state.leases.len() + state.reclaiming,
842            retained_bytes: state.bytes,
843            calls: state.calls,
844            reclaiming: state.reclaiming,
845            declines: state.declines,
846        }
847    }
848
849    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
850    fn decline(&self, reason: AllocationDecline) {
851        lock(&self.state).decline(reason);
852    }
853
854    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
855    fn allocate_request(
856        &self,
857        token: usize,
858        request: std::result::Result<AllocationRequest, AllocationDecline>,
859    ) -> Option<(NonNull<u8>, i32)> {
860        match request {
861            Ok(request) => self.allocate(token, request),
862            Err(reason) => {
863                self.decline(reason);
864                None
865            }
866        }
867    }
868
869    /// Register `policy` as a new generation and return its token, or return
870    /// the policy when the process has no room for another.
871    fn register<P: ReceiveAllocator>(&self, policy: P) -> std::result::Result<usize, Rejected<P>> {
872        let token = match self.admit() {
873            Ok(token) => token,
874            Err(error) => return Err(Rejected::new(error, policy)),
875        };
876        let generation = Arc::new(Generation {
877            policy: ManuallyDrop::new(Box::new(policy)),
878            count: self.generations.clone(),
879        });
880        lock(&self.state).active.insert(token, generation);
881        Ok(token)
882    }
883
884    /// Count one more generation and name it with a token that has never
885    /// been used.
886    fn admit(&self) -> Result<usize> {
887        advance(&self.generations, |count| {
888            (count < self.limits.max_generations).then_some(count + 1)
889        })
890        .ok_or_else(|| invalid_input(crate::InputDefect::AllocatorGenerationBudget))?;
891        advance(&self.next, |token| token.checked_add(1)).ok_or_else(|| {
892            self.generations.fetch_sub(1, Ordering::AcqRel);
893            invalid_input(crate::InputDefect::AllocatorTokensExhausted)
894        })
895    }
896
897    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
898    fn closing(&self, token: usize) {
899        // Removing membership is the one transition: an admitted call retains
900        // the generation, but can no longer publish. User policy destruction
901        // runs after the state lock is released.
902        let generation = lock(&self.state).active.remove(&token);
903        drop(generation);
904    }
905
906    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
907    fn allocate(&self, token: usize, mut request: AllocationRequest) -> Option<(NonNull<u8>, i32)> {
908        let (generation, reservation) = {
909            let mut s = lock(&self.state);
910            let Some(generation) = s.active.get(&token).cloned() else {
911                s.decline(AllocationDecline::GenerationUnavailable);
912                return None;
913            };
914            if s.calls >= self.limits.max_concurrent_calls {
915                s.decline(AllocationDecline::ConcurrencyLimit);
916                return None;
917            }
918            if s.leases.len() + s.calls + s.reclaiming >= self.limits.max_allocations {
919                s.decline(AllocationDecline::AllocationCountLimit);
920                return None;
921            }
922            // Grant the call its buffer before user code runs, so that the
923            // policies running at once cannot return more than the budget
924            // between them, padding included: the largest single allocation,
925            // or whatever is left when that is less.
926            let granted = self
927                .limits
928                .max_bytes
929                .saturating_sub(s.bytes)
930                .saturating_sub(s.reserved_bytes)
931                .min(self.limits.max_allocation_bytes);
932            if granted < request.bytes {
933                s.decline(AllocationDecline::ByteLimit);
934                return None;
935            }
936            s.calls += 1;
937            s.reserved_bytes += granted;
938            let reservation = Reservation {
939                registry: self,
940                bytes: granted,
941            };
942            (generation, reservation)
943        };
944        request.capacity_limit = reservation.bytes;
945        // Storage accessors are application code too. A panic while checking a
946        // returned buffer must be counted just like a panic in the policy,
947        // before the outer native callback turns it into a refused request.
948        let (allocation, pointer, capacity) = match catch_unwind(AssertUnwindSafe(|| {
949            generation.policy.allocate(request).map(|allocation| {
950                let pointer = allocation.storage.pointer();
951                let capacity = allocation.capacity();
952                (allocation, pointer, capacity)
953            })
954        })) {
955            Ok(Ok(allocation)) => allocation,
956            Ok(Err(_)) => {
957                self.decline(AllocationDecline::PolicyError);
958                return None;
959            }
960            Err(_) => {
961                self.decline(AllocationDecline::PolicyPanic);
962                return None;
963            }
964        };
965        let actual = allocation.request;
966        // The request's stride rule also defines the publication layout. A
967        // compressed size must match exactly; uncompressed padding must produce
968        // this same minimum extent. Capacity is a separate admission bound.
969        let consistent = request
970            .with_stride_bytes(actual.stride)
971            .is_ok_and(|expected| {
972                expected
973                    == AllocationRequest {
974                        capacity_limit: expected.capacity_limit,
975                        ..actual
976                    }
977            });
978        if capacity > reservation.bytes || !consistent || capacity < actual.bytes {
979            self.decline(AllocationDecline::BufferRefused);
980            return None;
981        }
982        // At most the capacity, which is at most MAX_ALLOCATION_BYTES.
983        let stride = match actual.layout {
984            RequestLayout::Audio(layout) => layout.sdk_channel_stride(),
985            RequestLayout::Video(_) | RequestLayout::Compressed(_) => {
986                let Ok(stride) = i32::try_from(actual.stride) else {
987                    self.decline(AllocationDecline::BufferRefused);
988                    return None;
989                };
990                stride
991            }
992        };
993        // Membership serializes publication against closing. An admitted policy
994        // may have blocked while replacement began; it must not publish late.
995        let mut s = lock(&self.state);
996        if !s.active.contains_key(&token) {
997            s.decline(AllocationDecline::GenerationUnavailable);
998            return None;
999        }
1000        let lease = Lease {
1001            _buffer: allocation,
1002            bytes: capacity,
1003            _generation: generation,
1004        };
1005        if let Err((_, lease)) = s
1006            .leases
1007            .insert_new((token, pointer.as_ptr() as usize), lease)
1008        {
1009            s.decline(AllocationDecline::BufferRefused);
1010            // Policy destructors must run after releasing the registry lock.
1011            drop(s);
1012            drop(lease);
1013            return None;
1014        }
1015        // The buffer takes the place of the grant that covered it.
1016        reservation.release(&mut s);
1017        s.bytes += capacity;
1018        drop(s);
1019        Some((pointer, stride))
1020    }
1021
1022    #[cfg(any(test, ndi_has_advanced_receive_allocators))]
1023    fn free(&self, token: usize, pointer: *mut u8) -> bool {
1024        if pointer.is_null() {
1025            return true;
1026        }
1027        let lease = {
1028            let mut s = lock(&self.state);
1029            let lease = s.leases.remove(&(token, pointer as usize));
1030            if lease.is_some() {
1031                s.reclaiming += 1;
1032            }
1033            lease
1034        };
1035        match lease {
1036            Some(lease) => {
1037                let bytes = lease.bytes;
1038                // User storage reclamation runs without registry locks. Its
1039                // memory remains charged until reclamation has completed.
1040                if catch_unwind(AssertUnwindSafe(|| drop(lease))).is_err() {
1041                    // A panicking external destructor may have leaked storage.
1042                    // Keep its count/bytes charged permanently rather than allow
1043                    // repeated failures to evade the process memory bound.
1044                    return false;
1045                }
1046                let mut s = lock(&self.state);
1047                s.bytes -= bytes;
1048                s.reclaiming -= 1;
1049                true
1050            }
1051            None => false,
1052        }
1053    }
1054}
1055
1056static REGISTRY: OnceLock<Registry> = OnceLock::new();
1057
1058/// Permission to give receivers custom allocators.
1059///
1060/// The SDK may call an allocator's free function long after the receiver's
1061/// policy was replaced, so custom allocation needs the NDI runtime to stay
1062/// initialized until the process exits: the service is created from a
1063/// [`ProcessLifetimeRuntime`]. The first service fixes the
1064/// [`AllocatorLimits`] for the process, and later ones must name the same
1065/// limits.
1066///
1067/// A program that loads this crate as part of a plug-in must also keep that
1068/// module loaded for as long as the process runs, because the SDK holds
1069/// pointers to its callbacks.
1070#[derive(Clone, Copy)]
1071pub struct AllocatorService {
1072    runtime: ProcessLifetimeRuntime,
1073    registry: &'static Registry,
1074}
1075
1076/// Why a custom receive allocation was declined and the SDK dropped its frame.
1077#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1078#[non_exhaustive]
1079pub enum AllocationDecline {
1080    /// The SDK's format, dimensions or requested extent cannot be represented.
1081    /// Includes planar audio above capture's 64 MiB frame limit; the policy
1082    /// is not called and recording this decline allocates nothing.
1083    RequestNotRepresentable,
1084    /// The policy generation is unknown, replaced, closing or retired.
1085    GenerationUnavailable,
1086    /// The process already has its maximum number of concurrent policy calls.
1087    ConcurrencyLimit,
1088    /// Retained allocations, calls and reclamations fill the allocation count limit.
1089    AllocationCountLimit,
1090    /// The remaining total or per-allocation byte grant cannot hold the request.
1091    ByteLimit,
1092    /// The application policy returned an error.
1093    PolicyError,
1094    /// The application policy or its buffer inspection panicked; the callback
1095    /// contained the panic.
1096    PolicyPanic,
1097    /// The policy's buffer has an inconsistent size, layout, stride or live address.
1098    BufferRefused,
1099}
1100
1101// Missing reasons make index() non-exhaustive; duplicates are unreachable
1102// patterns. The count and the test list therefore cannot drift from indexing.
1103macro_rules! allocation_declines {
1104    ($($reason:ident),+ $(,)?) => {
1105        impl AllocationDecline {
1106            const COUNT: usize = [$(Self::$reason),+].len();
1107            #[cfg(test)]
1108            const ALL: [Self; Self::COUNT] = [$(Self::$reason),+];
1109            const fn index(self) -> usize {
1110                enum Index { $($reason),+ }
1111                match self { $(Self::$reason => Index::$reason as usize),+ }
1112            }
1113        }
1114    };
1115}
1116allocation_declines!(
1117    RequestNotRepresentable,
1118    GenerationUnavailable,
1119    ConcurrencyLimit,
1120    AllocationCountLimit,
1121    ByteLimit,
1122    PolicyError,
1123    PolicyPanic,
1124    BufferRefused,
1125);
1126
1127/// A snapshot of custom allocation across the process.
1128///
1129/// Decline counters include all generations since the service was created,
1130/// including retired policies. They saturate at `u64::MAX` and never reset.
1131/// Each declined SDK request increments exactly one reason; successful
1132/// allocations increment none.
1133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
1134pub struct AllocatorUsage {
1135    generations: usize,
1136    active_generations: usize,
1137    retained_allocations: usize,
1138    retained_bytes: usize,
1139    calls: usize,
1140    reclaiming: usize,
1141    declines: [u64; AllocationDecline::COUNT],
1142}
1143
1144impl AllocatorUsage {
1145    /// All declined custom receive allocations across the process.
1146    ///
1147    /// The total saturates at `u64::MAX`.
1148    pub fn declined_allocations(self) -> u64 {
1149        self.declines.into_iter().fold(0, u64::saturating_add)
1150    }
1151
1152    /// Declined custom receive allocations for one reason.
1153    pub fn declined(self, reason: AllocationDecline) -> u64 {
1154        self.declines[reason.index()]
1155    }
1156
1157    /// Policies that exist, including replaced ones whose allocations the SDK
1158    /// still holds. A policy whose destructor panicked stays counted.
1159    pub fn generations(self) -> usize {
1160        self.generations
1161    }
1162
1163    /// Policies currently registered with a receiver.
1164    pub fn active_generations(self) -> usize {
1165        self.active_generations
1166    }
1167
1168    /// Allocations the SDK holds, including those being released.
1169    /// A release whose policy code panicked stays counted, because its storage
1170    /// may have leaked.
1171    pub fn retained_allocations(self) -> usize {
1172        self.retained_allocations
1173    }
1174
1175    /// Bytes the SDK holds, including those being released.
1176    /// A release whose policy code panicked stays counted, because its storage
1177    /// may have leaked.
1178    pub fn retained_bytes(self) -> usize {
1179        self.retained_bytes
1180    }
1181
1182    /// Policy calls running at this moment.
1183    pub fn in_progress_allocations(self) -> usize {
1184        self.calls
1185    }
1186
1187    /// Buffers whose release is running at this moment.
1188    /// A release whose policy code panicked stays counted, because its storage
1189    /// may have leaked. This count therefore does not return to zero after
1190    /// such a panic.
1191    pub fn in_progress_reclamations(self) -> usize {
1192        self.reclaiming
1193    }
1194}
1195
1196impl std::fmt::Debug for AllocatorService {
1197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1198        f.debug_struct("AllocatorService")
1199            .field("limits", &self.registry.limits)
1200            .finish_non_exhaustive()
1201    }
1202}
1203
1204impl AllocatorService {
1205    /// Enable custom allocation with these process-wide limits.
1206    ///
1207    /// # Errors
1208    ///
1209    /// [`Error::InvalidInput`](crate::Error::InvalidInput) when the limits are
1210    /// out of range or differ from those of an earlier service.
1211    /// [`Error::AllocationFailed`](crate::Error::AllocationFailed) when the
1212    /// bounded lease bookkeeping cannot be reserved.
1213    pub fn new(runtime: ProcessLifetimeRuntime, limits: &AllocatorLimits) -> Result<Self> {
1214        let limits = (*limits).validate()?;
1215        let registry = match REGISTRY.get() {
1216            Some(registry) => registry,
1217            None => {
1218                // Reserve off the SDK's threads. If another caller initializes
1219                // first, its limits win and the comparison below is unchanged.
1220                let candidate = Registry::new(limits)?;
1221                REGISTRY.get_or_init(|| candidate)
1222            }
1223        };
1224        if registry.limits != limits {
1225            return Err(crate::Error::InvalidInput(
1226                crate::InputDefect::AllocatorLimitsDiffer,
1227            ));
1228        }
1229        Ok(Self { runtime, registry })
1230    }
1231
1232    /// Native setter fixtures share whichever limits the process callback
1233    /// fixture established first; neither fixture needs a particular limit.
1234    #[cfg(all(test, ndi_has_advanced_receive_allocators))]
1235    pub(crate) fn for_test(runtime: ProcessLifetimeRuntime) -> Self {
1236        Self {
1237            runtime,
1238            registry: REGISTRY.get_or_init(|| Registry::new(AllocatorLimits::default()).unwrap()),
1239        }
1240    }
1241
1242    /// A consistent snapshot of retained storage, active calls and decline
1243    /// counters across the process. Counter updates allocate no storage and
1244    /// run under the same lock that accounts for retained allocations.
1245    pub fn usage(self) -> AllocatorUsage {
1246        self.registry.usage()
1247    }
1248
1249    /// Take a receiver so that its allocators can be set.
1250    ///
1251    /// # Errors
1252    ///
1253    /// Returns the receiver, untouched, with
1254    /// [`Error::UnsupportedCapability`](crate::Error::UnsupportedCapability)
1255    /// without an Advanced runtime (or in a build without the Advanced SDK).
1256    pub fn attach(
1257        self,
1258        receiver: Receiver,
1259    ) -> std::result::Result<AllocatedReceiver, Rejected<Receiver>> {
1260        self.allocation(receiver)
1261    }
1262
1263    /// Take a packet receiver so that its allocators can be set.
1264    ///
1265    /// # Errors
1266    ///
1267    /// As for [`attach`](Self::attach).
1268    pub fn attach_packets(
1269        self,
1270        receiver: PacketReceiver,
1271    ) -> std::result::Result<AllocatedReceiver<PacketAttached>, Rejected<PacketReceiver>> {
1272        self.allocation(receiver.receiver)
1273            .map_err(|rejected| rejected.map(PacketReceiver::from_receiver))
1274    }
1275
1276    /// Take `receiver`, in any mode, with no allocator of its own set yet.
1277    fn allocation<M: ReceiverMode>(
1278        self,
1279        mut receiver: Receiver<M>,
1280    ) -> std::result::Result<AllocatedReceiver<M>, Rejected<Receiver<M>>> {
1281        let owner = AllocatorOwner {
1282            authority: receiver.allocator_owner(),
1283            service: self,
1284        };
1285        match crate::runtime::Bound::<ReceiveAllocators, _>::with_owner(owner) {
1286            Ok(table) => Ok(AllocatedReceiver {
1287                registration: Registration {
1288                    table,
1289                    #[cfg(ndi_has_advanced_receive_allocators)]
1290                    video_token: None,
1291                    #[cfg(ndi_has_advanced_receive_allocators)]
1292                    audio_token: None,
1293                },
1294                receiver,
1295            }),
1296            Err(error) => Err(Rejected::new(error, receiver)),
1297        }
1298    }
1299}
1300
1301/// Which of a receiver's two allocators an operation concerns.
1302#[derive(Clone, Copy)]
1303enum Stream {
1304    Video,
1305    Audio,
1306}
1307
1308/// A receiver whose frames can be received into application memory.
1309///
1310/// The default [`RawCapture`] mode retains ordinary receiver capture.
1311/// [`AllocatorService::attach_packets`] returns the [`PacketAttached`] mode,
1312/// which captures through [`capture_any`](AllocatedReceiver::capture_any) and
1313/// [`capture_any_ref`](AllocatedReceiver::capture_any_ref).
1314/// [`receiver`](Self::receiver) lends the receiver in its existing mode;
1315/// [`controls`](Self::controls) permits exclusive stream controls and KVM
1316/// without allowing that receiver to be replaced.
1317///
1318/// Dropping this owner, or taking the receiver back, returns it to the SDK's
1319/// own memory first. The receiver may live on in a
1320/// [`RecvAdvertiser`](crate::discovery_server::RecvAdvertiser) registration;
1321/// allocations it still holds are freed through the process-wide token registry.
1322/// The registration retains the exact receiver core, so resetting always
1323/// reaches the original native instance.
1324///
1325/// Setting an allocator replaces the previous one for frames allocated from
1326/// then on. Frames allocated earlier stay in the memory the earlier policy
1327/// supplied, and that policy is kept until the SDK has freed the last of
1328/// them. Only a call of the earlier policy still running when the replacement
1329/// is installed is declined.
1330///
1331/// # Threading
1332///
1333/// Both returned modes are [`Send`] and [`Sync`]: capturing, changing allocators
1334/// and dropping the owner can happen on any thread. Captures borrow it shared;
1335/// changing allocators requires an exclusive borrow. The SDK calls policies
1336/// on its own threads, possibly concurrently, and frees each allocation through
1337/// the callback that created it. Registry access is synchronized.
1338///
1339/// # Examples
1340///
1341/// ```no_run
1342/// use std::time::Duration;
1343/// use grafton_ndi::{
1344///     advanced::{AllocationBuffer, AllocationRequest, AllocatorLimits, AllocatorService},
1345///     Receiver, ReceiverOptions, Ndi,
1346/// };
1347///
1348/// # fn main() -> Result<(), grafton_ndi::Error> {
1349/// let ndi = Ndi::new()?;
1350/// let receiver = Receiver::new(&ndi, &ReceiverOptions::disconnected())?;
1351/// let service = AllocatorService::new(ndi.process_lifetime(), &AllocatorLimits::default())?;
1352/// let mut receiver = service.attach(receiver)?;
1353///
1354/// // Pad every video line to a multiple of 256 bytes.
1355/// receiver.set_video_allocator(|request: AllocationRequest| {
1356///     let stride = request.stride_bytes().next_multiple_of(256);
1357///     AllocationBuffer::zeroed(request.with_stride_bytes(stride)?)
1358/// })?;
1359/// if let Some(frame) = receiver.receiver().capture_video(Duration::from_secs(1))? {
1360///     println!("line stride: {} bytes", frame.line_stride_bytes());
1361/// }
1362/// # Ok(())
1363/// # }
1364/// ```
1365///
1366/// Application allocator code follows the
1367/// [`ReceiveAllocator` callback contract](ReceiveAllocator#callback-contract).
1368pub struct AllocatedReceiver<M: ReceiverMode = RawCapture> {
1369    registration: Registration,
1370    receiver: Receiver<M>,
1371}
1372
1373impl<M: ReceiverMode> std::fmt::Debug for AllocatedReceiver<M> {
1374    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1375        f.debug_struct("AllocatedReceiver")
1376            .field("receiver", &self.receiver)
1377            .finish_non_exhaustive()
1378    }
1379}
1380
1381impl<M: ReceiverMode> AllocatedReceiver<M> {
1382    /// The receiver, for capture permitted by its mode and shared controls.
1383    pub fn receiver(&self) -> &Receiver<M> {
1384        &self.receiver
1385    }
1386
1387    /// Borrow exclusive stream controls or start KVM without permitting
1388    /// receiver replacement. This allocates nothing and makes no SDK call.
1389    /// Capture through the KVM session while inputs are held.
1390    pub fn controls(&mut self) -> ReceiverControls<'_, M> {
1391        ReceiverControls::new(&mut self.receiver)
1392    }
1393
1394    /// Receive video into memory from `policy`.
1395    ///
1396    /// # Errors
1397    ///
1398    /// Returns the policy with [`Error::InvalidInput`](crate::Error::InvalidInput)
1399    /// when the process already has [`AllocatorLimits::max_generations`]
1400    /// policies. The current allocator then stays in place.
1401    #[doc(alias = "NDIlib_recv_set_video_allocator")]
1402    pub fn set_video_allocator<P: ReceiveAllocator>(
1403        &mut self,
1404        policy: P,
1405    ) -> std::result::Result<(), Rejected<P>> {
1406        self.set_allocator(Stream::Video, policy)
1407    }
1408
1409    /// Receive audio into memory from `policy`.
1410    ///
1411    /// # Errors
1412    ///
1413    /// As for [`set_video_allocator`](Self::set_video_allocator).
1414    #[doc(alias = "NDIlib_recv_set_audio_allocator")]
1415    pub fn set_audio_allocator<P: ReceiveAllocator>(
1416        &mut self,
1417        policy: P,
1418    ) -> std::result::Result<(), Rejected<P>> {
1419        self.set_allocator(Stream::Audio, policy)
1420    }
1421
1422    /// Return to the SDK's own video memory.
1423    #[doc(alias = "NDIlib_recv_set_video_allocator")]
1424    pub fn reset_video_allocator(&mut self) {
1425        self.registration.install(Stream::Video, None);
1426    }
1427
1428    /// Return to the SDK's own audio memory.
1429    #[doc(alias = "NDIlib_recv_set_audio_allocator")]
1430    pub fn reset_audio_allocator(&mut self) {
1431        self.registration.install(Stream::Audio, None);
1432    }
1433
1434    fn set_allocator<P: ReceiveAllocator>(
1435        &mut self,
1436        stream: Stream,
1437        policy: P,
1438    ) -> std::result::Result<(), Rejected<P>> {
1439        let token = self
1440            .registration
1441            .table
1442            .owner()
1443            .service
1444            .registry
1445            .register(policy)?;
1446        self.registration.install(stream, Some(token));
1447        Ok(())
1448    }
1449    fn release_receiver(self) -> Receiver<M> {
1450        let Self {
1451            registration,
1452            receiver,
1453        } = self;
1454        drop(registration);
1455        receiver
1456    }
1457}
1458
1459impl AllocatedReceiver<RawCapture> {
1460    /// Return to the SDK's own memory and give the receiver back.
1461    pub fn into_receiver(self) -> Receiver {
1462        self.release_receiver()
1463    }
1464}
1465
1466impl AllocatedReceiver<PacketAttached> {
1467    /// Wait up to `timeout` for the next frame or event; see
1468    /// [`PacketReceiver::capture_any`].
1469    ///
1470    /// # Errors
1471    ///
1472    /// As for [`PacketReceiver::capture_any`], including [`crate::Error::UnexpectedSdkResult`]
1473    /// once per failed status publication, whose event remains pending.
1474    #[doc(alias = "NDIlib_recv_capture_v3")]
1475    pub fn capture_any(&self, timeout: std::time::Duration) -> Result<Option<PacketItem>> {
1476        PacketReceiver::capture_from(self.receiver(), timeout)
1477    }
1478
1479    /// Borrow a packet directly from SDK or application-provided storage.
1480    /// A held item keeps its custom allocation charged until the SDK releases
1481    /// it after the item is dropped. See [`PacketReceiver::capture_any_ref`].
1482    ///
1483    /// # Errors
1484    ///
1485    /// As for [`PacketReceiver::capture_any_ref`], including [`crate::Error::UnexpectedSdkResult`]
1486    /// once per failed status publication, whose event remains pending.
1487    #[doc(alias = "NDIlib_recv_capture_v3")]
1488    pub fn capture_any_ref(
1489        &self,
1490        timeout: std::time::Duration,
1491    ) -> Result<Option<PacketItemRef<'_>>> {
1492        PacketReceiver::capture_ref_from(self.receiver(), timeout)
1493    }
1494
1495    /// Return to the SDK's own memory and give the packet receiver back.
1496    pub fn into_packet_receiver(self) -> PacketReceiver {
1497        PacketReceiver::from_receiver(self.release_receiver())
1498    }
1499}
1500
1501/// The receiver authority and permanent service retained by the native capability.
1502struct AllocatorOwner {
1503    #[cfg_attr(
1504        not(ndi_has_advanced_receive_allocators),
1505        expect(
1506            dead_code,
1507            reason = "the uninhabited table prevents registrations without declarations"
1508        )
1509    )]
1510    authority: crate::receiver::AllocatorOwner,
1511    service: AllocatorService,
1512}
1513
1514impl crate::runtime::LiveOwner for AllocatorOwner {
1515    fn ndi(&self) -> &crate::Ndi {
1516        self.service.runtime.ndi()
1517    }
1518}
1519
1520/// Owns the exact receiver and runtime needed to uninstall both callback pairs.
1521/// Its own Drop keeps reset before native destruction independent of field order.
1522struct Registration {
1523    table: crate::runtime::Bound<ReceiveAllocators, AllocatorOwner>,
1524    #[cfg(ndi_has_advanced_receive_allocators)]
1525    video_token: Option<usize>,
1526    #[cfg(ndi_has_advanced_receive_allocators)]
1527    audio_token: Option<usize>,
1528}
1529impl Registration {
1530    /// Register generation `token` (or the SDK's own allocator) for `stream`
1531    /// and retire the generation it replaces.
1532    #[cfg(ndi_has_advanced_receive_allocators)]
1533    fn install(&mut self, stream: Stream, token: Option<usize>) {
1534        let table = &self.table;
1535        let slot = match stream {
1536            Stream::Video => &mut self.video_token,
1537            Stream::Audio => &mut self.audio_token,
1538        };
1539        let opaque = token.map_or(std::ptr::null_mut(), |token| token as *mut c_void);
1540        // SAFETY: the registration retains exclusive allocator authority and
1541        // borrows its separately locked native allocator state. The callbacks
1542        // belong to this program; their opaque tokens are looked up, never followed.
1543        install_with(table.owner().service.registry, slot, token, || {
1544            // The owned proof keeps the receiver live. The native allocator
1545            // rwlock excludes callback-state replacement. Keep unrelated Rust
1546            // gates outside this wait for arbitrary native policy callbacks.
1547            let access = table.owner().authority.access();
1548            let instance = access.instance();
1549            // SAFETY: exclusive allocator authority and callback storage are
1550            // retained through this setter, as described above.
1551            unsafe {
1552                match stream {
1553                    Stream::Video => table.NDIlib_recv_set_video_allocator(
1554                        instance,
1555                        opaque,
1556                        token.map(|_| allocate::<NDIlib_video_frame_v2_t> as _),
1557                        token.map(|_| free::<NDIlib_video_frame_v2_t> as _),
1558                    ),
1559                    Stream::Audio => table.NDIlib_recv_set_audio_allocator(
1560                        instance,
1561                        opaque,
1562                        token.map(|_| allocate::<NDIlib_audio_frame_v3_t> as _),
1563                        token.map(|_| free::<NDIlib_audio_frame_v3_t> as _),
1564                    ),
1565                }
1566            }
1567        });
1568    }
1569
1570    // A build without this declaration family cannot create an Allocation.
1571    // Its uninhabited table proves that no allocator can be installed here.
1572    #[cfg(not(ndi_has_advanced_receive_allocators))]
1573    fn install(&mut self, _: Stream, _: Option<usize>) {
1574        match *self.table {}
1575    }
1576}
1577impl Drop for Registration {
1578    fn drop(&mut self) {
1579        self.install(Stream::Video, None);
1580        self.install(Stream::Audio, None);
1581    }
1582}
1583
1584/// Install the native pair before retiring its predecessor. The setter may
1585/// still call the earlier policy; its allocations remain admitted until the
1586/// pair has been replaced. Retirement then prevents unfinished calls from
1587/// publishing and can destroy a policy only after the SDK has moved on.
1588#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1589fn install_with(
1590    registry: &Registry,
1591    slot: &mut Option<usize>,
1592    token: Option<usize>,
1593    set: impl FnOnce(),
1594) {
1595    set();
1596    if let Some(earlier) = std::mem::replace(slot, token) {
1597        registry.closing(earlier);
1598    }
1599}
1600
1601/// A compressed frame's size, which the SDK passes in the stride union.
1602#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1603fn compressed_size(size: i32) -> std::result::Result<PacketLen, AllocationDecline> {
1604    PacketLen::from_sdk(size).ok_or(AllocationDecline::RequestNotRepresentable)
1605}
1606
1607/// A dimension of a compressed frame the SDK is about to receive.
1608#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1609fn compressed_dimension(value: i32) -> std::result::Result<u32, AllocationDecline> {
1610    u32::try_from(value).map_err(|_| AllocationDecline::RequestNotRepresentable)
1611}
1612
1613/// The native frame types accepted by the allocation and release callbacks.
1614/// Kept private so only this module determines how their unions are read and written.
1615#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1616trait AllocatedDescriptor {
1617    fn request(&self) -> std::result::Result<AllocationRequest, AllocationDecline>;
1618    fn clear(&mut self);
1619    fn fill(&mut self, pointer: NonNull<u8>, stride: i32);
1620    fn data(&self) -> *mut u8;
1621}
1622
1623#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1624impl AllocatedDescriptor for NDIlib_video_frame_v2_t {
1625    fn request(&self) -> std::result::Result<AllocationRequest, AllocationDecline> {
1626        let fourcc = FourCc::from_raw(self.FourCC);
1627        if VideoCodec::from_outer(self.FourCC).is_some() {
1628            // SAFETY: for a compressed frame the union holds the data size.
1629            let size = compressed_size(unsafe { self.__bindgen_anon_1.data_size_in_bytes })?;
1630            return Ok(AllocationRequest {
1631                bytes: size.to_usize(),
1632                stride: size.to_usize(),
1633                layout: RequestLayout::Compressed(AllocationFormat::CompressedVideo(fourcc)),
1634                width: compressed_dimension(self.xres)?,
1635                height: compressed_dimension(self.yres)?,
1636                capacity_limit: MAX_ALLOCATION_BYTES,
1637            });
1638        }
1639        let pixel =
1640            PixelFormat::from_fourcc(fourcc).ok_or(AllocationDecline::RequestNotRepresentable)?;
1641        let layout = ValidatedVideoLayout::from_sdk_checked(pixel, self.xres, self.yres, 0)
1642            .map_err(|_| AllocationDecline::RequestNotRepresentable)?;
1643        Ok(AllocationRequest {
1644            bytes: layout.data_len_bytes(),
1645            stride: layout.line_stride_bytes(),
1646            layout: RequestLayout::Video(pixel),
1647            width: layout.width(),
1648            height: layout.height(),
1649            capacity_limit: MAX_ALLOCATION_BYTES,
1650        })
1651    }
1652
1653    fn clear(&mut self) {
1654        self.p_data = std::ptr::null_mut();
1655        self.__bindgen_anon_1.line_stride_in_bytes = 0;
1656    }
1657
1658    fn fill(&mut self, pointer: NonNull<u8>, stride: i32) {
1659        self.p_data = pointer.as_ptr();
1660        self.__bindgen_anon_1.line_stride_in_bytes = stride;
1661    }
1662
1663    fn data(&self) -> *mut u8 {
1664        self.p_data
1665    }
1666}
1667
1668#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1669impl AllocatedDescriptor for NDIlib_audio_frame_v3_t {
1670    fn request(&self) -> std::result::Result<AllocationRequest, AllocationDecline> {
1671        if self.FourCC != crate::FourCc::from(crate::AudioFormat::Fltp).raw() {
1672            if AudioCodec::from_outer(self.FourCC).is_none() {
1673                return Err(AllocationDecline::RequestNotRepresentable);
1674            }
1675            // SAFETY: for compressed audio the union holds the exact packet size;
1676            // tests/advanced_runtime.rs::compressed_audio_packets_use_exact_custom_allocator_grants
1677            // pins the AAC/Opus request format, extent and delivered application memory.
1678            let size = compressed_size(unsafe { self.__bindgen_anon_1.data_size_in_bytes })?;
1679            return Ok(AllocationRequest {
1680                bytes: size.to_usize(),
1681                stride: size.to_usize(),
1682                layout: RequestLayout::Compressed(AllocationFormat::CompressedAudio(
1683                    FourCc::from_raw(self.FourCC),
1684                )),
1685                width: compressed_dimension(self.no_samples)?,
1686                height: compressed_dimension(self.no_channels)?,
1687                capacity_limit: MAX_ALLOCATION_BYTES,
1688            });
1689        }
1690        // The callback chooses a packed stride. The incoming data pointer and
1691        // stride do not name allocated storage yet and must not be read as media.
1692        let layout = ValidatedAudioLayout::from_sdk_checked(
1693            AudioFormat::Fltp,
1694            self.sample_rate,
1695            self.no_channels,
1696            self.no_samples,
1697            None,
1698        )
1699        .map_err(|_| AllocationDecline::RequestNotRepresentable)?;
1700        Ok(AllocationRequest {
1701            bytes: layout.sample_count() * size_of::<f32>(),
1702            stride: layout.channel_stride_bytes(),
1703            layout: RequestLayout::Audio(layout),
1704            width: layout.num_samples(),
1705            height: layout.num_channels(),
1706            capacity_limit: MAX_ALLOCATION_BYTES,
1707        })
1708    }
1709
1710    fn clear(&mut self) {
1711        self.p_data = std::ptr::null_mut();
1712        self.__bindgen_anon_1.channel_stride_in_bytes = 0;
1713    }
1714
1715    fn fill(&mut self, pointer: NonNull<u8>, stride: i32) {
1716        self.p_data = pointer.as_ptr();
1717        self.__bindgen_anon_1.channel_stride_in_bytes = stride;
1718    }
1719
1720    fn data(&self) -> *mut u8 {
1721        self.p_data
1722    }
1723}
1724
1725/// The SDK's request for frame memory. `opaque` is the generation token.
1726#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1727unsafe extern "C" fn allocate<D: AllocatedDescriptor>(opaque: *mut c_void, frame: *mut D) -> bool {
1728    catch_unwind(AssertUnwindSafe(|| {
1729        let Some(registry) = REGISTRY.get() else {
1730            return false;
1731        };
1732        // SAFETY: the SDK passes null or a descriptor it owns for this call.
1733        let Some(frame) = (unsafe { frame.as_mut() }) else {
1734            registry.decline(AllocationDecline::RequestNotRepresentable);
1735            return false;
1736        };
1737        let request = frame.request();
1738        frame.clear();
1739        let Some((pointer, stride)) = registry.allocate_request(opaque as usize, request) else {
1740            return false;
1741        };
1742        frame.fill(pointer, stride);
1743        true
1744    }))
1745    .unwrap_or(false)
1746}
1747
1748/// The SDK's release of frame memory. `opaque` names the owning generation.
1749#[cfg(any(test, ndi_has_advanced_receive_allocators))]
1750unsafe extern "C" fn free<D: AllocatedDescriptor>(opaque: *mut c_void, frame: *const D) -> bool {
1751    catch_unwind(AssertUnwindSafe(|| {
1752        // SAFETY: the SDK passes null or a descriptor that is valid for this call.
1753        let Some(frame) = (unsafe { frame.as_ref() }) else {
1754            return false;
1755        };
1756        REGISTRY
1757            .get()
1758            .is_some_and(|registry| registry.free(opaque as usize, frame.data()))
1759    }))
1760    .unwrap_or(false)
1761}
1762
1763#[cfg(test)]
1764mod tests {
1765    use super::*;
1766    use crate::Error;
1767    use crate::StreamTier;
1768
1769    static CALLBACK_TEST_LOCK: Mutex<()> = Mutex::new(());
1770
1771    include!("allocators/cycle_cost_tests.rs");
1772    #[test]
1773    fn compressed_allocator_sizes_keep_the_packet_bound() {
1774        for size in [-1, 0, i32::MAX] {
1775            assert_eq!(
1776                compressed_size(size),
1777                Err(AllocationDecline::RequestNotRepresentable)
1778            );
1779        }
1780        for size in [1, super::super::MAX_PACKET_BYTES] {
1781            let sdk_size = i32::try_from(size).unwrap();
1782            let checked = compressed_size(sdk_size).unwrap();
1783            assert_eq!(checked.to_usize(), size);
1784            assert_eq!(checked.to_sdk(), sdk_size);
1785        }
1786        assert_eq!(
1787            compressed_size(i32::try_from(super::super::MAX_PACKET_BYTES + 1).unwrap()),
1788            Err(AllocationDecline::RequestNotRepresentable)
1789        );
1790    }
1791
1792    #[test]
1793    #[cfg_attr(
1794        miri,
1795        ignore = "the maximum packet allocation is covered by the native test run"
1796    )]
1797    fn compressed_allocator_and_capture_accept_the_same_maximum_extent() {
1798        let mut bytes = vec![0; super::super::MAX_PACKET_BYTES];
1799        let size = compressed_size(i32::try_from(bytes.len()).unwrap()).unwrap();
1800        let mut raw = super::super::VideoPacketFormat::new(VideoCodec::SpeedHq422, 16, 16)
1801            .unwrap()
1802            .raw();
1803        raw.p_data = bytes.as_mut_ptr();
1804        raw.__bindgen_anon_1.data_size_in_bytes = size.to_sdk();
1805        let request = raw.request().unwrap();
1806        assert_eq!(request.bytes, size.to_usize());
1807        assert_eq!(request.stride, size.to_usize());
1808        // SAFETY: bytes owns this initialized allocation through the borrowed
1809        // frame's lifetime; the synthetic guard releases no native storage.
1810        let guard =
1811            unsafe { crate::capture::Guard::with_test_free(std::ptr::null_mut(), raw, |_, _| {}) };
1812        let frame =
1813            super::super::CompressedRef::<super::super::VideoPacketFormat>::new(guard).unwrap();
1814        assert_eq!(frame.data().len(), request.bytes);
1815    }
1816
1817    /// Reusable initialized aligned blocks; the bounded free list grants one
1818    /// exclusive slot per claim and returns it only after lease reclamation.
1819    struct TestPool {
1820        _storage: Mutex<Vec<OwnedStorage>>,
1821        blocks: Vec<PoolBlock>,
1822        free: Mutex<std::collections::VecDeque<usize>>,
1823        releases: AtomicUsize,
1824    }
1825    impl TestPool {
1826        fn new(count: usize, bytes: usize) -> Arc<Self> {
1827            let storage = (0..count)
1828                .map(|_| OwnedStorage::zeroed(request_of(bytes)).unwrap())
1829                .collect::<Vec<_>>();
1830            let blocks = storage
1831                .iter()
1832                .enumerate()
1833                .map(|(tag, storage)| PoolBlock::new(storage.pointer(), bytes, tag))
1834                .collect();
1835            let pool = Arc::new(Self {
1836                _storage: Mutex::new(storage),
1837                blocks,
1838                free: Mutex::new((0..count).collect()),
1839                releases: AtomicUsize::new(0),
1840            });
1841            // Apple pthread mutexes allocate on first lock. Pool setup belongs
1842            // outside callback allocation counts and cycle measurements.
1843            drop(lock(&pool.free));
1844            pool
1845        }
1846        fn claim(&self) -> PoolBlock {
1847            self.blocks[lock(&self.free)
1848                .pop_front()
1849                .expect("benchmark/test has enough exclusive slots")]
1850        }
1851        fn buffer(self: &Arc<Self>, request: AllocationRequest) -> Result<AllocationBuffer> {
1852            let block = self.claim();
1853            // SAFETY: claim removes one initialized aligned block from the free
1854            // list; this Arc owns its storage until release returns that slot.
1855            match unsafe { AllocationBuffer::from_pool(request, self, block) } {
1856                Ok(buffer) => Ok(buffer),
1857                Err(rejected) => {
1858                    let (error, block) = rejected.into_parts();
1859                    // SAFETY: refusal returned the same unpublished exclusive loan.
1860                    unsafe { self.release(block) };
1861                    Err(error)
1862                }
1863            }
1864        }
1865    }
1866    // SAFETY: storage is owned by this pool, initialized and aligned. The free
1867    // list grants exclusive slots, and storage stays live through each Arc loan.
1868    unsafe impl ExternalPool for TestPool {
1869        unsafe fn release(&self, block: PoolBlock) {
1870            assert_eq!(self.blocks[block.tag], block);
1871            let mut free = lock(&self.free);
1872            assert!(!free.contains(&block.tag), "a block must be released once");
1873            free.push_back(block.tag);
1874            self.releases.fetch_add(1, Ordering::Relaxed);
1875        }
1876    }
1877    struct PoolHandle {
1878        pool: Arc<TestPool>,
1879        block: PoolBlock,
1880    }
1881    // SAFETY: a handle owns one exclusively claimed TestPool slot until Drop.
1882    unsafe impl ExternalAllocation for PoolHandle {
1883        fn pointer(&self) -> NonNull<u8> {
1884            self.block.pointer
1885        }
1886        fn capacity(&self) -> usize {
1887            self.block.capacity
1888        }
1889    }
1890    impl Drop for PoolHandle {
1891        fn drop(&mut self) {
1892            // SAFETY: this non-Clone handle owns the only release of its claim.
1893            unsafe { self.pool.release(self.block) };
1894        }
1895    }
1896
1897    #[test]
1898    fn pool_constructor_returns_refused_blocks_without_releasing_them() {
1899        let pool = TestPool::new(1, 64);
1900        let original = pool.claim();
1901        let request = AllocationRequest {
1902            capacity_limit: 64,
1903            ..request()
1904        };
1905        for (block, expected) in [
1906            (
1907                PoolBlock::new(original.pointer, 63, original.tag),
1908                crate::InputDefect::ExternalAllocationTooSmall,
1909            ),
1910            (
1911                PoolBlock::new(original.pointer, 65, original.tag),
1912                crate::InputDefect::ExternalAllocationTooLarge,
1913            ),
1914            (
1915                PoolBlock::new(
1916                    NonNull::new((original.pointer.as_ptr() as usize + 1) as *mut u8).unwrap(),
1917                    64,
1918                    original.tag,
1919                ),
1920                crate::InputDefect::ExternalAllocationAlignment,
1921            ),
1922        ] {
1923            // SAFETY: these intentionally invalid descriptors all fail validation
1924            // before a loan is accepted; none is accessed, published or released.
1925            let rejected = unsafe { AllocationBuffer::from_pool(request, &pool, block) }
1926                .expect_err("invalid block must be refused");
1927            assert!(matches!(rejected.error(), Error::InvalidInput(actual) if actual == &expected));
1928            assert_eq!(rejected.into_inner(), block);
1929            assert_eq!(pool.releases.load(Ordering::Relaxed), 0);
1930        }
1931        // SAFETY: the original claim was never lent and is returned once.
1932        unsafe { pool.release(original) };
1933    }
1934
1935    #[test]
1936    fn pool_policy_constructs_buffers_without_allocating_but_external_handles_box_once() {
1937        for external in [false, true] {
1938            let registry = Registry::new(limits()).unwrap();
1939            let pool = TestPool::new(1, 64);
1940            let policy_pool = pool.clone();
1941            let token = registry
1942                .register(move |request| {
1943                    if external {
1944                        let block = policy_pool.claim();
1945                        Ok(AllocationBuffer::from_external(
1946                            request,
1947                            PoolHandle {
1948                                pool: policy_pool.clone(),
1949                                block,
1950                            },
1951                        )?)
1952                    } else {
1953                        policy_pool.buffer(request)
1954                    }
1955                })
1956                .unwrap();
1957            let (published, allocations) =
1958                crate::test_alloc::allocation_count(|| registry.allocate(token, request()));
1959            assert_eq!(allocations, usize::from(external));
1960            let (pointer, _) = published.unwrap();
1961            assert!(registry.free(token, pointer.as_ptr()));
1962            assert_eq!(pool.releases.load(Ordering::Relaxed), 1);
1963        }
1964    }
1965
1966    #[test]
1967    fn pool_blocks_are_released_once_when_publication_refuses_them() {
1968        for retired in [false, true] {
1969            let registry = Arc::new(Registry::new(limits()).unwrap());
1970            let pool = TestPool::new(1, 64);
1971            let policy_pool = pool.clone();
1972            let weak_registry = Arc::downgrade(&registry);
1973            let name = Arc::new(AtomicUsize::new(0));
1974            let policy_name = name.clone();
1975            let token = registry
1976                .register(move |mut request: AllocationRequest| {
1977                    if retired {
1978                        weak_registry
1979                            .upgrade()
1980                            .unwrap()
1981                            .closing(policy_name.load(Ordering::Relaxed));
1982                    } else {
1983                        request.width += 1;
1984                    } // A buffer for a different layout.
1985                    policy_pool.buffer(request)
1986                })
1987                .unwrap();
1988            name.store(token, Ordering::Relaxed);
1989            assert!(registry.allocate(token, request()).is_none());
1990            assert_eq!(pool.releases.load(Ordering::Relaxed), 1);
1991            assert_eq!(registry.usage().retained_allocations(), 0);
1992            assert_eq!(
1993                registry.usage().declined(if retired {
1994                    AllocationDecline::GenerationUnavailable
1995                } else {
1996                    AllocationDecline::BufferRefused
1997                }),
1998                1
1999            );
2000        }
2001    }
2002
2003    #[test]
2004    fn panicking_pool_release_is_contained_and_keeps_bytes_charged() {
2005        struct Panics(Arc<TestPool>);
2006        // Intentionally violates the release no-panic rule to test containment.
2007        unsafe impl ExternalPool for Panics {
2008            unsafe fn release(&self, _: PoolBlock) {
2009                panic!("contained pool release");
2010            }
2011        }
2012        let pool = Arc::new(Panics(TestPool::new(1, 64)));
2013        let policy_pool = pool.clone();
2014        let registry = Registry::new(limits()).unwrap();
2015        let token = registry
2016            .register(move |request| {
2017                let block = policy_pool.0.claim();
2018                // SAFETY: the nested pool grants initialized stable exclusive memory;
2019                // this test intentionally misbehaves only at release, after SDK use.
2020                Ok(unsafe { AllocationBuffer::from_pool(request, &policy_pool, block) }?)
2021            })
2022            .unwrap();
2023        let (pointer, _) = registry.allocate(token, request()).unwrap();
2024        assert!(!registry.free(token, pointer.as_ptr()));
2025        assert_eq!(registry.usage().retained_bytes(), 64);
2026        assert_eq!(registry.usage().in_progress_reclamations(), 1);
2027        assert_eq!(registry.usage().retained_allocations(), 1);
2028    }
2029
2030    #[test]
2031    fn every_decline_reason_has_one_counter() {
2032        let registry = Registry::new(limits()).unwrap();
2033        for reason in AllocationDecline::ALL {
2034            registry.decline(reason);
2035        }
2036        let usage = registry.usage();
2037        assert_eq!(
2038            usage.declined_allocations(),
2039            AllocationDecline::COUNT as u64
2040        );
2041        for reason in AllocationDecline::ALL {
2042            assert_eq!(usage.declined(reason), 1);
2043        }
2044    }
2045
2046    #[test]
2047    fn panicking_policy_destruction_keeps_its_generation_budget_charged() {
2048        struct Panics;
2049        impl ReceiveAllocator for Panics {
2050            fn allocate(&self, request: AllocationRequest) -> Result<AllocationBuffer> {
2051                AllocationBuffer::zeroed(request)
2052            }
2053        }
2054        impl Drop for Panics {
2055            fn drop(&mut self) {
2056                panic!("contained policy destructor");
2057            }
2058        }
2059        let registry = Registry::new(limits()).unwrap();
2060        let earlier = registry.register(Panics).unwrap();
2061        let replacement = registry.register(AllocationBuffer::zeroed).unwrap();
2062        let mut slot = Some(earlier);
2063        install_with(&registry, &mut slot, Some(replacement), || {});
2064        assert_eq!(registry.usage().active_generations(), 1);
2065        assert_eq!(registry.usage().generations(), 2);
2066        registry.closing(replacement);
2067        assert_eq!(registry.usage().active_generations(), 0);
2068        assert_eq!(registry.usage().generations(), 1);
2069    }
2070
2071    #[test]
2072    fn native_allocation_formats_preserve_protection_and_decoded_formats() {
2073        use crate::advanced::packets::PROTECTED;
2074        let protected_video = VideoCodec::H264.outer(StreamTier::Program, true);
2075        let mut video = NDIlib_video_frame_v2_t {
2076            FourCC: protected_video,
2077            xres: 16,
2078            yres: 16,
2079            ..Default::default()
2080        };
2081        video.__bindgen_anon_1.data_size_in_bytes = 64;
2082        let request = video.request().unwrap();
2083        assert_eq!(
2084            request.format(),
2085            AllocationFormat::CompressedVideo(FourCc::from_raw(protected_video))
2086        );
2087        assert_eq!(
2088            (request.width(), request.height(), request.stride_bytes()),
2089            (16, 16, 64)
2090        );
2091        video.xres = -16;
2092        assert!(matches!(
2093            video.request(),
2094            Err(AllocationDecline::RequestNotRepresentable)
2095        ));
2096        video.xres = 16;
2097        video.__bindgen_anon_1.data_size_in_bytes = 0;
2098        assert!(video.request().is_err());
2099        video.FourCC = crate::FourCc::from(PixelFormat::Bgra).raw();
2100        let request = video.request().unwrap();
2101        assert_eq!(request.format(), AllocationFormat::Video(PixelFormat::Bgra));
2102        assert_eq!(
2103            (request.width(), request.height(), request.stride_bytes()),
2104            (16, 16, 64)
2105        );
2106        assert_eq!(request.minimum_bytes(), 16 * 64);
2107        video.FourCC = u32::MAX;
2108        assert!(video.request().is_err());
2109        for codec in [AudioCodec::Aac, AudioCodec::Opus] {
2110            for protected in [false, true] {
2111                let bits = codec.outer(protected);
2112                let mut audio = NDIlib_audio_frame_v3_t {
2113                    FourCC: bits,
2114                    ..Default::default()
2115                };
2116                audio.__bindgen_anon_1.data_size_in_bytes = 64;
2117                assert_eq!(
2118                    audio.request().unwrap().format(),
2119                    AllocationFormat::CompressedAudio(FourCc::from_raw(bits))
2120                );
2121                audio.FourCC = bits ^ PROTECTED ^ 1;
2122                assert!(audio.request().is_err());
2123            }
2124        }
2125    }
2126
2127    fn limits() -> AllocatorLimits {
2128        AllocatorLimits {
2129            max_generations: 2,
2130            max_allocations: 2,
2131            max_bytes: 128,
2132            max_concurrent_calls: 2,
2133            max_allocation_bytes: 64,
2134        }
2135        .validate()
2136        .unwrap()
2137    }
2138
2139    fn request_of(bytes: usize) -> AllocationRequest {
2140        let layout = ValidatedAudioLayout::new_uncompressed(
2141            AudioFormat::Fltp,
2142            48_000,
2143            2,
2144            (bytes / 8) as u32,
2145            None,
2146        )
2147        .unwrap();
2148        AllocationRequest {
2149            bytes,
2150            stride: bytes / 2,
2151            layout: RequestLayout::Audio(layout),
2152            width: (bytes / 8) as u32,
2153            height: 2,
2154            capacity_limit: MAX_ALLOCATION_BYTES,
2155        }
2156    }
2157
2158    fn request() -> AllocationRequest {
2159        request_of(64)
2160    }
2161
2162    #[test]
2163    fn request_conversion_declines_count_once_without_calling_a_policy() {
2164        let registry = Registry::new(limits()).unwrap();
2165        let token = registry.register(AllocationBuffer::zeroed).unwrap();
2166        let video = NDIlib_video_frame_v2_t {
2167            FourCC: u32::MAX,
2168            ..Default::default()
2169        };
2170        let audio = NDIlib_audio_frame_v3_t {
2171            FourCC: u32::MAX,
2172            ..Default::default()
2173        };
2174        assert!(registry.allocate_request(token, video.request()).is_none());
2175        assert!(registry.allocate_request(token, audio.request()).is_none());
2176        let usage = registry.usage();
2177        assert_eq!(
2178            usage.declined(AllocationDecline::RequestNotRepresentable),
2179            2
2180        );
2181        assert_eq!(usage.declined_allocations(), 2);
2182        assert_eq!(usage.in_progress_allocations(), 0);
2183        assert_eq!(usage.retained_allocations(), 0);
2184        let (pointer, _) = registry.allocate(token, request()).unwrap();
2185        assert_eq!(registry.usage().declined_allocations(), 2);
2186        assert!(registry.free(token, pointer.as_ptr()));
2187    }
2188
2189    #[test]
2190    fn unrepresentable_requests_decline_without_allocating_or_calling_the_policy() {
2191        let registry = Registry::new(limits()).unwrap();
2192        let policy_calls = Arc::new(AtomicUsize::new(0));
2193        let calls = policy_calls.clone();
2194        let token = registry
2195            .register(move |_: AllocationRequest| -> Result<AllocationBuffer> {
2196                calls.fetch_add(1, Ordering::Relaxed);
2197                Err(crate::error::allocation_failed(
2198                    crate::AllocationKind::AllocatorLeases,
2199                    None,
2200                ))
2201            })
2202            .unwrap();
2203        let video = NDIlib_video_frame_v2_t {
2204            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
2205            xres: 16,
2206            yres: 16,
2207            ..Default::default()
2208        };
2209        let videos = [
2210            NDIlib_video_frame_v2_t {
2211                FourCC: u32::MAX,
2212                ..video
2213            },
2214            NDIlib_video_frame_v2_t { xres: -1, ..video },
2215            NDIlib_video_frame_v2_t { xres: 3, ..video },
2216            NDIlib_video_frame_v2_t { yres: 0, ..video },
2217            NDIlib_video_frame_v2_t {
2218                FourCC: FourCc::from(PixelFormat::I420).raw(),
2219                yres: 3,
2220                ..video
2221            },
2222            NDIlib_video_frame_v2_t {
2223                FourCC: FourCc::from(PixelFormat::Nv12).raw(),
2224                yres: 3,
2225                ..video
2226            },
2227            NDIlib_video_frame_v2_t {
2228                xres: i32::MAX - 1,
2229                yres: i32::MAX,
2230                ..video
2231            },
2232            NDIlib_video_frame_v2_t {
2233                FourCC: VideoCodec::H264.outer(StreamTier::Program, false),
2234                ..video
2235            },
2236        ];
2237        // FLTP extents are multiples of four: the first representable excess
2238        // over the 64 MiB capture cap is four bytes, not one byte.
2239        let audio = NDIlib_audio_frame_v3_t {
2240            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
2241            sample_rate: 48_000,
2242            no_channels: 1,
2243            no_samples: (crate::frames::MAX_AUDIO_BYTES / size_of::<f32>()) as i32 + 1,
2244            ..Default::default()
2245        };
2246        let audios = [
2247            audio,
2248            NDIlib_audio_frame_v3_t {
2249                FourCC: u32::MAX,
2250                ..audio
2251            },
2252            NDIlib_audio_frame_v3_t {
2253                sample_rate: 0,
2254                ..audio
2255            },
2256            NDIlib_audio_frame_v3_t {
2257                no_channels: 0,
2258                ..audio
2259            },
2260            NDIlib_audio_frame_v3_t {
2261                no_samples: 0,
2262                ..audio
2263            },
2264            NDIlib_audio_frame_v3_t {
2265                no_samples: i32::MAX,
2266                ..audio
2267            },
2268            NDIlib_audio_frame_v3_t {
2269                FourCC: AudioCodec::Aac.outer(false),
2270                no_channels: -1,
2271                __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
2272                    data_size_in_bytes: 64,
2273                },
2274                ..audio
2275            },
2276        ];
2277        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2278            for frame in &videos {
2279                assert!(registry.allocate_request(token, frame.request()).is_none());
2280            }
2281            for frame in &audios {
2282                assert!(registry.allocate_request(token, frame.request()).is_none());
2283            }
2284        });
2285        assert_eq!(allocations, 0);
2286        assert_eq!(policy_calls.load(Ordering::Relaxed), 0);
2287        let usage = registry.usage();
2288        assert_eq!(
2289            usage.declined(AllocationDecline::RequestNotRepresentable),
2290            (videos.len() + audios.len()) as u64
2291        );
2292        assert_eq!(usage.in_progress_allocations(), 0);
2293        assert_eq!(usage.retained_allocations(), 0);
2294    }
2295
2296    #[test]
2297    fn audio_request_at_capture_limit_uses_the_shared_packed_layout() {
2298        let frame = NDIlib_audio_frame_v3_t {
2299            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
2300            sample_rate: 48_000,
2301            no_channels: 1,
2302            no_samples: (crate::frames::MAX_AUDIO_BYTES / size_of::<f32>()) as i32,
2303            // Allocator input is geometry, not existing media. The callback
2304            // chooses the packed stride without requiring a data pointer.
2305            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
2306                channel_stride_in_bytes: -1,
2307            },
2308            ..Default::default()
2309        };
2310        let (request, allocations) = crate::test_alloc::allocation_count(|| frame.request());
2311        let request = request.unwrap();
2312        assert_eq!(allocations, 0);
2313        let layout = ValidatedAudioLayout::from_sdk_checked(
2314            AudioFormat::Fltp,
2315            frame.sample_rate,
2316            frame.no_channels,
2317            frame.no_samples,
2318            None,
2319        )
2320        .unwrap();
2321        assert_eq!(request.minimum_bytes(), crate::frames::MAX_AUDIO_BYTES);
2322        assert_eq!(request.stride_bytes(), layout.channel_stride_bytes());
2323        assert_eq!(request.width(), layout.num_samples());
2324        assert_eq!(request.height(), layout.num_channels());
2325    }
2326
2327    #[test]
2328    fn successful_owned_allocation_allocates_only_its_frame_memory() {
2329        let registry = Registry::new(limits()).unwrap();
2330        let token = registry.register(AllocationBuffer::zeroed).unwrap();
2331        let (published, allocations) =
2332            crate::test_alloc::allocation_count(|| registry.allocate(token, request()));
2333        let (pointer, _) = published.unwrap();
2334        assert_eq!(allocations, 1);
2335        assert!(registry.free(token, pointer.as_ptr()));
2336    }
2337
2338    #[test]
2339    fn successful_preboxed_external_allocation_needs_no_bookkeeping_allocation() {
2340        let registry = Registry::new(limits()).unwrap();
2341        let buffer =
2342            AllocationBuffer::from_external(request(), OwnedStorage::zeroed(request()).unwrap())
2343                .unwrap();
2344        let buffer = Mutex::new(Some(buffer));
2345        // Some platforms allocate a native mutex on its first lock. Initialize
2346        // this application policy's pool lock outside the measured callback;
2347        // register initializes the registry's own lock before SDK calls begin.
2348        drop(lock(&buffer));
2349        let token = registry
2350            .register(move |_| Ok(lock(&buffer).take().unwrap()))
2351            .unwrap();
2352        let (published, allocations) =
2353            crate::test_alloc::allocation_count(|| registry.allocate(token, request()));
2354        let (pointer, _) = published.unwrap();
2355        assert_eq!(allocations, 0);
2356        assert!(registry.free(token, pointer.as_ptr()));
2357    }
2358
2359    #[test]
2360    fn lease_bookkeeping_is_fallibly_reserved_for_the_full_limit() {
2361        let limit = 32;
2362        let registry = Registry::new(AllocatorLimits {
2363            max_allocations: limit,
2364            max_bytes: limit * 64,
2365            ..limits()
2366        })
2367        .unwrap();
2368        let token = registry.register(AllocationBuffer::zeroed).unwrap();
2369        let capacity = lock(&registry.state).leases.capacity();
2370        assert!(capacity >= limit);
2371        let mut held = Vec::with_capacity(limit);
2372        for _ in 0..limit {
2373            let (published, allocations) =
2374                crate::test_alloc::allocation_count(|| registry.allocate(token, request()));
2375            held.push(published.unwrap().0);
2376            assert_eq!(allocations, 1);
2377        }
2378        let state = lock(&registry.state);
2379        assert_eq!(state.leases.len(), limit);
2380        assert_eq!(state.leases.capacity(), capacity);
2381        drop(state);
2382        for pointer in held {
2383            assert!(registry.free(token, pointer.as_ptr()));
2384        }
2385
2386        // An impossible reservation is an allocation failure, rather than a panic or
2387        // an infallible allocation on the first SDK callback.
2388        assert!(matches!(
2389            Registry::new(AllocatorLimits {
2390                max_allocations: usize::MAX,
2391                ..limits()
2392            }),
2393            Err(Error::AllocationFailed(crate::AllocationFailure {
2394                kind: crate::AllocationKind::AllocatorLeases,
2395                bytes: None,
2396            }))
2397        ));
2398    }
2399
2400    #[test]
2401    fn lease_churn_never_allocates_for_pool_storage() {
2402        let limit = 16;
2403        let changes = 1024;
2404        let registry = Registry::new(AllocatorLimits {
2405            max_allocations: limit,
2406            max_bytes: limit * 64,
2407            ..limits()
2408        })
2409        .unwrap();
2410        // All backing storage exists before tracking. FIFO claims visit distinct
2411        // addresses across churn, exercising the bounded map's tombstone rebuild.
2412        let pool = TestPool::new(limit + changes, 64);
2413        let policy_pool = pool.clone();
2414        let token = registry
2415            .register(move |request| policy_pool.buffer(request))
2416            .unwrap();
2417        let mut held = Vec::with_capacity(limit);
2418        for _ in 0..limit {
2419            held.push(registry.allocate(token, request()).unwrap().0);
2420        }
2421        for change in 0..changes {
2422            let slot = &mut held[change % limit];
2423            let (published, allocations) = crate::test_alloc::allocation_count(|| {
2424                assert!(registry.free(token, slot.as_ptr()));
2425                registry.allocate(token, request())
2426            });
2427            *slot = published.unwrap().0;
2428            assert_eq!(allocations, 0);
2429        }
2430        for pointer in held {
2431            assert!(registry.free(token, pointer.as_ptr()));
2432        }
2433        assert_eq!(pool.releases.load(Ordering::Relaxed), limit + changes);
2434    }
2435
2436    #[test]
2437    fn unavailable_generations_and_policy_errors_have_distinct_decline_counts() {
2438        let registry = Registry::new(limits()).unwrap();
2439        let token = registry
2440            .register(|_: AllocationRequest| -> Result<AllocationBuffer> {
2441                Err(crate::error::allocation_failed(
2442                    crate::AllocationKind::AllocatorLeases,
2443                    None,
2444                ))
2445            })
2446            .unwrap();
2447        let (result, allocations) =
2448            crate::test_alloc::allocation_count(|| registry.allocate(token, request()));
2449        assert!(result.is_none());
2450        assert_eq!(allocations, 0);
2451        assert_eq!(registry.usage().declined(AllocationDecline::PolicyError), 1);
2452        registry.closing(token);
2453        assert!(registry.allocate(token, request()).is_none());
2454        registry.closing(token);
2455        assert!(registry.allocate(token, request()).is_none());
2456        let usage = registry.usage();
2457        assert_eq!(usage.declined(AllocationDecline::GenerationUnavailable), 2);
2458        assert_eq!(usage.declined_allocations(), 3);
2459        assert_eq!(usage.retained_bytes(), 0);
2460        assert_eq!(usage.in_progress_allocations(), 0);
2461    }
2462
2463    #[test]
2464    fn panicking_external_buffer_inspection_counts_once_and_releases_storage() {
2465        use std::cell::Cell;
2466
2467        struct InspectionPanics {
2468            storage: OwnedStorage,
2469            pointer_calls: Cell<usize>,
2470            capacity_calls: Cell<usize>,
2471            panic_in_pointer: bool,
2472            drops: Arc<AtomicUsize>,
2473        }
2474        // SAFETY: OwnedStorage supplies initialized, aligned, writable memory
2475        // with a stable pointer and capacity. This fixture panics on a later
2476        // accessor call without ever changing either returned value. Its
2477        // destructor is nonpanicking and releases the allocation exactly once.
2478        unsafe impl ExternalAllocation for InspectionPanics {
2479            fn pointer(&self) -> NonNull<u8> {
2480                let calls = self.pointer_calls.replace(self.pointer_calls.get() + 1);
2481                assert!(
2482                    !self.panic_in_pointer || calls == 0,
2483                    "buffer pointer inspection panicked"
2484                );
2485                self.storage.pointer()
2486            }
2487
2488            fn capacity(&self) -> usize {
2489                let calls = self.capacity_calls.replace(self.capacity_calls.get() + 1);
2490                assert!(
2491                    self.panic_in_pointer || calls == 0,
2492                    "buffer capacity inspection panicked"
2493                );
2494                self.storage.capacity()
2495            }
2496        }
2497        impl Drop for InspectionPanics {
2498            fn drop(&mut self) {
2499                self.drops.fetch_add(1, Ordering::Relaxed);
2500            }
2501        }
2502
2503        for panic_in_pointer in [true, false] {
2504            let registry = Registry::new(limits()).unwrap();
2505            let drops = Arc::new(AtomicUsize::new(0));
2506            let token = registry
2507                .register({
2508                    let drops = drops.clone();
2509                    move |request: AllocationRequest| {
2510                        let storage = InspectionPanics {
2511                            storage: OwnedStorage::zeroed(request)?,
2512                            pointer_calls: Cell::new(0),
2513                            capacity_calls: Cell::new(0),
2514                            panic_in_pointer,
2515                            drops: drops.clone(),
2516                        };
2517                        Ok(AllocationBuffer::from_external(request, storage)?)
2518                    }
2519                })
2520                .unwrap();
2521            let outcome = catch_unwind(AssertUnwindSafe(|| registry.allocate(token, request())));
2522            assert!(
2523                outcome.is_ok(),
2524                "buffer inspection must remain inside panic containment"
2525            );
2526            assert!(outcome.unwrap().is_none());
2527            let usage = registry.usage();
2528            assert_eq!(usage.declined(AllocationDecline::PolicyPanic), 1);
2529            assert_eq!(usage.declined_allocations(), 1);
2530            assert_eq!(usage.retained_allocations(), 0);
2531            assert_eq!(usage.retained_bytes(), 0);
2532            assert_eq!(usage.in_progress_allocations(), 0);
2533            assert_eq!(lock(&registry.state).reserved_bytes, 0);
2534            assert_eq!(drops.load(Ordering::Relaxed), 1);
2535        }
2536    }
2537
2538    #[test]
2539    fn declined_budget_requests_allocate_nothing_and_stay_exact_under_contention() {
2540        let registry = Registry::new(limits()).unwrap();
2541        let token = registry.register(AllocationBuffer::zeroed).unwrap();
2542        let oversized = request_of(128);
2543        let ((), allocations) = crate::test_alloc::allocation_count(|| {
2544            for _ in 0..32 {
2545                assert!(registry.allocate(token, oversized).is_none());
2546            }
2547        });
2548        assert_eq!(allocations, 0);
2549        std::thread::scope(|scope| {
2550            for _ in 0..8 {
2551                scope.spawn(|| {
2552                    for _ in 0..100 {
2553                        assert!(registry.allocate(token, oversized).is_none());
2554                        let usage = registry.usage();
2555                        assert_eq!(
2556                            usage.declined_allocations(),
2557                            usage.declined(AllocationDecline::ByteLimit)
2558                        );
2559                        assert_eq!(usage.in_progress_allocations(), 0);
2560                        assert_eq!(usage.retained_bytes(), 0);
2561                    }
2562                });
2563            }
2564        });
2565        assert_eq!(registry.usage().declined(AllocationDecline::ByteLimit), 832);
2566    }
2567
2568    #[test]
2569    fn duplicate_live_addresses_are_declined_without_releasing_the_first_lease() {
2570        struct RepeatedAddress(Arc<Mutex<OwnedStorage>>);
2571        // SAFETY: this fixture never lets an SDK access the storage. It keeps
2572        // initialized aligned memory alive and deliberately offers its stable
2573        // address twice so the registry can refuse a second publication.
2574        unsafe impl ExternalAllocation for RepeatedAddress {
2575            fn pointer(&self) -> NonNull<u8> {
2576                lock(&self.0).pointer()
2577            }
2578            fn capacity(&self) -> usize {
2579                lock(&self.0).capacity()
2580            }
2581        }
2582        let registry = Registry::new(limits()).unwrap();
2583        let storage = Arc::new(Mutex::new(OwnedStorage::zeroed(request_of(64)).unwrap()));
2584        let token = registry
2585            .register(move |request| {
2586                Ok(AllocationBuffer::from_external(
2587                    request,
2588                    RepeatedAddress(storage.clone()),
2589                )?)
2590            })
2591            .unwrap();
2592        let (pointer, _) = registry.allocate(token, request()).unwrap();
2593        assert!(registry.allocate(token, request()).is_none());
2594        let usage = registry.usage();
2595        assert_eq!(usage.declined(AllocationDecline::BufferRefused), 1);
2596        assert_eq!(usage.declined_allocations(), 1);
2597        assert_eq!(usage.retained_allocations(), 1);
2598        assert_eq!(usage.retained_bytes(), 64);
2599        assert_eq!(usage.in_progress_allocations(), 0);
2600        assert!(registry.free(token, pointer.as_ptr()));
2601        assert_eq!(registry.usage().retained_bytes(), 0);
2602    }
2603
2604    #[test]
2605    fn invalid_buffer_layout_and_stride_overflow_are_counted_once() {
2606        for malformed in 0..4 {
2607            let registry = Registry::new(limits()).unwrap();
2608            let token = registry
2609                .register(move |request| {
2610                    let mut buffer = AllocationBuffer::zeroed(request)?;
2611                    // Simulate a malformed policy result inside the fixture;
2612                    // neither value can be published as a native descriptor.
2613                    match malformed {
2614                        0 => buffer.request.width += 1,
2615                        1 => buffer.request.stride = i32::MAX as usize + 1,
2616                        2 => buffer.request.bytes -= 1,
2617                        3 => {
2618                            buffer.storage =
2619                                AllocationStorage::Owned(OwnedStorage::zeroed(request_of(32))?)
2620                        }
2621                        _ => unreachable!(),
2622                    }
2623                    Ok(buffer)
2624                })
2625                .unwrap();
2626            assert!(registry.allocate(token, request()).is_none());
2627            let usage = registry.usage();
2628            assert_eq!(usage.declined(AllocationDecline::BufferRefused), 1);
2629            assert_eq!(usage.declined_allocations(), 1);
2630            assert_eq!(usage.retained_allocations(), 0);
2631            assert_eq!(usage.retained_bytes(), 0);
2632            assert_eq!(usage.in_progress_allocations(), 0);
2633            assert_eq!(lock(&registry.state).reserved_bytes, 0);
2634        }
2635    }
2636
2637    fn compressed_requests(bytes: i32) -> [AllocationRequest; 2] {
2638        let mut video = NDIlib_video_frame_v2_t {
2639            FourCC: VideoCodec::H264.outer(StreamTier::Program, false),
2640            xres: 16,
2641            yres: 16,
2642            ..Default::default()
2643        };
2644        video.__bindgen_anon_1.data_size_in_bytes = bytes;
2645        let mut audio = NDIlib_audio_frame_v3_t {
2646            FourCC: AudioCodec::Opus.outer(false),
2647            sample_rate: 48_000,
2648            no_channels: 2,
2649            no_samples: 8,
2650            ..Default::default()
2651        };
2652        audio.__bindgen_anon_1.data_size_in_bytes = bytes;
2653        [video.request().unwrap(), audio.request().unwrap()]
2654    }
2655
2656    fn cached_request_policy() -> impl ReceiveAllocator {
2657        let cached = Mutex::new(None);
2658        move |request| AllocationBuffer::zeroed(*lock(&cached).get_or_insert(request))
2659    }
2660
2661    #[test]
2662    fn stale_compressed_requests_are_declined_without_retaining_storage() {
2663        for (first, smaller) in compressed_requests(64)
2664            .into_iter()
2665            .zip(compressed_requests(32))
2666        {
2667            let registry = Registry::new(limits()).unwrap();
2668            let token = registry.register(cached_request_policy()).unwrap();
2669            let (pointer, size) = registry.allocate(token, first).unwrap();
2670            assert_eq!(size, 64);
2671            assert!(registry.free(token, pointer.as_ptr()));
2672
2673            assert!(registry.allocate(token, smaller).is_none());
2674            let usage = registry.usage();
2675            assert_eq!(usage.declined(AllocationDecline::BufferRefused), 1);
2676            assert_eq!(usage.declined_allocations(), 1);
2677            assert_eq!(usage.retained_allocations(), 0);
2678            assert_eq!(usage.retained_bytes(), 0);
2679            assert_eq!(usage.in_progress_allocations(), 0);
2680        }
2681    }
2682
2683    #[test]
2684    fn same_stride_cached_video_buffers_must_match_format_and_dimensions() {
2685        let descriptor = |format, height| NDIlib_video_frame_v2_t {
2686            FourCC: FourCc::from(format).raw(),
2687            xres: 4,
2688            yres: height,
2689            ..Default::default()
2690        };
2691        let first = descriptor(PixelFormat::Bgra, 2).request().unwrap();
2692        let registry = Registry::new(limits()).unwrap();
2693        let token = registry.register(cached_request_policy()).unwrap();
2694        let (pointer, stride) = registry.allocate(token, first).unwrap();
2695        assert_eq!(stride, 16);
2696        assert!(registry.free(token, pointer.as_ptr()));
2697
2698        for later in [
2699            descriptor(PixelFormat::Rgba, 2),
2700            descriptor(PixelFormat::Bgra, 1),
2701        ] {
2702            let later = later.request().unwrap();
2703            assert_eq!(later.stride_bytes(), first.stride_bytes());
2704            assert!(registry.allocate(token, later).is_none());
2705        }
2706        let usage = registry.usage();
2707        assert_eq!(usage.declined(AllocationDecline::BufferRefused), 2);
2708        assert_eq!(usage.declined_allocations(), 2);
2709        assert_eq!(usage.retained_allocations(), 0);
2710        assert_eq!(usage.retained_bytes(), 0);
2711        assert_eq!(usage.in_progress_allocations(), 0);
2712        assert_eq!(lock(&registry.state).reserved_bytes, 0);
2713    }
2714
2715    #[test]
2716    fn a_cached_buffer_at_the_same_stride_still_has_to_fit_its_new_grant() {
2717        let registry = Registry::new(AllocatorLimits {
2718            max_concurrent_calls: 1,
2719            max_bytes: 96,
2720            ..limits()
2721        })
2722        .unwrap();
2723        let pool = TestPool::new(2, 64);
2724        let token = registry
2725            .register({
2726                let pool = pool.clone();
2727                let cached = Mutex::new(None);
2728                move |request| pool.buffer(*lock(&cached).get_or_insert(request))
2729            })
2730            .unwrap();
2731        let request = request_of(32);
2732        let (pointer, stride) = registry.allocate(token, request).unwrap();
2733        assert_eq!(stride, 16);
2734        // The second call needs 32 bytes and gets 32, but the cached policy's
2735        // unchanged layout still comes with a 64-byte pool block.
2736        assert!(registry.allocate(token, request).is_none());
2737        let usage = registry.usage();
2738        assert_eq!(usage.declined(AllocationDecline::BufferRefused), 1);
2739        assert_eq!(usage.declined_allocations(), 1);
2740        assert_eq!(usage.retained_bytes(), 64);
2741        assert_eq!(usage.retained_allocations(), 1);
2742        assert_eq!(usage.in_progress_allocations(), 0);
2743        assert_eq!(lock(&registry.state).reserved_bytes, 0);
2744        assert_eq!(pool.releases.load(Ordering::Relaxed), 1);
2745        assert!(registry.free(token, pointer.as_ptr()));
2746        assert_eq!(pool.releases.load(Ordering::Relaxed), 2);
2747        assert_eq!(registry.usage().retained_bytes(), 0);
2748        assert_eq!(registry.usage().retained_allocations(), 0);
2749    }
2750
2751    #[test]
2752    fn exact_compressed_sizes_and_valid_uncompressed_padding_are_published() {
2753        let video = (NDIlib_video_frame_v2_t {
2754            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
2755            xres: 4,
2756            yres: 2,
2757            ..Default::default()
2758        })
2759        .request()
2760        .unwrap();
2761        for request in compressed_requests(32)
2762            .into_iter()
2763            .chain([video, request_of(32)])
2764        {
2765            let registry = Registry::new(limits()).unwrap();
2766            let token = registry
2767                .register(|request: AllocationRequest| {
2768                    AllocationBuffer::zeroed(request.with_stride_bytes(32)?)
2769                })
2770                .unwrap();
2771            let (pointer, stride) = registry.allocate(token, request).unwrap();
2772            assert_eq!(stride, 32);
2773            assert_eq!(registry.usage().declined_allocations(), 0);
2774            assert!(registry.free(token, pointer.as_ptr()));
2775        }
2776    }
2777
2778    #[test]
2779    fn uncompressed_callbacks_reuse_the_checked_layout_only_at_the_same_stride() {
2780        use crate::frames::layout_validation_counts::{AUDIO, VIDEO};
2781
2782        let _serial = lock(&CALLBACK_TEST_LOCK);
2783        let registry = REGISTRY.get_or_init(|| Registry::new(limits()).unwrap());
2784        for (stride, expected_stride, expected_validations) in [(None, 16, 1), (Some(32), 32, 3)] {
2785            let token = registry
2786                .register(move |request: AllocationRequest| {
2787                    let request = match stride {
2788                        Some(stride) => request.with_stride_bytes(stride)?,
2789                        None => request,
2790                    };
2791                    AllocationBuffer::zeroed(request)
2792                })
2793                .unwrap();
2794            let opaque = token as *mut c_void;
2795            let mut video = NDIlib_video_frame_v2_t {
2796                FourCC: FourCc::from(PixelFormat::Bgra).raw(),
2797                xres: 4,
2798                yres: 2,
2799                ..Default::default()
2800            };
2801            let mut audio = NDIlib_audio_frame_v3_t {
2802                FourCC: AudioFormat::Fltp.to_sdk(),
2803                sample_rate: 48_000,
2804                no_channels: 2,
2805                no_samples: 4,
2806                ..Default::default()
2807            };
2808            VIDEO.set(0);
2809            AUDIO.set(0);
2810            // SAFETY: both descriptors are live for the calls, and this
2811            // fixture only passes their allocated pointers back for release.
2812            unsafe {
2813                assert!(allocate(opaque, &mut video));
2814                assert!(free(opaque, &video));
2815                assert!(allocate(opaque, &mut audio));
2816                assert!(free(opaque, &audio));
2817                assert!(!video.p_data.is_null());
2818                assert!(!audio.p_data.is_null());
2819                assert_eq!(video.__bindgen_anon_1.line_stride_in_bytes, expected_stride);
2820                assert_eq!(
2821                    audio.__bindgen_anon_1.channel_stride_in_bytes,
2822                    expected_stride
2823                );
2824            }
2825            registry.closing(token);
2826            // Each packed request is decoded once. Padding validates again
2827            // in the policy and when the registry checks the returned request.
2828            assert_eq!(VIDEO.get(), expected_validations);
2829            assert_eq!(AUDIO.get(), expected_validations);
2830        }
2831    }
2832
2833    #[test]
2834    fn compressed_callback_declines_clear_the_data_and_size() {
2835        // Drive the process callback registry directly. Native setter fixtures
2836        // may share it, but never allocate frames or alter these decline counts.
2837        let _serial = lock(&CALLBACK_TEST_LOCK);
2838        let registry = REGISTRY.get_or_init(|| Registry::new(limits()).unwrap());
2839        let token = registry.register(cached_request_policy()).unwrap();
2840        let opaque = token as *mut c_void;
2841        let mut video = NDIlib_video_frame_v2_t {
2842            FourCC: VideoCodec::H264.outer(StreamTier::Program, false),
2843            xres: 16,
2844            yres: 16,
2845            ..Default::default()
2846        };
2847        video.__bindgen_anon_1.data_size_in_bytes = 64;
2848        // SAFETY: this live descriptor belongs to this call, and the token
2849        // names a registered policy. The fixture performs no native access.
2850        unsafe {
2851            assert!(allocate(opaque, &mut video));
2852            assert!(free(opaque, &video));
2853            video.__bindgen_anon_1.data_size_in_bytes = 32;
2854            assert!(!allocate(opaque, &mut video));
2855            assert!(video.p_data.is_null());
2856            assert_eq!(video.__bindgen_anon_1.data_size_in_bytes, 0);
2857        }
2858        registry.closing(token);
2859
2860        let token = registry.register(cached_request_policy()).unwrap();
2861        let opaque = token as *mut c_void;
2862        let mut audio = NDIlib_audio_frame_v3_t {
2863            FourCC: AudioCodec::Opus.outer(false),
2864            sample_rate: 48_000,
2865            no_channels: 2,
2866            no_samples: 8,
2867            ..Default::default()
2868        };
2869        audio.__bindgen_anon_1.data_size_in_bytes = 64;
2870        // SAFETY: as above, with the matching audio allocation and release.
2871        unsafe {
2872            assert!(allocate(opaque, &mut audio));
2873            assert!(free(opaque, &audio));
2874            audio.__bindgen_anon_1.data_size_in_bytes = 32;
2875            assert!(!allocate(opaque, &mut audio));
2876            assert!(audio.p_data.is_null());
2877            assert_eq!(audio.__bindgen_anon_1.data_size_in_bytes, 0);
2878        }
2879        registry.closing(token);
2880        let usage = registry.usage();
2881        assert_eq!(usage.declined(AllocationDecline::BufferRefused), 2);
2882        assert_eq!(usage.retained_allocations(), 0);
2883        assert_eq!(usage.in_progress_allocations(), 0);
2884    }
2885
2886    /// A policy that can be told apart from another of its type.
2887    struct Tagged(u32);
2888
2889    impl ReceiveAllocator for Tagged {
2890        fn allocate(&self, request: AllocationRequest) -> Result<AllocationBuffer> {
2891            AllocationBuffer::zeroed(request)
2892        }
2893    }
2894
2895    /// Where the policy calls of a test wait for each other.
2896    #[derive(Default)]
2897    struct Gate {
2898        state: Mutex<(usize, bool)>,
2899        changed: std::sync::Condvar,
2900    }
2901
2902    impl Gate {
2903        const PATIENCE: std::time::Duration = std::time::Duration::from_secs(10);
2904
2905        /// Called by a policy: count the call, then wait to be let through.
2906        fn enter(&self) {
2907            let mut state = lock(&self.state);
2908            state.0 += 1;
2909            self.changed.notify_all();
2910            let _ = self
2911                .changed
2912                .wait_timeout_while(state, Self::PATIENCE, |state| !state.1);
2913        }
2914
2915        /// Wait until `calls` policy calls are inside, then say whether they
2916        /// all arrived.
2917        fn wait_for(&self, calls: usize) -> bool {
2918            let (state, _) = self
2919                .changed
2920                .wait_timeout_while(lock(&self.state), Self::PATIENCE, |state| state.0 < calls)
2921                .unwrap_or_else(|poisoned| poisoned.into_inner());
2922            state.0 >= calls
2923        }
2924
2925        fn open(&self) {
2926            lock(&self.state).1 = true;
2927            self.changed.notify_all();
2928        }
2929    }
2930
2931    #[test]
2932    fn limits_are_accepted_only_when_they_can_all_be_reached() {
2933        let defaults = AllocatorLimits::default().validate().unwrap();
2934        assert_eq!(
2935            (
2936                defaults.max_generations,
2937                defaults.max_allocations,
2938                defaults.max_bytes,
2939                defaults.max_concurrent_calls,
2940                defaults.max_allocation_bytes,
2941            ),
2942            (256, 1024, 1024 * MIB, 16, 64 * MIB)
2943        );
2944
2945        let reason = |limits: AllocatorLimits| match limits.validate() {
2946            Err(crate::Error::InvalidInput(reason)) => reason,
2947            other => panic!("expected the limits to be refused, got {other:?}"),
2948        };
2949        for zero in [
2950            defaults.max_generations(0),
2951            defaults.max_allocations(0),
2952            defaults.max_concurrent_calls(0),
2953            defaults.max_allocation_bytes(0),
2954        ] {
2955            assert!(matches!(
2956                reason(zero),
2957                crate::InputDefect::AllocatorPositiveLimits
2958            ));
2959        }
2960        assert!(matches!(
2961            reason(defaults.max_allocation_bytes(MAX_ALLOCATION_BYTES + 1)),
2962            crate::InputDefect::AllocatorAllocationLimit
2963        ));
2964        assert!(matches!(
2965            reason(defaults.max_allocations(15)),
2966            crate::InputDefect::AllocatorConcurrentLimit
2967        ));
2968        // Each of these promises more concurrent calls than the byte budget
2969        // can grant a largest allocation to.
2970        assert!(matches!(
2971            reason(defaults.max_concurrent_calls(17)),
2972            crate::InputDefect::AllocatorByteLimit
2973        ));
2974        assert!(matches!(
2975            reason(defaults.max_allocation_bytes(64 * MIB + 1)),
2976            crate::InputDefect::AllocatorByteLimit
2977        ));
2978        assert!(matches!(
2979            reason(defaults.max_bytes(1024 * MIB - 1)),
2980            crate::InputDefect::AllocatorByteLimit
2981        ));
2982        assert!(matches!(
2983            reason(
2984                defaults
2985                    .max_concurrent_calls(32)
2986                    .max_allocation_bytes(MAX_ALLOCATION_BYTES)
2987            ),
2988            crate::InputDefect::AllocatorByteLimit
2989        ));
2990        assert!(matches!(
2991            reason(
2992                defaults
2993                    .max_bytes(usize::MAX)
2994                    .max_allocations(usize::MAX)
2995                    .max_concurrent_calls(usize::MAX)
2996            ),
2997            crate::InputDefect::AllocatorByteLimit
2998        ));
2999
3000        // The largest single allocation, with the budget to match: accepted
3001        // whenever the budget for the calls can be named. On a 32-bit target
3002        // sixteen largest allocations exceed `usize::MAX`, so
3003        // the same limits are refused there as unreachable.
3004        for calls in [4, 16] {
3005            let limits = defaults
3006                .max_allocation_bytes(MAX_ALLOCATION_BYTES)
3007                .max_concurrent_calls(calls);
3008            match calls.checked_mul(MAX_ALLOCATION_BYTES) {
3009                Some(budget) => {
3010                    limits.max_bytes(budget).validate().unwrap();
3011                }
3012                None => assert!(matches!(
3013                    reason(limits.max_bytes(usize::MAX)),
3014                    crate::InputDefect::AllocatorByteLimit
3015                )),
3016            }
3017        }
3018        defaults
3019            .max_allocation_bytes(MAX_ALLOCATION_BYTES)
3020            .max_concurrent_calls(1)
3021            .validate()
3022            .unwrap();
3023    }
3024
3025    /// With the default limits, as many policy calls as the limits name run
3026    /// at the same time, each granted a largest allocation, and one more is
3027    /// declined.
3028    #[test]
3029    fn every_concurrent_call_the_limits_name_is_admitted() {
3030        let limits = AllocatorLimits::default();
3031        let calls = limits.max_concurrent_calls;
3032        let registry = Registry::new(limits).unwrap();
3033        let gate = Arc::new(Gate::default());
3034        let granted = Arc::new(Mutex::new(Vec::new()));
3035        let token = registry
3036            .register({
3037                let (gate, granted) = (gate.clone(), granted.clone());
3038                move |request: AllocationRequest| {
3039                    lock(&granted).push(request.capacity_limit());
3040                    gate.enter();
3041                    AllocationBuffer::zeroed(request)
3042                }
3043            })
3044            .unwrap();
3045
3046        let (admitted, all_inside, in_progress, one_more) = std::thread::scope(|scope| {
3047            let workers: Vec<_> = (0..calls)
3048                .map(|_| {
3049                    scope.spawn(|| {
3050                        let (pointer, _) = registry.allocate(token, request())?;
3051                        Some(pointer.as_ptr() as usize)
3052                    })
3053                })
3054                .collect();
3055            let all_inside = gate.wait_for(calls);
3056            let in_progress = lock(&registry.state).calls;
3057            let one_more = registry.allocate(token, request());
3058            gate.open();
3059            let admitted: Vec<_> = workers
3060                .into_iter()
3061                .filter_map(|worker| worker.join().unwrap())
3062                .collect();
3063            (admitted, all_inside, in_progress, one_more)
3064        });
3065        assert!(
3066            all_inside,
3067            "only {in_progress} of {calls} calls ran at once"
3068        );
3069        assert_eq!(in_progress, calls);
3070        assert!(one_more.is_none(), "a call beyond the limit was admitted");
3071        let usage = registry.usage();
3072        assert_eq!(usage.declined(AllocationDecline::ConcurrencyLimit), 1);
3073        assert_eq!(usage.declined_allocations(), 1);
3074        assert_eq!(admitted.len(), calls);
3075        assert_eq!(*lock(&granted), vec![limits.max_allocation_bytes; calls]);
3076
3077        let state = lock(&registry.state);
3078        assert_eq!((state.calls, state.reserved_bytes), (0, 0));
3079        assert_eq!((state.leases.len(), state.bytes), (calls, calls * 64));
3080        drop(state);
3081        for address in admitted {
3082            assert!(registry.free(token, address as *mut u8));
3083        }
3084        registry.closing(token);
3085    }
3086
3087    /// A call is granted what is left of the byte budget, and declined only
3088    /// when that cannot hold the frame; buffers the SDK already holds do not
3089    /// cost a later call more than their own size.
3090    #[test]
3091    fn a_call_is_granted_what_is_left_of_the_byte_budget() {
3092        let registry = Registry::new(
3093            AllocatorLimits {
3094                max_generations: 1,
3095                max_allocations: 8,
3096                max_bytes: 256,
3097                max_concurrent_calls: 4,
3098                max_allocation_bytes: 64,
3099            }
3100            .validate()
3101            .unwrap(),
3102        )
3103        .unwrap();
3104        let granted = Arc::new(Mutex::new(Vec::new()));
3105        let token = registry
3106            .register({
3107                let granted = granted.clone();
3108                move |request: AllocationRequest| {
3109                    lock(&granted).push(request.capacity_limit());
3110                    AllocationBuffer::zeroed(request)
3111                }
3112            })
3113            .unwrap();
3114        let mut held = Vec::new();
3115        for _ in 0..3 {
3116            held.push(registry.allocate(token, request()).unwrap().0);
3117        }
3118        held.push(registry.allocate(token, request_of(32)).unwrap().0);
3119        // 224 of 256 bytes are held: 32 are left.
3120        assert!(registry.allocate(token, request()).is_none());
3121        held.push(registry.allocate(token, request_of(16)).unwrap().0);
3122        assert!(registry.allocate(token, request_of(32)).is_none());
3123        held.push(registry.allocate(token, request_of(16)).unwrap().0);
3124        assert!(registry.allocate(token, request_of(8)).is_none());
3125        assert_eq!(*lock(&granted), [64, 64, 64, 64, 32, 16]);
3126        assert_eq!(lock(&registry.state).bytes, 256);
3127        assert_eq!(registry.usage().declined(AllocationDecline::ByteLimit), 3);
3128        assert_eq!(registry.usage().declined_allocations(), 3);
3129
3130        // Freeing returns exactly what the buffer took.
3131        assert!(registry.free(token, held[0].as_ptr()));
3132        assert!(registry.allocate(token, request()).is_some());
3133        assert_eq!(lock(&granted).last(), Some(&64));
3134    }
3135
3136    #[test]
3137    fn a_buffer_beyond_its_grant_is_declined_and_nothing_stays_charged() {
3138        let registry = Registry::new(limits()).unwrap();
3139        let token = registry
3140            .register(|request: AllocationRequest| {
3141                // Twice what the call was granted.
3142                let padded = AllocationRequest {
3143                    capacity_limit: MAX_ALLOCATION_BYTES,
3144                    ..request
3145                };
3146                AllocationBuffer::zeroed(padded.with_stride_bytes(request.stride_bytes() * 4)?)
3147            })
3148            .unwrap();
3149        assert!(registry.allocate(token, request()).is_none());
3150        assert_eq!(
3151            registry.usage().declined(AllocationDecline::BufferRefused),
3152            1
3153        );
3154        assert_eq!(registry.usage().declined_allocations(), 1);
3155        let state = lock(&registry.state);
3156        assert_eq!((state.calls, state.reserved_bytes, state.bytes), (0, 0, 0));
3157        assert!(state.leases.is_empty());
3158    }
3159
3160    #[test]
3161    fn a_counter_advances_only_while_its_rule_allows() {
3162        let counter = AtomicUsize::new(0);
3163        let below = |limit| move |value| (value < limit).then_some(value + 1);
3164        assert_eq!(advance(&counter, below(2)), Some(0));
3165        assert_eq!(advance(&counter, below(2)), Some(1));
3166        assert_eq!(advance(&counter, below(2)), None);
3167        assert_eq!(counter.load(Ordering::Acquire), 2);
3168
3169        counter.store(usize::MAX - 1, Ordering::Release);
3170        let next = |value: usize| value.checked_add(1);
3171        assert_eq!(advance(&counter, next), Some(usize::MAX - 1));
3172        assert_eq!(advance(&counter, next), None);
3173        assert_eq!(counter.load(Ordering::Acquire), usize::MAX);
3174
3175        // Racing threads take exactly the room there is.
3176        let counter = AtomicUsize::new(0);
3177        let taken = AtomicUsize::new(0);
3178        std::thread::scope(|scope| {
3179            for _ in 0..8 {
3180                scope.spawn(|| {
3181                    for _ in 0..1000 {
3182                        if advance(&counter, below(1000)).is_some() {
3183                            taken.fetch_add(1, Ordering::Relaxed);
3184                        }
3185                    }
3186                });
3187            }
3188        });
3189        assert_eq!(counter.load(Ordering::Acquire), 1000);
3190        assert_eq!(taken.load(Ordering::Relaxed), 1000);
3191    }
3192
3193    #[test]
3194    fn a_policy_the_process_has_no_room_for_is_handed_back() {
3195        let registry = Registry::new(limits()).unwrap();
3196        let first = registry.register(Tagged(1)).unwrap();
3197        let second = registry.register(Tagged(2)).unwrap();
3198        assert_eq!((first, second), (1, 2));
3199
3200        // The generation budget is exhausted.
3201        let rejected = registry.register(Tagged(3)).unwrap_err();
3202        assert!(
3203            matches!(rejected.error(), Error::InvalidInput(reason) if matches!(reason, crate::InputDefect::AllocatorGenerationBudget))
3204        );
3205        assert_eq!(rejected.into_inner().0, 3);
3206        assert_eq!(registry.generations.load(Ordering::Acquire), 2);
3207        assert_eq!(lock(&registry.state).active.len(), 2);
3208
3209        // Room again, but no token left to name a generation with: the
3210        // generation that was counted for the attempt is given up.
3211        registry.closing(second);
3212        assert_eq!(registry.generations.load(Ordering::Acquire), 1);
3213        registry.next.store(usize::MAX, Ordering::Release);
3214        let rejected = registry.register(Tagged(4)).unwrap_err();
3215        assert!(matches!(
3216            rejected.error(),
3217            Error::InvalidInput(crate::InputDefect::AllocatorTokensExhausted)
3218        ));
3219        assert_eq!(rejected.into_inner().0, 4);
3220        assert_eq!(registry.generations.load(Ordering::Acquire), 1);
3221        assert_eq!(registry.next.load(Ordering::Acquire), usize::MAX);
3222
3223        // The last token is still handed out.
3224        registry.next.store(usize::MAX - 1, Ordering::Release);
3225        assert_eq!(registry.register(Tagged(5)).unwrap(), usize::MAX - 1);
3226        assert!(registry.allocate(usize::MAX - 1, request()).is_some());
3227    }
3228
3229    #[test]
3230    fn memory_a_request_cannot_use_is_handed_back() {
3231        /// Storage that reports an address one byte into its allocation.
3232        struct Misaligned(OwnedStorage);
3233        // SAFETY: the buffer is refused for its alignment before any use.
3234        unsafe impl ExternalAllocation for Misaligned {
3235            fn pointer(&self) -> NonNull<u8> {
3236                // SAFETY: the allocation is longer than one byte.
3237                unsafe { self.0.pointer().add(1) }
3238            }
3239            fn capacity(&self) -> usize {
3240                self.0.capacity() - 1
3241            }
3242        }
3243
3244        let request = AllocationRequest {
3245            capacity_limit: 128,
3246            ..request()
3247        };
3248        let refused = |storage: OwnedStorage, expected: crate::InputDefect| {
3249            let address = storage.pointer();
3250            let rejected = AllocationBuffer::from_external(request, storage)
3251                .expect_err("the storage does not fit the request");
3252            assert!(matches!(rejected.error(), Error::InvalidInput(reason) if *reason==expected));
3253            assert_eq!(rejected.into_inner().pointer(), address);
3254        };
3255        refused(
3256            OwnedStorage::zeroed(request_of(32)).unwrap(),
3257            crate::InputDefect::ExternalAllocationTooSmall,
3258        );
3259        refused(
3260            OwnedStorage::zeroed(request_of(192)).unwrap(),
3261            crate::InputDefect::ExternalAllocationTooLarge,
3262        );
3263        let rejected = AllocationBuffer::from_external(
3264            request,
3265            Misaligned(OwnedStorage::zeroed(request_of(128)).unwrap()),
3266        )
3267        .expect_err("the storage is misaligned");
3268        assert!(matches!(
3269            rejected.error(),
3270            Error::InvalidInput(crate::InputDefect::ExternalAllocationAlignment)
3271        ));
3272        assert_eq!(rejected.into_inner().0.capacity(), 128);
3273
3274        let buffer = AllocationBuffer::from_external(
3275            request,
3276            OwnedStorage::zeroed(request_of(128)).unwrap(),
3277        )
3278        .unwrap();
3279        assert_eq!(buffer.capacity(), 128);
3280    }
3281
3282    #[test]
3283    fn every_native_request_constructor_requires_a_nonzero_extent() {
3284        let video = NDIlib_video_frame_v2_t {
3285            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
3286            xres: 2,
3287            yres: 1,
3288            ..Default::default()
3289        };
3290        let audio = NDIlib_audio_frame_v3_t {
3291            FourCC: AudioFormat::Fltp.to_sdk(),
3292            sample_rate: 48_000,
3293            no_channels: 1,
3294            no_samples: 1,
3295            ..Default::default()
3296        };
3297        assert!(video.request().unwrap().minimum_bytes() > 0);
3298        assert!(audio.request().unwrap().minimum_bytes() > 0);
3299        assert!((NDIlib_video_frame_v2_t { xres: 0, ..video })
3300            .request()
3301            .is_err());
3302        assert!((NDIlib_audio_frame_v3_t {
3303            no_samples: 0,
3304            ..audio
3305        })
3306        .request()
3307        .is_err());
3308        for size in [0, 1] {
3309            let compressed_video = NDIlib_video_frame_v2_t {
3310                FourCC: VideoCodec::H264.outer(StreamTier::Program, false),
3311                __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
3312                    data_size_in_bytes: size,
3313                },
3314                ..Default::default()
3315            };
3316            let compressed_audio = NDIlib_audio_frame_v3_t {
3317                FourCC: AudioCodec::Opus.outer(false),
3318                __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
3319                    data_size_in_bytes: size,
3320                },
3321                ..Default::default()
3322            };
3323            assert_eq!(compressed_video.request().is_ok(), size != 0);
3324            assert_eq!(compressed_audio.request().is_ok(), size != 0);
3325        }
3326    }
3327
3328    #[test]
3329    fn padded_audio_cannot_publish_a_layout_capture_would_refuse() {
3330        const MIB: usize = 1024 * 1024;
3331        let registry = Registry::new(
3332            AllocatorLimits::default()
3333                .max_allocation_bytes(256 * MIB)
3334                .max_concurrent_calls(4)
3335                .max_bytes(1024 * MIB)
3336                .validate()
3337                .unwrap(),
3338        )
3339        .unwrap();
3340        let format = AudioFormat::Fltp;
3341        let request = (NDIlib_audio_frame_v3_t {
3342            FourCC: format.to_sdk(),
3343            sample_rate: 48_000,
3344            no_channels: 2,
3345            no_samples: 1024,
3346            ..Default::default()
3347        })
3348        .request()
3349        .unwrap();
3350        assert!(matches!(
3351            request.with_stride_bytes(4098),
3352            Err(Error::InvalidInput(crate::InputDefect::Layout(
3353                crate::LayoutDefect::AudioStrideAlignment(4098)
3354            )))
3355        ));
3356        assert!(matches!(
3357            request.with_stride_bytes(65 * MIB),
3358            Err(Error::InvalidInput(crate::InputDefect::Layout(
3359                crate::LayoutDefect::AudioBytes(bytes)
3360            ))) if bytes.get() == (65 * MIB + 4096) as u64
3361        ));
3362        let token = registry
3363            .register(|request: AllocationRequest| {
3364                AllocationBuffer::zeroed(request.with_stride_bytes(65 * MIB)?)
3365            })
3366            .unwrap();
3367        assert!(registry.allocate(token, request).is_none());
3368        assert_eq!(registry.usage().declined(AllocationDecline::PolicyError), 1);
3369        let state = lock(&registry.state);
3370        assert_eq!((state.calls, state.reserved_bytes, state.bytes), (0, 0, 0));
3371        assert!(state.leases.is_empty());
3372    }
3373
3374    #[test]
3375    fn strides_a_request_cannot_use_are_refused_as_input() {
3376        let input = |result: Result<AllocationRequest>| match result {
3377            Err(Error::InvalidInput(reason)) => reason,
3378            other => panic!("expected invalid input, got {other:?}"),
3379        };
3380        let planar = (NDIlib_video_frame_v2_t {
3381            FourCC: FourCc::from(PixelFormat::I420).raw(),
3382            xres: 16,
3383            yres: 16,
3384            ..Default::default()
3385        })
3386        .request()
3387        .unwrap();
3388        assert_eq!(planar.stride_bytes(), 16);
3389        let padded = planar.with_stride_bytes(32).unwrap();
3390        assert_eq!(
3391            (padded.stride_bytes(), padded.minimum_bytes()),
3392            (32, 32 * 16 * 3 / 2)
3393        );
3394        for stride in [0, 15, 17] {
3395            let crate::InputDefect::Layout(input_cause) = input(planar.with_stride_bytes(stride))
3396            else {
3397                panic!("expected the shared layout cause")
3398            };
3399            let Err(Error::InvalidFrame(crate::FrameDefect::Layout(frame_cause))) =
3400                PixelFormat::I420.send_buffer_len(
3401                    16,
3402                    16,
3403                    Some(stride),
3404                    crate::ScanType::Progressive,
3405                )
3406            else {
3407                panic!("expected the same frame layout refusal")
3408            };
3409            assert_eq!(input_cause, frame_cause);
3410            if stride == 0 {
3411                assert_eq!(input_cause, crate::LayoutDefect::VideoZeroStride);
3412            }
3413        }
3414        assert_eq!(padded.with_stride_bytes(16).unwrap(), planar);
3415
3416        let audio = request();
3417        for stride in [0, 30, 34, i32::MAX as usize + 1] {
3418            let crate::InputDefect::Layout(input_cause) = input(audio.with_stride_bytes(stride))
3419            else {
3420                panic!("expected the shared audio layout cause");
3421            };
3422            let Err(Error::InvalidFrame(crate::FrameDefect::Layout(frame_cause))) =
3423                ValidatedAudioLayout::new_uncompressed(
3424                    AudioFormat::Fltp,
3425                    48_000,
3426                    2,
3427                    8,
3428                    Some(stride),
3429                )
3430            else {
3431                panic!("expected the same frame layout refusal");
3432            };
3433            assert_eq!(input_cause, frame_cause);
3434        }
3435        let limited = AllocationRequest {
3436            capacity_limit: 64,
3437            ..audio
3438        };
3439        assert!(matches!(
3440            input(limited.with_stride_bytes(36)),
3441            crate::InputDefect::AllocationTooLarge { .. }
3442        ));
3443
3444        let compressed = (NDIlib_audio_frame_v3_t {
3445            FourCC: AudioCodec::Opus.outer(false),
3446            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
3447                data_size_in_bytes: 32,
3448            },
3449            ..Default::default()
3450        })
3451        .request()
3452        .unwrap();
3453        assert_eq!(compressed.with_stride_bytes(32).unwrap(), compressed);
3454        for request in [planar, audio, compressed] {
3455            let bytes = request.minimum_bytes();
3456            let limited = AllocationRequest {
3457                capacity_limit: bytes - 1,
3458                ..request
3459            };
3460            assert_eq!(
3461                input(limited.with_stride_bytes(limited.stride_bytes())),
3462                crate::InputDefect::AllocationTooLarge {
3463                    bytes,
3464                    limit: bytes - 1,
3465                }
3466            );
3467        }
3468        for stride in [0, 31, 36] {
3469            assert!(matches!(
3470                input(compressed.with_stride_bytes(stride)),
3471                crate::InputDefect::CompressedAllocationStride
3472            ));
3473        }
3474        let audio = (NDIlib_audio_frame_v3_t {
3475            FourCC: AudioFormat::Fltp.to_sdk(),
3476            sample_rate: 48_000,
3477            no_channels: 2,
3478            no_samples: 4,
3479            ..Default::default()
3480        })
3481        .request()
3482        .unwrap();
3483        let narrowed = audio
3484            .with_stride_bytes(32)
3485            .unwrap()
3486            .with_stride_bytes(20)
3487            .unwrap();
3488        assert_eq!(
3489            (narrowed.stride_bytes(), narrowed.minimum_bytes()),
3490            (20, 40)
3491        );
3492    }
3493
3494    #[test]
3495    fn retired_lease_keeps_generation_and_budget_until_matching_free() {
3496        let registry = Registry::new(limits()).unwrap();
3497        let token = registry.register(AllocationBuffer::zeroed).unwrap();
3498        let (pointer, _) = registry.allocate(token, request()).unwrap();
3499        registry.closing(token);
3500        assert!(registry.allocate(token, request()).is_none());
3501        assert_eq!(registry.generations.load(Ordering::Acquire), 1);
3502        let next = registry.register(AllocationBuffer::zeroed).unwrap();
3503        assert_ne!(token, next);
3504        assert!(registry.register(AllocationBuffer::zeroed).is_err());
3505        assert!(registry.free(token, pointer.as_ptr()));
3506        assert!(!registry.free(token, pointer.as_ptr()));
3507        assert_eq!(registry.generations.load(Ordering::Acquire), 1);
3508        registry.closing(next);
3509    }
3510
3511    #[test]
3512    fn a_free_releases_only_an_allocation_of_the_generation_it_names() {
3513        let registry = Registry::new(limits()).unwrap();
3514        let first = registry.register(AllocationBuffer::zeroed).unwrap();
3515        let (pointer, _) = registry.allocate(first, request()).unwrap();
3516        // The receiver moves on to a second generation while the SDK still
3517        // holds the first one's buffer.
3518        registry.closing(first);
3519        let second = registry.register(AllocationBuffer::zeroed).unwrap();
3520
3521        // A free that names the second generation cannot release it.
3522        assert!(!registry.free(second, pointer.as_ptr()));
3523        assert_eq!(lock(&registry.state).bytes, 64);
3524        assert_eq!(registry.generations.load(Ordering::Acquire), 2);
3525
3526        // The free the SDK sends names the generation that allocated, and
3527        // releases the buffer, its budget and the retired generation.
3528        assert!(registry.free(first, pointer.as_ptr()));
3529        assert_eq!(lock(&registry.state).bytes, 0);
3530        assert!(lock(&registry.state).leases.is_empty());
3531        assert_eq!(registry.generations.load(Ordering::Acquire), 1);
3532        registry.closing(second);
3533        assert_eq!(registry.generations.load(Ordering::Acquire), 0);
3534    }
3535
3536    #[test]
3537    fn replacement_is_installed_before_the_earlier_policy_is_destroyed() {
3538        struct ObserveDrop {
3539            setter_calls: Arc<AtomicUsize>,
3540            observed: Arc<AtomicUsize>,
3541        }
3542        impl Drop for ObserveDrop {
3543            fn drop(&mut self) {
3544                self.observed
3545                    .store(self.setter_calls.load(Ordering::Acquire), Ordering::Release);
3546            }
3547        }
3548
3549        // Resetting to SDK memory uses the same ordering as replacement.
3550        for reset in [false, true] {
3551            let registry = Registry::new(limits()).unwrap();
3552            let setter_calls = Arc::new(AtomicUsize::new(1));
3553            let observed = Arc::new(AtomicUsize::new(0));
3554            let observer = ObserveDrop {
3555                setter_calls: setter_calls.clone(),
3556                observed: observed.clone(),
3557            };
3558            let earlier = registry
3559                .register(move |request| {
3560                    let _ = &observer;
3561                    AllocationBuffer::zeroed(request)
3562                })
3563                .unwrap();
3564            let replacement =
3565                (!reset).then(|| registry.register(AllocationBuffer::zeroed).unwrap());
3566            let mut slot = Some(earlier);
3567            install_with(&registry, &mut slot, replacement, || {
3568                setter_calls.fetch_add(1, Ordering::AcqRel);
3569                assert_eq!(observed.load(Ordering::Acquire), 0);
3570            });
3571            assert_eq!(slot, replacement);
3572            assert_eq!(observed.load(Ordering::Acquire), 2);
3573            if let Some(replacement) = replacement {
3574                registry.closing(replacement);
3575            }
3576        }
3577    }
3578
3579    #[test]
3580    fn setter_allocations_publish_but_calls_still_running_at_retirement_do_not() {
3581        let registry = Registry::new(limits()).unwrap();
3582        let gate = Arc::new(Gate::default());
3583        let calls = Arc::new(AtomicUsize::new(0));
3584        let earlier = registry
3585            .register({
3586                let gate = gate.clone();
3587                move |request| {
3588                    if calls.fetch_add(1, Ordering::AcqRel) == 0 {
3589                        gate.enter();
3590                    }
3591                    AllocationBuffer::zeroed(request)
3592                }
3593            })
3594            .unwrap();
3595        let replacement = registry.register(AllocationBuffer::zeroed).unwrap();
3596        let mut slot = Some(earlier);
3597        std::thread::scope(|scope| {
3598            let unfinished = scope.spawn(|| registry.allocate(earlier, request()).is_some());
3599            assert!(gate.wait_for(1));
3600            let mut published = None;
3601            let setter_calls = AtomicUsize::new(0);
3602            install_with(&registry, &mut slot, Some(replacement), || {
3603                setter_calls.fetch_add(1, Ordering::AcqRel);
3604                // The native setter has run, but still has the earlier
3605                // callbacks available until it returns.
3606                published = registry.allocate(earlier, request());
3607                assert!(published.is_some());
3608            });
3609            assert_eq!(setter_calls.load(Ordering::Acquire), 1);
3610            assert_eq!(slot, Some(replacement));
3611            assert_eq!(registry.usage().active_generations(), 1);
3612            gate.open();
3613            assert!(!unfinished.join().unwrap());
3614            assert_eq!(
3615                registry
3616                    .usage()
3617                    .declined(AllocationDecline::GenerationUnavailable),
3618                1
3619            );
3620            assert!(registry.free(earlier, published.unwrap().0.as_ptr()));
3621        });
3622        registry.closing(replacement);
3623        assert_eq!(registry.usage().generations(), 0);
3624    }
3625
3626    #[test]
3627    fn policy_cannot_publish_after_close() {
3628        let registry = Registry::new(limits()).unwrap();
3629        let gate = Arc::new(Gate::default());
3630        let token = registry
3631            .register({
3632                let gate = gate.clone();
3633                move |request| {
3634                    gate.enter();
3635                    AllocationBuffer::zeroed(request)
3636                }
3637            })
3638            .unwrap();
3639        let published = std::thread::scope(|scope| {
3640            let worker = scope.spawn(|| registry.allocate(token, request()).is_some());
3641            assert!(gate.wait_for(1));
3642            registry.closing(token);
3643            assert_eq!(registry.usage().active_generations(), 0);
3644            assert_eq!(registry.usage().in_progress_allocations(), 1);
3645            assert_eq!(registry.usage().generations(), 1);
3646            let replacement = registry.register(AllocationBuffer::zeroed).unwrap();
3647            let (pointer, _) = registry.allocate(replacement, request()).unwrap();
3648            assert!(registry.free(replacement, pointer.as_ptr()));
3649            registry.closing(replacement);
3650            gate.open();
3651            worker.join().unwrap()
3652        });
3653        assert!(!published);
3654        assert_eq!(
3655            registry
3656                .usage()
3657                .declined(AllocationDecline::GenerationUnavailable),
3658            1
3659        );
3660        assert_eq!(registry.usage().declined_allocations(), 1);
3661        assert_eq!(lock(&registry.state).bytes, 0);
3662        assert_eq!(registry.generations.load(Ordering::Acquire), 0);
3663    }
3664
3665    #[test]
3666    fn budgets_cover_multiple_generations_and_panic_paths() {
3667        let registry = Registry::new(limits()).unwrap();
3668        let first = registry.register(AllocationBuffer::zeroed).unwrap();
3669        let second = registry.register(AllocationBuffer::zeroed).unwrap();
3670        let (a, _) = registry.allocate(first, request()).unwrap();
3671        let (b, _) = registry.allocate(second, request()).unwrap();
3672        assert!(registry.allocate(first, request()).is_none());
3673        assert_eq!(
3674            registry
3675                .usage()
3676                .declined(AllocationDecline::AllocationCountLimit),
3677            1
3678        );
3679        registry.closing(first);
3680        registry.closing(second);
3681        assert!(registry.free(first, a.as_ptr()));
3682        assert!(registry.free(second, b.as_ptr()));
3683        let panic = registry
3684            .register(|_| -> Result<AllocationBuffer> { panic!("policy") })
3685            .unwrap();
3686        assert!(registry.allocate(panic, request()).is_none());
3687        assert_eq!(registry.usage().declined(AllocationDecline::PolicyPanic), 1);
3688        assert_eq!(registry.usage().declined_allocations(), 2);
3689        assert_eq!(lock(&registry.state).calls, 0);
3690        assert_eq!(lock(&registry.state).reserved_bytes, 0);
3691        registry.closing(panic);
3692    }
3693
3694    #[test]
3695    fn blocked_storage_reclamation_remains_charged() {
3696        struct DelayedStorage {
3697            storage: OwnedStorage,
3698            gate: Arc<Gate>,
3699        }
3700        // SAFETY: the storage is an owned allocation that this value neither
3701        // changes nor shares.
3702        unsafe impl ExternalAllocation for DelayedStorage {
3703            fn pointer(&self) -> NonNull<u8> {
3704                self.storage.pointer()
3705            }
3706            fn capacity(&self) -> usize {
3707                self.storage.capacity()
3708            }
3709        }
3710        impl Drop for DelayedStorage {
3711            fn drop(&mut self) {
3712                self.gate.enter();
3713            }
3714        }
3715        let registry = Registry::new(
3716            AllocatorLimits {
3717                max_allocations: 1,
3718                max_concurrent_calls: 1,
3719                ..limits()
3720            }
3721            .validate()
3722            .unwrap(),
3723        )
3724        .unwrap();
3725        let gate = Arc::new(Gate::default());
3726        let token = registry
3727            .register({
3728                let gate = gate.clone();
3729                move |request: AllocationRequest| {
3730                    let storage = DelayedStorage {
3731                        storage: OwnedStorage::zeroed(request)?,
3732                        gate: gate.clone(),
3733                    };
3734                    Ok(AllocationBuffer::from_external(request, storage)?)
3735                }
3736            })
3737            .unwrap();
3738        let (pointer, _) = registry.allocate(token, request()).unwrap();
3739        let pointer = pointer.as_ptr() as usize;
3740        std::thread::scope(|scope| {
3741            let free = scope.spawn(|| registry.free(token, pointer as *mut u8));
3742            assert!(gate.wait_for(1));
3743            assert_eq!(lock(&registry.state).bytes, 64);
3744            assert_eq!(lock(&registry.state).reclaiming, 1);
3745            assert!(registry.allocate(token, request()).is_none());
3746            gate.open();
3747            assert!(free.join().unwrap());
3748        });
3749        assert_eq!(lock(&registry.state).bytes, 0);
3750        registry.closing(token);
3751    }
3752}