Skip to main content

usbdac_core/
feedback_diagnostics.rs

1//! Bounded evidence from a stream's dedicated USB feedback endpoint.
2
3use parking_lot::Mutex;
4use std::collections::VecDeque;
5use std::fmt;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::Instant;
8
9const STARTUP_ENTRIES: usize = 128;
10const RECENT_ENTRIES: usize = 2_048;
11
12/// What happened to a packet while it was examined for explicit feedback.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum ExplicitFeedbackOutcome {
16    Valid,
17    Empty,
18    TransferFailed,
19    PacketFailed,
20    InvalidLength,
21    InvalidEncoding,
22    RateOutOfRange,
23    PacketCapacityExceeded,
24    TimebaseCandidate,
25}
26
27impl ExplicitFeedbackOutcome {
28    pub fn code(self) -> &'static str {
29        match self {
30            Self::Valid => "valid",
31            Self::Empty => "empty",
32            Self::TransferFailed => "transfer_failed",
33            Self::PacketFailed => "packet_failed",
34            Self::InvalidLength => "invalid_length",
35            Self::InvalidEncoding => "invalid_encoding",
36            Self::RateOutOfRange => "rate_out_of_range",
37            Self::PacketCapacityExceeded => "packet_capacity_exceeded",
38            Self::TimebaseCandidate => "timebase_candidate",
39        }
40    }
41
42    fn index(self) -> usize {
43        match self {
44            Self::Valid => 0,
45            Self::Empty => 1,
46            Self::TransferFailed => 2,
47            Self::PacketFailed => 3,
48            Self::InvalidLength => 4,
49            Self::InvalidEncoding => 5,
50            Self::RateOutOfRange => 6,
51            Self::PacketCapacityExceeded => 7,
52            Self::TimebaseCandidate => 8,
53        }
54    }
55}
56
57/// The most recent packet observed for one feedback outcome.
58#[derive(Debug, Clone, Copy, PartialEq)]
59#[non_exhaustive]
60pub struct ExplicitFeedbackPacket {
61    pub outcome: ExplicitFeedbackOutcome,
62    pub transfer_status: i32,
63    /// The libusb packet status, or `None` when no packet status was reported.
64    pub packet_status: Option<i32>,
65    pub requested_bytes: usize,
66    pub actual_bytes: usize,
67    pub frames_per_out_service: Option<f64>,
68    pub decoded_rate_hz: Option<f64>,
69    bytes: [u8; 8],
70    byte_count: usize,
71}
72
73impl ExplicitFeedbackPacket {
74    #[allow(clippy::too_many_arguments)]
75    pub(crate) fn new(
76        outcome: ExplicitFeedbackOutcome,
77        transfer_status: i32,
78        packet_status: Option<i32>,
79        requested_bytes: usize,
80        actual_bytes: usize,
81        raw_bytes: &[u8],
82        decoded: Option<(f64, f64)>,
83    ) -> Self {
84        let mut bytes = [0; 8];
85        let byte_count = raw_bytes.len().min(bytes.len());
86        bytes[..byte_count].copy_from_slice(&raw_bytes[..byte_count]);
87        Self {
88            outcome,
89            transfer_status,
90            packet_status,
91            requested_bytes,
92            actual_bytes,
93            frames_per_out_service: decoded.map(|(frames, _)| frames),
94            decoded_rate_hz: decoded.map(|(_, rate)| rate),
95            bytes,
96            byte_count,
97        }
98    }
99
100    /// Up to eight bytes from the feedback IN endpoint. No audio OUT payload.
101    pub fn raw_bytes(&self) -> &[u8] {
102        &self.bytes[..self.byte_count]
103    }
104}
105
106/// Feedback endpoint geometry and observations for one stream. Status counts
107/// are indexed by libusb transfer status (0 completed, 1 error, 2 timed out,
108/// 3 cancelled, 4 stall, 5 no device, 6 overflow). Index 7 is unknown or
109/// unreported. An interrupt transfer has no separate packet status.
110#[derive(Debug, Default, Clone, Copy, PartialEq)]
111#[non_exhaustive]
112pub struct ExplicitFeedbackDiagnostics {
113    pub endpoint: u8,
114    pub transfer_type: &'static str,
115    pub link_speed: &'static str,
116    pub interface_number: u8,
117    pub alt_setting: u8,
118    pub out_endpoint: u8,
119    pub nominal_rate_hz: u32,
120    pub out_service_interval_us: u32,
121    pub out_max_packet_bytes: usize,
122    pub out_bytes_per_frame: usize,
123    pub feedback_interval: u8,
124    pub feedback_refresh: u8,
125    pub feedback_service_interval_us: u32,
126    pub feedback_max_packet_bytes: usize,
127    pub requested_packet_bytes: usize,
128    pub packets_per_transfer: usize,
129    pub transfer_timeout_ms: u32,
130    pub per_service_interval_quirk: bool,
131    pub post_alt_readback_hz: Option<u32>,
132    pub timebase: Option<&'static str>,
133    pub inferred_timebase: bool,
134    /// The current stream validated units already learned on this DAC session.
135    pub reused_timebase: bool,
136    pub successful_submissions: u64,
137    pub submit_failures: u64,
138    /// libusb submission error code, separate from completion status.
139    pub last_submit_error: Option<i32>,
140    pub transfer_status_counts: [u64; 8],
141    pub packet_status_counts: [u64; 8],
142    pub accepted_reports: u64,
143    pub(crate) samples: [Option<ExplicitFeedbackPacket>; 9],
144}
145
146impl ExplicitFeedbackDiagnostics {
147    /// One latest observation per outcome, including bytes from rejected reports.
148    pub fn packet_samples(&self) -> impl Iterator<Item = &ExplicitFeedbackPacket> {
149        self.samples.iter().flatten()
150    }
151
152    pub(crate) fn record_submit(&mut self, result: i32) {
153        if result == 0 {
154            self.successful_submissions = self.successful_submissions.saturating_add(1);
155        } else {
156            self.submit_failures = self.submit_failures.saturating_add(1);
157            self.last_submit_error = Some(result);
158        }
159    }
160
161    fn count_status(counts: &mut [u64; 8], status: Option<i32>) {
162        let index = match status {
163            Some(code @ 0..=6) => code as usize,
164            _ => 7,
165        };
166        counts[index] = counts[index].saturating_add(1);
167    }
168
169    pub(crate) fn record_transfer(&mut self, status: i32) {
170        Self::count_status(&mut self.transfer_status_counts, Some(status));
171    }
172
173    pub(crate) fn record_packet(&mut self, sample: ExplicitFeedbackPacket, is_iso: bool) {
174        if is_iso {
175            Self::count_status(&mut self.packet_status_counts, sample.packet_status);
176        }
177        let slot = &mut self.samples[sample.outcome.index()];
178        // On a transfer error preserve any observed payload in preference to
179        // a following descriptor with no bytes.
180        if sample.outcome != ExplicitFeedbackOutcome::TransferFailed
181            || sample.actual_bytes > 0
182            || slot.map_or(true, |previous| previous.actual_bytes == 0)
183        {
184            *slot = Some(sample);
185        }
186    }
187}
188
189/// An observation from the selected USB feedback path.
190#[derive(Debug, Clone, Copy, PartialEq)]
191#[non_exhaustive]
192pub enum FeedbackTraceEvent {
193    Submit {
194        slot: Option<usize>,
195        status: i32,
196    },
197    Completion {
198        slot: Option<usize>,
199        status: i32,
200        actual_bytes: usize,
201    },
202    ExplicitPacket {
203        index: usize,
204        sample: ExplicitFeedbackPacket,
205    },
206    ImplicitSource {
207        interface_number: u8,
208        alt_setting: u8,
209        endpoint: u8,
210        service_interval_us: u32,
211        max_packet_bytes: usize,
212        bytes_per_frame: usize,
213    },
214    ImplicitPacket {
215        index: usize,
216        status: i32,
217        requested_bytes: usize,
218        actual_bytes: usize,
219    },
220    Lock {
221        locked: bool,
222        stale: bool,
223    },
224    Timebase {
225        unit: &'static str,
226        inferred: bool,
227    },
228}
229
230/// A record in the trace, timed from stream creation using a monotonic clock.
231#[derive(Debug, Clone, Copy, PartialEq)]
232#[non_exhaustive]
233pub struct FeedbackTraceEntry {
234    pub elapsed_us: u64,
235    pub event: FeedbackTraceEvent,
236}
237
238/// A shareable support capture for the most recent stream of a DAC session.
239#[derive(Debug, Clone, PartialEq)]
240#[non_exhaustive]
241pub struct FeedbackTrace {
242    pub format: crate::StreamFormat,
243    pub explicit: Option<ExplicitFeedbackDiagnostics>,
244    pub entries: Vec<FeedbackTraceEntry>,
245    /// Observations overwritten at the retention limit or missed during an export.
246    pub dropped_entries: u64,
247    pub failure: Option<String>,
248}
249
250#[derive(Debug)]
251pub(crate) struct FeedbackRecorder {
252    started_at: Instant,
253    dropped: AtomicU64,
254    history: Mutex<History>,
255}
256
257#[derive(Debug)]
258struct History {
259    startup: Vec<FeedbackTraceEntry>,
260    recent: VecDeque<FeedbackTraceEntry>,
261    failure: Option<String>,
262}
263
264impl FeedbackRecorder {
265    pub(crate) fn new(started_at: Instant) -> Self {
266        Self {
267            started_at,
268            dropped: AtomicU64::new(0),
269            history: Mutex::new(History {
270                startup: Vec::with_capacity(STARTUP_ENTRIES),
271                recent: VecDeque::with_capacity(RECENT_ENTRIES),
272                failure: None,
273            }),
274        }
275    }
276
277    pub(crate) fn record(&self, event: FeedbackTraceEvent) {
278        self.record_at(Instant::now(), event);
279    }
280
281    pub(crate) fn record_at(&self, timestamp: Instant, event: FeedbackTraceEvent) {
282        let Some(mut history) = self.history.try_lock() else {
283            self.dropped.fetch_add(1, Ordering::Relaxed);
284            return;
285        };
286        let entry = FeedbackTraceEntry {
287            elapsed_us: timestamp
288                .saturating_duration_since(self.started_at)
289                .as_micros()
290                .min(u128::from(u64::MAX)) as u64,
291            event,
292        };
293        if history.startup.len() < STARTUP_ENTRIES {
294            history.startup.push(entry);
295        } else {
296            if history.recent.len() == RECENT_ENTRIES {
297                history.recent.pop_front();
298                self.dropped.fetch_add(1, Ordering::Relaxed);
299            }
300            history.recent.push_back(entry);
301        }
302    }
303
304    pub(crate) fn fail(&self, reason: &str) {
305        self.history.lock().failure = Some(reason.to_owned());
306    }
307
308    pub(crate) fn snapshot(
309        &self,
310        format: crate::StreamFormat,
311        explicit: Option<ExplicitFeedbackDiagnostics>,
312    ) -> FeedbackTrace {
313        let history = self.history.lock();
314        FeedbackTrace {
315            format,
316            explicit,
317            entries: history
318                .startup
319                .iter()
320                .chain(&history.recent)
321                .copied()
322                .collect(),
323            dropped_entries: self.dropped.load(Ordering::Relaxed),
324            failure: history.failure.clone(),
325        }
326    }
327}
328
329impl fmt::Display for ExplicitFeedbackDiagnostics {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        write!(
332            f,
333            concat!(
334                "feedback ep=0x{:02x} {} {} if={} alt={} bInterval={} refresh={} poll={}us ",
335                "request={}B x{} descriptor={}B timeout={}ms out=0x{:02x} {}us ",
336                "capacity={}B stride={}B nominal={}Hz clock_readback={:?} ",
337                "timebase={:?} inferred={} reused={} per_service_quirk={} ",
338                "submits={} submit_failures={} last_submit_error={:?} ",
339                "transfer_statuses={:?} packet_statuses={:?} accepted={}"
340            ),
341            self.endpoint,
342            self.transfer_type,
343            self.link_speed,
344            self.interface_number,
345            self.alt_setting,
346            self.feedback_interval,
347            self.feedback_refresh,
348            self.feedback_service_interval_us,
349            self.requested_packet_bytes,
350            self.packets_per_transfer,
351            self.feedback_max_packet_bytes,
352            self.transfer_timeout_ms,
353            self.out_endpoint,
354            self.out_service_interval_us,
355            self.out_max_packet_bytes,
356            self.out_bytes_per_frame,
357            self.nominal_rate_hz,
358            self.post_alt_readback_hz,
359            self.timebase,
360            self.inferred_timebase,
361            self.reused_timebase,
362            self.per_service_interval_quirk,
363            self.successful_submissions,
364            self.submit_failures,
365            self.last_submit_error,
366            self.transfer_status_counts,
367            self.packet_status_counts,
368            self.accepted_reports,
369        )?;
370        for packet in self.packet_samples() {
371            write!(
372                f,
373                " {}(transfer={} packet={:?} bytes={}/{} raw={:02x?} rate={:?} frames={:?})",
374                packet.outcome.code(),
375                packet.transfer_status,
376                packet.packet_status,
377                packet.actual_bytes,
378                packet.requested_bytes,
379                packet.raw_bytes(),
380                packet.decoded_rate_hz,
381                packet.frames_per_out_service,
382            )?;
383        }
384        Ok(())
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn preserves_startup_and_latest_observations_with_bounded_storage() {
394        let start = Instant::now();
395        let recorder = FeedbackRecorder::new(start);
396        let total = STARTUP_ENTRIES + RECENT_ENTRIES + 5;
397        for n in 0..total {
398            recorder.record_at(
399                start + std::time::Duration::from_micros(n as u64),
400                FeedbackTraceEvent::Submit {
401                    slot: None,
402                    status: 0,
403                },
404            );
405        }
406        recorder.fail("feedback deadline");
407        let history = recorder.history.lock();
408        assert_eq!(history.startup.len(), STARTUP_ENTRIES);
409        assert_eq!(history.startup[0].elapsed_us, 0);
410        assert_eq!(history.recent.len(), RECENT_ENTRIES);
411        assert_eq!(
412            history.recent.front().unwrap().elapsed_us,
413            (STARTUP_ENTRIES + 5) as u64
414        );
415        assert_eq!(
416            history.recent.back().unwrap().elapsed_us,
417            (total - 1) as u64
418        );
419        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
420        assert_eq!(history.failure.as_deref(), Some("feedback deadline"));
421    }
422}