Skip to main content

usbdac_core/
capture.rs

1//! PCM capture data contracts and bounded buffering.
2//!
3//! This module does not open USB interfaces. The session owner must serialize
4//! completion delivery and reads (for example under its existing stream lock).
5//! No allocations occur on the completion or read paths.
6
7/// Spatial labels in USB Audio channel configurations. These are identities,
8/// not instructions to reorder samples.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ChannelPosition {
11    FrontLeft,
12    FrontRight,
13    FrontCenter,
14    LowFrequency,
15    BackLeft,
16    BackRight,
17    FrontLeftOfCenter,
18    FrontRightOfCenter,
19    BackCenter,
20    SideLeft,
21    SideRight,
22    TopCenter,
23    TopFrontLeft,
24    TopFrontCenter,
25    TopFrontRight,
26    TopBackLeft,
27    TopBackCenter,
28    TopBackRight,
29    TopFrontLeftOfCenter,
30    TopFrontRightOfCenter,
31    LeftLowFrequency,
32    RightLowFrequency,
33    TopSideLeft,
34    TopSideRight,
35    BottomCenter,
36    BackLeftOfCenter,
37    BackRightOfCenter,
38    /// ADC3 HC information segment, preserving relationship, purpose and group.
39    Adc3Information {
40        purpose: u8,
41        relationship: u8,
42        group: u8,
43    },
44    /// ADC3 HC ambisonic segment in its declared wire order.
45    Adc3Ambisonic {
46        ordering: u8,
47        acn: u8,
48        normalization: u8,
49        group: u8,
50    },
51    /// No descriptor label; retain the zero-based interleaved channel index.
52    Unspecified {
53        index: u16,
54    },
55}
56
57/// Ordered channel identities, including unnamed wire channels.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ChannelMap {
60    positions: Vec<ChannelPosition>,
61}
62
63impl ChannelMap {
64    /// Preserve an explicitly ordered map, including unknown positions. Indices
65    /// on unnamed channels must match their zero-based position on the wire.
66    pub fn from_positions(positions: Vec<ChannelPosition>) -> Result<Self, CaptureError> {
67        if positions.is_empty() || positions.len() > usize::from(u16::MAX)
68            || positions.iter().enumerate().any(|(index, position)|
69                matches!(position, ChannelPosition::Unspecified { index: named } if usize::from(*named) != index))
70        { return Err(CaptureError::InvalidChannelMap); }
71        Ok(Self { positions })
72    }
73    /// Decode UAC1's wChannelConfig (Audio 1.0 section 3.7.2.3).
74    pub fn uac1(channels: u16, mask: u16) -> Result<Self, CaptureError> {
75        Self::from_mask(channels, u32::from(mask), 12)
76    }
77
78    /// Decode UAC2's bmChannelConfig (Audio 2.0 section 3.7.2.1).
79    /// Bit 31 indicates non-predefined positions, rather than another speaker.
80    pub fn uac2(channels: u16, mask: u32) -> Result<Self, CaptureError> {
81        if mask & 0x8000_0000 != 0 {
82            if mask != 0x8000_0000 {
83                return Err(CaptureError::InvalidChannelMap);
84            }
85            return Self::from_mask(channels, 0, 27);
86        }
87        Self::from_mask(channels, mask, 27)
88    }
89
90    fn from_mask(channels: u16, mask: u32, bits: u32) -> Result<Self, CaptureError> {
91        use ChannelPosition::*;
92        // USB bit order is the wire channel order. Keep labels explicit instead
93        // of relying on another audio API's numeric speaker enumeration.
94        const LABELS: [ChannelPosition; 27] = [
95            FrontLeft,
96            FrontRight,
97            FrontCenter,
98            LowFrequency,
99            BackLeft,
100            BackRight,
101            FrontLeftOfCenter,
102            FrontRightOfCenter,
103            BackCenter,
104            SideLeft,
105            SideRight,
106            TopCenter,
107            TopFrontLeft,
108            TopFrontCenter,
109            TopFrontRight,
110            TopBackLeft,
111            TopBackCenter,
112            TopBackRight,
113            TopFrontLeftOfCenter,
114            TopFrontRightOfCenter,
115            LeftLowFrequency,
116            RightLowFrequency,
117            TopSideLeft,
118            TopSideRight,
119            BottomCenter,
120            BackLeftOfCenter,
121            BackRightOfCenter,
122        ];
123        if channels == 0 || mask >> bits != 0 || mask.count_ones() > u32::from(channels) {
124            return Err(CaptureError::InvalidChannelMap);
125        }
126        let mut positions = Vec::with_capacity(usize::from(channels));
127        for bit in 0..bits {
128            if mask & (1 << bit) != 0 {
129                positions.push(LABELS[bit as usize]);
130            }
131        }
132        while positions.len() < usize::from(channels) {
133            positions.push(Unspecified {
134                index: positions.len() as u16,
135            });
136        }
137        Ok(Self { positions })
138    }
139
140    pub fn positions(&self) -> &[ChannelPosition] {
141        &self.positions
142    }
143}
144
145/// Exact linear PCM request. No conversion, rate substitution or channel remix.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct CaptureRequest {
148    pub sample_rate: u32,
149    pub channels: u16,
150    pub valid_bits: u8,
151    /// Optional required wire order, preserved across negotiation/reopen.
152    pub channel_map: Option<ChannelMap>,
153}
154
155/// Device PCM geometry, including padding bytes carried unchanged to callers.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct CaptureFormat {
158    sample_rate: u32,
159    valid_bits: u8,
160    subslot_bytes: u8,
161    channel_map: ChannelMap,
162}
163
164impl CaptureFormat {
165    pub fn pcm(
166        sample_rate: u32,
167        valid_bits: u8,
168        subslot_bytes: u8,
169        channel_map: ChannelMap,
170    ) -> Result<Self, CaptureError> {
171        if sample_rate == 0
172            || !(1..=4).contains(&subslot_bytes)
173            || valid_bits == 0
174            || valid_bits > subslot_bytes * 8
175        {
176            return Err(CaptureError::InvalidFormat);
177        }
178        Ok(Self {
179            sample_rate,
180            valid_bits,
181            subslot_bytes,
182            channel_map,
183        })
184    }
185
186    pub fn sample_rate(&self) -> u32 {
187        self.sample_rate
188    }
189    pub fn valid_bits(&self) -> u8 {
190        self.valid_bits
191    }
192    pub fn subslot_bytes(&self) -> u8 {
193        self.subslot_bytes
194    }
195    pub fn channel_map(&self) -> &ChannelMap {
196        &self.channel_map
197    }
198    pub fn channels(&self) -> u16 {
199        self.channel_map.positions.len() as u16
200    }
201    pub fn bytes_per_frame(&self) -> usize {
202        self.channel_map.positions.len() * usize::from(self.subslot_bytes)
203    }
204
205    pub fn satisfies(&self, request: &CaptureRequest) -> bool {
206        self.sample_rate == request.sample_rate
207            && self.channels() == request.channels
208            && self.valid_bits == request.valid_bits
209            && request
210                .channel_map
211                .as_ref()
212                .map_or(true, |map| map == &self.channel_map)
213    }
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum CaptureError {
218    InvalidFormat,
219    InvalidChannelMap,
220    InvalidCapacity,
221    AllocationFailed,
222    /// Caller buffer cannot contain a whole number of wire frames.
223    PartialFrame,
224    /// Packet count, submitted length or backing buffer bounds changed.
225    InvalidCompletion,
226    Stopped,
227    Failed,
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum CaptureState {
232    Active,
233    Stopped,
234    Failed,
235}
236
237#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
238pub struct CaptureStats {
239    /// Callback publication observed ahead of an older submitted transfer.
240    /// Bytes are still delivered in submission order.
241    pub reordered_completions: u64,
242    /// Valid full frames received, including any subsequently dropped backlog.
243    pub captured_frames: u64,
244    pub delivered_frames: u64,
245    /// Host backlog only. Never includes transport loss.
246    pub overrun_frames: u64,
247    /// Valid received frames discarded because a duplex reader held the buffer.
248    /// Separate from ring backlog overruns and device transport loss.
249    pub contention_frames: u64,
250    /// Valid frames withheld while startup or rate proof is pending.
251    pub proof_suppressed_frames: u64,
252    pub empty_packets: u64,
253    /// Successful nonempty packets shorter than their submitted capacity.
254    pub short_packets: u64,
255    pub failed_packets: u64,
256    pub malformed_packets: u64,
257    pub malformed_completions: u64,
258    pub failed_transfers: u64,
259    /// Independently known lost device frames; never infer this from spare IN
260    /// request capacity or an empty/short successful service packet.
261    pub missing_frames: u64,
262}
263
264impl CaptureStats {
265    pub(crate) fn merge(&mut self, stats: CaptureStats) {
266        self.reordered_completions = self
267            .reordered_completions
268            .saturating_add(stats.reordered_completions);
269        self.captured_frames = self.captured_frames.saturating_add(stats.captured_frames);
270        self.delivered_frames = self.delivered_frames.saturating_add(stats.delivered_frames);
271        self.overrun_frames = self.overrun_frames.saturating_add(stats.overrun_frames);
272        self.contention_frames = self
273            .contention_frames
274            .saturating_add(stats.contention_frames);
275        self.proof_suppressed_frames = self
276            .proof_suppressed_frames
277            .saturating_add(stats.proof_suppressed_frames);
278        self.empty_packets = self.empty_packets.saturating_add(stats.empty_packets);
279        self.short_packets = self.short_packets.saturating_add(stats.short_packets);
280        self.failed_packets = self.failed_packets.saturating_add(stats.failed_packets);
281        self.malformed_packets = self
282            .malformed_packets
283            .saturating_add(stats.malformed_packets);
284        self.malformed_completions = self
285            .malformed_completions
286            .saturating_add(stats.malformed_completions);
287        self.failed_transfers = self.failed_transfers.saturating_add(stats.failed_transfers);
288        self.missing_frames = self.missing_frames.saturating_add(stats.missing_frames);
289    }
290
291    /// Classify payload without copying it. The USB worker uses the same rules
292    /// when reader contention requires dropping valid frames at the host.
293    pub(crate) fn record_completion(
294        &mut self,
295        data_len: usize,
296        submitted: &[usize],
297        packets: &[CapturePacket],
298        transfer_succeeded: bool,
299        known_missing_frames: u64,
300        frame_bytes: usize,
301    ) -> Result<(), CaptureError> {
302        self.missing_frames = self.missing_frames.saturating_add(known_missing_frames);
303        if !transfer_succeeded {
304            self.failed_transfers = self.failed_transfers.saturating_add(1);
305            return Ok(());
306        }
307        let total = submitted
308            .iter()
309            .try_fold(0usize, |total, length| total.checked_add(*length));
310        if submitted.len() != packets.len()
311            || total != Some(data_len)
312            || submitted
313                .iter()
314                .zip(packets)
315                .any(|(length, packet)| *length != packet.requested_bytes)
316        {
317            self.malformed_completions = self.malformed_completions.saturating_add(1);
318            return Err(CaptureError::InvalidCompletion);
319        }
320        for (length, packet) in submitted.iter().zip(packets) {
321            if !packet.succeeded {
322                self.failed_packets = self.failed_packets.saturating_add(1);
323            } else if packet.actual_bytes > *length || packet.actual_bytes % frame_bytes != 0 {
324                self.malformed_packets = self.malformed_packets.saturating_add(1);
325            } else if packet.actual_bytes == 0 {
326                self.empty_packets = self.empty_packets.saturating_add(1);
327            } else {
328                if packet.actual_bytes < *length {
329                    self.short_packets = self.short_packets.saturating_add(1);
330                }
331                self.captured_frames = self
332                    .captured_frames
333                    .saturating_add((packet.actual_bytes / frame_bytes) as u64);
334            }
335        }
336        Ok(())
337    }
338
339    /// Lower-bound device position since configure. Unknown losses make this
340    /// an underestimate; host backlog does not change device position.
341    pub fn device_position_frames(&self) -> u64 {
342        self.captured_frames.saturating_add(self.missing_frames)
343    }
344}
345
346/// Completion descriptor detached from libusb. `requested_bytes` must equal
347/// the immutable submitted packet length supplied to `ingest_completion`.
348#[derive(Debug, Clone, Copy)]
349pub struct CapturePacket {
350    pub requested_bytes: usize,
351    pub actual_bytes: usize,
352    pub succeeded: bool,
353}
354
355/// Fixed-capacity queue of interleaved wire frames. Configure once before
356/// transfer submission; retain newest frames when the reader falls behind.
357pub struct CaptureBuffer {
358    format: CaptureFormat,
359    storage: Vec<u8>,
360    head_frame: usize,
361    queued_frames: usize,
362    capacity_frames: usize,
363    stats: CaptureStats,
364    state: CaptureState,
365}
366
367/// Standalone PCM capture running through the direct USB session. A caller may
368/// read from any thread; reads copy complete interleaved wire frames without
369/// conversion. Standalone capture drops old queued frames when readers fall
370/// behind. The synchronized duplex producer instead drops new frames on overflow;
371/// both policies report dropped frames in capture statistics.
372pub struct DacCaptureStream {
373    dac: std::sync::Arc<crate::dac::DacShared>,
374    format: CaptureFormat,
375    interface: u8,
376    alternate: u8,
377    endpoint: u8,
378    configuration: u8,
379    handle: parking_lot::Mutex<crate::transport::capture_stream::CaptureHandle>,
380}
381
382impl DacCaptureStream {
383    pub(crate) fn new(
384        dac: std::sync::Arc<crate::dac::DacShared>,
385        handle: crate::transport::capture_stream::CaptureHandle,
386    ) -> Self {
387        Self {
388            dac,
389            format: handle.endpoint.format.clone(),
390            interface: handle.endpoint.interface,
391            alternate: handle.endpoint.alternate,
392            endpoint: handle.endpoint.address,
393            configuration: handle.endpoint.configuration,
394            handle: parking_lot::Mutex::new(handle),
395        }
396    }
397
398    pub fn format(&self) -> &CaptureFormat {
399        &self.format
400    }
401    pub fn interface_number(&self) -> u8 {
402        self.interface
403    }
404    pub fn alternate_setting(&self) -> u8 {
405        self.alternate
406    }
407    pub fn endpoint_address(&self) -> u8 {
408        self.endpoint
409    }
410    pub fn configuration_id(&self) -> u8 {
411        self.configuration
412    }
413
414    /// Return whole wire frames copied. An active empty stream returns zero.
415    /// Destination length must be a multiple of `format().bytes_per_frame()`.
416    pub fn read(&self, destination: &mut [u8]) -> crate::Result<usize> {
417        let _scope = self.dac.enter()?;
418        let handle = self.handle.lock();
419        let result = handle.read(destination);
420        result.map_err(|error| match error {
421            CaptureError::PartialFrame => crate::Error::InvalidArgument(
422                "capture read buffer must contain whole wire frames".into(),
423            ),
424            CaptureError::Stopped => crate::Error::InvalidState("capture stream is stopped".into()),
425            CaptureError::Failed => handle
426                .error
427                .lock()
428                .clone()
429                .unwrap_or_else(|| crate::Error::Transfer("capture stream failed".into())),
430            other => crate::Error::Transfer(format!("capture read: {other:?}")),
431        })
432    }
433
434    pub fn available_frames(&self) -> usize {
435        self.handle.lock().available_frames()
436    }
437    pub fn stats(&self) -> CaptureStats {
438        self.handle.lock().stats()
439    }
440    pub fn state(&self) -> CaptureState {
441        self.handle.lock().state()
442    }
443    pub fn last_error(&self) -> Option<crate::Error> {
444        self.handle.lock().error.lock().clone()
445    }
446
447    /// Stop and retire IN transfers before handing the interface back. A
448    /// timeout retains USB ownership in the worker; keep host claims/FD until
449    /// `Dac::await_usb_retirement` confirms retirement after closing the DAC.
450    pub fn close(&self) -> crate::Result<()> {
451        let _scope = self.dac.context.enter();
452        self.handle.lock().stop()
453    }
454}
455
456impl CaptureBuffer {
457    pub(crate) fn merge_stats(&mut self, stats: CaptureStats) {
458        self.stats.merge(stats);
459    }
460
461    pub(crate) fn note_malformed_completion(&mut self) {
462        self.stats.malformed_completions = self.stats.malformed_completions.saturating_add(1);
463    }
464
465    pub(crate) fn note_reordered_completion(&mut self) {
466        self.stats.reordered_completions = self.stats.reordered_completions.saturating_add(1);
467    }
468    pub fn new(format: CaptureFormat, capacity_frames: usize) -> Result<Self, CaptureError> {
469        let bytes = capacity_frames
470            .checked_mul(format.bytes_per_frame())
471            .filter(|size| *size != 0)
472            .ok_or(CaptureError::InvalidCapacity)?;
473        let mut storage = Vec::new();
474        storage
475            .try_reserve_exact(bytes)
476            .map_err(|_| CaptureError::AllocationFailed)?;
477        storage.resize(bytes, 0);
478        Ok(Self {
479            format,
480            storage,
481            head_frame: 0,
482            queued_frames: 0,
483            capacity_frames,
484            stats: CaptureStats::default(),
485            state: CaptureState::Active,
486        })
487    }
488
489    pub fn format(&self) -> &CaptureFormat {
490        &self.format
491    }
492    pub fn available_frames(&self) -> usize {
493        self.queued_frames
494    }
495    pub fn stats(&self) -> CaptureStats {
496        self.stats
497    }
498    pub fn state(&self) -> CaptureState {
499        self.state
500    }
501    pub fn stop(&mut self) {
502        self.state = CaptureState::Stopped;
503    }
504    pub fn fail(&mut self) {
505        self.state = CaptureState::Failed;
506    }
507
508    fn require_active(&self) -> Result<(), CaptureError> {
509        match self.state {
510            CaptureState::Active => Ok(()),
511            CaptureState::Stopped => Err(CaptureError::Stopped),
512            CaptureState::Failed => Err(CaptureError::Failed),
513        }
514    }
515
516    /// Validate the entire submitted geometry before accepting any payload.
517    /// Buffer length must equal the sum of immutable submitted packet lengths;
518    /// packet offsets advance by submitted capacity, never by actual length.
519    /// Failed transfers have no trustworthy payload, regardless of packet flags.
520    pub fn ingest_completion(
521        &mut self,
522        data: &[u8],
523        submitted: &[usize],
524        packets: &[CapturePacket],
525        transfer_succeeded: bool,
526        known_missing_frames: u64,
527    ) -> Result<(), CaptureError> {
528        self.require_active()?;
529        self.stats.record_completion(
530            data.len(),
531            submitted,
532            packets,
533            transfer_succeeded,
534            known_missing_frames,
535            self.format.bytes_per_frame(),
536        )?;
537        if transfer_succeeded {
538            let frame_bytes = self.format.bytes_per_frame();
539            let mut offset = 0;
540            for (length, packet) in submitted.iter().zip(packets) {
541                if packet.succeeded
542                    && packet.actual_bytes <= *length
543                    && packet.actual_bytes % frame_bytes == 0
544                    && packet.actual_bytes != 0
545                {
546                    self.push_frames(&data[offset..offset + packet.actual_bytes]);
547                }
548                offset += length;
549            }
550        }
551        Ok(())
552    }
553
554    fn push_frames(&mut self, mut data: &[u8]) {
555        let frame_bytes = self.format.bytes_per_frame();
556        let frames = data.len() / frame_bytes;
557        let dropped = self
558            .queued_frames
559            .saturating_add(frames)
560            .saturating_sub(self.capacity_frames);
561        self.stats.overrun_frames = self.stats.overrun_frames.saturating_add(dropped as u64);
562        if frames >= self.capacity_frames {
563            data = &data[(frames - self.capacity_frames) * frame_bytes..];
564            self.head_frame = 0;
565            self.queued_frames = 0;
566        } else if dropped != 0 {
567            self.head_frame = (self.head_frame + dropped) % self.capacity_frames;
568            self.queued_frames -= dropped;
569        }
570        let tail = (self.head_frame + self.queued_frames) % self.capacity_frames * frame_bytes;
571        let first = data.len().min(self.storage.len() - tail);
572        self.storage[tail..tail + first].copy_from_slice(&data[..first]);
573        self.storage[..data.len() - first].copy_from_slice(&data[first..]);
574        self.queued_frames += data.len() / frame_bytes;
575    }
576
577    /// Copy whole frames, returning their count. Zero means active but empty.
578    /// Stop/failure are distinct errors even if old frames remain queued.
579    pub fn read(&mut self, destination: &mut [u8]) -> Result<usize, CaptureError> {
580        self.require_active()?;
581        let frame_bytes = self.format.bytes_per_frame();
582        if destination.len() % frame_bytes != 0 {
583            return Err(CaptureError::PartialFrame);
584        }
585        let frames = self.queued_frames.min(destination.len() / frame_bytes);
586        let bytes = frames * frame_bytes;
587        let start = self.head_frame * frame_bytes;
588        let first = bytes.min(self.storage.len() - start);
589        destination[..first].copy_from_slice(&self.storage[start..start + first]);
590        destination[first..bytes].copy_from_slice(&self.storage[..bytes - first]);
591        self.head_frame = (self.head_frame + frames) % self.capacity_frames;
592        self.queued_frames -= frames;
593        self.stats.delivered_frames = self.stats.delivered_frames.saturating_add(frames as u64);
594        Ok(frames)
595    }
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    fn format(bits: u8, subslot: u8, channels: u16) -> CaptureFormat {
603        CaptureFormat::pcm(
604            48_000,
605            bits,
606            subslot,
607            ChannelMap::uac2(channels, 0).unwrap(),
608        )
609        .unwrap()
610    }
611
612    fn packet(requested_bytes: usize, actual_bytes: usize, succeeded: bool) -> CapturePacket {
613        CapturePacket {
614            requested_bytes,
615            actual_bytes,
616            succeeded,
617        }
618    }
619
620    fn feed(queue: &mut CaptureBuffer, bytes: &[u8]) {
621        queue
622            .ingest_completion(
623                bytes,
624                &[bytes.len()],
625                &[packet(bytes.len(), bytes.len(), true)],
626                true,
627                0,
628            )
629            .unwrap();
630    }
631
632    #[test]
633    fn channel_masks_preserve_usb_order_and_unknown_indices() {
634        use ChannelPosition::*;
635        assert_eq!(
636            ChannelMap::uac1(5, (1 << 0) | (1 << 2) | (1 << 11))
637                .unwrap()
638                .positions(),
639            &[
640                FrontLeft,
641                FrontCenter,
642                TopCenter,
643                Unspecified { index: 3 },
644                Unspecified { index: 4 }
645            ]
646        );
647        assert_eq!(
648            ChannelMap::uac2(3, (1 << 26) | (1 << 20) | (1 << 12))
649                .unwrap()
650                .positions(),
651            &[TopFrontLeft, LeftLowFrequency, BackRightOfCenter]
652        );
653        assert_eq!(
654            ChannelMap::uac2(2, 0x8000_0000).unwrap().positions(),
655            &[Unspecified { index: 0 }, Unspecified { index: 1 }]
656        );
657        assert_eq!(ChannelMap::uac1(1, 3), Err(CaptureError::InvalidChannelMap));
658        assert_eq!(
659            ChannelMap::uac1(1, 1 << 12),
660            Err(CaptureError::InvalidChannelMap)
661        );
662        assert_eq!(
663            ChannelMap::uac2(1, 1 << 27),
664            Err(CaptureError::InvalidChannelMap)
665        );
666        assert_eq!(
667            ChannelMap::uac2(2, 0x8000_0001),
668            Err(CaptureError::InvalidChannelMap)
669        );
670    }
671
672    #[test]
673    fn exact_request_includes_channel_identity_and_wire_padding() {
674        let stereo = ChannelMap::uac2(2, 3).unwrap();
675        let pcm = CaptureFormat::pcm(48_000, 24, 4, stereo.clone()).unwrap();
676        let mut request = CaptureRequest {
677            sample_rate: 48_000,
678            channels: 2,
679            valid_bits: 24,
680            channel_map: Some(stereo),
681        };
682        assert_eq!(pcm.bytes_per_frame(), 8);
683        assert!(pcm.satisfies(&request));
684        request.channel_map = Some(ChannelMap::uac2(2, 0).unwrap());
685        assert!(!pcm.satisfies(&request));
686        request.channel_map = None;
687        request.sample_rate = 44_100;
688        assert!(!pcm.satisfies(&request));
689        assert_eq!(
690            CaptureFormat::pcm(48_000, 25, 3, ChannelMap::uac2(1, 0).unwrap()),
691            Err(CaptureError::InvalidFormat)
692        );
693    }
694
695    #[test]
696    fn multichannel_vectors_keep_all_wire_bytes_across_packet_batches() {
697        for (bits, subslot) in [(8, 1), (12, 2), (16, 2), (20, 3), (24, 3), (24, 4), (32, 4)] {
698            let mut queue = CaptureBuffer::new(format(bits, subslot, 6), 8).unwrap();
699            let frame_bytes = queue.format().bytes_per_frame();
700            // Every channel, padding byte, and frame has distinct input bytes.
701            let input: Vec<u8> = (0..frame_bytes * 5).map(|n| n as u8).collect();
702            let first = frame_bytes * 2;
703            feed(&mut queue, &input[..first]);
704            feed(&mut queue, &input[first..]);
705            let mut output = vec![0; input.len()];
706            assert_eq!(queue.read(&mut output).unwrap(), 5);
707            assert_eq!(output, input);
708            assert_eq!(queue.stats().captured_frames, 5);
709            assert_eq!(queue.stats().delivered_frames, 5);
710        }
711    }
712
713    #[test]
714    fn wrap_and_host_backlog_drop_oldest_complete_frames() {
715        let mut queue = CaptureBuffer::new(format(16, 2, 1), 3).unwrap();
716        feed(&mut queue, &[1, 1, 2, 2, 3, 3]);
717        assert_eq!(queue.read(&mut [0; 2]).unwrap(), 1);
718        feed(&mut queue, &[4, 4, 5, 5]);
719        let mut out = [0; 6];
720        assert_eq!(queue.read(&mut out).unwrap(), 3);
721        assert_eq!(out, [3, 3, 4, 4, 5, 5]);
722        // One incoming packet is larger than the entire configured ring.
723        feed(&mut queue, &[6, 6, 7, 7, 8, 8, 9, 9]);
724        queue.read(&mut out).unwrap();
725        assert_eq!(out, [7, 7, 8, 8, 9, 9]);
726        assert_eq!(queue.stats().overrun_frames, 2);
727        assert_eq!(queue.stats().missing_frames, 0);
728        assert_eq!(queue.stats().device_position_frames(), 9);
729    }
730
731    #[test]
732    fn short_and_empty_packets_advance_by_submitted_capacity() {
733        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
734        queue
735            .ingest_completion(
736                &[1, 2, 99, 99, 88, 88, 3, 4, 5, 6],
737                &[4, 2, 4],
738                &[packet(4, 2, true), packet(2, 0, true), packet(4, 4, true)],
739                true,
740                0,
741            )
742            .unwrap();
743        let mut out = [0; 6];
744        assert_eq!(queue.read(&mut out).unwrap(), 3);
745        assert_eq!(out, [1, 2, 3, 4, 5, 6]);
746        assert_eq!(queue.stats().short_packets, 1);
747        assert_eq!(queue.stats().empty_packets, 1);
748        assert_eq!(queue.stats().missing_frames, 0);
749    }
750
751    #[test]
752    fn malformed_failed_and_transport_loss_are_separate_from_overrun() {
753        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
754        queue
755            .ingest_completion(
756                &[0; 10],
757                &[2, 2, 2, 2, 2],
758                &[
759                    packet(2, 1, true),
760                    packet(2, 4, true),
761                    packet(2, 0, false),
762                    packet(2, 0, true),
763                    packet(2, 2, true),
764                ],
765                true,
766                7,
767            )
768            .unwrap();
769        queue.ingest_completion(&[], &[], &[], false, 3).unwrap();
770        let stats = queue.stats();
771        assert_eq!(stats.malformed_packets, 2);
772        assert_eq!(stats.failed_packets, 1);
773        assert_eq!(stats.empty_packets, 1);
774        assert_eq!(stats.failed_transfers, 1);
775        assert_eq!(stats.missing_frames, 10);
776        assert_eq!(stats.captured_frames, 1);
777        assert_eq!(stats.device_position_frames(), 11);
778        assert_eq!(stats.overrun_frames, 0);
779    }
780
781    #[test]
782    fn mutated_request_geometry_is_rejected_before_payload_delivery() {
783        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
784        for (data, lengths, packets) in [
785            (
786                &[0; 4][..],
787                vec![2, 2],
788                vec![packet(2, 2, true), packet(4, 2, true)],
789            ),
790            (
791                &[0; 2][..],
792                vec![2, 2],
793                vec![packet(2, 2, true), packet(2, 2, true)],
794            ),
795            (&[0; 2][..], vec![2], vec![]),
796            (
797                &[][..],
798                vec![usize::MAX, 1],
799                vec![packet(usize::MAX, 0, true), packet(1, 0, true)],
800            ),
801        ] {
802            assert_eq!(
803                queue.ingest_completion(data, &lengths, &packets, true, 0),
804                Err(CaptureError::InvalidCompletion)
805            );
806        }
807        assert_eq!(queue.available_frames(), 0);
808        assert_eq!(queue.stats().captured_frames, 0);
809        assert_eq!(queue.stats().malformed_completions, 4);
810    }
811
812    #[test]
813    fn active_empty_partial_read_and_terminal_states_are_distinct() {
814        let mut queue = CaptureBuffer::new(format(16, 2, 1), 1).unwrap();
815        assert_eq!(queue.read(&mut [0; 2]), Ok(0));
816        feed(&mut queue, &[1, 2]);
817        assert_eq!(queue.read(&mut [0; 1]), Err(CaptureError::PartialFrame));
818        assert_eq!(queue.available_frames(), 1);
819        queue.stop();
820        assert_eq!(queue.read(&mut [0; 2]), Err(CaptureError::Stopped));
821        assert_eq!(
822            queue.ingest_completion(&[], &[], &[], true, 0),
823            Err(CaptureError::Stopped)
824        );
825        queue.fail();
826        assert_eq!(queue.read(&mut [0; 2]), Err(CaptureError::Failed));
827    }
828}