prolink 0.5.0

Pioneer Pro DJ Link: browse and play from CDJs on the network, and serve a rekordbox medium to them
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
// SPDX-License-Identifier: GPL-3.0-only

//! Announcing ourselves as a player: the claim chain, the keep-alive and the
//! status stream.
//!
//! This is the **only** part of the library that transmits on a Pro DJ Link
//! port, which is what makes everything else passive by construction.
//!
//! # Two modes, and the difference is not cosmetic
//!
//! [`Numbering::Observer`] emits keep-alives at a number outside the player
//! range and never contends for anything. It is enough to be *seen*, and enough
//! for peers to start unicasting status to us โ€” which is what makes their slot
//! contents and the tempo master visible at all. It is **not** enough to be
//! browsed, and it cannot issue dbserver queries.
//!
//! [`Numbering::Claim`] runs the full handshake and takes a real player slot in
//! 1โ€“4. Necessary to be browsable, and the only mode that can disturb a live
//! rig, so it is opt-in, it refuses a number it has seen anyone else use, and it
//! backs off on conflict.
//!
//! The range is a requirement rather than a preference. At device 5 a deck
//! accepts the announcement completely โ€” it puts us in its device table and
//! unicasts hundreds of status packets to us โ€” and then never sends a single
//! media query, so it never offers us as a source. The check precedes the whole
//! browse path and the failure is silent (F45). [`BrowsableDeviceNumber`] exists
//! so that this cannot be configured by accident.
//!
//! # The handshake
//!
//! ```text
//! 3ร— hello โ†’ 3ร— claim_mac โ†’ 3ร— claim_ip โ†’ Nร— claim_number โ†’ keep_alive forever
//! ```
//!
//! All broadcast, ~300 ms apart. **N is 3 when the device boots into an empty
//! network and 1 when it joins one that already has peers** (C13) โ€” it is not
//! governed by the auto/manual assignment setting, which three controlled boots
//! with the setting held constant settle.
//!
//! Before any of that, we watch for [`PRESCAN`]. Silence is not evidence a
//! number is free: an XDJ-XZ and an Opus Quad do not defend their numbers with
//! conflict packets at all, so only having watched the network is.
//!
//! # Who was first, and why we give it up
//!
//! Keep-alive byte `0x25` says whether a device was first on the network, and
//! it is **not** latched at boot: it is a role the players settle between
//! them. Exactly one says `0x02`. A player that says `0x02` and hears another
//! say it too re-claims its number, stage 3 again, every few seconds, for as
//! long as it hears the other: S10-S24, the 20 sessions with this library's
//! ancestors on the link saying `0x02` beside a real deck, have 18-249 claims
//! each, and in S24b and S18 the claims stop while the other device is silent
//! and start again when it comes back saying `0x02`. Between two players it is
//! settled by an AUTO-numbered holder answering the claim with a unicast
//! `0x05` (S13 17.391, S26 5.606), at which the claimer says `0x01` from then
//! on.
//!
//! We announce as MANUAL and never send `0x05`, so we settle it the other way:
//! **we step aside.** Another device's keep-alive saying `0x02`, or a `0x05`
//! answering our own stage-3 claim, makes us say `0x01` for good. The role,
//! and whatever a player does with it (answering joiners, and perhaps
//! defending numbers, which no capture shows a player saying `0x01` doing),
//! stays with Pioneer's firmware. Saying `0x02` beside a real deck is what made
//! it re-claim for ever.

use std::collections::BTreeMap;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use prolink_proto::djl::{self, Body};
use prolink_proto::status::{self, CdjStatus, MediaState};
use prolink_proto::{
    BEAT_PORT, BrowsableDeviceNumber, DISCOVERY_PORT, DeviceKind, DeviceName, DeviceNumber,
    STATUS_PORT, Slot,
};
use tokio::net::UdpSocket;
use tokio::sync::{broadcast, watch};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};

use crate::discovery::Discovery;
use crate::media::{MediaDescription, MediaSource, NoMedia};
use crate::playback::{BeatPosition, Playback, PlaybackCell};
use crate::socket::{self, MAX_DATAGRAM};
use crate::{Error, Result};

/// How long to watch the network before claiming a number.
pub const PRESCAN: Duration = Duration::from_millis(2500);

/// How often [`VirtualCdj::query_media`] looks for its answer.
///
/// A deck answers a media query in **0.7 to 1.2 ms** โ€” three deck-to-deck
/// exchanges across `S4b-media-insert`, `S15b-sd-and-usb` and
/// `S16a-settings-over-link`, where this server takes 5 to 6 ms (S18). So the
/// wait is dominated by whether the datagram arrives at all, not by the poll.
const MEDIA_POLL: Duration = Duration::from_millis(10);

/// The number an observer takes: outside the 1โ€“6 player range, so it can never
/// collide with hardware โ€” and, being above 4, one a peer will never browse.
pub const OBSERVER_NUMBER: DeviceNumber = match DeviceNumber::new(7) {
    Some(number) => number,
    // Unreachable, and settled at compile time: 7 is not zero.
    None => DeviceNumber::ONE,
};

/// How often the beat emitter looks to see whether a beat is due.
///
/// The worst-case lateness of a beat packet, so it is a latency budget rather
/// than a rate: at 145 BPM a beat is 414 ms apart and 5 ms is 1.2% of one, well
/// inside what a deck's own jitter contributes.
const BEAT_TICK: Duration = Duration::from_millis(5);

/// How often the status emitter looks at what we publish.
///
/// So a change goes out at once rather than on the next 200 ms tick: a real
/// deck answering a master request names its successor in a status packet
/// 3.3-5.2 ms after the request, and the requester takes master on that
/// packet (S28, five hand-overs). Reading what we publish is a few atomics and
/// two short locks, the beat emitter's own cadence.
const STATUS_CHECK: Duration = Duration::from_millis(5);

/// The least time between two of our status packets.
///
/// S28's own floor: not one of its 4,834 status packets came less than 61.7 ms
/// after the one before to the same peer, and the early ones, sent on a
/// change, cluster at ~64 ms. A burst of changes goes out at that rate.
const STATUS_FLOOR: Duration = Duration::from_millis(62);

/// Keep-alive byte `0x25` when this device was first onto the network.
///
/// Held while no other device says it. A deck holding it keeps it as peers
/// join (F9), but gives it up when another device holding it answers its
/// claim (S26 5.606); see the module docs for why we give it up sooner.
const FIRST_ON_NETWORK: u8 = 0x02;
/// ...and when peers were already present, or another device holds the role.
const JOINED_PEERS: u8 = 0x01;

/// How a virtual CDJ gets its device number.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Numbering {
    /// Run the claim chain and hold a browsable number.
    ///
    /// Required to be browsed by a peer, and to issue dbserver queries.
    Claim {
        /// The number to try first. Any other browsable number is tried if it
        /// turns out to be taken; if all four are, starting fails with
        /// [`crate::Error::NoBrowsableNumber`] rather than silently degrading,
        /// because the degraded state cannot serve and the caller has to know.
        preferred: Option<BrowsableDeviceNumber>,
    },
    /// Announce at a fixed number without contending for it.
    ///
    /// Safe next to a live rig. Cannot be browsed, and cannot browse over
    /// dbserver.
    Observer(DeviceNumber),
}

impl Default for Numbering {
    fn default() -> Self {
        Self::Observer(OBSERVER_NUMBER)
    }
}

/// How to present ourselves.
#[derive(Clone, Debug)]
pub struct VirtualCdjConfig {
    /// The name to announce. `CDJ-2000nexus` is the exact casing real hardware
    /// uses (F1).
    pub name: DeviceName,
    /// What kind of device to claim to be.
    pub kind: DeviceKind,
    /// How to get a device number.
    pub numbering: Numbering,
    /// Keep-alive byte `0x35`, a product-generation code.
    ///
    /// `0x00` is what real nexus gear sends โ€” 148 packets from a CDJ-2000nexus
    /// and 91 from a DJM-2000nexus, all `0x00`, where the literature says
    /// `0x01` (C3). **`0x64` is required to coexist with CDJ-3000s**: the wrong
    /// value can make a CDJ-3000 set to player 5 or 6 repeatedly kick itself off
    /// the network.
    pub generation: u8,
    /// The firmware string to report in status packets.
    pub firmware: String,
    /// Whether to emit status packets on UDP 50002.
    ///
    /// Required for a peer to learn what is in our slots, and therefore for
    /// being browsable at all. Off means we are visible but have nothing to
    /// offer.
    pub emit_status: bool,
}

impl Default for VirtualCdjConfig {
    fn default() -> Self {
        Self {
            name: DeviceName::default(),
            kind: DeviceKind::CDJ,
            numbering: Numbering::default(),
            generation: 0x00,
            firmware: "1.44".to_owned(),
            emit_status: true,
        }
    }
}

/// Where the claim chain has got to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    /// Watching the network before claiming.
    Watching,
    /// Broadcasting the claim chain.
    Claiming,
    /// Holding a number and sending keep-alives.
    Announcing,
    /// Every candidate number was defended.
    Failed,
}

/// What each peer has loaded **from our media**, as its status packets report it.
///
/// A browsing deck needs a reference to compare rows against โ€” the key of the
/// track it has loaded โ€” and it does not compute that locally. It expects the
/// *server* to mark the loaded track's row, and it takes the key from whatever
/// row carries the mark. A listing with no marked row gives it nothing to
/// compare against and no row lights (F55).
///
/// So a server has to know what its clients have loaded. It does: a deck
/// unicasts status to us every ~200 ms naming the track, the player it came
/// from and the slot, and a track whose source player is us came off our
/// medium. That is the whole mechanism, and it is why this lives beside the
/// socket that already receives those packets rather than in the dbserver.
#[derive(Debug, Default)]
pub struct LoadedTracks {
    /// `(device, slot)` โ†’ the track id that device loaded from that slot.
    by_device: Mutex<BTreeMap<(u8, Slot), u32>>,
}

impl LoadedTracks {
    /// Record that `device` has `track` loaded from our `slot`.
    ///
    /// A track id of zero means nothing is loaded, and forgets the entry
    /// rather than marking row zero.
    pub fn note(&self, device: u8, slot: Slot, track: u32) {
        let Ok(mut loaded) = self.by_device.lock() else {
            return;
        };
        if track == 0 {
            loaded.remove(&(device, slot));
        } else {
            loaded.insert((device, slot), track);
        }
    }

    /// Forget everything a device had loaded, when it leaves the network.
    pub fn forget(&self, device: u8) {
        if let Ok(mut loaded) = self.by_device.lock() {
            loaded.retain(|(had, _), _| *had != device);
        }
    }

    /// Everyone reading from us, as `(device, slot, track)`.
    ///
    /// A serving host shows this: which players have taken a track off our
    /// media and which one each is holding. It is the same registry that marks
    /// the loaded row in a browse listing (F55), read the other way round.
    pub fn consumers(&self) -> Vec<(u8, Slot, u32)> {
        self.by_device.lock().map_or_else(
            |_| Vec::new(),
            |loaded| {
                loaded
                    .iter()
                    .map(|((device, slot), track)| (*device, *slot, *track))
                    .collect()
            },
        )
    }

    /// What `device` has loaded from `slot`, if anything.
    pub fn track_on(&self, device: u8, slot: Slot) -> Option<u32> {
        self.by_device.lock().ok()?.get(&(device, slot)).copied()
    }
}

/// What a peer says is in one of its slots.
///
/// The two halves arrive by different routes and neither substitutes for the
/// other. **Occupancy** is published in status packets and nowhere else (F20),
/// so [`Self::state`] is current the moment a peer unicasts to us and needs
/// nothing asked. **The name and the counts** only come from a media response,
/// which has to be asked for โ€” and a deck answers for an empty slot too, with
/// everything zeroed (F51), so a description is not evidence of a medium. That
/// is what [`Self::has_media`] is for.
#[derive(Clone, Debug)]
pub struct PeerSlot {
    /// Whose slot it is.
    pub device: DeviceNumber,
    /// Which slot.
    pub slot: Slot,
    /// What the owner publishes at `0x6f`/`0x73`, including the states an
    /// eject passes through.
    pub state: MediaState,
    /// The label and the counts, once a media query has been answered, and
    /// until the slot is empty: a pulled or swapped medium's name goes with it
    /// at the end of its eject (ยง3.2b), so the next one is asked about afresh.
    pub description: Option<MediaDescription>,
}

impl PeerSlot {
    /// Whether a medium is present and mounted.
    ///
    /// From the status byte, not from the description: an unlabelled stick with
    /// a full library reports no name, and an empty slot still gets a reply.
    pub fn has_media(&self) -> bool {
        self.state.has_media()
    }

    /// The volume label, or empty when unknown or unlabelled.
    pub fn volume_name(&self) -> &str {
        self.description
            .as_ref()
            .map_or("", |description| description.volume_name.as_str())
    }

    /// How many tracks the medium holds, once it has been described.
    pub fn track_count(&self) -> Option<u32> {
        Some(self.description.as_ref()?.track_count)
    }

    /// How many playlists the medium holds, once it has been described.
    pub fn playlist_count(&self) -> Option<u32> {
        Some(self.description.as_ref()?.playlist_count)
    }
}

/// What our peers have in their slots, kept current by the status socket.
///
/// Filled from two kinds of datagram as they arrive: every peer status packet
/// updates the slot states, and every media response fills in a description.
/// Reading it never transmits โ€” [`VirtualCdj::survey_media`] is what asks.
#[derive(Debug, Default)]
pub struct PeerMedia {
    /// `(device, slot)` โ†’ what that peer says about it.
    slots: Mutex<BTreeMap<(u8, Slot), PeerSlot>>,
}

impl PeerMedia {
    /// Every slot we have heard anything about, by device and then slot.
    pub fn all(&self) -> Vec<PeerSlot> {
        self.with(|slots| slots.values().cloned().collect())
    }

    /// Every slot of one device.
    pub fn of(&self, device: DeviceNumber) -> Vec<PeerSlot> {
        self.with(|slots| {
            slots
                .values()
                .filter(|entry| entry.device == device)
                .cloned()
                .collect()
        })
    }

    /// One slot of one device.
    pub fn get(&self, device: DeviceNumber, slot: Slot) -> Option<PeerSlot> {
        self.with(|slots| slots.get(&(device.get(), slot)).cloned())
    }

    /// Only the slots that currently hold a medium.
    pub fn occupied(&self) -> Vec<PeerSlot> {
        self.with(|slots| {
            slots
                .values()
                .filter(|entry| entry.has_media())
                .cloned()
                .collect()
        })
    }

    /// Record what a status packet says about a slot.
    ///
    /// An empty slot loses its description: the label and counts were the
    /// medium's, and the next medium in that slot has to be asked about. Kept
    /// through the eject's two unmounting states, which still name what is
    /// going.
    fn note_state(&self, device: DeviceNumber, slot: Slot, state: MediaState) {
        self.entry(device, slot, |entry| {
            if state == MediaState::EMPTY {
                entry.description = None;
            }
            entry.state = state;
        });
    }

    /// Record what a media response says about a slot.
    fn note_description(&self, device: DeviceNumber, slot: Slot, description: &MediaDescription) {
        self.entry(device, slot, |entry| {
            entry.description = Some(description.clone());
        });
    }

    fn entry(&self, device: DeviceNumber, slot: Slot, update: impl FnOnce(&mut PeerSlot)) {
        let Ok(mut slots) = self.slots.lock() else {
            return;
        };
        let entry = slots.entry((device.get(), slot)).or_insert(PeerSlot {
            device,
            slot,
            // Until a status packet says otherwise. A slot we have only ever
            // queried is not a slot we have been told holds anything.
            state: MediaState::EMPTY,
            description: None,
        });
        update(entry);
    }

    fn with<T>(&self, read: impl FnOnce(&BTreeMap<(u8, Slot), PeerSlot>) -> T) -> T {
        match self.slots.lock() {
            Ok(slots) => read(&slots),
            Err(poisoned) => read(&poisoned.into_inner()),
        }
    }
}

/// A device on the network: keep-alives, and optionally status.
#[derive(Debug)]
pub struct VirtualCdj {
    config: VirtualCdjConfig,
    interface: crate::Interface,
    /// The number currently held. Changes during the claim chain, so it is
    /// shared rather than copied.
    number: Arc<AtomicU8>,
    phase: watch::Sender<Phase>,
    media: Arc<dyn MediaSource>,
    /// What our peers have loaded from us, kept current by the status socket.
    loaded: Arc<LoadedTracks>,
    /// What our peers have in their own slots, kept current by the same socket.
    peers: Arc<PeerMedia>,
    /// UDP 50002, when we hold it. A media query has to leave from the port its
    /// answer will come back to, and only one socket in a `SO_REUSEPORT` group
    /// receives a given unicast datagram โ€” so this is `None` when
    /// [`VirtualCdjConfig::emit_status`] is off and something else, typically a
    /// [`crate::Monitor`], has the port.
    status_socket: Option<Arc<UdpSocket>>,
    /// Every datagram the status socket receives, for anything else that needs
    /// to read UDP 50002.
    ///
    /// A second socket is not an option. Only one member of a `SO_REUSEPORT`
    /// group receives a given *unicast* datagram, and status is only ever
    /// unicast (F21) โ€” so two readers would each get an arbitrary half of the
    /// stream and both would be wrong. `None` when we do not hold the port.
    status_tap: Option<broadcast::Sender<Arc<Vec<u8>>>>,
    status_counter: Arc<AtomicU32>,
    /// What this host is playing, for the status stream and the beat emitter.
    playback: Arc<PlaybackCell>,
    /// What this host has loaded, for the status stream.
    ///
    /// Separate from `playback` because it changes once per load rather than
    /// thirty times a second, and because it must **not** go stale: a tempo
    /// with no track beside it is a state no deck has ever published.
    playing_track: Arc<Mutex<Option<status::LoadedTrack>>>,
    /// Whether we claim tempo master.
    ///
    /// A plain flag rather than a state machine: taking mastership *from*
    /// another device needs the `0x26`/`0x27` handshake on the beat port, and
    /// the beat port is held by a [`crate::Monitor`] in every configuration
    /// this library supports โ€” one member of a `SO_REUSEPORT` group receives a
    /// given unicast datagram, so we could not hear the reply. So the policy
    /// this supports is the safe half: hold master while nobody else does, and
    /// step aside the moment somebody claims it.
    tempo_master: Arc<AtomicBool>,
    /// The device we are handing mastership to, as byte `0x9f` of our status,
    /// or zero for no handover. Held beside `tempo_master` because the two are
    /// published together and only mean anything together: naming a successor
    /// while not claiming mastership describes a deck that has never existed.
    yielding_to: Arc<AtomicU8>,
    /// Whether SYNC is engaged here, for flag bit 4.
    ///
    /// Published so the rest of the network can see that this deck is
    /// following rather than flying its own tempo -- which is what a CDJ shows
    /// on its SYNC button and what decides whether it is part of the tempo
    /// group at all.
    synced: Arc<AtomicBool>,
    /// Whether our keep-alive says we were first on the network, byte `0x25`.
    ///
    /// True only from a start into an empty network, and only until another
    /// device says it too, or answers our claim with a `0x05`: then false for
    /// good. See "Who was first" in the module docs.
    first_on_network: Arc<AtomicBool>,
    tasks: Vec<JoinHandle<()>>,
}

/// How many datagrams a slow tap subscriber may fall behind by.
///
/// Status arrives every 200 ms per peer, so four decks make 20 a second: a
/// subscriber this far behind has stopped reading altogether, and dropping is
/// better than growing without bound.
const TAP_CAPACITY: usize = 64;

impl VirtualCdj {
    /// Announce on the network `discovery` is listening to.
    ///
    /// Returns once a number is held โ€” after the claim chain in
    /// [`Numbering::Claim`], immediately in [`Numbering::Observer`].
    pub async fn start(
        discovery: &Discovery,
        config: VirtualCdjConfig,
        media: Arc<dyn MediaSource>,
    ) -> Result<Self> {
        let interface = discovery.interface().clone();
        // We bind 0.0.0.0 and so receive our own broadcasts. Without this we
        // would list ourselves as a peer, which corrupts the peer count we put
        // in our own keep-alive.
        discovery.ignore(interface.mac);

        let was_first = discovery.is_alone();
        info!(
            first_on_network = was_first,
            peers = discovery.devices().len(),
            "starting virtual CDJ"
        );

        let (phase, _) = watch::channel(Phase::Watching);
        let (number, answered) = match config.numbering {
            Numbering::Observer(number) => (number, false),
            Numbering::Claim { preferred } => {
                match claim(discovery, &config, &interface, preferred, was_first, &phase).await {
                    Ok(claimed) => claimed,
                    Err(error) => {
                        let _ = phase.send(Phase::Failed);
                        return Err(error);
                    }
                }
            }
        };
        let _ = phase.send(Phase::Announcing);
        if answered {
            info!("a player holding the first-on-network role answered our claim; not taking it");
        }

        // Bound here rather than inside the responder, because asking a peer
        // what is in its slots uses the same socket as answering that question
        // for ourselves, and the answer comes back to this port.
        let status_socket = if config.emit_status {
            Some(Arc::new(socket::bind(STATUS_PORT, Some(&interface))?))
        } else {
            None
        };
        let status_tap = status_socket
            .as_ref()
            .map(|_| broadcast::Sender::new(TAP_CAPACITY));

        let mut cdj = Self {
            config,
            interface,
            number: Arc::new(AtomicU8::new(number.get())),
            phase,
            media,
            loaded: Arc::new(LoadedTracks::default()),
            peers: Arc::new(PeerMedia::default()),
            status_socket,
            status_tap,
            status_counter: Arc::new(AtomicU32::new(0)),
            playback: Arc::new(PlaybackCell::default()),
            playing_track: Arc::new(Mutex::new(None)),
            tempo_master: Arc::new(AtomicBool::new(false)),
            yielding_to: Arc::new(AtomicU8::new(0)),
            synced: Arc::new(AtomicBool::new(false)),
            first_on_network: Arc::new(AtomicBool::new(was_first && !answered)),
            tasks: Vec::new(),
        };
        cdj.tasks.push(cdj.spawn_keep_alive(discovery));
        cdj.tasks.push(cdj.spawn_defender(discovery));
        cdj.tasks.push(cdj.spawn_step_aside(discovery));
        if let Some(socket) = cdj.status_socket.clone() {
            cdj.tasks.push(cdj.spawn_status(discovery)?);
            cdj.tasks.push(cdj.spawn_query_responder(socket));
            // Beats ride with status, not with the keep-alive: a device that
            // does not publish what it is doing has no business claiming a
            // beat, and the two are read together by everything downstream.
            cdj.tasks.push(cdj.spawn_beats()?);
        }
        Ok(cdj)
    }

    /// Announce without serving anything: enough to make peers talk to us.
    pub async fn observe(discovery: &Discovery, config: VirtualCdjConfig) -> Result<Self> {
        Self::start(discovery, config, Arc::new(NoMedia)).await
    }

    /// The number currently held.
    pub fn number(&self) -> DeviceNumber {
        DeviceNumber::new(self.number.load(Ordering::Relaxed)).unwrap_or(OBSERVER_NUMBER)
    }

    /// Every datagram arriving on UDP 50002, when we are the one holding it.
    ///
    /// `None` means we do not have the port and a reader should bind its own.
    /// See the `status_tap` field for why there is no third option.
    pub fn status_datagrams(&self) -> Option<broadcast::Receiver<Arc<Vec<u8>>>> {
        self.status_tap.as_ref().map(broadcast::Sender::subscribe)
    }

    /// The number currently held, if a peer would browse it.
    ///
    /// `None` means serving is pointless: a peer will accept everything and
    /// then never ask (F45). The serve side requires this rather than a plain
    /// device number, so a server that can never be browsed cannot be started.
    pub fn browsable_number(&self) -> Option<BrowsableDeviceNumber> {
        self.number().browsable()
    }

    /// What our peers have loaded from us. Shared, and kept current for as
    /// long as this virtual CDJ runs.
    pub fn loaded(&self) -> Arc<LoadedTracks> {
        Arc::clone(&self.loaded)
    }

    /// What our peers have in their own slots.
    ///
    /// Reading this never transmits. The slot states are current from the
    /// moment peers start unicasting status to us, which announcing is what
    /// earns (F21); the names and counts appear once [`Self::survey_media`] or
    /// [`Self::query_media`] has asked for them.
    pub fn peer_media(&self) -> Arc<PeerMedia> {
        Arc::clone(&self.peers)
    }

    /// Watch the claim state machine.
    pub fn phase(&self) -> watch::Receiver<Phase> {
        self.phase.subscribe()
    }

    /// State what this host is playing.
    ///
    /// Call this several times a second while a track is loaded. The playhead
    /// is projected between calls, so the rate governs how quickly a tempo
    /// *change* reaches the network, not how accurately beats are timed โ€” see
    /// [`crate::playback`].
    ///
    /// It takes about [`crate::playback::STALE_AFTER`] of silence for the
    /// network to conclude that nothing is playing here, which is deliberate:
    /// the alternative is a stale tempo other decks stay locked to.
    pub fn set_playback(&self, playback: Playback) {
        self.playback.set(playback);
    }

    /// Nothing is playing here.
    ///
    /// Deliberately does **not** clear the loaded track. The two are set by
    /// different things at different moments: the browser says what it loaded
    /// the instant it loads it, and the tempo poll says what is playing thirty
    /// times a second -- so a poll that happened to land in the gap before the
    /// engine had the track was wiping the announcement that had just been
    /// made, and the track never reached the wire at all.
    pub fn clear_playback(&self) {
        self.playback.clear();
    }

    /// State what is loaded, and whose medium it came from.
    ///
    /// **Required alongside a tempo, not optional beside it.** A deck that
    /// publishes a tempo always publishes this too, and a CDJ asked to follow a
    /// master with no track simply does not.
    pub fn set_loaded_track(&self, track: Option<status::LoadedTrack>) {
        match self.playing_track.lock() {
            Ok(mut held) => *held = track,
            Err(poisoned) => *poisoned.into_inner() = track,
        }
    }

    /// What we are announcing as loaded.
    #[must_use]
    pub fn loaded_track(&self) -> Option<status::LoadedTrack> {
        match self.playing_track.lock() {
            Ok(held) => *held,
            Err(poisoned) => *poisoned.into_inner(),
        }
    }

    /// What we are announcing as playing, playhead projected to now.
    pub fn playback(&self) -> Playback {
        self.playback.now()
    }

    /// Claim or release tempo master.
    ///
    /// **Only ever call this with `true` when nothing else holds it.** There is
    /// no handshake here (see the `tempo_master` field), so claiming it while
    /// another deck also claims it puts two masters on the network and every
    /// follower flickers between them. [`crate::Monitor::players`] is where to
    /// find out.
    pub fn set_tempo_master(&self, master: bool) {
        // Any handover in flight ends here, whichever way this goes: naming a
        // successor is only meaningful while the claim it is handing over still
        // stands, and this sets that claim outright.
        self.yielding_to.store(0, Ordering::Relaxed);
        self.tempo_master.store(master, Ordering::Relaxed);
    }

    /// Whether SYNC is engaged here.
    pub fn set_synced(&self, synced: bool) {
        self.synced.store(synced, Ordering::Relaxed);
    }

    /// Whether we are claiming tempo master.
    pub fn is_tempo_master(&self) -> bool {
        self.tempo_master.load(Ordering::Relaxed)
    }

    /// Whether our keep-alive says we were first on the network, byte `0x25`.
    ///
    /// Becomes false for good once another device says it, or answers our
    /// claim with a `0x05`; see "Who was first" in the module docs.
    pub fn first_on_network(&self) -> bool {
        self.first_on_network.load(Ordering::Relaxed)
    }

    /// Answer a `0x26` and stand down.
    ///
    /// **A CDJ's MASTER button always wins.** Pressing it on another deck takes
    /// mastership from whoever has it; there is no refusing, and a device that
    /// ignored the request would go on claiming a mastership the rest of the
    /// network had already moved off โ€” two masters, and every follower
    /// flickering between them.
    ///
    /// Synchronous, and deliberately so: this is one datagram sent in answer to
    /// one datagram, the reply arrives within 5 ms on real hardware, and making
    /// it `async` would mean holding the session lock across an await at every
    /// call site.
    pub fn yield_tempo_master(&self, requester: DeviceNumber, address: Ipv4Addr) -> Result<()> {
        if !self.is_tempo_master() {
            // Not ours to give. The request was broadcast at us by mistake, or
            // we stood down a moment ago; either way answering would claim a
            // handover that is not happening.
            return Ok(());
        }
        let response = prolink_proto::beat::MasterResponse {
            name: self.config.name,
            device: self.number(),
            granted: true,
        };
        let to = SocketAddr::V4(SocketAddrV4::new(address, BEAT_PORT));
        socket::send_once(&self.interface, to, &response.encode())?;
        // **The claim is kept, and the successor is named.** This is the half
        // that was missing, and without it the handover never completed: a real
        // deck watches byte `0x9f` for its own number, because the grant is
        // that byte and not the absence of byte `0x9e`. We answered the `0x26`
        // and then simply stopped claiming mastership, which from the
        // requester's side is indistinguishable from a refusal -- it asked, we
        // went quiet, and nobody ended up master at all.
        //
        // `finish_yield` drops both, once the requester has picked it up.
        self.yielding_to.store(requester.get(), Ordering::Relaxed);
        info!(%requester, "granted tempo master; naming it as successor");
        Ok(())
    }

    /// The device we are handing mastership to, if a handover is in flight.
    pub fn yielding_to(&self) -> Option<DeviceNumber> {
        DeviceNumber::new(self.yielding_to.load(Ordering::Relaxed))
    }

    /// Name *successor* at byte `0x9f` while keeping our claim: hand
    /// mastership over without having been asked.
    ///
    /// What a CDJ master does when it stops while another deck plays on: the
    /// successor picks it up, and [`Self::finish_yield`] then lets go.
    ///
    /// False, and nothing changed, when we do not hold mastership, **or while
    /// a hand-over is already in flight.** A master names one successor at a
    /// time: a player claims master 12-69 ms after it is named (S28), so a
    /// second name written over the first can leave two of them claiming it.
    /// The offer in flight ends when it is taken up ([`Self::finish_yield`])
    /// or withdrawn ([`Self::withdraw_offer`]); a hand-over asked for with a
    /// `0x26` ([`Self::yield_tempo_master`]) still overrides it, as a CDJ's
    /// MASTER button always wins.
    pub fn offer_tempo_master(&self, successor: DeviceNumber) -> bool {
        if !self.is_tempo_master() {
            return false;
        }
        if self
            .yielding_to
            .compare_exchange(0, successor.get(), Ordering::AcqRel, Ordering::Relaxed)
            .is_err()
        {
            return false;
        }
        info!(%successor, "offering tempo master");
        true
    }

    /// Withdraw an offer nobody took up, keeping our claim.
    pub fn withdraw_offer(&self) {
        self.yielding_to.store(0, Ordering::Relaxed);
    }

    /// Complete a handover: stop claiming mastership and stop naming a
    /// successor.
    ///
    /// Called once the requester is claiming it, which is what the yield was
    /// waiting for โ€” or once waiting has gone on long enough that holding a
    /// mastership the network is not acting on is the worse of the two states.
    pub fn finish_yield(&self) {
        self.yielding_to.store(0, Ordering::Relaxed);
        self.set_tempo_master(false);
    }

    /// Ask the deck at *holder* to hand mastership over.
    ///
    /// One `0x26` on the beat port, unicast, exactly as a deck sends when its
    /// MASTER button is pressed. The holder answers with a `0x27` within about
    /// 5 ms and its status byte `0x9e` drops within ~70 ms (S28).
    ///
    /// **This does not set our own flag.** The `0x27` comes back unicast to
    /// port 50001, which a [`crate::Monitor`] is holding. The grant is watched
    /// for where every other device sees it: the holder's *status* naming us
    /// at byte `0x9f`, which it sends at once with its `0x27` (S28: within
    /// 1 ms), and on which a real requester claims (16-73 ms after asking).
    ///
    /// Synchronous, like the `0x27` [`Self::yield_tempo_master`] answers with:
    /// one datagram, sent from whatever thread asks, so no caller has to hold
    /// a lock across an await -- or, worse, block a UI thread on a runtime
    /// whose I/O driver a lock-waiting worker might be the only one to turn.
    pub fn request_tempo_master(&self, holder: Ipv4Addr) -> Result<()> {
        let request = prolink_proto::beat::MasterRequest {
            name: self.config.name,
            device: self.number(),
        };
        let to = SocketAddr::V4(SocketAddrV4::new(holder, BEAT_PORT));
        socket::send_once(&self.interface, to, &request.encode())?;
        info!(%holder, "asked the tempo master to hand over");
        Ok(())
    }

    /// Ask every online peer what is in both of its slots, and return the table.
    ///
    /// One `0x05` per peer per slot, then a single wait โ€” rather than a wait per
    /// slot โ€” because the answers land in [`Self::peer_media`] as they arrive
    /// and nothing here needs to match them up. A peer that does not answer in
    /// time keeps whatever the table already knew, so a slow deck costs its own
    /// row and not the survey.
    ///
    /// A deck answers for an empty slot too, with everything zeroed (F51), so
    /// use [`PeerSlot::has_media`] โ€” which reads the status byte โ€” rather than
    /// the presence of a description.
    pub async fn survey_media(
        &self,
        discovery: &Discovery,
        wait: Duration,
    ) -> Result<Vec<PeerSlot>> {
        let ours = self.number();
        let mut asked = 0usize;
        for device in discovery.online() {
            if device.number == ours {
                continue;
            }
            for slot in [Slot::USB, Slot::SD] {
                self.send_media_query(device.ip, device.number, slot)
                    .await?;
                asked += 1;
            }
        }
        debug!(queries = asked, "asked our peers what is in their slots");
        if asked > 0 {
            tokio::time::sleep(wait).await;
        }
        Ok(self.peers.all())
    }

    /// Ask one peer about one slot, and wait for that answer.
    ///
    /// For the whole network prefer [`Self::survey_media`], which asks
    /// everything at once instead of paying the timeout per slot.
    pub async fn query_media(
        &self,
        peer: Ipv4Addr,
        target: DeviceNumber,
        slot: Slot,
        wait: Duration,
    ) -> Result<MediaDescription> {
        self.send_media_query(peer, target, slot).await?;

        // Polled rather than notified: the answer arrives on another task, this
        // is a once-per-slot question, and a poll loop needs no channel that
        // could drop an answer while nobody is listening.
        let deadline = tokio::time::Instant::now() + wait;
        while tokio::time::Instant::now() < deadline {
            if let Some(entry) = self.peers.get(target, slot)
                && let Some(description) = entry.description
            {
                return Ok(description);
            }
            tokio::time::sleep(MEDIA_POLL).await;
        }
        Err(Error::Timeout {
            what: "a media query",
            after: wait,
        })
    }

    /// Ask one peer about one slot, and return without waiting for the answer.
    ///
    /// The answer lands in [`Self::peer_media`] when it comes. For a host that
    /// asks the way a deck does: when a peer's status shows a slot loaded, and
    /// again while it is unanswered.
    pub async fn ask_media(&self, peer: Ipv4Addr, target: DeviceNumber, slot: Slot) -> Result<()> {
        self.send_media_query(peer, target, slot).await
    }

    /// Send one `0x05`, addressed the way a deck addresses it.
    async fn send_media_query(
        &self,
        peer: Ipv4Addr,
        target: DeviceNumber,
        slot: Slot,
    ) -> Result<()> {
        let Some(socket) = self.status_socket.as_ref() else {
            return Err(Error::NoStatusPort { port: STATUS_PORT });
        };
        // We name ourselves by number *and* by address, because the answer is
        // sent to the address in the query rather than to the sender of it.
        let query = status::MediaQuery {
            requester: self.number(),
            requester_ip: self.interface.ip,
            target,
            slot,
        };
        let to = SocketAddr::V4(SocketAddrV4::new(peer, STATUS_PORT));
        socket
            .send_to(&query.encode(self.config.name), to)
            .await
            .map_err(Error::io("asking a peer about a slot"))?;
        Ok(())
    }

    /// The status packet we are emitting, for byte-diffing against a real deck.
    ///
    /// Built through the same function the emitter uses, so what this shows is
    /// what goes out rather than something assembled alongside it.
    pub fn status_packet(&self, peers: usize) -> CdjStatus {
        status_packet(
            &self.config,
            &self.number,
            self.media.as_ref(),
            &self.status_counter,
            peers,
            Transport {
                playback: &self.playback.now(),
                loaded: self.loaded_track(),
                tempo_master: self.is_tempo_master(),
                yielding_to: self.yielding_to(),
                synced: self.synced.load(Ordering::Relaxed),
            },
        )
    }

    /// The keep-alive we are broadcasting, for byte-diffing against a real deck.
    pub fn keep_alive(&self, peers: usize, was_first: bool) -> djl::Packet {
        djl::Packet::new(
            self.config.name,
            self.config.kind,
            Body::KeepAlive {
                device_number: self.number().get(),
                was_first_on_network: if was_first {
                    FIRST_ON_NETWORK
                } else {
                    JOINED_PEERS
                },
                mac: self.interface.mac,
                ip: self.interface.ip,
                // Includes ourselves.
                peer_count: u8::try_from(peers.saturating_add(1)).unwrap_or(u8::MAX),
                pad_31: [0; 3],
                flags: self.config.kind.role(),
                trailing: self.config.generation,
            },
        )
    }

    fn spawn_keep_alive(&self, discovery: &Discovery) -> JoinHandle<()> {
        let socket = discovery.socket();
        let broadcast = SocketAddr::V4(SocketAddrV4::new(
            self.interface.broadcast(),
            DISCOVERY_PORT,
        ));
        let first_on_network = Arc::clone(&self.first_on_network);
        let config = self.config.clone();
        let interface = self.interface.clone();
        let number = Arc::clone(&self.number);
        let peers = PeerAddresses::new(discovery);

        tokio::spawn(async move {
            let mut ticker = tokio::time::interval(djl::KEEPALIVE_INTERVAL);
            loop {
                ticker.tick().await;
                let packet = keep_alive_packet(
                    &config,
                    &interface,
                    &number,
                    peers.len(),
                    first_on_network.load(Ordering::Relaxed),
                );
                if let Err(error) = socket.send_to(&packet.encode(), broadcast).await {
                    warn!(%error, "keep-alive failed");
                }
            }
        })
    }

    /// Give up keep-alive byte `0x25` the moment another device says it.
    ///
    /// A real deck saying `0x02` re-claims its number every few seconds for as
    /// long as it hears another device say it too (S10-S24, S24b, S18), so
    /// saying it beside one is what kept a CDJ re-claiming for ever. See "Who
    /// was first" in the module docs. Nothing is sent: our next keep-alive
    /// simply says `0x01`, and goes on saying it.
    fn spawn_step_aside(&self, discovery: &Discovery) -> JoinHandle<()> {
        let mut announcements = discovery.announcements();
        let first_on_network = Arc::clone(&self.first_on_network);
        let ours = self.interface.mac;

        tokio::spawn(async move {
            loop {
                let announcement = match announcements.recv().await {
                    Ok(announcement) => announcement,
                    // Behind by a few: the next keep-alive saying 0x02 comes
                    // within two seconds, and is as good as the one missed.
                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(broadcast::error::RecvError::Closed) => return,
                };
                if !first_on_network.load(Ordering::Relaxed) {
                    // Given up for good: nothing left to watch for.
                    return;
                }
                if steps_aside(&announcement, ours) {
                    first_on_network.store(false, Ordering::Relaxed);
                    info!(
                        holder = %announcement.from,
                        "another device says it was first on the network; stepping aside"
                    );
                    return;
                }
            }
        })
    }

    /// Emit status, unicast, one copy per announced peer.
    ///
    /// Status is unicast on real hardware โ€” not one of 1507 captured packets was
    /// broadcast (F21) โ€” so this sends per peer rather than once. Peers that
    /// have not announced themselves get nothing, which mirrors why we received
    /// nothing until we announced.
    fn spawn_status(&self, discovery: &Discovery) -> Result<JoinHandle<()>> {
        // A real deck sends each status packet from a different, incrementing
        // source port. We do not imitate that; an ephemeral port is enough, and
        // the socket bound to 50002 is kept free to receive queries.
        let socket = socket::bind_at(self.interface.ip, 0, Some(&self.interface))?;
        let config = self.config.clone();
        let number = Arc::clone(&self.number);
        let media = Arc::clone(&self.media);
        let counter = Arc::clone(&self.status_counter);
        let table = PeerAddresses::new(discovery);
        let playback = Arc::clone(&self.playback);
        let playing_track = Arc::clone(&self.playing_track);
        let master = Arc::clone(&self.tempo_master);
        let yielding = Arc::clone(&self.yielding_to);
        let synced = Arc::clone(&self.synced);

        Ok(tokio::spawn(async move {
            // Every 200 ms, and at once when what we publish changes: see
            // `status_due`. The check is cheap; the packets are what a real
            // deck sends.
            let mut check = tokio::time::interval(STATUS_CHECK);
            check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
            let mut last: Option<(Instant, Published)> = None;
            loop {
                check.tick().await;
                let playing_now = playback.now();
                let transport = Transport {
                    playback: &playing_now,
                    loaded: playing_track.lock().ok().and_then(|held| *held),
                    tempo_master: master.load(Ordering::Relaxed),
                    yielding_to: DeviceNumber::new(yielding.load(Ordering::Relaxed)),
                    synced: synced.load(Ordering::Relaxed),
                };
                let published = Published::of(&transport, media.as_ref());
                let now = Instant::now();
                if !status_due(last, now, published) {
                    continue;
                }
                let peers = table.get();
                let packet = status_packet(
                    &config,
                    &number,
                    media.as_ref(),
                    &counter,
                    peers.len(),
                    transport,
                );
                counter.fetch_add(1, Ordering::Relaxed);
                for peer in peers {
                    let to = SocketAddr::V4(SocketAddrV4::new(peer, STATUS_PORT));
                    if let Err(error) = socket.send_to(packet.as_bytes(), to).await {
                        debug!(%error, %peer, "status unicast failed");
                    }
                }
                last = Some((now, published));
            }
        }))
    }

    /// Broadcast a beat packet on UDP 50001 as each beat arrives.
    ///
    /// **This is what makes us a tempo other devices can follow.** A status
    /// packet says what our tempo *is*, five times a second; a beat packet says
    /// where the beat *is*, and a follower phase-locks to the arrival time of
    /// this datagram, not to anything inside it. So the one property that
    /// matters is that it leaves on the beat.
    ///
    /// Hence the polling rather than a sleep-until-next-beat: a tempo change or
    /// a seek arrives between beats, and a task parked on a deadline computed
    /// before it would send the next beat in the wrong place. [`BEAT_TICK`] is
    /// the resulting worst-case lateness, and it is well under a millisecond of
    /// a DJ's perception at any tempo.
    ///
    /// Beats are **broadcast**, unlike status: they arrive on 50001 from decks
    /// that have never been told we exist, which is the whole reason a passive
    /// listener can see a tempo without announcing.
    fn spawn_beats(&self) -> Result<JoinHandle<()>> {
        let socket = socket::bind_at(self.interface.ip, 0, Some(&self.interface))?;
        let broadcast = SocketAddr::V4(SocketAddrV4::new(self.interface.broadcast(), BEAT_PORT));
        let name = self.config.name;
        let number = Arc::clone(&self.number);
        let playback = Arc::clone(&self.playback);

        Ok(tokio::spawn(async move {
            let mut ticker = tokio::time::interval(BEAT_TICK);
            let mut emitted: Option<u32> = None;
            loop {
                ticker.tick().await;
                let now = playback.now();
                let Some(position) = beat_to_emit(&now, &mut emitted) else {
                    continue;
                };
                let Some(device) = DeviceNumber::new(number.load(Ordering::Relaxed)) else {
                    continue;
                };
                let Some(packet) = now.beat_packet(device, name, position) else {
                    continue;
                };
                if let Err(error) = socket.send_to(&packet.encode(), broadcast).await {
                    debug!(%error, "beat broadcast failed");
                }
            }
        }))
    }

    /// Answer media and settings queries on UDP 50002.
    ///
    /// **The step no reference implementation performs, because none of them
    /// serve.** Until these are answered, a deck that has otherwise fully
    /// accepted us โ€” it is unicasting status to us and has completed a portmap
    /// and mount against our NFS server โ€” still refuses to list us as a LINK
    /// source, because as far as it knows our slots hold nothing (F24).
    fn spawn_query_responder(&self, socket: Arc<UdpSocket>) -> JoinHandle<()> {
        let name = self.config.name;
        let number = Arc::clone(&self.number);
        let media = Arc::clone(&self.media);
        let loaded = Arc::clone(&self.loaded);
        let peers = Arc::clone(&self.peers);
        let tap = self.status_tap.clone();

        tokio::spawn(async move {
            let mut buffer = vec![0u8; MAX_DATAGRAM];
            loop {
                let (len, from) = match socket.recv_from(&mut buffer).await {
                    Ok(received) => received,
                    Err(error) => {
                        warn!(%error, "status socket closed");
                        return;
                    }
                };
                let SocketAddr::V4(from) = from else { continue };
                let Some(datagram) = buffer.get(..len) else {
                    continue;
                };
                let Some(ours) = DeviceNumber::new(number.load(Ordering::Relaxed)) else {
                    continue;
                };
                // Before the decode, and unconditionally: a tap subscriber is
                // interested in packets this responder ignores, and copying is
                // only paid for when somebody is listening.
                if let Some(tap) = tap.as_ref()
                    && tap.receiver_count() > 0
                {
                    let _ = tap.send(Arc::new(datagram.to_vec()));
                }

                let reply = match status::decode(datagram) {
                    // Not a query, but the packet that tells us what this deck
                    // has loaded from us โ€” which is what lets a track row be
                    // marked as the loaded one (F55). Only a track whose
                    // source player is *us* came off our medium.
                    Ok(status::Packet::CdjStatus(peer)) => {
                        observe_loaded(&loaded, ours, &peer);
                        observe_peer_slots(&peers, &peer);
                        None
                    }
                    // The answer to a question we asked. It is not addressed to
                    // us by number โ€” a deck sends it to whoever asked โ€” so the
                    // table is filled here and `survey_media` only has to wait.
                    Ok(status::Packet::MediaResponse(response)) => {
                        observe_peer_media(&peers, &response);
                        None
                    }
                    Ok(status::Packet::MediaQuery(query)) => {
                        answer_media_query(query, ours, name, media.as_ref())
                            .map(|reply| (reply, query.requester_ip))
                    }
                    Ok(status::Packet::SettingsQuery(query)) => {
                        let settings = media.settings(query.slot);
                        let response = status::SettingsResponse::build(
                            name,
                            ours,
                            query.requester,
                            query.slot,
                            &settings,
                        );
                        info!(slot = %query.slot, bytes = settings.len(), "answered a settings query");
                        Some((response.into_bytes(), *from.ip()))
                    }
                    _ => None,
                };

                if let Some((datagram, to)) = reply {
                    let to = SocketAddr::V4(SocketAddrV4::new(to, STATUS_PORT));
                    if let Err(error) = socket.send_to(&datagram, to).await {
                        warn!(%error, "could not answer a query");
                    }
                }
            }
        })
    }

    /// Defend our number, and watch for anyone defending it against us.
    ///
    /// A device that takes a number but never defends it simply loses it to the
    /// next player that boots.
    fn spawn_defender(&self, discovery: &Discovery) -> JoinHandle<()> {
        let mut announcements = discovery.announcements();
        let socket = discovery.socket();
        let config = self.config.clone();
        let interface = self.interface.clone();
        let number = Arc::clone(&self.number);

        tokio::spawn(async move {
            loop {
                let Ok(announcement) = announcements.recv().await else {
                    return;
                };
                let ours = number.load(Ordering::Relaxed);
                let (Body::ClaimIp {
                    device_number: proposed,
                    ..
                }
                | Body::ClaimNumber {
                    device_number: proposed,
                    ..
                }) = announcement.packet.body
                else {
                    continue;
                };
                if proposed != ours || announcement.packet.body.mac() == Some(interface.mac) {
                    continue;
                }

                info!(number = ours, challenger = %announcement.from, "defending our device number");
                let packet = djl::Packet::new(
                    config.name,
                    config.kind,
                    Body::NumberConflict {
                        device_number: ours,
                        ip: interface.ip,
                    },
                );
                let to = SocketAddr::V4(SocketAddrV4::new(announcement.from, DISCOVERY_PORT));
                if let Err(error) = socket.send_to(&packet.encode(), to).await {
                    warn!(%error, "could not defend our number");
                }
            }
        })
    }
}

impl Drop for VirtualCdj {
    fn drop(&mut self) {
        for task in &self.tasks {
            task.abort();
        }
    }
}

/// Build the answer to a media query, or nothing if the slot is not ours.
///
/// Saying nothing about a slot we do not serve is right: an empty reply would
/// tell the deck the slot exists and holds no tracks, and it would then offer an
/// empty medium.
fn answer_media_query(
    query: status::MediaQuery,
    ours: DeviceNumber,
    name: DeviceName,
    media: &dyn MediaSource,
) -> Option<Vec<u8>> {
    if query.target != ours {
        return None;
    }
    let description = media.describe(query.slot)?;
    info!(
        requester = %query.requester,
        slot = %query.slot,
        tracks = description.track_count,
        playlists = description.playlist_count,
        "answered a media query",
    );
    let mut builder = status::MediaResponse::builder()
        .device_number(ours)
        .slot(query.slot)
        .name(name)
        .volume_name(&description.volume_name)
        .counts(description.track_count, description.playlist_count)
        .plain(description.plain);
    if let (Some(total), Some(free)) = (description.total_bytes, description.free_bytes) {
        builder = builder.size(total, free);
    }
    Some(builder.build().into_bytes())
}

fn keep_alive_packet(
    config: &VirtualCdjConfig,
    interface: &crate::Interface,
    number: &AtomicU8,
    peers: usize,
    was_first: bool,
) -> djl::Packet {
    djl::Packet::new(
        config.name,
        config.kind,
        Body::KeepAlive {
            device_number: number.load(Ordering::Relaxed),
            was_first_on_network: if was_first {
                FIRST_ON_NETWORK
            } else {
                JOINED_PEERS
            },
            mac: interface.mac,
            ip: interface.ip,
            peer_count: u8::try_from(peers.saturating_add(1)).unwrap_or(u8::MAX),
            pad_31: [0; 3],
            flags: config.kind.role(),
            trailing: config.generation,
        },
    )
}

/// Record what a peer's status packet says it has loaded **from us**.
///
/// Only a track whose source player is our own number came off our medium; a
/// track a deck loaded from another player is not ours to mark, and marking by
/// id alone would mark whichever of our tracks happened to share that id.
fn observe_loaded(loaded: &LoadedTracks, ours: DeviceNumber, peer: &CdjStatus) {
    let Some(device) = peer.sender() else {
        return;
    };
    if peer.source_player() != Some(ours) {
        return;
    }
    loaded.note(device.get(), peer.source_slot(), peer.track_id());
}

/// Record what a peer's status packet says about its own two slots.
///
/// Free of charge and unasked-for: occupancy is published here and nowhere else
/// (F20), so every status packet that arrives is a fresh answer to "does that
/// deck have media in it".
fn observe_peer_slots(peers: &PeerMedia, peer: &CdjStatus) {
    let Some(device) = peer.sender() else {
        return;
    };
    for slot in [Slot::USB, Slot::SD] {
        if let Some(state) = peer.slot_state(slot) {
            peers.note_state(device, slot, state);
        }
    }
}

/// Record what a media response says about the slot it describes.
fn observe_peer_media(peers: &PeerMedia, response: &status::MediaResponse) {
    let Some(device) = response.device() else {
        return;
    };
    let slot = response.slot();
    let description = MediaDescription {
        volume_name: response.volume_name(),
        created: response.created(),
        track_count: response.track_count(),
        playlist_count: response.playlist_count(),
        total_bytes: response.total_bytes(),
        free_bytes: response.free_bytes(),
        plain: response.is_plain(),
    };
    debug!(
        %device,
        %slot,
        tracks = description.track_count,
        playlists = description.playlist_count,
        volume = description.volume_name,
        "a peer described one of its slots",
    );
    peers.note_description(device, slot, &description);
}

/// Which beat, if any, is due to be broadcast right now.
///
/// A follower phase-locks to the *arrival* of each beat packet, so a packet
/// may only leave on a beat. `emitted` is the last beat number this playhead
/// was seen in, and:
///
///  * **The playhead entering a beat it was not in** sends that beat, as its
///    downbeat -- if it is still at the start of it. Crossing into the next
///    beat in play is the ordinary case; a jump landing on a downbeat is the
///    same thing.
///  * **Anywhere else is a silent re-sync**: a crossing the task noticed late
///    (a stall), a hot cue or beat jump forwards, a seek or a loop wrapping
///    backwards, the first beat seen after play. The count moves to where the
///    playhead is, and the next crossing sends. Sending the landing beat at
///    once put it on the wire mid-beat; catching up beat by beat put
///    sixty-four packets on it in a third of a second for a hot cue sixteen
///    bars on. Followers acted on both.
///  * **Stopping**, or the platter being scratched, clears the count.
fn beat_to_emit(playback: &Playback, emitted: &mut Option<u32>) -> Option<BeatPosition> {
    // A scratched platter's playhead is the hand's, not the music's: its
    // position comes in thirty times a second and jumps both ways, and every
    // beat crossing it made used to go out as a beat at the nominal tempo.
    if playback.scratching {
        *emitted = None;
        return None;
    }
    let (Some(position), true) = (playback.beat, playback.playing) else {
        *emitted = None;
        return None;
    };
    let previous = emitted.replace(position.number);
    if previous == Some(position.number) {
        return None;
    }
    // How far past the downbeat the playhead is: within a couple of ticks of
    // it is "on the beat", and anything more is too late to be one.
    let late = playback
        .beat_interval()
        .map(|interval| interval.mul_f64(position.fraction.clamp(0.0, 1.0)));
    // A crossing and a jump are told apart by nothing else: either way the
    // playhead is in a beat it was not in, and it is sent only if it is at
    // that beat's start.
    late.is_some_and(|late| late <= 2 * BEAT_TICK)
        .then_some(BeatPosition {
            number: position.number,
            fraction: 0.0,
        })
}

/// Everything the status packet says about what this deck is *doing*, as
/// against what media it has.
///
/// One struct because they travel together and are read together: a follower
/// checks several of them against each other, and a packet where the tempo,
/// the loaded track and the play state disagree describes a deck that has
/// never existed. Passing them as loose arguments made that easy to get wrong
/// and easy to leave out.
#[derive(Clone, Copy, Debug)]
struct Transport<'a> {
    playback: &'a Playback,
    loaded: Option<status::LoadedTrack>,
    tempo_master: bool,
    /// Byte `0x9f`: who we are handing mastership to, mid-handover.
    yielding_to: Option<DeviceNumber>,
    synced: bool,
}

/// What a peer acts on the moment it changes: who is master and whom it is
/// going to, sync, whether we play, what is loaded, what is in our slots.
///
/// Not the tempo, the pitch or the beat, which move all the time and which a
/// follower takes from beat packets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Published {
    tempo_master: bool,
    yielding_to: Option<DeviceNumber>,
    synced: bool,
    playing: bool,
    play_state: u8,
    loaded: Option<status::LoadedTrack>,
    usb: MediaState,
    sd: MediaState,
}

impl Published {
    fn of(transport: &Transport<'_>, media: &dyn MediaSource) -> Self {
        Self {
            tempo_master: transport.tempo_master,
            yielding_to: transport.yielding_to,
            synced: transport.synced,
            playing: transport.playback.playing,
            play_state: play_state_for(transport.playback).0,
            loaded: transport.loaded,
            usb: media.slot_state(Slot::USB),
            sd: media.slot_state(Slot::SD),
        }
    }
}

/// Whether a status packet is due: every [`status::STATUS_INTERVAL`], and at
/// once when what we publish changed, but never sooner than [`STATUS_FLOOR`]
/// after the last one. `last` is when the last one went and what it said.
fn status_due(last: Option<(Instant, Published)>, now: Instant, published: Published) -> bool {
    let Some((sent, said)) = last else {
        return true;
    };
    let since = now.saturating_duration_since(sent);
    since >= status::STATUS_INTERVAL || (published != said && since >= STATUS_FLOOR)
}

fn status_packet(
    config: &VirtualCdjConfig,
    number: &AtomicU8,
    media: &dyn MediaSource,
    counter: &AtomicU32,
    peers: usize,
    transport: Transport<'_>,
) -> CdjStatus {
    let Transport {
        playback,
        loaded,
        tempo_master,
        yielding_to,
        synced,
    } = transport;
    let occupied = media.occupied_slots();
    let state = |slot: Slot| media.slot_state(slot);
    let mut builder = CdjStatus::builder()
        .name(config.name)
        .slot_state(Slot::USB, state(Slot::USB))
        .slot_state(Slot::SD, state(Slot::SD))
        .link_available(!occupied.is_empty() || peers > 0)
        .firmware(&config.firmware)
        .packet_counter(counter.load(Ordering::Relaxed))
        .tempo(playback.bpm_centi, playback.pitch)
        .loaded_track(loaded)
        .playing(playback.playing)
        .tempo_master(tempo_master)
        .yielding_to(yielding_to)
        .synced(synced)
        .beat(
            playback.beat.map(|beat| beat.number),
            playback.beat.map(BeatPosition::in_bar),
        )
        .play_state(play_state_for(playback).0);
    if let Some(number) = DeviceNumber::new(number.load(Ordering::Relaxed)) {
        builder = builder.device_number(number);
    }
    builder.build()
}

/// Byte `0x7b` for what we are doing.
///
/// Three of the twelve values a CDJ can send, because three is all a host with
/// no platter can honestly be in: nothing loaded, playing, or paused. Reporting
/// a cue or search state we do not have would be inventing a transport.
fn play_state_for(playback: &Playback) -> crate::monitor::PlayState {
    use crate::monitor::PlayState;
    if playback.bpm_centi.is_none() {
        PlayState::NO_TRACK
    } else if playback.playing {
        PlayState::PLAYING
    } else {
        PlayState::PAUSED
    }
}

/// Run the claim chain and return the number we ended up holding, and whether
/// a player answered our stage-3 claim with a `0x05`: the one holding the
/// first-on-network role, which we then leave to it.
async fn claim(
    discovery: &Discovery,
    config: &VirtualCdjConfig,
    interface: &crate::Interface,
    preferred: Option<BrowsableDeviceNumber>,
    was_first: bool,
    phase: &watch::Sender<Phase>,
) -> Result<(DeviceNumber, bool)> {
    debug!(?preferred, "watching before claiming");
    let _ = phase.send(Phase::Watching);
    tokio::time::sleep(PRESCAN).await;

    let seen = discovery.numbers_seen();
    let mut candidates: Vec<BrowsableDeviceNumber> = preferred
        .into_iter()
        .chain(BrowsableDeviceNumber::descending())
        .filter(|number| !seen.contains(&number.get()))
        .collect();
    candidates.dedup();
    if candidates.is_empty() {
        return Err(discovery.no_browsable_number());
    }

    let socket = discovery.socket();
    let to = SocketAddr::V4(SocketAddrV4::new(interface.broadcast(), DISCOVERY_PORT));
    let _ = phase.send(Phase::Claiming);

    for candidate in candidates {
        let mut conflicts = discovery.announcements();
        match claim_one(
            &socket,
            to,
            config,
            interface,
            candidate,
            was_first,
            &mut conflicts,
        )
        .await
        {
            Ok(answered) => {
                info!(number = %candidate, "claimed a browsable device number");
                return Ok((candidate.number(), answered));
            }
            Err(holder) => {
                warn!(number = %candidate, %holder, "number is taken; backing off");
            }
        }
    }
    Err(discovery.no_browsable_number())
}

/// One pass of the claim chain for one candidate.
///
/// `Ok(true)` means it is ours and a player answered our stage-3 claim with a
/// `0x05`, which ends the burst there: that player holds the first-on-network
/// role (S13 17.389-17.392, S26 5.605-5.606). `Err(holder)` means somebody
/// defended it, or that a rival claiming it at the same moment outranks us.
///
/// # Two at once
///
/// Only a holder defends a number, so two devices claiming the same one at the
/// same time never hear a conflict: both finish the chain, and both announce
/// it. That is what emulated decks started together did, every time, each
/// having watched the network before the other spoke. So a rival heard
/// proposing our candidate in its own claim decides it: the lower address keeps
/// claiming and the higher backs off to its next candidate. Both apply the same
/// rule to the same two addresses, so exactly one of them moves. A deck that
/// never backs off (real hardware) costs us nothing we did not already lose.
async fn claim_one(
    socket: &UdpSocket,
    to: SocketAddr,
    config: &VirtualCdjConfig,
    interface: &crate::Interface,
    candidate: BrowsableDeviceNumber,
    was_first: bool,
    conflicts: &mut broadcast::Receiver<crate::discovery::Announcement>,
) -> std::result::Result<bool, Ipv4Addr> {
    // N is 3 into an empty network and 1 into a populated one (C13).
    let final_stage = if was_first { 3 } else { 1 };
    let mut stages: Vec<Body> = Vec::new();
    for iteration in 1..=3 {
        stages.push(Body::Hello {
            payload: config.kind.role(),
        });
        let _ = iteration;
    }
    for iteration in 1..=3 {
        stages.push(Body::ClaimMac {
            iteration,
            flags: config.kind.role(),
            mac: interface.mac,
        });
    }
    for iteration in 1..=3 {
        stages.push(Body::ClaimIp {
            ip: interface.ip,
            mac: interface.mac,
            device_number: candidate.get(),
            iteration,
            role: config.kind.role(),
            // We always ask for a specific number, having picked it ourselves.
            assignment_mode: djl::AssignmentMode::MANUAL,
        });
    }
    for iteration in 1..=final_stage {
        stages.push(Body::ClaimNumber {
            device_number: candidate.get(),
            iteration,
        });
    }

    for body in stages {
        let stage_3 = matches!(body, Body::ClaimNumber { .. });
        let packet = djl::Packet::new(config.name, config.kind, body);
        if let Err(error) = socket.send_to(&packet.encode(), to).await {
            warn!(%error, "claim packet failed");
        }
        // Sleep between packets, watching for a conflict the whole time.
        let deadline = tokio::time::sleep(djl::DISCOVERY_INTERVAL);
        tokio::pin!(deadline);
        loop {
            tokio::select! {
                () = &mut deadline => break,
                received = conflicts.recv() => {
                    let Ok(announcement) = received else { break };
                    if let Some(holder) = contested(&announcement, candidate, interface) {
                        return Err(holder);
                    }
                    // Answered: the number is ours (a 0x05 names the sender's
                    // own, F58), and the burst ends here, as a real deck's did.
                    if stage_3 && answers_our_claim(&announcement) {
                        return Ok(true);
                    }
                }
            }
        }
    }
    Ok(false)
}

/// Whether `announcement` is a player answering our stage-3 claim.
///
/// A `0x05` is only ever sent in answer to a claim, unicast to the claimer, by
/// the player holding the first-on-network role (S13 17.391, S26 5.606, E07
/// 56.165). It names the sender's own number, not a rejection of ours (F58).
fn answers_our_claim(announcement: &crate::discovery::Announcement) -> bool {
    matches!(announcement.packet.body, Body::NumberInUse { .. })
}

/// Whether `announcement` is another device's keep-alive saying it was first
/// on the network, which is our cue to stop saying so.
///
/// Our own keep-alives come back to us (we bind 0.0.0.0), and are ours by
/// their MAC.
fn steps_aside(
    announcement: &crate::discovery::Announcement,
    ours: prolink_proto::MacAddress,
) -> bool {
    matches!(
        announcement.packet.body,
        Body::KeepAlive {
            was_first_on_network: FIRST_ON_NETWORK,
            mac,
            ..
        } if mac != ours
    )
}

/// Whether `announcement` takes `candidate` from us mid-claim, and from whom.
fn contested(
    announcement: &crate::discovery::Announcement,
    candidate: BrowsableDeviceNumber,
    interface: &crate::Interface,
) -> Option<Ipv4Addr> {
    match announcement.packet.body {
        Body::NumberConflict { device_number, ip } if device_number == candidate.get() => {
            Some(if ip.is_unspecified() {
                announcement.from
            } else {
                ip
            })
        }
        // A rival's claim for the same number: the lower address keeps it.
        // Our own claims come back to us too (we bind 0.0.0.0), and are ours by
        // their address.
        Body::ClaimIp {
            device_number, ip, ..
        } if device_number == candidate.get() && outranks(ip, interface) => Some(ip),
        Body::ClaimNumber { device_number, .. }
            if device_number == candidate.get() && outranks(announcement.from, interface) =>
        {
            Some(announcement.from)
        }
        _ => None,
    }
}

/// Whether a rival at `ip` keeps a number we are both claiming. An address of
/// nothing outranks nobody: it is not a device anyone could unicast to.
fn outranks(ip: Ipv4Addr, interface: &crate::Interface) -> bool {
    !ip.is_unspecified() && ip < interface.ip
}

/// The addresses of every peer currently answering, refreshed as the table
/// changes.
///
/// Status is unicast per peer and the keep-alive carries a peer count, so both
/// timers need this and neither wants to lock the whole device table at 200 ms.
#[derive(Debug)]
struct PeerAddresses {
    devices: Arc<Mutex<Vec<Ipv4Addr>>>,
    task: JoinHandle<()>,
}

impl PeerAddresses {
    fn new(discovery: &Discovery) -> Self {
        let devices = Arc::new(Mutex::new(
            discovery
                .online()
                .into_iter()
                .map(|device| device.ip)
                .collect::<Vec<_>>(),
        ));
        let mut events = discovery.subscribe();
        let shared = Arc::clone(&devices);
        let task = tokio::spawn(async move {
            loop {
                let Ok(event) = events.recv().await else {
                    return;
                };
                let ip = event.device().ip;
                let add = !matches!(
                    event,
                    crate::device::DeviceEvent::Forgotten(_)
                        | crate::device::DeviceEvent::WentOffline(_)
                );
                let mut devices = match shared.lock() {
                    Ok(devices) => devices,
                    Err(poisoned) => poisoned.into_inner(),
                };
                devices.retain(|known| *known != ip);
                if add {
                    devices.push(ip);
                }
            }
        });
        Self { devices, task }
    }

    fn get(&self) -> Vec<Ipv4Addr> {
        match self.devices.lock() {
            Ok(devices) => devices.clone(),
            Err(poisoned) => poisoned.into_inner().clone(),
        }
    }

    fn len(&self) -> usize {
        match self.devices.lock() {
            Ok(devices) => devices.len(),
            Err(poisoned) => poisoned.into_inner().len(),
        }
    }
}

impl Drop for PeerAddresses {
    fn drop(&mut self) {
        self.task.abort();
    }
}

#[cfg(test)]
mod tests {
    /// Every status packet in a capture, fed through [`observe_loaded`] the way
    /// the live socket feeds it.
    ///
    /// The one end-to-end check that the registry behind the key-matching
    /// indicator fills at all: a real deck-to-deck session in which device 2
    /// loaded track 472 off device 1's USB (F55).
    #[test]
    fn a_capture_of_a_deck_loading_from_us_fills_the_registry() {
        let Some(corpus) = prolink_capture::Corpus::locate() else {
            return;
        };
        let path = corpus.root().join("S27-sort-by-and-key/run.pcap");
        let Ok(capture) = prolink_capture::Capture::open(&path) else {
            return;
        };
        let loaded = LoadedTracks::default();
        let mut seen = 0usize;
        for packet in capture.udp_to(STATUS_PORT).flatten() {
            let Ok(status::Packet::CdjStatus(peer)) = status::decode(&packet.payload) else {
                continue;
            };
            let Some(source) = peer.source_player() else {
                continue;
            };
            // Stand in for whichever deck was serving in this session.
            observe_loaded(&loaded, source, &peer);
            seen += 1;
        }
        assert!(
            seen > 100,
            "the corpus should hold plenty of status packets"
        );
        assert!(
            !loaded.by_device.lock().expect("not poisoned").is_empty(),
            "no deck's loaded track was recorded from {seen} status packets"
        );
    }

    #[test]
    fn a_track_loaded_from_another_player_is_not_ours_to_mark() {
        let loaded = LoadedTracks::default();
        let ours = DeviceNumber::new(4).expect("4 is a device number");
        let theirs = DeviceNumber::new(1).expect("1 is a device number");
        let mut raw = CdjStatus::builder()
            .device_number(DeviceNumber::new(2).expect("2 is a device number"))
            .name(DeviceName::default())
            .build()
            .into_bytes();
        raw[0x28] = theirs.get();
        raw[0x29] = Slot::USB.0;
        raw[0x2c..0x30].copy_from_slice(&99u32.to_be_bytes());
        let peer = CdjStatus::parse(&raw).expect("a status packet");
        observe_loaded(&loaded, ours, &peer);
        assert_eq!(loaded.track_on(2, Slot::USB), None);

        raw[0x28] = ours.get();
        let peer = CdjStatus::parse(&raw).expect("a status packet");
        observe_loaded(&loaded, ours, &peer);
        assert_eq!(loaded.track_on(2, Slot::USB), Some(99));
    }

    use super::*;
    use prolink_proto::status::MediaState;

    fn interface() -> crate::Interface {
        crate::Interface {
            name: "test0".to_owned(),
            index: 1,
            ip: Ipv4Addr::new(169, 254, 99, 100),
            netmask: Ipv4Addr::new(255, 255, 0, 0),
            mac: prolink_proto::MacAddress([0xa0, 0xce, 0xc8, 0xe2, 0x26, 0xde]),
        }
    }

    fn announcement(body: Body, from: [u8; 4]) -> crate::discovery::Announcement {
        crate::discovery::Announcement {
            packet: djl::Packet::new(DeviceName::default(), DeviceKind::CDJ, body),
            from: Ipv4Addr::from(from),
        }
    }

    fn browsable(number: u8) -> BrowsableDeviceNumber {
        BrowsableDeviceNumber::new(number).expect("a browsable device number")
    }

    #[test]
    fn a_rival_claiming_our_number_at_once_is_settled_by_address() {
        let ours = interface(); // 169.254.99.100
        let claim_ip = |ip: [u8; 4], number: u8| {
            announcement(
                Body::ClaimIp {
                    ip: Ipv4Addr::from(ip),
                    mac: prolink_proto::MacAddress([2, 0, 0, 0, 0, 1]),
                    device_number: number,
                    iteration: 1,
                    role: DeviceKind::CDJ.role(),
                    assignment_mode: djl::AssignmentMode::MANUAL,
                },
                ip,
            )
        };
        let lower = [169, 254, 3, 7];
        let higher = [169, 254, 200, 1];
        assert_eq!(
            contested(&claim_ip(lower, 4), browsable(4), &ours),
            Some(Ipv4Addr::from(lower)),
            "a lower address claiming our candidate keeps it"
        );
        assert_eq!(
            contested(&claim_ip(higher, 4), browsable(4), &ours),
            None,
            "a higher one backs off itself, by the same rule"
        );
        assert_eq!(
            contested(&claim_ip(lower, 3), browsable(4), &ours),
            None,
            "another number is no contest"
        );
        assert_eq!(
            contested(&claim_ip(ours.ip.octets(), 4), browsable(4), &ours),
            None,
            "our own claim, heard back, is not a rival"
        );

        let claim_number = |from: [u8; 4]| {
            announcement(
                Body::ClaimNumber {
                    device_number: 4,
                    iteration: 1,
                },
                from,
            )
        };
        assert_eq!(
            contested(&claim_number(lower), browsable(4), &ours),
            Some(Ipv4Addr::from(lower)),
            "the last stage carries no address of its own: the sender's decides"
        );
        assert_eq!(contested(&claim_number(higher), browsable(4), &ours), None);
        assert_eq!(
            contested(&claim_number(ours.ip.octets()), browsable(4), &ours),
            None
        );
        assert_eq!(
            contested(&claim_number([0, 0, 0, 0]), browsable(4), &ours),
            None,
            "nor does a sender with no address"
        );
    }

    /// Every discovery packet real hardware sent, put to [`contested`] as if
    /// we were claiming each browsable number at that moment, from the lowest
    /// and from the highest link-local address.
    ///
    /// The rule must only ever take a number from us when the packet is that
    /// very number being claimed (or defended) by a device below us: never a
    /// keep-alive, a hello, a MAC claim, a NUMBER_IN_USE, a mixer, or a claim
    /// for another number. From the lowest address nothing but a defence can
    /// move us, which is the behaviour this had before the rule existed.
    #[test]
    fn real_hardware_takes_a_number_from_a_claim_only_by_claiming_it() {
        let Some(corpus) = prolink_capture::Corpus::locate() else {
            return;
        };
        let lowest = crate::Interface {
            ip: Ipv4Addr::new(169, 254, 0, 1),
            ..interface()
        };
        let highest = crate::Interface {
            ip: Ipv4Addr::new(169, 254, 255, 254),
            ..interface()
        };
        let (mut packets, mut rival_claims) = (0usize, 0usize);
        for path in corpus.captures() {
            let Ok(capture) = prolink_capture::Capture::open(&path) else {
                continue;
            };
            for packet in capture.udp_to(DISCOVERY_PORT).flatten() {
                let Ok(decoded) = djl::Packet::decode(&packet.payload) else {
                    continue;
                };
                packets += 1;
                let heard = crate::discovery::Announcement {
                    packet: decoded,
                    from: *packet.source.ip(),
                };
                for number in 1..=4 {
                    let candidate = browsable(number);
                    let (expected_low, expected_high) = match heard.packet.body {
                        Body::NumberConflict { device_number, .. } if device_number == number => {
                            let holder = contested(&heard, candidate, &lowest);
                            assert!(holder.is_some(), "a defence must always win");
                            (holder, holder)
                        }
                        Body::ClaimIp {
                            device_number, ip, ..
                        } if device_number == number && !ip.is_unspecified() => {
                            rival_claims += 1;
                            (None, Some(ip))
                        }
                        Body::ClaimNumber { device_number, .. } if device_number == number => {
                            rival_claims += 1;
                            (None, Some(heard.from))
                        }
                        _ => (None, None),
                    };
                    assert_eq!(
                        contested(&heard, candidate, &lowest),
                        expected_low,
                        "{} frame {}: {:?} claiming {number} from below everyone",
                        path.display(),
                        packet.index,
                        heard.packet.body
                    );
                    assert_eq!(
                        contested(&heard, candidate, &highest),
                        expected_high,
                        "{} frame {}: {:?} claiming {number} from above everyone",
                        path.display(),
                        packet.index,
                        heard.packet.body
                    );
                }
            }
        }
        assert!(
            packets > 1000,
            "only {packets} discovery packets in the corpus"
        );
        assert!(
            rival_claims > 0,
            "the corpus holds real claims, and each one is checked above"
        );
    }

    fn keep_alive_from(mac: [u8; 6], was_first_on_network: u8) -> crate::discovery::Announcement {
        announcement(
            Body::KeepAlive {
                device_number: 1,
                was_first_on_network,
                mac: prolink_proto::MacAddress(mac),
                ip: Ipv4Addr::new(169, 254, 103, 172),
                peer_count: 2,
                pad_31: [0; 3],
                flags: DeviceKind::CDJ.role(),
                trailing: 0,
            },
            [169, 254, 103, 172],
        )
    }

    #[test]
    fn another_device_saying_it_was_first_makes_us_step_aside() {
        let ours = interface().mac;
        assert!(
            steps_aside(
                &keep_alive_from([0x74, 0x5e, 0x1c, 0x56, 0x67, 0xac], 0x02),
                ours
            ),
            "a player saying 0x02 holds the role, and we leave it to it"
        );
        assert!(
            !steps_aside(
                &keep_alive_from([0x74, 0x5e, 0x1c, 0x56, 0x67, 0xac], 0x01),
                ours
            ),
            "a player saying 0x01 holds nothing we have to give up"
        );
        assert!(
            !steps_aside(&keep_alive_from(ours.0, 0x02), ours),
            "our own keep-alive comes back to us, and is ours by its MAC"
        );
        let claim = announcement(
            Body::ClaimNumber {
                device_number: 2,
                iteration: 1,
            },
            [169, 254, 202, 84],
        );
        assert!(
            !steps_aside(&claim, ours),
            "a claim says nothing of the role"
        );
    }

    #[test]
    fn only_a_0x05_answers_our_claim() {
        let answer = announcement(
            Body::NumberInUse {
                device_number: 2,
                iteration: 1,
            },
            [169, 254, 202, 84],
        );
        assert!(answers_our_claim(&answer));
        let claim = announcement(
            Body::ClaimNumber {
                device_number: 2,
                iteration: 1,
            },
            [169, 254, 202, 84],
        );
        assert!(
            !answers_our_claim(&claim),
            "a rival's claim is not an answer"
        );
        assert!(!answers_our_claim(&keep_alive_from(
            [2, 0, 0, 0, 0, 1],
            0x02
        )));
    }

    /// Every discovery packet real hardware sent, put to the two rules that
    /// end our hold on keep-alive byte `0x25`, as if we were on each link
    /// with a MAC no capture holds.
    ///
    /// We step aside for exactly the keep-alives that say `0x02`, and take a
    /// `0x05` as an answer, and nothing else does either. And S26, replayed
    /// from player 2's side: it heard player 1 say `0x02` 1.8 s before it
    /// re-claimed and was answered, so a deck stepping aside on the keep-alive
    /// alone gives the role up sooner, and sends nothing to do it.
    #[test]
    fn real_hardware_asks_us_to_step_aside_only_by_saying_it_was_first() {
        let Some(corpus) = prolink_capture::Corpus::locate() else {
            return;
        };
        let ours = prolink_proto::MacAddress([0x02, 0xff, 0xff, 0xff, 0xff, 0xfe]);
        let (mut said_first, mut answers, mut others) = (0usize, 0usize, 0usize);
        for path in corpus.captures() {
            let Ok(capture) = prolink_capture::Capture::open(&path) else {
                continue;
            };
            for packet in capture.udp_to(DISCOVERY_PORT).flatten() {
                let Ok(decoded) = djl::Packet::decode(&packet.payload) else {
                    continue;
                };
                let heard = crate::discovery::Announcement {
                    packet: decoded,
                    from: *packet.source.ip(),
                };
                let first = matches!(
                    heard.packet.body,
                    Body::KeepAlive {
                        was_first_on_network: FIRST_ON_NETWORK,
                        ..
                    }
                );
                let answer = matches!(heard.packet.body, Body::NumberInUse { .. });
                assert_eq!(
                    steps_aside(&heard, ours),
                    first,
                    "{} frame {}: {:?}",
                    path.display(),
                    packet.index,
                    heard.packet.body
                );
                assert_eq!(answers_our_claim(&heard), answer);
                match (first, answer) {
                    (true, _) => said_first += 1,
                    (_, true) => answers += 1,
                    _ => others += 1,
                }
            }
        }
        assert!(
            said_first > 1000,
            "only {said_first} keep-alives saying 0x02"
        );
        assert!(others > 1000, "only {others} other discovery packets");
        assert_eq!(answers, 2, "the corpus holds two 0x05s, S13's and S26's");
    }

    /// Run one claim pass against a stand-in for the other player, which hears
    /// everything we send and answers our first stage-3 claim with `answer`.
    /// What came back, and every packet body we sent.
    async fn claim_against(
        answer: Option<crate::discovery::Announcement>,
    ) -> (std::result::Result<bool, Ipv4Addr>, Vec<Body>) {
        let player_socket = UdpSocket::bind("127.0.0.1:0").await.expect("a socket");
        let to = player_socket.local_addr().expect("its address");
        let socket = UdpSocket::bind("127.0.0.1:0").await.expect("a socket");
        let (tell, mut heard) = broadcast::channel(16);
        let player = tokio::spawn(async move {
            let mut answer = answer;
            let mut sent = Vec::new();
            let mut buffer = [0u8; 128];
            // Our packets are 300 ms apart; half a second of silence is the end.
            while let Ok(Ok(len)) =
                tokio::time::timeout(Duration::from_millis(500), player_socket.recv(&mut buffer))
                    .await
            {
                let packet = djl::Packet::decode(&buffer[..len]).expect("our own packet");
                if matches!(packet.body, Body::ClaimNumber { .. })
                    && let Some(answer) = answer.take()
                {
                    let _ = tell.send(answer);
                }
                sent.push(packet.body);
            }
            sent
        });
        let result = claim_one(
            &socket,
            to,
            &VirtualCdjConfig::default(),
            &interface(),
            browsable(4),
            true,
            &mut heard,
        )
        .await;
        (result, player.await.expect("the stand-in player"))
    }

    /// Our stage-3 burst against a player that answers it, and one that does
    /// not. The answer is S13's own `0x05` (17.391): player 2, holding the
    /// first-on-network role, answering player 1's first stage-3 claim.
    #[tokio::test]
    async fn a_0x05_ends_our_burst_and_we_do_not_take_the_role() {
        const S13_ANSWER: &[u8] = &[
            0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x05, 0x00, 0x43, 0x44,
            0x4a, 0x2d, 0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x26, 0x02, 0x01,
        ];
        let answer = crate::discovery::Announcement {
            packet: djl::Packet::decode(S13_ANSWER).expect("S13's 0x05 decodes"),
            from: Ipv4Addr::new(169, 254, 202, 84),
        };
        let claims = |sent: &[Body]| {
            sent.iter()
                .filter(|body| matches!(body, Body::ClaimNumber { .. }))
                .count()
        };

        let ((answered, sent_answered), (unanswered, sent_unanswered)) =
            tokio::join!(claim_against(Some(answer)), claim_against(None));

        assert_eq!(
            answered,
            Ok(true),
            "the number is ours, and we were answered"
        );
        assert_eq!(
            (sent_answered.len(), claims(&sent_answered)),
            (10, 1),
            "the burst ends at the answer: S13's player 1 sent one claim"
        );
        // Unanswered, into an empty network, the burst is three (C13).
        assert_eq!(unanswered, Ok(false));
        assert_eq!((sent_unanswered.len(), claims(&sent_unanswered)), (12, 3));
    }

    fn published(tempo_master: bool, yielding_to: Option<u8>) -> Published {
        Published {
            tempo_master,
            yielding_to: yielding_to.and_then(DeviceNumber::new),
            synced: false,
            playing: true,
            play_state: crate::monitor::PlayState::PLAYING.0,
            loaded: None,
            usb: MediaState::EMPTY,
            sd: MediaState::EMPTY,
        }
    }

    #[test]
    fn status_goes_out_every_200_ms_unchanged_and_at_once_on_a_change() {
        let sent = Instant::now();
        let master = published(true, None);
        let ms = |n: u64| sent + Duration::from_millis(n);
        assert!(status_due(None, sent, master), "the first one goes at once");
        let last = Some((sent, master));
        assert!(!status_due(last, ms(100), master), "nothing new: wait");
        assert!(!status_due(last, ms(199), master));
        assert!(status_due(last, ms(200), master), "the 200 ms cadence");

        // Naming a successor is news a requester acts on: S28's holders sent
        // it 3.3-5.2 ms after the request.
        let handing_over = published(true, Some(2));
        assert!(status_due(last, ms(62), handing_over));
        assert!(
            !status_due(last, ms(61), handing_over),
            "but never sooner than 62 ms after the last packet: S28's floor"
        );
    }

    #[test]
    fn what_a_peer_acts_on_at_once_is_what_triggers_a_packet() {
        let master = published(true, None);
        assert_ne!(master, published(true, Some(2)), "a successor named");
        assert_ne!(master, published(false, None), "master given up");
        assert_ne!(
            master,
            Published {
                playing: false,
                play_state: crate::monitor::PlayState::PAUSED.0,
                ..master
            },
            "a stop"
        );
        assert_ne!(
            master,
            Published {
                synced: true,
                ..master
            },
            "SYNC lit"
        );
        assert_ne!(
            master,
            Published {
                usb: MediaState::UNMOUNTING,
                ..master
            },
            "an eject's first step"
        );
    }

    /// A virtual CDJ with no tasks and no sockets: enough for what touches
    /// only its own state.
    fn bare_cdj() -> VirtualCdj {
        VirtualCdj {
            config: VirtualCdjConfig::default(),
            interface: interface(),
            number: Arc::new(AtomicU8::new(3)),
            phase: watch::channel(Phase::Announcing).0,
            media: Arc::new(NoMedia),
            loaded: Arc::new(LoadedTracks::default()),
            peers: Arc::new(PeerMedia::default()),
            status_socket: None,
            status_tap: None,
            status_counter: Arc::new(AtomicU32::new(0)),
            playback: Arc::new(PlaybackCell::default()),
            playing_track: Arc::new(Mutex::new(None)),
            tempo_master: Arc::new(AtomicBool::new(false)),
            yielding_to: Arc::new(AtomicU8::new(0)),
            synced: Arc::new(AtomicBool::new(false)),
            first_on_network: Arc::new(AtomicBool::new(false)),
            tasks: Vec::new(),
        }
    }

    /// With two decks that may each take over, a master that named one and
    /// then the other would leave both claiming it: one successor at a time.
    #[test]
    fn a_master_offers_its_mastership_to_one_deck_at_a_time() {
        let cdj = bare_cdj();
        let two = DeviceNumber::new(2).expect("2 is a device number");
        let four = DeviceNumber::new(4).expect("4 is a device number");
        assert!(!cdj.offer_tempo_master(two), "not master: nothing to offer");

        cdj.set_tempo_master(true);
        assert!(cdj.offer_tempo_master(two));
        assert_eq!(cdj.yielding_to(), Some(two));
        assert!(
            !cdj.offer_tempo_master(four),
            "an offer in flight is not written over"
        );
        assert_eq!(cdj.yielding_to(), Some(two), "0x9f still names the first");

        // Withdrawn after nobody took it up: the next deck may be offered it.
        cdj.withdraw_offer();
        assert!(cdj.offer_tempo_master(four));
        assert_eq!(cdj.yielding_to(), Some(four));

        // Taken up: we are no longer master, and offer nothing.
        cdj.finish_yield();
        assert!(!cdj.offer_tempo_master(two));
        assert_eq!(cdj.yielding_to(), None);
    }

    #[test]
    fn a_holder_defending_our_candidate_still_takes_it() {
        let ours = interface();
        let defended = announcement(
            Body::NumberConflict {
                device_number: 4,
                ip: Ipv4Addr::new(169, 254, 250, 250),
            },
            [169, 254, 250, 250],
        );
        assert_eq!(
            contested(&defended, browsable(4), &ours),
            Some(Ipv4Addr::new(169, 254, 250, 250)),
            "a defence wins whatever the address"
        );
    }

    #[test]
    fn the_default_numbering_cannot_disturb_a_live_rig() {
        let Numbering::Observer(number) = Numbering::default() else {
            panic!("the default must not claim");
        };
        assert_eq!(number, OBSERVER_NUMBER);
        assert!(
            !number.is_player(),
            "outside 1-6, so it cannot collide with hardware"
        );
        assert!(
            number.browsable().is_none(),
            "and cannot be browsed, by construction"
        );
    }

    #[test]
    fn our_keep_alive_matches_a_real_deck_byte_for_byte() {
        // The captured keep-alive from `captures/S24b-e9-control`, which the
        // codec's own test also pins. Emitting a packet that differs from this
        // is the definition of being distinguishable from a real deck.
        const REAL: &[u8] = &[
            0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x06, 0x00, 0x43, 0x44,
            0x4a, 0x2d, 0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x36, 0x05, 0x02, 0xa0, 0xce, 0xc8, 0xe2,
            0x26, 0xde, 0xa9, 0xfe, 0x63, 0x64, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
        ];
        let config = VirtualCdjConfig {
            numbering: Numbering::Observer(DeviceNumber::new(5).unwrap()),
            ..VirtualCdjConfig::default()
        };
        let number = AtomicU8::new(5);
        let packet = keep_alive_packet(&config, &interface(), &number, 0, true);
        assert_eq!(packet.encode(), REAL);
    }

    #[test]
    fn a_status_packet_reports_only_the_slots_we_serve() {
        #[derive(Debug)]
        struct UsbOnly;
        impl MediaSource for UsbOnly {
            fn occupied_slots(&self) -> std::collections::BTreeSet<Slot> {
                [Slot::USB].into_iter().collect()
            }
            fn describe(&self, slot: Slot) -> Option<MediaDescription> {
                (slot == Slot::USB).then(MediaDescription::default)
            }
        }

        let number = AtomicU8::new(3);
        let counter = AtomicU32::new(0);
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &UsbOnly,
            &counter,
            1,
            Transport {
                playback: &Playback::default(),
                loaded: None,
                tempo_master: false,
                yielding_to: None,
                synced: false,
            },
        );
        assert_eq!(packet.usb_state(), MediaState::LOADED);
        assert_eq!(
            packet.sd_state(),
            MediaState::EMPTY,
            "a slot we do not serve is empty"
        );
        assert!(packet.link_available());
        assert_eq!(
            packet.bpm_centi(),
            None,
            "a server with nothing playing states no tempo"
        );
        assert_eq!(packet.beat_in_bar(), None);
    }

    /// Track 42 off player 2's USB, which is where `playing()` came from.
    fn playing_track() -> status::LoadedTrack {
        status::LoadedTrack {
            source_player: DeviceNumber::new(2).expect("device 2"),
            slot: Slot::USB,
            id: 42,
            track_type: prolink_proto::dbserver::TrackType::REKORDBOX,
        }
    }

    /// A deck playing 145.00 BPM, on beat 6, halfway through it.
    fn playing() -> Playback {
        Playback {
            bpm_centi: Some(14_500),
            pitch: prolink_proto::beat::Pitch::UNITY,
            playing: true,
            beat: Some(BeatPosition {
                number: 6,
                fraction: 0.5,
            }),
            scratching: false,
        }
    }

    #[test]
    fn what_we_are_playing_reaches_the_status_packet() {
        // The whole point of the tempo half: without these fields a CDJ sees a
        // device with no tempo, has nothing to beat-match against, and draws no
        // phase for us at all.
        let number = AtomicU8::new(2);
        let counter = AtomicU32::new(0);
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &NoMedia,
            &counter,
            1,
            Transport {
                playback: &playing(),
                loaded: Some(playing_track()),
                tempo_master: true,
                yielding_to: None,
                synced: false,
            },
        );
        assert_eq!(packet.bpm_centi(), Some(14_500));
        assert_eq!(packet.beat_number(), Some(6));
        assert_eq!(packet.beat_in_bar(), prolink_proto::beat::BeatInBar::new(2));
        assert_eq!(packet.is_tempo_master(), Some(true));
        // The track the tempo belongs to. A master that states one without the
        // other is a state no deck has ever published, and a CDJ will not
        // follow it -- which is how this was found.
        assert_eq!(packet.track_id(), 42);
        assert_eq!(packet.source_slot(), Slot::USB);
        assert_eq!(packet.track_type(), 1);
        assert_eq!(
            packet.play_state(),
            Some(crate::monitor::PlayState::PLAYING.0)
        );
    }

    #[test]
    fn a_handover_names_its_successor_and_keeps_the_claim() {
        // **The grant is byte `0x9f`, not the absence of byte `0x9e`.** A deck
        // asking for mastership watches for its own number to appear at 0x9f
        // and acts on nothing else; the holder's claim simply going away is
        // what a refusal looks like from the requester's side.
        //
        // So a handover in flight publishes BOTH: still master, and naming who
        // it is handing to. Publishing only the second would be a deck that has
        // never existed, and publishing only the first is the bug this test
        // exists for -- a CDJ that pressed MASTER and never got it, with both
        // decks believing the handover had happened.
        let number = AtomicU8::new(2);
        let counter = AtomicU32::new(0);
        let successor = DeviceNumber::new(3).expect("a device number");
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &NoMedia,
            &counter,
            1,
            Transport {
                playback: &playing(),
                loaded: Some(playing_track()),
                tempo_master: true,
                yielding_to: Some(successor),
                synced: false,
            },
        );
        assert_eq!(packet.is_tempo_master(), Some(true));
        assert_eq!(packet.yielding_to(), Some(successor));
    }

    #[test]
    fn no_handover_leaves_the_successor_byte_empty() {
        // 0xff, not zero, and written every packet rather than left to the
        // captured skeleton: a field only written when it is interesting keeps
        // whatever the last interesting packet put there.
        let number = AtomicU8::new(2);
        let counter = AtomicU32::new(0);
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &NoMedia,
            &counter,
            1,
            Transport {
                playback: &playing(),
                loaded: Some(playing_track()),
                tempo_master: true,
                yielding_to: None,
                synced: false,
            },
        );
        assert_eq!(packet.yielding_to(), None);
    }

    #[test]
    fn a_paused_deck_still_states_its_tempo() {
        // It has a track loaded and a tempo to state; what it does not have is
        // sound coming out. Reporting no tempo would make the deck vanish from
        // every other player's tempo display the moment it is paused.
        let number = AtomicU8::new(2);
        let counter = AtomicU32::new(0);
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &NoMedia,
            &counter,
            0,
            Transport {
                playback: &Playback {
                    playing: false,
                    ..playing()
                },
                loaded: Some(playing_track()),
                tempo_master: false,
                yielding_to: None,
                synced: false,
            },
        );
        assert_eq!(packet.bpm_centi(), Some(14_500));
        assert_eq!(
            packet.play_state(),
            Some(crate::monitor::PlayState::PAUSED.0)
        );
        assert_eq!(
            packet.flags().map(status::StatusFlags::is_playing),
            Some(false)
        );
    }

    /// At 145 BPM a beat is 414 ms: a tick (5 ms) is about 0.012 of one.
    fn at(number: u32, fraction: f64) -> Playback {
        Playback {
            beat: Some(BeatPosition { number, fraction }),
            ..playing()
        }
    }

    #[test]
    fn a_beat_goes_out_once_on_its_downbeat() {
        let mut emitted = None;
        // Seen mid-beat: nothing to send, only somewhere to count from.
        assert_eq!(beat_to_emit(&at(6, 0.5), &mut emitted), None);
        assert_eq!(beat_to_emit(&at(6, 0.9), &mut emitted), None);
        // Crossing into the next beat sends it, as its downbeat.
        let next = beat_to_emit(&at(7, 0.005), &mut emitted).expect("beat 7");
        assert_eq!(next.number, 7);
        assert!(next.fraction.abs() < f64::EPSILON);
        assert_eq!(beat_to_emit(&at(7, 0.02), &mut emitted), None);
    }

    #[test]
    fn a_crossing_noticed_late_is_skipped_not_sent_late() {
        let mut emitted = None;
        beat_to_emit(&at(6, 0.9), &mut emitted);
        // The task stalled: by the time it looks, beat 7 is a third gone.
        assert_eq!(beat_to_emit(&at(7, 0.3), &mut emitted), None);
        assert_eq!(
            beat_to_emit(&at(8, 0.0), &mut emitted).map(|p| p.number),
            Some(8)
        );
    }

    #[test]
    fn a_jump_forwards_sends_no_burst() {
        // A hot cue sixteen bars on used to send all sixty-four beats in
        // between, one per tick: a third of a second of tempo spike.
        let mut emitted = None;
        beat_to_emit(&at(6, 0.9), &mut emitted);
        assert_eq!(beat_to_emit(&at(70, 0.4), &mut emitted), None);
        assert_eq!(beat_to_emit(&at(70, 0.6), &mut emitted), None);
        assert_eq!(
            beat_to_emit(&at(71, 0.0), &mut emitted).map(|p| p.number),
            Some(71)
        );
    }

    #[test]
    fn a_jump_backwards_resumes_at_the_next_beat() {
        // Not silence until the track catches up -- and not the landing beat
        // sent mid-beat either.
        let mut emitted = None;
        beat_to_emit(&at(40, 0.5), &mut emitted);
        assert_eq!(beat_to_emit(&at(2, 0.5), &mut emitted), None);
        assert_eq!(
            beat_to_emit(&at(3, 0.004), &mut emitted).map(|p| p.number),
            Some(3)
        );
    }

    #[test]
    fn a_jump_that_lands_on_a_downbeat_sends_it() {
        let mut emitted = None;
        beat_to_emit(&at(40, 0.5), &mut emitted);
        assert_eq!(
            beat_to_emit(&at(17, 0.0), &mut emitted).map(|p| p.number),
            Some(17)
        );
    }

    #[test]
    fn a_scratched_platter_sends_no_beats() {
        let mut emitted = None;
        beat_to_emit(&at(6, 0.9), &mut emitted);
        let scratched = Playback {
            scratching: true,
            ..at(7, 0.0)
        };
        assert_eq!(beat_to_emit(&scratched, &mut emitted), None);
        // Let go mid-beat: the next downbeat sends.
        assert_eq!(beat_to_emit(&at(7, 0.5), &mut emitted), None);
        assert_eq!(
            beat_to_emit(&at(8, 0.0), &mut emitted).map(|p| p.number),
            Some(8)
        );
    }

    #[test]
    fn nothing_playing_emits_nothing_and_forgets_where_it_was() {
        let mut emitted = None;
        beat_to_emit(&at(6, 0.5), &mut emitted);
        let stopped = Playback {
            playing: false,
            ..at(6, 0.5)
        };
        assert_eq!(beat_to_emit(&stopped, &mut emitted), None);
        assert_eq!(emitted, None);
        // Play from a cue on the beat: that beat is sent.
        assert_eq!(
            beat_to_emit(&at(6, 0.0), &mut emitted).map(|p| p.number),
            Some(6)
        );
    }

    #[test]
    fn a_slot_being_ejected_publishes_the_state_a_consumer_acts_on() {
        // `0x03` is what makes a deck send UMNT โ€” it did so within 16 ms of it
        // in both captured ejects, and did nothing on `0x02`. So a source that
        // reports it must reach the wire unchanged rather than being flattened
        // to "no media here".
        #[derive(Debug)]
        struct Ejecting;
        impl MediaSource for Ejecting {
            fn occupied_slots(&self) -> std::collections::BTreeSet<Slot> {
                std::collections::BTreeSet::new()
            }
            fn describe(&self, _slot: Slot) -> Option<MediaDescription> {
                None
            }
            fn slot_state(&self, slot: Slot) -> MediaState {
                if slot == Slot::USB {
                    MediaState::UNMOUNTING_ALT
                } else {
                    MediaState::EMPTY
                }
            }
        }

        let number = AtomicU8::new(3);
        let counter = AtomicU32::new(0);
        let packet = status_packet(
            &VirtualCdjConfig::default(),
            &number,
            &Ejecting,
            &counter,
            1,
            Transport {
                playback: &Playback::default(),
                loaded: None,
                tempo_master: false,
                yielding_to: None,
                synced: false,
            },
        );
        assert_eq!(packet.usb_state(), MediaState::UNMOUNTING_ALT);
        assert_eq!(packet.sd_state(), MediaState::EMPTY);
    }

    /// A peer's status packet, with whatever it says about its slots.
    fn peer_status(device: u8, usb: MediaState, sd: MediaState) -> CdjStatus {
        let number = DeviceNumber::new(device).expect("a real device number");
        CdjStatus::builder()
            .device_number(number)
            .name(DeviceName::default())
            .slot_state(Slot::USB, usb)
            .slot_state(Slot::SD, sd)
            .build()
    }

    #[test]
    fn a_peers_status_packet_says_which_of_its_slots_hold_media() {
        // Occupancy is published here and nowhere else (F20), so this needs no
        // query and is current as soon as a peer unicasts to us.
        let peers = PeerMedia::default();
        observe_peer_slots(
            &peers,
            &peer_status(2, MediaState::LOADED, MediaState::EMPTY),
        );

        let device = DeviceNumber::new(2).unwrap();
        let usb = peers.get(device, Slot::USB).expect("the USB is known");
        assert!(usb.has_media());
        assert!(
            !peers
                .get(device, Slot::SD)
                .expect("the SD is known too")
                .has_media(),
            "an empty slot is known to be empty, which is not the same as unknown"
        );
        assert_eq!(peers.occupied().len(), 1);
        assert_eq!(
            usb.track_count(),
            None,
            "nothing has described it yet, and occupancy does not imply a count"
        );
    }

    #[test]
    fn a_media_response_names_the_medium_and_counts_it() {
        // Round-tripped through the wire form rather than constructed, so this
        // exercises the same parse a real deck's answer goes through.
        let peers = PeerMedia::default();
        let device = DeviceNumber::new(2).unwrap();
        let raw = status::MediaResponse::builder()
            .device_number(device)
            .slot(Slot::USB)
            .name(DeviceName::default())
            .volume_name("SAM2")
            .counts(692, 35)
            .build()
            .into_bytes();
        let response = status::MediaResponse::parse(&raw).expect("our own encoding parses");
        observe_peer_media(&peers, &response);

        let usb = peers.get(device, Slot::USB).expect("the USB is described");
        assert_eq!(usb.volume_name(), "SAM2");
        assert_eq!(usb.track_count(), Some(692));
        assert_eq!(usb.playlist_count(), Some(35));
        assert!(
            !usb.has_media(),
            "a description is not evidence of a medium: a deck answers for an empty slot too (F51)"
        );
    }

    #[test]
    fn the_two_halves_of_a_slot_arrive_separately_and_do_not_overwrite_each_other() {
        let peers = PeerMedia::default();
        let device = DeviceNumber::new(2).unwrap();
        let raw = status::MediaResponse::builder()
            .device_number(device)
            .slot(Slot::USB)
            .name(DeviceName::default())
            .volume_name("SAM2")
            .counts(692, 35)
            .build()
            .into_bytes();
        observe_peer_media(
            &peers,
            &status::MediaResponse::parse(&raw).expect("it parses"),
        );
        observe_peer_slots(
            &peers,
            &peer_status(2, MediaState::LOADED, MediaState::EMPTY),
        );

        let usb = peers.get(device, Slot::USB).expect("both halves landed");
        assert!(usb.has_media(), "the status packet supplied the occupancy");
        assert_eq!(usb.track_count(), Some(692), "and the response the counts");

        // And the other way round: a later status packet must not erase what a
        // response taught us, or an eject would take the name with it.
        observe_peer_slots(
            &peers,
            &peer_status(2, MediaState::UNMOUNTING, MediaState::EMPTY),
        );
        let usb = peers.get(device, Slot::USB).expect("still there");
        assert_eq!(usb.state, MediaState::UNMOUNTING);
        assert_eq!(usb.volume_name(), "SAM2");
    }

    #[test]
    fn a_pulled_mediums_name_goes_with_it() {
        let peers = PeerMedia::default();
        let deck = DeviceNumber::new(1).expect("1 is a device number");
        peers.note_state(deck, Slot::USB, MediaState::LOADED);
        peers.note_description(
            deck,
            Slot::USB,
            &MediaDescription {
                volume_name: "SAM1".to_owned(),
                created: "2026-01-04".to_owned(),
                track_count: 141,
                playlist_count: 4,
                total_bytes: None,
                free_bytes: None,
                plain: false,
            },
        );
        assert_eq!(
            peers.get(deck, Slot::USB).expect("a slot").volume_name(),
            "SAM1"
        );

        // An eject walks 0x02, 0x03, 0x04 (ยง3.2b). The name stays while it
        // unmounts, and goes when the slot is empty.
        peers.note_state(deck, Slot::USB, MediaState::UNMOUNTING);
        peers.note_state(deck, Slot::USB, MediaState::UNMOUNTING_ALT);
        assert_eq!(
            peers.get(deck, Slot::USB).expect("a slot").volume_name(),
            "SAM1"
        );
        peers.note_state(deck, Slot::USB, MediaState::EMPTY);
        let pulled = peers.get(deck, Slot::USB).expect("a slot");
        assert!(
            pulled.description.is_none(),
            "the medium's name went with it"
        );
        assert_eq!(pulled.volume_name(), "");

        // The next stick is not described until it is asked about.
        peers.note_state(deck, Slot::USB, MediaState::LOADED);
        assert!(
            peers
                .get(deck, Slot::USB)
                .expect("a slot")
                .description
                .is_none()
        );
    }

    #[test]
    fn peers_are_listed_by_device_and_slot() {
        let peers = PeerMedia::default();
        observe_peer_slots(
            &peers,
            &peer_status(3, MediaState::LOADED, MediaState::LOADED),
        );
        observe_peer_slots(
            &peers,
            &peer_status(1, MediaState::LOADED, MediaState::EMPTY),
        );

        let listed: Vec<_> = peers
            .all()
            .into_iter()
            .map(|entry| (entry.device.get(), entry.slot))
            .collect();
        assert_eq!(
            listed,
            vec![(1, Slot::SD), (1, Slot::USB), (3, Slot::SD), (3, Slot::USB)],
            "device order first, so a listing reads like the rig looks"
        );
        assert_eq!(peers.of(DeviceNumber::new(3).unwrap()).len(), 2);
    }

    #[test]
    fn a_media_query_for_a_slot_we_do_not_serve_gets_no_answer() {
        // An empty reply would tell the deck the slot exists and holds no
        // tracks, and it would then offer an empty medium (F24).
        let ours = DeviceNumber::new(3).unwrap();
        let query = status::MediaQuery {
            requester: DeviceNumber::new(2).unwrap(),
            requester_ip: Ipv4Addr::new(169, 254, 1, 2),
            target: ours,
            slot: Slot::SD,
        };
        assert!(answer_media_query(query, ours, DeviceName::default(), &NoMedia).is_none());
    }

    #[test]
    fn a_media_query_addressed_elsewhere_gets_no_answer() {
        let ours = DeviceNumber::new(3).unwrap();
        let query = status::MediaQuery {
            requester: DeviceNumber::new(2).unwrap(),
            requester_ip: Ipv4Addr::new(169, 254, 1, 2),
            target: DeviceNumber::new(4).unwrap(),
            slot: Slot::USB,
        };
        assert!(answer_media_query(query, ours, DeviceName::default(), &NoMedia).is_none());
    }
}