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. Slow readers drop old queued frames and expose that in stats.
370pub struct DacCaptureStream {
371    dac: std::sync::Arc<crate::dac::DacShared>,
372    format: CaptureFormat,
373    interface: u8,
374    alternate: u8,
375    endpoint: u8,
376    configuration: u8,
377    handle: parking_lot::Mutex<crate::transport::capture_stream::CaptureHandle>,
378}
379
380impl DacCaptureStream {
381    pub(crate) fn new(
382        dac: std::sync::Arc<crate::dac::DacShared>,
383        handle: crate::transport::capture_stream::CaptureHandle,
384    ) -> Self {
385        Self {
386            dac,
387            format: handle.endpoint.format.clone(),
388            interface: handle.endpoint.interface,
389            alternate: handle.endpoint.alternate,
390            endpoint: handle.endpoint.address,
391            configuration: handle.endpoint.configuration,
392            handle: parking_lot::Mutex::new(handle),
393        }
394    }
395
396    pub fn format(&self) -> &CaptureFormat {
397        &self.format
398    }
399    pub fn interface_number(&self) -> u8 {
400        self.interface
401    }
402    pub fn alternate_setting(&self) -> u8 {
403        self.alternate
404    }
405    pub fn endpoint_address(&self) -> u8 {
406        self.endpoint
407    }
408    pub fn configuration_id(&self) -> u8 {
409        self.configuration
410    }
411
412    /// Return whole wire frames copied. An active empty stream returns zero.
413    /// Destination length must be a multiple of `format().bytes_per_frame()`.
414    pub fn read(&self, destination: &mut [u8]) -> crate::Result<usize> {
415        let _scope = self.dac.enter()?;
416        let handle = self.handle.lock();
417        let result = handle.read(destination);
418        result.map_err(|error| match error {
419            CaptureError::PartialFrame => crate::Error::InvalidArgument(
420                "capture read buffer must contain whole wire frames".into(),
421            ),
422            CaptureError::Stopped => crate::Error::InvalidState("capture stream is stopped".into()),
423            CaptureError::Failed => handle
424                .error
425                .lock()
426                .clone()
427                .unwrap_or_else(|| crate::Error::Transfer("capture stream failed".into())),
428            other => crate::Error::Transfer(format!("capture read: {other:?}")),
429        })
430    }
431
432    pub fn available_frames(&self) -> usize {
433        self.handle.lock().available_frames()
434    }
435    pub fn stats(&self) -> CaptureStats {
436        self.handle.lock().stats()
437    }
438    pub fn state(&self) -> CaptureState {
439        self.handle.lock().state()
440    }
441    pub fn last_error(&self) -> Option<crate::Error> {
442        self.handle.lock().error.lock().clone()
443    }
444
445    /// Stop and retire IN transfers before handing the interface back. A
446    /// timeout retains USB ownership in the worker; keep host claims/FD until
447    /// `Dac::await_usb_retirement` confirms retirement after closing the DAC.
448    pub fn close(&self) -> crate::Result<()> {
449        let _scope = self.dac.context.enter();
450        self.handle.lock().stop()
451    }
452}
453
454impl CaptureBuffer {
455    pub(crate) fn merge_stats(&mut self, stats: CaptureStats) {
456        self.stats.merge(stats);
457    }
458
459    pub(crate) fn note_malformed_completion(&mut self) {
460        self.stats.malformed_completions = self.stats.malformed_completions.saturating_add(1);
461    }
462
463    pub(crate) fn note_reordered_completion(&mut self) {
464        self.stats.reordered_completions = self.stats.reordered_completions.saturating_add(1);
465    }
466    pub fn new(format: CaptureFormat, capacity_frames: usize) -> Result<Self, CaptureError> {
467        let bytes = capacity_frames
468            .checked_mul(format.bytes_per_frame())
469            .filter(|size| *size != 0)
470            .ok_or(CaptureError::InvalidCapacity)?;
471        let mut storage = Vec::new();
472        storage
473            .try_reserve_exact(bytes)
474            .map_err(|_| CaptureError::AllocationFailed)?;
475        storage.resize(bytes, 0);
476        Ok(Self {
477            format,
478            storage,
479            head_frame: 0,
480            queued_frames: 0,
481            capacity_frames,
482            stats: CaptureStats::default(),
483            state: CaptureState::Active,
484        })
485    }
486
487    pub fn format(&self) -> &CaptureFormat {
488        &self.format
489    }
490    pub fn available_frames(&self) -> usize {
491        self.queued_frames
492    }
493    pub fn stats(&self) -> CaptureStats {
494        self.stats
495    }
496    pub fn state(&self) -> CaptureState {
497        self.state
498    }
499    pub fn stop(&mut self) {
500        self.state = CaptureState::Stopped;
501    }
502    pub fn fail(&mut self) {
503        self.state = CaptureState::Failed;
504    }
505
506    fn require_active(&self) -> Result<(), CaptureError> {
507        match self.state {
508            CaptureState::Active => Ok(()),
509            CaptureState::Stopped => Err(CaptureError::Stopped),
510            CaptureState::Failed => Err(CaptureError::Failed),
511        }
512    }
513
514    /// Validate the entire submitted geometry before accepting any payload.
515    /// Buffer length must equal the sum of immutable submitted packet lengths;
516    /// packet offsets advance by submitted capacity, never by actual length.
517    /// Failed transfers have no trustworthy payload, regardless of packet flags.
518    pub fn ingest_completion(
519        &mut self,
520        data: &[u8],
521        submitted: &[usize],
522        packets: &[CapturePacket],
523        transfer_succeeded: bool,
524        known_missing_frames: u64,
525    ) -> Result<(), CaptureError> {
526        self.require_active()?;
527        self.stats.record_completion(
528            data.len(),
529            submitted,
530            packets,
531            transfer_succeeded,
532            known_missing_frames,
533            self.format.bytes_per_frame(),
534        )?;
535        if transfer_succeeded {
536            let frame_bytes = self.format.bytes_per_frame();
537            let mut offset = 0;
538            for (length, packet) in submitted.iter().zip(packets) {
539                if packet.succeeded
540                    && packet.actual_bytes <= *length
541                    && packet.actual_bytes % frame_bytes == 0
542                    && packet.actual_bytes != 0
543                {
544                    self.push_frames(&data[offset..offset + packet.actual_bytes]);
545                }
546                offset += length;
547            }
548        }
549        Ok(())
550    }
551
552    fn push_frames(&mut self, mut data: &[u8]) {
553        let frame_bytes = self.format.bytes_per_frame();
554        let frames = data.len() / frame_bytes;
555        let dropped = self
556            .queued_frames
557            .saturating_add(frames)
558            .saturating_sub(self.capacity_frames);
559        self.stats.overrun_frames = self.stats.overrun_frames.saturating_add(dropped as u64);
560        if frames >= self.capacity_frames {
561            data = &data[(frames - self.capacity_frames) * frame_bytes..];
562            self.head_frame = 0;
563            self.queued_frames = 0;
564        } else if dropped != 0 {
565            self.head_frame = (self.head_frame + dropped) % self.capacity_frames;
566            self.queued_frames -= dropped;
567        }
568        let tail = (self.head_frame + self.queued_frames) % self.capacity_frames * frame_bytes;
569        let first = data.len().min(self.storage.len() - tail);
570        self.storage[tail..tail + first].copy_from_slice(&data[..first]);
571        self.storage[..data.len() - first].copy_from_slice(&data[first..]);
572        self.queued_frames += data.len() / frame_bytes;
573    }
574
575    /// Copy whole frames, returning their count. Zero means active but empty.
576    /// Stop/failure are distinct errors even if old frames remain queued.
577    pub fn read(&mut self, destination: &mut [u8]) -> Result<usize, CaptureError> {
578        self.require_active()?;
579        let frame_bytes = self.format.bytes_per_frame();
580        if destination.len() % frame_bytes != 0 {
581            return Err(CaptureError::PartialFrame);
582        }
583        let frames = self.queued_frames.min(destination.len() / frame_bytes);
584        let bytes = frames * frame_bytes;
585        let start = self.head_frame * frame_bytes;
586        let first = bytes.min(self.storage.len() - start);
587        destination[..first].copy_from_slice(&self.storage[start..start + first]);
588        destination[first..bytes].copy_from_slice(&self.storage[..bytes - first]);
589        self.head_frame = (self.head_frame + frames) % self.capacity_frames;
590        self.queued_frames -= frames;
591        self.stats.delivered_frames = self.stats.delivered_frames.saturating_add(frames as u64);
592        Ok(frames)
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    fn format(bits: u8, subslot: u8, channels: u16) -> CaptureFormat {
601        CaptureFormat::pcm(
602            48_000,
603            bits,
604            subslot,
605            ChannelMap::uac2(channels, 0).unwrap(),
606        )
607        .unwrap()
608    }
609
610    fn packet(requested_bytes: usize, actual_bytes: usize, succeeded: bool) -> CapturePacket {
611        CapturePacket {
612            requested_bytes,
613            actual_bytes,
614            succeeded,
615        }
616    }
617
618    fn feed(queue: &mut CaptureBuffer, bytes: &[u8]) {
619        queue
620            .ingest_completion(
621                bytes,
622                &[bytes.len()],
623                &[packet(bytes.len(), bytes.len(), true)],
624                true,
625                0,
626            )
627            .unwrap();
628    }
629
630    #[test]
631    fn channel_masks_preserve_usb_order_and_unknown_indices() {
632        use ChannelPosition::*;
633        assert_eq!(
634            ChannelMap::uac1(5, (1 << 0) | (1 << 2) | (1 << 11))
635                .unwrap()
636                .positions(),
637            &[
638                FrontLeft,
639                FrontCenter,
640                TopCenter,
641                Unspecified { index: 3 },
642                Unspecified { index: 4 }
643            ]
644        );
645        assert_eq!(
646            ChannelMap::uac2(3, (1 << 26) | (1 << 20) | (1 << 12))
647                .unwrap()
648                .positions(),
649            &[TopFrontLeft, LeftLowFrequency, BackRightOfCenter]
650        );
651        assert_eq!(
652            ChannelMap::uac2(2, 0x8000_0000).unwrap().positions(),
653            &[Unspecified { index: 0 }, Unspecified { index: 1 }]
654        );
655        assert_eq!(ChannelMap::uac1(1, 3), Err(CaptureError::InvalidChannelMap));
656        assert_eq!(
657            ChannelMap::uac1(1, 1 << 12),
658            Err(CaptureError::InvalidChannelMap)
659        );
660        assert_eq!(
661            ChannelMap::uac2(1, 1 << 27),
662            Err(CaptureError::InvalidChannelMap)
663        );
664        assert_eq!(
665            ChannelMap::uac2(2, 0x8000_0001),
666            Err(CaptureError::InvalidChannelMap)
667        );
668    }
669
670    #[test]
671    fn exact_request_includes_channel_identity_and_wire_padding() {
672        let stereo = ChannelMap::uac2(2, 3).unwrap();
673        let pcm = CaptureFormat::pcm(48_000, 24, 4, stereo.clone()).unwrap();
674        let mut request = CaptureRequest {
675            sample_rate: 48_000,
676            channels: 2,
677            valid_bits: 24,
678            channel_map: Some(stereo),
679        };
680        assert_eq!(pcm.bytes_per_frame(), 8);
681        assert!(pcm.satisfies(&request));
682        request.channel_map = Some(ChannelMap::uac2(2, 0).unwrap());
683        assert!(!pcm.satisfies(&request));
684        request.channel_map = None;
685        request.sample_rate = 44_100;
686        assert!(!pcm.satisfies(&request));
687        assert_eq!(
688            CaptureFormat::pcm(48_000, 25, 3, ChannelMap::uac2(1, 0).unwrap()),
689            Err(CaptureError::InvalidFormat)
690        );
691    }
692
693    #[test]
694    fn multichannel_vectors_keep_all_wire_bytes_across_packet_batches() {
695        for (bits, subslot) in [(8, 1), (12, 2), (16, 2), (20, 3), (24, 3), (24, 4), (32, 4)] {
696            let mut queue = CaptureBuffer::new(format(bits, subslot, 6), 8).unwrap();
697            let frame_bytes = queue.format().bytes_per_frame();
698            // Every channel, padding byte, and frame has distinct input bytes.
699            let input: Vec<u8> = (0..frame_bytes * 5).map(|n| n as u8).collect();
700            let first = frame_bytes * 2;
701            feed(&mut queue, &input[..first]);
702            feed(&mut queue, &input[first..]);
703            let mut output = vec![0; input.len()];
704            assert_eq!(queue.read(&mut output).unwrap(), 5);
705            assert_eq!(output, input);
706            assert_eq!(queue.stats().captured_frames, 5);
707            assert_eq!(queue.stats().delivered_frames, 5);
708        }
709    }
710
711    #[test]
712    fn wrap_and_host_backlog_drop_oldest_complete_frames() {
713        let mut queue = CaptureBuffer::new(format(16, 2, 1), 3).unwrap();
714        feed(&mut queue, &[1, 1, 2, 2, 3, 3]);
715        assert_eq!(queue.read(&mut [0; 2]).unwrap(), 1);
716        feed(&mut queue, &[4, 4, 5, 5]);
717        let mut out = [0; 6];
718        assert_eq!(queue.read(&mut out).unwrap(), 3);
719        assert_eq!(out, [3, 3, 4, 4, 5, 5]);
720        // One incoming packet is larger than the entire configured ring.
721        feed(&mut queue, &[6, 6, 7, 7, 8, 8, 9, 9]);
722        queue.read(&mut out).unwrap();
723        assert_eq!(out, [7, 7, 8, 8, 9, 9]);
724        assert_eq!(queue.stats().overrun_frames, 2);
725        assert_eq!(queue.stats().missing_frames, 0);
726        assert_eq!(queue.stats().device_position_frames(), 9);
727    }
728
729    #[test]
730    fn short_and_empty_packets_advance_by_submitted_capacity() {
731        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
732        queue
733            .ingest_completion(
734                &[1, 2, 99, 99, 88, 88, 3, 4, 5, 6],
735                &[4, 2, 4],
736                &[packet(4, 2, true), packet(2, 0, true), packet(4, 4, true)],
737                true,
738                0,
739            )
740            .unwrap();
741        let mut out = [0; 6];
742        assert_eq!(queue.read(&mut out).unwrap(), 3);
743        assert_eq!(out, [1, 2, 3, 4, 5, 6]);
744        assert_eq!(queue.stats().short_packets, 1);
745        assert_eq!(queue.stats().empty_packets, 1);
746        assert_eq!(queue.stats().missing_frames, 0);
747    }
748
749    #[test]
750    fn malformed_failed_and_transport_loss_are_separate_from_overrun() {
751        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
752        queue
753            .ingest_completion(
754                &[0; 10],
755                &[2, 2, 2, 2, 2],
756                &[
757                    packet(2, 1, true),
758                    packet(2, 4, true),
759                    packet(2, 0, false),
760                    packet(2, 0, true),
761                    packet(2, 2, true),
762                ],
763                true,
764                7,
765            )
766            .unwrap();
767        queue.ingest_completion(&[], &[], &[], false, 3).unwrap();
768        let stats = queue.stats();
769        assert_eq!(stats.malformed_packets, 2);
770        assert_eq!(stats.failed_packets, 1);
771        assert_eq!(stats.empty_packets, 1);
772        assert_eq!(stats.failed_transfers, 1);
773        assert_eq!(stats.missing_frames, 10);
774        assert_eq!(stats.captured_frames, 1);
775        assert_eq!(stats.device_position_frames(), 11);
776        assert_eq!(stats.overrun_frames, 0);
777    }
778
779    #[test]
780    fn mutated_request_geometry_is_rejected_before_payload_delivery() {
781        let mut queue = CaptureBuffer::new(format(16, 2, 1), 8).unwrap();
782        for (data, lengths, packets) in [
783            (
784                &[0; 4][..],
785                vec![2, 2],
786                vec![packet(2, 2, true), packet(4, 2, true)],
787            ),
788            (
789                &[0; 2][..],
790                vec![2, 2],
791                vec![packet(2, 2, true), packet(2, 2, true)],
792            ),
793            (&[0; 2][..], vec![2], vec![]),
794            (
795                &[][..],
796                vec![usize::MAX, 1],
797                vec![packet(usize::MAX, 0, true), packet(1, 0, true)],
798            ),
799        ] {
800            assert_eq!(
801                queue.ingest_completion(data, &lengths, &packets, true, 0),
802                Err(CaptureError::InvalidCompletion)
803            );
804        }
805        assert_eq!(queue.available_frames(), 0);
806        assert_eq!(queue.stats().captured_frames, 0);
807        assert_eq!(queue.stats().malformed_completions, 4);
808    }
809
810    #[test]
811    fn active_empty_partial_read_and_terminal_states_are_distinct() {
812        let mut queue = CaptureBuffer::new(format(16, 2, 1), 1).unwrap();
813        assert_eq!(queue.read(&mut [0; 2]), Ok(0));
814        feed(&mut queue, &[1, 2]);
815        assert_eq!(queue.read(&mut [0; 1]), Err(CaptureError::PartialFrame));
816        assert_eq!(queue.available_frames(), 1);
817        queue.stop();
818        assert_eq!(queue.read(&mut [0; 2]), Err(CaptureError::Stopped));
819        assert_eq!(
820            queue.ingest_completion(&[], &[], &[], true, 0),
821            Err(CaptureError::Stopped)
822        );
823        queue.fail();
824        assert_eq!(queue.read(&mut [0; 2]), Err(CaptureError::Failed));
825    }
826}