mx-remote 5.1.0

Client library for Pulse-Eight MatrixOS devices over UDP multicast/broadcast
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
// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
// Copyright (c) 2026 Op den Kamp IT Solutions

//! The command and notification opcodes: the frames addressed to a device
//! rather than reporting its state.
//!
//! Most of these are unpacked structs whose padding the firmware never clears,
//! so a field read one byte too wide picks up live stack content rather than a
//! zero. The fixtures here are poisoned wherever that padding is in reach.

use std::net::Ipv4Addr;

use crate::event::Event;
use crate::types::{
    AudioChangeSource, MultiviewerCommand, V2ipDecoderDetail, V2ipDecoderFormat, V2ipDecoderReason,
    V2ipDecoderState, VideoWallCommand, VideoWallOp, SCALING_FLAG_AUTO_SCALING,
    SCALING_FLAG_MATCH_SOURCE, SCALING_FLAG_MODE_VALID, SCALING_FLAG_OPTIONS2_VALID,
    SCALING_FLAG_OPTIONS_VALID, SCALING_FLAG_SKIP_420,
};
use crate::wire::{
    op, BayFeatures, BayStatus, DeviceFeature, DeviceUid, FirmwareType, MultiviewerViewMode,
    RcAction, RcKey, V2ipDeviceSetting, V2ipFpgaFeature, PROTOCOL_VERSION, V2IP_DSCP_DEFAULT,
    V2IP_PORT_ANC, V2IP_PORT_AUDIO, V2IP_PORT_VIDEO,
};

use crate::testing::{bay_config_rec, hello_payload, poisoned, uid_n, Cfg};

use super::Harness;

/// A registry whose single peer is a current OneIP unit.
fn command_device(n: u8) -> Harness {
    let mut h = Harness::new(n);
    h.hello(0x28, "ONEIP", "CM0001", DeviceFeature::VIDEO_ROUTING);
    h
}

/// Builds the `V2IP_AUDIO` command header: a `u16` sub-opcode, two pad bytes
/// and the target uid.
fn audio_cmd(sub: u16, target: DeviceUid) -> Vec<u8> {
    let mut p = Vec::with_capacity(20);
    p.extend_from_slice(&sub.to_le_bytes());
    p.extend_from_slice(&[0, 0]);
    p.extend_from_slice(target.as_bytes());
    p
}

/// Builds the endpoint/value pair an audio command carries after its header.
fn audio_param(endpoint: u16, value: u32) -> [u8; 8] {
    let e = endpoint.to_le_bytes();
    let v = value.to_le_bytes();
    [e[0], e[1], 0, 0, v[0], v[1], v[2], v[3]]
}

/// Builds a multiviewer command body: target uid, sub-opcode, seven pad bytes
/// and the parameters.
fn mv_cmd(target: DeviceUid, sub: u8, args: &[u8]) -> Vec<u8> {
    let mut p = Vec::with_capacity(24 + args.len());
    p.extend_from_slice(target.as_bytes());
    p.push(sub);
    p.extend_from_slice(&[0; 7]);
    p.extend_from_slice(args);
    p
}

/// Writes an address and port into a `v2ip_stream_addr` at `at`.
fn stream_addr(p: &mut [u8], at: usize, ip: &str, port: u16) {
    let addr: Ipv4Addr = ip.parse().expect("test address");
    p[at..at + 4].copy_from_slice(&addr.octets());
    p[at + 4..at + 6].copy_from_slice(&port.to_le_bytes());
}

// ---- routing ----

#[test]
fn a_set_route_addresses_its_bays_as_u16() {
    let mut h = command_device(40);

    // mbay_port_id is a u16, so both bays are two bytes and no_power_on lands
    // at 20. Reading them as bytes at 16 and 17 would put the sink's high byte
    // in the source.
    let mut p = vec![0u8; 21];
    p[0..12].copy_from_slice(b"P9SN00000001");
    p[16..18].copy_from_slice(&300u16.to_le_bytes()); // a sink bay above a byte
    p[18..20].copy_from_slice(&7u16.to_le_bytes());
    p[20] = 1;
    h.feed(op::MX_SET_ROUTE, &p);

    let request = h
        .events
        .iter()
        .find_map(|e| match e {
            Event::SetRouteRequested { request, .. } => Some(request.clone()),
            _ => None,
        })
        .expect("no route request");
    assert_eq!(request.serial, "P9SN00000001");
    assert_eq!(request.sink_bay, 300);
    assert_eq!(request.source_bay, 7);
    assert!(request.no_power_on);
    assert!(!request.audio_only);
}

#[test]
fn an_audio_set_route_has_no_power_on_byte() {
    let mut h = command_device(41);

    // AUDIO_SET_ROUTE addresses its target by serial like MX_SET_ROUTE, but its
    // struct stops after the two bays.
    let mut p = vec![0u8; 20];
    p[0..12].copy_from_slice(b"P9SN00000002");
    p[16..18].copy_from_slice(&4u16.to_le_bytes());
    p[18..20].copy_from_slice(&2u16.to_le_bytes());
    h.feed(op::AUDIO_SET_ROUTE, &p);

    let request = h
        .events
        .iter()
        .find_map(|e| match e {
            Event::SetRouteRequested { request, .. } => Some(request.clone()),
            _ => None,
        })
        .expect("no route request");
    assert!(request.audio_only);
    assert_eq!((request.sink_bay, request.source_bay), (4, 2));
    assert!(!request.no_power_on);
}

// ---- infrared ----

#[test]
fn an_ir_capture_aligns_its_timestamp() {
    let mut h = command_device(42);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            3,
            0,
            0,
            "Input 1",
            "Sky",
            BayStatus::NONE,
            BayFeatures::HDMI_IN,
        ),
    );

    // mxr_ir_data is not packed, so the u32 timestamp aligns to 4 and two
    // padding bytes follow the port.
    let mut p = poisoned(24 + 8);
    p[0..2].copy_from_slice(&3u16.to_le_bytes());
    p[4..8].copy_from_slice(&0xAABB_CCDDu32.to_le_bytes());
    p[8..12].copy_from_slice(&0x1122_3344u32.to_le_bytes());
    p[12..14].copy_from_slice(&2u16.to_le_bytes()); // timer resolution
    p[14..16].copy_from_slice(&38000u16.to_le_bytes()); // carrier frequency
                                                        // Four timings, two bytes each, which is the eight that follow.
    p[16..18].copy_from_slice(&4u16.to_le_bytes()); // timing count
    p[18..20].copy_from_slice(&0u16.to_le_bytes()); // repeat offset
    p[20] = 1; // status
    p[24..].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
    h.feed(op::RC_IR, &p);

    let capture = h
        .events
        .iter()
        .find_map(|e| match e {
            Event::IrCaptured { capture, .. } => Some(capture.clone()),
            _ => None,
        })
        .expect("no capture");
    assert_eq!(capture.port, 3);
    assert_eq!(capture.timestamp, 0xAABB_CCDD);
    assert_eq!(capture.last_change, 0x1122_3344);
    assert_eq!(capture.meta.frequency, 38000);
    assert_eq!(capture.meta.nb_timings, 4);
    assert_eq!(capture.meta.status, 1);
    assert_eq!(capture.timings, [1, 2, 3, 4, 5, 6, 7, 8]);
}

/// Both timing widths are read, and both reach a caller as the wider one.
///
/// The header counts timings rather than bytes, so what follows it is what says
/// which width arrived: the same count takes twice the room in the wider form.
/// A narrow list is widened rather than refused - the values are the device's
/// and only the encoding differs - so a caller gets one representation whatever
/// sent it. A frame carrying less than even the narrow form declares is
/// refused, and bytes behind a full list are not timings.
#[test]
fn an_ir_capture_reads_both_timing_widths() {
    let mut h = command_device(44);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            3,
            0,
            0,
            "Input 1",
            "Sky",
            BayStatus::NONE,
            BayFeatures::HDMI_IN,
        ),
    );
    let capture_of = |h: &Harness| {
        h.events.iter().find_map(|e| match e {
            Event::IrCaptured { capture, .. } => Some(capture.clone()),
            _ => None,
        })
    };
    let frame = |count: u16, tail: &[u8]| {
        let mut p = poisoned(24 + tail.len());
        p[0..2].copy_from_slice(&3u16.to_le_bytes());
        p[16..18].copy_from_slice(&count.to_le_bytes());
        p[24..].copy_from_slice(tail);
        p
    };

    // Four one-byte timings, which is what a sender predating the widening
    // appends. Each reaches the caller as the same value two bytes wide.
    h.feed(op::RC_IR, &frame(4, &[1, 2, 3, 4]));
    assert_eq!(
        capture_of(&h).expect("a narrow list was refused").timings,
        [1, 0, 2, 0, 3, 0, 4, 0],
        "a narrow list was not widened to the reported representation"
    );

    // The same count in the wider form is taken as it stands, and the eight
    // bytes behind the list are not timings.
    h.events.clear();
    h.feed(
        op::RC_IR,
        &frame(4, &[1, 0, 2, 0, 3, 0, 4, 0, 9, 9, 9, 9, 9, 9, 9, 9]),
    );
    assert_eq!(
        capture_of(&h).expect("a whole list was refused").timings,
        [1, 0, 2, 0, 3, 0, 4, 0],
        "bytes behind the list were read as timings"
    );

    // Less than even the narrow form declares is refused rather than truncated.
    h.events.clear();
    h.feed(op::RC_IR, &frame(4, &[1, 2, 3]));
    assert!(
        capture_of(&h).is_none(),
        "a list shorter than its own count was handed to a caller"
    );
}

/// A burst with no timings is not a capture.
///
/// The struct ends at 24 and a receiver measures one timing past it before it
/// reads a field, so a frame that stops at the struct is one nothing acted on
/// - and it carries no burst to hand a caller either.
#[test]
fn an_ir_frame_with_no_timings_is_not_a_capture() {
    let mut h = command_device(43);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            3,
            0,
            0,
            "Input 1",
            "Sky",
            BayStatus::NONE,
            BayFeatures::HDMI_IN,
        ),
    );

    let mut p = poisoned(24);
    p[0..2].copy_from_slice(&3u16.to_le_bytes());
    h.feed_proto(op::RC_IR, 0x19, &p);
    assert!(
        !h.saw(|e| matches!(e, Event::IrCaptured { .. })),
        "a frame that stops at the struct was reported as a burst"
    );
}

/// A blast request with no timings is not a request.
///
/// The addressed device measures the struct plus one timing before it looks at
/// anything else, so a request that stops at the struct asks it for nothing.
#[test]
fn an_ir_request_with_no_timings_is_not_a_request() {
    let mut h = command_device(44);
    let target = uid_n(45);

    let mut p = poisoned(36);
    p[0..16].copy_from_slice(target.as_bytes());
    h.feed(op::RC_IR_TX, &p);
    assert!(
        !h.saw(|e| matches!(e, Event::IrTransmitRequested { .. })),
        "a request that stops at the struct reached the caller"
    );
}

#[test]
fn ir_transmit_timings_start_at_the_struct_size() {
    let mut h = command_device(70);
    let target = uid_n(71);

    // mxr_tx_ir_data is unpacked and 4-aligned, so the firmware appends the
    // timings at sizeof = 36. Taking them from the end of the last field would
    // shift every u16 timing by two bytes.
    //
    // Poisoned so the padding at 18..20 and the struct tail at 33..36 are not
    // zero: a field read at the right offset but the wrong width shows here.
    let mut p = poisoned(36 + 6);
    p[0..16].copy_from_slice(target.as_bytes());
    p[16] = 1;
    p[17] = 2;
    p[20..24].copy_from_slice(&0xDEAD_BEEFu32.to_le_bytes());
    p[24..26].copy_from_slice(&0u16.to_le_bytes()); // meta.timer_resolution
    p[26..28].copy_from_slice(&38000u16.to_le_bytes()); // meta.frequency
    p[28..30].copy_from_slice(&3u16.to_le_bytes()); // meta.nb_timings
    p[30..32].copy_from_slice(&0u16.to_le_bytes()); // meta.repeat_offset
    p[32] = 0; // meta.status
    p[36..].copy_from_slice(&[1, 0, 2, 0, 3, 0]);
    h.feed(op::RC_IR_TX, &p);

    let request = h
        .events
        .iter()
        .find_map(|e| match e {
            Event::IrTransmitRequested { request, .. } => Some(request.clone()),
            _ => None,
        })
        .expect("no transmit request");
    assert_eq!(request.target, target);
    assert_eq!((request.local_mode, request.local_bay), (1, 2));
    assert_eq!(request.timestamp, 0xDEAD_BEEF);
    assert_eq!(request.meta.frequency, 38000);
    assert_eq!(request.meta.nb_timings, 3);
    assert_eq!(
        request.timings,
        [1, 0, 2, 0, 3, 0],
        "the timings start at the struct size, not at the end of the last field"
    );
}

// ---- EDID ----

#[test]
fn a_combined_edid_reply_carries_a_mode_per_record() {
    let mut h = command_device(44);

    // A combined reply is two 257-byte records, so the mode byte leads both
    // halves rather than one mode covering the pair.
    let mut p = vec![0u8; 2 * 257];
    p[0] = 0; // input
    p[1] = 0xAB;
    p[257] = 1; // output
    p[258] = 0xCD;
    h.feed(op::DEV_EDID, &p);

    let records: Vec<_> = h
        .events
        .iter()
        .filter_map(|e| match e {
            Event::EdidReceived { edid, .. } => Some(edid.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(records.len(), 2);
    assert!(!records[0].output);
    assert_eq!(records[0].data.len(), 256);
    assert_eq!(records[0].data[0], 0xAB);
    assert!(records[1].output);
    assert_eq!(records[1].data[0], 0xCD);
}

#[test]
fn an_edid_request_is_not_a_record() {
    let mut h = command_device(45);
    let target = uid_n(99);

    let mut p = target.as_bytes().to_vec();
    p.push(1);
    h.feed(op::DEV_EDID, &p);

    assert!(h.saw(
        |e| matches!(e, Event::EdidRequested { request, .. } if request.target == target && request.output)
    ));
    assert!(
        !h.saw(|e| matches!(e, Event::EdidReceived { .. })),
        "a 17-byte request also decoded as an EDID record"
    );
}

// ---- video wall ----

#[test]
fn a_video_wall_command_separates_a_clear_from_a_revert() {
    let mut h = command_device(46);
    let target = uid_n(77);

    let wall = |op: VideoWallOp, w: u16, h: u16| {
        // Poisoned, so the three pad bytes after the op byte are not zero.
        let mut p = poisoned(32);
        p[0..16].copy_from_slice(target.as_bytes());
        p[16..18].copy_from_slice(&1920u16.to_le_bytes());
        p[18..20].copy_from_slice(&0u16.to_le_bytes());
        p[20..22].copy_from_slice(&w.to_le_bytes());
        p[22..24].copy_from_slice(&h.to_le_bytes());
        p[24..26].copy_from_slice(&3840u16.to_le_bytes());
        p[26..28].copy_from_slice(&2160u16.to_le_bytes());
        p[28] = op.to_wire();
        p
    };
    let latest = |h: &Harness| -> VideoWallCommand {
        h.events
            .iter()
            .rev()
            .find_map(|e| match e {
                Event::VideoWallCommand { command, .. } => Some(*command),
                _ => None,
            })
            .expect("no wall command")
    };

    h.feed(op::V2IP_VIDEO_WALL, &wall(VideoWallOp::STORE, 1920, 1080));
    let got = latest(&h);
    assert_eq!(got.target, target);
    assert_eq!((got.pos_x, got.pos_y), (1920, 0));
    assert_eq!((got.width, got.height), (1920, 1080));
    assert_eq!((got.raster_w, got.raster_h), (3840, 2160));
    assert_eq!(got.op, VideoWallOp::STORE);
    assert!(got.has_window() && !got.is_cleared());

    // A zero width is the wire spelling of "clear the wall", not "unset".
    h.feed(op::V2IP_VIDEO_WALL, &wall(VideoWallOp::PREVIEW, 0, 0));
    assert!(latest(&h).is_cleared());

    // A revert zeroes the geometry and the receiver ignores it, so those zeros
    // are not a clear.
    h.feed(op::V2IP_VIDEO_WALL, &wall(VideoWallOp::REVERT, 0, 0));
    let got = latest(&h);
    assert!(!got.has_window());
    assert!(!got.is_cleared());
}

/// The length check is a floor, matching the device's.
///
/// A sink accepts a payload longer than the struct and ignores the tail, which
/// is the room the frame has to grow in. A decoder that demanded the exact
/// size would refuse traffic the sinks are already honouring, and would do it
/// on the wire rather than at a version boundary anyone could see coming.
#[test]
fn a_longer_video_wall_frame_is_read_and_its_tail_ignored() {
    let mut h = command_device(47);
    let target = uid_n(78);

    let mut p = poisoned(48);
    p[0..16].copy_from_slice(target.as_bytes());
    p[16..18].copy_from_slice(&64u16.to_le_bytes());
    p[18..20].copy_from_slice(&128u16.to_le_bytes());
    p[20..22].copy_from_slice(&1920u16.to_le_bytes());
    p[22..24].copy_from_slice(&1080u16.to_le_bytes());
    p[24..26].copy_from_slice(&3840u16.to_le_bytes());
    p[26..28].copy_from_slice(&2160u16.to_le_bytes());
    p[28] = VideoWallOp::STORE.to_wire();
    // Everything from 29 on stays poisoned: a field read past the struct picks
    // it up, and the assertions below are all inside the struct.
    h.feed(op::V2IP_VIDEO_WALL, &p);

    let got = h
        .events
        .iter()
        .rev()
        .find_map(|e| match e {
            Event::VideoWallCommand { command, .. } => Some(*command),
            _ => None,
        })
        .expect("a frame longer than the struct was dropped");
    assert_eq!(got.target, target);
    assert_eq!((got.pos_x, got.pos_y), (64, 128));
    assert_eq!((got.width, got.height), (1920, 1080));
    assert_eq!((got.raster_w, got.raster_h), (3840, 2160));
    assert_eq!(got.op, VideoWallOp::STORE);

    // The paired direction: one byte short of the struct is still dropped, so
    // the acceptance above is not one a decoder without any check would give.
    let before = h.events.len();
    h.feed(op::V2IP_VIDEO_WALL, &poisoned(31));
    assert_eq!(
        h.events.len(),
        before,
        "a payload shorter than the struct produced an event"
    );
}

// ---- remote control ----

#[test]
fn a_key_and_an_action_request_share_their_layout() {
    let mut h = command_device(47);
    let target = uid_n(88);

    let mk = |value: u16| {
        let mut p = vec![0u8; 20];
        p[0..16].copy_from_slice(target.as_bytes());
        p[16..18].copy_from_slice(&300u16.to_le_bytes());
        p[18..20].copy_from_slice(&value.to_le_bytes());
        p
    };
    h.feed(op::RC_TX_KEY, &mk(0x0041));
    h.feed(op::RC_TX_ACTION, &mk(RcAction::POWER_ON.to_wire()));

    assert!(h.saw(|e| matches!(e, Event::KeyTransmitRequested { request, .. }
        if request.target == target && request.local_bay == 300 && request.key == RcKey::from_wire(0x41))));
    assert!(h.saw(
        |e| matches!(e, Event::ActionTransmitRequested { request, .. }
        if request.local_bay == 300 && request.action == RcAction::POWER_ON)
    ));
}

#[test]
fn rc_settings_read_one_flag_byte() {
    let mut h = command_device(53);
    let sender = h.sender;

    let mut p = vec![0u8; 48];
    p[0..16].copy_from_slice(sender.as_bytes());
    p[16..20].copy_from_slice(&7u32.to_le_bytes()); // RC_TARGET_MX_REMOTE
    p[20..24].copy_from_slice(&[10, 8, 80, 30]);
    // CEC on, RC forwarded, status 3.
    p[24..26].copy_from_slice(&(1u16 | (1 << 2) | (3 << 4)).to_le_bytes());
    h.feed(op::RC_SETTINGS, &p);

    let s = h.device().rc_settings.clone().expect("no rc settings");
    assert_eq!(s.rc_target, 7);
    assert_eq!(s.ip, Some(Ipv4Addr::new(10, 8, 80, 30)));
    assert!(s.cec_enabled);
    assert!(!s.cec_auto_on);
    assert!(s.forward_rc);
    assert!(!s.forward_ir);
    assert_eq!(s.rc_status, 3);
}

/// A device reports its own remote-control settings and only management
/// changes them, so another peer's frame about it moves nothing.
#[test]
fn rc_settings_about_another_device_need_management_standing() {
    let mut h = command_device(54);
    let subject = h.sender;
    let settings_for = |forward_rc: bool| {
        let mut p = vec![0u8; 48];
        p[0..16].copy_from_slice(subject.as_bytes());
        p[16] = 1; // RC_TARGET_CEC
        p[24] = if forward_rc { 1 << 2 } else { 0 };
        p
    };
    h.feed(op::RC_SETTINGS, &settings_for(false));

    let peer = uid_n(79);
    h.feed_as(
        peer,
        op::SYS_HELLO,
        &hello_payload(
            0x28,
            "ONEIP",
            "CM0005",
            "4.8.0",
            DeviceFeature::VIDEO_ROUTING,
        ),
    );
    h.feed_as(peer, op::RC_SETTINGS, &settings_for(true));
    let s = h.state.device(subject).and_then(|d| d.rc_settings.clone());
    assert_eq!(
        s.map(|s| s.forward_rc),
        Some(false),
        "a peer without standing rewrote another device's settings"
    );

    let controller = uid_n(80);
    h.feed_as(
        controller,
        op::SYS_HELLO,
        &hello_payload(0x28, "Ctrl", "CTRL0004", "4.8.0", DeviceFeature::MANAGER),
    );
    h.feed_as(controller, op::RC_SETTINGS, &settings_for(true));
    let s = h.state.device(subject).and_then(|d| d.rc_settings.clone());
    assert_eq!(
        s.map(|s| s.forward_rc),
        Some(true),
        "management's write was dropped"
    );
}

#[test]
fn an_rc_status_name_starts_past_the_reserved_bits() {
    let mut h = command_device(72);
    let sender = h.sender;

    let mut p = vec![0u8; 48];
    p[0..16].copy_from_slice(sender.as_bytes());
    p[16..20].copy_from_slice(&7u32.to_le_bytes());
    p[20..24].copy_from_slice(&[10, 8, 80, 30]);
    p[24] = 1 | (1 << 3) | (5 << 4); // CEC on, IR forwarded, status 5
                                     // Byte 25 is dead space in the same bitfield container; a decoder reading
                                     // 24..26 as one little-endian u16 and shifting would pick this up.
    p[25] = 0xFF;
    p[28..37].copy_from_slice(b"Detecting");
    h.feed(op::RC_SETTINGS, &p);

    let s = h.device().rc_settings.clone().expect("no rc settings");
    assert!(s.cec_enabled);
    assert!(!s.cec_auto_on);
    assert!(!s.forward_rc);
    assert!(s.forward_ir);
    assert_eq!(s.rc_status, 5);
    assert_eq!(s.status_name, "Detecting");
}

/// Bytes 16..19 and 24..27 of three real `RC_SETTINGS` frames, from units all
/// configured for CEC.
///
/// The control method is one byte and the three that follow are padding the
/// firmware never clears, so they carry live stack content that differs per
/// frame. Reading the field as a u32 makes one unchanged setting decode as
/// three different values; the expectation below comes from the units' known
/// configuration, not from what the decoder produces.
const RC_SETTINGS_CAPTURES: [([u8; 4], [u8; 4]); 3] = [
    ([0x01, 0x73, 0x20, 0x28], [0x0f, 0x6f, 0x05, 0x28]),
    ([0x01, 0x6e, 0x1e, 0x28], [0x0f, 0x6f, 0x05, 0x28]),
    ([0x01, 0xb5, 0x1b, 0x28], [0x0f, 0x00, 0x00, 0x00]),
];

#[test]
fn rc_settings_padding_is_not_part_of_the_field() {
    for (index, (rc_target, flags)) in RC_SETTINGS_CAPTURES.iter().enumerate() {
        let mut h = command_device(90 + index as u8);
        let sender = h.sender;

        let mut p = vec![0u8; 48];
        p[0..16].copy_from_slice(sender.as_bytes());
        p[16..20].copy_from_slice(rc_target);
        p[20..24].copy_from_slice(&[10, 8, 80, 30]);
        p[24..28].copy_from_slice(flags);
        // status_name stays empty: firmware writes a NUL and returns for any
        // non-network target, so a CEC unit cannot legitimately report one.
        h.feed(op::RC_SETTINGS, &p);

        let s = h.device().rc_settings.clone().expect("no rc settings");
        // RC_TARGET_CEC, identical across all three despite the padding.
        assert_eq!(s.rc_target, 1, "capture {index} swallowed the padding");
        assert!(
            s.cec_enabled && s.cec_auto_on && s.forward_rc && s.forward_ir,
            "capture {index}: 0x0f should set all four flags"
        );
        assert_eq!(s.rc_status, 0, "capture {index}");
        assert_eq!(s.status_name, "", "capture {index}");
    }
}

// ---- device state ----

#[test]
fn setup_status_and_installer() {
    let mut h = command_device(48);

    h.feed(op::SETUP_STATUS, &[1]);
    assert_eq!(h.device().setup_done, Some(true));

    h.feed(op::SET_INSTALLER, &[0x34, 0x12]);
    assert_eq!(h.device().installer_id, Some(0x1234));
}

#[test]
fn a_filter_status_lists_every_uid_past_the_target() {
    let mut h = command_device(49);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            2,
            1,
            0,
            "Output 1",
            "TV",
            BayStatus::NONE,
            BayFeatures::HDMI_OUT,
        ),
    );

    let (a, b) = (uid_n(61), uid_n(62));
    let mut p = h.sender.as_bytes().to_vec();
    p.extend_from_slice(a.as_bytes());
    p.extend_from_slice(b.as_bytes());
    h.feed(op::BAY_FILTER_STATUS, &p);

    assert_eq!(h.bay(2).filtered, [a, b]);
}

#[test]
fn power_save_arrives_in_both_forms() {
    let mut h = command_device(50);

    h.feed(op::V2IP_POWER_SAVE, &[1]);
    assert!(
        h.saw(|e| matches!(e, Event::PowerSaveRequested { request, .. }
        if request.target.is_none() && request.enabled))
    );

    let target = uid_n(55);
    let mut p = target.as_bytes().to_vec();
    p.push(0);
    h.feed(op::V2IP_POWER_SAVE, &p);
    assert!(
        h.saw(|e| matches!(e, Event::PowerSaveRequested { request, .. }
        if request.target == Some(target) && !request.enabled))
    );
}

#[test]
fn a_factory_reset_arrives_in_three_forms() {
    let mut h = command_device(51);
    let latest = |h: &Harness| {
        h.events
            .iter()
            .rev()
            .find_map(|e| match e {
                Event::FactoryResetRequested { request, .. } => Some(*request),
                _ => None,
            })
            .expect("no reset request")
    };

    h.feed(op::SYS_FACTORY_RESET, &[0xFF]);
    let got = latest(&h);
    assert!(got.all);
    assert_eq!(got.target, None);

    let target = uid_n(56);
    h.feed(op::SYS_FACTORY_RESET, target.as_bytes());
    let got = latest(&h);
    assert!(!got.all);
    assert_eq!(got.target, Some(target));

    // Neither form: the request addresses only the sender.
    h.feed(op::SYS_FACTORY_RESET, &[]);
    let got = latest(&h);
    assert!(!got.all);
    assert_eq!(got.target, None);

    // A payload that reaches no form is not the empty one. Reading it as the
    // sender resetting itself would report a destructive request built from a
    // frame nothing understood, so it is dropped and the last request stands.
    let before = h.events.len();
    h.feed(op::SYS_FACTORY_RESET, &[0x01, 0x02, 0x03]);
    assert!(
        !h.events[before..]
            .iter()
            .any(|e| matches!(e, Event::FactoryResetRequested { .. })),
        "a payload matching no form was read as a reset of the sender"
    );
}

#[test]
fn a_payload_that_grew_at_the_back_is_still_read() {
    // A protocol update appends to an opcode's payload and leaves the fields
    // ahead of the addition where they were, which is the only way a newer
    // device stays readable by an older client. A handler that requires an
    // exact length reads such a frame as neither of the forms it knows, and
    // drops or misfiles the whole thing - fields it does understand included.
    // The symptom appears only once a device is upgraded, so it is asserted
    // here rather than left to the first field that gets added.
    let mut h = command_device(52);
    let target = uid_n(64);
    let grown = |base: &[u8]| {
        let mut p = base.to_vec();
        p.extend_from_slice(&[0x5A, 0x5B, 0x5C]);
        p
    };

    let mut record = vec![0u8; 257];
    record[0] = 1; // output
    record[1] = 0xAB;
    h.feed(op::DEV_EDID, &grown(&record));
    assert!(
        h.saw(|e| matches!(e, Event::EdidReceived { edid, .. }
        if edid.output && edid.data.len() == 256 && edid.data[0] == 0xAB)),
        "an EDID record with bytes appended was not read as a record"
    );

    let mut request = target.as_bytes().to_vec();
    request.push(1);
    h.feed(op::DEV_EDID, &grown(&request));
    assert!(
        h.saw(|e| matches!(e, Event::EdidRequested { request, .. }
        if request.target == target && request.output)),
        "an EDID request with bytes appended was not read as a request"
    );

    let mut power = target.as_bytes().to_vec();
    power.push(1);
    h.feed(op::V2IP_POWER_SAVE, &grown(&power));
    assert!(
        h.saw(|e| matches!(e, Event::PowerSaveRequested { request, .. }
        if request.target == Some(target) && request.enabled)),
        "an addressed power-save request with bytes appended lost its target"
    );

    h.feed(op::SYS_FACTORY_RESET, &grown(target.as_bytes()));
    assert!(
        h.saw(|e| matches!(e, Event::FactoryResetRequested { request, .. }
        if request.target == Some(target) && !request.all)),
        "a factory reset with bytes appended lost the device it names"
    );
}

#[test]
fn a_reply_holds_as_many_edid_records_as_it_is_long() {
    // The count is not enumerated: the output flag leads every record, so a
    // reply carrying a third is three records rather than an unknown length.
    let mut h = command_device(53);
    let mut p = vec![0u8; 3 * 257];
    for (i, mark) in [0xA1u8, 0xA2, 0xA3].iter().enumerate() {
        p[i * 257] = u8::from(i == 1); // only the middle record is an output
        p[i * 257 + 1] = *mark;
    }
    h.feed(op::DEV_EDID, &p);

    let records: Vec<_> = h
        .events
        .iter()
        .filter_map(|e| match e {
            Event::EdidReceived { edid, .. } => Some(edid.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(records.len(), 3, "a three-record reply was not read");
    assert_eq!(
        records.iter().map(|r| r.data[0]).collect::<Vec<_>>(),
        [0xA1, 0xA2, 0xA3]
    );
    assert_eq!(
        records.iter().map(|r| r.output).collect::<Vec<_>>(),
        [false, true, false],
        "the flag leading each record was not read per record"
    );
}

#[test]
fn a_filter_list_is_read_to_its_last_whole_uid() {
    let mut h = command_device(54);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            2,
            1,
            0,
            "Output 1",
            "TV",
            BayStatus::NONE,
            BayFeatures::HDMI_OUT,
        ),
    );

    let filtered = uid_n(65);
    let mut p = h.sender.as_bytes().to_vec();
    p.extend_from_slice(filtered.as_bytes());
    p.extend_from_slice(&[0x5A, 0x5B, 0x5C]);
    h.feed(op::BAY_FILTER_STATUS, &p);

    assert_eq!(
        h.bay(2).filtered,
        [filtered],
        "a trailing partial uid was read as a malformed frame rather than ignored"
    );
}

#[test]
fn a_bay_name_filling_its_field_keeps_every_character() {
    let mut h = command_device(52);
    let target = uid_n(57);

    let full = "0123456789ABCDEF"; // fills the field, so it carries no terminator
    let mut p = target.as_bytes().to_vec();
    p.extend_from_slice(&300u16.to_le_bytes());
    p.extend_from_slice(full.as_bytes());
    h.feed(op::CHANGE_BAY_NAME, &p);

    assert!(
        h.saw(|e| matches!(e, Event::BayNameChangeRequested { change, .. }
        if change.target == target && change.port == 300 && change.name == full))
    );
}

// ---- audio ----

#[test]
fn an_audio_select_input_names_its_sink_twice() {
    let mut h = command_device(60);
    let sender = h.sender;
    let source = uid_n(61);

    // The body names the sink again at 20 with the source at 36. Decoding
    // those the other way round swaps source and sink.
    let mut p = audio_cmd(3, sender);
    p.extend_from_slice(sender.as_bytes());
    p.extend_from_slice(source.as_bytes());
    p.extend_from_slice(&[7, 0, 9, 0]); // sink endpoint 7, source endpoint 9
    h.feed(op::V2IP_AUDIO, &p);

    let want = AudioChangeSource {
        source_uid: source,
        source_id: 9,
        target_uid: sender,
        target_id: 7,
    };
    assert!(h.saw(|e| matches!(e, Event::AudioSelectInput { change, .. } if *change == want)));
    assert_eq!(h.device().audio_select, Some(want));
}

#[test]
fn audio_endpoint_commands_carry_an_endpoint_and_a_value() {
    let mut h = command_device(64);
    let sender = h.sender;
    let mut send = |sub: u16, endpoint: u16, value: u32| {
        let mut p = audio_cmd(sub, sender);
        p.extend_from_slice(&audio_param(endpoint, value));
        h.feed(op::V2IP_AUDIO, &p);
    };
    send(1, 2, 1); // mute
    send(2, 3, 0); // trigger
    send(4, 4, 80); // volume

    assert!(h.saw(|e| matches!(
        e,
        Event::AudioEndpointMute {
            endpoint: 2,
            muted: true,
            ..
        }
    )));
    assert!(h.saw(|e| matches!(
        e,
        Event::AudioEndpointTrigger {
            endpoint: 3,
            active: false,
            ..
        }
    )));
    assert!(h.saw(|e| matches!(
        e,
        Event::AudioEndpointVolume {
            endpoint: 4,
            volume: 80,
            ..
        }
    )));
}

// ---- multiviewer ----

#[test]
fn every_multiviewer_sub_command_surfaces() {
    let mut h = command_device(74);
    let sender = h.sender;

    for sub in 0..16u8 {
        h.feed(op::V2IP_MULTIVIEWER, &mv_cmd(sender, sub, &[1, 2, 3]));
    }

    let seen: Vec<u8> = h
        .events
        .iter()
        .filter_map(|e| match e {
            Event::MultiviewerCommand { command, .. } => Some(command.op),
            _ => None,
        })
        .collect();
    assert_eq!(seen, (0..16u8).collect::<Vec<_>>());
    assert!(
        h.saw(|e| matches!(e, Event::MultiviewerCommand { command, .. }
        if *command == MultiviewerCommand { target: sender, op: 15, params: vec![1, 2, 3] }))
    );
}

#[test]
fn an_unnamed_enum_value_reaches_the_caller_as_itself() {
    let mut h = command_device(73);
    h.hello(
        0x28,
        "ONEIP-MV",
        "MV9",
        DeviceFeature::V2IP_SINK | DeviceFeature::MULTIVIEWER,
    );

    // The 192 bytes a status report carries; a shorter one is not decoded.
    let mut p = vec![0u8; 192];
    p[169] = 200; // a view mode far beyond anything named
    h.feed(op::V2IP_MULTIVIEWER, &p);
    let status = h.device().multiviewer.clone().expect("no multiviewer");
    assert_eq!(status.view_mode, MultiviewerViewMode::from_wire(200));

    // A firmware type must not read back as a known one either.
    let mut fw = vec![0u8; 12 + 8];
    fw[0] = 42;
    fw[12..17].copy_from_slice(b"9.9.9");
    h.feed(op::FIRMWARE_VERSION, &fw);
    assert!(h
        .device()
        .firmware
        .contains_key(&FirmwareType::from_wire(42)));
}

// ---- statistics ----

#[test]
fn the_stats_blocks_are_twenty_and_forty_four() {
    let mut h = command_device(80);

    // fpga_tx_stats and fpga_rx_stats carry their ALIGN(8) before the struct
    // keyword, where GCC ignores it, so the blocks are 20 and 44 rather than 24
    // and 48. The 128-byte total is stable by accident, so this pins the block
    // boundaries by reading a field from each rather than the total.
    let mut p = vec![0u8; 128];
    p[0..4].copy_from_slice(&11u32.to_le_bytes()); // tx totals, video
    p[20..24].copy_from_slice(&22u32.to_le_bytes()); // tx per minute, video
    p[40..44].copy_from_slice(&33u32.to_le_bytes()); // rx totals, video total
    p[76..80].copy_from_slice(&44u32.to_le_bytes()); // rx totals, anc seq errors
    p[80..84].copy_from_slice(&u32::from(V2ipDecoderState::STARTING.to_wire()).to_le_bytes());
    p[84..88].copy_from_slice(&55u32.to_le_bytes()); // rx per minute, video total
    p[124..128].copy_from_slice(&u32::from(V2ipDecoderState::BAD.to_wire()).to_le_bytes());
    h.feed(op::V2IP_STATS, &p);

    let stats = h.device().v2ip_stats.expect("no stats");
    assert_eq!(stats.tx.video, 11);
    assert_eq!(stats.tx_per_minute.video, 22);
    assert_eq!(stats.rx.video_total, 33);
    assert_eq!(stats.rx.anc_seq_errors, 44);
    assert_eq!(stats.rx_per_minute.video_total, 55);
    assert_eq!(stats.rx.decoder_state, V2ipDecoderState::STARTING);
    assert_eq!(stats.rx_per_minute.decoder_state, V2ipDecoderState::BAD);
}

#[test]
fn a_stats_request_is_not_a_report() {
    // The opcode carries a request as well as a report, and the request is far
    // short of the counters. The length test that separates them also guards
    // the slicing that reads the counter blocks, so failing it is not a missed
    // reading but a panic on a frame a device legitimately sends - and this
    // client would take itself down decoding traffic it asked for.
    let mut h = command_device(89);
    let mut request = uid_n(70).as_bytes().to_vec();
    request.push(1); // enable

    h.feed(op::V2IP_STATS, &request);
    assert!(
        h.device().v2ip_stats.is_none(),
        "a request was read as a report"
    );

    // A payload one byte short of the counters is the other side of the same
    // gate: nothing about it says request, and it must still not be sliced.
    h.feed(op::V2IP_STATS, &[0u8; 127]);
    assert!(
        h.device().v2ip_stats.is_none(),
        "a truncated report was read as a whole one"
    );
}

#[test]
fn a_starting_decoder_is_not_a_verdict() {
    assert_eq!(V2ipDecoderState::STARTING.to_wire(), 3);
    for state in [V2ipDecoderState::UNKNOWN, V2ipDecoderState::STARTING] {
        assert!(!state.is_settled(), "{state} should not be a verdict");
    }
    for state in [V2ipDecoderState::HEALTHY, V2ipDecoderState::BAD] {
        assert!(state.is_settled(), "{state} should be a verdict");
    }
    assert_eq!(
        V2ipDecoderState::STARTING.to_string(),
        "Starting",
        "conflating a starting decoder with an unknown one loses the distinction"
    );
    assert_eq!(V2ipDecoderState::from_wire(9).to_string(), "state 9");
}

/// A statistics report with the decoder block appended, poisoned everywhere a
/// caller then writes nothing.
///
/// The counter blocks in front of it are left poisoned: the block is read from
/// the payload length rather than from anything in them, and a decode that
/// reached into them would read a number rather than a zero.
fn stats_with_decoder(valid: u8) -> Vec<u8> {
    let mut p = poisoned(152);
    p[128] = valid;
    p[129] = V2ipDecoderReason::FORMAT_MISMATCH.to_wire();
    p[130] = 0; // blocking
    p[131] = 0x77; // reserved, and never a colour depth
    p[132..134].copy_from_slice(&3840u16.to_le_bytes());
    p[134..136].copy_from_slice(&2160u16.to_le_bytes());
    p[136..138].copy_from_slice(&V2ipDecoderFormat::YCBCR_422.to_wire().to_le_bytes());
    p[138..140].copy_from_slice(&600u16.to_le_bytes());
    // Bit 20 is a cause this build does not name, and it is what makes the
    // word's width readable: every cause it does name fits in the low half.
    p[140..144].copy_from_slice(&((1u32 << 4) | (1u32 << 8) | (1u32 << 20)).to_le_bytes());
    p[144..148].copy_from_slice(&100_009u32.to_le_bytes());
    // The block's own tail padding, 20 bytes of fields rounded to 24. A device
    // sends it as zero, having cleared the payload buffer first, so this is
    // poison a parser must ignore rather than anything a sender puts there.
    p[148..152].copy_from_slice(&0xDEADBEEFu32.to_le_bytes());
    p
}

#[test]
fn an_idle_sink_keeps_every_cause_beneath_idle() {
    // A switched-off sink reports idle, and the word can carry causes beneath
    // it: what the decoder still observes is reported whether or not the sink
    // is on. Those bits are a reading, not a fault to escalate - idle outranks
    // them, and a caller testing a fault mask over the whole word would call a
    // sink somebody deliberately switched off broken. What this pins is that
    // the library reports the word as it arrived: suppressing the lower bits
    // here would answer that question for every caller, and answer it by
    // throwing away what the decoder saw.
    //
    // Which causes accompany idle is the sender's business and will change, so
    // this asserts the bits the fixture wrote rather than a word a device is
    // expected to produce.
    let mut h = command_device(88);
    let mut p = stats_with_decoder(1);
    p[129] = V2ipDecoderReason::IDLE.to_wire();
    p[140..144].copy_from_slice(
        &((1u32 << V2ipDecoderReason::NO_PACKETS.to_wire())
            | (1u32 << V2ipDecoderReason::NO_FORMAT.to_wire())
            | (1u32 << V2ipDecoderReason::IDLE.to_wire()))
        .to_le_bytes(),
    );
    h.feed(op::V2IP_STATS, &p);

    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no decoder reading");
    assert_eq!(d.reason, V2ipDecoderReason::IDLE, "idle did not win");
    for cause in [
        V2ipDecoderReason::NO_PACKETS,
        V2ipDecoderReason::NO_FORMAT,
        V2ipDecoderReason::IDLE,
    ] {
        assert!(
            d.has_cause(cause),
            "{cause} was dropped from a word that carried it"
        );
    }
    assert!(
        !d.has_cause(V2ipDecoderReason::PACKETS_DEGRADED),
        "a cause the word does not carry was reported"
    );
}

#[test]
fn the_decoder_block_is_read_at_its_own_offsets() {
    let mut h = command_device(81);
    let mut p = stats_with_decoder(1);
    // Every field distinct, and the counters in front of the block set so that
    // a decoder reading the block at the wrong base is visible as a counter
    // that moved.
    p[0..4].copy_from_slice(&11u32.to_le_bytes()); // tx totals, video
    p[40..44].copy_from_slice(&33u32.to_le_bytes()); // rx totals, video total
    p[80] = V2ipDecoderState::HEALTHY.to_wire();
    h.feed(op::V2IP_STATS, &p);

    let stats = h.device().v2ip_stats.expect("no stats");
    assert_eq!((stats.tx.video, stats.rx.video_total), (11, 33));
    assert_eq!(stats.rx.decoder_state, V2ipDecoderState::HEALTHY);

    let d = stats
        .decoder
        .reading()
        .expect("a valid decoder block read as no reading");
    assert_eq!(d.reason, V2ipDecoderReason::FORMAT_MISMATCH);
    assert!(
        !d.blocking,
        "the reserved byte beside it is set, and it is not the watchdog flag"
    );
    assert_eq!((d.width, d.height), (3840, 2160));
    assert_eq!(d.format, V2ipDecoderFormat::YCBCR_422);
    assert_eq!(d.updates, 600);
    assert_eq!(d.flags, (1u32 << 4) | (1u32 << 8) | (1u32 << 20));
    assert_eq!(d.blocked_count, 100_009);
    assert!(d.has_geometry());

    // The other direction, so that the flag above is read rather than always
    // false.
    p[130] = 1;
    h.feed(op::V2IP_STATS, &p);
    assert!(
        h.device()
            .v2ip_stats
            .expect("no stats")
            .decoder
            .reading()
            .expect("no reading")
            .blocking
    );
}

#[test]
fn a_report_that_stops_after_the_counters_carries_no_decoder_block() {
    let mut h = command_device(82);

    // What a sender predating the block sends. The bytes that would hold it are
    // absent rather than zero, so nothing here is a reading.
    let p = poisoned(128);
    h.feed(op::V2IP_STATS, &p);
    assert_eq!(
        h.device().v2ip_stats.expect("no stats").decoder,
        V2ipDecoderDetail::Absent
    );

    // And a longer report than this build knows still yields the block, since
    // a version adds to the tail.
    let mut long = stats_with_decoder(1);
    long.extend_from_slice(&poisoned(16));
    h.feed(op::V2IP_STATS, &long);
    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("a tail this build does not know cost it the block it does");
    assert_eq!((d.width, d.height), (3840, 2160));
}

#[test]
fn a_decoder_that_has_never_answered_offers_no_reading() {
    let mut h = command_device(83);

    // Everything behind `valid` still carries what a real reading would, which
    // is what a reader keying on any of it would report as a 4K picture.
    let p = stats_with_decoder(0);
    h.feed(op::V2IP_STATS, &p);
    assert_eq!(
        h.device().v2ip_stats.expect("no stats").decoder,
        V2ipDecoderDetail::NeverAnswered
    );
}

#[test]
fn geometry_says_there_is_no_signal_and_format_never_does() {
    let mut h = command_device(84);

    // A sink with nothing arriving: zero geometry beside a format of zero,
    // which is RGB and is exactly what a real RGB source reads as.
    let mut p = stats_with_decoder(1);
    p[129] = V2ipDecoderReason::NO_PACKETS.to_wire();
    p[132..136].copy_from_slice(&[0; 4]);
    p[136..138].copy_from_slice(&V2ipDecoderFormat::RGB.to_wire().to_le_bytes());
    h.feed(op::V2IP_STATS, &p);

    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("a sink with no stream reports, and this dropped the reading");
    assert_eq!(d.reason, V2ipDecoderReason::NO_PACKETS);
    assert_eq!(d.format, V2ipDecoderFormat::RGB);
    assert!(
        !d.has_geometry(),
        "nothing was recovered, and only the geometry says so"
    );

    // The other direction: a working stream carrying that same format. Both
    // halves pin the format to RGB rather than to each other, so the pair keeps
    // testing what it says it does even if one half is edited later. The reason
    // moves with the geometry because the wire ties them - an idle sink reports
    // no geometry - and the format is what stays put across both.
    let mut p = stats_with_decoder(1);
    p[136..138].copy_from_slice(&V2ipDecoderFormat::RGB.to_wire().to_le_bytes());
    h.feed(op::V2IP_STATS, &p);
    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no reading");
    assert_eq!(d.format, V2ipDecoderFormat::RGB);
    assert!(
        d.has_geometry(),
        "a working RGB stream read as no signal, which is what format 0 invites"
    );
}

#[test]
fn an_unnamed_format_is_not_an_unknown_colour_space() {
    let mut h = command_device(85);
    let mut p = stats_with_decoder(1);
    p[136..138].copy_from_slice(&255u16.to_le_bytes());
    p[129] = 200; // a cause no build of this library names
    h.feed(op::V2IP_STATS, &p);

    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no reading");
    assert_eq!(d.format, V2ipDecoderFormat::UNNAMED);
    assert_eq!(d.format.to_wire(), 255);
    assert_ne!(
        d.format.to_wire(),
        0xF,
        "the decoder's unnamed format is not a signal report's unknown colour space"
    );
    assert_eq!(d.reason, V2ipDecoderReason::from_wire(200));
    assert_eq!(d.reason.to_string(), "reason 200");

    // A format wider than a byte, which every value named here is not. Firmware
    // adds formats, and the field is two bytes whether or not one has used them.
    let mut p = stats_with_decoder(1);
    p[136..138].copy_from_slice(&0x0102u16.to_le_bytes());
    h.feed(op::V2IP_STATS, &p);
    assert_eq!(
        h.device()
            .v2ip_stats
            .expect("no stats")
            .decoder
            .reading()
            .expect("no reading")
            .format,
        V2ipDecoderFormat::from_wire(0x0102)
    );
}

#[test]
fn the_flags_word_names_every_cause_but_never_the_first() {
    let mut h = command_device(86);
    let mut p = stats_with_decoder(1);
    p[140..144].copy_from_slice(
        &((1u32 << V2ipDecoderReason::PTP_UNLOCKED.to_wire())
            | (1u32 << V2ipDecoderReason::DECODER_BLOCKED.to_wire()))
        .to_le_bytes(),
    );
    h.feed(op::V2IP_STATS, &p);

    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no reading");
    assert!(d.has_cause(V2ipDecoderReason::PTP_UNLOCKED));
    assert!(d.has_cause(V2ipDecoderReason::DECODER_BLOCKED));
    assert!(!d.has_cause(V2ipDecoderReason::NO_PACKETS));
    assert!(
        !d.has_cause(V2ipDecoderReason::OK),
        "bit 0 is unused, so ok is never among the causes"
    );
    assert!(
        !d.has_cause(V2ipDecoderReason::from_wire(200)),
        "a cause past the word's width is not in it"
    );
}

#[test]
fn an_idle_sink_reports_whatever_geometry_it_still_detects() {
    // Geometry is read before any cause is decided, so it answers what the
    // decoder currently detects and never whether the sink is on. A parser
    // that zeroed geometry under idle - or that inferred idle from a zero one
    // - would be reading a rank order into a field that has none, and both
    // directions are wrong. A doc comment saying so has no failing state,
    // which is why this is a test: the claim it defends was itself a
    // correction, and nothing else in the suite contradicts a parser that
    // reintroduces it.
    let mut h = command_device(91);
    let mut p = stats_with_decoder(1);
    p[129] = V2ipDecoderReason::IDLE.to_wire();
    p[140..144].copy_from_slice(&(1u32 << V2ipDecoderReason::IDLE.to_wire()).to_le_bytes());
    h.feed(op::V2IP_STATS, &p);

    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no decoder reading");
    assert_eq!(d.reason, V2ipDecoderReason::IDLE);
    assert_eq!(
        (d.width, d.height),
        (3840, 2160),
        "a switched-off sink had the geometry it still detects taken away"
    );
    assert!(
        d.has_geometry(),
        "idle was read as an answer about signal rather than about the sink"
    );

    // And the other direction: no geometry does not make a sink idle.
    let mut dark = stats_with_decoder(1);
    dark[129] = V2ipDecoderReason::NO_PACKETS.to_wire();
    dark[132..136].copy_from_slice(&[0, 0, 0, 0]);
    h.feed(op::V2IP_STATS, &dark);
    let d = h
        .device()
        .v2ip_stats
        .expect("no stats")
        .decoder
        .reading()
        .expect("no decoder reading");
    assert!(!d.has_geometry());
    assert_eq!(
        d.reason,
        V2ipDecoderReason::NO_PACKETS,
        "a dark decoder was reported as a switched-off sink"
    );
}

#[test]
fn a_video_wall_command_is_read_at_any_stamp() {
    // Deliberately no version floor. The module that owns this opcode never
    // reads the stamp - its gates are the target uid and the length - and its
    // answer to a MatrixOS too old to carry the opcode is to fail registration
    // at load, not to check a version per frame. A floor here would rest on
    // nothing that module could corroborate, and it fails in the direction that
    // costs: too low is free, too high drops every frame from a sender nobody
    // is testing against.
    let mut h = command_device(92);
    let mut p = poisoned(32);
    p[0..16].copy_from_slice(uid_n(92).as_bytes());

    for stamp in [0x00, 0x27, 0x28] {
        h.events.clear();
        h.feed_proto(op::V2IP_VIDEO_WALL, stamp, &p);
        assert!(
            h.saw(|e| matches!(e, Event::VideoWallCommand { .. })),
            "a wall command stamped {stamp:#04x} was dropped"
        );
    }
}

/// The decoder block is found by length, at whatever stamp a sender uses.
///
/// It was appended behind the counters, so every offset ahead of it is where it
/// has always been and a sender that predates it stops at the counters. Gating
/// it on a version drops the block from every sender the moment that version is
/// not the one being stamped - which is exactly what happened here: this client
/// floored on a row that was later reverted, and no sender will carry it again.
#[test]
fn a_decoder_block_is_found_by_length_at_any_stamp() {
    for stamp in [0x01, 0x13, 0x28, PROTOCOL_VERSION, PROTOCOL_VERSION + 1] {
        let mut h = command_device(90);
        h.feed_proto(op::V2IP_STATS, stamp, &stats_with_decoder(1));

        let stats = h.device().v2ip_stats.expect("the report was lost");
        assert!(
            stats.decoder.reading().is_some(),
            "the block was dropped at stamp {stamp:#06x}"
        );
    }
}

#[test]
fn a_report_stamped_above_this_clients_own_version_is_still_read() {
    let mut h = command_device(87);
    let p = stats_with_decoder(1);
    h.feed_proto(op::V2IP_STATS, PROTOCOL_VERSION + 1, &p);

    // The receive path takes a frame's stamp and discards it. A ceiling here
    // would drop a newer device's report whole - the counters that predate the
    // block with it - and the symptom appears only once a device is upgraded,
    // by which time nothing points at the client. The asymmetry with transmit
    // is deliberate: a frame is stamped at its opcode's own version because the
    // device has a ceiling, which is not a reason to grow one here.
    let stats = h
        .device()
        .v2ip_stats
        .expect("a stamp above this client's version cost it the whole report");
    assert_eq!(stats.tx.video, u32::from_le_bytes([0xA5, 0xA4, 0xA7, 0xA6]));
    assert!(
        stats.decoder.reading().is_some(),
        "the counters survived the stamp and the block did not"
    );
}

/// The value this fixture writes at payload offset `off`.
///
/// Distinct per offset, so a field read four bytes out returns a wrong number
/// rather than a neighbour holding the same one. Above `0xFFFF`, so a four-byte
/// read narrowed to two returns a wrong number as well. Those are separate
/// failure modes over one fixture, and small distinct values pin only the
/// first: every counter here fits four bytes, so a narrowed read of a small one
/// returns the same answer.
fn at(off: u32) -> u32 {
    0x0037_0000 + off
}

#[test]
fn every_counter_is_read_at_its_own_offset() {
    let mut h = command_device(88);

    // All four counter blocks at once. Asserting a field against the same
    // field of another block cannot catch a shift - two reads off one wrong
    // offset agree with each other - so every counter is checked against the
    // absolute value its own offset carries.
    let mut p = poisoned(152);
    for off in (0..128).step_by(4) {
        assert!(
            at(off as u32) > u32::from(u16::MAX),
            "a counter that fits in two bytes cannot catch a narrowed read"
        );
        p[off..off + 4].copy_from_slice(&at(off as u32).to_le_bytes());
    }
    p[80] = V2ipDecoderState::HEALTHY.to_wire();
    p[124] = V2ipDecoderState::BAD.to_wire();
    p[128] = 0; // the decoder block is not what this test is about
    h.feed(op::V2IP_STATS, &p);
    let s = h.device().v2ip_stats.expect("no stats");

    assert_eq!(
        (
            s.tx.video,
            s.tx.audio,
            s.tx.anc,
            s.tx.stream_down,
            s.tx.overflow
        ),
        (at(0), at(4), at(8), at(12), at(16))
    );
    assert_eq!(
        (
            s.tx_per_minute.video,
            s.tx_per_minute.audio,
            s.tx_per_minute.anc,
            s.tx_per_minute.stream_down,
            s.tx_per_minute.overflow
        ),
        (at(20), at(24), at(28), at(32), at(36))
    );
    for (block, base, state) in [
        (s.rx, 40, V2ipDecoderState::HEALTHY),
        (s.rx_per_minute, 84, V2ipDecoderState::BAD),
    ] {
        assert_eq!(
            (
                block.video_total,
                block.video_dropped,
                block.video_seq_errors,
                block.wdt_timeout,
                block.audio_total
            ),
            (
                at(base),
                at(base + 4),
                at(base + 8),
                at(base + 12),
                at(base + 16)
            ),
            "receive block at {base}"
        );
        assert_eq!(
            (
                block.audio_dropped,
                block.audio_seq_errors,
                block.anc_total,
                block.anc_dropped,
                block.anc_seq_errors
            ),
            (
                at(base + 20),
                at(base + 24),
                at(base + 28),
                at(base + 32),
                at(base + 36)
            ),
            "receive block at {base}"
        );
        assert_eq!(block.decoder_state, state, "receive block at {base}");
    }
}

#[test]
fn half_a_geometry_is_not_a_geometry() {
    let mut h = command_device(89);

    // One dimension zero is the only shape that separates "both were
    // recovered" from "either was", and no reading a sink sends has it: a
    // decoder that recovered a width recovered a height. It is here because
    // the two readings differ nowhere else.
    for (width, height) in [(0u16, 2160u16), (3840, 0)] {
        let mut p = stats_with_decoder(1);
        p[132..134].copy_from_slice(&width.to_le_bytes());
        p[134..136].copy_from_slice(&height.to_le_bytes());
        h.feed(op::V2IP_STATS, &p);
        let d = h
            .device()
            .v2ip_stats
            .expect("no stats")
            .decoder
            .reading()
            .expect("no reading");
        assert!(
            !d.has_geometry(),
            "{width}x{height} is half a geometry and was read as a whole one"
        );
    }
}

#[test]
fn the_primary_cause_is_not_derivable_from_the_flags_word() {
    let mut h = command_device(90);

    // `reason` cannot be computed from `flags`: it is the sender's fixed
    // priority order, which the numbering does not express. In the first
    // reading bit 1 is set and bit 7 is the reason; in the second bit 1 is the
    // reason while bit 3 is also set. So it is neither the lowest set bit nor
    // the highest, and a caller asking "is this cause present" has to read the
    // word rather than compare the byte.
    //
    // The first two are a teardown reported from a device - the switch, then
    // the silence after it - relayed here rather than captured, so they are
    // evidence of what a sink sends and not a frame this crate has seen. The
    // third is composed from the priority order rather than observed at all.
    let readings = [
        (
            V2ipDecoderReason::SWITCH_PENDING,
            0b1000_1010u32,
            [
                V2ipDecoderReason::NO_PACKETS,
                V2ipDecoderReason::NO_FORMAT,
                V2ipDecoderReason::SWITCH_PENDING,
            ],
        ),
        (
            V2ipDecoderReason::NO_PACKETS,
            0b0000_1010u32,
            [
                V2ipDecoderReason::NO_PACKETS,
                V2ipDecoderReason::NO_FORMAT,
                V2ipDecoderReason::NO_PACKETS,
            ],
        ),
        // The sharper case, and a standing one rather than a moment: the
        // transmitter bridge sits below every input-side cause, so a pipeline
        // rebuilding in a loop always names an input cause and carries bit 9
        // here alone. A caller reading the byte never sees the loop at all.
        (
            V2ipDecoderReason::NO_PACKETS,
            0b0010_0000_0010u32,
            [
                V2ipDecoderReason::NO_PACKETS,
                V2ipDecoderReason::TX_BRIDGE_UNLOCKED,
                V2ipDecoderReason::TX_BRIDGE_UNLOCKED,
            ],
        ),
    ];

    // The set has to contradict both derivations, or a parser implementing one
    // of them passes on the readings that happen not to catch it. Losing the
    // first reading leaves the other two agreeing with a lowest-set-bit answer,
    // so this guards the fixtures rather than the parser: it fires when the set
    // degrades, not only when the decode does.
    let bit_of = |r: V2ipDecoderReason| u32::from(r.to_wire());
    assert!(
        readings
            .iter()
            .any(|(r, flags, _)| bit_of(*r) != flags.trailing_zeros()),
        "no reading here contradicts reading the primary cause as the lowest set bit"
    );
    assert!(
        readings
            .iter()
            .any(|(r, flags, _)| bit_of(*r) != u32::BITS - 1 - flags.leading_zeros()),
        "no reading here contradicts reading the primary cause as the highest set bit"
    );

    for (reason, flags, present) in readings {
        let mut p = stats_with_decoder(1);
        p[129] = reason.to_wire();
        p[140..144].copy_from_slice(&flags.to_le_bytes());
        h.feed(op::V2IP_STATS, &p);
        let d = h
            .device()
            .v2ip_stats
            .expect("no stats")
            .decoder
            .reading()
            .expect("no reading");
        assert_eq!(d.reason, reason);
        for cause in present {
            assert!(
                d.has_cause(cause),
                "{cause} is set in {flags:#b} and unread"
            );
        }
        assert!(
            !d.has_cause(V2ipDecoderReason::DECODER_BLOCKED),
            "a cause absent from {flags:#b} was reported as applying"
        );
        assert!(
            !d.has_cause(V2ipDecoderReason::OK),
            "bit 0 is cleared by the sender, so ok is never a cause"
        );
    }
}

// ---- V2IP stream configuration ----

#[test]
fn a_manual_source_switch_and_a_config_sink_block_decode_alike() {
    let mut h = command_device(95);
    h.feed(
        op::SYS_BAY_CONFIG,
        &bay_config_rec(
            1,
            1,
            0,
            "Output 1",
            "TV",
            BayStatus::NONE,
            BayFeatures::V2IP_SINK_LOCAL,
        ),
    );

    // A manual switch: the uid, then video, audio and ancillary at 16, 24 and
    // 32, with an optional audio format at 40.
    let mut p = vec![0u8; 48];
    p[0..16].copy_from_slice(h.sender.as_bytes());
    stream_addr(&mut p, 16, "239.1.1.1", V2IP_PORT_VIDEO);
    stream_addr(&mut p, 24, "239.1.1.2", V2IP_PORT_AUDIO);
    stream_addr(&mut p, 32, "239.1.1.3", V2IP_PORT_ANC);
    p[40..44].copy_from_slice(&96000u32.to_le_bytes());
    p[44] = 6;
    h.feed(op::V2IP_MANUAL_SRC_SWITCH, &p);

    let sink = h.device().v2ip_sink.expect("no sink");
    assert_eq!(sink.addresses.video.ip, Ipv4Addr::new(239, 1, 1, 1));
    assert_eq!(sink.addresses.video.port, V2IP_PORT_VIDEO);
    assert_eq!(sink.addresses.audio.ip, Ipv4Addr::new(239, 1, 1, 2));
    assert_eq!(sink.addresses.anc.ip, Ipv4Addr::new(239, 1, 1, 3));
    let fmt = sink.audio_fmt.expect("no audio format");
    assert_eq!((fmt.sample_rate, fmt.channels), (96000, 6));

    // The same block appended to a device config, at 88 with its format at 112.
    let mut c = vec![0u8; 120];
    c[..88].copy_from_slice(&Cfg::addresses(h.sender, "239.2.2.2").bytes());
    stream_addr(&mut c, 88, "239.3.3.1", V2IP_PORT_VIDEO);
    stream_addr(&mut c, 96, "239.3.3.2", V2IP_PORT_AUDIO);
    stream_addr(&mut c, 104, "239.3.3.3", V2IP_PORT_ANC);
    c[112..116].copy_from_slice(&44100u32.to_le_bytes());
    c[116] = 2;
    // A 120-byte configuration is the layout from before the codec word, so it
    // only ever arrives from a sender stamping below the version that added it.
    h.feed_proto(op::V2IP_DEVICE_CFG, DEVICE_CFG_CAPTURE_PROTOCOL, &c);

    let sink = h.device().v2ip_sink.expect("no sink");
    assert_eq!(sink.addresses.video.ip, Ipv4Addr::new(239, 3, 3, 1));
    assert_eq!(sink.addresses.anc.ip, Ipv4Addr::new(239, 3, 3, 3));
    let fmt = sink.audio_fmt.expect("no audio format");
    assert_eq!((fmt.sample_rate, fmt.channels), (44100, 2));
}

#[test]
fn an_options_write_caches_no_noise_bits() {
    let mut h = command_device(96);
    let sender = h.sender;

    // Firmware without DeviceFeature::CONFIG_INITIALISED builds this frame from
    // an uninitialised stack local and ORs its scaling flags onto whatever was
    // there, so bits 2..6 arrive as noise. Only bit 7 carries meaning.
    let mut base = Cfg::addresses(sender, "239.1.2.3");
    base.mode = 16;
    base.refresh = 60;
    base.flags = SCALING_FLAG_MODE_VALID | SCALING_FLAG_OPTIONS_VALID | SCALING_FLAG_AUTO_SCALING;
    h.feed(op::V2IP_DEVICE_CFG, &base.bytes());

    // An options-only write carrying garbage in the undefined bits, with
    // auto-scaling genuinely off.
    let noisy = Cfg {
        uid: sender,
        flags: SCALING_FLAG_OPTIONS_VALID | 0x7C,
        ..Cfg::default()
    };
    h.feed(op::V2IP_DEVICE_CFG, &noisy.bytes());

    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_eq!(scaling.flags & SCALING_FLAG_AUTO_SCALING, 0);
    assert_eq!(
        scaling.flags & !(SCALING_FLAG_MODE_VALID | SCALING_FLAG_OPTIONS_VALID),
        0,
        "undefined flag bits survived a merge: {:#04x}",
        scaling.flags
    );
    assert_eq!(scaling.mode.svd(), 16);
    assert_eq!(scaling.refresh, 60);

    // A genuine auto-scaling bit still arrives beside the noise.
    let on = Cfg {
        uid: sender,
        flags: SCALING_FLAG_OPTIONS_VALID | SCALING_FLAG_AUTO_SCALING | 0x34,
        ..Cfg::default()
    };
    h.feed(op::V2IP_DEVICE_CFG, &on.bytes());
    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_ne!(scaling.flags & SCALING_FLAG_AUTO_SCALING, 0);
}

/// A real `V2IP_DEVICE_CFG`, captured off a live mesh.
///
/// The expected values below come from the sending unit's own configuration
/// and from firmware behaviour, not from what this decoder produces.
#[rustfmt::skip]
const DEVICE_CFG_CAPTURE: [u8; 120] = [
    0x27, 0x40, 0x01, 0x04, 0x85, 0xac, 0xb7, 0xaa, 0x3e, 0x7d, 0x2c, 0x67, 0xc6, 0x07, 0x00, 0xf5,
    0xea, 0xda, 0x44, 0xf4, 0x64, 0xc3, 0x00, 0x00, // source.video 234.218.68.244:50020
    0xea, 0xda, 0x44, 0xf5, 0x66, 0xc3, 0x00, 0x00, // source.audio 234.218.68.245:50022
    0xea, 0xda, 0x44, 0xf4, 0x65, 0xc3, 0x00, 0x00, // source.anc   234.218.68.244:50021
    0x5a, 0x90, 0x90, 0x90, 0x00, 0x00, 0x00, 0x00, // tx_rate 90, dscp SET|16 on all three
    0xea, 0xda, 0x44, 0xf6, 0x67, 0xc3, 0x00, 0x00, // audio_return 234.218.68.246:50023
    0x13, 0x20, 0x32, 0x00, 0xdf, 0x1b, 0x00, 0x10, // scaling: svd 19, 8bpp, 50Hz, flags 0xdf
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,             // tiling, uid zero: not carried
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0xea, 0xda, 0x44, 0xf4, 0x64, 0xc3, 0x00, 0x00, // sink.video
    0xea, 0xda, 0x44, 0xf5, 0x66, 0xc3, 0x00, 0x00, // sink.audio
    0xea, 0xda, 0x44, 0xf4, 0x65, 0xc3, 0x00, 0x00, // sink.anc
    0, 0, 0, 0, 0, 0, 0, 0,                         // sink_audio_fmt
];

/// The protocol the captured frame was stamped with.
///
/// Part of the capture, not a choice: the layout a frame carries is selected by
/// its stamp, so feeding these bytes under any other one describes a frame no
/// device has ever sent. A configuration this length is the form from before
/// the codec word, and every sender of it stamps below that word's version.
const DEVICE_CFG_CAPTURE_PROTOCOL: u16 = 0x12;

/// The unit the capture came from, as its own payload names it.
///
/// A configuration frame carries its subject in the first sixteen bytes, and a
/// device describing itself puts its own uid there. So the capture has to
/// arrive from this uid to be the report it is: fed from any other sender it is
/// a management write for a third device, which is a different frame with
/// different rules.
const DEVICE_CFG_CAPTURE_UID: DeviceUid = DeviceUid::from_array([
    0x27, 0x40, 0x01, 0x04, 0x85, 0xac, 0xb7, 0xaa, 0x3e, 0x7d, 0x2c, 0x67, 0xc6, 0x07, 0x00, 0xf5,
]);

/// A harness whose peer is the unit the capture was taken from.
fn capture_device() -> Harness {
    let mut h = Harness::new(0);
    h.sender = DEVICE_CFG_CAPTURE_UID;
    h.hello(0x28, "ONEIP", "CM0001", DeviceFeature::VIDEO_ROUTING);
    h
}

#[test]
fn a_captured_device_config_decodes_field_for_field() {
    let mut h = capture_device();
    h.feed_proto(
        op::V2IP_DEVICE_CFG,
        DEVICE_CFG_CAPTURE_PROTOCOL,
        &DEVICE_CFG_CAPTURE,
    );

    let details = h.device().v2ip_details.expect("no details");
    // v2ip_stream_source is 8 bytes: the port is a uint_fast16_t, four bytes on
    // ARM, so the two bytes after it belong to the port's field rather than to
    // the next one.
    assert_eq!(details.video.ip, Ipv4Addr::new(234, 218, 68, 244));
    assert_eq!(details.video.port, 50020);
    assert_eq!(details.audio.port, 50022);
    assert_eq!(details.anc.port, 50021);
    assert_eq!(details.arc.ip, Ipv4Addr::new(234, 218, 68, 246));
    assert_eq!(details.arc.port, 50023);
    assert_eq!(details.tx_rate, Some(90));

    // 0x90 is V2IP_DSCP_SET | 16, and 16 is CS2, the boot default.
    assert!(details.dscp.is_complete());
    assert_eq!(details.dscp.video, Some(V2IP_DSCP_DEFAULT));
    assert_eq!(details.dscp.audio, Some(V2IP_DSCP_DEFAULT));
    assert_eq!(details.dscp.anc, Some(V2IP_DSCP_DEFAULT));

    assert_eq!(details.scaling.mode.svd(), 19);
    assert_eq!(details.scaling.mode.bpp(), Some(8));
    assert_eq!(details.scaling.refresh, 50);
    // Flags 0xdf carries bits 2, 3, 4 and 6 as well: this unit does not
    // initialise the configuration it broadcasts, so only bits 0, 1 and 7 mean
    // anything.
    assert_ne!(details.scaling.flags & SCALING_FLAG_AUTO_SCALING, 0);
    assert_eq!(
        details.scaling.flags
            & !(SCALING_FLAG_MODE_VALID | SCALING_FLAG_OPTIONS_VALID | SCALING_FLAG_AUTO_SCALING),
        0,
        "undefined flag bits cached from a 0xdf frame"
    );

    // The tiling block is zeroed, so its uid is zero: not carried, not a clear.
    assert_eq!(h.device().tiling, None);

    let sink = h.device().v2ip_sink.expect("no sink block");
    assert_eq!(sink.addresses.video.port, 50020);
    assert_eq!(sink.addresses.anc.port, 50021);
}

/// A sender that stops at the sink block reports no processor features.
///
/// The captured frame is exactly that sender, so this is a released shape
/// rather than a truncation invented for the test.
#[test]
fn a_frame_ending_at_the_sink_block_reports_no_processor_features() {
    let mut h = capture_device();
    h.feed_proto(
        op::V2IP_DEVICE_CFG,
        DEVICE_CFG_CAPTURE_PROTOCOL,
        &DEVICE_CFG_CAPTURE,
    );

    assert!(
        h.device().v2ip_sink.is_some(),
        "the sink block itself was lost"
    );
    assert_eq!(
        h.device().v2ip_features,
        None,
        "a frame with no processor word reported one"
    );
}

/// A real shipping `V2IP_DEVICE_CFG`, captured off a live mesh with the
/// processor word behind the sink block.
///
/// A different unit from `DEVICE_CFG_CAPTURE`, and the pair is what pins the
/// move: bytes 88..120 are the sink block both of them carry at 88, and the
/// feature mask is at 120 behind it rather than in front.
#[rustfmt::skip]
const DEVICE_CFG_CODEC_CAPTURE: [u8; 128] = [
    0x1A, 0x30, 0x01, 0x10, 0xE1, 0xDC, 0x01, 0xAA, 0x78, 0x7D, 0x10, 0x63, 0xC2, 0x07, 0x00, 0xF5,
    0xEA, 0x41, 0x6C, 0xC6, 0x64, 0xC3, 0x00, 0x00, // source.video 234.65.108.198:50020
    0xEA, 0x41, 0x6C, 0xC7, 0x66, 0xC3, 0x00, 0x00, // source.audio 234.65.108.199:50022
    0xEA, 0x41, 0x6C, 0xC6, 0x65, 0xC3, 0x00, 0x00, // source.anc   234.65.108.198:50021
    0x5A, 0x90, 0x90, 0x90, 0x00, 0x00, 0x00, 0x00, // tx_rate 90, dscp SET|16 on all three
    0xEA, 0x41, 0x6C, 0xC8, 0x67, 0xC3, 0x00, 0x00, // audio_return 234.65.108.200:50023
    0x00, 0xA0, 0x00, 0x00, 0xF2, 0x00, 0x00, 0x00, // scaling: mode 0xa000, refresh 0, flags 0xf2
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // tiling, uid zero: not carried
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xEA, 0x41, 0x6C, 0xC6, 0x64, 0xC3, 0x00, 0x00, // sink.video
    0xEA, 0x41, 0x6C, 0xC7, 0x66, 0xC3, 0x00, 0x00, // sink.audio
    0xEA, 0x41, 0x6C, 0xC6, 0x65, 0xC3, 0x00, 0x00, // sink.anc
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // sink_audio_fmt: no channels
    0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // codec: all six feature bits
];

/// The stamp that capture carries. Nothing on this opcode is selected by it -
/// every block is found by length - but a fixture fed under a stamp its sender
/// does not use describes a frame no device sends.
const DEVICE_CFG_CODEC_PROTOCOL: u16 = 0x12;

/// The unit the longer capture came from, as its own payload names it.
const DEVICE_CFG_CODEC_UID: DeviceUid = DeviceUid::from_array([
    0x1A, 0x30, 0x01, 0x10, 0xE1, 0xDC, 0x01, 0xAA, 0x78, 0x7D, 0x10, 0x63, 0xC2, 0x07, 0x00, 0xF5,
]);

/// A harness whose peer is the unit the longer capture was taken from.
fn codec_capture_device() -> Harness {
    let mut h = Harness::new(0);
    h.sender = DEVICE_CFG_CODEC_UID;
    h.hello(0x27, "ONEIP", "CM0002", DeviceFeature::VIDEO_ROUTING);
    h
}

/// The processor word sits behind the sink block, and the sink block is where
/// it has always been.
///
/// Read the word at the sink block's offset and it comes out as that block's
/// video address instead - a large invented capability set rather than nothing.
#[test]
fn a_captured_processor_word_is_read_behind_the_sink_block() {
    let mut h = codec_capture_device();
    h.feed_proto(
        op::V2IP_DEVICE_CFG,
        DEVICE_CFG_CODEC_PROTOCOL,
        &DEVICE_CFG_CODEC_CAPTURE,
    );

    let features = h.device().v2ip_features.expect("no processor features");
    assert_eq!(features.bits(), 0x3F);
    assert!(features.has(V2ipFpgaFeature::SINK_STREAM_INFO));

    let sink = h.device().v2ip_sink.expect("no sink block");
    assert_eq!(sink.addresses.video.ip, Ipv4Addr::new(234, 65, 108, 198));
    assert_eq!(sink.addresses.video.port, 50020);
    assert_eq!(sink.addresses.audio.port, 50022);
    assert_eq!(sink.addresses.anc.port, 50021);
    assert_eq!(sink.audio_fmt, None, "a zero format block reports no audio");

    let details = h.device().v2ip_details.expect("no details");
    assert_eq!(details.tx_rate, Some(90));
    assert_eq!(details.arc.ip, Ipv4Addr::new(234, 65, 108, 200));
    assert_eq!(details.dscp.video, Some(V2IP_DSCP_DEFAULT));
    assert_eq!(details.scaling.refresh, 0);
    // 0xf2 carries auto-scaling and the options bit, and no mode is configured.
    assert_ne!(details.scaling.flags & SCALING_FLAG_AUTO_SCALING, 0);
    assert_eq!(details.scaling.flags & SCALING_FLAG_MODE_VALID, 0);
    assert_eq!(h.device().tiling, None, "a zero uid is not a window");
}

/// A full-length frame from a current sender can still carry no mask.
///
/// Observed on a unit that had just rebooted: every gate satisfied - 128 bytes,
/// current stamp, subject equal to sender - and the processor had simply not
/// answered its feature query yet, so the device had nothing to report. The
/// same unit reported a real mask a minute later. Length is therefore not a
/// promise that a mask is there, which is why zero reads as unknown and not as
/// a device that supports nothing.
#[test]
fn a_zero_mask_in_a_full_length_capture_is_still_unknown() {
    let mut just_booted = DEVICE_CFG_CODEC_CAPTURE;
    just_booted[120..128].fill(0);

    let mut h = codec_capture_device();
    h.feed_proto(op::V2IP_DEVICE_CFG, DEVICE_CFG_CODEC_PROTOCOL, &just_booted);

    assert_eq!(
        h.device().v2ip_features,
        None,
        "an unanswered processor was reported as supporting nothing"
    );
    // Everything else in the frame is the capture, and still lands.
    let sink = h.device().v2ip_sink.expect("no sink block");
    assert_eq!(sink.addresses.video.port, 50020);

    // And the mask lands once the processor answers.
    h.feed_proto(
        op::V2IP_DEVICE_CFG,
        DEVICE_CFG_CODEC_PROTOCOL,
        &DEVICE_CFG_CODEC_CAPTURE,
    );
    assert_eq!(
        h.device()
            .v2ip_features
            .expect("the answered mask was dropped")
            .bits(),
        0x3F
    );
}

/// A device that initialises its configuration reports the second options
/// group; one that does not has it discarded as the noise it is.
///
/// The bits sit where older firmware leaves uninitialised stack, and the
/// validity bit is what claims the device has these options at all - so junk
/// there would invent settings rather than misreport real ones.
#[test]
fn the_second_scaling_options_group_is_read_only_from_a_sender_that_means_it() {
    let mut h = Harness::new(106);
    h.hello(
        0x28,
        "ONEIP",
        "CM0003",
        DeviceFeature::VIDEO_ROUTING | DeviceFeature::CONFIG_INITIALISED,
    );
    let mut cfg = Cfg::addresses(h.sender, "239.1.2.3");
    // What a factory unit broadcasts: auto scaling on, both options on, and no
    // mode configured.
    cfg.flags = SCALING_FLAG_OPTIONS_VALID
        | SCALING_FLAG_OPTIONS2_VALID
        | SCALING_FLAG_MATCH_SOURCE
        | SCALING_FLAG_SKIP_420
        | SCALING_FLAG_AUTO_SCALING;
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes());

    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_eq!(scaling.match_source(), Some(true));
    assert_eq!(scaling.skip_420(), Some(true));
    assert_eq!(scaling.auto_scaling(), Some(true));
    assert_eq!(scaling.configured_mode(), None, "no mode is configured");

    // The same byte from a sender that does not initialise its configuration.
    let mut h = command_device(107);
    let mut cfg = Cfg::addresses(h.sender, "239.1.2.3");
    cfg.flags = SCALING_FLAG_OPTIONS2_VALID | SCALING_FLAG_MATCH_SOURCE;
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes());

    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_eq!(
        scaling.match_source(),
        None,
        "uninitialised stack was reported as a setting"
    );
    assert_eq!(scaling.skip_420(), None);
}

/// Knowing a device has these options is not taken back by a write that does
/// not mention them.
///
/// One validity bit covers both, and a controller writing any other field
/// sends it clear. Reading the capability off the latest frame would report a
/// device as lacking options it had already announced.
#[test]
fn a_later_write_does_not_unsay_the_second_options_group() {
    let mut h = Harness::new(108);
    h.hello(
        0x28,
        "ONEIP",
        "CM0004",
        DeviceFeature::VIDEO_ROUTING | DeviceFeature::CONFIG_INITIALISED,
    );
    let sender = h.sender;
    let mut cfg = Cfg::addresses(sender, "239.1.2.3");
    cfg.flags = SCALING_FLAG_OPTIONS2_VALID | SCALING_FLAG_MATCH_SOURCE;
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes());
    assert_eq!(
        h.device().v2ip_details.unwrap().scaling.match_source(),
        Some(true)
    );

    // An options-only write, carrying the first group's bit and not the second.
    let mut options = Cfg::addresses(sender, "239.1.2.3");
    options.flags = SCALING_FLAG_OPTIONS_VALID | SCALING_FLAG_AUTO_SCALING;
    h.feed(op::V2IP_DEVICE_CFG, &options.bytes());

    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_eq!(
        scaling.match_source(),
        Some(true),
        "a write about another field unsaid what the device had reported"
    );
    assert_eq!(
        scaling.auto_scaling(),
        Some(true),
        "the write itself landed"
    );

    // And a frame that does carry the bit replaces both options together.
    let mut off = Cfg::addresses(sender, "239.1.2.3");
    off.flags = SCALING_FLAG_OPTIONS2_VALID | SCALING_FLAG_SKIP_420;
    h.feed(op::V2IP_DEVICE_CFG, &off.bytes());
    let scaling = h.device().v2ip_details.expect("no details").scaling;
    assert_eq!(scaling.match_source(), Some(false));
    assert_eq!(scaling.skip_420(), Some(true));
}

/// A device stamps the word only when describing itself, so a write aimed at
/// one device says nothing about its processor.
///
/// Caching the zero a controller sends would report the subject as supporting
/// nothing, on the strength of a frame that never asked it.
#[test]
fn a_write_from_a_controller_leaves_processor_features_alone() {
    let mut h = command_device(104);
    let subject = h.sender;
    let mut own = Cfg::addresses(subject, "239.1.2.3");
    own.codec = 0x3F;
    h.feed(op::V2IP_DEVICE_CFG, &own.bytes_with_options());
    assert!(h.device().v2ip_features.is_some(), "nothing was cached");

    // A controller with management standing writes the same device's config.
    // Firmware leaves the word zero on a write aimed at someone else, so the
    // mask here is one no MatrixOS controller sends - and that is the point:
    // what makes the subject's features its own is who the frame is from, not
    // that every other sender happens to write a zero. A client on this
    // protocol that filled the field in would otherwise redefine a device's
    // capabilities from across the network.
    let controller = uid_n(77);
    h.feed_as(
        controller,
        op::SYS_HELLO,
        &hello_payload(0x28, "Ctrl", "CTRL0002", "4.8.0", DeviceFeature::MANAGER),
    );
    let mut cfg = Cfg::addresses(subject, "239.9.9.9");
    cfg.codec = V2ipFpgaFeature::SINK_OVERLAY_STATE.bits();
    h.feed_as(controller, op::V2IP_DEVICE_CFG, &cfg.bytes_with_options());

    let features = h
        .state
        .device(subject)
        .expect("the subject is not registered")
        .v2ip_features
        .expect("a controller's write cleared the cached features");
    assert_eq!(
        features.bits(),
        0x3F,
        "a third party's frame rewrote the subject's processor features"
    );
    assert_eq!(
        h.state.device(controller).and_then(|d| d.v2ip_features),
        None,
        "the features landed on the sender instead"
    );
}

/// A controller writing a device's configuration has nothing to say about its
/// sink, and sends that block zeroed.
///
/// Caching those zeros would clear every reader's record of the sink's route on
/// each unrelated write, such as turning its automatic scaling off.
#[test]
fn a_write_from_a_controller_leaves_the_sink_route_alone() {
    let mut h = command_device(109);
    let subject = h.sender;
    let mut own = Cfg::addresses(subject, "239.1.2.3").bytes_with_options();
    own[88..92].copy_from_slice(&[239, 7, 8, 9]);
    own[92..96].copy_from_slice(&50020u32.to_le_bytes());
    h.feed(op::V2IP_DEVICE_CFG, &own);
    let reported = h.device().v2ip_sink.expect("no sink block");
    assert_eq!(reported.addresses.video.ip, Ipv4Addr::new(239, 7, 8, 9));

    let controller = uid_n(78);
    h.feed_as(
        controller,
        op::SYS_HELLO,
        &hello_payload(0x28, "Ctrl", "CTRL0003", "4.8.0", DeviceFeature::MANAGER),
    );
    let mut write = Cfg::addresses(subject, "0.0.0.0");
    write.flags = SCALING_FLAG_OPTIONS_VALID;
    h.feed_as(controller, op::V2IP_DEVICE_CFG, &write.bytes_with_options());

    let subject_record = h.state.device(subject).expect("subject vanished");
    assert!(
        subject_record
            .v2ip_details
            .is_some_and(|d| d.scaling.auto_scaling() == Some(false)),
        "the write itself did not land"
    );
    assert_eq!(
        subject_record.v2ip_sink,
        Some(reported),
        "a controller's zeroed sink block replaced the device's own report"
    );
}

/// Every device setting a unit has, as it reports them.
const ALL_SETTINGS: u32 = 0x7FF;

/// The device settings sit behind the processor word, each field at its own
/// offset.
///
/// Every field carries a distinct value, so one read at a neighbour's offset
/// shows, and the reserved bytes behind them are poisoned.
#[test]
fn device_settings_are_read_behind_the_processor_word() {
    let mut h = command_device(110);
    let mut cfg = Cfg::addresses(h.sender, "239.1.2.3");
    cfg.codec = 0x3F;
    let on = V2ipDeviceSetting::SINK_CHECK_POWER
        | V2ipDeviceSetting::STATUS_LED
        | V2ipDeviceSetting::CEC_COMBO_INPUT;
    h.feed(
        op::V2IP_DEVICE_CFG,
        &cfg.bytes_with_settings(ALL_SETTINGS, on.bits(), 0b101, 3, -1),
    );

    let s = h.device().v2ip_settings.expect("no settings were read");
    assert_eq!(s.valid.bits(), ALL_SETTINGS);
    assert_eq!(s.get(V2ipDeviceSetting::SINK_CHECK_POWER), Some(true));
    assert_eq!(s.get(V2ipDeviceSetting::SINK_OFF_NO_SIGNAL), Some(false));
    assert_eq!(s.get(V2ipDeviceSetting::STATUS_LED), Some(true));
    assert_eq!(s.get(V2ipDeviceSetting::NETWORK_LED), Some(false));
    assert_eq!(s.get(V2ipDeviceSetting::CEC_COMBO_INPUT), Some(true));
    assert_eq!(s.stored_ir_profiles(), Some(0b101));
    assert_eq!(s.ir_profile(), Some(3));
    assert_eq!(s.ir_profile_sink(), Some(-1), "the sign was lost");
    assert_eq!(
        h.device().v2ip_features.map(V2ipFpgaFeature::bits),
        Some(0x3F),
        "the block moved the processor word"
    );
}

/// The settings were appended, so a sender that predates them stops short of
/// them and one byte short of the block is not the block.
#[test]
fn device_settings_are_read_only_from_a_frame_long_enough_to_hold_them() {
    let mut h = command_device(111);
    let cfg = Cfg::addresses(h.sender, "239.1.2.3");
    let whole = cfg.bytes_with_settings(ALL_SETTINGS, 0, 0, 0, 0);
    assert_eq!(whole.len(), 144);

    // A block that carries no setting says nothing, which is not a device
    // reporting that it has none.
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes_with_settings(0, 0, 0, 0, 0));
    assert_eq!(h.device().v2ip_settings, None);

    h.feed(op::V2IP_DEVICE_CFG, &whole[..143]);
    assert!(h.device().v2ip_details.is_some(), "the frame was dropped");
    assert_eq!(h.device().v2ip_settings, None);

    h.feed(op::V2IP_DEVICE_CFG, &whole);
    assert!(h.device().v2ip_settings.is_some());
}

/// A frame carrying some settings leaves the others as they were.
#[test]
fn a_frame_carrying_one_setting_keeps_the_rest() {
    let mut h = command_device(112);
    let cfg = Cfg::addresses(h.sender, "239.1.2.3");
    let fan = V2ipDeviceSetting::FAN_QUIET;
    h.feed(
        op::V2IP_DEVICE_CFG,
        &cfg.bytes_with_settings(ALL_SETTINGS, fan.bits(), 0b11, 2, 4),
    );
    h.feed(
        op::V2IP_DEVICE_CFG,
        &cfg.bytes_with_settings(V2ipDeviceSetting::STATUS_LED.bits(), 0, 0, 0, 0),
    );

    let s = h.device().v2ip_settings.expect("no settings");
    assert_eq!(s.get(V2ipDeviceSetting::STATUS_LED), Some(false));
    assert_eq!(
        s.get(fan),
        Some(true),
        "a setting the frame did not carry was changed"
    );
    assert_eq!(s.ir_profile(), Some(2));
    assert_eq!(s.ir_profile_sink(), Some(4));
    assert_eq!(s.stored_ir_profiles(), Some(0b11));
    assert_eq!(s.valid.bits(), ALL_SETTINGS);
}

/// A controller's write is cached as far as the device takes it.
///
/// The device applies a setting only if it has it and a profile only within
/// its range, and the list of stored profiles is its own. Caching more would
/// report a change the device never made.
#[test]
fn a_controller_write_is_cached_only_as_far_as_the_device_takes_it() {
    let mut h = command_device(113);
    let subject = h.sender;
    let cfg = Cfg::addresses(subject, "239.1.2.3");
    let has = V2ipDeviceSetting::SWITCHES
        | V2ipDeviceSetting::IR_PROFILE
        | V2ipDeviceSetting::IR_PROFILES;
    h.feed(
        op::V2IP_DEVICE_CFG,
        &cfg.bytes_with_settings(has.bits(), 0, 0b101, 1, 0),
    );

    let controller = uid_n(81);
    h.feed_as(
        controller,
        op::SYS_HELLO,
        &hello_payload(0x28, "Ctrl", "CTRL0005", "4.8.0", DeviceFeature::MANAGER),
    );
    let mut write = Cfg::addresses(subject, "0.0.0.0");
    write.flags = 0;
    let carried = V2ipDeviceSetting::STATUS_LED
        | V2ipDeviceSetting::IR_PROFILE
        | V2ipDeviceSetting::IR_PROFILE_SINK
        | V2ipDeviceSetting::IR_PROFILES;
    h.feed_as(
        controller,
        op::V2IP_DEVICE_CFG,
        &write.bytes_with_settings(
            carried.bits(),
            V2ipDeviceSetting::STATUS_LED.bits(),
            0xFFFF,
            40,
            2,
        ),
    );

    let s = h
        .state
        .device(subject)
        .and_then(|d| d.v2ip_settings)
        .expect("the subject's settings are gone");
    assert_eq!(
        s.get(V2ipDeviceSetting::STATUS_LED),
        Some(true),
        "the write itself did not land"
    );
    assert_eq!(
        s.ir_profile(),
        Some(1),
        "an out-of-range profile was cached"
    );
    assert_eq!(
        s.ir_profile_sink(),
        None,
        "a setting the device does not have was cached"
    );
    assert_eq!(
        s.stored_ir_profiles(),
        Some(0b101),
        "a third party rewrote the profiles only the device knows"
    );
    assert_eq!(
        h.state.device(controller).and_then(|d| d.v2ip_settings),
        None,
        "the settings landed on the sender instead"
    );

    // The output port's range starts one lower, at "follow the global one".
    let sink_port = V2ipDeviceSetting::IR_PROFILE_SINK;
    h.feed(
        op::V2IP_DEVICE_CFG,
        &cfg.bytes_with_settings(sink_port.bits(), 0, 0, 0, 5),
    );
    for (profile, cached) in [(-2, 5), (-1, -1)] {
        h.feed_as(
            controller,
            op::V2IP_DEVICE_CFG,
            &write.bytes_with_settings(sink_port.bits(), 0, 0, 0, profile),
        );
        let s = h.state.device(subject).and_then(|d| d.v2ip_settings);
        assert_eq!(
            s.and_then(|s| s.ir_profile_sink()),
            Some(cached),
            "a write of {profile} to the output port"
        );
    }
}

/// An empty mask is "not reported yet", not "supports nothing".
///
/// A processor that has yet to answer after boot and one too old to have any of
/// the optional commands send the same zero, so nothing distinguishes them and
/// the honest reading is that the device has not said.
#[test]
fn an_empty_processor_mask_is_not_a_capability_set() {
    let mut h = command_device(103);
    let mut cfg = Cfg::addresses(h.sender, "239.1.2.3");
    cfg.codec = 0;
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes_with_options());

    assert!(
        h.device().v2ip_details.is_some(),
        "the configuration itself was dropped"
    );
    assert_eq!(
        h.device().v2ip_features,
        None,
        "an empty mask was reported as a capability set"
    );

    // Once the processor answers, the mask lands.
    cfg.codec = V2ipFpgaFeature::SINK_STATE.bits();
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes_with_options());
    let features = h.device().v2ip_features.expect("a real mask was dropped");
    assert!(features.has(V2ipFpgaFeature::SINK_STATE));
}

/// A configuration from before the tiling window is decoded, not refused.
///
/// The window was appended, so every field ahead of it sits where it always
/// has and an older sender's frame is complete rather than truncated. Devices
/// emitting this form are still in the field, and reading it costs nothing:
/// the window is gated on its own length, so its absence stays absence rather
/// than becoming a window built from whatever followed the frame.
#[test]
fn a_configuration_from_before_the_tiling_window_is_still_read() {
    let mut h = command_device(102);
    let cfg = Cfg::addresses(h.sender, "239.4.5.6");
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes()[..64]);

    let details = h
        .device()
        .v2ip_details
        .expect("a complete older configuration was refused");
    assert_eq!(details.video.ip, Ipv4Addr::new(239, 4, 5, 6));
    assert_eq!(
        h.device().tiling,
        None,
        "a window came out of a frame that carries none"
    );

    // One byte short of that oldest whole form is a frame no sender emits.
    let mut h = command_device(105);
    let cfg = Cfg::addresses(h.sender, "239.4.5.6");
    h.feed(op::V2IP_DEVICE_CFG, &cfg.bytes()[..63]);
    assert!(
        h.device().v2ip_details.is_none(),
        "a configuration shorter than any sender emits was read"
    );
}

#[test]
fn a_stamped_tiling_block_is_told_from_an_absent_one() {
    let mut h = capture_device();
    let target = uid_n(99);

    let mut p = DEVICE_CFG_CAPTURE;
    p[64..80].copy_from_slice(target.as_bytes());
    let feed = |h: &mut Harness, p: &[u8]| {
        h.feed_proto(op::V2IP_DEVICE_CFG, DEVICE_CFG_CAPTURE_PROTOCOL, p)
    };
    p[80..82].copy_from_slice(&1920u16.to_le_bytes());
    p[84..86].copy_from_slice(&3840u16.to_le_bytes());
    p[86..88].copy_from_slice(&2160u16.to_le_bytes());
    feed(&mut h, &p);

    let tiling = h.device().tiling.expect("no window");
    assert_eq!(tiling.target, target);
    assert_eq!(tiling.pos_x, 1920);
    assert_eq!((tiling.width, tiling.height), (3840, 2160));

    // A stamped uid with zero geometry is a real clear, and must still cache.
    p[80..88].fill(0);
    feed(&mut h, &p);
    let tiling = h.device().tiling.expect("a stamped clear was dropped");
    assert_eq!((tiling.width, tiling.height), (0, 0));

    // A zero-uid block must leave that cached clear alone.
    p[64..80].fill(0);
    p[84..86].copy_from_slice(&1234u16.to_le_bytes());
    feed(&mut h, &p);
    let tiling = h
        .device()
        .tiling
        .expect("an uncarried block cleared the cache");
    assert_eq!(tiling.width, 0);
}