1use 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#[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#[derive(Debug, Clone, Copy, PartialEq)]
61#[non_exhaustive]
62pub struct ExplicitFeedbackPacket {
63 pub outcome: ExplicitFeedbackOutcome,
64 pub transfer_status: i32,
65 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 pub fn raw_bytes(&self) -> &[u8] {
104 &self.bytes[..self.byte_count]
105 }
106}
107
108#[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 pub reused_timebase: bool,
139 pub successful_submissions: u64,
140 pub submit_failures: u64,
141 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 pub rate_samples: u64,
148 pub rate_min_frames: f64,
149 pub rate_max_frames: f64,
150 pub rate_mean_frames: f64,
151 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 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 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#[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 ExplicitFeedbackPolicy {
243 smoothing: crate::FeedbackSmoothing,
244 },
245 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 ClockReadbackSuggestion {
259 control_interface: u8,
260 clock_entity: u8,
261 strikes: u8,
262 },
263}
264
265#[derive(Debug, Clone, Copy, PartialEq)]
267#[non_exhaustive]
268pub struct FeedbackTraceEntry {
269 pub elapsed_us: u64,
270 pub event: FeedbackTraceEvent,
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275#[non_exhaustive]
276pub enum UnderrunEdgeKind {
277 Started,
279 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#[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#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
312#[non_exhaustive]
313pub struct IsoSubmitIncident {
314 pub elapsed_us: u64,
315 pub interface_number: u8,
316 pub alt_setting: u8,
317 pub endpoint_address: u8,
318 pub slot: usize,
319 pub generation: u64,
320 pub attempt: u8,
321 pub libusb_status: Option<i32>,
322 pub native_error: Option<String>,
324 pub outcome: &'static str,
325 pub packets: usize,
326 pub service_interval_us: u32,
327 pub queued_slots: usize,
328 pub adaptive_queue_us: u64,
329 pub max_event_pump_elapsed_us: u64,
330 pub max_worker_loop_gap_us: u64,
331 pub lost_frames: u64,
332}
333
334const ISO_SUBMIT_INCIDENTS: usize = 32;
335
336#[derive(Debug, Clone, PartialEq)]
338#[non_exhaustive]
339pub struct FeedbackTrace {
340 pub started_at: Instant,
343 pub format: crate::StreamFormat,
344 pub explicit: Option<ExplicitFeedbackDiagnostics>,
345 pub entries: Vec<FeedbackTraceEntry>,
346 pub dropped_entries: u64,
348 pub underrun_edges: Vec<UnderrunEdge>,
350 pub underrun_dropped: u64,
352 pub iso_submit_incidents: Vec<IsoSubmitIncident>,
353 pub iso_submit_dropped: u64,
354 pub failure: Option<String>,
355}
356
357#[derive(Debug)]
358pub(crate) struct FeedbackRecorder {
359 started_at: Instant,
360 dropped: AtomicU64,
361 history: Mutex<History>,
362 underrun_dropped: AtomicU64,
363 underruns: Mutex<UnderrunHistory>,
364 iso_submit_dropped: AtomicU64,
365 iso_submits: Mutex<VecDeque<IsoSubmitIncident>>,
366}
367
368#[derive(Debug)]
369struct History {
370 startup: Vec<FeedbackTraceEntry>,
371 recent: VecDeque<FeedbackTraceEntry>,
372 failure: Option<String>,
373}
374
375#[derive(Debug)]
376struct UnderrunHistory {
377 startup: Vec<UnderrunEdge>,
378 recent: VecDeque<UnderrunEdge>,
379}
380
381impl FeedbackRecorder {
382 pub(crate) fn new(started_at: Instant) -> Self {
383 Self {
384 started_at,
385 dropped: AtomicU64::new(0),
386 underrun_dropped: AtomicU64::new(0),
387 iso_submit_dropped: AtomicU64::new(0),
388 iso_submits: Mutex::new(VecDeque::with_capacity(ISO_SUBMIT_INCIDENTS)),
389 underruns: Mutex::new(UnderrunHistory {
390 startup: Vec::with_capacity(UNDERRUN_STARTUP_ENTRIES),
391 recent: VecDeque::with_capacity(UNDERRUN_RECENT_ENTRIES),
392 }),
393 history: Mutex::new(History {
394 startup: Vec::with_capacity(STARTUP_ENTRIES),
395 recent: VecDeque::with_capacity(RECENT_ENTRIES),
396 failure: None,
397 }),
398 }
399 }
400
401 pub(crate) fn record_clock_readback_suggestions(
404 &self,
405 suggestions: impl IntoIterator<Item = ((u8, u8), u8)>,
406 ) {
407 let mut suggestions: Vec<_> = suggestions
408 .into_iter()
409 .filter(|(_, strikes)| *strikes >= 3)
410 .collect();
411 suggestions.sort_unstable_by_key(|(identity, _)| *identity);
412 for ((control_interface, clock_entity), strikes) in suggestions.into_iter().take(16) {
413 self.record(FeedbackTraceEvent::ClockReadbackSuggestion {
414 control_interface,
415 clock_entity,
416 strikes,
417 });
418 }
419 }
420
421 pub(crate) fn record(&self, event: FeedbackTraceEvent) {
422 self.record_at(Instant::now(), event);
423 }
424
425 pub(crate) fn record_at(&self, timestamp: Instant, event: FeedbackTraceEvent) {
426 let Some(mut history) = self.history.try_lock() else {
427 self.dropped.fetch_add(1, Ordering::Relaxed);
428 return;
429 };
430 let entry = FeedbackTraceEntry {
431 elapsed_us: timestamp
432 .saturating_duration_since(self.started_at)
433 .as_micros()
434 .min(u128::from(u64::MAX)) as u64,
435 event,
436 };
437 if history.startup.len() < STARTUP_ENTRIES {
438 history.startup.push(entry);
439 } else {
440 if history.recent.len() == RECENT_ENTRIES {
441 history.recent.pop_front();
442 self.dropped.fetch_add(1, Ordering::Relaxed);
443 }
444 history.recent.push_back(entry);
445 }
446 }
447
448 pub(crate) fn record_underrun_at(&self, timestamp: Instant, mut edge: UnderrunEdge) {
450 edge.elapsed_us = timestamp
451 .saturating_duration_since(self.started_at)
452 .as_micros()
453 .min(u128::from(u64::MAX)) as u64;
454 let Some(mut history) = self.underruns.try_lock() else {
455 self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
456 return;
457 };
458 if history.startup.len() < UNDERRUN_STARTUP_ENTRIES {
459 history.startup.push(edge);
460 } else {
461 if history.recent.len() == UNDERRUN_RECENT_ENTRIES {
462 history.recent.pop_front();
463 self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
464 }
465 history.recent.push_back(edge);
466 }
467 }
468
469 pub(crate) fn underrun_snapshot(&self) -> (Vec<UnderrunEdge>, u64) {
470 let history = self.underruns.lock();
471 (
472 history
473 .startup
474 .iter()
475 .chain(&history.recent)
476 .copied()
477 .collect(),
478 self.underrun_dropped.load(Ordering::Relaxed),
479 )
480 }
481
482 pub(crate) fn record_iso_submit(&self, mut incident: IsoSubmitIncident) {
483 incident.elapsed_us = Instant::now()
484 .saturating_duration_since(self.started_at)
485 .as_micros()
486 .min(u128::from(u64::MAX)) as u64;
487 let Some(mut entries) = self.iso_submits.try_lock() else {
488 self.iso_submit_dropped.fetch_add(1, Ordering::Relaxed);
489 return;
490 };
491 if entries.len() == ISO_SUBMIT_INCIDENTS {
492 entries.pop_front();
493 self.iso_submit_dropped.fetch_add(1, Ordering::Relaxed);
494 }
495 entries.push_back(incident);
496 }
497
498 pub(crate) fn fail(&self, reason: &str) {
499 self.history.lock().failure = Some(reason.to_owned());
500 }
501
502 pub(crate) fn snapshot(
503 &self,
504 format: crate::StreamFormat,
505 explicit: Option<ExplicitFeedbackDiagnostics>,
506 ) -> FeedbackTrace {
507 let history = self.history.lock();
508 let (underrun_edges, underrun_dropped) = self.underrun_snapshot();
509 FeedbackTrace {
510 started_at: self.started_at,
511 format,
512 explicit,
513 entries: history
514 .startup
515 .iter()
516 .chain(&history.recent)
517 .copied()
518 .collect(),
519 dropped_entries: self.dropped.load(Ordering::Relaxed),
520 underrun_edges,
521 underrun_dropped,
522 iso_submit_incidents: self.iso_submits.lock().iter().cloned().collect(),
523 iso_submit_dropped: self.iso_submit_dropped.load(Ordering::Relaxed),
524 failure: history.failure.clone(),
525 }
526 }
527}
528
529impl fmt::Display for ExplicitFeedbackDiagnostics {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 write!(
532 f,
533 concat!(
534 "feedback ep=0x{:02x} {} {} if={} alt={} bInterval={} refresh={} poll={}us ",
535 "request={}B x{} slots={} descriptor={}B timeout={}ms out=0x{:02x} {}us ",
536 "capacity={}B stride={}B nominal={}Hz clock_readback={:?} ",
537 "timebase={:?} inferred={} reused={} per_service_quirk={} ",
538 "submits={} submit_failures={} last_submit_error={:?} ",
539 "transfer_statuses={:?} packet_statuses={:?} accepted={} empty={} rejected={}"
540 ),
541 self.endpoint,
542 self.transfer_type,
543 self.link_speed,
544 self.interface_number,
545 self.alt_setting,
546 self.feedback_interval,
547 self.feedback_refresh,
548 self.feedback_service_interval_us,
549 self.requested_packet_bytes,
550 self.packets_per_transfer,
551 self.transfer_slots,
552 self.feedback_max_packet_bytes,
553 self.transfer_timeout_ms,
554 self.out_endpoint,
555 self.out_service_interval_us,
556 self.out_max_packet_bytes,
557 self.out_bytes_per_frame,
558 self.nominal_rate_hz,
559 self.post_alt_readback_hz,
560 self.timebase,
561 self.inferred_timebase,
562 self.reused_timebase,
563 self.per_service_interval_quirk,
564 self.successful_submissions,
565 self.submit_failures,
566 self.last_submit_error,
567 self.transfer_status_counts,
568 self.packet_status_counts,
569 self.accepted_reports,
570 self.empty_polls,
571 self.rejected_reports,
572 )?;
573 for packet in self.packet_samples() {
574 write!(
575 f,
576 " {}(transfer={} packet={:?} bytes={}/{} raw={:02x?} rate={:?} frames={:?})",
577 packet.outcome.code(),
578 packet.transfer_status,
579 packet.packet_status,
580 packet.actual_bytes,
581 packet.requested_bytes,
582 packet.raw_bytes(),
583 packet.decoded_rate_hz,
584 packet.frames_per_out_service,
585 )?;
586 }
587 Ok(())
588 }
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594
595 fn edge() -> UnderrunEdge {
596 UnderrunEdge {
597 elapsed_us: 0,
598 kind: UnderrunEdgeKind::Started,
599 underrun_transfers: 1,
600 buffered_samples: 4,
601 capacity_samples: 100,
602 channels: 2,
603 producer_frames: 8,
604 played_frames: 4,
605 inflight_frames: 2,
606 flush_epoch: 0,
607 transfer_queue_depth: 3,
608 }
609 }
610 #[test]
611 fn underrun_history_has_independent_bounded_first_and_recent_edges() {
612 let start = Instant::now();
613 let recorder = FeedbackRecorder::new(start);
614 for n in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 5) {
615 recorder.record_at(
616 start + std::time::Duration::from_micros(n as u64),
617 FeedbackTraceEvent::Submit {
618 slot: None,
619 status: 0,
620 },
621 );
622 }
623 let count = UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES + 3;
624 for n in 0..count {
625 recorder.record_underrun_at(start + std::time::Duration::from_micros(n as u64), edge());
626 }
627 let (events, dropped) = recorder.underrun_snapshot();
628 assert_eq!(
629 events.len(),
630 UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES
631 );
632 assert_eq!(events[0].elapsed_us, 0);
633 assert_eq!(
634 events[UNDERRUN_STARTUP_ENTRIES].elapsed_us,
635 (UNDERRUN_STARTUP_ENTRIES + 3) as u64
636 );
637 assert_eq!(events.last().unwrap().elapsed_us, (count - 1) as u64);
638 assert_eq!(dropped, 3);
639 assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
640 let held = recorder.underruns.lock();
641 recorder.record_underrun_at(start, edge());
642 drop(held);
643 assert_eq!(recorder.underrun_snapshot().1, 4);
644 }
645
646 #[test]
647 fn preserves_startup_and_latest_observations_with_bounded_storage() {
648 let start = Instant::now();
649 let recorder = FeedbackRecorder::new(start);
650 let total = STARTUP_ENTRIES + RECENT_ENTRIES + 5;
651 for n in 0..total {
652 recorder.record_at(
653 start + std::time::Duration::from_micros(n as u64),
654 FeedbackTraceEvent::Submit {
655 slot: None,
656 status: 0,
657 },
658 );
659 }
660 recorder.fail("feedback deadline");
661 let history = recorder.history.lock();
662 assert_eq!(history.startup.len(), STARTUP_ENTRIES);
663 assert_eq!(history.startup[0].elapsed_us, 0);
664 assert_eq!(history.recent.len(), RECENT_ENTRIES);
665 assert_eq!(
666 history.recent.front().unwrap().elapsed_us,
667 (STARTUP_ENTRIES + 5) as u64
668 );
669 assert_eq!(
670 history.recent.back().unwrap().elapsed_us,
671 (total - 1) as u64
672 );
673 assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
674 assert_eq!(history.failure.as_deref(), Some("feedback deadline"));
675 }
676}
677
678#[cfg(test)]
679mod compatibility_suggestion_trace_tests {
680 use super::*;
681 #[test]
682 fn three_strike_suggestions_stay_bounded_and_survive_recent_history_overwrite() {
683 let recorder = FeedbackRecorder::new(Instant::now());
684 let events = crate::events::EventHub::start();
685 crate::events::CompatibilityAdmissions::new(false, true, true, false, None).publish(
686 true,
687 &events,
688 Some(&recorder),
689 );
690 events.shutdown();
691 let suggestions = (0..32u8).map(|interface| ((interface, 7), 3));
692 recorder.record_clock_readback_suggestions(suggestions.chain([((99, 1), 2)]));
693 for _ in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 8) {
694 recorder.record(FeedbackTraceEvent::Lock {
695 locked: true,
696 stale: false,
697 });
698 }
699 let history = recorder.history.lock();
700 let suggestions: Vec<_> = history
701 .startup
702 .iter()
703 .filter_map(|entry| match entry.event {
704 FeedbackTraceEvent::ClockReadbackSuggestion {
705 control_interface,
706 clock_entity,
707 strikes,
708 } => Some((control_interface, clock_entity, strikes)),
709 _ => None,
710 })
711 .collect();
712 assert_eq!(
713 suggestions,
714 (0..16u8)
715 .map(|interface| (interface, 7, 3))
716 .collect::<Vec<_>>()
717 );
718 assert!(history.startup.iter().any(|entry|matches!(entry.event,
719 FeedbackTraceEvent::CompatibilityFallback {tier:crate::CompatibilityFallbackTier::UnverifiedClock,reason} if !reason.is_empty())));
720 }
721}