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;
11const UNDERRUN_STARTUP_ENTRIES: usize = 16;
12const UNDERRUN_RECENT_ENTRIES: usize = 64;
13
14/// What happened to a packet while it was examined for explicit feedback.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum ExplicitFeedbackOutcome {
18    Valid,
19    Empty,
20    TransferFailed,
21    PacketFailed,
22    InvalidLength,
23    InvalidEncoding,
24    RateOutOfRange,
25    PacketCapacityExceeded,
26    TimebaseCandidate,
27}
28
29impl ExplicitFeedbackOutcome {
30    pub fn code(self) -> &'static str {
31        match self {
32            Self::Valid => "valid",
33            Self::Empty => "empty",
34            Self::TransferFailed => "transfer_failed",
35            Self::PacketFailed => "packet_failed",
36            Self::InvalidLength => "invalid_length",
37            Self::InvalidEncoding => "invalid_encoding",
38            Self::RateOutOfRange => "rate_out_of_range",
39            Self::PacketCapacityExceeded => "packet_capacity_exceeded",
40            Self::TimebaseCandidate => "timebase_candidate",
41        }
42    }
43
44    fn index(self) -> usize {
45        match self {
46            Self::Valid => 0,
47            Self::Empty => 1,
48            Self::TransferFailed => 2,
49            Self::PacketFailed => 3,
50            Self::InvalidLength => 4,
51            Self::InvalidEncoding => 5,
52            Self::RateOutOfRange => 6,
53            Self::PacketCapacityExceeded => 7,
54            Self::TimebaseCandidate => 8,
55        }
56    }
57}
58
59/// The most recent packet observed for one feedback outcome.
60#[derive(Debug, Clone, Copy, PartialEq)]
61#[non_exhaustive]
62pub struct ExplicitFeedbackPacket {
63    pub outcome: ExplicitFeedbackOutcome,
64    pub transfer_status: i32,
65    /// The libusb packet status, or `None` when no packet status was reported.
66    pub packet_status: Option<i32>,
67    pub requested_bytes: usize,
68    pub actual_bytes: usize,
69    pub frames_per_out_service: Option<f64>,
70    pub decoded_rate_hz: Option<f64>,
71    bytes: [u8; 8],
72    byte_count: usize,
73}
74
75impl ExplicitFeedbackPacket {
76    #[allow(clippy::too_many_arguments)]
77    pub(crate) fn new(
78        outcome: ExplicitFeedbackOutcome,
79        transfer_status: i32,
80        packet_status: Option<i32>,
81        requested_bytes: usize,
82        actual_bytes: usize,
83        raw_bytes: &[u8],
84        decoded: Option<(f64, f64)>,
85    ) -> Self {
86        let mut bytes = [0; 8];
87        let byte_count = raw_bytes.len().min(bytes.len());
88        bytes[..byte_count].copy_from_slice(&raw_bytes[..byte_count]);
89        Self {
90            outcome,
91            transfer_status,
92            packet_status,
93            requested_bytes,
94            actual_bytes,
95            frames_per_out_service: decoded.map(|(frames, _)| frames),
96            decoded_rate_hz: decoded.map(|(_, rate)| rate),
97            bytes,
98            byte_count,
99        }
100    }
101
102    /// Up to eight bytes from the feedback IN endpoint. No audio OUT payload.
103    pub fn raw_bytes(&self) -> &[u8] {
104        &self.bytes[..self.byte_count]
105    }
106}
107
108/// Feedback endpoint geometry and observations for one stream. Status counts
109/// are indexed by libusb transfer status (0 completed, 1 error, 2 timed out,
110/// 3 cancelled, 4 stall, 5 no device, 6 overflow). Index 7 is unknown or
111/// unreported. An interrupt transfer has no separate packet status.
112#[derive(Debug, Default, Clone, Copy, PartialEq)]
113#[non_exhaustive]
114pub struct ExplicitFeedbackDiagnostics {
115    pub endpoint: u8,
116    pub transfer_type: &'static str,
117    pub link_speed: &'static str,
118    pub interface_number: u8,
119    pub alt_setting: u8,
120    pub out_endpoint: u8,
121    pub nominal_rate_hz: u32,
122    pub out_service_interval_us: u32,
123    pub out_max_packet_bytes: usize,
124    pub out_bytes_per_frame: usize,
125    pub feedback_interval: u8,
126    pub feedback_refresh: u8,
127    pub feedback_service_interval_us: u32,
128    pub feedback_max_packet_bytes: usize,
129    pub requested_packet_bytes: usize,
130    pub transfer_slots: usize,
131    pub packets_per_transfer: usize,
132    pub transfer_timeout_ms: u32,
133    pub per_service_interval_quirk: bool,
134    pub post_alt_readback_hz: Option<u32>,
135    pub timebase: Option<&'static str>,
136    pub inferred_timebase: bool,
137    /// The current stream validated units already learned on this DAC session.
138    pub reused_timebase: bool,
139    pub successful_submissions: u64,
140    pub submit_failures: u64,
141    /// libusb submission error code, separate from completion status.
142    pub last_submit_error: Option<i32>,
143    pub transfer_status_counts: [u64; 8],
144    pub packet_status_counts: [u64; 8],
145    pub accepted_reports: u64,
146    /// Accepted unsmoothed observations, in frames per OUT service interval.
147    pub rate_samples: u64,
148    pub rate_min_frames: f64,
149    pub rate_max_frames: f64,
150    pub rate_mean_frames: f64,
151    /// Population variance before the configured timing policy. No audible
152    /// smoothing tradeoff is inferred.
153    pub rate_variance_frames: f64,
154    pub empty_polls: u64,
155    pub rejected_reports: u64,
156    pub(crate) samples: [Option<ExplicitFeedbackPacket>; 9],
157}
158
159impl ExplicitFeedbackDiagnostics {
160    /// One latest observation per outcome, including bytes from rejected reports.
161    pub fn packet_samples(&self) -> impl Iterator<Item = &ExplicitFeedbackPacket> {
162        self.samples.iter().flatten()
163    }
164
165    pub(crate) fn record_submit(&mut self, result: i32) {
166        if result == 0 {
167            self.successful_submissions = self.successful_submissions.saturating_add(1);
168        } else {
169            self.submit_failures = self.submit_failures.saturating_add(1);
170            self.last_submit_error = Some(result);
171        }
172    }
173
174    fn count_status(counts: &mut [u64; 8], status: Option<i32>) {
175        let index = match status {
176            Some(code @ 0..=6) => code as usize,
177            _ => 7,
178        };
179        counts[index] = counts[index].saturating_add(1);
180    }
181
182    pub(crate) fn record_transfer(&mut self, status: i32) {
183        Self::count_status(&mut self.transfer_status_counts, Some(status));
184    }
185
186    pub(crate) fn record_packet(&mut self, sample: ExplicitFeedbackPacket, is_iso: bool) {
187        if is_iso {
188            Self::count_status(&mut self.packet_status_counts, sample.packet_status);
189        }
190        let slot = &mut self.samples[sample.outcome.index()];
191        // On a transfer error preserve any observed payload in preference to
192        // a following descriptor with no bytes.
193        if sample.outcome != ExplicitFeedbackOutcome::TransferFailed
194            || sample.actual_bytes > 0
195            || slot.map_or(true, |previous| previous.actual_bytes == 0)
196        {
197            *slot = Some(sample);
198        }
199    }
200}
201
202/// An observation from the selected USB feedback path.
203#[derive(Debug, Clone, Copy, PartialEq)]
204#[non_exhaustive]
205pub enum FeedbackTraceEvent {
206    Submit {
207        slot: Option<usize>,
208        status: i32,
209    },
210    Completion {
211        slot: Option<usize>,
212        status: i32,
213        actual_bytes: usize,
214    },
215    ExplicitPacket {
216        index: usize,
217        sample: ExplicitFeedbackPacket,
218    },
219    ImplicitSource {
220        interface_number: u8,
221        alt_setting: u8,
222        endpoint: u8,
223        service_interval_us: u32,
224        max_packet_bytes: usize,
225        bytes_per_frame: usize,
226    },
227    ImplicitPacket {
228        index: usize,
229        status: i32,
230        requested_bytes: usize,
231        actual_bytes: usize,
232    },
233    Lock {
234        locked: bool,
235        stale: bool,
236    },
237    Timebase {
238        unit: &'static str,
239        inferred: bool,
240    },
241    /// Selected policy, retained before the first explicit report arrives.
242    ExplicitFeedbackPolicy {
243        smoothing: crate::FeedbackSmoothing,
244    },
245    /// The validated selected report and the actual fractional scheduling rate.
246    /// Raw feedback statistics remain independent of the configured filter.
247    ExplicitFeedbackRate {
248        smoothing: crate::FeedbackSmoothing,
249        reported_frames_per_out_service: f64,
250        applied_frames_per_out_service: f64,
251        applied_rate_hz: f64,
252    },
253    CompatibilityFallback {
254        tier: crate::CompatibilityFallbackTier,
255        reason: &'static str,
256    },
257    /// Session-local observation only; never a persisted device rule.
258    ClockReadbackSuggestion {
259        control_interface: u8,
260        clock_entity: u8,
261        strikes: u8,
262    },
263}
264
265/// A record in the trace, timed from stream creation using a monotonic clock.
266#[derive(Debug, Clone, Copy, PartialEq)]
267#[non_exhaustive]
268pub struct FeedbackTraceEntry {
269    pub elapsed_us: u64,
270    pub event: FeedbackTraceEvent,
271}
272
273/// A worker-observed transition into or out of an underrun episode.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275#[non_exhaustive]
276pub enum UnderrunEdgeKind {
277    /// A prepared transfer first required underrun padding.
278    Started,
279    /// A later prepared transfer no longer required underrun padding.
280    Recovered,
281}
282impl UnderrunEdgeKind {
283    pub fn code(self) -> &'static str {
284        match self {
285            Self::Started => "started",
286            Self::Recovered => "recovered",
287        }
288    }
289}
290
291/// Relaxed atomic snapshots taken at the observed worker edge, after preparing the transfer.
292/// `elapsed_us` shares the exact origin of the enclosing feedback trace. Sample counts
293/// are interleaved ring samples; frame counters use the stream's native counter rate.
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
295pub struct UnderrunEdge {
296    pub elapsed_us: u64,
297    pub kind: UnderrunEdgeKind,
298    pub underrun_transfers: u64,
299    pub buffered_samples: usize,
300    pub capacity_samples: usize,
301    pub channels: usize,
302    pub producer_frames: u64,
303    pub played_frames: u64,
304    pub inflight_frames: u64,
305    pub flush_epoch: u64,
306    pub transfer_queue_depth: usize,
307}
308
309/// A shareable support capture for the most recent stream of a DAC session.
310#[derive(Debug, Clone, PartialEq)]
311#[non_exhaustive]
312pub struct FeedbackTrace {
313    /// In-process monotonic origin shared by feedback entries and underrun edges.
314    /// This instant has no portable UTC representation; compute offsets in-process.
315    pub started_at: Instant,
316    pub format: crate::StreamFormat,
317    pub explicit: Option<ExplicitFeedbackDiagnostics>,
318    pub entries: Vec<FeedbackTraceEntry>,
319    /// Observations overwritten at the retention limit or missed during an export.
320    pub dropped_entries: u64,
321    /// First and recent underrun edges, independently retained from feedback events.
322    pub underrun_edges: Vec<UnderrunEdge>,
323    /// Underrun edges overwritten or missed due to a concurrent snapshot.
324    pub underrun_dropped: u64,
325    pub failure: Option<String>,
326}
327
328#[derive(Debug)]
329pub(crate) struct FeedbackRecorder {
330    started_at: Instant,
331    dropped: AtomicU64,
332    history: Mutex<History>,
333    underrun_dropped: AtomicU64,
334    underruns: Mutex<UnderrunHistory>,
335}
336
337#[derive(Debug)]
338struct History {
339    startup: Vec<FeedbackTraceEntry>,
340    recent: VecDeque<FeedbackTraceEntry>,
341    failure: Option<String>,
342}
343
344#[derive(Debug)]
345struct UnderrunHistory {
346    startup: Vec<UnderrunEdge>,
347    recent: VecDeque<UnderrunEdge>,
348}
349
350impl FeedbackRecorder {
351    pub(crate) fn new(started_at: Instant) -> Self {
352        Self {
353            started_at,
354            dropped: AtomicU64::new(0),
355            underrun_dropped: AtomicU64::new(0),
356            underruns: Mutex::new(UnderrunHistory {
357                startup: Vec::with_capacity(UNDERRUN_STARTUP_ENTRIES),
358                recent: VecDeque::with_capacity(UNDERRUN_RECENT_ENTRIES),
359            }),
360            history: Mutex::new(History {
361                startup: Vec::with_capacity(STARTUP_ENTRIES),
362                recent: VecDeque::with_capacity(RECENT_ENTRIES),
363                failure: None,
364            }),
365        }
366    }
367
368    /// Preserve a bounded, deterministic startup snapshot before recent traffic
369    /// can overwrite it. A closed stream's exported trace retains these facts.
370    pub(crate) fn record_clock_readback_suggestions(
371        &self,
372        suggestions: impl IntoIterator<Item = ((u8, u8), u8)>,
373    ) {
374        let mut suggestions: Vec<_> = suggestions
375            .into_iter()
376            .filter(|(_, strikes)| *strikes >= 3)
377            .collect();
378        suggestions.sort_unstable_by_key(|(identity, _)| *identity);
379        for ((control_interface, clock_entity), strikes) in suggestions.into_iter().take(16) {
380            self.record(FeedbackTraceEvent::ClockReadbackSuggestion {
381                control_interface,
382                clock_entity,
383                strikes,
384            });
385        }
386    }
387
388    pub(crate) fn record(&self, event: FeedbackTraceEvent) {
389        self.record_at(Instant::now(), event);
390    }
391
392    pub(crate) fn record_at(&self, timestamp: Instant, event: FeedbackTraceEvent) {
393        let Some(mut history) = self.history.try_lock() else {
394            self.dropped.fetch_add(1, Ordering::Relaxed);
395            return;
396        };
397        let entry = FeedbackTraceEntry {
398            elapsed_us: timestamp
399                .saturating_duration_since(self.started_at)
400                .as_micros()
401                .min(u128::from(u64::MAX)) as u64,
402            event,
403        };
404        if history.startup.len() < STARTUP_ENTRIES {
405            history.startup.push(entry);
406        } else {
407            if history.recent.len() == RECENT_ENTRIES {
408                history.recent.pop_front();
409                self.dropped.fetch_add(1, Ordering::Relaxed);
410            }
411            history.recent.push_back(entry);
412        }
413    }
414
415    /// Try to retain an edge without blocking or allocating on the USB worker.
416    pub(crate) fn record_underrun_at(&self, timestamp: Instant, mut edge: UnderrunEdge) {
417        edge.elapsed_us = timestamp
418            .saturating_duration_since(self.started_at)
419            .as_micros()
420            .min(u128::from(u64::MAX)) as u64;
421        let Some(mut history) = self.underruns.try_lock() else {
422            self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
423            return;
424        };
425        if history.startup.len() < UNDERRUN_STARTUP_ENTRIES {
426            history.startup.push(edge);
427        } else {
428            if history.recent.len() == UNDERRUN_RECENT_ENTRIES {
429                history.recent.pop_front();
430                self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
431            }
432            history.recent.push_back(edge);
433        }
434    }
435
436    pub(crate) fn underrun_snapshot(&self) -> (Vec<UnderrunEdge>, u64) {
437        let history = self.underruns.lock();
438        (
439            history
440                .startup
441                .iter()
442                .chain(&history.recent)
443                .copied()
444                .collect(),
445            self.underrun_dropped.load(Ordering::Relaxed),
446        )
447    }
448
449    pub(crate) fn fail(&self, reason: &str) {
450        self.history.lock().failure = Some(reason.to_owned());
451    }
452
453    pub(crate) fn snapshot(
454        &self,
455        format: crate::StreamFormat,
456        explicit: Option<ExplicitFeedbackDiagnostics>,
457    ) -> FeedbackTrace {
458        let history = self.history.lock();
459        let (underrun_edges, underrun_dropped) = self.underrun_snapshot();
460        FeedbackTrace {
461            started_at: self.started_at,
462            format,
463            explicit,
464            entries: history
465                .startup
466                .iter()
467                .chain(&history.recent)
468                .copied()
469                .collect(),
470            dropped_entries: self.dropped.load(Ordering::Relaxed),
471            underrun_edges,
472            underrun_dropped,
473            failure: history.failure.clone(),
474        }
475    }
476}
477
478impl fmt::Display for ExplicitFeedbackDiagnostics {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        write!(
481            f,
482            concat!(
483                "feedback ep=0x{:02x} {} {} if={} alt={} bInterval={} refresh={} poll={}us ",
484                "request={}B x{} slots={} descriptor={}B timeout={}ms out=0x{:02x} {}us ",
485                "capacity={}B stride={}B nominal={}Hz clock_readback={:?} ",
486                "timebase={:?} inferred={} reused={} per_service_quirk={} ",
487                "submits={} submit_failures={} last_submit_error={:?} ",
488                "transfer_statuses={:?} packet_statuses={:?} accepted={} empty={} rejected={}"
489            ),
490            self.endpoint,
491            self.transfer_type,
492            self.link_speed,
493            self.interface_number,
494            self.alt_setting,
495            self.feedback_interval,
496            self.feedback_refresh,
497            self.feedback_service_interval_us,
498            self.requested_packet_bytes,
499            self.packets_per_transfer,
500            self.transfer_slots,
501            self.feedback_max_packet_bytes,
502            self.transfer_timeout_ms,
503            self.out_endpoint,
504            self.out_service_interval_us,
505            self.out_max_packet_bytes,
506            self.out_bytes_per_frame,
507            self.nominal_rate_hz,
508            self.post_alt_readback_hz,
509            self.timebase,
510            self.inferred_timebase,
511            self.reused_timebase,
512            self.per_service_interval_quirk,
513            self.successful_submissions,
514            self.submit_failures,
515            self.last_submit_error,
516            self.transfer_status_counts,
517            self.packet_status_counts,
518            self.accepted_reports,
519            self.empty_polls,
520            self.rejected_reports,
521        )?;
522        for packet in self.packet_samples() {
523            write!(
524                f,
525                " {}(transfer={} packet={:?} bytes={}/{} raw={:02x?} rate={:?} frames={:?})",
526                packet.outcome.code(),
527                packet.transfer_status,
528                packet.packet_status,
529                packet.actual_bytes,
530                packet.requested_bytes,
531                packet.raw_bytes(),
532                packet.decoded_rate_hz,
533                packet.frames_per_out_service,
534            )?;
535        }
536        Ok(())
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    fn edge() -> UnderrunEdge {
545        UnderrunEdge {
546            elapsed_us: 0,
547            kind: UnderrunEdgeKind::Started,
548            underrun_transfers: 1,
549            buffered_samples: 4,
550            capacity_samples: 100,
551            channels: 2,
552            producer_frames: 8,
553            played_frames: 4,
554            inflight_frames: 2,
555            flush_epoch: 0,
556            transfer_queue_depth: 3,
557        }
558    }
559    #[test]
560    fn underrun_history_has_independent_bounded_first_and_recent_edges() {
561        let start = Instant::now();
562        let recorder = FeedbackRecorder::new(start);
563        for n in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 5) {
564            recorder.record_at(
565                start + std::time::Duration::from_micros(n as u64),
566                FeedbackTraceEvent::Submit {
567                    slot: None,
568                    status: 0,
569                },
570            );
571        }
572        let count = UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES + 3;
573        for n in 0..count {
574            recorder.record_underrun_at(start + std::time::Duration::from_micros(n as u64), edge());
575        }
576        let (events, dropped) = recorder.underrun_snapshot();
577        assert_eq!(
578            events.len(),
579            UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES
580        );
581        assert_eq!(events[0].elapsed_us, 0);
582        assert_eq!(
583            events[UNDERRUN_STARTUP_ENTRIES].elapsed_us,
584            (UNDERRUN_STARTUP_ENTRIES + 3) as u64
585        );
586        assert_eq!(events.last().unwrap().elapsed_us, (count - 1) as u64);
587        assert_eq!(dropped, 3);
588        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
589        let held = recorder.underruns.lock();
590        recorder.record_underrun_at(start, edge());
591        drop(held);
592        assert_eq!(recorder.underrun_snapshot().1, 4);
593    }
594
595    #[test]
596    fn preserves_startup_and_latest_observations_with_bounded_storage() {
597        let start = Instant::now();
598        let recorder = FeedbackRecorder::new(start);
599        let total = STARTUP_ENTRIES + RECENT_ENTRIES + 5;
600        for n in 0..total {
601            recorder.record_at(
602                start + std::time::Duration::from_micros(n as u64),
603                FeedbackTraceEvent::Submit {
604                    slot: None,
605                    status: 0,
606                },
607            );
608        }
609        recorder.fail("feedback deadline");
610        let history = recorder.history.lock();
611        assert_eq!(history.startup.len(), STARTUP_ENTRIES);
612        assert_eq!(history.startup[0].elapsed_us, 0);
613        assert_eq!(history.recent.len(), RECENT_ENTRIES);
614        assert_eq!(
615            history.recent.front().unwrap().elapsed_us,
616            (STARTUP_ENTRIES + 5) as u64
617        );
618        assert_eq!(
619            history.recent.back().unwrap().elapsed_us,
620            (total - 1) as u64
621        );
622        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
623        assert_eq!(history.failure.as_deref(), Some("feedback deadline"));
624    }
625}
626
627#[cfg(test)]
628mod compatibility_suggestion_trace_tests {
629    use super::*;
630    #[test]
631    fn three_strike_suggestions_stay_bounded_and_survive_recent_history_overwrite() {
632        let recorder = FeedbackRecorder::new(Instant::now());
633        let events = crate::events::EventHub::start();
634        crate::events::CompatibilityAdmissions::new(false, true, true, false, None).publish(
635            true,
636            &events,
637            Some(&recorder),
638        );
639        events.shutdown();
640        let suggestions = (0..32u8).map(|interface| ((interface, 7), 3));
641        recorder.record_clock_readback_suggestions(suggestions.chain([((99, 1), 2)]));
642        for _ in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 8) {
643            recorder.record(FeedbackTraceEvent::Lock {
644                locked: true,
645                stale: false,
646            });
647        }
648        let history = recorder.history.lock();
649        let suggestions: Vec<_> = history
650            .startup
651            .iter()
652            .filter_map(|entry| match entry.event {
653                FeedbackTraceEvent::ClockReadbackSuggestion {
654                    control_interface,
655                    clock_entity,
656                    strikes,
657                } => Some((control_interface, clock_entity, strikes)),
658                _ => None,
659            })
660            .collect();
661        assert_eq!(
662            suggestions,
663            (0..16u8)
664                .map(|interface| (interface, 7, 3))
665                .collect::<Vec<_>>()
666        );
667        assert!(history.startup.iter().any(|entry|matches!(entry.event,
668            FeedbackTraceEvent::CompatibilityFallback {tier:crate::CompatibilityFallbackTier::UnverifiedClock,reason} if !reason.is_empty())));
669    }
670}