atdecc 0.1.2

IEEE 1722.1 ATDECC (AVDECC) with Milan: frames, controller and entity state machines, without I/O
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
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
//! The controller role, without I/O: the caller passes in received frames
//! and the time, and takes back frames to send, events and the next
//! deadline.
//!
//! It discovers entities (IEEE 1722.1-2021, 6.2.6), reads the descriptors
//! of those that support AEM, asks Milan entities for their Milan
//! information, registers for unsolicited notifications and re-reads what
//! they report changed, answers the CONTROLLER_AVAILABLE checks of the
//! entities it registered with (Milan 1.3, 5.4.5.4), and can advertise
//! itself.

use alloc::collections::{BTreeMap, VecDeque};
use alloc::vec::Vec;
use core::time::Duration;

use avb_mrp::msrp;
use avb_net::MacAddress;

use crate::acmp::{AcmpFlags, AcmpMessageType, AcmpStatus, Acmpdu};
use crate::adp::{AdpMessageType, Adpdu, ControllerCapabilities, EntityCapabilities};
use crate::aecp::{
    AaMode, AaStatus, AaTlv, AddressAccessPdu, AecpHeader, AecpMessageType, AemCommandType, AemPdu,
    AemStatus, VendorUniquePdu,
};
use crate::aem::{
    self, Addressing, AsPath, AudioMap, AudioMapping, AudioMappings, AvbInfo, Counters,
    DynamicQuery, MappingChange, MaxTransitTime, ReadDescriptorResponse, SetClockSource, SetName,
    SetSamplingRate, SetStreamFormat, StreamInfo, StreamInfoFlags,
};
use crate::cache::{CachedModel, ModelKey};
use crate::descriptor::{
    AudioUnitDescriptor, ConfigurationDescriptor, DescriptorType, EntityDescriptor,
    LocaleDescriptor, MemoryObjectDescriptor, MemoryObjectType, SamplingRate, StreamPortDescriptor,
};
use crate::error::{DecodeError, EncodeError};
use crate::id::{EntityId, EntityModelId};
use crate::lite::{self, CvuMessage, LiteCommandType, LiteMessage, LiteStatus};
use crate::model::{Binding, EntityModel, EnumerationFailure, EnumerationState, TxState, Wireless};
use crate::mvu::{self, MediaClockReference, MilanInfo, MvuCommandType, MvuMessage};
use crate::pdu::{self, Pdu};
use crate::stream_format::StreamFormat;
use crate::time::Instant;
use crate::wireless::{self, WirelessCommandType, WirelessMessage, WirelessStatus};

/// How long a command waits for its response before its one retry
/// (IEEE 1722.1-2021, 9.3.2.6).
pub const COMMAND_TIMEOUT: Duration = Duration::from_millis(250);

/// How long a CVU SRP declaration lasts without a refresh: well past
/// MSRP's LeaveAll period of 10 s (IEEE 802.1Q-2022, 10.7.11).
const CVU_LIFETIME: Duration = Duration::from_secs(30);

/// The most descriptors read from one entity, against counts no entity
/// could mean.
const MAX_DESCRIPTORS: usize = 4096;

/// Top level descriptors read from each configuration; STREAM_PORT,
/// AUDIO_CLUSTER, AUDIO_MAP and STRINGS are read as children of these.
const READ_TYPES: [DescriptorType; 11] = [
    DescriptorType::AUDIO_UNIT,
    DescriptorType::STREAM_INPUT,
    DescriptorType::STREAM_OUTPUT,
    DescriptorType::JACK_INPUT,
    DescriptorType::JACK_OUTPUT,
    DescriptorType::AVB_INTERFACE,
    DescriptorType::CLOCK_SOURCE,
    DescriptorType::MEMORY_OBJECT,
    DescriptorType::LOCALE,
    DescriptorType::CONTROL,
    DescriptorType::CLOCK_DOMAIN,
];

/// Descriptors whose every field stays the same for entities of a model,
/// which a cached model can stand in for without asking again.
const STATIC_TYPES: [DescriptorType; 5] = [
    DescriptorType::STRINGS,
    DescriptorType::LOCALE,
    DescriptorType::AUDIO_MAP,
    DescriptorType::STREAM_PORT_INPUT,
    DescriptorType::STREAM_PORT_OUTPUT,
];

/// Descriptors holding what differs between entities of a model, such as
/// an interface's MAC address and clock identity or a clock source's
/// identifier; always read from the entity.
const OWN_TYPES: [DescriptorType; 4] = [
    DescriptorType::ENTITY,
    DescriptorType::CONFIGURATION,
    DescriptorType::AVB_INTERFACE,
    DescriptorType::CLOCK_SOURCE,
];

/// Unanswered AVB Wireless status queries before an entity is taken not
/// to answer them: a Wi-Fi hop loses frames, and a bridge under load can
/// stall for seconds, so one silence is not an answer.
const WIRELESS_MISSES: u8 = 3;

/// The most values one GET_DYNAMIC_INFO asks for.
const MAX_DYNAMIC_QUERIES: usize = 16;

/// The largest logo read, against lengths no image needs.
const MAX_LOGO: u64 = 1 << 20;

/// The most octets of a memory object one Address Access response
/// carries, in a TLV of its own.
const MEMORY_SEGMENT: u64 = (AddressAccessPdu::MAX_TLVS_LEN - AaTlv::HEADER_LEN) as u64;

/// The most parts a stream port's dynamic mappings are read in, against
/// counts no entity could mean; Milan's parts hold up to 176 mappings.
const MAX_MAP_PARTS: u16 = 256;

/// How the controller identifies and behaves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    /// The controller's entity ID, in the commands it sends.
    pub entity_id: EntityId,
    /// Read the descriptors of each entity that supports AEM.
    pub enumerate: bool,
    /// Register for unsolicited notifications once an entity is read.
    pub register_unsolicited: bool,
    /// Ask each AVB interface for its gPTP and SRP state, its gPTP path
    /// and its counters once an entity is read.
    pub network_info: bool,
    /// Read each stream port's dynamic mappings once an entity is read.
    pub read_mappings: bool,
    /// Ask each Milan entity's clock domains for their media clock
    /// reference priority and domain name once it is read.
    pub media_clock_info: bool,
    /// Ask each clock domain, stream input and stream output for its
    /// counters once an entity is read; Milan entities then report
    /// changes.
    pub read_counters: bool,
    /// Ask each Milan entity's stream outputs for their max transit time
    /// once it is read.
    pub read_transit_times: bool,
    /// Read an entity's other configurations and their streams once it is
    /// read, to tell them apart.
    pub read_configurations: bool,
    /// Ask a talker for each stream output's state, and the listeners of
    /// its connections where it keeps them, as talkers outside Milan do,
    /// once the output's stream info is read and whenever it changes.
    pub read_talker_state: bool,
    /// Ask each entity for its AVB Lite status once it is read, and keep
    /// asking those that answer every `lite_poll`, zero for never, to
    /// follow their PTP offset.
    pub lite_status: bool,
    pub lite_poll: Duration,
    /// Ask each entity's AVB interfaces for their AVB Wireless status once
    /// it is read, and keep asking the wireless ones every
    /// `wireless_poll`, zero for never, to follow their link and time.
    pub wireless_status: bool,
    pub wireless_poll: Duration,
    /// Read each entity's logos, its own and its vendor's, through Address
    /// Access once it is read, where it advertises Address Access.
    pub read_logos: bool,
    /// The controller's own MAC address, where entities advertised from
    /// it are out of its reach: it does not read them.
    pub own_mac: Option<MacAddress>,
    /// Advertise the controller with ADP.
    pub advertise: Option<Advertise>,
    /// The first sequence ID of AEM and of MVU commands.
    pub first_sequence_id: u16,
    /// Seeds the random delays ADP calls for.
    pub random_seed: u64,
}

impl Config {
    pub fn new(entity_id: EntityId) -> Self {
        Self {
            entity_id,
            enumerate: true,
            register_unsolicited: true,
            network_info: true,
            read_mappings: true,
            media_clock_info: true,
            read_counters: true,
            read_transit_times: true,
            read_configurations: true,
            read_talker_state: true,
            lite_status: true,
            lite_poll: Duration::from_secs(5),
            wireless_status: true,
            wireless_poll: Duration::from_secs(5),
            read_logos: true,
            own_mac: None,
            advertise: None,
            first_sequence_id: 0,
            random_seed: entity_id.0,
        }
    }
}

/// How the controller advertises itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Advertise {
    pub entity_model_id: EntityModelId,
    /// In units of 2 seconds, 1 to 31.
    pub valid_time: u8,
}

/// An entity the controller has heard advertise itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiscoveredEntity {
    /// Its latest ENTITY_AVAILABLE.
    pub adp: Adpdu,
    /// The source address of that advertisement.
    pub mac: MacAddress,
    pub first_seen: Instant,
    pub last_seen: Instant,
    /// When it is forgotten unless it advertises again.
    pub expires: Instant,
}

impl DiscoveredEntity {
    pub fn entity_id(&self) -> EntityId {
        self.adp.entity_id
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OfflineReason {
    /// It sent ENTITY_DEPARTING.
    Departed,
    /// It stopped advertising for longer than its valid time.
    TimedOut,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
    /// A new entity, or one back after going offline.
    EntityOnline(EntityId),
    /// An entity advertised different capabilities, grandmaster, configuration or
    /// address.
    EntityChanged(EntityId),
    /// An entity's available_index went back, so it restarted; its model
    /// is read again.
    EntityRestarted(EntityId),
    EntityOffline(EntityId, OfflineReason),
    /// Reading an entity's descriptors began.
    EnumerationStarted(EntityId),
    /// All of an entity's descriptors that could be read were.
    EntityEnumerated(EntityId),
    /// The ENTITY or CONFIGURATION descriptor could not be read.
    EnumerationFailed(EntityId, EnumerationFailure),
    /// A descriptor read again after a notification changed, or a stream's
    /// binding or info did.
    EntityModelChanged(EntityId),
    /// A command the caller asked for finished.
    CommandFinished(CommandId, Outcome),
}

/// Identifies a command the caller asked for, in
/// [`Event::CommandFinished`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CommandId(pub u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    Done,
    /// The entity answered with an error.
    Refused(Refusal),
    /// No response, after a retry.
    NoResponse,
    /// The entity is not online, went away before answering, or lacks what
    /// the command needs, such as an identify control.
    NotPossible,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
    Acmp(AcmpStatus),
    Aem(AemStatus),
}

/// A frame for the caller to send: `length` octets at the start of the
/// buffer given to [`Controller::poll_transmit`], on the AVTP ethertype.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Transmit {
    pub destination: MacAddress,
    pub length: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Request {
    ReadDescriptor {
        descriptor_type: DescriptorType,
        index: u16,
        /// Read again after a notification, not as part of enumeration.
        refresh: bool,
    },
    GetMilanInfo,
    /// GET_MEDIA_CLOCK_REFERENCE_INFO for a CLOCK_DOMAIN.
    GetMediaClockReference {
        domain: u16,
    },
    RegisterUnsolicited,
    GetRxState {
        input: u16,
    },
    GetStreamInfo {
        descriptor_type: DescriptorType,
        index: u16,
    },
    GetAvbInfo {
        index: u16,
    },
    GetAsPath {
        index: u16,
    },
    GetCounters {
        descriptor_type: DescriptorType,
        index: u16,
    },
    Bind {
        talker: EntityId,
        talker_unique_id: u16,
        input: u16,
        /// The talker's stream is class B, so the connect says so.
        class_b: bool,
        command: CommandId,
    },
    Unbind {
        talker: EntityId,
        talker_unique_id: u16,
        input: u16,
        command: CommandId,
    },
    Identify {
        control: u16,
        on: bool,
        command: Option<CommandId>,
    },
    /// SET_NAME; its configuration is the entity's when it is sent.
    SetName {
        set: SetName,
        command: CommandId,
    },
    SetStreamFormat {
        set: SetStreamFormat,
        command: CommandId,
    },
    /// START_STREAMING, or STOP_STREAMING where `start` is false.
    Streaming {
        descriptor_type: DescriptorType,
        index: u16,
        start: bool,
        command: CommandId,
    },
    SetSamplingRate {
        set: SetSamplingRate,
        command: CommandId,
    },
    SetClockSource {
        set: SetClockSource,
        command: CommandId,
    },
    SetConfiguration {
        configuration: u16,
        command: CommandId,
    },
    /// A descriptor of another configuration than the one read.
    ReadOther {
        configuration: u16,
        descriptor_type: DescriptorType,
        index: u16,
    },
    /// One part of a stream port's dynamic mappings.
    GetAudioMap {
        descriptor_type: DescriptorType,
        index: u16,
        map_index: u16,
    },
    /// ADD_AUDIO_MAPPINGS or REMOVE_AUDIO_MAPPINGS on a stream port; the
    /// mappings wait in the controller's `mapping_changes`.
    ChangeMappings {
        change: MappingChange,
        descriptor_type: DescriptorType,
        index: u16,
        command: CommandId,
    },
    /// SET_CONTROL; the values wait in the controller's `control_values`.
    SetControl {
        index: u16,
        command: CommandId,
    },
    /// GET_TX_STATE to a talker about a stream output.
    GetTxState {
        output: u16,
        command: Option<CommandId>,
    },
    /// GET_TX_CONNECTION to a talker: the listener of one of a stream
    /// output's connections, by its index.
    GetTxConnection {
        output: u16,
        index: u16,
        command: Option<CommandId>,
    },
    /// DISCONNECT_TX to a talker, for a listener's stream input, without
    /// the listener taking part.
    DisconnectTx {
        output: u16,
        listener: EntityId,
        listener_unique_id: u16,
        command: CommandId,
    },
    GetMaxTransitTime {
        output: u16,
        command: Option<CommandId>,
    },
    SetMaxTransitTime {
        set: MaxTransitTime,
        command: CommandId,
    },
    /// The AVB Lite status of an AVB_INTERFACE (AVB Lite profile, 2.4).
    GetLiteStatus {
        interface: u16,
    },
    /// How an AVB_INTERFACE runs AVB Lite (SET_LITE_CONFIG).
    SetLiteConfig {
        interface: u16,
        flags: u8,
        command: CommandId,
    },
    /// The AVB Wireless status of an AVB_INTERFACE (AVB Wireless profile,
    /// 5.1).
    GetWirelessStatus {
        interface: u16,
    },
    /// An AVB_INTERFACE's AVB Wireless configuration (SET_WIRELESS_CONFIG).
    SetWirelessConfig {
        interface: u16,
        flags: u8,
        command: CommandId,
    },
    /// READ_DESCRIPTOR the caller asked for, outside enumeration.
    ReadForCaller {
        descriptor_type: DescriptorType,
        index: u16,
        command: CommandId,
    },
    /// What changes on an entity whose descriptors came from the cache.
    GetDynamicInfo {
        queries: [DynamicQuery; MAX_DYNAMIC_QUERIES],
        count: u8,
    },
    /// One part of a memory object's octets, from `offset`, read through
    /// Address Access: a logo.
    ReadMemory {
        index: u16,
        offset: u32,
    },
}

/// The protocols whose commands are numbered apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Channel {
    Aem,
    Mvu,
    Acmp,
    AddressAccess,
}

impl Request {
    fn channel(self) -> Channel {
        match self {
            // Vendor unique commands, numbered apart from AEM.
            Request::GetMilanInfo
            | Request::GetMediaClockReference { .. }
            | Request::GetLiteStatus { .. }
            | Request::SetLiteConfig { .. }
            | Request::GetWirelessStatus { .. }
            | Request::SetWirelessConfig { .. } => Channel::Mvu,
            Request::GetRxState { .. }
            | Request::Bind { .. }
            | Request::Unbind { .. }
            | Request::GetTxState { .. }
            | Request::GetTxConnection { .. }
            | Request::DisconnectTx { .. } => Channel::Acmp,
            Request::ReadMemory { .. } => Channel::AddressAccess,
            _ => Channel::Aem,
        }
    }

    /// The ACMP message the request is sent as.
    fn acmp_message(self) -> Option<AcmpMessageType> {
        match self {
            Request::GetRxState { .. } => Some(AcmpMessageType::GET_RX_STATE_COMMAND),
            Request::Bind { .. } => Some(AcmpMessageType::CONNECT_RX_COMMAND),
            Request::GetTxState { .. } => Some(AcmpMessageType::GET_TX_STATE_COMMAND),
            Request::GetTxConnection { .. } => Some(AcmpMessageType::GET_TX_CONNECTION_COMMAND),
            Request::DisconnectTx { .. } => Some(AcmpMessageType::DISCONNECT_TX_COMMAND),
            Request::Unbind { .. } => Some(AcmpMessageType::DISCONNECT_RX_COMMAND),
            _ => None,
        }
    }

    /// The caller's command, for requests the caller asked for.
    fn command(self) -> Option<CommandId> {
        match self {
            Request::Bind { command, .. }
            | Request::Unbind { command, .. }
            | Request::SetName { command, .. }
            | Request::SetStreamFormat { command, .. }
            | Request::Streaming { command, .. }
            | Request::SetSamplingRate { command, .. }
            | Request::SetClockSource { command, .. }
            | Request::SetConfiguration { command, .. }
            | Request::SetControl { command, .. }
            | Request::DisconnectTx { command, .. }
            | Request::SetMaxTransitTime { command, .. }
            | Request::ReadForCaller { command, .. }
            | Request::SetLiteConfig { command, .. }
            | Request::SetWirelessConfig { command, .. }
            | Request::ChangeMappings { command, .. } => Some(command),
            Request::Identify { command, .. }
            | Request::GetTxState { command, .. }
            | Request::GetTxConnection { command, .. }
            | Request::GetMaxTransitTime { command, .. } => command,
            _ => None,
        }
    }
}

/// A command waiting for its response.
#[derive(Debug, Clone, Copy)]
struct Inflight {
    entity_id: EntityId,
    request: Request,
    deadline: Instant,
    retried: bool,
}

/// The commands queued for one entity; one is in flight at a time.
#[derive(Debug, Default)]
struct Session {
    queue: VecDeque<Request>,
    inflight: Option<(Channel, u16)>,
    /// Descriptors queued or read during this enumeration.
    requested: usize,
}

/// A small xorshift generator for ADP's random delays.
#[derive(Debug, Clone, Copy)]
struct Random(u64);

impl Random {
    fn new(seed: u64) -> Self {
        Self(seed | 1)
    }

    /// A duration from zero to `limit`.
    fn up_to(&mut self, limit: Duration) -> Duration {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        let millis = limit.as_millis() as u64;
        Duration::from_millis(if millis == 0 {
            0
        } else {
            self.0 % (millis + 1)
        })
    }
}

#[derive(Debug)]
struct Advertiser {
    config: Advertise,
    available_index: u32,
    next: Option<Instant>,
    started: bool,
}

impl Advertiser {
    fn valid(&self) -> Duration {
        Duration::from_secs(2 * u64::from(self.config.valid_time.clamp(1, 31)))
    }

    /// The longest random delay before advertising: a fifth of the valid
    /// time (6.2.4.2.2), and no more than a second, so other controllers
    /// see this one promptly.
    fn delay_limit(&self) -> Duration {
        (self.valid() / 5).min(Duration::from_secs(1))
    }
}

pub struct Controller {
    config: Config,
    entities: BTreeMap<EntityId, DiscoveredEntity>,
    models: BTreeMap<EntityId, EntityModel>,
    sessions: BTreeMap<EntityId, Session>,
    inflight: BTreeMap<(Channel, u16), Inflight>,
    next_aem_sequence: u16,
    next_mvu_sequence: u16,
    next_acmp_sequence: u16,
    next_address_access_sequence: u16,
    next_command: u32,
    /// When to turn each identifying entity's identify control off.
    identify_off: BTreeMap<EntityId, (Instant, u16)>,
    /// When to ask the entities that answer it for their AVB Lite status
    /// again.
    next_lite_poll: Option<Instant>,
    /// When to ask the wireless interfaces for their AVB Wireless status
    /// again.
    next_wireless_poll: Option<Instant>,
    /// Entity models read before, by what they are for.
    cache: BTreeMap<ModelKey, CachedModel>,
    /// The mappings of each mapping change queued or in flight.
    mapping_changes: BTreeMap<CommandId, Vec<AudioMapping>>,
    /// The values of each SET_CONTROL waiting to go.
    control_values: BTreeMap<CommandId, Vec<u8>>,
    /// The octets read so far of each memory object being read, by entity
    /// and MEMORY_OBJECT index.
    memory_reads: BTreeMap<(EntityId, u16), Vec<u8>>,
    advertiser: Option<Advertiser>,
    random: Random,
    outgoing: VecDeque<(MacAddress, Vec<u8>)>,
    events: VecDeque<Event>,
    malformed: u64,
}

impl Controller {
    pub fn new(config: Config) -> Self {
        Self {
            config,
            entities: BTreeMap::new(),
            models: BTreeMap::new(),
            sessions: BTreeMap::new(),
            inflight: BTreeMap::new(),
            next_aem_sequence: config.first_sequence_id,
            next_mvu_sequence: config.first_sequence_id,
            next_acmp_sequence: config.first_sequence_id,
            next_address_access_sequence: config.first_sequence_id,
            next_command: 0,
            identify_off: BTreeMap::new(),
            next_lite_poll: None,
            next_wireless_poll: None,
            cache: BTreeMap::new(),
            mapping_changes: BTreeMap::new(),
            control_values: BTreeMap::new(),
            memory_reads: BTreeMap::new(),
            advertiser: config.advertise.map(|advertise| Advertiser {
                config: advertise,
                available_index: 0,
                next: None,
                started: false,
            }),
            random: Random::new(config.random_seed),
            outgoing: VecDeque::new(),
            events: VecDeque::new(),
            malformed: 0,
        }
    }

    pub fn entity_id(&self) -> EntityId {
        self.config.entity_id
    }

    /// Asks `entity`, or every entity when `None`, to advertise itself
    /// now rather than at its next periodic advertisement.
    pub fn discover(&mut self, entity: Option<EntityId>) {
        let adpdu = Adpdu::discover(entity.unwrap_or_default());
        self.queue_adp(&adpdu);
    }

    /// Reads an entity's descriptors again.
    pub fn enumerate(&mut self, now: Instant, entity_id: EntityId) {
        if self.entities.contains_key(&entity_id) {
            self.start_enumeration(now, entity_id);
        }
    }

    /// Advertises that the controller is leaving and stops advertising.
    pub fn depart(&mut self) {
        let Some(advertiser) = &mut self.advertiser else {
            return;
        };
        advertiser.next = None;
        advertiser.available_index = 0;
        let adpdu = self.own_adpdu(AdpMessageType::ENTITY_DEPARTING, 0);
        self.queue_adp(&adpdu);
    }

    /// Handles the payload of a frame received on the AVTP ethertype from
    /// `source`. Frames that do not decode are counted and their error
    /// returned; the controller's state is unchanged by them.
    pub fn handle_frame(
        &mut self,
        now: Instant,
        source: MacAddress,
        bytes: &[u8],
    ) -> Result<(), DecodeError> {
        self.start_advertising(now);
        let result = match pdu::decode(bytes) {
            Ok(Pdu::Adp(adpdu)) => {
                self.handle_adpdu(now, source, &adpdu);
                Ok(())
            }
            Ok(Pdu::Aem(aem)) => {
                self.handle_aem(now, source, &aem);
                Ok(())
            }
            Ok(Pdu::Acmp(acmpdu)) => {
                self.handle_acmp(&acmpdu);
                Ok(())
            }
            Ok(Pdu::VendorUnique(vendor_unique)) => {
                self.handle_vendor_unique(now, &vendor_unique);
                Ok(())
            }
            Ok(Pdu::Aecp(header, _))
                if header.message_type == AecpMessageType::ADDRESS_ACCESS_RESPONSE =>
            {
                if let Ok(response) = AddressAccessPdu::decode(bytes) {
                    self.handle_address_access(&response);
                }
                Ok(())
            }
            Ok(_) => Ok(()),
            Err(error) => {
                self.malformed += 1;
                Err(error)
            }
        };
        self.pump(now);
        result
    }

    /// Handles an ADPDU received from `source`.
    pub fn handle_adpdu(&mut self, now: Instant, source: MacAddress, adpdu: &Adpdu) {
        let entity_id = adpdu.entity_id;
        if entity_id == self.config.entity_id {
            return;
        }
        match adpdu.message_type {
            AdpMessageType::ENTITY_AVAILABLE if entity_id.is_valid() => {
                self.entity_available(now, source, adpdu);
            }
            AdpMessageType::ENTITY_DEPARTING => {
                let known = self.entities.remove(&entity_id).is_some();
                if known {
                    self.forget(entity_id);
                    self.events
                        .push_back(Event::EntityOffline(entity_id, OfflineReason::Departed));
                }
            }
            AdpMessageType::ENTITY_DISCOVER => {
                let asked = !entity_id.is_valid() || entity_id == self.config.entity_id;
                if let Some(advertiser) = self.advertiser.as_mut().filter(|_| asked) {
                    let soon = now + self.random.up_to(advertiser.delay_limit());
                    advertiser.next = Some(advertiser.next.map_or(soon, |next| next.min(soon)));
                }
            }
            _ => {}
        }
    }

    fn entity_available(&mut self, now: Instant, source: MacAddress, adpdu: &Adpdu) {
        let entity_id = adpdu.entity_id;
        // Valid times run from 1 to 31 units of 2 s; zero would expire the
        // entity at once, so it counts as one unit.
        let expires = now + Duration::from_secs(2 * u64::from(adpdu.valid_time.max(1)));
        let Some(known) = self.entities.get_mut(&entity_id) else {
            self.entities.insert(
                entity_id,
                DiscoveredEntity {
                    adp: *adpdu,
                    mac: source,
                    first_seen: now,
                    last_seen: now,
                    expires,
                },
            );
            self.events.push_back(Event::EntityOnline(entity_id));
            if self.wants_model(adpdu) {
                self.start_enumeration(now, entity_id);
            }
            return;
        };
        let restarted = adpdu.available_index < known.adp.available_index;
        let changed = !same_advertisement(&known.adp, adpdu) || known.mac != source;
        // A new grandmaster or domain moves the entity in the network.
        let moved = adpdu.gptp_grandmaster_id != known.adp.gptp_grandmaster_id
            || adpdu.gptp_domain_number != known.adp.gptp_domain_number;
        let reconfigured = adpdu.current_configuration_index
            != known.adp.current_configuration_index
            && adpdu
                .entity_capabilities
                .contains(EntityCapabilities::AEM_CONFIGURATION_INDEX_VALID);
        // Another model, as when an entity's streams change while it
        // stays, has other descriptors to read.
        let remodeled = adpdu.entity_model_id != known.adp.entity_model_id;
        known.adp = *adpdu;
        known.mac = source;
        known.last_seen = now;
        known.expires = expires;
        if restarted {
            self.events.push_back(Event::EntityRestarted(entity_id));
        }
        if changed {
            self.events.push_back(Event::EntityChanged(entity_id));
        }
        if (restarted || reconfigured || remodeled) && self.wants_model(adpdu) {
            self.start_enumeration(now, entity_id);
        } else if moved {
            self.read_network_info(now, entity_id);
        }
    }

    /// Reads again where an entity sits in the network, each AVB
    /// interface's gPTP state and path, as not every entity says unasked
    /// when they change.
    fn read_network_info(&mut self, now: Instant, entity_id: EntityId) {
        if !self.config.network_info {
            return;
        }
        let Some(model) = self.models.get(&entity_id) else {
            return;
        };
        let interfaces: Vec<u16> = model
            .descriptors(DescriptorType::AVB_INTERFACE)
            .map(|(index, _)| index)
            .collect();
        for index in interfaces {
            self.queue_query(entity_id, Request::GetAvbInfo { index });
            self.queue_query(entity_id, Request::GetAsPath { index });
        }
        self.pump(now);
    }

    fn wants_model(&self, adpdu: &Adpdu) -> bool {
        self.config.enumerate
            && adpdu
                .entity_capabilities
                .contains(EntityCapabilities::AEM_SUPPORTED)
    }

    /// Drops everything kept about an entity apart from its discovery,
    /// finishing the caller's commands to it as not possible.
    fn forget(&mut self, entity_id: EntityId) {
        self.models.remove(&entity_id);
        self.identify_off.remove(&entity_id);
        self.memory_reads.retain(|&(read, _), _| read != entity_id);
        let mut abandoned: Vec<CommandId> = Vec::new();
        if let Some(session) = self.sessions.remove(&entity_id) {
            abandoned.extend(session.queue.iter().filter_map(|request| request.command()));
        }
        self.inflight.retain(|_, inflight| {
            let keep = inflight.entity_id != entity_id;
            if !keep {
                abandoned.extend(inflight.request.command());
            }
            keep
        });
        for command in abandoned {
            self.drop_command_data(command);
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
        }
    }

    fn start_enumeration(&mut self, now: Instant, entity_id: EntityId) {
        self.forget(entity_id);
        let Some(entity) = self.entities.get(&entity_id) else {
            return;
        };
        if self.config.own_mac == Some(entity.mac) {
            let mut model = EntityModel::reading();
            model.state = EnumerationState::Failed(EnumerationFailure::OnThisComputer);
            self.models.insert(entity_id, model);
            self.events.push_back(Event::EnumerationFailed(
                entity_id,
                EnumerationFailure::OnThisComputer,
            ));
            return;
        }
        let mut session = Session::default();
        if entity
            .adp
            .entity_capabilities
            .contains(EntityCapabilities::VENDOR_UNIQUE_SUPPORTED)
        {
            session.queue.push_back(Request::GetMilanInfo);
        }
        session.queue.push_back(Request::ReadDescriptor {
            descriptor_type: DescriptorType::ENTITY,
            index: 0,
            refresh: false,
        });
        self.sessions.insert(entity_id, session);
        self.models.insert(entity_id, EntityModel::reading());
        self.events.push_back(Event::EnumerationStarted(entity_id));
        self.pump(now);
    }

    fn handle_aem(&mut self, now: Instant, source: MacAddress, aem: &AemPdu<'_>) {
        let header = &aem.header;
        match header.message_type {
            AecpMessageType::AEM_COMMAND if header.target_entity_id == self.config.entity_id => {
                // Entities check on the controllers registered with them; a
                // controller answers commands it does not implement too.
                let status = match aem.command_type {
                    AemCommandType::CONTROLLER_AVAILABLE => AemStatus::SUCCESS,
                    _ => AemStatus::NOT_IMPLEMENTED,
                };
                let mut out = [0; 600];
                if let Ok(length) = aem::encode_response(aem, status, &mut out) {
                    self.outgoing.push_back((source, out[..length].to_vec()));
                }
            }
            AecpMessageType::AEM_RESPONSE
                if header.controller_entity_id == self.config.entity_id =>
            {
                if aem.unsolicited {
                    // Another controller chose another configuration.
                    if aem.command_type == AemCommandType::SET_CONFIGURATION {
                        self.reconfigured(now, header.target_entity_id, aem.payload);
                        return;
                    }
                    self.handle_notification(header.target_entity_id, aem);
                    return;
                }
                let key = (Channel::Aem, header.sequence_id);
                let Some(inflight) = self.inflight.get_mut(&key) else {
                    return;
                };
                if inflight.entity_id != header.target_entity_id
                    || aem.command_type != command_type_of(inflight.request)
                {
                    return;
                }
                if aem.status() == AemStatus::IN_PROGRESS {
                    inflight.deadline = now + COMMAND_TIMEOUT;
                    return;
                }
                let inflight = *inflight;
                self.complete(key, inflight);
                if let Request::SetConfiguration { command, .. } = inflight.request {
                    self.events
                        .push_back(Event::CommandFinished(command, aem_outcome(aem)));
                    if aem.status().is_success() {
                        self.reconfigured(now, inflight.entity_id, aem.payload);
                    }
                    return;
                }
                self.handle_response(inflight, aem);
            }
            // Controllers on one computer share its address, so another's
            // responses come here too. One that changed an entity, or read
            // how a stream stands, tells this controller what a
            // notification would, which some entities never send.
            AecpMessageType::AEM_RESPONSE
                if !aem.unsolicited && aem.status().is_success() && overheard(aem.command_type) =>
            {
                if aem.command_type == AemCommandType::SET_CONFIGURATION {
                    self.reconfigured(now, header.target_entity_id, aem.payload);
                    return;
                }
                self.handle_notification(header.target_entity_id, aem);
            }
            _ => {}
        }
    }

    /// Reads an entity again in the configuration a SET_CONFIGURATION
    /// response or notification names, taking it as advertised so the
    /// advertisement that follows does not start the read over.
    fn reconfigured(&mut self, now: Instant, entity_id: EntityId, payload: &[u8]) {
        if let (Some(configuration), Some(entity)) = (
            aem::configuration_of(payload),
            self.entities.get_mut(&entity_id),
        ) {
            entity.adp.current_configuration_index = configuration;
        }
        if self.entities.contains_key(&entity_id) && self.config.enumerate {
            self.start_enumeration(now, entity_id);
        }
    }

    fn handle_vendor_unique(&mut self, now: Instant, pdu: &VendorUniquePdu<'_>) {
        // CVU SRP declarations are commands every AVB Lite endpoint
        // broadcasts; the controller listens.
        if pdu.header.message_type == AecpMessageType::VENDOR_UNIQUE_COMMAND {
            if let Ok(cvu) = CvuMessage::from_pdu(pdu) {
                self.store_cvu(now, &cvu);
            }
            return;
        }
        if pdu.header.message_type != AecpMessageType::VENDOR_UNIQUE_RESPONSE
            || pdu.header.controller_entity_id != self.config.entity_id
        {
            return;
        }
        if let Ok(message) = LiteMessage::from_pdu(pdu) {
            self.handle_lite(now, pdu, &message);
            return;
        }
        if let Ok(message) = WirelessMessage::from_pdu(pdu) {
            self.handle_wireless(now, pdu, &message);
            return;
        }
        let Ok(message) = MvuMessage::from_pdu(pdu) else {
            return;
        };
        let entity_id = pdu.header.target_entity_id;
        if message.unsolicited {
            // Another controller set a clock domain's media clock reference
            // information.
            if pdu.header.status == 0
                && message.command_type == MvuCommandType::SET_MEDIA_CLOCK_REFERENCE_INFO
                && let Ok(reference) = MediaClockReference::decode(message.data)
            {
                self.store_media_clock_reference(entity_id, reference);
            }
            return;
        }
        let key = (Channel::Mvu, pdu.header.sequence_id);
        let Some(inflight) = self.inflight.get(&key).copied() else {
            return;
        };
        if inflight.entity_id != entity_id {
            return;
        }
        match (inflight.request, message.command_type) {
            (Request::GetMilanInfo, MvuCommandType::GET_MILAN_INFO) => {
                self.complete(key, inflight);
                let info = (pdu.header.status == 0)
                    .then(|| MilanInfo::decode(message.data).ok())
                    .flatten();
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.milan = info;
                }
            }
            (
                Request::GetMediaClockReference { domain },
                MvuCommandType::GET_MEDIA_CLOCK_REFERENCE_INFO,
            ) => {
                self.complete(key, inflight);
                if pdu.header.status == 0
                    && let Ok(reference) = MediaClockReference::decode(message.data)
                    && reference.domain == domain
                {
                    self.store_media_clock_reference(entity_id, reference);
                }
            }
            _ => return,
        }
        self.check_complete(entity_id);
    }

    /// An AVB Lite status response, or one an entity sent unsolicited.
    fn handle_lite(&mut self, now: Instant, pdu: &VendorUniquePdu<'_>, message: &LiteMessage<'_>) {
        let entity_id = pdu.header.target_entity_id;
        let status = (pdu.header.status == 0
            && message.command_type == LiteCommandType::GET_LITE_STATUS)
            .then(|| LiteStatus::decode(message.data).ok())
            .flatten();
        if message.unsolicited {
            if let Some(status) = status {
                self.store_lite_status(entity_id, status);
            }
            return;
        }
        let key = (Channel::Mvu, pdu.header.sequence_id);
        let Some(inflight) = self.inflight.get(&key).copied() else {
            return;
        };
        if let Request::SetLiteConfig {
            interface, command, ..
        } = inflight.request
        {
            if inflight.entity_id != entity_id {
                return;
            }
            self.complete(key, inflight);
            let status = AemStatus(pdu.header.status);
            self.events.push_back(Event::CommandFinished(
                command,
                if status.is_success() {
                    Outcome::Done
                } else {
                    Outcome::Refused(Refusal::Aem(status))
                },
            ));
            // The status shows the change.
            self.queue_query(entity_id, Request::GetLiteStatus { interface });
            return;
        }
        let Request::GetLiteStatus { interface } = inflight.request else {
            return;
        };
        if inflight.entity_id != entity_id {
            return;
        }
        self.complete(key, inflight);
        match status {
            Some(status) if status.interface == interface => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.lite_supported = Some(true);
                }
                // Asked again from here on, to follow its offset.
                if !self.config.lite_poll.is_zero() {
                    self.next_lite_poll
                        .get_or_insert(now + self.config.lite_poll);
                }
                self.store_lite_status(entity_id, status);
            }
            // An entity without AVB Lite says it does not implement the
            // query; it is not asked again.
            _ if pdu.header.status == AemStatus::NOT_IMPLEMENTED.0 => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.lite_supported = Some(false);
                }
            }
            _ => {}
        }
        self.check_complete(entity_id);
    }

    fn store_lite_status(&mut self, entity_id: EntityId, status: LiteStatus) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::AVB_INTERFACE, status.interface)
            && model.set_lite_status(status)
            && model.state == EnumerationState::Complete
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// An AVB Wireless status response, or one an entity sent unsolicited.
    fn handle_wireless(
        &mut self,
        now: Instant,
        pdu: &VendorUniquePdu<'_>,
        message: &WirelessMessage<'_>,
    ) {
        let entity_id = pdu.header.target_entity_id;
        let wireless = (pdu.header.status == 0
            && message.command_type == WirelessCommandType::GET_WIRELESS_STATUS)
            .then(|| WirelessStatus::decode(message.data).ok())
            .flatten()
            .map(|status| Wireless {
                status,
                stations: status.stations(message.data).collect(),
            });
        if message.unsolicited {
            if let Some(wireless) = wireless {
                self.store_wireless(entity_id, wireless);
            }
            return;
        }
        let key = (Channel::Mvu, pdu.header.sequence_id);
        let Some(inflight) = self.inflight.get(&key).copied() else {
            return;
        };
        if inflight.entity_id != entity_id {
            return;
        }
        if let Request::SetWirelessConfig {
            interface, command, ..
        } = inflight.request
        {
            self.complete(key, inflight);
            let status = AemStatus(pdu.header.status);
            self.events.push_back(Event::CommandFinished(
                command,
                if status.is_success() {
                    Outcome::Done
                } else {
                    Outcome::Refused(Refusal::Aem(status))
                },
            ));
            // The status shows the change.
            self.queue_query(entity_id, Request::GetWirelessStatus { interface });
            return;
        }
        let Request::GetWirelessStatus { interface } = inflight.request else {
            return;
        };
        self.complete(key, inflight);
        let status = AemStatus(pdu.header.status);
        match wireless {
            Some(wireless) if wireless.status.interface == interface => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.wireless_supported = Some(true);
                }
                // Asked again from here on, to follow its link and time.
                if !self.config.wireless_poll.is_zero() {
                    self.next_wireless_poll
                        .get_or_insert(now + self.config.wireless_poll);
                }
                self.store_wireless(entity_id, wireless);
            }
            // The entity answers the query, but the interface is wired.
            _ if status == AemStatus::NOT_SUPPORTED => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.wireless_supported = Some(true);
                }
            }
            // An entity without AVB Wireless says it does not implement
            // the query; it is not asked again.
            _ if status == AemStatus::NOT_IMPLEMENTED => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.wireless_supported = Some(false);
                }
            }
            _ => {}
        }
        self.check_complete(entity_id);
    }

    fn store_wireless(&mut self, entity_id: EntityId, wireless: Wireless) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::AVB_INTERFACE, wireless.status.interface)
            && model.set_wireless(wireless)
            && model.state == EnumerationState::Complete
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Keeps what a CVU SRP talker message declares, and forgets what it
    /// withdraws, in the talker's model.
    fn store_cvu(&mut self, now: Instant, cvu: &CvuMessage<'_>) {
        let Some(model) = self.models.get_mut(&cvu.sender) else {
            return;
        };
        let mut changed = false;
        for declaration in msrp::talker_declarations(cvu.msrp) {
            changed |= if declaration.event.declares() {
                model.set_cvu_talker(declaration, now)
            } else {
                model.remove_cvu_talker(declaration.stream_id)
            };
        }
        if changed {
            self.events.push_back(Event::EntityModelChanged(cvu.sender));
        }
    }

    fn store_media_clock_reference(&mut self, entity_id: EntityId, reference: MediaClockReference) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::CLOCK_DOMAIN, reference.domain)
            && model.set_media_clock_reference(reference)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Clears a command from flight, so the entity's next one can go.
    fn complete(&mut self, key: (Channel, u16), inflight: Inflight) {
        self.inflight.remove(&key);
        if let Some(session) = self.sessions.get_mut(&inflight.entity_id)
            && session.inflight == Some(key)
        {
            session.inflight = None;
        }
    }

    /// An Address Access response: the next part of a memory object read.
    fn handle_address_access(&mut self, response: &AddressAccessPdu<'_>) {
        let header = &response.header;
        if header.controller_entity_id != self.config.entity_id {
            return;
        }
        let key = (Channel::AddressAccess, header.sequence_id);
        let Some(&inflight) = self.inflight.get(&key) else {
            return;
        };
        let Request::ReadMemory { index, offset } = inflight.request else {
            return;
        };
        if inflight.entity_id != header.target_entity_id {
            return;
        }
        self.complete(key, inflight);
        let read = (response.status() == AaStatus::SUCCESS)
            .then(|| response.tlvs().next())
            .flatten()
            .and_then(Result::ok)
            .filter(|tlv| tlv.mode == AaMode::READ && !tlv.data.is_empty());
        self.memory_read(inflight.entity_id, index, offset, read.map(|tlv| tlv.data));
    }

    /// Takes the octets read of memory object `index` from `offset`, none
    /// when the read failed: asks for the next part, or keeps the object
    /// once it is all read.
    fn memory_read(&mut self, entity_id: EntityId, index: u16, offset: u32, data: Option<&[u8]>) {
        let key = (entity_id, index);
        let Some(data) = data else {
            self.memory_reads.remove(&key);
            return;
        };
        let read = self.memory_reads.entry(key).or_default();
        if offset == 0 {
            read.clear();
        }
        if read.len() != offset as usize {
            self.memory_reads.remove(&key);
            return;
        }
        read.extend_from_slice(data);
        let have = read.len() as u64;
        let Some(model) = self.models.get_mut(&entity_id) else {
            self.memory_reads.remove(&key);
            return;
        };
        let length = model
            .memory_objects()
            .find(|object| object.index == index)
            .map(|object| object.length);
        match length {
            Some(length) if have < length => {
                if let Some(session) = self.sessions.get_mut(&entity_id) {
                    session.queue.push_front(Request::ReadMemory {
                        index,
                        offset: have as u32,
                    });
                }
            }
            Some(length) if have == length => {
                let octets = self.memory_reads.remove(&key).unwrap_or_default();
                if model.store_memory(index, octets) {
                    self.events.push_back(Event::EntityModelChanged(entity_id));
                }
            }
            // More than the object holds, or an object gone.
            _ => {
                self.memory_reads.remove(&key);
            }
        }
    }

    fn handle_response(&mut self, inflight: Inflight, aem: &AemPdu<'_>) {
        let entity_id = inflight.entity_id;
        match inflight.request {
            Request::ReadDescriptor {
                descriptor_type,
                index,
                refresh,
            } => {
                if !aem.status().is_success() {
                    self.read_failed(
                        entity_id,
                        descriptor_type,
                        refresh,
                        EnumerationFailure::Refused(aem.status()),
                    );
                    return;
                }
                let response = ReadDescriptorResponse::decode(aem.payload);
                let Some(response) = matching(response, descriptor_type, index) else {
                    self.read_failed(
                        entity_id,
                        descriptor_type,
                        refresh,
                        EnumerationFailure::Malformed,
                    );
                    return;
                };
                self.descriptor_read(entity_id, response, refresh);
            }
            Request::RegisterUnsolicited => {
                if let Some(model) = self.models.get_mut(&entity_id) {
                    model.registered = aem.status().is_success();
                }
            }
            Request::GetStreamInfo {
                descriptor_type,
                index,
            } => {
                if let Ok(info) = StreamInfo::decode(aem.payload)
                    && aem.status().is_success()
                    && info.descriptor_type == descriptor_type
                    && info.index == index
                {
                    self.store_stream_info(entity_id, info);
                }
            }
            Request::GetAvbInfo { index } => {
                if let Ok(info) = AvbInfo::decode(aem.payload)
                    && aem.status().is_success()
                    && info.index == index
                {
                    self.store_avb_info(entity_id, info);
                }
            }
            Request::GetAsPath { index } => {
                if let Ok(path) = AsPath::decode(aem.payload)
                    && aem.status().is_success()
                    && path.index == index
                {
                    self.store_as_path(entity_id, &path);
                }
            }
            Request::GetCounters {
                descriptor_type,
                index,
            } => {
                if let Ok(counters) = Counters::decode(aem.payload)
                    && aem.status().is_success()
                    && counters.descriptor_type == descriptor_type
                    && counters.index == index
                {
                    self.store_counters(entity_id, counters);
                }
            }
            Request::Identify { command, .. } => {
                if let Some(command) = command {
                    self.events
                        .push_back(Event::CommandFinished(command, aem_outcome(aem)));
                }
            }
            Request::Streaming {
                descriptor_type,
                index,
                command,
                ..
            } => {
                // The stream info tells whether it runs now.
                if aem.status().is_success() {
                    self.queue_query(
                        entity_id,
                        Request::GetStreamInfo {
                            descriptor_type,
                            index,
                        },
                    );
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            Request::SetControl { index, command } => {
                self.control_values.remove(&command);
                // The response holds the values the control has after,
                // set or not.
                if let Some(values) = control_values(aem.payload, index) {
                    self.store_control(entity_id, index, values);
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            Request::GetDynamicInfo { queries, count } => {
                self.dynamic_info_answered(entity_id, &queries[..usize::from(count)], Some(aem));
            }
            Request::GetMaxTransitTime { output, command } => {
                if aem.status().is_success() {
                    self.store_max_transit_time(entity_id, output, aem.payload);
                    self.read_other_transit_times(entity_id, output);
                }
                if let Some(command) = command {
                    self.events
                        .push_back(Event::CommandFinished(command, aem_outcome(aem)));
                }
            }
            Request::SetMaxTransitTime { set, command } => {
                // The response holds the time the output has after; a
                // refusal may hold the time asked for instead, as macOS's
                // does, so the time the model has stays.
                if aem.status().is_success() {
                    self.store_max_transit_time(entity_id, set.output, aem.payload);
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            Request::ReadForCaller {
                descriptor_type,
                index,
                command,
            } => {
                let response = ReadDescriptorResponse::decode(aem.payload);
                if aem.status().is_success()
                    && let Some(response) = matching(response, descriptor_type, index)
                    && let Some(model) = self.models.get_mut(&entity_id)
                    && model.store(descriptor_type, index, response.descriptor)
                    && model.state == EnumerationState::Complete
                {
                    self.events.push_back(Event::EntityModelChanged(entity_id));
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            Request::GetAudioMap {
                descriptor_type,
                index,
                map_index,
            } => {
                if let Ok(map) = AudioMap::decode(aem.payload)
                    && aem.status().is_success()
                    && (map.descriptor_type, map.index, map.map_index)
                        == (descriptor_type, index, map_index)
                {
                    self.store_audio_map(entity_id, &map);
                }
            }
            Request::ChangeMappings {
                change,
                descriptor_type,
                index,
                command,
            } => {
                self.mapping_changes.remove(&command);
                if aem.status().is_success() {
                    if let Ok(changed) = AudioMappings::decode(aem.payload) {
                        self.store_mapping_change(entity_id, change, &changed);
                    }
                    // Entities may change more than asked, such as removing
                    // the mapping a new one replaces; read the map again.
                    self.queue_query(
                        entity_id,
                        Request::GetAudioMap {
                            descriptor_type,
                            index,
                            map_index: 0,
                        },
                    );
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            Request::ReadOther {
                configuration,
                descriptor_type,
                index,
            } => {
                let response = ReadDescriptorResponse::decode(aem.payload);
                let read = aem
                    .status()
                    .is_success()
                    .then(|| matching(response, descriptor_type, index))
                    .flatten()
                    .map(|response| response.descriptor);
                self.other_read(entity_id, configuration, descriptor_type, index, read);
            }
            Request::SetName { command, .. }
            | Request::SetStreamFormat { command, .. }
            | Request::SetSamplingRate { command, .. }
            | Request::SetClockSource { command, .. } => {
                if aem.status().is_success() {
                    self.applied(entity_id, inflight.request, aem.payload);
                }
                self.events
                    .push_back(Event::CommandFinished(command, aem_outcome(aem)));
            }
            // Finished as it is answered, where the read starts over.
            Request::SetConfiguration { .. }
            | Request::GetMilanInfo
            | Request::GetMediaClockReference { .. }
            | Request::GetLiteStatus { .. }
            | Request::SetLiteConfig { .. }
            | Request::GetWirelessStatus { .. }
            | Request::SetWirelessConfig { .. }
            | Request::GetRxState { .. }
            | Request::Bind { .. }
            | Request::Unbind { .. }
            | Request::GetTxState { .. }
            | Request::GetTxConnection { .. }
            | Request::DisconnectTx { .. }
            | Request::ReadMemory { .. } => {}
        }
        self.check_complete(entity_id);
    }

    /// Keeps a descriptor of another configuration, when it was read; for
    /// its CONFIGURATION descriptor, reads its streams; once the last is
    /// answered, says the model changed.
    fn other_read(
        &mut self,
        entity_id: EntityId,
        configuration: u16,
        descriptor_type: DescriptorType,
        index: u16,
        bytes: Option<&[u8]>,
    ) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        if let Some(bytes) = bytes {
            model.store_other(configuration, descriptor_type, index, bytes);
        }
        if descriptor_type == DescriptorType::CONFIGURATION
            && let Some(Ok(descriptor)) = bytes.map(ConfigurationDescriptor::decode)
        {
            // Its name, from its own strings, where it has no name of its
            // own.
            if descriptor.object_name.is_empty()
                && let Some(strings) = self
                    .models
                    .get(&entity_id)
                    .and_then(|model| model.strings_of(descriptor.localized_description))
            {
                self.queue_query(
                    entity_id,
                    Request::ReadOther {
                        configuration,
                        descriptor_type: DescriptorType::STRINGS,
                        index: strings,
                    },
                );
            }
            for (stream_type, count) in descriptor.descriptor_counts().filter(|(found, _)| {
                matches!(
                    *found,
                    DescriptorType::STREAM_INPUT | DescriptorType::STREAM_OUTPUT
                )
            }) {
                for stream in 0..count {
                    self.queue_query(
                        entity_id,
                        Request::ReadOther {
                            configuration,
                            descriptor_type: stream_type,
                            index: stream,
                        },
                    );
                }
            }
        }
        let pending = self.sessions.get(&entity_id).is_some_and(|session| {
            session
                .queue
                .iter()
                .any(|request| matches!(request, Request::ReadOther { .. }))
        });
        if !pending {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Updates the model with what a SET command's response says the
    /// entity now has, reading again what the response cannot tell: a
    /// descriptor not stored as expected, and the streams after a new
    /// sampling rate, whose formats may follow it.
    fn applied(&mut self, entity_id: EntityId, request: Request, payload: &[u8]) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        let (changed, target) = match request {
            Request::SetName { set, .. } => (
                SetName::decode(payload).is_ok_and(|set| model.apply_name(&set)),
                (set.descriptor_type, set.index),
            ),
            Request::SetStreamFormat { set, .. } => (
                SetStreamFormat::decode(payload).is_ok_and(|set| model.apply_stream_format(&set)),
                (set.descriptor_type, set.index),
            ),
            Request::SetSamplingRate { set, .. } => (
                SetSamplingRate::decode(payload).is_ok_and(|set| model.apply_sampling_rate(&set)),
                (set.descriptor_type, set.index),
            ),
            Request::SetClockSource { set, .. } => (
                SetClockSource::decode(payload).is_ok_and(|set| model.apply_clock_source(&set)),
                (DescriptorType::CLOCK_DOMAIN, set.domain),
            ),
            _ => return,
        };
        let streams: Vec<(DescriptorType, u16)> = match request {
            Request::SetSamplingRate { .. } => {
                [DescriptorType::STREAM_INPUT, DescriptorType::STREAM_OUTPUT]
                    .into_iter()
                    .flat_map(|descriptor_type| {
                        model
                            .descriptors(descriptor_type)
                            .map(move |(index, _)| (descriptor_type, index))
                    })
                    .collect()
            }
            _ => Vec::new(),
        };
        if changed {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        } else {
            self.queue_read(entity_id, target.0, target.1, true);
        }
        for (descriptor_type, index) in streams {
            self.queue_read(entity_id, descriptor_type, index, true);
        }
        if let Request::SetStreamFormat { set, .. } = request {
            self.queue_query(
                entity_id,
                Request::GetStreamInfo {
                    descriptor_type: set.descriptor_type,
                    index: set.index,
                },
            );
        }
        // Mappings to channels a stream no longer has may be dropped.
        if matches!(
            request,
            Request::SetStreamFormat { .. } | Request::SetSamplingRate { .. }
        ) {
            self.queue_audio_map_reads(entity_id);
        }
    }

    /// Queues reading each of an entity's dynamic stream port maps again.
    fn queue_audio_map_reads(&mut self, entity_id: EntityId) {
        if !self.config.read_mappings {
            return;
        }
        let Some(model) = self.models.get(&entity_id) else {
            return;
        };
        for request in audio_map_reads(model) {
            self.queue_query(entity_id, request);
        }
    }

    fn store_audio_map(&mut self, entity_id: EntityId, map: &AudioMap<'_>) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        if !model.has(map.descriptor_type, map.index) {
            return;
        }
        if model.set_audio_map(map) {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
        // The next part goes next, after the caller's commands, so the parts
        // are read together.
        let next = map.map_index.saturating_add(1);
        if next < map.number_of_maps.min(MAX_MAP_PARTS)
            && let Some(session) = self.sessions.get_mut(&entity_id)
        {
            let request = Request::GetAudioMap {
                descriptor_type: map.descriptor_type,
                index: map.index,
                map_index: next,
            };
            if !session.queue.contains(&request) {
                let place = session
                    .queue
                    .iter()
                    .position(|queued| queued.command().is_none())
                    .unwrap_or(session.queue.len());
                session.queue.insert(place, request);
            }
        }
    }

    fn store_mapping_change(
        &mut self,
        entity_id: EntityId,
        change: MappingChange,
        changed: &AudioMappings<'_>,
    ) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.apply_mappings(change, changed)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    fn store_stream_info(&mut self, entity_id: EntityId, info: StreamInfo) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(info.descriptor_type, info.index)
            && model.set_stream_info(info)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
            // A stream output that changed may have other listeners.
            if self.config.read_talker_state
                && info.descriptor_type == DescriptorType::STREAM_OUTPUT
            {
                self.queue_query(
                    entity_id,
                    Request::GetTxState {
                        output: info.index,
                        command: None,
                    },
                );
            }
        }
    }

    fn store_avb_info(&mut self, entity_id: EntityId, info: AvbInfo) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::AVB_INTERFACE, info.index)
            && model.set_avb_info(info)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    fn store_as_path(&mut self, entity_id: EntityId, path: &AsPath<'_>) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::AVB_INTERFACE, path.index)
            && model.set_as_path(path)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    fn store_counters(&mut self, entity_id: EntityId, counters: Counters) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.has(counters.descriptor_type, counters.index)
            && model.set_counters(counters)
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    fn handle_acmp(&mut self, acmpdu: &Acmpdu) {
        if !acmpdu.message_type.is_response() {
            return;
        }
        let key = (Channel::Acmp, acmpdu.sequence_id);
        // TX commands go to the talker, RX ones to the listener.
        let addressed = if to_talker(acmpdu.message_type) {
            acmpdu.talker_entity_id
        } else {
            acmpdu.listener_entity_id
        };
        if acmpdu.controller_entity_id == self.config.entity_id
            && let Some(inflight) = self.inflight.get(&key).copied()
            && inflight.entity_id == addressed
            && inflight
                .request
                .acmp_message()
                .map(AcmpMessageType::response)
                == Some(acmpdu.message_type)
        {
            self.complete(key, inflight);
            // A listener that refuses a bind or unbind may be bound
            // otherwise than the model holds, as one that answers
            // NOT_CONNECTED to an unbind it was thought bound for: it is
            // asked how it stands.
            if let Request::Bind { input, .. } | Request::Unbind { input, .. } = inflight.request
                && !acmpdu.status.is_success()
            {
                self.queue_query(addressed, Request::GetRxState { input });
            }
            if let Request::GetTxState { output, .. } = inflight.request
                && acmpdu.status.is_success()
                && acmpdu.talker_unique_id == output
            {
                let state = TxState {
                    stream_id: acmpdu.stream_id,
                    destination: acmpdu.stream_dest_mac,
                    connection_count: acmpdu.connection_count,
                    vlan_id: acmpdu.stream_vlan_id,
                };
                if let Some(model) = self.models.get_mut(&addressed) {
                    let mut changed = model.set_tx_state(output, state);
                    changed |= model.trim_tx_connections(output, state.connection_count);
                    if changed {
                        self.events.push_back(Event::EntityModelChanged(addressed));
                    }
                    // Who listens, from a talker that keeps its listeners.
                    if self.config.read_talker_state
                        && model.tx_connections_supported != Some(false)
                    {
                        for index in 0..state.connection_count {
                            self.queue_query(
                                addressed,
                                Request::GetTxConnection {
                                    output,
                                    index,
                                    command: None,
                                },
                            );
                        }
                    }
                }
            }
            if let Request::GetTxConnection { .. } = inflight.request
                && acmpdu.status == AcmpStatus::NOT_SUPPORTED
                && let Some(model) = self.models.get_mut(&addressed)
            {
                model.tx_connections_supported = Some(false);
            }

            if let Request::GetTxConnection { output, index, .. } = inflight.request
                && acmpdu.status.is_success()
                && acmpdu.talker_unique_id == output
                && let Some(model) = self.models.get_mut(&addressed)
                && model.set_tx_connection(
                    output,
                    index,
                    (acmpdu.listener_entity_id, acmpdu.listener_unique_id),
                )
            {
                self.events.push_back(Event::EntityModelChanged(addressed));
            }
            if let Some(command) = inflight.request.command() {
                let outcome = if acmpdu.status.is_success() {
                    Outcome::Done
                } else {
                    Outcome::Refused(Refusal::Acmp(acmpdu.status))
                };
                self.events
                    .push_back(Event::CommandFinished(command, outcome));
            }
        }
        // Responses to every controller's commands tell the listener's
        // bindings, so changes made elsewhere show too.
        if acmpdu.status.is_success() {
            self.observe_binding(acmpdu);
            self.observe_talker(acmpdu);
        }
    }

    /// A talker that took or let go of a listener, for whoever asked, is
    /// asked again what its stream output does and who listens: a talker
    /// outside Milan says nothing of it unasked.
    fn observe_talker(&mut self, acmpdu: &Acmpdu) {
        if !self.config.read_talker_state
            || !matches!(
                acmpdu.message_type,
                AcmpMessageType::CONNECT_TX_RESPONSE | AcmpMessageType::DISCONNECT_TX_RESPONSE
            )
        {
            return;
        }
        let (talker, output) = (acmpdu.talker_entity_id, acmpdu.talker_unique_id);
        if !self
            .models
            .get(&talker)
            .is_some_and(|model| model.has(DescriptorType::STREAM_OUTPUT, output))
        {
            return;
        }
        self.queue_query(
            talker,
            Request::GetTxState {
                output,
                command: None,
            },
        );
        self.queue_query(
            talker,
            Request::GetStreamInfo {
                descriptor_type: DescriptorType::STREAM_OUTPUT,
                index: output,
            },
        );
    }

    fn observe_binding(&mut self, acmpdu: &Acmpdu) {
        let binding = match acmpdu.message_type {
            AcmpMessageType::CONNECT_RX_RESPONSE => Binding {
                talker: acmpdu.talker_entity_id,
                talker_unique_id: acmpdu.talker_unique_id,
                connection_count: acmpdu.connection_count.max(1),
                flags: acmpdu.flags,
            },
            AcmpMessageType::DISCONNECT_RX_RESPONSE => Binding::default(),
            AcmpMessageType::GET_RX_STATE_RESPONSE => Binding {
                talker: acmpdu.talker_entity_id,
                talker_unique_id: acmpdu.talker_unique_id,
                connection_count: acmpdu.connection_count,
                flags: acmpdu.flags,
            },
            _ => return,
        };
        let entity_id = acmpdu.listener_entity_id;
        let input = acmpdu.listener_unique_id;
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        if !model.has(DescriptorType::STREAM_INPUT, input) {
            return;
        }
        if model.set_binding(input, binding) {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
        // The input's stream info changes with its binding.
        if acmpdu.message_type != AcmpMessageType::GET_RX_STATE_RESPONSE {
            self.queue_query(
                entity_id,
                Request::GetStreamInfo {
                    descriptor_type: DescriptorType::STREAM_INPUT,
                    index: input,
                },
            );
        }
    }

    /// Queues a query about the entity's current state, unless the same
    /// one is queued already.
    fn queue_query(&mut self, entity_id: EntityId, request: Request) {
        if let Some(session) = self.sessions.get_mut(&entity_id)
            && !session.queue.contains(&request)
        {
            session.queue.push_back(request);
        }
    }

    fn read_failed(
        &mut self,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        refresh: bool,
        failure: EnumerationFailure,
    ) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        let essential = matches!(
            descriptor_type,
            DescriptorType::ENTITY | DescriptorType::CONFIGURATION
        );
        if essential && !refresh {
            model.state = EnumerationState::Failed(failure);
            if let Some(session) = self.sessions.get_mut(&entity_id) {
                session.queue.clear();
            }
            self.events
                .push_back(Event::EnumerationFailed(entity_id, failure));
        } else {
            model.failed_reads = model.failed_reads.saturating_add(1);
        }
    }

    fn descriptor_read(
        &mut self,
        entity_id: EntityId,
        response: ReadDescriptorResponse<'_>,
        refresh: bool,
    ) {
        let descriptor = response.descriptor;
        let mut follow_ups: Vec<(DescriptorType, u16, u16)> = Vec::new();
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        if !refresh {
            match response.descriptor_type {
                DescriptorType::ENTITY => match EntityDescriptor::decode(descriptor) {
                    Ok(entity) => {
                        model.configuration = entity.current_configuration;
                        follow_ups.push((
                            DescriptorType::CONFIGURATION,
                            entity.current_configuration,
                            1,
                        ));
                    }
                    Err(_) => {
                        self.read_failed(
                            entity_id,
                            DescriptorType::ENTITY,
                            false,
                            EnumerationFailure::Malformed,
                        );
                        return;
                    }
                },
                DescriptorType::CONFIGURATION => {
                    match ConfigurationDescriptor::decode(descriptor) {
                        Ok(configuration) => {
                            let key = model.entity().map(|entity| ModelKey {
                                entity_model_id: entity.entity_model_id,
                                firmware: entity.firmware_version.into(),
                                configuration: response.index,
                            });
                            // A model cached for the same model, firmware
                            // and configuration, with the same descriptors.
                            let cached =
                                key.and_then(|key| self.cache.get(&key)).filter(|cached| {
                                    cached
                                        .descriptor(DescriptorType::CONFIGURATION, response.index)
                                        .and_then(|bytes| {
                                            ConfigurationDescriptor::decode(bytes).ok()
                                        })
                                        .is_some_and(|known| {
                                            known
                                                .descriptor_counts()
                                                .eq(configuration.descriptor_counts())
                                        })
                                });
                            if let Some(cached) = cached {
                                let cached = cached.clone();
                                model.store(response.descriptor_type, response.index, descriptor);
                                self.use_cached(entity_id, &cached);
                                return;
                            }
                            for (descriptor_type, count) in configuration.descriptor_counts() {
                                if READ_TYPES.contains(&descriptor_type) {
                                    follow_ups.push((descriptor_type, 0, count));
                                }
                            }
                        }
                        Err(_) => {
                            self.read_failed(
                                entity_id,
                                DescriptorType::CONFIGURATION,
                                false,
                                EnumerationFailure::Malformed,
                            );
                            return;
                        }
                    }
                }
                DescriptorType::AUDIO_UNIT => {
                    if let Ok(unit) = AudioUnitDescriptor::decode(descriptor) {
                        follow_ups.push((
                            DescriptorType::STREAM_PORT_INPUT,
                            unit.base_stream_input_port,
                            unit.number_of_stream_input_ports,
                        ));
                        follow_ups.push((
                            DescriptorType::STREAM_PORT_OUTPUT,
                            unit.base_stream_output_port,
                            unit.number_of_stream_output_ports,
                        ));
                    }
                }
                DescriptorType::STREAM_PORT_INPUT | DescriptorType::STREAM_PORT_OUTPUT => {
                    if let Ok(port) = StreamPortDescriptor::decode(descriptor) {
                        follow_ups.push((
                            DescriptorType::AUDIO_CLUSTER,
                            port.base_cluster,
                            port.number_of_clusters,
                        ));
                        follow_ups.push((
                            DescriptorType::AUDIO_MAP,
                            port.base_map,
                            port.number_of_maps,
                        ));
                    }
                }
                DescriptorType::LOCALE => {
                    if let Ok(locale) = LocaleDescriptor::decode(descriptor) {
                        follow_ups.push((
                            DescriptorType::STRINGS,
                            locale.base_strings,
                            locale.number_of_strings,
                        ));
                    }
                }
                _ => {}
            }
        }
        let changed = model.store(response.descriptor_type, response.index, descriptor);
        if refresh && changed {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
        for (descriptor_type, first, count) in follow_ups {
            for index in first..first.saturating_add(count) {
                self.queue_read(entity_id, descriptor_type, index, false);
            }
        }
    }

    /// Takes an entity's descriptors from a cached model of its entity
    /// model: what never changes as it is, what differs between entities
    /// read from the entity, and what changes on an entity asked for with
    /// GET_DYNAMIC_INFO when it is a Milan entity, read otherwise.
    fn use_cached(&mut self, entity_id: EntityId, cached: &CachedModel) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        model.from_cache = true;
        let milan = model.milan.is_some();
        let mut own = Vec::new();
        let mut queries = Vec::new();
        for (descriptor_type, index, bytes) in &cached.descriptors {
            let (descriptor_type, index) = (*descriptor_type, *index);
            if OWN_TYPES.contains(&descriptor_type) {
                if !matches!(
                    descriptor_type,
                    DescriptorType::ENTITY | DescriptorType::CONFIGURATION
                ) {
                    own.push((descriptor_type, index));
                }
                continue;
            }
            model.store(descriptor_type, index, bytes);
            if STATIC_TYPES.contains(&descriptor_type) {
                continue;
            }
            queries.extend(dynamic_queries(descriptor_type, index));
        }
        for (descriptor_type, index) in own {
            self.queue_read(entity_id, descriptor_type, index, false);
        }
        if milan {
            self.queue_dynamic_info(entity_id, &queries);
        } else {
            self.read_instead(entity_id, &queries);
        }
    }

    /// Queues GET_DYNAMIC_INFO for `queries`, as many to a command as
    /// their answers fit.
    fn queue_dynamic_info(&mut self, entity_id: EntityId, queries: &[DynamicQuery]) {
        let Some(session) = self.sessions.get_mut(&entity_id) else {
            return;
        };
        let mut batch = [DynamicQuery::ClockSource { domain: 0 }; MAX_DYNAMIC_QUERIES];
        let (mut count, mut room) = (0, 0);
        for &query in queries {
            if count == MAX_DYNAMIC_QUERIES || room + query.answer_len() > aem::MAX_AEM_PAYLOAD {
                session.queue.push_back(Request::GetDynamicInfo {
                    queries: batch,
                    count: count as u8,
                });
                (count, room) = (0, 0);
            }
            batch[count] = query;
            count += 1;
            room += query.answer_len();
        }
        if count > 0 {
            session.queue.push_back(Request::GetDynamicInfo {
                queries: batch,
                count: count as u8,
            });
        }
    }

    /// Reads again the descriptors `queries` ask about, for an entity that
    /// does not answer GET_DYNAMIC_INFO.
    fn read_instead(&mut self, entity_id: EntityId, queries: &[DynamicQuery]) {
        let mut targets: Vec<(DescriptorType, u16)> =
            queries.iter().map(|query| query.target()).collect();
        targets.dedup();
        for (descriptor_type, index) in targets {
            self.queue_read(entity_id, descriptor_type, index, true);
        }
    }

    /// Applies a GET_DYNAMIC_INFO response, reading again what it did not
    /// answer; when the entity refused it, reads instead what this one and
    /// the ones still queued ask about.
    fn dynamic_info_answered(
        &mut self,
        entity_id: EntityId,
        asked: &[DynamicQuery],
        aem: Option<&AemPdu<'_>>,
    ) {
        let Some(aem) = aem.filter(|aem| aem.status().is_success()) else {
            let mut queries = asked.to_vec();
            if let Some(session) = self.sessions.get_mut(&entity_id) {
                session.queue.retain(|request| match request {
                    Request::GetDynamicInfo {
                        queries: more,
                        count,
                    } => {
                        queries.extend_from_slice(&more[..usize::from(*count)]);
                        false
                    }
                    _ => true,
                });
            }
            self.read_instead(entity_id, &queries);
            return;
        };
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        let mut unanswered: Vec<DynamicQuery> = asked.to_vec();
        let mut changed = false;
        for info in aem::dynamic_infos(aem.payload) {
            if !info.status.is_success() {
                continue;
            }
            let applied = match info.command_type {
                AemCommandType::GET_NAME => SetName::decode(info.data).ok().map(|got| {
                    let query = DynamicQuery::Name {
                        descriptor_type: got.descriptor_type,
                        index: got.index,
                        name_index: got.name_index,
                    };
                    (query, model.apply_name(&got))
                }),
                AemCommandType::GET_STREAM_FORMAT => {
                    SetStreamFormat::decode(info.data).ok().map(|got| {
                        let query = DynamicQuery::StreamFormat {
                            descriptor_type: got.descriptor_type,
                            index: got.index,
                        };
                        (query, model.apply_stream_format(&got))
                    })
                }
                AemCommandType::GET_SAMPLING_RATE => {
                    SetSamplingRate::decode(info.data).ok().map(|got| {
                        let query = DynamicQuery::SamplingRate {
                            descriptor_type: got.descriptor_type,
                            index: got.index,
                        };
                        (query, model.apply_sampling_rate(&got))
                    })
                }
                AemCommandType::GET_CLOCK_SOURCE => {
                    SetClockSource::decode(info.data).ok().map(|got| {
                        (
                            DynamicQuery::ClockSource { domain: got.domain },
                            model.apply_clock_source(&got),
                        )
                    })
                }
                _ => None,
            };
            if let Some((query, applied)) = applied {
                unanswered.retain(|asked| *asked != query);
                changed |= applied;
            }
        }
        if changed && model.state == EnumerationState::Complete {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
        self.read_instead(entity_id, &unanswered);
    }

    /// Remembers an entity model read before, so entities of that model are
    /// read faster; the caller decides which, as from
    /// [`static_model`](Self::static_model) once an entity is read.
    pub fn remember_model(&mut self, model: CachedModel) {
        self.cache.insert(model.key.clone(), model);
    }

    /// An entity's model to keep for next time: its descriptors as read,
    /// once all of them were and none came from the cache.
    pub fn static_model(&self, entity_id: EntityId) -> Option<CachedModel> {
        let model = self.models.get(&entity_id)?;
        if model.state != EnumerationState::Complete || model.failed_reads > 0 || model.from_cache {
            return None;
        }
        let entity = model.entity()?;
        Some(CachedModel {
            key: ModelKey {
                entity_model_id: entity.entity_model_id,
                firmware: entity.firmware_version.into(),
                configuration: model.configuration,
            },
            descriptors: model
                .all_descriptors()
                .filter(|(descriptor_type, _, _)| *descriptor_type != DescriptorType::ENTITY)
                .map(|(descriptor_type, index, bytes)| (descriptor_type, index, bytes.to_vec()))
                .collect(),
        })
    }

    /// Queues a descriptor read unless it is read or queued already, or
    /// the entity has asked for more than any could need.
    fn queue_read(
        &mut self,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
        refresh: bool,
    ) {
        let (Some(session), Some(model)) = (
            self.sessions.get_mut(&entity_id),
            self.models.get(&entity_id),
        ) else {
            return;
        };
        let request = Request::ReadDescriptor {
            descriptor_type,
            index,
            refresh,
        };
        if session.queue.contains(&request) {
            return;
        }
        if !refresh {
            if model.has(descriptor_type, index) || session.requested >= MAX_DESCRIPTORS {
                return;
            }
            session.requested += 1;
        }
        session.queue.push_back(request);
    }

    /// Marks an entity read once nothing is queued or in flight for it,
    /// and registers for its notifications.
    fn check_complete(&mut self, entity_id: EntityId) {
        let (Some(session), Some(model)) = (
            self.sessions.get_mut(&entity_id),
            self.models.get_mut(&entity_id),
        ) else {
            return;
        };
        if model.state != EnumerationState::Reading
            || !session.queue.is_empty()
            || session.inflight.is_some()
        {
            return;
        }
        model.state = EnumerationState::Complete;
        // What the streams are doing now.
        for (index, _) in model.descriptors(DescriptorType::STREAM_INPUT) {
            session
                .queue
                .push_back(Request::GetRxState { input: index });
            session.queue.push_back(Request::GetStreamInfo {
                descriptor_type: DescriptorType::STREAM_INPUT,
                index,
            });
        }
        for (index, _) in model.descriptors(DescriptorType::STREAM_OUTPUT) {
            session.queue.push_back(Request::GetStreamInfo {
                descriptor_type: DescriptorType::STREAM_OUTPUT,
                index,
            });
        }
        // How channels map to and from the streams.
        if self.config.read_mappings {
            session.queue.extend(audio_map_reads(model));
        }
        // How the clocks and streams have fared.
        if self.config.read_counters {
            for descriptor_type in [
                DescriptorType::CLOCK_DOMAIN,
                DescriptorType::STREAM_INPUT,
                DescriptorType::STREAM_OUTPUT,
            ] {
                for (index, _) in model.descriptors(descriptor_type) {
                    session.queue.push_back(Request::GetCounters {
                        descriptor_type,
                        index,
                    });
                }
            }
        }
        // How long each stream output's frames may take, which Milan
        // talkers report and others may, as macOS does: an entity outside
        // Milan is asked for its first output's, and for the rest once it
        // answers.
        if self.config.read_transit_times {
            let asked = if model.milan.is_some() { usize::MAX } else { 1 };
            for (output, _) in model.descriptors(DescriptorType::STREAM_OUTPUT).take(asked) {
                session.queue.push_back(Request::GetMaxTransitTime {
                    output,
                    command: None,
                });
            }
        }
        // What its other configurations hold, to choose among them: each
        // one's CONFIGURATION descriptor, then its streams.
        if self.config.read_configurations
            && let Some(entity) = model.entity()
        {
            for configuration in
                (0..entity.configurations_count).filter(|&other| other != model.configuration)
            {
                session.queue.push_back(Request::ReadOther {
                    configuration,
                    descriptor_type: DescriptorType::CONFIGURATION,
                    index: configuration,
                });
            }
        }
        // Whether each interface runs AVB or AVB Lite, from entities that
        // answer the query.
        if self.config.lite_status && model.lite_supported != Some(false) {
            for (interface, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
                session
                    .queue
                    .push_back(Request::GetLiteStatus { interface });
            }
        }
        // Which interfaces are wireless, and how their link and time hold,
        // from entities that answer the query.
        if self.config.wireless_status && model.wireless_supported != Some(false) {
            for (interface, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
                session
                    .queue
                    .push_back(Request::GetWirelessStatus { interface });
            }
        }
        // How each clock domain stands in media clock management.
        if self.config.media_clock_info && model.milan.is_some() {
            for (domain, _) in model.descriptors(DescriptorType::CLOCK_DOMAIN) {
                session
                    .queue
                    .push_back(Request::GetMediaClockReference { domain });
            }
        }
        // Where the entity sits in the network.
        if self.config.network_info {
            for (index, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
                session.queue.push_back(Request::GetAvbInfo { index });
                session.queue.push_back(Request::GetAsPath { index });
                session.queue.push_back(Request::GetCounters {
                    descriptor_type: DescriptorType::AVB_INTERFACE,
                    index,
                });
            }
        }
        if self.config.register_unsolicited && !model.registered {
            session.queue.push_back(Request::RegisterUnsolicited);
        }
        // Its logos, from an entity that advertises Address Access.
        let address_access = self.entities.get(&entity_id).is_some_and(|entity| {
            entity
                .adp
                .entity_capabilities
                .contains(EntityCapabilities::ADDRESS_ACCESS_SUPPORTED)
        });
        if self.config.read_logos && address_access {
            for object in model.memory_objects().filter(is_logo) {
                session.queue.push_back(Request::ReadMemory {
                    index: object.index,
                    offset: 0,
                });
            }
        }
        self.events.push_back(Event::EntityEnumerated(entity_id));
    }

    fn handle_notification(&mut self, entity_id: EntityId, aem: &AemPdu<'_>) {
        let Some(model) = self.models.get_mut(&entity_id) else {
            return;
        };
        if aem.command_type == AemCommandType::DEREGISTER_UNSOLICITED_NOTIFICATION {
            model.registered = false;
            if self.config.register_unsolicited
                && model.state == EnumerationState::Complete
                && let Some(session) = self.sessions.get_mut(&entity_id)
            {
                session.queue.push_back(Request::RegisterUnsolicited);
            }
            return;
        }
        match aem.command_type {
            AemCommandType::GET_STREAM_INFO | AemCommandType::SET_STREAM_INFO => {
                if let Ok(info) = StreamInfo::decode(aem.payload) {
                    self.store_stream_info(entity_id, info);
                }
                return;
            }
            AemCommandType::GET_AVB_INFO => {
                if let Ok(info) = AvbInfo::decode(aem.payload) {
                    self.store_avb_info(entity_id, info);
                }
                return;
            }
            AemCommandType::GET_AS_PATH => {
                if let Ok(path) = AsPath::decode(aem.payload) {
                    self.store_as_path(entity_id, &path);
                }
                return;
            }
            AemCommandType::GET_COUNTERS => {
                if let Ok(counters) = Counters::decode(aem.payload) {
                    self.store_counters(entity_id, counters);
                }
                return;
            }
            AemCommandType::ADD_AUDIO_MAPPINGS | AemCommandType::REMOVE_AUDIO_MAPPINGS => {
                let change = if aem.command_type == AemCommandType::ADD_AUDIO_MAPPINGS {
                    MappingChange::Add
                } else {
                    MappingChange::Remove
                };
                if let Ok(changed) = AudioMappings::decode(aem.payload) {
                    self.store_mapping_change(entity_id, change, &changed);
                }
                return;
            }
            // Reading a map changes nothing; its descriptor needs no read.
            AemCommandType::GET_AUDIO_MAP => return,
            AemCommandType::SET_MAX_TRANSIT_TIME | AemCommandType::GET_MAX_TRANSIT_TIME => {
                if let Ok(time) = MaxTransitTime::decode(aem.payload) {
                    self.store_max_transit_time(entity_id, time.output, aem.payload);
                }
                return;
            }
            AemCommandType::SET_CONTROL | AemCommandType::GET_CONTROL => {
                if let Some((DescriptorType::CONTROL, index)) = aem::target_descriptor(aem.payload)
                    && let Some(values) = control_values(aem.payload, index)
                {
                    self.store_control(entity_id, index, values);
                }
                return;
            }
            _ => {}
        }
        // Whatever the notification changed, the descriptor it names holds
        // the new value; read it again.
        if let Some((descriptor_type, index)) = aem::target_descriptor(aem.payload)
            && model.has(descriptor_type, index)
        {
            self.queue_read(entity_id, descriptor_type, index, true);
        }
    }

    /// Sends the next queued command of each entity with none in flight.
    fn pump(&mut self, now: Instant) {
        let ready: Vec<EntityId> = self
            .sessions
            .iter()
            .filter(|(_, session)| session.inflight.is_none() && !session.queue.is_empty())
            .map(|(&entity_id, _)| entity_id)
            .collect();
        for entity_id in ready {
            let Some(request) = self
                .sessions
                .get_mut(&entity_id)
                .and_then(|session| session.queue.pop_front())
            else {
                continue;
            };
            let counter = match request.channel() {
                Channel::Aem => &mut self.next_aem_sequence,
                Channel::Mvu => &mut self.next_mvu_sequence,
                Channel::Acmp => &mut self.next_acmp_sequence,
                Channel::AddressAccess => &mut self.next_address_access_sequence,
            };
            let sequence = *counter;
            *counter = sequence.wrapping_add(1);
            let key = (request.channel(), sequence);
            let inflight = Inflight {
                entity_id,
                request,
                deadline: now + self.timeout(entity_id, request),
                retried: false,
            };
            if !self.send(key, inflight) {
                continue;
            }
            self.inflight.insert(key, inflight);
            if let Some(session) = self.sessions.get_mut(&entity_id) {
                session.inflight = Some(key);
            }
        }
    }

    /// Queues a command for sending, returning whether it could be built.
    fn send(&mut self, (_, sequence_id): (Channel, u16), inflight: Inflight) -> bool {
        let Some(entity) = self.entities.get(&inflight.entity_id) else {
            return false;
        };
        let addressing = Addressing {
            target: inflight.entity_id,
            controller: self.config.entity_id,
            sequence_id,
        };
        // Room for the longest commands, GET_DYNAMIC_INFO and a padded
        // Address Access READ.
        let mut out = [0; 600];
        let acmp = |message_type, talker: (EntityId, u16), input: u16, out: &mut [u8]| {
            Acmpdu::command(
                message_type,
                addressing.controller,
                talker,
                (addressing.target, input),
                sequence_id,
            )
            .encode(out)
        };
        let destination = match inflight.request.channel() {
            Channel::Acmp => crate::ADP_ACMP_MULTICAST,
            Channel::Aem | Channel::Mvu | Channel::AddressAccess => entity.mac,
        };
        let length = match inflight.request {
            Request::ReadDescriptor {
                descriptor_type,
                index,
                ..
            } => {
                let configuration = self
                    .models
                    .get(&inflight.entity_id)
                    .map_or(0, |model| model.configuration);
                aem::encode_read_descriptor(
                    addressing,
                    configuration,
                    descriptor_type,
                    index,
                    &mut out,
                )
            }
            Request::RegisterUnsolicited => aem::encode_register_unsolicited(addressing, &mut out),
            Request::GetLiteStatus { interface } => lite::encode_get_lite_status(
                addressing.target,
                addressing.controller,
                sequence_id,
                interface,
                &mut out,
            ),
            Request::SetLiteConfig {
                interface, flags, ..
            } => lite::encode_set_lite_config(
                addressing.target,
                addressing.controller,
                sequence_id,
                interface,
                lite::LiteConfigFlags(flags),
                &mut out,
            ),
            Request::GetWirelessStatus { interface } => wireless::encode_get_wireless_status(
                addressing.target,
                addressing.controller,
                sequence_id,
                interface,
                &mut out,
            ),
            Request::SetWirelessConfig {
                interface, flags, ..
            } => wireless::encode_set_wireless_config(
                addressing.target,
                addressing.controller,
                sequence_id,
                interface,
                wireless::WirelessConfigFlags(flags),
                &mut out,
            ),
            Request::GetMilanInfo => mvu::encode_get_milan_info(
                addressing.target,
                addressing.controller,
                sequence_id,
                &mut out,
            ),
            Request::GetMediaClockReference { domain } => mvu::encode_get_media_clock_reference(
                addressing.target,
                addressing.controller,
                sequence_id,
                domain,
                &mut out,
            ),
            Request::GetStreamInfo {
                descriptor_type,
                index,
            } => aem::encode_get_stream_info(addressing, descriptor_type, index, &mut out),
            Request::GetAvbInfo { index } => aem::encode_get_avb_info(addressing, index, &mut out),
            Request::GetAsPath { index } => aem::encode_get_as_path(addressing, index, &mut out),
            Request::GetCounters {
                descriptor_type,
                index,
            } => aem::encode_get_counters(addressing, descriptor_type, index, &mut out),
            Request::Identify { control, on, .. } => {
                aem::encode_set_control(addressing, control, &[if on { 255 } else { 0 }], &mut out)
            }
            Request::SetName { set, .. } => {
                let configuration = match set.descriptor_type {
                    DescriptorType::ENTITY | DescriptorType::CONFIGURATION => 0,
                    _ => self
                        .models
                        .get(&inflight.entity_id)
                        .map_or(0, |model| model.configuration),
                };
                SetName {
                    configuration,
                    ..set
                }
                .encode(addressing, &mut out)
            }
            Request::SetStreamFormat { set, .. } => set.encode(addressing, &mut out),
            Request::Streaming {
                descriptor_type,
                index,
                start,
                ..
            } => aem::encode_streaming(addressing, start, descriptor_type, index, &mut out),
            Request::SetSamplingRate { set, .. } => set.encode(addressing, &mut out),
            Request::SetClockSource { set, .. } => set.encode(addressing, &mut out),
            Request::SetConfiguration { configuration, .. } => {
                aem::encode_set_configuration(addressing, configuration, &mut out)
            }
            Request::ReadOther {
                configuration,
                descriptor_type,
                index,
            } => aem::encode_read_descriptor(
                addressing,
                configuration,
                descriptor_type,
                index,
                &mut out,
            ),
            Request::GetMaxTransitTime { output, .. } => {
                aem::encode_get_max_transit_time(addressing, output, &mut out)
            }
            Request::SetMaxTransitTime { set, .. } => set.encode(addressing, &mut out),
            Request::ReadForCaller {
                descriptor_type,
                index,
                ..
            } => {
                let configuration = self
                    .models
                    .get(&inflight.entity_id)
                    .map_or(0, |model| model.configuration);
                aem::encode_read_descriptor(
                    addressing,
                    configuration,
                    descriptor_type,
                    index,
                    &mut out,
                )
            }
            Request::GetTxState { output, .. } => Acmpdu::command(
                AcmpMessageType::GET_TX_STATE_COMMAND,
                addressing.controller,
                (addressing.target, output),
                (EntityId(0), 0),
                sequence_id,
            )
            .encode(&mut out),
            // The connection's index goes in connection_count (8.2.1.18).
            Request::GetTxConnection { output, index, .. } => Acmpdu {
                connection_count: index,
                ..Acmpdu::command(
                    AcmpMessageType::GET_TX_CONNECTION_COMMAND,
                    addressing.controller,
                    (addressing.target, output),
                    (EntityId(0), 0),
                    sequence_id,
                )
            }
            .encode(&mut out),
            Request::DisconnectTx {
                output,
                listener,
                listener_unique_id,
                ..
            } => Acmpdu::command(
                AcmpMessageType::DISCONNECT_TX_COMMAND,
                addressing.controller,
                (addressing.target, output),
                (listener, listener_unique_id),
                sequence_id,
            )
            .encode(&mut out),
            Request::SetControl { index, command } => aem::encode_set_control(
                addressing,
                index,
                self.control_values
                    .get(&command)
                    .map_or(&[][..], Vec::as_slice),
                &mut out,
            ),
            Request::GetAudioMap {
                descriptor_type,
                index,
                map_index,
            } => aem::encode_get_audio_map(addressing, descriptor_type, index, map_index, &mut out),
            Request::ChangeMappings {
                change,
                descriptor_type,
                index,
                command,
            } => aem::encode_audio_mappings(
                addressing,
                change,
                descriptor_type,
                index,
                self.mapping_changes
                    .get(&command)
                    .map_or(&[][..], Vec::as_slice),
                &mut out,
            ),
            Request::GetDynamicInfo { queries, count } => {
                let configuration = self
                    .models
                    .get(&inflight.entity_id)
                    .map_or(0, |model| model.configuration);
                aem::encode_get_dynamic_info(
                    addressing,
                    configuration,
                    &queries[..usize::from(count)],
                    &mut out,
                )
            }
            Request::ReadMemory { index, offset } => {
                let Some((address, length)) = self
                    .models
                    .get(&inflight.entity_id)
                    .and_then(|model| memory_part(model, index, offset))
                else {
                    return false;
                };
                // As many zeros as it asks for: ESP32 endpoints answer a
                // READ in place, in a response as long as the command.
                let zeros = [0; MEMORY_SEGMENT as usize];
                let mut tlv = [0; AaTlv::HEADER_LEN + MEMORY_SEGMENT as usize];
                let read = AaTlv {
                    mode: AaMode::READ,
                    length,
                    address,
                    data: &zeros[..usize::from(length)],
                };
                read.encode(&mut tlv).and_then(|_| {
                    AddressAccessPdu {
                        header: AecpHeader {
                            message_type: AecpMessageType::ADDRESS_ACCESS_COMMAND,
                            status: 0,
                            target_entity_id: addressing.target,
                            controller_entity_id: addressing.controller,
                            sequence_id,
                        },
                        tlv_count: 1,
                        tlvs: &tlv[..AaTlv::HEADER_LEN + usize::from(length)],
                    }
                    .encode(&mut out)
                })
            }
            Request::GetRxState { input } => acmp(
                AcmpMessageType::GET_RX_STATE_COMMAND,
                (EntityId(0), 0),
                input,
                &mut out,
            ),
            Request::Bind {
                talker,
                talker_unique_id,
                input,
                class_b,
                ..
            } => {
                let mut connect = Acmpdu::command(
                    AcmpMessageType::CONNECT_RX_COMMAND,
                    addressing.controller,
                    (talker, talker_unique_id),
                    (addressing.target, input),
                    sequence_id,
                );
                if class_b {
                    connect.flags |= AcmpFlags::CLASS_B;
                }
                connect.encode(&mut out)
            }
            Request::Unbind {
                talker,
                talker_unique_id,
                input,
                ..
            } => acmp(
                AcmpMessageType::DISCONNECT_RX_COMMAND,
                (talker, talker_unique_id),
                input,
                &mut out,
            ),
        };
        match length {
            Ok(length) => {
                self.outgoing
                    .push_back((destination, out[..length].to_vec()));
                true
            }
            Err(_) => false,
        }
    }

    /// How long to wait for the response to `request`: ACMP's timeouts
    /// for the message, Milan's for Milan entities, else 250 ms.
    fn timeout(&self, entity_id: EntityId, request: Request) -> Duration {
        let Some(message_type) = request.acmp_message() else {
            return COMMAND_TIMEOUT;
        };
        let milan = self
            .models
            .get(&entity_id)
            .is_some_and(|model| model.milan.is_some());
        let millis = if milan {
            message_type.milan_timeout_ms()
        } else {
            message_type.timeout_ms()
        };
        Duration::from_millis(u64::from(millis.unwrap_or(250)))
    }

    fn next_command(&mut self) -> CommandId {
        self.next_command = self.next_command.wrapping_add(1);
        CommandId(self.next_command)
    }

    /// Queues a caller's request ahead of the entity's queries, after the
    /// caller's earlier ones so they happen in order, or finishes it at
    /// once if the entity is not online.
    fn queue_command(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        command: CommandId,
        request: Request,
    ) {
        if !self.entities.contains_key(&entity_id) {
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
            return;
        }
        let queue = &mut self.sessions.entry(entity_id).or_default().queue;
        let place = queue
            .iter()
            .position(|queued| queued.command().is_none())
            .unwrap_or(queue.len());
        queue.insert(place, request);
        self.pump(now);
    }

    /// Renames a descriptor (SET_NAME): for the ENTITY, `name_index` 0 is
    /// its entity_name and 1 its group_name; for other descriptors 0 is
    /// the object_name. A name longer than 64 octets of UTF-8 is not
    /// possible.
    pub fn set_name(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
        name_index: u16,
        name: &str,
    ) -> CommandId {
        let command = self.next_command();
        let Some(name) = aem::aem_name(name) else {
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
            return command;
        };
        let set = SetName {
            descriptor_type,
            index,
            name_index,
            configuration: 0,
            name,
        };
        self.queue_command(now, entity_id, command, Request::SetName { set, command });
        command
    }

    /// Changes a STREAM_INPUT's or STREAM_OUTPUT's format
    /// (SET_STREAM_FORMAT). Entities refuse while the stream runs.
    pub fn set_stream_format(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
        format: StreamFormat,
    ) -> CommandId {
        let command = self.next_command();
        let set = SetStreamFormat {
            descriptor_type,
            index,
            format,
        };
        let request = Request::SetStreamFormat { set, command };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Starts a STREAM_INPUT or STREAM_OUTPUT streaming again after
    /// [`Controller::stop_streaming`] (START_STREAMING).
    pub fn start_streaming(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
    ) -> CommandId {
        self.streaming(now, entity_id, descriptor_type, index, true)
    }

    /// Stops a STREAM_INPUT or STREAM_OUTPUT streaming (STOP_STREAMING),
    /// as entities take a new format only while the stream is stopped.
    pub fn stop_streaming(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
    ) -> CommandId {
        self.streaming(now, entity_id, descriptor_type, index, false)
    }

    fn streaming(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
        start: bool,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::Streaming {
            descriptor_type,
            index,
            start,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Changes an AUDIO_UNIT's sampling rate (SET_SAMPLING_RATE), then
    /// reads its streams again, whose formats may follow it.
    pub fn set_sampling_rate(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
        rate: SamplingRate,
    ) -> CommandId {
        let command = self.next_command();
        let set = SetSamplingRate {
            descriptor_type,
            index,
            rate,
        };
        let request = Request::SetSamplingRate { set, command };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Allows or disallows an AVB_INTERFACE's talkers escalating streams to
    /// multicast in AVB Lite (SET_LITE_CONFIG, AVB Lite profile 2.4).
    pub fn set_lite_config(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        interface: u16,
        escalation_allowed: bool,
    ) -> CommandId {
        let command = self.next_command();
        let flags = if escalation_allowed {
            lite::LiteConfigFlags::ESCALATION_ALLOWED.0
        } else {
            0
        };
        let request = Request::SetLiteConfig {
            interface,
            flags,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Allows an access point to admit Class A toward its wireless port,
    /// where it delivers 12000 frames a second, or keeps Class A off the hop
    /// (SET_WIRELESS_CONFIG, AVB Wireless profile 4 and 5.2).
    pub fn set_wireless_config(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        interface: u16,
        class_a_allowed: bool,
    ) -> CommandId {
        let command = self.next_command();
        let flags = if class_a_allowed {
            wireless::WirelessConfigFlags::CLASS_A_ALLOWED.0
        } else {
            0
        };
        let request = Request::SetWirelessConfig {
            interface,
            flags,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Picks a CLOCK_DOMAIN's clock source (SET_CLOCK_SOURCE).
    pub fn set_clock_source(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        domain: u16,
        source: u16,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::SetClockSource {
            set: SetClockSource { domain, source },
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Makes `configuration` the entity's current configuration
    /// (SET_CONFIGURATION); once it answers, the entity is read again in
    /// it.
    pub fn set_configuration(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        configuration: u16,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::SetConfiguration {
            configuration,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Sets a control's current values (SET_CONTROL), encoded as its value
    /// type keeps them (see [`control::encode_values`]); the entity answers
    /// with the values it has after, set or not, and the model takes them.
    /// Up to [`aem::MAX_CONTROL_VALUES`] octets.
    ///
    /// [`control::encode_values`]: crate::control::encode_values
    pub fn set_control(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        index: u16,
        values: &[u8],
    ) -> CommandId {
        let command = self.next_command();
        if values.is_empty() || values.len() > aem::MAX_CONTROL_VALUES {
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
            return command;
        }
        self.control_values.insert(command, values.to_vec());
        self.queue_command(
            now,
            entity_id,
            command,
            Request::SetControl { index, command },
        );
        if !self.entities.contains_key(&entity_id) {
            self.control_values.remove(&command);
        }
        command
    }

    /// Reads one of an entity's descriptors again, as after a
    /// notification, the model taking what it holds now: to follow what
    /// other controllers change on entities that send no notifications.
    pub fn refresh_descriptor(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
    ) {
        if self.read(entity_id, descriptor_type, index) {
            self.queue_read(entity_id, descriptor_type, index, true);
            self.pump(now);
        }
    }

    /// Asks an entity again how one of its streams stands: its stream
    /// info, and its counters where the controller reads them, which
    /// entities that send no notifications never tell as they change.
    pub fn refresh_stream(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
    ) {
        if !self.read(entity_id, descriptor_type, index) {
            return;
        }
        self.queue_query(
            entity_id,
            Request::GetStreamInfo {
                descriptor_type,
                index,
            },
        );
        if self.config.read_counters {
            self.queue_query(
                entity_id,
                Request::GetCounters {
                    descriptor_type,
                    index,
                },
            );
        }
        self.pump(now);
    }

    /// Whether an entity is read, with the descriptor named.
    fn read(&self, entity_id: EntityId, descriptor_type: DescriptorType, index: u16) -> bool {
        self.models.get(&entity_id).is_some_and(|model| {
            model.state == EnumerationState::Complete && model.has(descriptor_type, index)
        })
    }

    /// Asks a talker what it has of a stream output (GET_TX_STATE): its
    /// stream ID, destination, VLAN and how many listen, which the model
    /// then holds.
    pub fn tx_state(&mut self, now: Instant, talker: (EntityId, u16)) -> CommandId {
        let command = self.next_command();
        let request = Request::GetTxState {
            output: talker.1,
            command: Some(command),
        };
        self.queue_command(now, talker.0, command, request);
        command
    }

    /// Asks a talker for the listener of one of a stream output's
    /// connections, by its index below the output's connection count
    /// (GET_TX_CONNECTION), which the model then holds.
    pub fn tx_connection(
        &mut self,
        now: Instant,
        talker: (EntityId, u16),
        index: u16,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::GetTxConnection {
            output: talker.1,
            index,
            command: Some(command),
        };
        self.queue_command(now, talker.0, command, request);
        command
    }

    /// Tells a talker to stop sending a stream output to a listener's
    /// stream input (DISCONNECT_TX), without the listener: for a talker
    /// still sending to a listener that went away.
    pub fn disconnect_talker(
        &mut self,
        now: Instant,
        talker: (EntityId, u16),
        listener: (EntityId, u16),
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::DisconnectTx {
            output: talker.1,
            listener: listener.0,
            listener_unique_id: listener.1,
            command,
        };
        self.queue_command(now, talker.0, command, request);
        command
    }

    /// Reads a stream output's max transit time (GET_MAX_TRANSIT_TIME)
    /// into the model.
    pub fn max_transit_time(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        output: u16,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::GetMaxTransitTime {
            output,
            command: Some(command),
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Sets a stream output's max transit time in nanoseconds
    /// (SET_MAX_TRANSIT_TIME), zero for the entity's default; only while
    /// the stream is not running.
    pub fn set_max_transit_time(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        output: u16,
        nanoseconds: u64,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::SetMaxTransitTime {
            set: MaxTransitTime {
                output,
                nanoseconds,
            },
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Reads a descriptor again (READ_DESCRIPTOR) into the model, whatever
    /// enumeration read; the command finishes when the entity answers.
    pub fn read_descriptor(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        descriptor_type: DescriptorType,
        index: u16,
    ) -> CommandId {
        let command = self.next_command();
        let request = Request::ReadForCaller {
            descriptor_type,
            index,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Takes the max transit time a response or notification carries for
    /// a stream output into the model.
    fn store_max_transit_time(&mut self, entity_id: EntityId, output: u16, payload: &[u8]) {
        if let Ok(time) = MaxTransitTime::decode(payload)
            && time.output == output
            && let Some(model) = self.models.get_mut(&entity_id)
            && model.has(DescriptorType::STREAM_OUTPUT, output)
            && model.set_max_transit_time(output, time.nanoseconds)
            && model.state == EnumerationState::Complete
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Asks an entity outside Milan, asked first for its first stream
    /// output's max transit time alone, for the others it has not told,
    /// once it answers for that one.
    fn read_other_transit_times(&mut self, entity_id: EntityId, answered: u16) {
        let Some(model) = self.models.get(&entity_id) else {
            return;
        };
        if model.milan.is_some() {
            return;
        }
        let mut outputs = model
            .descriptors(DescriptorType::STREAM_OUTPUT)
            .map(|(output, _)| output);
        if outputs.next() != Some(answered) {
            return;
        }
        let others: Vec<u16> = outputs
            .filter(|&output| model.max_transit_time(output).is_none())
            .collect();
        let queue = &mut self.sessions.entry(entity_id).or_default().queue;
        for output in others {
            queue.push_back(Request::GetMaxTransitTime {
                output,
                command: None,
            });
        }
    }

    /// Forgets what a caller's command was to send, once it is answered or
    /// given up.
    fn drop_command_data(&mut self, command: CommandId) {
        self.mapping_changes.remove(&command);
        self.control_values.remove(&command);
    }

    /// Takes a control's current values into its entity's model.
    fn store_control(&mut self, entity_id: EntityId, index: u16, values: &[u8]) {
        if let Some(model) = self.models.get_mut(&entity_id)
            && model.apply_control(index, values)
            && model.state == EnumerationState::Complete
        {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Adds mappings to a stream port's dynamic mappings
    /// (ADD_AUDIO_MAPPINGS): stream channels to an input's cluster
    /// channels, or an output's cluster channels to stream channels. The
    /// entity refuses the whole change if any mapping is not valid, and
    /// may replace a mapping to the same channel; the map is read again
    /// after. From 1 to [`aem::MAX_MAPPINGS_PER_CHANGE`] mappings.
    pub fn add_audio_mappings(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        port: (DescriptorType, u16),
        mappings: &[AudioMapping],
    ) -> CommandId {
        self.change_mappings(now, entity_id, MappingChange::Add, port, mappings)
    }

    /// Removes mappings from a stream port's dynamic mappings
    /// (REMOVE_AUDIO_MAPPINGS), as for
    /// [`add_audio_mappings`](Self::add_audio_mappings).
    pub fn remove_audio_mappings(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        port: (DescriptorType, u16),
        mappings: &[AudioMapping],
    ) -> CommandId {
        self.change_mappings(now, entity_id, MappingChange::Remove, port, mappings)
    }

    fn change_mappings(
        &mut self,
        now: Instant,
        entity_id: EntityId,
        change: MappingChange,
        (descriptor_type, index): (DescriptorType, u16),
        mappings: &[AudioMapping],
    ) -> CommandId {
        let command = self.next_command();
        if mappings.is_empty() || mappings.len() > aem::MAX_MAPPINGS_PER_CHANGE {
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
            return command;
        }
        self.mapping_changes.insert(command, mappings.to_vec());
        let request = Request::ChangeMappings {
            change,
            descriptor_type,
            index,
            command,
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Binds a listener's stream input to a talker's stream output
    /// (CONNECT_RX, which Milan calls BIND_RX). Where the talker reports
    /// its output in class B, the connect carries CLASS_B, which the
    /// listener passes on to the talker: a talker that takes its class
    /// from the connect would otherwise go to class A.
    pub fn connect(
        &mut self,
        now: Instant,
        talker: (EntityId, u16),
        listener: (EntityId, u16),
    ) -> CommandId {
        let command = self.next_command();
        let class_b = self
            .models
            .get(&talker.0)
            .and_then(|model| model.stream_info(DescriptorType::STREAM_OUTPUT, talker.1))
            .is_some_and(|info| info.flags.contains(StreamInfoFlags::CLASS_B));
        let request = Request::Bind {
            talker: talker.0,
            talker_unique_id: talker.1,
            input: listener.1,
            class_b,
            command,
        };
        self.queue_command(now, listener.0, command, request);
        command
    }

    /// Unbinds a listener's stream input (DISCONNECT_RX, which Milan calls
    /// UNBIND_RX), naming the talker it is bound to when that is known.
    pub fn disconnect(&mut self, now: Instant, listener: (EntityId, u16)) -> CommandId {
        let command = self.next_command();
        let talker = self
            .models
            .get(&listener.0)
            .and_then(|model| model.binding(listener.1))
            .map_or((EntityId(0), 0), |binding| {
                (binding.talker, binding.talker_unique_id)
            });
        let request = Request::Unbind {
            talker: talker.0,
            talker_unique_id: talker.1,
            input: listener.1,
            command,
        };
        self.queue_command(now, listener.0, command, request);
        command
    }

    /// Turns on an entity's identify control, the one its advertisement
    /// names, and turns it off again after `duration`.
    pub fn identify(&mut self, now: Instant, entity_id: EntityId, duration: Duration) -> CommandId {
        let command = self.next_command();
        let control = self.entities.get(&entity_id).and_then(|entity| {
            entity
                .adp
                .entity_capabilities
                .contains(EntityCapabilities::AEM_IDENTIFY_CONTROL_INDEX_VALID)
                .then_some(entity.adp.identify_control_index)
        });
        let Some(control) = control else {
            self.events
                .push_back(Event::CommandFinished(command, Outcome::NotPossible));
            return command;
        };
        self.identify_off
            .insert(entity_id, (now + duration, control));
        let request = Request::Identify {
            control,
            on: true,
            command: Some(command),
        };
        self.queue_command(now, entity_id, command, request);
        command
    }

    /// Forgets entities whose valid time ran out by `now`, retries or
    /// gives up on commands not answered in time, and advertises when due.
    pub fn handle_timeout(&mut self, now: Instant) {
        self.start_advertising(now);
        let mut expired = Vec::new();
        self.entities.retain(|&entity_id, entity| {
            let keep = entity.expires > now;
            if !keep {
                expired.push(entity_id);
            }
            keep
        });
        for entity_id in expired {
            self.forget(entity_id);
            self.events
                .push_back(Event::EntityOffline(entity_id, OfflineReason::TimedOut));
        }

        let late: Vec<((Channel, u16), Inflight)> = self
            .inflight
            .iter()
            .filter(|(_, inflight)| inflight.deadline <= now)
            .map(|(&key, &inflight)| (key, inflight))
            .collect();
        for (key, inflight) in late {
            if !inflight.retried {
                let retry = Inflight {
                    deadline: now + self.timeout(inflight.entity_id, inflight.request),
                    retried: true,
                    ..inflight
                };
                self.inflight.insert(key, retry);
                self.send(key, retry);
                continue;
            }
            self.complete(key, inflight);
            if let Request::ReadDescriptor {
                descriptor_type,
                refresh,
                ..
            } = inflight.request
            {
                self.read_failed(
                    inflight.entity_id,
                    descriptor_type,
                    refresh,
                    EnumerationFailure::NoResponse,
                );
            }
            // An entity that never answered the query is not asked again.
            if let Request::GetLiteStatus { .. } = inflight.request
                && let Some(model) = self.models.get_mut(&inflight.entity_id)
                && model.lite_supported.is_none()
            {
                model.lite_supported = Some(false);
            }
            // An entity that does not answer is asked again at the next
            // poll, and taken not to answer only after a few silences.
            if let Request::GetWirelessStatus { .. } = inflight.request
                && let Some(model) = self.models.get_mut(&inflight.entity_id)
                && model.wireless_supported.is_none()
            {
                model.wireless_misses += 1;
                if model.wireless_misses >= WIRELESS_MISSES {
                    model.wireless_supported = Some(false);
                } else if !self.config.wireless_poll.is_zero() {
                    self.next_wireless_poll
                        .get_or_insert(now + self.config.wireless_poll);
                }
            }
            if let Request::ReadMemory { index, .. } = inflight.request {
                self.memory_reads.remove(&(inflight.entity_id, index));
            }
            if let Request::GetDynamicInfo { queries, count } = inflight.request {
                self.dynamic_info_answered(
                    inflight.entity_id,
                    &queries[..usize::from(count)],
                    None,
                );
            }
            if let Some(command) = inflight.request.command() {
                self.drop_command_data(command);
                self.events
                    .push_back(Event::CommandFinished(command, Outcome::NoResponse));
            }
            self.check_complete(inflight.entity_id);
        }

        let due: Vec<(EntityId, u16)> = self
            .identify_off
            .iter()
            .filter(|(_, (when, _))| *when <= now)
            .map(|(&entity_id, &(_, control))| (entity_id, control))
            .collect();
        for (entity_id, control) in due {
            self.identify_off.remove(&entity_id);
            self.queue_query(
                entity_id,
                Request::Identify {
                    control,
                    on: false,
                    command: None,
                },
            );
        }

        self.poll_lite(now);
        self.poll_wireless(now);
        self.age_cvu_talkers(now);

        if let Some(advertiser) = &mut self.advertiser
            && advertiser.next.is_some_and(|next| next <= now)
        {
            let index = advertiser.available_index;
            advertiser.available_index = index.wrapping_add(1);
            advertiser.next = Some(now + advertiser.valid() / 4);
            let adpdu = self.own_adpdu(AdpMessageType::ENTITY_AVAILABLE, index);
            self.queue_adp(&adpdu);
        }
        self.pump(now);
    }

    /// Asks each entity that answers the AVB Lite status query again, every
    /// `lite_poll`.
    fn poll_lite(&mut self, now: Instant) {
        if self.next_lite_poll.is_none_or(|next| next > now) {
            return;
        }
        let asked: Vec<(EntityId, u16)> = self
            .models
            .iter()
            .filter(|(_, model)| model.lite_supported == Some(true))
            .flat_map(|(&entity_id, model)| {
                model
                    .descriptors(DescriptorType::AVB_INTERFACE)
                    .map(move |(interface, _)| (entity_id, interface))
            })
            .collect();
        // The timer stops once no entity answers the query.
        self.next_lite_poll = (!asked.is_empty()).then(|| now + self.config.lite_poll);
        for (entity_id, interface) in asked {
            self.queue_query(entity_id, Request::GetLiteStatus { interface });
        }
    }

    /// Asks each wireless interface for its AVB Wireless status again,
    /// every `wireless_poll`.
    fn poll_wireless(&mut self, now: Instant) {
        if self.next_wireless_poll.is_none_or(|next| next > now) {
            return;
        }
        let mut asked: Vec<(EntityId, u16)> = self
            .models
            .iter()
            .flat_map(|(&entity_id, model)| {
                model
                    .wireless_interfaces()
                    .map(move |(interface, _)| (entity_id, interface))
            })
            .collect();
        // Entities whose queries went unanswered are asked again, every
        // AVB interface, until they answer or have missed too often.
        asked.extend(
            self.models
                .iter()
                .filter(|(_, model)| {
                    model.wireless_supported.is_none() && model.wireless_misses > 0
                })
                .flat_map(|(&entity_id, model)| {
                    model
                        .descriptors(DescriptorType::AVB_INTERFACE)
                        .map(move |(interface, _)| (entity_id, interface))
                }),
        );
        // The timer stops once no interface is wireless or waits for an
        // answer.
        self.next_wireless_poll = (!asked.is_empty()).then(|| now + self.config.wireless_poll);
        for (entity_id, interface) in asked {
            self.queue_query(entity_id, Request::GetWirelessStatus { interface });
        }
    }

    /// Forgets CVU SRP declarations not refreshed for [`CVU_LIFETIME`].
    fn age_cvu_talkers(&mut self, now: Instant) {
        let Some(before) = now.checked_sub(CVU_LIFETIME) else {
            return;
        };
        let mut aged = Vec::new();
        for (&entity_id, model) in &mut self.models {
            if model.age_cvu_talkers(before) {
                aged.push(entity_id);
            }
        }
        for entity_id in aged {
            self.events.push_back(Event::EntityModelChanged(entity_id));
        }
    }

    /// Schedules the first advertisement, a random moment after the
    /// controller first sees the time.
    fn start_advertising(&mut self, now: Instant) {
        if let Some(advertiser) = &mut self.advertiser
            && !advertiser.started
        {
            advertiser.started = true;
            advertiser.next = Some(now + self.random.up_to(advertiser.delay_limit()));
        }
    }

    fn own_adpdu(&self, message_type: AdpMessageType, available_index: u32) -> Adpdu {
        let advertise = self.advertiser.as_ref().map(|advertiser| advertiser.config);
        Adpdu {
            message_type,
            valid_time: if message_type == AdpMessageType::ENTITY_AVAILABLE {
                advertise.map_or(31, |advertise| advertise.valid_time.clamp(1, 31))
            } else {
                0
            },
            entity_id: self.config.entity_id,
            entity_model_id: advertise
                .map_or_else(Default::default, |advertise| advertise.entity_model_id),
            controller_capabilities: ControllerCapabilities::IMPLEMENTED,
            available_index,
            ..Adpdu::default()
        }
    }

    fn queue_adp(&mut self, adpdu: &Adpdu) {
        if let Ok(bytes) = adpdu.to_bytes() {
            self.outgoing
                .push_back((crate::ADP_ACMP_MULTICAST, bytes.to_vec()));
        }
    }

    /// When [`handle_timeout`](Self::handle_timeout) next has work.
    pub fn poll_timeout(&self) -> Option<Instant> {
        let expiries = self.entities.values().map(|entity| entity.expires);
        let deadlines = self.inflight.values().map(|inflight| inflight.deadline);
        let advertise = self
            .advertiser
            .as_ref()
            .and_then(|advertiser| advertiser.next);
        let identify = self.identify_off.values().map(|(when, _)| *when);
        let lite = self.next_lite_poll;
        let wireless = self.next_wireless_poll;
        let declarations = self
            .models
            .values()
            .filter_map(EntityModel::oldest_cvu_talker)
            .map(|heard| heard + CVU_LIFETIME);
        expiries
            .chain(deadlines)
            .chain(advertise)
            .chain(identify)
            .chain(lite)
            .chain(wireless)
            .chain(declarations)
            .min()
    }

    /// Copies the next frame to send into `out`. A frame that does not
    /// fit stays queued; 1500 octets always suffice.
    pub fn poll_transmit(&mut self, out: &mut [u8]) -> Result<Option<Transmit>, EncodeError> {
        let Some((destination, bytes)) = self.outgoing.front() else {
            return Ok(None);
        };
        let length = bytes.len();
        let Some(target) = out.get_mut(..length) else {
            return Err(EncodeError::BufferTooSmall {
                needed: length,
                available: out.len(),
            });
        };
        target.copy_from_slice(bytes);
        let destination = *destination;
        self.outgoing.pop_front();
        Ok(Some(Transmit {
            destination,
            length,
        }))
    }

    pub fn poll_event(&mut self) -> Option<Event> {
        self.events.pop_front()
    }

    pub fn entity(&self, entity_id: EntityId) -> Option<&DiscoveredEntity> {
        self.entities.get(&entity_id)
    }

    /// The entities online, by entity ID.
    pub fn entities(&self) -> impl Iterator<Item = &DiscoveredEntity> {
        self.entities.values()
    }

    /// What has been read of an entity's model.
    pub fn model(&self, entity_id: EntityId) -> Option<&EntityModel> {
        self.models.get(&entity_id)
    }

    /// Whether commands to the entity are queued or waiting for an answer,
    /// such as the queries that follow reading its descriptors.
    pub fn busy(&self, entity_id: EntityId) -> bool {
        self.sessions
            .get(&entity_id)
            .is_some_and(|session| session.inflight.is_some() || !session.queue.is_empty())
    }

    /// Frames received that did not decode.
    pub fn malformed_frames(&self) -> u64 {
        self.malformed
    }
}

/// Whether an ACMP message goes to or comes from the talker: the TX
/// commands and their responses.
fn to_talker(message: AcmpMessageType) -> bool {
    matches!(
        message.0 & !1,
        0 | 2 | 4 | 12 // CONNECT_TX, DISCONNECT_TX, GET_TX_STATE, GET_TX_CONNECTION
    )
}

/// The values a SET_CONTROL or GET_CONTROL response or notification for
/// CONTROL `index` carries.
fn control_values(payload: &[u8], index: u16) -> Option<&[u8]> {
    let (descriptor_type, named) = aem::target_descriptor(payload)?;
    (descriptor_type == DescriptorType::CONTROL && named == index)
        .then(|| payload.get(4..))
        .flatten()
        .filter(|values| !values.is_empty())
}

/// The responses to another controller this one learns from, as from a
/// notification: those that changed what the model holds, or read how a
/// stream or an interface stands.
fn overheard(command_type: AemCommandType) -> bool {
    matches!(
        command_type,
        AemCommandType::SET_CONFIGURATION
            | AemCommandType::SET_STREAM_FORMAT
            | AemCommandType::SET_STREAM_INFO
            | AemCommandType::GET_STREAM_INFO
            | AemCommandType::SET_NAME
            | AemCommandType::SET_SAMPLING_RATE
            | AemCommandType::SET_CLOCK_SOURCE
            | AemCommandType::SET_CONTROL
            | AemCommandType::GET_AVB_INFO
            | AemCommandType::GET_AS_PATH
            | AemCommandType::GET_COUNTERS
            | AemCommandType::ADD_AUDIO_MAPPINGS
            | AemCommandType::REMOVE_AUDIO_MAPPINGS
            | AemCommandType::SET_MAX_TRANSIT_TIME
    )
}

/// Whether a memory object is a logo the controller reads: a PNG of the
/// entity or of its vendor, of a length an image needs.
fn is_logo(object: &MemoryObjectDescriptor<'_>) -> bool {
    matches!(
        object.memory_object_type,
        MemoryObjectType::PNG_ENTITY | MemoryObjectType::PNG_MANUFACTURER
    ) && (1..=MAX_LOGO).contains(&object.length)
}

/// Where the part of memory object `index` from `offset` starts, and how
/// many octets of it one read asks for: as many as the entity's segments
/// and one response hold, to the object's end.
fn memory_part(model: &EntityModel, index: u16, offset: u32) -> Option<(u64, u16)> {
    let object = model
        .memory_objects()
        .find(|object| object.index == index)
        .filter(is_logo)?;
    let left = object.length.checked_sub(u64::from(offset))?;
    let segment = object
        .maximum_segment_length
        .filter(|&segment| segment > 0)
        .map_or(MEMORY_SEGMENT, |segment| segment.min(MEMORY_SEGMENT));
    let length = u16::try_from(left.min(segment))
        .ok()
        .filter(|&length| length > 0)?;
    Some((object.start_address.checked_add(u64::from(offset))?, length))
}

fn command_type_of(request: Request) -> AemCommandType {
    match request {
        Request::ReadDescriptor { .. } => AemCommandType::READ_DESCRIPTOR,
        Request::RegisterUnsolicited => AemCommandType::REGISTER_UNSOLICITED_NOTIFICATION,
        Request::GetStreamInfo { .. } => AemCommandType::GET_STREAM_INFO,
        Request::GetAvbInfo { .. } => AemCommandType::GET_AVB_INFO,
        Request::GetAsPath { .. } => AemCommandType::GET_AS_PATH,
        Request::GetCounters { .. } => AemCommandType::GET_COUNTERS,
        Request::Identify { .. } => AemCommandType::SET_CONTROL,
        Request::SetName { .. } => AemCommandType::SET_NAME,
        Request::SetStreamFormat { .. } => AemCommandType::SET_STREAM_FORMAT,
        Request::Streaming { start: true, .. } => AemCommandType::START_STREAMING,
        Request::Streaming { start: false, .. } => AemCommandType::STOP_STREAMING,
        Request::SetSamplingRate { .. } => AemCommandType::SET_SAMPLING_RATE,
        Request::SetClockSource { .. } => AemCommandType::SET_CLOCK_SOURCE,
        Request::SetConfiguration { .. } => AemCommandType::SET_CONFIGURATION,
        Request::SetControl { .. } => AemCommandType::SET_CONTROL,
        Request::GetMaxTransitTime { .. } => AemCommandType::GET_MAX_TRANSIT_TIME,
        Request::SetMaxTransitTime { .. } => AemCommandType::SET_MAX_TRANSIT_TIME,
        Request::ReadForCaller { .. } | Request::ReadOther { .. } => {
            AemCommandType::READ_DESCRIPTOR
        }
        Request::GetDynamicInfo { .. } => AemCommandType::GET_DYNAMIC_INFO,
        Request::GetAudioMap { .. } => AemCommandType::GET_AUDIO_MAP,
        Request::ChangeMappings { change, .. } => change.command_type(),
        // Not AEM commands; never match an AEM response.
        Request::GetMilanInfo
        | Request::GetMediaClockReference { .. }
        | Request::GetLiteStatus { .. }
        | Request::SetLiteConfig { .. }
        | Request::GetWirelessStatus { .. }
        | Request::SetWirelessConfig { .. }
        | Request::GetRxState { .. }
        | Request::Bind { .. }
        | Request::Unbind { .. }
        | Request::GetTxState { .. }
        | Request::GetTxConnection { .. }
        | Request::DisconnectTx { .. }
        | Request::ReadMemory { .. } => AemCommandType(0xffff),
    }
}

/// What changes on an entity in a descriptor of this type: its name, and
/// for a stream its format, an audio unit its sampling rate and a clock
/// domain its clock source.
fn dynamic_queries(descriptor_type: DescriptorType, index: u16) -> Vec<DynamicQuery> {
    let mut queries = Vec::new();
    if descriptor_type.has_object_name() {
        queries.push(DynamicQuery::Name {
            descriptor_type,
            index,
            name_index: 0,
        });
    }
    match descriptor_type {
        DescriptorType::STREAM_INPUT | DescriptorType::STREAM_OUTPUT => {
            queries.push(DynamicQuery::StreamFormat {
                descriptor_type,
                index,
            });
        }
        DescriptorType::AUDIO_UNIT => queries.push(DynamicQuery::SamplingRate {
            descriptor_type,
            index,
        }),
        DescriptorType::CLOCK_DOMAIN => queries.push(DynamicQuery::ClockSource { domain: index }),
        _ => {}
    }
    queries
}

/// The first GET_AUDIO_MAP of each of an entity's stream ports with
/// dynamic mappings.
fn audio_map_reads(model: &EntityModel) -> Vec<Request> {
    [true, false]
        .into_iter()
        .flat_map(|input| model.stream_ports(input))
        .filter(|port| port.has_dynamic_mappings())
        .map(|port| Request::GetAudioMap {
            descriptor_type: port.descriptor_type,
            index: port.index,
            map_index: 0,
        })
        .collect()
}

/// How an AEM command the caller asked for went, by its response.
fn aem_outcome(aem: &AemPdu<'_>) -> Outcome {
    if aem.status().is_success() {
        Outcome::Done
    } else {
        Outcome::Refused(Refusal::Aem(aem.status()))
    }
}

/// The response, if it decoded and is for the descriptor asked for.
fn matching<'a>(
    response: Result<ReadDescriptorResponse<'a>, DecodeError>,
    descriptor_type: DescriptorType,
    index: u16,
) -> Option<ReadDescriptorResponse<'a>> {
    response
        .ok()
        .filter(|response| response.descriptor_type == descriptor_type && response.index == index)
}

/// The same advertisement apart from the fields that change on every one
/// or do not describe the entity.
fn same_advertisement(left: &Adpdu, right: &Adpdu) -> bool {
    let normalized = |adpdu: &Adpdu| Adpdu {
        available_index: 0,
        valid_time: 0,
        ..*adpdu
    };
    normalized(left) == normalized(right)
}

#[cfg(test)]
mod tests;