usbdac-core 0.1.4

Direct USB DAC playback for Rust audio applications on Android and Linux, with PCM, DoP, native DSD and bit-perfect reporting.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
use super::*;
use std::collections::VecDeque;

#[derive(Debug)]
pub(super) struct IsoTransferCompletion {
    pub(super) status: StdMutex<Option<i32>>,
    pub(super) completed_at: StdMutex<Option<Instant>>,
    pub(super) actual_length: AtomicUsize,
}

impl IsoTransferCompletion {
    pub(super) fn new() -> Self {
        Self {
            status: StdMutex::new(None),
            completed_at: StdMutex::new(None),
            actual_length: AtomicUsize::new(0),
        }
    }

    pub(super) fn reset(&self) {
        match self.status.lock() {
            Ok(mut guard) => *guard = None,
            Err(poisoned) => *poisoned.into_inner() = None,
        }
        match self.completed_at.lock() {
            Ok(mut guard) => *guard = None,
            Err(poisoned) => *poisoned.into_inner() = None,
        }
        self.actual_length.store(0, Ordering::Release);
    }

    /// libusb has handed the transfer back and nobody has taken the result yet.
    pub(super) fn is_published(&self) -> bool {
        match self.status.lock() {
            Ok(guard) => guard.is_some(),
            Err(poisoned) => poisoned.into_inner().is_some(),
        }
    }

    pub(super) fn take(&self) -> Option<(i32, Instant, usize)> {
        let status = match self.status.lock() {
            Ok(mut guard) => guard.take()?,
            Err(poisoned) => poisoned.into_inner().take()?,
        };
        let completed_at = match self.completed_at.lock() {
            Ok(mut guard) => guard.take(),
            Err(poisoned) => poisoned.into_inner().take(),
        }
        .unwrap_or_else(Instant::now);
        Some((
            status,
            completed_at,
            self.actual_length.load(Ordering::Acquire),
        ))
    }
}

#[derive(Debug)]
pub(super) struct IsoTransferUserData {
    pub(super) completion: Arc<IsoTransferCompletion>,
    pub(super) buffer: Vec<u8>,
}

pub(super) struct IsoTransferSlot {
    pub(super) transfer: std::ptr::NonNull<libusb_transfer>,
    pub(super) user_data: *mut IsoTransferUserData,
    pub(super) slot_index: usize,
    pub(super) generation: u64,
    pub(super) submitted_endpoint: u8,
    pub(super) submitted_bytes: usize,
    pub(super) packet_sizes: Vec<usize>,
    pub(super) queued_frame_count: usize,
    pub(super) queued_underrun: bool,
    /// The queued transfer carries held wire silence, not audio.
    pub(super) queued_held: bool,
    /// Frames of the queued transfer taken from the ring (not padding or hold).
    pub(super) queued_music_frames: usize,
    /// Flush epoch the queued transfer was filled in.
    pub(super) queued_epoch: u64,
    pub(super) submitted_at: Option<Instant>,
    pub(super) in_flight: bool,
    retirement_context: Option<Context>,
    /// The flush asked libusb to cancel this transfer. Cleared when it comes
    /// back, whatever its status: a transfer that finished first is still
    /// accounted as played.
    pub(super) cancelled_for_flush: bool,
}

pub(super) struct IsoTransferPayload {
    pub(super) packet_sizes: Vec<usize>,
    pub(super) packet_samples: Vec<i32>,
    pub(super) transfer_buffer: Vec<u8>,
    pub(super) underrun: bool,
    /// Wire silence sent while paused or while a flushed ring refills. It
    /// consumed nothing from the ring, so it is not an underrun, and a transfer
    /// that carries it cannot have lost audio.
    pub(super) held: bool,
    pub(super) frame_count: usize,
    /// Frames taken from the ring: `frame_count` minus padding and holds.
    pub(super) music_frames: usize,
    /// Flush epoch of the ring when this transfer was filled.
    pub(super) epoch: u64,
}

impl IsoTransferSlot {
    pub(super) fn new(slot_index: usize, packet_count: usize, buffer_capacity: usize) -> Result<Self, String> {
        let completion = Arc::new(IsoTransferCompletion::new());
        let user_data = Box::new(IsoTransferUserData {
            completion,
            buffer: vec![0u8; buffer_capacity.max(1)],
        });
        let user_data_ptr = Box::into_raw(user_data);
        let transfer = unsafe { libusb_alloc_transfer(packet_count as i32) };

        let Some(transfer) = std::ptr::NonNull::new(transfer) else {
            unsafe {
                drop(Box::from_raw(user_data_ptr));
            }
            return Err("libusb_alloc_transfer returned null".to_string());
        };

        Ok(Self {
            transfer,
            user_data: user_data_ptr,
            slot_index,
            generation: 0,
            submitted_endpoint: 0,
            submitted_bytes: 0,
            packet_sizes: vec![0; packet_count],
            queued_frame_count: 0,
            queued_underrun: false,
            queued_held: false,
            queued_music_frames: 0,
            queued_epoch: 0,
            submitted_at: None,
            in_flight: false,
            retirement_context: None,
            cancelled_for_flush: false,
        })
    }

    pub(super) fn submit(
        &mut self,
        handle: &DeviceHandle<Context>,
        endpoint: u8,
        payload: IsoTransferPayload,
    ) -> Result<(), String> {
        self.submit_with_timeout(handle, endpoint, payload, ISO_TRANSFER_TIMEOUT_MS)
    }

    pub(super) fn submit_with_timeout(&mut self, handle: &DeviceHandle<Context>, endpoint: u8,
        payload: IsoTransferPayload, timeout_ms: u32) -> Result<(), String> {
        if self.in_flight {
            return Err("isochronous transfer slot already has a transfer in flight".to_string());
        }

        if payload.packet_sizes.len() != self.packet_sizes.len() {
            return Err(format!(
                "isochronous packet count mismatch: slot={}, payload={}",
                self.packet_sizes.len(),
                payload.packet_sizes.len()
            ));
        }

        self.retirement_context = Some(handle.context().clone());
        unsafe {
            let user_data = &mut *self.user_data;
            if payload.transfer_buffer.len() > user_data.buffer.len() {
                return Err(format!(
                    "isochronous transfer buffer too small: capacity={}, payload={}",
                    user_data.buffer.len(),
                    payload.transfer_buffer.len()
                ));
            }
            user_data.buffer[..payload.transfer_buffer.len()]
                .copy_from_slice(&payload.transfer_buffer);
            user_data.completion.reset();

            libusb_fill_iso_transfer(
                self.transfer.as_mut(),
                handle.as_raw(),
                endpoint,
                user_data.buffer.as_mut_ptr(),
                payload.transfer_buffer.len() as i32,
                payload.packet_sizes.len() as i32,
                iso_transfer_callback,
                self.user_data as *mut c_void,
                timeout_ms,
            );

            for (index, packet_size) in payload.packet_sizes.iter().enumerate() {
                (*self
                    .transfer
                    .as_mut()
                    .iso_packet_desc
                    .as_mut_ptr()
                    .add(index))
                .length = *packet_size as u32;
            }

            let submit_result = libusb_submit_transfer(self.transfer.as_ptr());
            if submit_result != 0 {
                if submit_result == libusb1_sys::constants::LIBUSB_ERROR_NO_DEVICE {
                    return Err("USB DAC disconnected (isochronous submit)".into());
                }
                return Err(format!(
                    "libusb_submit_transfer failed with code {}",
                    submit_result
                ));
            }
        }

        self.generation = self.generation.saturating_add(1);
        self.submitted_endpoint = endpoint;
        self.submitted_bytes = payload.transfer_buffer.len();
        self.queued_frame_count = payload.frame_count;
        self.queued_underrun = payload.underrun;
        self.queued_held = payload.held;
        self.queued_music_frames = payload.music_frames;
        self.queued_epoch = payload.epoch;
        self.packet_sizes.copy_from_slice(&payload.packet_sizes);
        self.submitted_at = Some(Instant::now());
        self.in_flight = true;
        Ok(())
    }

    /// Reuse the capture buffer without copying or exposing captured audio.
    pub(super) fn submit_capture(&mut self, handle: &DeviceHandle<Context>, endpoint: u8, packet_bytes: usize,
        trace: Option<&crate::feedback_diagnostics::FeedbackRecorder>) -> Result<(), String> {
        if self.in_flight { return Err("capture slot already submitted".into()); }
        if endpoint & 0x80 == 0 || packet_bytes == 0 || packet_bytes > u32::MAX as usize
            || self.packet_sizes.len() > i32::MAX as usize {
            return Err("invalid capture request geometry".into());
        }
        self.retirement_context = Some(handle.context().clone());
        unsafe {
            let data = &mut *self.user_data;
            data.completion.reset();
            let bytes = packet_bytes.checked_mul(self.packet_sizes.len()).ok_or("capture size overflow")?;
            if bytes > data.buffer.len() || bytes > i32::MAX as usize { return Err("capture buffer too small or request too large".into()); }
            libusb_fill_iso_transfer(self.transfer.as_mut(), handle.as_raw(), endpoint,
                data.buffer.as_mut_ptr(), bytes as i32, self.packet_sizes.len() as i32,
                iso_transfer_callback, self.user_data as *mut c_void, ISO_TRANSFER_TIMEOUT_MS);
            for index in 0..self.packet_sizes.len() {
                (*self.transfer.as_mut().iso_packet_desc.as_mut_ptr().add(index)).length = packet_bytes as u32;
            }
            let result = libusb_submit_transfer(self.transfer.as_ptr());
            if let Some(trace) = trace {
                trace.record(crate::FeedbackTraceEvent::Submit { slot: Some(self.slot_index), status: result });
            }
            if result != 0 {
                return Err(if result == libusb1_sys::constants::LIBUSB_ERROR_NO_DEVICE {
                    "USB DAC disconnected (implicit capture submit)".into()
                } else { format!("implicit capture submit failed: {}", result) });
            }
            self.packet_sizes.fill(packet_bytes);
            self.generation = self.generation.saturating_add(1);
            self.submitted_endpoint = endpoint;
            self.submitted_bytes = bytes;
            self.in_flight = true;
            self.submitted_at = Some(Instant::now());
        }
        Ok(())
    }

    pub(super) fn take_completion(&mut self) -> Option<(i32, Instant, usize)> {
        let completion = unsafe { &(*self.user_data).completion };
        completion.take()
    }

    pub(super) fn turnaround_us(&self, completed_at: Instant) -> Option<u64> {
        self.submitted_at.map(|submitted_at| {
            completed_at
                .saturating_duration_since(submitted_at)
                .as_micros()
                .min(u128::from(u64::MAX)) as u64
        })
    }

    pub(super) fn validate_packets(&self, acceptance: PacketAcceptance) -> Result<CompletionStats, String> {
        let transfer = unsafe { self.transfer.as_ref() };
        validate_iso_packet_results(transfer, &self.packet_sizes, acceptance).map_err(|error| {
            format!(
                "{}; slot={} generation={} submitted_endpoint=0x{:02x} \
                 completed_endpoint=0x{:02x} submitted_bytes={} transfer_length={}",
                error,
                self.slot_index,
                self.generation,
                self.submitted_endpoint,
                transfer.endpoint,
                self.submitted_bytes,
                transfer.length,
            )
        })
    }

    /// What a timed-out URB cost, from its packet descriptors.
    pub(super) fn account_timeout(&self, acceptance: PacketAcceptance) -> CompletionStats {
        let transfer = unsafe { self.transfer.as_ref() };
        timed_out_packet_results(transfer, &self.packet_sizes, acceptance)
    }

    pub(super) fn mark_completed(&mut self) {
        self.queued_frame_count = 0;
        self.queued_underrun = false;
        self.queued_held = false;
        self.queued_music_frames = 0;
        self.submitted_at = None;
        self.in_flight = false;
        self.cancelled_for_flush = false;
    }

    pub(super) fn cancel(&mut self) {
        if !self.in_flight {
            return;
        }

        let _ = unsafe { libusb_cancel_transfer(self.transfer.as_ptr()) };
    }

    /// Cancels the transfer because the stream was flushed. The buffer stays
    /// owned by the slot until libusb hands the transfer back (see
    /// [`completion_ready`](Self::completion_ready)). A transfer that already
    /// finished cannot be cancelled and comes back with its own status.
    pub(super) fn cancel_for_flush(&mut self) {
        if !self.in_flight {
            return;
        }
        self.cancelled_for_flush = true;
        self.cancel();
    }

    /// libusb has handed this transfer back: its result is waiting to be taken.
    pub(super) fn completion_ready(&self) -> bool {
        unsafe { &(*self.user_data).completion }.is_published()
    }
}

impl Drop for IsoTransferSlot {
    fn drop(&mut self) {
        if self.in_flight {
            // Also protects unwinding: the handle/FD owner outlives the slots.
            self.cancel();
            if let Some(context) = self.retirement_context.clone() {
                let mut warned = false;
                while self.in_flight {
                    if self.take_completion().is_some() { self.mark_completed(); break; }
                    if let Err(error) = context.handle_events(Some(Duration::from_millis(10))) {
                        if !warned { log_warn!("USB unwind cancellation retirement pending: {}", error); warned = true; }
                        thread::sleep(Duration::from_millis(10));
                    }
                }
            }
        }

        unsafe {
            libusb_free_transfer(self.transfer.as_ptr());
            drop(Box::from_raw(self.user_data));
        }
    }
}

/// AudioControl status IN transfer, retired by the stream's existing event owner.
pub(super) struct InterruptTransferSlot {
    slot: IsoTransferSlot,
    packet_bytes: usize,
}

impl InterruptTransferSlot {
    pub(super) fn new(packet_bytes: usize) -> Result<Self, String> {
        if packet_bytes == 0 || packet_bytes > i32::MAX as usize {
            return Err("invalid interrupt transfer capacity".into());
        }
        Ok(Self {
            slot: IsoTransferSlot::new(0, 0, packet_bytes)?,
            packet_bytes,
        })
    }

    pub(super) fn submit(
        &mut self,
        handle: &DeviceHandle<Context>,
        endpoint: u8,
    ) -> Result<(), Error> {
        if self.slot.in_flight {
            return Err(Error::InvalidState("interrupt transfer already in flight".into()));
        }
        if endpoint & 0x80 == 0 || endpoint & 0x70 != 0 || endpoint & 0x0f == 0 {
            return Err(Error::InvalidArgument("invalid interrupt IN endpoint".into()));
        }

        unsafe {
            let data = &mut *self.slot.user_data;
            if self.packet_bytes == 0 || self.packet_bytes > i32::MAX as usize
                || self.packet_bytes > data.buffer.len()
            {
                return Err(Error::InvalidArgument("invalid interrupt transfer capacity".into()));
            }
            data.completion.reset();
            self.slot.retirement_context = Some(handle.context().clone());
            libusb_fill_interrupt_transfer(
                self.slot.transfer.as_mut(),
                handle.as_raw(),
                endpoint,
                data.buffer.as_mut_ptr(),
                self.packet_bytes as i32,
                iso_transfer_callback,
                self.slot.user_data as *mut c_void,
                0, // Status endpoints may NAK indefinitely until a change occurs.
            );
            let result = libusb_submit_transfer(self.slot.transfer.as_ptr());
            if result != 0 {
                return Err(if result == libusb1_sys::constants::LIBUSB_ERROR_NO_DEVICE {
                    Error::DeviceLost
                } else {
                    Error::Transfer(format!("interrupt submit failed with code {}", result))
                });
            }
        }
        self.slot.submitted_endpoint = endpoint;
        self.slot.submitted_bytes = self.packet_bytes;
        self.slot.in_flight = true;
        Ok(())
    }

    pub(super) fn take_completion(&mut self) -> Option<(i32, &[u8])> {
        if !self.slot.in_flight {
            return None;
        }
        let (mut status, _, actual_length) = self.slot.take_completion()?;
        self.slot.mark_completed();
        let buffer = unsafe { &(*self.slot.user_data).buffer };
        let length = if status == LIBUSB_TRANSFER_COMPLETED {
            if actual_length > self.packet_bytes || actual_length > buffer.len() {
                status = libusb1_sys::constants::LIBUSB_TRANSFER_OVERFLOW;
                0
            } else {
                actual_length
            }
        } else {
            0
        };
        Some((status, &buffer[..length]))
    }
}

/// Private deferred compatibility state; release construction is neutral.
#[derive(Default, Debug)]
pub(super) struct FeedbackCompatibility {
    tenor_nominal_q16: Option<u32>,
    startup_packets_remaining: u8,
}

impl FeedbackCompatibility {
    pub(super) fn for_device(
        _vendor: u16,
        _product: u16,
        _speed: Speed,
        _endpoint: FeedbackEndpoint,
        _sample_rate: u32,
    ) -> Self {
        // Shared-parity release keeps universal feedback/timebase handling.
        // Tenor correction and Playback Designs startup skipping are deferred.
        Self::default()
    }

    fn skip_packet(&mut self) -> bool {
        let skip = self.startup_packets_remaining != 0;
        self.startup_packets_remaining = self.startup_packets_remaining.saturating_sub(1);
        skip
    }
}

// Linux endpoint.c Tenor 8802 rule: correct only values strictly outside the
// nominal half-sample window, before applying this transport's tighter guards.
fn correct_tenor_feedback(raw: u32, nominal: u32) -> Option<u32> {
    if raw == 0 || raw & 0xf000_0000 != 0 {
        return None;
    }
    let lower = nominal.checked_sub(0x8000)?;
    let upper = nominal.checked_add(0x8000)?;
    if raw < lower {
        raw.checked_add(0xf000)
    } else if raw > upper {
        raw.checked_sub(0xf000)
    } else {
        Some(raw)
    }
}

const NO_FEEDBACK_PACKET_STATUS: i32 = i32::MIN;

/// Persistent asynchronous feedback IN transfers owned by the output event loop.
/// Keep a second batch submitted while the output thread handles the first.
/// Divide the existing polling window between slots rather than growing it:
/// blocking reads can otherwise drain the queued OUT audio while awaiting IN.
pub(super) struct FeedbackTransfers {
    pub(super) slots: Vec<FeedbackTransferSlot>,
    pending: VecDeque<usize>,
    // Startup skips and device corrections belong to the ordered pipe, not each slot.
    compatibility: FeedbackCompatibility,
}

fn feedback_poll_geometry(endpoint: FeedbackEndpoint, bus_queue_ms: u32) -> (usize, usize) {
    if endpoint.transfer_type != TransferType::Isochronous {
        return (1, 1);
    }
    let window_packets = (USB_FEEDBACK_POLL_WINDOW_MS.min(bus_queue_ms.max(1)) * 1_000)
        / endpoint.service_interval_us.max(125);
    let packets = window_packets.clamp(1, 32) as usize;
    let slots = packets.min(2);
    (slots, packets / slots)
}

impl FeedbackTransfers {
    pub(super) fn new(endpoint: FeedbackEndpoint, bus_queue_ms: u32,
        compatibility: FeedbackCompatibility) -> Result<Self, String> {
        let (count, packets_per_slot) = feedback_poll_geometry(endpoint, bus_queue_ms);
        let slots = (0..count)
            .map(|_| FeedbackTransferSlot::new(endpoint, packets_per_slot))
            .collect::<Result<_, _>>()?;
        Ok(Self { slots, pending: VecDeque::with_capacity(count), compatibility })
    }

    pub(super) fn start(
        &mut self, handle: &DeviceHandle<Context>, counters: &mut FeedbackCounters,
    ) -> Result<(), FeedbackFault> {
        for index in 0..self.slots.len() {
            self.submit(index, handle, counters, index == 0)?;
        }
        Ok(())
    }

    fn take_next_completion(&mut self) -> Option<(usize, i32, Instant, usize)> {
        let index = *self.pending.front()?;
        let slot = &mut self.slots[index];
        let (status, completed_at, actual_length) = slot.take_completion()?;
        self.pending.pop_front();
        slot.mark_completed();
        Some((index, status, completed_at, actual_length))
    }

    fn submit(
        &mut self, index: usize, handle: &DeviceHandle<Context>, counters: &mut FeedbackCounters,
        first: bool,
    ) -> Result<(), FeedbackFault> {
        let slot = &mut self.slots[index];
        let result = slot.submit(handle);
        self.record_submission(index, result, counters, first)
    }

    fn record_submission(
        &mut self, index: usize, result: Result<(), String>, counters: &mut FeedbackCounters,
        first: bool,
    ) -> Result<(), FeedbackFault> {
        let slot = &mut self.slots[index];
        counters.record_submit(index, slot.last_submit_status);
        match result {
            Ok(()) => self.pending.push_back(index),
            Err(error) => {
                counters.errors = counters.errors.saturating_add(1);
                if let Some(fault) = feedback_submit_failure(error.clone(), slot.submit_no_device, first) {
                    return Err(fault);
                }
                slot.retry_at = Instant::now() + Duration::from_millis(5);
                if counters.errors <= 4 || counters.errors % 64 == 0 {
                    log_warn!("explicit feedback resubmit failed: {}", error);
                }
            }
        }
        Ok(())
    }
}

/// Persistent asynchronous feedback IN transfer and its buffer.
pub(super) struct FeedbackTransferSlot {
    pub(super) transfer: std::ptr::NonNull<libusb_transfer>,
    pub(super) user_data: *mut IsoTransferUserData,
    pub(super) endpoint: FeedbackEndpoint,
    pub(super) packet_count: usize,
    pub(super) packet_bytes: usize,
    pub(super) timeout_ms: u32,
    pub(super) in_flight: bool,
    retirement_context: Option<Context>,
    pub(super) submit_no_device: bool,
    pub(super) last_submit_status: Option<i32>,
    retry_at: Instant,
}

impl FeedbackTransferSlot {
    fn new(endpoint: FeedbackEndpoint, packet_count: usize) -> Result<Self, String> {
        let packet_bytes = endpoint.max_packet_bytes.max(4);

        let poll_window_ms = ((packet_count as u64)
            .saturating_mul(endpoint.service_interval_us as u64)
            / 1_000)
            .max(1) as u32;
        let timeout_ms =
            USB_FEEDBACK_TIMEOUT_MS.max(poll_window_ms.saturating_add(20));

        let completion = Arc::new(IsoTransferCompletion::new());
        let user_data = Box::new(IsoTransferUserData {
            completion,
            buffer: vec![0u8; packet_bytes.saturating_mul(packet_count).max(4)],
        });
        let user_data_ptr = Box::into_raw(user_data);
        let transfer = unsafe { libusb_alloc_transfer(packet_count as i32) };

        let Some(transfer) = std::ptr::NonNull::new(transfer) else {
            unsafe {
                drop(Box::from_raw(user_data_ptr));
            }
            return Err("libusb_alloc_transfer returned null for feedback transfer".to_string());
        };

        Ok(Self {
            transfer,
            user_data: user_data_ptr,
            endpoint,
            packet_count,
            packet_bytes,
            timeout_ms,
            in_flight: false,
            retirement_context: None,
            submit_no_device: false,
            last_submit_status: None,
            retry_at: Instant::now(),
        })
    }

    pub(super) fn submit(&mut self, handle: &DeviceHandle<Context>) -> Result<(), String> {
        self.last_submit_status = None;
        if self.in_flight {
            return Err("feedback transfer slot already in flight".to_string());
        }

        self.retirement_context = Some(handle.context().clone());
        unsafe {
            let user_data = &mut *self.user_data;
            user_data.completion.reset();
            let buffer_len = self.packet_bytes.saturating_mul(self.packet_count);
            match self.endpoint.transfer_type {
                TransferType::Isochronous => {
                    libusb_fill_iso_transfer(
                        self.transfer.as_mut(),
                        handle.as_raw(),
                        self.endpoint.address,
                        user_data.buffer.as_mut_ptr(),
                        buffer_len as i32,
                        self.packet_count as i32,
                        iso_transfer_callback,
                        self.user_data as *mut c_void,
                        self.timeout_ms,
                    );
                    for index in 0..self.packet_count {
                        let packet = &mut *self
                            .transfer
                            .as_mut()
                            .iso_packet_desc
                            .as_mut_ptr()
                            .add(index);
                        packet.length = self.packet_bytes as u32;
                        // A transfer can fail before every packet is reported.
                        // Do not reuse lengths or statuses from its last poll.
                        packet.actual_length = 0;
                        packet.status = NO_FEEDBACK_PACKET_STATUS;
                    }
                }
                TransferType::Interrupt => {
                    libusb_fill_interrupt_transfer(
                        self.transfer.as_mut(),
                        handle.as_raw(),
                        self.endpoint.address,
                        user_data.buffer.as_mut_ptr(),
                        self.packet_bytes as i32,
                        iso_transfer_callback,
                        self.user_data as *mut c_void,
                        self.timeout_ms,
                    );
                }
                other => {
                    return Err(format!(
                        "Unsupported feedback transfer type {}",
                        transfer_type_label(other)
                    ));
                }
            }

            let submit_result = libusb_submit_transfer(self.transfer.as_ptr());
            self.last_submit_status = Some(submit_result);
            self.submit_no_device = submit_result == libusb1_sys::constants::LIBUSB_ERROR_NO_DEVICE;
            if submit_result != 0 {
                return Err(format!(
                    "libusb_submit_transfer failed for feedback endpoint 0x{:02x} with code {}",
                    self.endpoint.address, submit_result
                ));
            }
        }

        self.in_flight = true;
        Ok(())
    }

    pub(super) fn take_completion(&self) -> Option<(i32, Instant, usize)> {
        let completion = unsafe { &(*self.user_data).completion };
        completion.take()
    }

    fn newest_valid_report(&mut self, scheduler: &IsoPacketScheduler, service_us: u32,
        speed: Speed, max_frames: usize, per_service: bool, counters: &mut FeedbackCounters,
        actual_length: usize, transfer_status: i32,
        compatibility: &mut FeedbackCompatibility) -> Option<(f64, f64)> {
        let buffer = unsafe { &(*self.user_data).buffer };
        if self.endpoint.transfer_type == TransferType::Isochronous {
            let transfer = unsafe { self.transfer.as_ref() };
            if transfer.num_iso_packets < 0 || transfer.num_iso_packets as usize != self.packet_count {
                if transfer_status == LIBUSB_TRANSFER_COMPLETED {
                    counters.errors = counters.errors.saturating_add(1);
                }
                return None;
            }
            inspect_feedback_packets_with_compatibility(buffer, (0..self.packet_count).map(|index| {
                let packet = unsafe { &*transfer.iso_packet_desc.as_ptr().add(index) };
                (packet.status, packet.length as usize, packet.actual_length as usize)
            }), scheduler, service_us, speed, max_frames, per_service, counters, transfer_status, true, compatibility)
        } else {
            inspect_feedback_packets_with_compatibility(buffer, [(transfer_status, self.packet_bytes, actual_length)],
                scheduler, service_us, speed, max_frames, per_service, counters, transfer_status, false, compatibility)
        }
    }

    pub(super) fn mark_completed(&mut self) {
        self.in_flight = false;
    }

    pub(super) fn cancel(&mut self) {
        if self.in_flight {
            let _ = unsafe { libusb_cancel_transfer(self.transfer.as_ptr()) };
        }
    }
}

impl Drop for FeedbackTransferSlot {
    fn drop(&mut self) {
        if self.in_flight {
            self.cancel();
            if let Some(context) = self.retirement_context.clone() {
                let mut warned = false;
                while self.in_flight {
                    if self.take_completion().is_some() { self.mark_completed(); break; }
                    if let Err(error) = context.handle_events(Some(Duration::from_millis(10))) {
                        if !warned { log_warn!("USB unwind cancellation retirement pending: {}", error); warned = true; }
                        thread::sleep(Duration::from_millis(10));
                    }
                }
            }
        }

        unsafe {
            libusb_free_transfer(self.transfer.as_ptr());
            drop(Box::from_raw(self.user_data));
        }
    }
}

#[derive(Default)]
pub(super) struct FeedbackCounters {
    pub(super) reports: u64,
    pub(super) timeouts: u64,
    pub(super) errors: u64,
    pub(super) rejected: u64,
    pub(super) last_report_at: Option<Instant>,
    pub(super) last_frames_per_packet: Option<f64>,
    pub(super) last_estimated_sample_rate: Option<f64>,
    pub(super) empty_polls: u64,
    malformed: u64,
    rate_rejected: u64,
    last_report_bytes: [u8; 8],
    last_report_len: usize,
    pub(super) diagnostics: Option<crate::ExplicitFeedbackDiagnostics>,
    pub(super) diagnostics_dirty: bool,
    pub(super) trace: Option<Arc<crate::feedback_diagnostics::FeedbackRecorder>>,
    pub(super) infer_service_interval: bool,
    pub(super) cached_service_interval: bool,
    selected_timebase: Option<FeedbackTimebase>,
    service_interval_confirmations: u8,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FeedbackTimebase {
    Bus,
    OutService,
}

const SERVICE_INTERVAL_CONFIRMATIONS: u8 = 3;

impl FeedbackCounters {
    pub(super) fn selected_service_interval(&self) -> bool {
        self.selected_timebase == Some(FeedbackTimebase::OutService)
    }

    fn record_submit(&mut self, index: usize, status: Option<i32>) {
        if let Some(status) = status {
            if let Some(diagnostics) = self.diagnostics.as_mut() {
                diagnostics.record_submit(status);
                self.diagnostics_dirty = true;
            }
            if let Some(trace) = &self.trace {
                trace.record(crate::FeedbackTraceEvent::Submit { slot: Some(index), status });
            }
        }
    }

    fn select_timebase(&mut self, timebase: FeedbackTimebase, speed: Speed, inferred: bool) {
        self.selected_timebase = Some(timebase);
        let unit = match (timebase, speed) {
            (FeedbackTimebase::OutService, _) => "out_service_interval",
            (_, Speed::Full) => "usb_frame",
            _ => "usb_microframe",
        };
        if let Some(diagnostics) = self.diagnostics.as_mut() {
            diagnostics.timebase = Some(unit);
            diagnostics.inferred_timebase = inferred;
            diagnostics.reused_timebase = inferred && self.cached_service_interval;
        }
        if let Some(trace) = &self.trace {
            trace.record(crate::FeedbackTraceEvent::Timebase { unit, inferred });
        }
        if inferred && self.cached_service_interval {
            log_info!("[USB] Explicit feedback timebase reused for DAC session: {}", unit);
        } else if inferred {
            log_info!("[USB] Explicit feedback timebase inferred: {} ({} matching completions)",
                unit, SERVICE_INTERVAL_CONFIRMATIONS);
        }
    }

    fn record_valid_bytes(&mut self, bytes: &[u8]) {
        self.last_report_bytes = [0; 8];
        self.last_report_bytes[..bytes.len()].copy_from_slice(bytes);
        self.last_report_len = bytes.len();
    }
}

/// Scan requested packet spans, never a shortened/concatenated actual-length prefix.
/// Validate all candidates before selecting one; update the EWMA only once per transfer.
#[cfg(test)]
fn select_feedback_report(
    buffer: &[u8], packets: impl IntoIterator<Item = (i32, usize, usize)>,
    scheduler: &IsoPacketScheduler, service_us: u32, speed: Speed,
    max_frames: usize, per_service: bool, counters: &mut FeedbackCounters,
) -> Option<(f64, f64)> {
    inspect_feedback_packets(buffer, packets, scheduler, service_us, speed, max_frames,
        per_service, counters, LIBUSB_TRANSFER_COMPLETED, true)
}

#[cfg(test)]
fn select_feedback_report_with_compatibility(
    buffer: &[u8], packets: impl IntoIterator<Item = (i32, usize, usize)>,
    scheduler: &IsoPacketScheduler, service_us: u32, speed: Speed,
    max_frames: usize, per_service: bool, counters: &mut FeedbackCounters,
    compatibility: &mut FeedbackCompatibility,
) -> Option<(f64, f64)> {
    inspect_feedback_packets_with_compatibility(buffer, packets, scheduler, service_us, speed,
        max_frames, per_service, counters, LIBUSB_TRANSFER_COMPLETED, true, compatibility)
}

#[cfg(test)]
fn inspect_feedback_packets(
    buffer: &[u8], packets: impl IntoIterator<Item = (i32, usize, usize)>,
    scheduler: &IsoPacketScheduler, service_us: u32, speed: Speed,
    max_frames: usize, per_service: bool, counters: &mut FeedbackCounters,
    transfer_status: i32, is_iso: bool,
) -> Option<(f64, f64)> {
    inspect_feedback_packets_with_compatibility(buffer, packets, scheduler, service_us, speed,
        max_frames, per_service, counters, transfer_status, is_iso, &mut FeedbackCompatibility::default())
}

fn inspect_feedback_packets_with_compatibility(
    buffer: &[u8], packets: impl IntoIterator<Item = (i32, usize, usize)>,
    scheduler: &IsoPacketScheduler, service_us: u32, speed: Speed,
    max_frames: usize, per_service: bool, counters: &mut FeedbackCounters,
    transfer_status: i32, is_iso: bool, compatibility: &mut FeedbackCompatibility,
) -> Option<(f64, f64)> {
    use crate::ExplicitFeedbackOutcome as Outcome;
    let mut offset = 0usize;
    let mut newest = None;
    let mut newest_service_interval = None;
    let mut conflicting_report = false;
    // Tenor's bounded correction defines its bus units; inference must not
    // reinterpret a report rejected by that correction as a different timebase.
    let detecting = !per_service && compatibility.tenor_nominal_q16.is_none()
        && counters.selected_timebase.is_none() && counters.infer_service_interval
        && speed == Speed::High && service_us > 125;
    let inferred_service_interval = !per_service && counters.selected_timebase == Some(FeedbackTimebase::OutService);
    for (index, (status, requested, actual)) in packets.into_iter().enumerate() {
        let start = offset;
        offset = offset.saturating_add(requested);
        // Only successful transfer completions consume startup bus opportunities.
        // Failed/empty packet descriptors within such a transfer still count.
        let skip = transfer_status == LIBUSB_TRANSFER_COMPLETED && compatibility.skip_packet();
        let report = (actual <= requested && offset <= buffer.len())
            .then(|| buffer.get(start..start.saturating_add(actual))).flatten();
        let mut decoded = None;
        let outcome = if transfer_status != LIBUSB_TRANSFER_COMPLETED {
            Outcome::TransferFailed
        } else if status != LIBUSB_TRANSFER_COMPLETED {
            Outcome::PacketFailed
        } else if actual == 0 {
            Outcome::Empty
        } else if let Some(bytes) = report.filter(|bytes| {
            if requested == 8 && matches!(speed, Speed::Super | Speed::SuperPlus) {
                bytes.len() == 8
            } else {
                matches!(bytes.len(), 3 | 4)
            }
        }) {
            if !inferred_service_interval || matches!(bytes.len(), 4 | 8) {
                decoded = if !per_service && !inferred_service_interval && speed == Speed::High
                    && bytes.len() == 4 && compatibility.tenor_nominal_q16.is_some()
                {
                    let raw = u32::from_le_bytes(bytes.try_into().unwrap());
                    correct_tenor_feedback(raw, compatibility.tenor_nominal_q16.unwrap())
                        .and_then(|corrected| decode_feedback_report_with_scale(
                            &corrected.to_le_bytes(), service_us, speed, false))
                } else {
                    decode_feedback_report_with_scale(
                        bytes, service_us, speed, per_service || inferred_service_interval,
                    )
                };
            }
            // Startup reports cannot select units, acquire lock or renew its deadline.
            // Retain ordinary malformed/empty/failed diagnostics below.
            if skip && decoded.is_some() { continue; }
            match decoded {
                None => Outcome::InvalidEncoding,
                Some((frames, _)) if !scheduler.feedback_rate_is_plausible(frames) => {
                    let compatible = (detecting && bytes.len() == 4)
                        .then(|| decode_feedback_report_with_scale(bytes, service_us, speed, true))
                        .flatten()
                        .filter(|(frames, _)| scheduler.feedback_rate_is_plausible(*frames)
                            && frames.ceil() <= max_frames as f64);
                    if let Some(rate) = compatible {
                        newest_service_interval = Some((rate, bytes));
                        decoded = Some(rate);
                        Outcome::TimebaseCandidate
                    } else {
                        conflicting_report = true;
                        Outcome::RateOutOfRange
                    }
                }
                Some((frames, _)) if frames.ceil() > max_frames as f64 => Outcome::PacketCapacityExceeded,
                Some(_) => {
                    newest = decoded;
                    counters.record_valid_bytes(bytes);
                    Outcome::Valid
                }
            }
        } else {
            Outcome::InvalidLength
        };
        match outcome {
            Outcome::Valid | Outcome::TransferFailed | Outcome::TimebaseCandidate => {}
            Outcome::Empty => counters.empty_polls = counters.empty_polls.saturating_add(1),
            Outcome::PacketFailed => counters.errors = counters.errors.saturating_add(1),
            Outcome::InvalidLength | Outcome::InvalidEncoding => {
                counters.malformed = counters.malformed.saturating_add(1);
                counters.rejected = counters.rejected.saturating_add(1);
            }
            Outcome::RateOutOfRange | Outcome::PacketCapacityExceeded => {
                counters.rate_rejected = counters.rate_rejected.saturating_add(1);
                counters.rejected = counters.rejected.saturating_add(1);
            }
        }
        if counters.diagnostics.is_some() || counters.trace.is_some() {
            let packet_status = (is_iso && status != NO_FEEDBACK_PACKET_STATUS).then_some(status);
            let raw = if counters.trace.is_some() {
                // Copy only bytes inside this packet's submitted span. A
                // failed transfer can still report a partial IN packet.
                buffer.get(start..offset)
                    .map(|span| &span[..actual.min(span.len())])
                    .unwrap_or_default()
            } else {
                &[]
            };
            let sample = crate::ExplicitFeedbackPacket::new(
                outcome, transfer_status, packet_status, requested, actual, raw, decoded,
            );
            if let Some(diagnostics) = counters.diagnostics.as_mut() {
                diagnostics.record_packet(sample, is_iso);
            }
            if let Some(trace) = &counters.trace {
                trace.record(crate::FeedbackTraceEvent::ExplicitPacket { index, sample });
            }
        }
    }
    if counters.selected_timebase.is_none() {
        if newest.is_some() {
            // A conforming report always wins, even if an earlier packet in
            // the same completion resembled a different timebase.
            let unit = if per_service && speed == Speed::High && counters.last_report_len == 4 {
                FeedbackTimebase::OutService
            } else {
                FeedbackTimebase::Bus
            };
            counters.select_timebase(unit, speed, false);
        } else if let Some((decoded, bytes)) = newest_service_interval.filter(|_| !conflicting_report) {
            // Count once per successful completion. A batch containing many
            // identical packets is only one observation. Empty polls do not
            // count or extend the existing feedback deadline.
            counters.service_interval_confirmations += 1;
            if counters.cached_service_interval
                || counters.service_interval_confirmations == SERVICE_INTERVAL_CONFIRMATIONS
            {
                counters.record_valid_bytes(bytes);
                counters.select_timebase(FeedbackTimebase::OutService, speed, true);
                newest = Some(decoded);
            }
        } else if conflicting_report {
            counters.service_interval_confirmations = 0;
            counters.cached_service_interval = false;
        }
    }
    newest
}

#[derive(Debug)]
pub(super) enum FeedbackFault { DeviceLost, Transfer(String) }

/// A selected explicit pipe cannot silently become nominal on first-submit failure.
/// Runtime transient submissions may retry only while the health deadline remains live.
pub(super) fn feedback_submit_failure(error: String, no_device: bool, first: bool) -> Option<FeedbackFault> {
    if no_device { Some(FeedbackFault::DeviceLost) }
    else if first { Some(FeedbackFault::Transfer(format!("explicit feedback initial submit failed: {}", error))) }
    else { None }
}

fn feedback_completion_fault(status: i32, stopping: bool, endpoint: u8) -> Option<FeedbackFault> {
    match status {
        LIBUSB_TRANSFER_NO_DEVICE => Some(FeedbackFault::DeviceLost),
        LIBUSB_TRANSFER_CANCELLED if !stopping => Some(FeedbackFault::Transfer("explicit feedback unexpectedly cancelled".into())),
        LIBUSB_TRANSFER_STALL => Some(FeedbackFault::Transfer(format!("explicit feedback endpoint 0x{:02x} stalled", endpoint))),
        _ => None,
    }
}

pub(super) fn pump_feedback_transfers(
    handle: &DeviceHandle<Context>, transfers: &mut FeedbackTransfers,
    scheduler: &mut IsoPacketScheduler, data_service_interval_us: u32, speed: Speed,
    max_frames: usize, per_service: bool, counters: &mut FeedbackCounters, stop: &AtomicBool,
    health: ExplicitFeedbackHealth, started_at: Instant,
) -> Result<(), FeedbackFault> {
    // Finished batches belong to earlier USB intervals even if libusb hands
    // a later slot back first. Process them in submission order.
    while let Some((index, status, completed_at, actual_length)) = transfers.take_next_completion() {
        let slot = &mut transfers.slots[index];
        if let Some(diagnostics) = counters.diagnostics.as_mut() {
            diagnostics.record_transfer(status);
            counters.diagnostics_dirty = true;
        }
        if let Some(trace) = &counters.trace {
            trace.record_at(completed_at, crate::FeedbackTraceEvent::Completion {
                slot: Some(index), status, actual_bytes: actual_length,
            });
        }
        let report = slot.newest_valid_report(scheduler, data_service_interval_us, speed,
            max_frames, per_service, counters, actual_length, status, &mut transfers.compatibility);
        if let Some(fault) = feedback_completion_fault(status, usb_stop_requested(stop), slot.endpoint.address) {
            return Err(fault);
        }
        match status {
            LIBUSB_TRANSFER_COMPLETED => {
                if let Some((frames, rate)) = report {
                    // A report delivered beyond the old lease cannot restart it.
                    // Use callback time: a timely report processed slightly late is valid.
                    if !health.report_is_timely(completed_at, started_at, counters.last_report_at) {
                        return Err(FeedbackFault::Transfer("explicit feedback report arrived after its terminal deadline".into()));
                    }
                    if scheduler.update_feedback_frames_per_packet(frames) {
                        counters.reports = counters.reports.saturating_add(1);
                        // Completion callbacks can run out of order. Never
                        // regress the last-report timestamp in that case.
                        counters.last_report_at = Some(counters.last_report_at.map_or(
                            completed_at, |last| last.max(completed_at),
                        ));
                        counters.last_frames_per_packet = Some(frames);
                        counters.last_estimated_sample_rate = Some(rate);
                        if counters.reports == 1 || counters.reports % 128 == 0 {
                            dev_eprintln!("[USB] Explicit feedback endpoint=0x{:02x} bytes={:02x?} framesPerOutService={:.6} rateHz={:.3} perServiceQuirk={} empty={} malformed={} rateRejected={}",
                                slot.endpoint.address, &counters.last_report_bytes[..counters.last_report_len],
                                frames, rate, per_service, counters.empty_polls, counters.malformed, counters.rate_rejected);
                        }
                    }
                }
            }
            LIBUSB_TRANSFER_TIMED_OUT => { counters.timeouts = counters.timeouts.saturating_add(1); }
            LIBUSB_TRANSFER_CANCELLED if usb_stop_requested(stop) => return Ok(()),
            LIBUSB_TRANSFER_OVERFLOW => { counters.rejected = counters.rejected.saturating_add(1); }
            _ => { counters.errors = counters.errors.saturating_add(1); }
        }
        // Retry transient completions with a small bounded delay, not a busy resubmit loop.
        if status != LIBUSB_TRANSFER_COMPLETED {
            slot.retry_at = Instant::now() + Duration::from_millis(5);
        }
        if !usb_stop_requested(stop) && Instant::now() >= slot.retry_at {
            transfers.submit(index, handle, counters, false)?;
        }
    }
    for index in 0..transfers.slots.len() {
        let slot = &transfers.slots[index];
        if !usb_stop_requested(stop) && !slot.in_flight && Instant::now() >= slot.retry_at {
            transfers.submit(index, handle, counters, false)?;
        }
    }
    Ok(())
}

/// Deadlines are measured from the first active transfer or the last actual rate.
/// Empty successful polls and transport retries do not refresh that epoch.
#[derive(Debug, Clone, Copy)]
pub(super) struct ExplicitFeedbackHealth { pub(super) warning: Duration, pub(super) terminal: Duration }
impl ExplicitFeedbackHealth {
    pub(super) fn new(poll_us: u32, refresh: Option<u8>) -> Self {
        // UAC1 bRefresh is log2 milliseconds, valid in the range 1..=9.
        let update_us = refresh.filter(|r| (1..=9).contains(r))
            .map(|r| (1u64 << r) * 1000).unwrap_or(u64::from(poll_us));
        let cadence = Duration::from_micros(update_us.max(u64::from(poll_us)));
        Self { warning: Duration::from_millis(USB_FEEDBACK_STALE_WARN_MS).max(cadence * 3),
            terminal: Duration::from_secs(1).max(cadence * 6) }
    }
    fn report_is_timely(&self, completed: Instant, started: Instant, previous: Option<Instant>) -> bool {
        completed.saturating_duration_since(previous.unwrap_or(started)) < self.terminal
    }
    pub(super) fn state(&self, now: Instant, started: Instant, last: Option<Instant>) -> (bool, bool, bool) {
        let age = now.saturating_duration_since(last.unwrap_or(started));
        (last.is_some() && age < self.warning, age >= self.warning, age >= self.terminal)
    }
}

/// Decode UAC feedback into frames per data-endpoint service interval.
///
/// UAC2 feedback reports samples per microframe on high-speed links and
/// samples per frame on full-speed links. Enhanced SuperSpeed reports unsigned
/// Q32.32 samples per 125 us bus interval (USB 3.2 section 4.4.8.4.1).
/// The feedback endpoint's own polling
/// interval is not the data endpoint's packet interval; using it as the
/// timebase previously produced a rate error of up to 8x at 125 us service.
#[cfg(test)]
pub(super) fn decode_feedback_report(
    raw_bytes: &[u8],
    data_service_interval_us: u32,
    speed: Speed,
) -> Option<(f64, f64)> {
    decode_feedback_report_with_scale(raw_bytes, data_service_interval_us, speed, false)
}

fn decode_feedback_report_with_scale(raw_bytes: &[u8], data_service_interval_us: u32,
    speed: Speed, per_service: bool) -> Option<(f64, f64)> {
    if data_service_interval_us == 0 { return None; }
    let high_speed = matches!(speed, Speed::High | Speed::Super | Speed::SuperPlus);
    if !matches!(speed, Speed::Full | Speed::High | Speed::Super | Speed::SuperPlus) { return None; }
    let per_service = per_service && speed == Speed::High && raw_bytes.len() == 4;
    let (frames_per_base_interval, base_interval_us) = match raw_bytes.len() {
        3 => {
            // Existing HS Q10.14 compatibility: only this exact length/scale;
            // the intake nominal window still has to identify a plausible rate.
            let raw = u32::from(raw_bytes[0])
                | (u32::from(raw_bytes[1]) << 8)
                | (u32::from(raw_bytes[2]) << 16);
            let base_interval_us = feedback_base_interval_us(speed, data_service_interval_us);
            (raw as f64 / 16_384.0, base_interval_us)
        }
        4 => {
            let raw = u32::from_le_bytes([raw_bytes[0], raw_bytes[1], raw_bytes[2], raw_bytes[3]]);
            if high_speed && raw & 0xf000_0000 != 0 { return None; }
            let base_interval_us = if per_service { f64::from(data_service_interval_us) } else { feedback_base_interval_us(speed, data_service_interval_us) };
            (raw as f64 / 65_536.0, base_interval_us)
        }
        8 if matches!(speed, Speed::Super | Speed::SuperPlus) => {
            let raw = u64::from_le_bytes(raw_bytes.try_into().ok()?);
            (raw as f64 / 4_294_967_296.0, 125.0)
        }
        _ => return None,
    };

    let packet_multiplier = data_service_interval_us as f64 / base_interval_us;
    let frames_per_packet = frames_per_base_interval * packet_multiplier;
    let estimated_sample_rate = frames_per_base_interval * (1_000_000.0 / base_interval_us);
    Some((frames_per_packet, estimated_sample_rate))
}

pub(super) fn feedback_base_interval_us(speed: Speed, data_service_interval_us: u32) -> f64 {
    match speed {
        Speed::Low | Speed::Full => 1_000.0,
        Speed::High | Speed::Super | Speed::SuperPlus => 125.0,
        Speed::Unknown => {
            // Isochronous audio at sub-millisecond service intervals can only
            // exist on a high-speed link. Fall back to the data endpoint when
            // libusb could not identify the bus speed.
            if data_service_interval_us < 1_000 {
                125.0
            } else {
                1_000.0
            }
        }
        _ => {
            if data_service_interval_us < 1_000 {
                125.0
            } else {
                1_000.0
            }
        }
    }
}

pub(super) extern "system" fn iso_transfer_callback(transfer: *mut libusb_transfer) {
    // Panicking across the FFI boundary aborts the process, so contain every
    // panic here; a poisoned lock must not kill the app either.
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let Some(transfer) = std::ptr::NonNull::new(transfer) else {
            return;
        };
        let user_data_ptr = unsafe { transfer.as_ref().user_data as *mut IsoTransferUserData };
        let Some(user_data) = std::ptr::NonNull::new(user_data_ptr) else {
            return;
        };

        let completed_at = Instant::now();
        let status = unsafe { transfer.as_ref().status };
        let actual_length = unsafe { transfer.as_ref().actual_length } as usize;
        // Keep the completion state alive independently of the transfer/user
        // data so the output thread can re-arm or free the slot as soon as the
        // status is published.
        let completion = unsafe { user_data.as_ref() }.completion.clone();
        completion
            .actual_length
            .store(actual_length, Ordering::Release);
        match completion.completed_at.lock() {
            Ok(mut guard) => *guard = Some(completed_at),
            Err(poisoned) => *poisoned.into_inner() = Some(completed_at),
        }
        // Publish status last. Everything above is mine; after this store the
        // slot owner may refill or release the transfer without racing this
        // callback, because the callback no longer touches either object.
        let mut guard = match completion.status.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        *guard = Some(status);
    }));
}

pub(super) fn validate_iso_packet_results(
    transfer: &libusb_transfer,
    packet_sizes: &[usize],
    acceptance: PacketAcceptance,
) -> Result<CompletionStats, String> {
    if transfer.num_iso_packets != packet_sizes.len() as i32 {
        return Err(format!(
            "isochronous transfer completed with packet errors: \
             packet count changed: requested={}, transfer={}",
            packet_sizes.len(),
            transfer.num_iso_packets,
        ));
    }

    // Both callers allocated exactly packet_sizes.len() descriptors and call
    // this only after completion, before resubmitting or freeing the transfer.
    let descriptors = unsafe {
        std::slice::from_raw_parts(transfer.iso_packet_desc.as_ptr(), packet_sizes.len())
    };
    validate_iso_packet_descriptors(packet_sizes, descriptors, acceptance)
}

pub(super) fn timed_out_packet_results(
    transfer: &libusb_transfer,
    packet_sizes: &[usize],
    acceptance: PacketAcceptance,
) -> CompletionStats {
    if transfer.num_iso_packets != packet_sizes.len() as i32 {
        // Not the schedule that was submitted: trust nothing, lose the URB.
        return account_timed_out_transfer(packet_sizes, &[], acceptance);
    }

    // Same contract as validate_iso_packet_results: the slot allocated exactly
    // packet_sizes.len() descriptors and this runs after completion, before the
    // slot is resubmitted.
    let descriptors = unsafe {
        std::slice::from_raw_parts(transfer.iso_packet_desc.as_ptr(), packet_sizes.len())
    };
    account_timed_out_transfer(packet_sizes, descriptors, acceptance)
}


#[cfg(test)]
mod explicit_feedback_tests {
    use super::*;

    fn q16(frames: f64) -> [u8; 4] { ((frames * 65536.0).round() as u32).to_le_bytes() }
    fn q32(frames: f64) -> [u8; 8] { ((frames * 4_294_967_296.0).round() as u64).to_le_bytes() }
    fn scheduler(service_us: u32) -> IsoPacketScheduler { IsoPacketScheduler::new(48_000, 8, service_us) }

    #[test]
    fn enhanced_superspeed_feedback_uses_q32_bus_units_at_every_output_interval() {
        for speed in [Speed::Super, Speed::SuperPlus] {
            for rate in [48_000, 44_100] {
                let report = q32(f64::from(rate) / 8000.0);
                for service_us in [125, 250, 1000] {
                    let scheduler = IsoPacketScheduler::new(rate, 8, service_us);
                    let mut counters = FeedbackCounters {
                        infer_service_interval: true, ..FeedbackCounters::default()
                    };
                    let (frames, decoded_rate) = select_feedback_report(&report, [(0, 8, 8)],
                        &scheduler, service_us, speed, 128, true, &mut counters).unwrap();
                    assert!((decoded_rate - f64::from(rate)).abs() < 0.00001);
                    let expected_frames = f64::from(rate) * f64::from(service_us) / 1_000_000.0;
                    assert!((frames - expected_frames).abs() < 0.00001);
                    assert_eq!(counters.last_report_bytes, report);
                    assert_eq!(counters.last_report_len, 8);
                    assert_eq!(counters.selected_timebase, Some(FeedbackTimebase::Bus));
                    assert!(!counters.selected_service_interval());
                }
            }
        }
    }

    #[test]
    fn enhanced_superspeed_keeps_valid_report_before_newer_short_report() {
        let report = q32(6.0);
        let mut batch = report.to_vec();
        batch.extend_from_slice(&q16(6.0));
        batch.extend_from_slice(&[0; 4]);
        let mut counters = FeedbackCounters::default();
        assert_eq!(select_feedback_report(&batch, [(0, 8, 8), (0, 8, 4)],
            &scheduler(250), 250, Speed::Super, 16, false, &mut counters), Some((12.0, 48_000.0)));
        assert_eq!(counters.last_report_bytes, report);
        assert_eq!(counters.last_report_len, 8);
        assert_eq!(counters.malformed, 1);
        assert_eq!(counters.rejected, 1);
    }

    #[test]
    fn enhanced_superspeed_feedback_retains_capacity_and_rate_rejection() {
        for (frames, max_frames) in [(6.0, 47), (48.0, 1024)] {
            let mut counters = FeedbackCounters::default();
            assert!(select_feedback_report(&q32(frames), [(0, 8, 8)], &scheduler(1000),
                1000, Speed::SuperPlus, max_frames, false, &mut counters).is_none());
            assert_eq!(counters.rate_rejected, 1);
            assert_eq!(counters.rejected, 1);
            assert_eq!(counters.last_report_len, 0);
            assert!(counters.last_report_at.is_none());
            assert!(counters.selected_timebase.is_none());
        }
    }

    #[test]
    fn eight_byte_feedback_requires_superspeed_and_exact_selected_request_span() {
        let report = q32(6.0);
        for speed in [Speed::Low, Speed::Full, Speed::High, Speed::Unknown] {
            assert!(decode_feedback_report(&report, 125, speed).is_none());
            let mut counters = FeedbackCounters::default();
            assert!(select_feedback_report(&report, [(0, 8, 8)], &scheduler(125),
                125, speed, 16, false, &mut counters).is_none());
            assert_eq!(counters.malformed, 1);
        }
        for speed in [Speed::Super, Speed::SuperPlus] {
            for actual in [3, 4, 7] {
                let mut counters = FeedbackCounters::default();
                assert!(select_feedback_report(&report, [(0, 8, actual)], &scheduler(125),
                    125, speed, 16, false, &mut counters).is_none());
                assert_eq!(counters.malformed, 1);
            }
            let mut counters = FeedbackCounters::default();
            assert!(select_feedback_report(&report.repeat(2), [(0, 16, 8)], &scheduler(125),
                125, speed, 16, false, &mut counters).is_none());
            assert_eq!(select_feedback_report(&q16(6.0), [(0, 4, 4)], &scheduler(125),
                125, speed, 16, false, &mut counters), Some((6.0, 48_000.0)));
        }
    }

    fn feedback_pipe() -> FeedbackEndpoint {
        FeedbackEndpoint { refresh: 0, address: 0x81, transfer_type: TransferType::Isochronous,
            interval: 1, service_interval_us: 125, max_packet_bytes: 4 }
    }

    #[test]
    fn physical_pcm_and_three_native_dsd_vectors_use_proven_universal_timebase() {
        // AP80 Pro-X physical captures: PCM44.1, native DSD64/128/256.
        // Raw DSD has an eight-byte wire frame; PCM16 stereo has four.
        for (nominal_rate, stride, raw, expected_rate) in [
            (44_100, 4, [0x16, 0x09, 0x0b, 0x00], 44_141.9677734375),
            (88_200, 8, [0xa2, 0x10, 0x16, 0x00], 88_259.8876953125),
            (176_400, 8, [0x2e, 0x1d, 0x2c, 0x00], 176_455.9326171875),
            (352_800, 8, [0x0a, 0x37, 0x58, 0x00], 352_859.9853515625),
        ] {
            let scheduler = IsoPacketScheduler::new(nominal_rate, stride, 250);
            let max_frames = 1024 / stride;
            let mut unproven = FeedbackCounters::default();
            for _ in 0..4 {
                assert!(select_feedback_report(&raw, [(0, 4, 4)], &scheduler, 250,
                    Speed::High, max_frames, false, &mut unproven).is_none());
            }
            assert!(unproven.selected_timebase.is_none());
            let mut proven = FeedbackCounters {
                infer_service_interval: true, ..Default::default()
            };
            for _ in 0..2 {
                assert!(select_feedback_report(&raw, [(0, 4, 4)], &scheduler, 250,
                    Speed::High, max_frames, false, &mut proven).is_none());
            }
            let selected = select_feedback_report(&raw, [(0, 4, 4)], &scheduler, 250,
                Speed::High, max_frames, false, &mut proven).unwrap();
            assert!((selected.1 - expected_rate).abs() < 0.000001);
            assert!((selected.0 - expected_rate / 4000.0).abs() < 0.000001);
            assert!(proven.selected_service_interval());
            // Saved units never waive the fresh stream's capacity guard.
            let mut capacity_limited = FeedbackCounters {
                infer_service_interval: true, cached_service_interval: true, ..Default::default()
            };
            assert!(select_feedback_report(&raw, [(0, 4, 4)], &scheduler, 250,
                Speed::High, 1, false, &mut capacity_limited).is_none());
            assert!(!capacity_limited.selected_service_interval());
        }
    }

    fn compatible_report(report: &[u8], service_us: u32, max_frames: usize, per_service: bool,
        compatibility: &mut FeedbackCompatibility) -> Option<(f64, f64)> {
        select_feedback_report_with_compatibility(report, [(0, report.len(), report.len())],
            &scheduler(service_us), service_us, Speed::High, max_frames, per_service,
            &mut FeedbackCounters::default(), compatibility)
    }

    #[test]
    fn shared_release_keeps_device_specific_feedback_profiles_inactive() {
        for (vendor, product) in [(0x0644, 0x8038), (0x1852, 0x5034), (0x23ba, 1)] {
            let mut compatibility = FeedbackCompatibility::for_device(vendor, product,
                Speed::High, feedback_pipe(), 48_000);
            assert!(compatibility.tenor_nominal_q16.is_none());
            assert_eq!(compatibility.startup_packets_remaining, 0);
            assert_eq!(compatible_report(&q16(6.0), 125, 7, false, &mut compatibility),
                Some((6.0, 48_000.0)));
        }
    }

    #[test]
    fn tenor_uses_checked_strict_bounds_and_never_bypasses_admission() {
        assert_eq!(correct_tenor_feedback(0, 0x60000), None);
        assert_eq!(correct_tenor_feedback(0x58000, 0x60000), Some(0x58000));
        assert_eq!(correct_tenor_feedback(0x68000, 0x60000), Some(0x68000));
        assert_eq!(correct_tenor_feedback(0x57fff, 0x60000), Some(0x66fff));
        assert_eq!(correct_tenor_feedback(0x68001, 0x60000), Some(0x59001));
        assert_eq!(correct_tenor_feedback(1, 0x7fff), None); // nominal bound underflow
        assert_eq!(correct_tenor_feedback(u32::MAX, u32::MAX), None); // nominal bound overflow
        let mut compatibility = FeedbackCompatibility { tenor_nominal_q16: Some(0x60000), startup_packets_remaining: 0 };
        for raw in [0, 1, 0xf0060000, 0x80000] {
            assert!(compatible_report(&u32::to_le_bytes(raw), 125, 7, false, &mut compatibility).is_none());
        }
        // Corrected values still need fractional-ceiling capacity and nominal-rate checks.
        let report = q16(6.01 + 0.9375);
        assert!(compatible_report(&report, 1000, 48, false, &mut compatibility).is_none());
        assert!(compatible_report(&report, 1000, 49, false, &mut compatibility).is_some());
        assert!(compatible_report(&q16(7.2), 125, 8, false, &mut compatibility).is_none());
        // The explicit user scale wins and is never followed by the Tenor subtraction.
        assert_eq!(compatible_report(&q16(48.0), 1000, 49, true, &mut compatibility), Some((48.0, 48_000.0)));
        // A three-byte report keeps the existing Q10.14 interpretation.
        assert_eq!(compatible_report(&[0, 0x80, 1], 125, 7, false, &mut compatibility), Some((6.0, 48_000.0)));
    }

    #[test]
    fn universal_inference_cannot_bypass_tenor_correction_or_playback_startup() {
        let mut tenor = FeedbackCompatibility { tenor_nominal_q16: Some(0x60000), startup_packets_remaining: 0 };
        let mut counters = FeedbackCounters {
            infer_service_interval: true, cached_service_interval: true, ..Default::default()
        };
        // Twelve raw frames would fit OUT-service units but violate the
        // Tenor bus-unit correction and must never acquire an inferred lock.
        assert!(select_feedback_report_with_compatibility(&q16(12.0), [(0, 4, 4)],
            &scheduler(250), 250, Speed::High, 128, false, &mut counters,
            &mut tenor).is_none());
        assert!(counters.selected_timebase.is_none());

        let mut playback = FeedbackCompatibility { tenor_nominal_q16: None, startup_packets_remaining: 4 };
        let mut counters = FeedbackCounters {
            infer_service_interval: true, ..Default::default()
        };
        let report = q16(12.0);
        assert!(select_feedback_report_with_compatibility(&report.repeat(4), [(0, 4, 4); 4],
            &scheduler(250), 250, Speed::High, 128, false, &mut counters,
            &mut playback).is_none());
        assert_eq!(counters.service_interval_confirmations, 0);
        assert!(counters.selected_timebase.is_none());
        for _ in 0..2 {
            assert!(select_feedback_report_with_compatibility(&report, [(0, 4, 4)],
                &scheduler(250), 250, Speed::High, 128, false, &mut counters,
                &mut playback).is_none());
        }
        assert_eq!(select_feedback_report_with_compatibility(&report, [(0, 4, 4)],
            &scheduler(250), 250, Speed::High, 128, false, &mut counters,
            &mut playback), Some((12.0, 48_000.0)));
    }

    #[test]
    fn playback_designs_skips_four_completed_bus_opportunities_across_batches() {
        let mut compatibility = FeedbackCompatibility { tenor_nominal_q16: None, startup_packets_remaining: 4 };
        let mut counters = FeedbackCounters::default();
        let prior_lock = Instant::now();
        counters.last_report_at = Some(prior_lock);
        let report = q16(6.0);
        assert!(select_feedback_report_with_compatibility(&report.repeat(2), [(0, 4, 4); 2],
            &scheduler(125), 125, Speed::High, 7, false, &mut counters, &mut compatibility).is_none());
        // Failed transfers are inspected for trace evidence but consume no skip.
        assert!(inspect_feedback_packets_with_compatibility(&report.repeat(2), [(0, 4, 4); 2],
            &scheduler(125), 125, Speed::High, 7, false, &mut counters,
            LIBUSB_TRANSFER_TIMED_OUT, true, &mut compatibility).is_none());
        assert!(feedback_completion_fault(LIBUSB_TRANSFER_TIMED_OUT, false, 0x81).is_none());
        assert_eq!(compatibility.startup_packets_remaining, 2);
        assert!(counters.selected_timebase.is_none());
        assert!(select_feedback_report_with_compatibility(&report.repeat(2),
            [(LIBUSB_TRANSFER_ERROR, 4, 4), (0, 4, 0)], &scheduler(125), 125, Speed::High,
            7, false, &mut counters, &mut compatibility).is_none());
        assert_eq!(counters.errors, 1);
        assert_eq!(counters.empty_polls, 1);
        assert_eq!(counters.last_report_at, Some(prior_lock));
        assert_eq!(counters.reports, 0);
        let mut bytes = report.to_vec();
        bytes.extend_from_slice(&q16(6.01));
        bytes.extend_from_slice(&q16(48.0)); // newest invalid report cannot replace the good one
        let selected = select_feedback_report_with_compatibility(&bytes, [(0, 4, 4); 3],
            &scheduler(125), 125, Speed::High, 7, false, &mut counters, &mut compatibility).unwrap();
        assert!((selected.0 - 6.01).abs() < 1.0 / 65536.0);
        assert_eq!(counters.rejected, 1);
        let fresh = FeedbackCompatibility { tenor_nominal_q16: None, startup_packets_remaining: 4 };
        assert_eq!(fresh.startup_packets_remaining, 4);
    }

    #[test]
    fn playback_startup_keeps_malformed_safety_and_non_iso_semantics() {
        let mut compatibility = FeedbackCompatibility { tenor_nominal_q16: None, startup_packets_remaining: 4 };
        let mut counters = FeedbackCounters::default();
        assert!(select_feedback_report_with_compatibility(&[0; 16],
            [(0, 4, 5), (0, 4, 2), (0, 4, 0), (LIBUSB_TRANSFER_ERROR, 4, 4)],
            &scheduler(125), 125, Speed::High, 7, false, &mut counters, &mut compatibility).is_none());
        assert_eq!(counters.malformed, 2);
        assert_eq!(counters.rejected, 2);
        assert_eq!(counters.empty_polls, 1);
        assert_eq!(counters.errors, 1);
        assert_eq!(compatibility.startup_packets_remaining, 0);
        for (vendor, pipe) in [(0x23bb, feedback_pipe()), (0x23ba,
            FeedbackEndpoint { transfer_type: TransferType::Interrupt, ..feedback_pipe() })] {
            let mut compatibility = FeedbackCompatibility::for_device(vendor, 1, Speed::High, pipe, 48_000);
            assert_eq!(compatible_report(&q16(6.0), 125, 7, false, &mut compatibility), Some((6.0, 48_000.0)));
        }
    }

    #[test]
    fn newest_fully_valid_poll_wins_at_requested_offsets() {
        let first = q16(6.0);
        let later = q16(6.005);
        // Requested spans deliberately vary; actual bytes are never concatenated.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&first);
        bytes.extend_from_slice(&[0; 6]); // oversized successful poll
        bytes.extend_from_slice(&later); // failed descriptor cannot replace first
        bytes.extend_from_slice(&[0; 4]); // successful empty poll
        bytes.extend_from_slice(&[1, 2]); // malformed trailing poll
        let mut counters = FeedbackCounters::default();
        let packets = [(0, 4, 4), (0, 6, 6), (LIBUSB_TRANSFER_ERROR, 4, 4), (0, 4, 0), (0, 2, 2)];
        assert_eq!(select_feedback_report(&bytes, packets, &scheduler(125), 125, Speed::High,
            7, false, &mut counters), Some((6.0, 48_000.0)));
        assert_eq!(counters.empty_polls, 1);
        assert_eq!(counters.errors, 1);
        assert_eq!(counters.malformed, 2);
        assert_eq!(counters.reports, 0); // scanning never commits the EWMA
        bytes.extend_from_slice(&later);
        let packets = [(0, 4, 4), (0, 6, 6), (LIBUSB_TRANSFER_ERROR, 4, 4), (0, 4, 0), (0, 2, 2), (0, 4, 4)];
        let chosen = select_feedback_report(&bytes, packets, &scheduler(125), 125, Speed::High,
            7, false, &mut counters).unwrap();
        assert!((chosen.0 - 6.005).abs() < 1.0 / 65536.0);
    }

    #[test]
    fn rejects_oversized_truncated_reserved_and_implausible_reports_without_masking_good() {
        let good = q16(6.0);
        let bad_rate = q16(48.0);
        let reserved = [0, 0, 6, 0xf0];
        let mut bytes = good.to_vec();
        bytes.extend_from_slice(&bad_rate);
        bytes.extend_from_slice(&reserved);
        let mut counters = FeedbackCounters::default();
        assert_eq!(select_feedback_report(&bytes, [(0, 4, 4), (0, 4, 4), (0, 4, 4), (0, 4, 5)],
            &scheduler(125), 125, Speed::High, 7, false, &mut counters), Some((6.0, 48_000.0)));
        assert_eq!(counters.rejected, 3);
        assert_eq!(counters.rate_rejected, 1);
        assert_eq!(counters.malformed, 2);
        assert!(decode_feedback_report(&[0, 0, 6, 0, 0], 125, Speed::High).is_none());
        assert!(decode_feedback_report(&good, 1000, Speed::Unknown).is_none());
    }

    #[test]
    fn capacity_checks_fractional_ceiling_after_out_service_scaling() {
        let mut counters = FeedbackCounters::default();
        let report = q16(48.05 / 8.0);
        assert!(select_feedback_report(&report, [(0, 4, 4)], &scheduler(1000), 1000,
            Speed::High, 48, false, &mut counters).is_none());
        let selected = select_feedback_report(&report, [(0, 4, 4)], &scheduler(1000), 1000,
            Speed::High, 49, false, &mut counters).unwrap();
        assert_eq!(selected.0.ceil(), 49.0);
        // Feedback polling interval is deliberately absent from the rate calculation.
        let mut stream = scheduler(1000);
        assert!(stream.update_feedback_frames_per_packet(selected.0));
        let mut total = 0usize;
        let mut packets = 0usize;
        for _ in 0..100 {
            let packet_bytes = stream.next_transfer_packet_bytes();
            packets += packet_bytes.len();
            total += packet_bytes.into_iter().map(|n| n / 8).sum::<usize>();
        }
        assert!((total as f64 - selected.0 * packets as f64).abs() < 1.0);
    }

    #[test]
    fn pipelined_iso_feedback_stays_within_the_poll_packet_budget() {
        let mut endpoint = FeedbackEndpoint {
            refresh: 0,
            address: 0x81,
            transfer_type: TransferType::Isochronous,
            interval: 4,
            service_interval_us: 1000,
            max_packet_bytes: 4,
        };
        assert_eq!(feedback_poll_geometry(endpoint, 16), (2, 8));
        assert_eq!(feedback_poll_geometry(endpoint, 5), (2, 2));
        endpoint.service_interval_us = 125;
        assert_eq!(feedback_poll_geometry(endpoint, 64), (2, 16));
        endpoint.service_interval_us = 32_000;
        assert_eq!(feedback_poll_geometry(endpoint, 16), (1, 1));
        endpoint.transfer_type = TransferType::Interrupt;
        assert_eq!(feedback_poll_geometry(endpoint, 16), (1, 1));
    }

    #[test]
    fn second_poll_submit_failure_retries_without_losing_the_active_poll() {
        let mut transfers = FeedbackTransfers::new(feedback_pipe(), 4,
            FeedbackCompatibility::default()).unwrap();
        assert_eq!(transfers.slots.len(), 2);
        let mut counters = FeedbackCounters::default();
        transfers.slots[0].last_submit_status = Some(0);
        transfers.record_submission(0, Ok(()), &mut counters, true).unwrap();
        transfers.slots[1].last_submit_status = Some(libusb1_sys::constants::LIBUSB_ERROR_IO);
        let before_retry = Instant::now();
        transfers.record_submission(1, Err("transient second poll".into()),
            &mut counters, false).unwrap();
        assert_eq!(transfers.pending.iter().copied().collect::<Vec<_>>(), vec![0]);
        assert!(!transfers.slots[1].in_flight);
        assert!(transfers.slots[1].retry_at >= before_retry + Duration::from_millis(5));
        assert_eq!(counters.errors, 1);
        transfers.slots[1].last_submit_status = Some(0);
        transfers.record_submission(1, Ok(()), &mut counters, false).unwrap();
        assert_eq!(transfers.pending.iter().copied().collect::<Vec<_>>(), vec![0, 1]);
        transfers.slots[1].submit_no_device = true;
        assert!(matches!(transfers.record_submission(1, Err("detached".into()),
            &mut counters, false), Err(FeedbackFault::DeviceLost)));
    }

    #[test]
    fn ordered_dual_polls_share_one_playback_startup_skip_budget() {
        let endpoint = FeedbackEndpoint { service_interval_us: 1000, ..feedback_pipe() };
        let compatibility = FeedbackCompatibility { tenor_nominal_q16: None, startup_packets_remaining: 4 };
        let mut transfers = FeedbackTransfers::new(endpoint, 4, compatibility).unwrap();
        assert_eq!(transfers.slots.len(), 2);
        assert_eq!(transfers.slots[0].packet_count, 2);
        transfers.pending.extend([0, 1]);
        let first = Instant::now();
        // The later poll may publish first, but cannot consume startup skips first.
        for index in [1, 0] {
            let slot = &mut transfers.slots[index];
            unsafe {
                let data = &mut *slot.user_data;
                data.buffer.copy_from_slice(&q16(6.0).repeat(2));
                for packet_index in 0..2 {
                    let packet = &mut *slot.transfer.as_mut().iso_packet_desc.as_mut_ptr().add(packet_index);
                    packet.length = 4;
                    packet.actual_length = 4;
                    packet.status = LIBUSB_TRANSFER_COMPLETED;
                }
                slot.transfer.as_mut().num_iso_packets = 2;
                *data.completion.completed_at.lock().unwrap() = Some(first + Duration::from_millis(index as u64));
                *data.completion.status.lock().unwrap() = Some(LIBUSB_TRANSFER_COMPLETED);
            }
            if index == 1 {
                assert!(transfers.take_next_completion().is_none());
                assert_eq!(transfers.compatibility.startup_packets_remaining, 4);
            }
        }
        let mut counters = FeedbackCounters::default();
        let scheduler = scheduler(1000);
        for expected in 0..2 {
            let (index, status, _, actual) = transfers.take_next_completion().unwrap();
            assert_eq!(index, expected);
            assert!(transfers.slots[index].newest_valid_report(&scheduler, 1000,
                Speed::High, 49, false, &mut counters, actual, status,
                &mut transfers.compatibility).is_none());
        }
        assert_eq!(transfers.compatibility.startup_packets_remaining, 0);
        assert!(counters.selected_timebase.is_none());
        // The next poll accepts the newest plausible report and rejects its later bad packet.
        unsafe {
            (&mut *transfers.slots[0].user_data).buffer[4..8].copy_from_slice(&q16(48.0));
        }
        assert_eq!(transfers.slots[0].newest_valid_report(&scheduler, 1000,
            Speed::High, 49, false, &mut counters, 8, LIBUSB_TRANSFER_COMPLETED,
            &mut transfers.compatibility), Some((48.0, 48_000.0)));
        assert_eq!(counters.rejected, 1);
        assert!(transfers.take_next_completion().is_none());
    }

    #[test]
    fn dual_poll_enhanced_feedback_keeps_exact_eight_byte_reports() {
        let endpoint = FeedbackEndpoint { max_packet_bytes: 8, service_interval_us: 1000, ..feedback_pipe() };
        let mut transfers = FeedbackTransfers::new(endpoint, 4,
            FeedbackCompatibility::default()).unwrap();
        let mut counters = FeedbackCounters::default();
        let report = (6u64 << 32).to_le_bytes();
        let slot = &mut transfers.slots[1];
        unsafe {
            (&mut *slot.user_data).buffer.copy_from_slice(&report.repeat(2));
            slot.transfer.as_mut().num_iso_packets = 2;
            for (index, actual) in [8, 4].into_iter().enumerate() {
                let packet = &mut *slot.transfer.as_mut().iso_packet_desc.as_mut_ptr().add(index);
                packet.length = 8;
                packet.actual_length = actual;
                packet.status = LIBUSB_TRANSFER_COMPLETED;
            }
        }
        assert_eq!(slot.newest_valid_report(&scheduler(1000), 1000,
            Speed::Super, 49, false, &mut counters, 12, LIBUSB_TRANSFER_COMPLETED,
            &mut transfers.compatibility), Some((48.0, 48_000.0)));
        assert_eq!(counters.last_report_len, 8);
        assert_eq!(counters.rejected, 1);
    }

    #[test]
    fn trace_distinguishes_rejected_rate_and_capacity_from_transport_failures() {
        use crate::ExplicitFeedbackOutcome as Outcome;
        let recorder = Arc::new(crate::feedback_diagnostics::FeedbackRecorder::new(Instant::now()));
        let mut counters = FeedbackCounters {
            trace: Some(recorder),
            diagnostics: Some(crate::ExplicitFeedbackDiagnostics::default()),
            ..Default::default()
        };
        let rate = q16(48.0);
        assert!(select_feedback_report(&rate, [(0, 4, 4)], &scheduler(250), 250,
            Speed::High, 128, false, &mut counters).is_none());
        let capacity = q16(6.005);
        assert!(select_feedback_report(&capacity, [(0, 4, 4)], &scheduler(125), 125,
            Speed::High, 6, false, &mut counters).is_none());
        let mut partial = q16(6.0).to_vec();
        partial.extend_from_slice(&[0; 4]);
        assert!(inspect_feedback_packets(&partial,
            [(0, 4, 4), (NO_FEEDBACK_PACKET_STATUS, 4, 0)], &scheduler(125), 125,
            Speed::High, 7, false, &mut counters, LIBUSB_TRANSFER_TIMED_OUT, true).is_none());
        let diagnostics = counters.diagnostics.unwrap();
        let sample = |outcome| diagnostics.packet_samples().find(|sample| sample.outcome == outcome).unwrap();
        assert_eq!(sample(Outcome::RateOutOfRange).decoded_rate_hz, Some(384_000.0));
        assert_eq!(sample(Outcome::RateOutOfRange).raw_bytes(), rate);
        assert_eq!(sample(Outcome::PacketCapacityExceeded).raw_bytes(), capacity);
        assert_eq!(sample(Outcome::TransferFailed).transfer_status, LIBUSB_TRANSFER_TIMED_OUT);
        assert_eq!(sample(Outcome::TransferFailed).packet_status, Some(0));
        assert_eq!(sample(Outcome::TransferFailed).raw_bytes(), &partial[..4]);
        assert_eq!(diagnostics.packet_status_counts[7], 1);
    }

    #[test]
    fn summary_has_no_raw_bytes_with_trace_disabled() {
        let mut counters = FeedbackCounters {
            diagnostics: Some(crate::ExplicitFeedbackDiagnostics::default()),
            ..Default::default()
        };
        let report = q16(48.0);
        select_feedback_report(&report, [(0, 4, 4)], &scheduler(125), 125,
            Speed::High, 7, false, &mut counters);
        let diagnostics = counters.diagnostics.unwrap();
        let sample = diagnostics.packet_samples().next().unwrap();
        assert_eq!(sample.outcome, crate::ExplicitFeedbackOutcome::RateOutOfRange);
        assert_eq!(sample.actual_bytes, 4);
        assert!(sample.raw_bytes().is_empty());
    }

    #[test]
    fn ap80_pcm_report_calibrates_from_three_completions_and_keeps_that_timebase() {
        // AP80 Pro-X c502:0072, 16-bit stereo PCM, alt 2. OUT is serviced
        // every 250 us and the IN feedback is polled every 1 ms.
        let report = [0x46, 0x09, 0x0b, 0x00];
        let standard = q16(44_100.0 / 8000.0);
        let scheduler = IsoPacketScheduler::new(44_100, 4, 250);
        let mut counters = FeedbackCounters {
            infer_service_interval: true,
            diagnostics: Some(crate::ExplicitFeedbackDiagnostics::default()),
            ..Default::default()
        };
        // Two reports in a single completion still count as one observation.
        let batch = [report, report].concat();
        assert!(select_feedback_report(&batch, [(0, 4, 4), (0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());
        assert!(select_feedback_report(&report, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());
        let (frames, rate) = select_feedback_report(&report, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).unwrap();
        assert!((frames - 11.036_224).abs() < 0.000_001);
        assert!((rate - 44_144.897).abs() < 0.001);
        let diagnostics = counters.diagnostics.unwrap();
        assert_eq!(diagnostics.timebase, Some("out_service_interval"));
        assert!(diagnostics.inferred_timebase);
        // A later report with different units is refused.
        assert!(select_feedback_report(&standard, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());
    }

    #[test]
    fn ap80_native_dsd_feedback_calibrates_at_all_measured_wire_rates() {
        for (rate, report) in [
            (88_200, [0xa2, 0x10, 0x16, 0]),
            (176_400, [0x2e, 0x1d, 0x2c, 0]),
            (352_800, [0x0a, 0x37, 0x58, 0]),
        ] {
            let scheduler = IsoPacketScheduler::new(rate, 8, 250);
            let mut counters = FeedbackCounters {
                infer_service_interval: true,
                ..Default::default()
            };
            for _ in 0..2 {
                assert!(select_feedback_report(&report, [(0, 4, 4)], &scheduler,
                    250, Speed::High, 128, false, &mut counters).is_none());
            }
            let (_, decoded) = select_feedback_report(&report, [(0, 4, 4)], &scheduler,
                250, Speed::High, 128, false, &mut counters).unwrap();
            assert!((decoded - f64::from(rate)).abs() < 65.0);
            assert!(counters.selected_service_interval());
        }
    }

    #[test]
    fn calibration_requires_verified_rate_and_prefers_a_valid_standard_report() {
        let alternate = q16(11.025);
        let standard = q16(5.5125);
        let scheduler = IsoPacketScheduler::new(44_100, 4, 250);
        let mut counters = FeedbackCounters::default();
        for _ in 0..4 {
            assert!(select_feedback_report(&alternate, [(0, 4, 4)], &scheduler,
                250, Speed::High, 256, false, &mut counters).is_none());
        }
        assert!(counters.selected_timebase.is_none());
        counters.infer_service_interval = true;
        // The alternate interpretation needs at least 12 frames of capacity.
        for _ in 0..4 {
            assert!(select_feedback_report(&alternate, [(0, 4, 4)], &scheduler,
                250, Speed::High, 11, false, &mut counters).is_none());
        }
        assert!(counters.selected_timebase.is_none());
        let batch = [alternate, standard, alternate].concat();
        let (_, rate) = select_feedback_report(&batch, [(0, 4, 4); 3], &scheduler,
            250, Speed::High, 256, false, &mut counters).unwrap();
        assert!((rate - 44_100.0).abs() < 0.1);
        assert_eq!(counters.selected_timebase, Some(FeedbackTimebase::Bus));
        assert!(select_feedback_report(&alternate, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());
    }

    #[test]
    fn saved_units_still_require_a_fresh_report_and_clock() {
        let alternate = q16(12.0);
        let scheduler = IsoPacketScheduler::new(48_000, 4, 250);
        let mut counters = FeedbackCounters {
            cached_service_interval: true,
            diagnostics: Some(crate::ExplicitFeedbackDiagnostics::default()),
            ..Default::default()
        };
        assert!(select_feedback_report(&alternate, [(0, 4, 0)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());
        assert!(counters.selected_timebase.is_none());
        assert!(select_feedback_report(&alternate, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters).is_none());

        // A second stream at a different rate can reuse the saved units after
        // checking them against its own readback and packet capacity.
        counters.infer_service_interval = true;
        counters.cached_service_interval = true;
        assert_eq!(select_feedback_report(&alternate, [(0, 4, 4)], &scheduler,
            250, Speed::High, 256, false, &mut counters), Some((12.0, 48_000.0)));
        assert!(counters.selected_service_interval());
        assert!(counters.diagnostics.unwrap().reused_timebase);
    }

    #[test]
    fn standard_timing_supersedes_saved_service_interval_units() {
        let scheduler = IsoPacketScheduler::new(48_000, 4, 250);
        let mut counters = FeedbackCounters {
            infer_service_interval: true,
            cached_service_interval: true,
            ..Default::default()
        };
        let batch = [q16(12.0), q16(6.0)].concat();
        assert_eq!(select_feedback_report(&batch, [(0, 4, 4); 2], &scheduler,
            250, Speed::High, 256, false, &mut counters), Some((12.0, 48_000.0)));
        assert_eq!(counters.selected_timebase, Some(FeedbackTimebase::Bus));
    }

    #[test]
    fn linux_uac2_gadget_per_service_vector_requires_opt_in() {
        // Linux v7.0 u_audio.c u_audio_set_fback_frequency: a 1 ms HS OUT
        // service can report 48 Q16.16 frames per OUT packet rather than 6
        // per USB microframe. Enable only after the device trace proves units.
        let report = q16(48.0);
        let mut counters = FeedbackCounters::default();
        assert!(select_feedback_report(&report, [(0, 4, 4)], &scheduler(1000), 1000,
            Speed::High, 49, false, &mut counters).is_none());
        assert_eq!(select_feedback_report(&report, [(0, 4, 4)], &scheduler(1000), 1000,
            Speed::High, 49, true, &mut counters), Some((48.0, 48_000.0)));
        assert_eq!(decode_feedback_report_with_scale(&report, 1000, Speed::Super, true),
            decode_feedback_report(&report, 1000, Speed::Super));
        assert_eq!(decode_feedback_report_with_scale(&[0, 0, 12], 1000, Speed::High, true),
            decode_feedback_report(&[0, 0, 12], 1000, Speed::High));
        assert_eq!(decode_feedback_report_with_scale(&[0, 0, 12], 1000, Speed::Full, true),
            Some((48.0, 48_000.0)));
    }

    #[test]
    fn nominal_warmup_stale_recovery_and_terminal_deadline_follow_last_actual_report() {
        let health = ExplicitFeedbackHealth::new(1000, None);
        let start = Instant::now();
        assert_eq!(health.state(start, start, None), (false, false, false));
        assert_eq!(health.state(start + Duration::from_millis(500), start, None), (false, true, false));
        assert_eq!(health.state(start + Duration::from_secs(1), start, None), (false, true, true));
        let good = start + Duration::from_millis(100);
        assert_eq!(health.state(good, start, Some(good)), (true, false, false));
        assert_eq!(health.state(start + Duration::from_millis(600), start, Some(good)), (false, true, false));
        let recovered = start + Duration::from_millis(900);
        assert_eq!(health.state(recovered, start, Some(recovered)), (true, false, false));
        // Empty success produces no report and cannot refresh the clock or last rate.
        let mut counters = FeedbackCounters { last_report_at: Some(good), ..Default::default() };
        assert!(select_feedback_report(&[0; 4], [(0, 4, 0)], &scheduler(125), 125,
            Speed::High, 7, false, &mut counters).is_none());
        assert_eq!(counters.last_report_at, Some(good));
        assert_eq!(health.state(start + Duration::from_millis(1100), start, counters.last_report_at), (false, true, true));
    }

    #[test]
    fn first_submit_failure_is_terminal_and_detach_is_distinct() {
        assert!(matches!(feedback_submit_failure("allocation/submit error".into(), false, true),
            Some(FeedbackFault::Transfer(_))));
        assert!(feedback_submit_failure("transient".into(), false, false).is_none());
        assert!(matches!(feedback_submit_failure("detached".into(), true, true), Some(FeedbackFault::DeviceLost)));
        assert!(matches!(feedback_submit_failure("detached".into(), true, false), Some(FeedbackFault::DeviceLost)));
        assert!(matches!(feedback_completion_fault(LIBUSB_TRANSFER_NO_DEVICE, false, 0x81), Some(FeedbackFault::DeviceLost)));
        assert!(feedback_completion_fault(LIBUSB_TRANSFER_CANCELLED, true, 0x81).is_none());
        assert!(matches!(feedback_completion_fault(LIBUSB_TRANSFER_CANCELLED, false, 0x81), Some(FeedbackFault::Transfer(_))));
        assert!(feedback_completion_fault(LIBUSB_TRANSFER_TIMED_OUT, false, 0x81).is_none());
        assert!(feedback_completion_fault(LIBUSB_TRANSFER_OVERFLOW, false, 0x81).is_none());
    }

    #[test]
    fn a_late_completion_cannot_renew_an_expired_feedback_lease() {
        let health = ExplicitFeedbackHealth::new(1000, None);
        let start = Instant::now();
        let at_deadline = start + health.terminal;
        let before_deadline = at_deadline - Duration::from_micros(1);
        assert!(health.report_is_timely(before_deadline, start, None));
        assert!(!health.report_is_timely(at_deadline, start, None));
        assert!(!health.report_is_timely(at_deadline + Duration::from_micros(1), start, None));
        // Processing after the old deadline is fine if the callback was timely:
        // its new age is measured from the true completion, not processing time.
        let processed = at_deadline + Duration::from_millis(5);
        assert_eq!(health.state(processed, start, Some(before_deadline)), (true, false, false));
        let prior_good = start + Duration::from_millis(200);
        assert!(health.report_is_timely(prior_good + health.terminal - Duration::from_micros(1), start, Some(prior_good)));
        assert!(!health.report_is_timely(prior_good + health.terminal, start, Some(prior_good)));
    }

    #[test]
    fn deadlines_honor_valid_uac1_refresh_and_sparse_polling() {
        let slow = ExplicitFeedbackHealth::new(1000, Some(9));
        assert_eq!(slow.warning, Duration::from_millis(1536));
        assert_eq!(slow.terminal, Duration::from_millis(3072));
        let invalid = ExplicitFeedbackHealth::new(1000, Some(10));
        assert_eq!(invalid.warning, Duration::from_millis(500));
        assert_eq!(ExplicitFeedbackHealth::new(1_024_000, None).terminal, Duration::from_millis(6144));
    }
}