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 transfer_slots: usize,
129    pub packets_per_transfer: usize,
130    pub transfer_timeout_ms: u32,
131    pub per_service_interval_quirk: bool,
132    pub post_alt_readback_hz: Option<u32>,
133    pub timebase: Option<&'static str>,
134    pub inferred_timebase: bool,
135    /// The current stream validated units already learned on this DAC session.
136    pub reused_timebase: bool,
137    pub successful_submissions: u64,
138    pub submit_failures: u64,
139    /// libusb submission error code, separate from completion status.
140    pub last_submit_error: Option<i32>,
141    pub transfer_status_counts: [u64; 8],
142    pub packet_status_counts: [u64; 8],
143    pub accepted_reports: u64,
144    /// Accepted unsmoothed observations, in frames per OUT service interval.
145    pub rate_samples: u64,
146    pub rate_min_frames: f64,
147    pub rate_max_frames: f64,
148    pub rate_mean_frames: f64,
149    /// Population variance before the configured timing policy. No audible
150    /// smoothing tradeoff is inferred.
151    pub rate_variance_frames: f64,
152    pub empty_polls: u64,
153    pub rejected_reports: u64,
154    pub(crate) samples: [Option<ExplicitFeedbackPacket>; 9],
155}
156
157impl ExplicitFeedbackDiagnostics {
158    /// One latest observation per outcome, including bytes from rejected reports.
159    pub fn packet_samples(&self) -> impl Iterator<Item = &ExplicitFeedbackPacket> {
160        self.samples.iter().flatten()
161    }
162
163    pub(crate) fn record_submit(&mut self, result: i32) {
164        if result == 0 {
165            self.successful_submissions = self.successful_submissions.saturating_add(1);
166        } else {
167            self.submit_failures = self.submit_failures.saturating_add(1);
168            self.last_submit_error = Some(result);
169        }
170    }
171
172    fn count_status(counts: &mut [u64; 8], status: Option<i32>) {
173        let index = match status {
174            Some(code @ 0..=6) => code as usize,
175            _ => 7,
176        };
177        counts[index] = counts[index].saturating_add(1);
178    }
179
180    pub(crate) fn record_transfer(&mut self, status: i32) {
181        Self::count_status(&mut self.transfer_status_counts, Some(status));
182    }
183
184    pub(crate) fn record_packet(&mut self, sample: ExplicitFeedbackPacket, is_iso: bool) {
185        if is_iso {
186            Self::count_status(&mut self.packet_status_counts, sample.packet_status);
187        }
188        let slot = &mut self.samples[sample.outcome.index()];
189        // On a transfer error preserve any observed payload in preference to
190        // a following descriptor with no bytes.
191        if sample.outcome != ExplicitFeedbackOutcome::TransferFailed
192            || sample.actual_bytes > 0
193            || slot.map_or(true, |previous| previous.actual_bytes == 0)
194        {
195            *slot = Some(sample);
196        }
197    }
198}
199
200/// An observation from the selected USB feedback path.
201#[derive(Debug, Clone, Copy, PartialEq)]
202#[non_exhaustive]
203pub enum FeedbackTraceEvent {
204    Submit {
205        slot: Option<usize>,
206        status: i32,
207    },
208    Completion {
209        slot: Option<usize>,
210        status: i32,
211        actual_bytes: usize,
212    },
213    ExplicitPacket {
214        index: usize,
215        sample: ExplicitFeedbackPacket,
216    },
217    ImplicitSource {
218        interface_number: u8,
219        alt_setting: u8,
220        endpoint: u8,
221        service_interval_us: u32,
222        max_packet_bytes: usize,
223        bytes_per_frame: usize,
224    },
225    ImplicitPacket {
226        index: usize,
227        status: i32,
228        requested_bytes: usize,
229        actual_bytes: usize,
230    },
231    Lock {
232        locked: bool,
233        stale: bool,
234    },
235    Timebase {
236        unit: &'static str,
237        inferred: bool,
238    },
239    /// Selected policy, retained before the first explicit report arrives.
240    ExplicitFeedbackPolicy {
241        smoothing: crate::FeedbackSmoothing,
242    },
243    /// The validated selected report and the actual fractional scheduling rate.
244    /// Raw feedback statistics remain independent of the configured filter.
245    ExplicitFeedbackRate {
246        smoothing: crate::FeedbackSmoothing,
247        reported_frames_per_out_service: f64,
248        applied_frames_per_out_service: f64,
249        applied_rate_hz: f64,
250    },
251    CompatibilityFallback {
252        tier: crate::CompatibilityFallbackTier,
253        reason: &'static str,
254    },
255    /// Session-local observation only; never a persisted device rule.
256    ClockReadbackSuggestion {
257        control_interface: u8,
258        clock_entity: u8,
259        strikes: u8,
260    },
261}
262
263/// A record in the trace, timed from stream creation using a monotonic clock.
264#[derive(Debug, Clone, Copy, PartialEq)]
265#[non_exhaustive]
266pub struct FeedbackTraceEntry {
267    pub elapsed_us: u64,
268    pub event: FeedbackTraceEvent,
269}
270
271/// A shareable support capture for the most recent stream of a DAC session.
272#[derive(Debug, Clone, PartialEq)]
273#[non_exhaustive]
274pub struct FeedbackTrace {
275    pub format: crate::StreamFormat,
276    pub explicit: Option<ExplicitFeedbackDiagnostics>,
277    pub entries: Vec<FeedbackTraceEntry>,
278    /// Observations overwritten at the retention limit or missed during an export.
279    pub dropped_entries: u64,
280    pub failure: Option<String>,
281}
282
283#[derive(Debug)]
284pub(crate) struct FeedbackRecorder {
285    started_at: Instant,
286    dropped: AtomicU64,
287    history: Mutex<History>,
288}
289
290#[derive(Debug)]
291struct History {
292    startup: Vec<FeedbackTraceEntry>,
293    recent: VecDeque<FeedbackTraceEntry>,
294    failure: Option<String>,
295}
296
297impl FeedbackRecorder {
298    pub(crate) fn new(started_at: Instant) -> Self {
299        Self {
300            started_at,
301            dropped: AtomicU64::new(0),
302            history: Mutex::new(History {
303                startup: Vec::with_capacity(STARTUP_ENTRIES),
304                recent: VecDeque::with_capacity(RECENT_ENTRIES),
305                failure: None,
306            }),
307        }
308    }
309
310    /// Preserve a bounded, deterministic startup snapshot before recent traffic
311    /// can overwrite it. A closed stream's exported trace retains these facts.
312    pub(crate) fn record_clock_readback_suggestions(
313        &self,
314        suggestions: impl IntoIterator<Item = ((u8, u8), u8)>,
315    ) {
316        let mut suggestions: Vec<_> = suggestions
317            .into_iter()
318            .filter(|(_, strikes)| *strikes >= 3)
319            .collect();
320        suggestions.sort_unstable_by_key(|(identity, _)| *identity);
321        for ((control_interface, clock_entity), strikes) in suggestions.into_iter().take(16) {
322            self.record(FeedbackTraceEvent::ClockReadbackSuggestion {
323                control_interface,
324                clock_entity,
325                strikes,
326            });
327        }
328    }
329
330    pub(crate) fn record(&self, event: FeedbackTraceEvent) {
331        self.record_at(Instant::now(), event);
332    }
333
334    pub(crate) fn record_at(&self, timestamp: Instant, event: FeedbackTraceEvent) {
335        let Some(mut history) = self.history.try_lock() else {
336            self.dropped.fetch_add(1, Ordering::Relaxed);
337            return;
338        };
339        let entry = FeedbackTraceEntry {
340            elapsed_us: timestamp
341                .saturating_duration_since(self.started_at)
342                .as_micros()
343                .min(u128::from(u64::MAX)) as u64,
344            event,
345        };
346        if history.startup.len() < STARTUP_ENTRIES {
347            history.startup.push(entry);
348        } else {
349            if history.recent.len() == RECENT_ENTRIES {
350                history.recent.pop_front();
351                self.dropped.fetch_add(1, Ordering::Relaxed);
352            }
353            history.recent.push_back(entry);
354        }
355    }
356
357    pub(crate) fn fail(&self, reason: &str) {
358        self.history.lock().failure = Some(reason.to_owned());
359    }
360
361    pub(crate) fn snapshot(
362        &self,
363        format: crate::StreamFormat,
364        explicit: Option<ExplicitFeedbackDiagnostics>,
365    ) -> FeedbackTrace {
366        let history = self.history.lock();
367        FeedbackTrace {
368            format,
369            explicit,
370            entries: history
371                .startup
372                .iter()
373                .chain(&history.recent)
374                .copied()
375                .collect(),
376            dropped_entries: self.dropped.load(Ordering::Relaxed),
377            failure: history.failure.clone(),
378        }
379    }
380}
381
382impl fmt::Display for ExplicitFeedbackDiagnostics {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        write!(
385            f,
386            concat!(
387                "feedback ep=0x{:02x} {} {} if={} alt={} bInterval={} refresh={} poll={}us ",
388                "request={}B x{} slots={} descriptor={}B timeout={}ms out=0x{:02x} {}us ",
389                "capacity={}B stride={}B nominal={}Hz clock_readback={:?} ",
390                "timebase={:?} inferred={} reused={} per_service_quirk={} ",
391                "submits={} submit_failures={} last_submit_error={:?} ",
392                "transfer_statuses={:?} packet_statuses={:?} accepted={} empty={} rejected={}"
393            ),
394            self.endpoint,
395            self.transfer_type,
396            self.link_speed,
397            self.interface_number,
398            self.alt_setting,
399            self.feedback_interval,
400            self.feedback_refresh,
401            self.feedback_service_interval_us,
402            self.requested_packet_bytes,
403            self.packets_per_transfer,
404            self.transfer_slots,
405            self.feedback_max_packet_bytes,
406            self.transfer_timeout_ms,
407            self.out_endpoint,
408            self.out_service_interval_us,
409            self.out_max_packet_bytes,
410            self.out_bytes_per_frame,
411            self.nominal_rate_hz,
412            self.post_alt_readback_hz,
413            self.timebase,
414            self.inferred_timebase,
415            self.reused_timebase,
416            self.per_service_interval_quirk,
417            self.successful_submissions,
418            self.submit_failures,
419            self.last_submit_error,
420            self.transfer_status_counts,
421            self.packet_status_counts,
422            self.accepted_reports,
423            self.empty_polls,
424            self.rejected_reports,
425        )?;
426        for packet in self.packet_samples() {
427            write!(
428                f,
429                " {}(transfer={} packet={:?} bytes={}/{} raw={:02x?} rate={:?} frames={:?})",
430                packet.outcome.code(),
431                packet.transfer_status,
432                packet.packet_status,
433                packet.actual_bytes,
434                packet.requested_bytes,
435                packet.raw_bytes(),
436                packet.decoded_rate_hz,
437                packet.frames_per_out_service,
438            )?;
439        }
440        Ok(())
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn preserves_startup_and_latest_observations_with_bounded_storage() {
450        let start = Instant::now();
451        let recorder = FeedbackRecorder::new(start);
452        let total = STARTUP_ENTRIES + RECENT_ENTRIES + 5;
453        for n in 0..total {
454            recorder.record_at(
455                start + std::time::Duration::from_micros(n as u64),
456                FeedbackTraceEvent::Submit {
457                    slot: None,
458                    status: 0,
459                },
460            );
461        }
462        recorder.fail("feedback deadline");
463        let history = recorder.history.lock();
464        assert_eq!(history.startup.len(), STARTUP_ENTRIES);
465        assert_eq!(history.startup[0].elapsed_us, 0);
466        assert_eq!(history.recent.len(), RECENT_ENTRIES);
467        assert_eq!(
468            history.recent.front().unwrap().elapsed_us,
469            (STARTUP_ENTRIES + 5) as u64
470        );
471        assert_eq!(
472            history.recent.back().unwrap().elapsed_us,
473            (total - 1) as u64
474        );
475        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
476        assert_eq!(history.failure.as_deref(), Some("feedback deadline"));
477    }
478}
479
480#[cfg(test)]
481mod compatibility_suggestion_trace_tests {
482    use super::*;
483    #[test]
484    fn three_strike_suggestions_stay_bounded_and_survive_recent_history_overwrite() {
485        let recorder = FeedbackRecorder::new(Instant::now());
486        let events = crate::events::EventHub::start();
487        crate::events::CompatibilityAdmissions::new(false, true, true, false, None).publish(
488            true,
489            &events,
490            Some(&recorder),
491        );
492        events.shutdown();
493        let suggestions = (0..32u8).map(|interface| ((interface, 7), 3));
494        recorder.record_clock_readback_suggestions(suggestions.chain([((99, 1), 2)]));
495        for _ in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 8) {
496            recorder.record(FeedbackTraceEvent::Lock {
497                locked: true,
498                stale: false,
499            });
500        }
501        let history = recorder.history.lock();
502        let suggestions: Vec<_> = history
503            .startup
504            .iter()
505            .filter_map(|entry| match entry.event {
506                FeedbackTraceEvent::ClockReadbackSuggestion {
507                    control_interface,
508                    clock_entity,
509                    strikes,
510                } => Some((control_interface, clock_entity, strikes)),
511                _ => None,
512            })
513            .collect();
514        assert_eq!(
515            suggestions,
516            (0..16u8)
517                .map(|interface| (interface, 7, 3))
518                .collect::<Vec<_>>()
519        );
520        assert!(history.startup.iter().any(|entry|matches!(entry.event,
521            FeedbackTraceEvent::CompatibilityFallback {tier:crate::CompatibilityFallbackTier::UnverifiedClock,reason} if !reason.is_empty())));
522    }
523}