mx-remote 7.0.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
// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
// Copyright (c) 2026 Op den Kamp IT Solutions

//! The control surface: what a caller can ask a device to do.
//!
//! Every method here has the same shape. It reads the registry to decide what
//! to send, releases that lock, transmits, and only then writes back what the
//! device will have done. The order is what makes a handler woken by the
//! write-back free to call in again, and it keeps the receive thread from
//! waiting on a socket write for the lock it needs to decode.
//!
//! Nothing here reaches the wire on its own: a payload is bytes until the
//! single transmit path stamps and writes it, which is where the addressee's
//! protocol version is checked.
//!
//! The multiviewer and audio-endpoint methods are served by loadable modules
//! rather than by the device firmware, and a model may not load modules at
//! all, may not ship that one, or may not support it. Those modules answer
//! nothing either way, so an `Ok` from one of those methods says a frame left
//! the socket and no more: "the device did it" and "nothing on the device
//! handles this" are the same observation from here. Read the state back to
//! tell them apart. A multiviewer broadcasts its whole status shortly after a
//! setting it accepted, which serves as that read for every one of its methods
//! but [`Remote::set_multiviewer_remote_control`] and
//! [`Remote::set_multiviewer_input_source`], which broadcast nothing.

use std::fmt;
use std::net::Ipv4Addr;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::event::Event;
use crate::state::{Bay, Device, State};
use crate::types::{
    AmpZoneSettings, AudioFeatures, HiddenStatus, MultiviewerStatus, PowerStatus, UnitNetConfig,
    V2ipAudioFormat, V2ipDeviceSettings, V2ipOutputMode, V2ipPowerSaveSchedule, V2ipRoute,
    V2ipRouteTarget, V2ipScalingSettings, V2ipStreamSources, V2ipTestSync, V2ipTestTone,
    V2ipTestcard, V2ipVlan, VideoWallOp, VideoWallWindow, VolumeMuteStatus, MULTIVIEWER_INPUTS,
    SCALING_FLAG_AUTO_SCALING, SCALING_FLAG_MODE_VALID, SCALING_FLAG_OPTIONS_VALID,
    V2IP_PTP_DOMAIN_MAX, V2IP_VLAN_PORT_SFP, VIDEO_WALL_CLEARED,
};
use crate::wire::{
    audio_cmd_header, audio_param, audio_sub, build_amp_zone_settings, build_audio_select_input,
    build_bay_hide, build_edid_profile, build_edid_request, build_mesh_operation, build_rc_action,
    build_rc_key, build_set_bay_name, build_set_volume, build_stats_request, build_target_only,
    build_time_zone, build_unit_command, build_v2ip_device_settings,
    build_v2ip_manual_source_switch, build_v2ip_scaling, build_v2ip_settings_all,
    build_v2ip_source_switch, build_v2ip_testcard, build_v2ip_vlan, build_video_wall, mesh_op,
    mv_cmd_payload, mv_sub, op, testcard_part, testcard_type, Addressee, BayUid, DeviceFeature,
    DeviceUid, EdidProfile, MultiviewerAspectRatio, MultiviewerEdidTemplate, MultiviewerHdcpMode,
    MultiviewerItcMode, MultiviewerOutputMode, MultiviewerPipPosition, MultiviewerPipSize,
    MultiviewerSource, MultiviewerViewMode, MxrSignalType, Opcode, RcAction, RcKey, SendError,
    StreamAddr, UnitCommandFlag, UnitCommandKind, V2ipDeviceSetting, V2ipFpgaFeature, V2ipPtpMode,
    V2ipStreams, V2ipTestPattern, V2ipToneMode, V2ipVlanFlag, DEVICE_NAME_LEN, TIME_ZONE_NAME_LEN,
    TIME_ZONE_RULE_LEN, V2IP_IR_PROFILE_MAX, V2IP_IR_PROFILE_NOT_SET, V2IP_PORT_ANC,
    V2IP_PORT_AUDIO, V2IP_PORT_VIDEO,
};

use super::{Remote, Shared};

/// Why a control method did nothing.
#[derive(Debug)]
#[non_exhaustive]
pub enum ControlError {
    /// No device with this identifier has been heard from.
    UnknownDevice(DeviceUid),
    /// The device has reported no bay on this port.
    UnknownBay(BayUid),
    /// No input bay on the device carries this user-assigned name.
    UnknownSource(String),
    /// The addressee does not do what was asked of it.
    Unsupported(&'static str),
    /// The request breaks a rule the device is not guaranteed to check.
    ///
    /// Nothing was sent. This is the caller's to fix, and it is separate from
    /// [`ControlError::Unsupported`] because the device would have taken the
    /// frame: refusing here is this library declining to let a bad value
    /// reach hardware that may store it rather than reject it.
    InvalidRequest(&'static str),
    /// The device has not reported something the request is assembled from.
    ///
    /// Unlike [`ControlError::Unsupported`], the same call may succeed once it
    /// has: this says the value is missing, not that it cannot exist.
    NotReported(&'static str),
    /// The frame could not be sent.
    Send(SendError),
}

impl fmt::Display for ControlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownDevice(uid) => write!(f, "no device {uid}"),
            Self::UnknownBay(uid) => write!(f, "no bay {uid}"),
            Self::UnknownSource(name) => write!(f, "no source named {name:?}"),
            Self::Unsupported(what) => f.write_str(what),
            Self::InvalidRequest(what) => f.write_str(what),
            Self::NotReported(what) => write!(f, "{what} has not been reported"),
            Self::Send(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for ControlError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Send(e) => Some(e),
            _ => None,
        }
    }
}

impl From<SendError> for ControlError {
    fn from(e: SendError) -> Self {
        Self::Send(e)
    }
}

/// What a command does to this client's copy of the registry once its frame is
/// away.
///
/// A device does not acknowledge a command, so without this a caller that read
/// back what it just wrote would see the old value until some unrelated report
/// happened to carry the new one.
type WriteBack = Box<dyn FnOnce(&mut State, &mut Vec<Event>) + Send>;

/// One command: the frame to send, and what the addressee will do with it.
struct Command {
    to: Addressee,
    opcode: Opcode,
    payload: Vec<u8>,
    write_back: Option<WriteBack>,
}

impl Command {
    fn new(to: Addressee, opcode: Opcode, payload: Vec<u8>) -> Self {
        Self {
            to,
            opcode,
            payload,
            write_back: None,
        }
    }

    /// Records what to apply locally once the frame is away.
    fn then(mut self, f: impl FnOnce(&mut State, &mut Vec<Event>) + Send + 'static) -> Self {
        self.write_back = Some(Box::new(f));
        self
    }
}

impl Shared {
    /// Runs one command: prepare under the registry lock, send without it,
    /// then write back.
    fn command(
        &self,
        prepare: impl FnOnce(&State) -> Result<Command, ControlError>,
    ) -> Result<(), ControlError> {
        let command = self.read(prepare)?;
        self.send(&command.to, command.opcode, &command.payload)?;
        if let Some(write_back) = command.write_back {
            self.mutate(|state, ev| write_back(state, ev));
        }
        Ok(())
    }
}

/// The first protocol version whose devices can act on the automatic address
/// operation.
///
/// Not the stamp: that is the mesh operation opcode's, and a device between
/// the two takes the frame and ignores an operation it does not know. Not
/// every device on this version has it either, but none below it does.
const AUTO_ADDRESSES_PROTOCOL: u16 = 0x2B;

fn device_of(state: &State, uid: DeviceUid) -> Result<&Device, ControlError> {
    state.device(uid).ok_or(ControlError::UnknownDevice(uid))
}

/// The device behind `uid`, once it is known to be a multiviewer.
fn multiviewer_of(state: &State, uid: DeviceUid) -> Result<&Device, ControlError> {
    let device = device_of(state, uid)?;
    if !device.is_multiviewer() {
        return Err(ControlError::Unsupported("the device is not a multiviewer"));
    }
    Ok(device)
}

/// Wraps one multiviewer sub-command in the envelope every one of them shares.
fn mv_command(device: &Device, sub: u8, args: &[u8]) -> Command {
    Command::new(
        Addressee::device(device),
        op::V2IP_MULTIVIEWER,
        mv_cmd_payload(device.uid, sub, args),
    )
}

/// The zero-based input a source names, refused when it names none.
///
/// A multiviewer reads zero as its first input, so there is no value that says
/// "no input": a source that names none would arrive as a request to switch to
/// input 1.
fn source_index(source: MultiviewerSource, what: &'static str) -> Result<u8, ControlError> {
    source
        .to_zero_based()
        .ok_or(ControlError::InvalidRequest(what))
}

/// A multiviewer setting within the range its firmware accepts.
///
/// Every one of these settings is numbered from one, with zero reserved for
/// "the device has reported nothing". The device drops a value it does not
/// know without answering, so a caller sending one would see a send succeed
/// and the setting stay as it was; this is what turns that into an error.
fn mv_setting(value: u8, highest: u8, what: &'static str) -> Result<u8, ControlError> {
    if (1..=highest).contains(&value) {
        Ok(value)
    } else {
        Err(ControlError::InvalidRequest(what))
    }
}

fn bay_of(state: &State, uid: BayUid) -> Result<(&Device, &Bay), ControlError> {
    let device = device_of(state, uid.device)?;
    let bay = device.bay(uid.port).ok_or(ControlError::UnknownBay(uid))?;
    Ok((device, bay))
}

/// The streams the source bay on `port` advertises.
fn source_streams(device: &Device, port: u16) -> Result<&V2ipStreamSources, ControlError> {
    let source = device
        .bay(port)
        .ok_or(ControlError::UnknownBay(BayUid::new(device.uid, port)))?;
    device
        .v2ip_source_for(source)
        .ok_or(ControlError::NotReported("the source's stream addresses"))
}

/// A sink bay, or the reason it cannot be routed.
fn v2ip_sink(state: &State, uid: BayUid) -> Result<(&Device, &Bay), ControlError> {
    let (device, bay) = bay_of(state, uid)?;
    if !bay.is_v2ip_sink() {
        return Err(ControlError::Unsupported("routing needs a V2IP sink"));
    }
    Ok((device, bay))
}

/// One route slot as the wire carries it, substituting the stream's standard
/// port for an unset one.
///
/// An unset address sends the slot zeroed, port included: the firmware reads
/// the pair together, and a port beside 0.0.0.0 describes nothing.
fn stream_addr(target: V2ipRouteTarget, standard_port: u16) -> StreamAddr {
    if target.ip.is_unspecified() {
        return StreamAddr::default();
    }
    StreamAddr {
        ip: target.ip,
        port: target.port_or(standard_port),
    }
}

/// The name as the device will store it: the field is
/// [`DEVICE_NAME_LEN`] bytes wide, so a longer one is cut there.
fn stored_name(name: &str) -> String {
    let bytes = name.as_bytes();
    String::from_utf8_lossy(bytes.get(..DEVICE_NAME_LEN).unwrap_or(bytes)).into_owned()
}

impl Remote {
    // ---- routing ----

    /// Routes this V2IP sink's video to the stream a source port advertises.
    pub fn select_video_source(&self, sink: BayUid, source_port: u16) -> Result<(), ControlError> {
        self.shared.command(|state| {
            let (device, bay) = v2ip_sink(state, sink)?;
            if !bay.is_output() {
                return Err(ControlError::Unsupported("not an output bay"));
            }
            let streams = source_streams(device, source_port)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_SOURCE_SWITCH,
                build_v2ip_source_switch(device.uid, streams.video.ip, Ipv4Addr::UNSPECIFIED),
            ))
        })
    }

    /// Routes this V2IP sink's audio to the stream a source port advertises.
    pub fn select_audio_source(&self, sink: BayUid, source_port: u16) -> Result<(), ControlError> {
        self.shared.command(|state| {
            let (device, _) = v2ip_sink(state, sink)?;
            let streams = source_streams(device, source_port)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_SOURCE_SWITCH,
                build_v2ip_source_switch(device.uid, Ipv4Addr::UNSPECIFIED, streams.audio.ip),
            ))
        })
    }

    /// Routes this V2IP sink's video to the input bay with the given
    /// user-assigned name.
    pub fn select_video_source_by_name(
        &self,
        sink: BayUid,
        name: &str,
    ) -> Result<(), ControlError> {
        self.select_video_source(sink, self.source_port(sink, name)?)
    }

    /// Routes this V2IP sink's audio to a multicast address directly, leaving
    /// its video and ancillary streams alone.
    ///
    /// An unset port is the standard V2IP audio port. A format overrides the
    /// sample rate and channel count the receiver would otherwise assume.
    pub fn select_audio_source_addr(
        &self,
        sink: BayUid,
        audio_ip: Ipv4Addr,
        audio_port: Option<u16>,
        format: Option<V2ipAudioFormat>,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = v2ip_sink(state, sink)?;
            let streams = V2ipStreams {
                audio: StreamAddr {
                    ip: audio_ip,
                    port: audio_port.unwrap_or(V2IP_PORT_AUDIO),
                },
                ..V2ipStreams::default()
            };
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_MANUAL_SRC_SWITCH,
                build_v2ip_manual_source_switch(device.uid, streams, format),
            ))
        })
    }

    /// Routes this V2IP sink's video, audio and ancillary streams to
    /// multicast groups the caller names.
    ///
    /// This is the only way to reach a stream no device on the mesh
    /// advertises, such as one the host is transmitting itself; a route by
    /// source port can only name a stream some bay has announced.
    ///
    /// Set all three groups. The firmware decides whether a sink has a manual
    /// route by looking at the video and ancillary groups, so a route that
    /// leaves either unset does not register as one and the sink falls back to
    /// the audio source its mesh picks.
    ///
    /// An unset `format` sends [`V2ipAudioFormat::STANDARD`] rather than
    /// omitting the trailer. The firmware stores whatever this frame carries
    /// and hands it to the FPGA unexamined, so a frame without one leaves a
    /// zero rate and zero channel count there, which the FPGA rejects and
    /// which takes the switch down with it.
    pub fn select_source_addr(
        &self,
        sink: BayUid,
        route: V2ipRoute,
        format: Option<V2ipAudioFormat>,
    ) -> Result<(), ControlError> {
        let streams = V2ipStreams {
            video: stream_addr(route.video, V2IP_PORT_VIDEO),
            audio: stream_addr(route.audio, V2IP_PORT_AUDIO),
            anc: stream_addr(route.anc, V2IP_PORT_ANC),
        };
        let format = format.unwrap_or(V2ipAudioFormat::STANDARD);
        self.shared.command(move |state| {
            let (device, _) = v2ip_sink(state, sink)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_MANUAL_SRC_SWITCH,
                build_v2ip_manual_source_switch(device.uid, streams, Some(format)),
            ))
        })
    }

    /// Routes this V2IP sink's audio from the input bay with the given
    /// user-assigned name.
    ///
    /// A format is carried on the manual switch frame, which is the only form
    /// that can override the receiver's sample rate and channel count.
    pub fn select_audio_source_by_name(
        &self,
        sink: BayUid,
        name: &str,
        format: Option<V2ipAudioFormat>,
    ) -> Result<(), ControlError> {
        let port = self.source_port(sink, name)?;
        let Some(format) = format else {
            return self.select_audio_source(sink, port);
        };
        self.shared.command(move |state| {
            let (device, _) = v2ip_sink(state, sink)?;
            let audio = source_streams(device, port)?.audio;
            let streams = V2ipStreams {
                audio: StreamAddr {
                    ip: audio.ip,
                    port: audio.port,
                },
                ..V2ipStreams::default()
            };
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_MANUAL_SRC_SWITCH,
                build_v2ip_manual_source_switch(device.uid, streams, Some(format)),
            ))
        })
    }

    /// The port of the input bay on `sink`'s device carrying `name`.
    fn source_port(&self, sink: BayUid, name: &str) -> Result<u16, ControlError> {
        self.shared.read(|state| {
            let (device, _) = bay_of(state, sink)?;
            device
                .bay_by_user_name(name)
                .map(|b| b.port)
                .ok_or_else(|| ControlError::UnknownSource(name.to_owned()))
        })
    }

    // ---- bay settings ----

    /// Renames a bay.
    pub fn set_bay_name(&self, bay: BayUid, name: &str) -> Result<(), ControlError> {
        let name = stored_name(name);
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            let payload = build_set_bay_name(device.uid, bay.port, &name);
            Ok(
                Command::new(Addressee::device(device), op::CHANGE_BAY_NAME, payload).then(
                    move |state, ev| {
                        if let Some(b) = state.bay_mut(bay) {
                            b.set_user_name(name, ev);
                        }
                    },
                ),
            )
        })
    }

    /// Hides a bay from the pickers that list it, or shows it again.
    pub fn set_bay_hidden(&self, bay: BayUid, hidden: bool) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::BAY_HIDE,
                build_bay_hide(device.uid, bay.port, hidden),
            )
            .then(move |state, ev| {
                if let Some(b) = state.bay_mut(bay) {
                    let status = if hidden {
                        HiddenStatus::Hidden
                    } else {
                        HiddenStatus::Visible
                    };
                    b.apply_hidden(status, ev);
                }
            }))
        })
    }

    /// Sets the EDID profile an input presents to the source attached to it.
    pub fn select_edid_profile(
        &self,
        bay: BayUid,
        profile: EdidProfile,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::BAY_EDID_PROFILE,
                build_edid_profile(device.uid, profile),
            )
            .then(move |state, ev| {
                if let Some(b) = state.bay_mut(bay) {
                    b.set_edid_profile(profile, ev);
                }
            }))
        })
    }

    /// Sends a remote-control action to whatever is attached to a bay.
    pub fn send_action(&self, bay: BayUid, action: RcAction) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::RC_TX_ACTION,
                build_rc_action(device.uid, bay.port, action),
            ))
        })
    }

    /// Sends a remote-control key press to whatever is attached to a bay.
    ///
    /// The device forwards it over CEC, infrared or IP, whichever that bay is
    /// configured for; the caller does not choose. An action from
    /// [`Remote::send_action`] names an outcome instead, and the device
    /// decides which keys reach it.
    pub fn send_key(&self, bay: BayUid, key: RcKey) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::RC_TX_KEY,
                build_rc_key(device.uid, bay.port, key),
            ))
        })
    }

    /// Powers on the device attached to a bay.
    pub fn power_on(&self, bay: BayUid) -> Result<(), ControlError> {
        self.set_power(bay, RcAction::POWER_ON, PowerStatus::On)
    }

    /// Powers off the device attached to a bay.
    pub fn power_off(&self, bay: BayUid) -> Result<(), ControlError> {
        self.set_power(bay, RcAction::POWER_OFF, PowerStatus::Off)
    }

    fn set_power(
        &self,
        bay: BayUid,
        action: RcAction,
        power: PowerStatus,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::RC_TX_ACTION,
                build_rc_action(device.uid, bay.port, action),
            )
            .then(move |state, ev| {
                if let Some(b) = state.bay_mut(bay) {
                    b.set_power_status(power, ev);
                }
            }))
        })
    }

    /// Sets a bay's volume, as a percentage, and optionally its mute state.
    ///
    /// Both channels are set together: the wire carries them separately, but
    /// nothing on this surface splits them.
    ///
    /// A bay with no volume control of its own is set through its
    /// [`linked_bay`](crate::BayInfo::linked_bay), so an output wired to an
    /// amplifier zone reaches that zone. [`volume_up`](Self::volume_up),
    /// [`volume_down`](Self::volume_down) and [`set_muted`](Self::set_muted)
    /// follow the same link, and read the volume they step from through it.
    pub fn set_volume(
        &self,
        bay: BayUid,
        volume: u8,
        muted: Option<bool>,
    ) -> Result<(), ControlError> {
        let volume = volume.min(100);
        let wanted = VolumeMuteStatus {
            volume_left: Some(volume),
            volume_right: Some(volume),
            muted_left: muted,
            muted_right: muted,
        };
        self.shared.command(move |state| {
            // The mesh may put this bay's volume control on another device, and
            // the command belongs where the volume lives, not where it was
            // addressed.
            let target = state.volume_bay(bay);
            let (device, b) = bay_of(state, target)?;
            if !b.has_volume_control() {
                return Err(ControlError::Unsupported("the bay has no volume control"));
            }
            Ok(Command::new(
                Addressee::device(device),
                op::AUDIO_SET_VOLUME,
                build_set_volume(device.uid, target.port, wanted),
            )
            .then(move |state, ev| {
                if let Some(device) = state.device_mut(target.device) {
                    device.apply_bay_volume(target.port, wanted, ev);
                }
            }))
        })
    }

    /// Raises a bay's volume by one percent.
    pub fn volume_up(&self, bay: BayUid) -> Result<(), ControlError> {
        self.set_volume(bay, self.current_volume(bay)?.saturating_add(1), None)
    }

    /// Lowers a bay's volume by one percent.
    pub fn volume_down(&self, bay: BayUid) -> Result<(), ControlError> {
        self.set_volume(bay, self.current_volume(bay)?.saturating_sub(1), None)
    }

    /// Mutes or unmutes a bay, keeping the volume it is set to.
    pub fn set_muted(&self, bay: BayUid, muted: bool) -> Result<(), ControlError> {
        self.set_volume(bay, self.current_volume(bay)?, Some(muted))
    }

    /// The volume a step or a mute is relative to.
    fn current_volume(&self, bay: BayUid) -> Result<u8, ControlError> {
        self.shared.read(|state| {
            let (_, b) = bay_of(state, state.volume_bay(bay))?;
            b.audio_volume
                .map(|v| v.volume())
                .ok_or(ControlError::NotReported("the bay's volume"))
        })
    }

    /// Applies amplifier settings to a zone.
    pub fn set_amp_zone_settings(
        &self,
        bay: BayUid,
        settings: AmpZoneSettings,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let (device, _) = bay_of(state, bay)?;
            Ok(Command::new(
                Addressee::device(device),
                op::AMP_ZONE_SETTINGS,
                build_amp_zone_settings(device.uid, bay.port, &settings),
            )
            .then(move |state, ev| {
                if let Some(b) = state.bay_mut(bay) {
                    b.set_amp_settings(settings, ev);
                }
            }))
        })
    }

    // ---- audio endpoints ----

    /// Mutes or unmutes an audio endpoint.
    pub fn set_audio_endpoint_muted(
        &self,
        device: DeviceUid,
        endpoint: u16,
        muted: bool,
    ) -> Result<(), ControlError> {
        self.audio_endpoint(device, audio_sub::MUTE, endpoint, u32::from(muted))
    }

    /// Sets an audio endpoint's trigger output.
    pub fn set_audio_endpoint_trigger(
        &self,
        device: DeviceUid,
        endpoint: u16,
        active: bool,
    ) -> Result<(), ControlError> {
        self.audio_endpoint(device, audio_sub::TRIGGER, endpoint, u32::from(active))
    }

    /// Locks or unlocks the audio source of an audio endpoint: while it is
    /// locked, a video route change leaves the endpoint's audio source alone.
    ///
    /// Refused unless the endpoint reports
    /// [`AudioFeatures::AUDIO_LOCK`], which
    /// is the only one the device acts on. The device reports its endpoints
    /// again once the lock has changed;
    /// [`AudioEndpoints::status`](crate::AudioEndpoints::status) reads it.
    pub fn set_audio_endpoint_locked(
        &self,
        device: DeviceUid,
        endpoint: u8,
        locked: bool,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            let Some(endpoints) = d.audio.as_ref() else {
                return Err(ControlError::NotReported("the device's audio endpoints"));
            };
            if !endpoints
                .get(endpoint)
                .is_some_and(|ep| ep.features.has(AudioFeatures::AUDIO_LOCK))
            {
                return Err(ControlError::Unsupported(
                    "the endpoint cannot lock its audio source",
                ));
            }
            let mut payload = audio_cmd_header(audio_sub::LOCK, d.uid);
            payload.extend_from_slice(&audio_param(u16::from(endpoint), u32::from(locked)));
            Ok(Command::new(Addressee::device(d), op::V2IP_AUDIO, payload))
        })
    }

    /// Sets an audio endpoint's volume.
    ///
    /// **The audio module has no receiver for this command and ignores it.**
    /// It builds and sends the same shape as
    /// [`Self::set_audio_endpoint_muted`], and the send succeeds, because
    /// nothing on these paths is acknowledged - so a caller sees success and no
    /// change. The module dispatches this sub-command to the branch it uses for
    /// one it does not recognise.
    ///
    /// It is kept because the command is defined and the module transmits it
    /// itself, so a receiver may appear; read the endpoint back rather than
    /// assuming either way.
    pub fn set_audio_endpoint_volume(
        &self,
        device: DeviceUid,
        endpoint: u16,
        volume: u32,
    ) -> Result<(), ControlError> {
        self.audio_endpoint(device, audio_sub::VOLUME, endpoint, volume)
    }

    fn audio_endpoint(
        &self,
        device: DeviceUid,
        sub: u16,
        endpoint: u16,
        value: u32,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let device = device_of(state, device)?;
            let mut payload = audio_cmd_header(sub, device.uid);
            payload.extend_from_slice(&audio_param(endpoint, value));
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_AUDIO,
                payload,
            ))
        })
    }

    /// Routes a source endpoint on one device to a sink endpoint on another.
    pub fn select_audio_endpoint_input(
        &self,
        sink: DeviceUid,
        sink_endpoint: u16,
        source: DeviceUid,
        source_endpoint: u16,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let device = device_of(state, sink)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_AUDIO,
                build_audio_select_input(sink, sink_endpoint, source, source_endpoint),
            ))
        })
    }

    // ---- the whole device ----

    /// Starts or stops a V2IP device reporting its transport statistics.
    ///
    /// There is no free-running mode: a device reports only while a
    /// subscription is live, at 1Hz, and the subscription lapses after a
    /// minute. A caller that wants a continuous feed re-sends inside the
    /// minute; nothing here re-arms it.
    ///
    /// Reports reach [`crate::EventHandler::on_v2ip_stats_changed`] and read
    /// back through [`Remote::v2ip_stats`]. A device new enough to send it also
    /// carries what the sink's decoder recovered, in
    /// [`crate::V2ipDeviceStats::decoder`].
    pub fn subscribe_v2ip_stats(
        &self,
        device: DeviceUid,
        subscribe: bool,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let device = device_of(state, device)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_STATS,
                build_stats_request(device.uid, subscribe),
            ))
        })
    }

    /// Asks a device for an EDID: the one the display on its output
    /// publishes, or the one it presents to the source on its input.
    ///
    /// The device answers with a frame the receive path decodes, so the bytes
    /// arrive at [`crate::EventHandler::on_edid_received`] and stay readable
    /// through [`Remote::edid`].
    ///
    /// Only V2IP hardware handles this opcode. A matrix or an amplifier
    /// accepts the frame and answers nothing, at any protocol version, so the
    /// silence that follows is permanent rather than a reply still to come.
    /// This call cannot tell the two apart and does not try: it reports what
    /// was sent, and a caller polling for an EDID should ask a device that can
    /// answer rather than wait on one that cannot.
    pub fn request_edid(&self, device: DeviceUid, output: bool) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let device = device_of(state, device)?;
            Ok(Command::new(
                Addressee::device(device),
                op::DEV_EDID,
                build_edid_request(device.uid, output),
            ))
        })
    }

    /// Asks for a detailed signal report from every bay of one device, or -
    /// with no device named - from every bay on the network.
    ///
    /// Devices report on their own when a signal changes, so this is what a
    /// client that has just started needs: without it, a bay that has been
    /// showing the same picture for an hour says nothing until it changes.
    pub fn request_signal_status(&self, device: Option<DeviceUid>) -> Result<(), ControlError> {
        let Some(device) = device else {
            self.shared
                .send(&Addressee::Broadcast, op::BAY_SIGNAL_STATUS, &[])?;
            return Ok(());
        };
        self.shared.command(move |state| {
            let device = device_of(state, device)?;
            Ok(Command::new(
                Addressee::device(device),
                op::BAY_SIGNAL_STATUS,
                build_target_only(device.uid),
            ))
        })
    }

    /// Reboots a device.
    ///
    /// The device is marked as rebooting once the frame is away, so the
    /// silence that follows does not read as one that went offline. A device
    /// on protocol 0x2C or later takes it only from its mesh controller or a
    /// management application, which this client announces itself as.
    pub fn reboot(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            Ok(Command::new(
                Addressee::device(d),
                op::SYS_REBOOT,
                build_target_only(d.uid),
            )
            .then(move |state, _| {
                if let Some(d) = state.device_mut(device) {
                    d.rebooting = true;
                }
            }))
        })
    }

    /// Asks a device to announce itself now.
    ///
    /// Its hello marks it online again, so a device suspected to be gone is
    /// confirmed or ruled out within a second or two rather than at the end of
    /// its silence window. A device that stays silent is not taken offline
    /// here: that remains the silence window's call.
    pub fn ping(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            Ok(Command::new(
                Addressee::device(d),
                op::SYS_PING,
                build_target_only(d.uid),
            ))
        })
    }

    /// Hands a V2IP source's stream addresses back to automatic assignment,
    /// undoing addresses that were set on it by hand.
    ///
    /// The device takes this only from management, which this client
    /// announces itself as. Nothing acknowledges it: the device's next
    /// configuration report carries the addresses it ends up with, and
    /// [`Remote::v2ip_details`] reads them.
    ///
    /// Refused for a device that is not a V2IP source, and for one below
    /// protocol 0x2B, which predates the operation and ignores it.
    pub fn auto_assign_v2ip_source_addresses(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            if !d.hello.features.has(DeviceFeature::V2IP_SOURCE) {
                return Err(ControlError::Unsupported("the device is not a V2IP source"));
            }
            let have = d.hello.supported_protocol;
            if have != 0 && have < AUTO_ADDRESSES_PROTOCOL {
                return Err(ControlError::Send(SendError::ProtocolTooOld {
                    serial: d.serial().to_owned(),
                    opcode: op::MESH_OPERATION.0,
                    have,
                    need: AUTO_ADDRESSES_PROTOCOL,
                }));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::MESH_OPERATION,
                build_mesh_operation(mesh_op::AUTO_ADDRESSES, d.uid),
            ))
        })
    }

    // ---- units ----

    /// Clears a unit's current system status.
    ///
    /// The terms of [`Remote::upgrade_unit_fpga`] apply.
    pub fn clear_unit_status(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.unit_command(
            device,
            UnitCommandKind::CLEAR_STATUS,
            UnitCommandFlag::NONE,
            None,
        )
    }

    /// Upgrades a unit's video processor to the latest image it holds, or
    /// flashes that image again when `force` is set and it already runs it.
    ///
    /// The unit takes a command only from its mesh controller or a management
    /// application, which this client announces itself as. Nothing
    /// acknowledges it: [`Remote::unit_status`] reads what the unit reports
    /// next. Refused for a device that is not a V2IP unit, and for one below
    /// protocol 0x2C, which predates the command.
    pub fn upgrade_unit_fpga(&self, device: DeviceUid, force: bool) -> Result<(), ControlError> {
        let flags = if force {
            UnitCommandFlag::FORCE
        } else {
            UnitCommandFlag::NONE
        };
        self.unit_command(device, UnitCommandKind::FPGA_UPGRADE, flags, None)
    }

    /// Switches a unit to an IP configuration from DHCP.
    ///
    /// The terms of [`Remote::set_unit_network`] apply.
    pub fn set_unit_dhcp(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.unit_command(
            device,
            UnitCommandKind::NET_CONFIG,
            UnitCommandFlag::DHCP,
            Some(UnitNetConfig::default()),
        )
    }

    /// Gives a unit a static IP configuration.
    ///
    /// The address must be one a unit can hold and the netmask a run of ones
    /// from the top; anything else is refused before it is sent.
    ///
    /// The unit applies the change at once and reverts it unless its mesh
    /// controller, hearing the unit report it, confirms it in time.
    /// [`UnitStatus::network_pending`](crate::UnitStatus::network_pending) says
    /// whether it still waits, and
    /// [`Remote::confirm_unit_network`] confirms it. Otherwise as
    /// [`Remote::upgrade_unit_fpga`].
    pub fn set_unit_network(
        &self,
        device: DeviceUid,
        network: UnitNetConfig,
    ) -> Result<(), ControlError> {
        if !network.is_valid() {
            return Err(ControlError::InvalidRequest(
                "not an address and netmask a unit can hold",
            ));
        }
        self.unit_command(
            device,
            UnitCommandKind::NET_CONFIG,
            UnitCommandFlag::NONE,
            Some(network),
        )
    }

    /// Keeps a unit's pending IP configuration, as its mesh controller does
    /// when it hears the unit at its new address.
    ///
    /// The terms of [`Remote::upgrade_unit_fpga`] apply.
    pub fn confirm_unit_network(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.unit_command(
            device,
            UnitCommandKind::NET_CONFIRM,
            UnitCommandFlag::NONE,
            None,
        )
    }

    /// The one send behind the unit command methods.
    fn unit_command(
        &self,
        device: DeviceUid,
        command: UnitCommandKind,
        flags: UnitCommandFlag,
        network: Option<UnitNetConfig>,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            if !d.is_v2ip() {
                return Err(ControlError::Unsupported("the device is not a V2IP unit"));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::SYS_UNIT_COMMAND,
                build_unit_command(d.uid, command, flags, network.as_ref()),
            ))
        })
    }

    /// Sets the time zone of every device that hears it.
    ///
    /// `zone` is an IANA name such as `Europe/Amsterdam` and `rule` the POSIX
    /// TZ rule the devices keep time by, such as `CET-1CEST,M3.5.0,M10.5.0/3`.
    /// A device applies the rule and shows the name.
    /// Neither may be empty, hold a NUL, or be longer than its field on the
    /// wire leaves room for; [`Remote::clear_mesh_time_zone`] sends both empty.
    ///
    /// The mesh controller takes it too, and announces it from then on with
    /// every periodic broadcast. A device takes it only from a management
    /// application or the controller, and this client announces itself as a
    /// management application.
    pub fn set_mesh_time_zone(&self, zone: &str, rule: &str) -> Result<(), ControlError> {
        let fits = |s: &str, len: usize| !s.is_empty() && s.len() < len && !s.contains('\0');
        if !fits(zone, TIME_ZONE_NAME_LEN) || !fits(rule, TIME_ZONE_RULE_LEN) {
            return Err(ControlError::InvalidRequest(
                "a time zone name or rule is empty, holds a NUL, or is too long",
            ));
        }
        self.shared.send(
            &Addressee::Broadcast,
            op::TIME_ZONE,
            &build_time_zone(zone, rule),
        )?;
        Ok(())
    }

    /// Clears the time zone of every device that hears it, which then keeps
    /// UTC. Sent, received and announced as [`Remote::set_mesh_time_zone`]
    /// with an empty name and rule.
    pub fn clear_mesh_time_zone(&self) -> Result<(), ControlError> {
        self.shared.send(
            &Addressee::Broadcast,
            op::TIME_ZONE,
            &build_time_zone("", ""),
        )?;
        Ok(())
    }

    /// Sets the clock of every device that hears it to `time`.
    ///
    /// A device keeps its own clock where that is within 2s of `time`. It takes
    /// the time only from a management application or the controller; see
    /// [`Remote::set_mesh_time_zone`]. A time before 1970 or past what 32 bits
    /// of seconds hold, in 2106, is refused.
    pub fn set_mesh_time(&self, time: SystemTime) -> Result<(), ControlError> {
        let utc = time
            .duration_since(UNIX_EPOCH)
            .ok()
            .and_then(|d| u32::try_from(d.as_secs()).ok())
            .ok_or(ControlError::InvalidRequest(
                "the time does not fit the frame",
            ))?;
        self.shared
            .send(&Addressee::Broadcast, op::TIME, &utc.to_le_bytes())?;
        Ok(())
    }

    /// Asks every peer to report its monitoring data now rather than on its own
    /// schedule.
    pub fn send_monitoring_pulse(&self) -> Result<(), ControlError> {
        self.shared
            .send(&Addressee::Broadcast, op::SYS_MONITORING_PULSE, &[])?;
        Ok(())
    }

    // ---- V2IP scaling ----

    /// Turns a V2IP sink's automatic scaling on or off.
    ///
    /// Automatic scaling and a configured output mode are separate reasons for
    /// a sink to scale, and this moves only the first: a sink with a mode
    /// configured goes on scaling to it with automatic scaling off. Turning
    /// both off is this call plus [`Remote::clear_v2ip_output_mode`].
    ///
    /// Nothing acknowledges the frame. Read the sink back through
    /// [`Remote::v2ip_details`] to learn what it did, and treat the block as
    /// meaningful only where [`crate::DeviceInfo::config_initialised`] is set.
    /// **Read any route you still need before writing.** The sink rebuilds
    /// and rebroadcasts its subscription in response, and that report can
    /// arrive empty for up to a minute; [`crate::DeviceV2ipSink`] says when
    /// and why.
    pub fn set_v2ip_auto_scaling(
        &self,
        device: DeviceUid,
        enabled: bool,
    ) -> Result<(), ControlError> {
        let written = if enabled {
            SCALING_FLAG_OPTIONS_VALID | SCALING_FLAG_AUTO_SCALING
        } else {
            SCALING_FLAG_OPTIONS_VALID
        };
        self.set_v2ip_scaling(device, MxrSignalType::NONE, 0, written, move |cached| {
            V2ipScalingSettings {
                flags: (cached.flags & !SCALING_FLAG_AUTO_SCALING)
                    | SCALING_FLAG_OPTIONS_VALID
                    | (written & SCALING_FLAG_AUTO_SCALING),
                ..cached
            }
        })
    }

    /// Sets the output format a V2IP sink scales to.
    ///
    /// The mode is checked here and nothing is sent if it fails, because every
    /// value a sink refuses it refuses in silence. Passing that check is not a
    /// guarantee: the sink also weighs the format against the display's EDID
    /// and against what its own output stage can produce.
    ///
    /// **Turn automatic scaling off first if it is on.** A sink refuses a mode
    /// whose format the attached display does not list while it is scaling
    /// automatically, and refuses it silently. Setting a mode and then turning
    /// automatic scaling back on is the order that survives, because the mode
    /// is checked while automatic scaling is still off.
    ///
    /// Configuring a mode is itself a reason to scale, so a sink with one
    /// scales whether or not automatic scaling is on.
    ///
    /// **Pass a descriptor and a refresh rate that agree.** A sink stores both
    /// halves and, with its match-source setting on as it ships, reports back
    /// the descriptor matching the refresh it holds: a 60Hz descriptor written
    /// with a refresh of 50 reads back as that descriptor's 50Hz sibling, once,
    /// and stays there. A sink with match-source off reports the descriptor it
    /// was given. Either way a pair that agrees reads back unchanged, and the
    /// format driven is the same - so this costs a caller nothing except a
    /// descriptor it did not write. That substitution shows up on the sink's
    /// next report rather than immediately, because
    /// [`crate::V2ipScalingSettings`] holds what was written until then.
    ///
    /// A mode read from the sink's own web interface is not interchangeable
    /// with this pair. That interface reports the descriptor's 60Hz sibling and
    /// carries the refresh in a field of its own, so writing back what it shows
    /// as the mode, on its own, changes the setting rather than restoring it.
    /// **Read any route you still need before writing.** The sink rebuilds
    /// and rebroadcasts its subscription in response, and that report can
    /// arrive empty for up to a minute; [`crate::DeviceV2ipSink`] says when
    /// and why.
    pub fn set_v2ip_output_mode(
        &self,
        device: DeviceUid,
        mode: V2ipOutputMode,
    ) -> Result<(), ControlError> {
        mode.validate().map_err(ControlError::InvalidRequest)?;
        let signal = mode.to_signal_type();
        let refresh = mode.refresh;
        self.set_v2ip_scaling(
            device,
            signal,
            refresh,
            SCALING_FLAG_MODE_VALID,
            move |cached| V2ipScalingSettings {
                mode: signal,
                refresh,
                flags: cached.flags | SCALING_FLAG_MODE_VALID,
            },
        )
    }

    /// Clears the output format a V2IP sink is configured to scale to.
    ///
    /// The sink stops scaling for that reason and keeps its automatic scaling
    /// setting, so a sink scaling for both reasons goes on scaling until
    /// [`Remote::set_v2ip_auto_scaling`] turns the other one off.
    ///
    /// This is the only way to express "no mode configured", and it is what a
    /// caller restoring a sink that had none has to send: a sink reports no
    /// mode by leaving the mode's valid bit clear, which is not something a
    /// write can say.
    /// **Read any route you still need before writing.** The sink rebuilds
    /// and rebroadcasts its subscription in response, and that report can
    /// arrive empty for up to a minute; [`crate::DeviceV2ipSink`] says when
    /// and why.
    pub fn clear_v2ip_output_mode(&self, device: DeviceUid) -> Result<(), ControlError> {
        // The valid bit with a zero descriptor is the clear. The receiver takes
        // that branch ahead of validating anything, and ignores the depth,
        // colour space and refresh rate beside it.
        self.set_v2ip_scaling(
            device,
            MxrSignalType::NONE,
            0,
            SCALING_FLAG_MODE_VALID,
            |cached| V2ipScalingSettings {
                mode: MxrSignalType::NONE,
                refresh: 0,
                flags: cached.flags & !SCALING_FLAG_MODE_VALID,
            },
        )
    }

    /// The one send behind the scaling methods.
    ///
    /// `written` is the flag byte that goes out, and `applied` says what the
    /// sink will report afterwards. The two differ where the wire spells a
    /// write differently from the state it produces - clearing a mode is sent
    /// as the valid bit over a zero mode and read back as the valid bit clear -
    /// so predicting the cached value from the frame alone would leave a
    /// caller reading a state no device ever broadcasts.
    fn set_v2ip_scaling(
        &self,
        device: DeviceUid,
        mode: MxrSignalType,
        refresh: u16,
        written: u8,
        applied: impl FnOnce(V2ipScalingSettings) -> V2ipScalingSettings + Send + 'static,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            if !d.is_v2ip_sink() {
                return Err(ControlError::Unsupported(
                    "scaling settings need a V2IP sink",
                ));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::V2IP_DEVICE_CFG,
                build_v2ip_scaling(d.uid, mode, refresh, written),
            )
            .then(move |state, ev| {
                if let Some(d) = state.device_mut(device) {
                    let cached = d.v2ip_scaling();
                    d.set_v2ip_scaling(applied(cached), ev);
                }
            }))
        })
    }

    // ---- V2IP device settings ----

    /// Switches on/off settings of a V2IP device, all to the same value.
    ///
    /// `setting` names one or more of [`V2ipDeviceSetting::SWITCHES`], and
    /// each must be one the device has reported: a device ignores a setting it
    /// does not have, so a write for one would read back as applied here and
    /// change nothing there.
    ///
    /// Nothing acknowledges the frame. The device answers by reporting its
    /// settings, and until then [`Remote::v2ip_device_settings`] reads back
    /// what was written.
    pub fn set_v2ip_device_setting(
        &self,
        device: DeviceUid,
        setting: V2ipDeviceSetting,
        enabled: bool,
    ) -> Result<(), ControlError> {
        if setting.is_empty() || !setting.without(V2ipDeviceSetting::SWITCHES).is_empty() {
            return Err(ControlError::InvalidRequest(
                "only on/off device settings are switched",
            ));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: setting,
                flags: if enabled {
                    setting
                } else {
                    V2ipDeviceSetting::NONE
                },
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets the infrared profile of a V2IP device's global infrared port.
    ///
    /// `profile` is below [`V2IP_IR_PROFILE_MAX`], and is checked here because
    /// a device ignores one out of range. The terms of
    /// [`Remote::set_v2ip_device_setting`] apply.
    pub fn set_v2ip_ir_profile(&self, device: DeviceUid, profile: i8) -> Result<(), ControlError> {
        if !(0..V2IP_IR_PROFILE_MAX).contains(&profile) {
            return Err(ControlError::InvalidRequest("no such infrared profile"));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::IR_PROFILE,
                ir_profile: profile,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets the infrared profile of a V2IP device's output infrared port.
    ///
    /// [`V2IP_IR_PROFILE_NOT_SET`] makes the port follow the global one.
    /// Otherwise as [`Remote::set_v2ip_ir_profile`].
    pub fn set_v2ip_sink_ir_profile(
        &self,
        device: DeviceUid,
        profile: i8,
    ) -> Result<(), ControlError> {
        if !(V2IP_IR_PROFILE_NOT_SET..V2IP_IR_PROFILE_MAX).contains(&profile) {
            return Err(ControlError::InvalidRequest("no such infrared profile"));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::IR_PROFILE_SINK,
                ir_profile_sink: profile,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets how many idle minutes a V2IP device waits before it powers down by
    /// itself, 0 for never. The terms of [`Remote::set_v2ip_device_setting`]
    /// apply.
    pub fn set_v2ip_auto_power_save(
        &self,
        device: DeviceUid,
        minutes: u16,
    ) -> Result<(), ControlError> {
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::AUTO_POWER_SAVE,
                auto_power_save: minutes,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets a V2IP device's daily power save windows.
    ///
    /// Every time is below [`V2IP_MINUTES_PER_DAY`](crate::V2IP_MINUTES_PER_DAY),
    /// and is checked here.
    /// The windows are kept in the device's own time zone. The terms of
    /// [`Remote::set_v2ip_device_setting`] apply.
    pub fn set_v2ip_power_save_schedule(
        &self,
        device: DeviceUid,
        schedule: V2ipPowerSaveSchedule,
    ) -> Result<(), ControlError> {
        if !schedule.is_valid() {
            return Err(ControlError::InvalidRequest(
                "a power save time is not a time of day",
            ));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::POWER_SAVE_SCHEDULE,
                power_save: schedule,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets the PTP mode a V2IP device runs. The terms of
    /// [`Remote::set_v2ip_device_setting`] apply.
    pub fn set_v2ip_ptp_mode(
        &self,
        device: DeviceUid,
        mode: V2ipPtpMode,
    ) -> Result<(), ControlError> {
        if mode > V2ipPtpMode::AUTO {
            return Err(ControlError::InvalidRequest("no such PTP mode"));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::PTP_MODE,
                ptp_mode: mode,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets the PTP domain a V2IP device runs in, at most
    /// [`V2IP_PTP_DOMAIN_MAX`](crate::V2IP_PTP_DOMAIN_MAX). The terms of
    /// [`Remote::set_v2ip_device_setting`] apply.
    pub fn set_v2ip_ptp_domain(&self, device: DeviceUid, domain: u8) -> Result<(), ControlError> {
        if domain > V2IP_PTP_DOMAIN_MAX {
            return Err(ControlError::InvalidRequest("no such PTP domain"));
        }
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::PTP_DOMAIN,
                ptp_domain: domain,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Sets the priority1 a V2IP device announces as a PTP grandmaster, lower
    /// winning. The terms of [`Remote::set_v2ip_device_setting`] apply.
    pub fn set_v2ip_ptp_priority1(
        &self,
        device: DeviceUid,
        priority1: u8,
    ) -> Result<(), ControlError> {
        self.set_v2ip_device_settings(
            device,
            V2ipDeviceSettings {
                valid: V2ipDeviceSetting::PTP_PRIORITY1,
                ptp_priority1: priority1,
                ..V2ipDeviceSettings::default()
            },
        )
    }

    /// Changes settings on every V2IP device of the mesh with one frame.
    ///
    /// `settings` carries the settings behind their bits in
    /// [`valid`](V2ipDeviceSettings::valid), as a device reports them. Each
    /// device applies those it has and ignores the rest, and none that
    /// predates the frame applies any. A setting only a device reports about
    /// itself, a profile, PTP mode or PTP domain out of range and a schedule
    /// time that is not a time of day are refused here, since every device
    /// would ignore them.
    ///
    /// Nothing is cached: each device that applies a change reports its
    /// settings, and [`Remote::v2ip_device_settings`] reads that.
    pub fn set_all_v2ip_device_settings(
        &self,
        settings: V2ipDeviceSettings,
    ) -> Result<(), ControlError> {
        let valid = settings.valid;
        if valid.is_empty() {
            return Err(ControlError::InvalidRequest("no setting is carried"));
        }
        if !(valid & V2ipDeviceSetting::REPORTED_ONLY).is_empty() {
            return Err(ControlError::InvalidRequest(
                "a setting only a device reports is carried",
            ));
        }
        if valid.has(V2ipDeviceSetting::IR_PROFILE)
            && !(0..V2IP_IR_PROFILE_MAX).contains(&settings.ir_profile)
        {
            return Err(ControlError::InvalidRequest("no such infrared profile"));
        }
        if valid.has(V2ipDeviceSetting::IR_PROFILE_SINK)
            && !(V2IP_IR_PROFILE_NOT_SET..V2IP_IR_PROFILE_MAX).contains(&settings.ir_profile_sink)
        {
            return Err(ControlError::InvalidRequest("no such infrared profile"));
        }
        if valid.has(V2ipDeviceSetting::POWER_SAVE_SCHEDULE) && !settings.power_save.is_valid() {
            return Err(ControlError::InvalidRequest(
                "a power save time is not a time of day",
            ));
        }
        if valid.has(V2ipDeviceSetting::PTP_MODE) && settings.ptp_mode > V2ipPtpMode::AUTO {
            return Err(ControlError::InvalidRequest("no such PTP mode"));
        }
        if valid.has(V2ipDeviceSetting::PTP_DOMAIN) && settings.ptp_domain > V2IP_PTP_DOMAIN_MAX {
            return Err(ControlError::InvalidRequest("no such PTP domain"));
        }
        self.shared.send(
            &Addressee::Broadcast,
            op::V2IP_SETTINGS_ALL,
            &build_v2ip_settings_all(&settings),
        )?;
        Ok(())
    }

    /// The one send behind the device settings methods.
    fn set_v2ip_device_settings(
        &self,
        device: DeviceUid,
        settings: V2ipDeviceSettings,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            let Some(reported) = d.v2ip_settings else {
                return Err(ControlError::NotReported("the device's settings"));
            };
            if !reported.valid.has(settings.valid) {
                return Err(ControlError::Unsupported(
                    "the device does not have this setting",
                ));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::V2IP_DEVICE_CFG,
                build_v2ip_device_settings(d.uid, &settings),
            )
            .then(move |state, ev| {
                if let Some(d) = state.device_mut(device) {
                    d.merge_v2ip_settings(settings, ev);
                }
            }))
        })
    }

    // ---- V2IP VLAN ----

    /// Changes a V2IP device's VLAN configuration.
    ///
    /// Writes the VLAN ids, the pinned uplink and the
    /// [`TRUNK`](V2ipVlanFlag::TRUNK) flag of `vlan`; its other flags and the
    /// fields only the device reports are not sent. Refused before anything is
    /// sent unless the device announces [`DeviceFeature::VLAN`] and has
    /// reported its configuration, every id is at most
    /// [`V2IP_VLAN_ID_MAX`](crate::V2IP_VLAN_ID_MAX), and the uplink is
    /// detected or names a port the device has.
    ///
    /// The device applies the change at once and reverts it unless the mesh
    /// controller, hearing the device report it, confirms it. Nothing is
    /// cached here: [`Remote::v2ip_vlan`] reads what the device reports, and
    /// [`V2ipVlan::is_pending`] whether it is still to be confirmed.
    pub fn set_v2ip_vlan(&self, device: DeviceUid, vlan: V2ipVlan) -> Result<(), ControlError> {
        if !vlan.is_valid() {
            return Err(ControlError::InvalidRequest(
                "a VLAN id is out of range or the uplink names no port",
            ));
        }
        let written = V2ipVlan {
            flags: V2ipVlanFlag::VALID | (vlan.flags & V2ipVlanFlag::TRUNK),
            device: vlan.device,
            port: vlan.port,
            uplink: vlan.uplink,
            active_uplink: 0,
            revert_s: 0,
        };
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            if !d.hello.features.has(DeviceFeature::VLAN) {
                return Err(ControlError::Unsupported("the device does not take VLANs"));
            }
            let Some(reported) = d.v2ip_vlan else {
                return Err(ControlError::NotReported("the device's VLAN configuration"));
            };
            if written.pinned_uplink() == Some(V2IP_VLAN_PORT_SFP) && !reported.has_sfp() {
                return Err(ControlError::Unsupported("the device has no SFP port"));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::V2IP_DEVICE_CFG,
                build_v2ip_vlan(d.uid, &written),
            ))
        })
    }

    // ---- V2IP test card ----

    /// Asks a V2IP sink for its test card, which it reports straight back;
    /// [`Remote::v2ip_testcard`] reads it.
    ///
    /// Refused unless the sink's video processor has reported
    /// [`SINK_TEST_PATTERN`](V2ipFpgaFeature::SINK_TEST_PATTERN). A sink with
    /// that feature but without the module that draws the test card does not
    /// answer.
    pub fn request_v2ip_testcard(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.send_v2ip_testcard(device, testcard_type::REQUEST, 0, V2ipTestcard::default())
    }

    /// Shows a test pattern on a V2IP sink's output, or none for
    /// [`V2ipTestPattern::OFF`]. `colour` is `0xRRGGBB`, used by
    /// [`V2ipTestPattern::FLAT`].
    ///
    /// A pattern runs until it is turned off, and holds the output on while it
    /// does. The sink reports its test card in answer. Refused as
    /// [`Remote::request_v2ip_testcard`] is, and for a pattern this library
    /// does not name or a colour above `0xFFFFFF`.
    pub fn set_v2ip_test_pattern(
        &self,
        device: DeviceUid,
        pattern: V2ipTestPattern,
        colour: u32,
    ) -> Result<(), ControlError> {
        if pattern.to_wire() > V2ipTestPattern::CARD.to_wire() || colour > 0x00FF_FFFF {
            return Err(ControlError::InvalidRequest(
                "no such test pattern, or a colour wider than 24 bits",
            ));
        }
        self.send_v2ip_testcard(
            device,
            testcard_type::SET,
            testcard_part::PATTERN,
            V2ipTestcard {
                pattern,
                colour,
                ..V2ipTestcard::default()
            },
        )
    }

    /// Plays a test tone on a V2IP sink's output.
    ///
    /// Every value is checked here, as the sink ignores a tone that is not
    /// [`V2ipTestTone::is_valid`]; [`V2ipToneMode::OFF`] stops it whatever the
    /// rest holds, and the sink keeps those values as its last ones. Otherwise
    /// as [`Remote::set_v2ip_test_pattern`].
    pub fn set_v2ip_test_tone(
        &self,
        device: DeviceUid,
        tone: V2ipTestTone,
    ) -> Result<(), ControlError> {
        if tone.mode != V2ipToneMode::OFF && !tone.is_valid() {
            return Err(ControlError::InvalidRequest(
                "a test tone value is out of range",
            ));
        }
        self.send_v2ip_testcard(
            device,
            testcard_type::SET,
            testcard_part::TONE,
            V2ipTestcard {
                tone,
                ..V2ipTestcard::default()
            },
        )
    }

    /// Sets a V2IP sink's lip-sync flash.
    ///
    /// Checked here as [`V2ipTestSync::is_valid`], since the sink ignores
    /// settings that are not. Otherwise as [`Remote::set_v2ip_test_pattern`].
    pub fn set_v2ip_test_sync(
        &self,
        device: DeviceUid,
        sync: V2ipTestSync,
    ) -> Result<(), ControlError> {
        if !sync.is_valid() {
            return Err(ControlError::InvalidRequest(
                "a lip-sync value is out of range",
            ));
        }
        self.send_v2ip_testcard(
            device,
            testcard_type::SET,
            testcard_part::SYNC,
            V2ipTestcard {
                sync,
                ..V2ipTestcard::default()
            },
        )
    }

    /// The one send behind the test card methods. Nothing is cached: the sink
    /// answers every frame with its test card.
    fn send_v2ip_testcard(
        &self,
        device: DeviceUid,
        kind: u8,
        parts: u8,
        testcard: V2ipTestcard,
    ) -> Result<(), ControlError> {
        self.shared.command(move |state| {
            let d = device_of(state, device)?;
            let Some(features) = d.v2ip_features else {
                return Err(ControlError::NotReported(
                    "the sink's video processor features",
                ));
            };
            if !features.has(V2ipFpgaFeature::SINK_TEST_PATTERN) {
                return Err(ControlError::Unsupported(
                    "the sink cannot draw a test card",
                ));
            }
            Ok(Command::new(
                Addressee::device(d),
                op::V2IP_TESTCARD,
                build_v2ip_testcard(d.uid, kind, parts, &testcard),
            ))
        })
    }

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

    /// Shows a window on a sink's video wall without persisting it.
    ///
    /// The window survives until the sink is told otherwise or restarts.
    /// [`Remote::revert_video_wall`] puts back whatever was stored.
    ///
    /// Pass [`crate::VIDEO_WALL_CLEARED`] to show the whole frame again.
    pub fn preview_video_wall(
        &self,
        sink: DeviceUid,
        window: VideoWallWindow,
    ) -> Result<(), ControlError> {
        self.set_video_wall(sink, window, VideoWallOp::PREVIEW)
    }

    /// Persists a window as a sink's video wall.
    ///
    /// The geometry is checked here, before anything is sent, because the sink
    /// is not guaranteed to check it. A sink running a video-wall module older
    /// than 2026083100 writes the window to its configuration *before* asking
    /// its video processor to apply it, and the processor's refusal does not
    /// undo that write - so an out-of-spec window survives a reboot and is
    /// re-offered on every stream restart until something else replaces it. A
    /// power cycle does not clear it.
    ///
    /// Nothing acknowledges this frame either way, so an `Ok` says only that
    /// it was sent. Read the sink's state back to learn what it did.
    ///
    /// Pass [`crate::VIDEO_WALL_CLEARED`] to store "show the whole frame".
    pub fn store_video_wall(
        &self,
        sink: DeviceUid,
        window: VideoWallWindow,
    ) -> Result<(), ControlError> {
        self.set_video_wall(sink, window, VideoWallOp::STORE)
    }

    /// Restores the window a sink has stored, discarding a preview.
    ///
    /// Carries no window of its own: the sink already holds the one this puts
    /// back.
    pub fn revert_video_wall(&self, sink: DeviceUid) -> Result<(), ControlError> {
        self.set_video_wall(sink, VIDEO_WALL_CLEARED, VideoWallOp::REVERT)
    }

    /// The one send behind the three video-wall methods.
    ///
    /// Validation sits here rather than in each of them, so an operation added
    /// later cannot reach the wire without it, and is skipped for a revert
    /// because the sink ignores the window on that operation rather than
    /// checking it.
    ///
    /// Passing it is not proof a wall appeared. Two things the sink refuses
    /// afterwards are equally silent: a window it will not draw, which it logs
    /// and drops, and a sink whose image has no tiling support at all, which
    /// takes the window into its own state and then fails to push it to the
    /// hardware. Neither reaches the wire, so read the sink back over HTTP to
    /// learn a window landed.
    fn set_video_wall(
        &self,
        sink: DeviceUid,
        window: VideoWallWindow,
        op: VideoWallOp,
    ) -> Result<(), ControlError> {
        if op != VideoWallOp::REVERT {
            window.validate().map_err(ControlError::InvalidRequest)?;
        }
        self.shared.command(move |state| {
            let device = device_of(state, sink)?;
            Ok(Command::new(
                Addressee::device(device),
                op::V2IP_VIDEO_WALL,
                build_video_wall(device.uid, window, op),
            ))
        })
    }

    // ---- multiviewer ----

    /// Sets the window layout.
    pub fn set_multiviewer_view_mode(
        &self,
        device: DeviceUid,
        mode: MultiviewerViewMode,
    ) -> Result<(), ControlError> {
        let mode = mv_setting(mode.to_wire(), 8, "the multiviewer has no such view mode")?;
        self.multiviewer(device, mv_sub::VIEW_MODE, &[mode])
    }

    /// Assigns a source to one window, counting windows from zero.
    ///
    /// A window index the multiviewer is not currently showing is refused
    /// rather than sent: firmware accepts an index one past the last window
    /// and writes through the end of the array it indexes, so the frame that
    /// would carry it is the one frame this library must never put on the
    /// wire. The bound comes from the layout in the multiviewer's last status
    /// report, so a multiviewer that has reported none can only be given
    /// window zero, which every layout has.
    pub fn set_multiviewer_video_source(
        &self,
        device: DeviceUid,
        screen: u8,
        source: MultiviewerSource,
    ) -> Result<(), ControlError> {
        let source = source_index(source, "the source names no multiviewer input")?;
        self.shared.command(|state| {
            let target = multiviewer_of(state, device)?;
            let windows = target
                .multiviewer
                .as_ref()
                .and_then(MultiviewerStatus::window_count)
                .unwrap_or(1);
            if screen >= windows {
                return Err(ControlError::InvalidRequest(
                    "the window is not one the multiviewer is showing",
                ));
            }
            Ok(mv_command(target, mv_sub::VIDEO_SOURCE, &[screen, source]))
        })
    }

    /// Selects which window's audio is output.
    pub fn set_multiviewer_audio_source(
        &self,
        device: DeviceUid,
        source: MultiviewerSource,
    ) -> Result<(), ControlError> {
        let source = source_index(source, "the audio source names no multiviewer input")?;
        self.multiviewer(device, mv_sub::AUDIO_SOURCE, &[source])
    }

    /// Sets the output volume, as a percentage, and the mute state.
    ///
    /// A volume above 100 is refused rather than sent. What a multiviewer does
    /// with one depends on its module version: from 2026083100 it drops the
    /// whole frame, and before that it dropped the volume alone and still
    /// acted on the mute beside it. Neither is what the caller asked for, and
    /// neither is reported back.
    pub fn set_multiviewer_audio_volume(
        &self,
        device: DeviceUid,
        volume: u8,
        muted: bool,
    ) -> Result<(), ControlError> {
        if volume > 100 {
            return Err(ControlError::InvalidRequest(
                "a multiviewer volume is a percentage",
            ));
        }
        self.multiviewer(device, mv_sub::AUDIO_VOLUME, &[volume, u8::from(muted)])
    }

    /// Sets the EDID template presented to the sources.
    pub fn set_multiviewer_edid_template(
        &self,
        device: DeviceUid,
        template: MultiviewerEdidTemplate,
    ) -> Result<(), ControlError> {
        let template = mv_setting(
            template.to_wire(),
            19,
            "the multiviewer has no such EDID template",
        )?;
        self.multiviewer(device, mv_sub::EDID_TEMPLATE, &[template])
    }

    /// Selects which window receives remote-control passthrough.
    pub fn set_multiviewer_remote_control(
        &self,
        device: DeviceUid,
        source: MultiviewerSource,
    ) -> Result<(), ControlError> {
        let source = source_index(
            source,
            "the remote-control source names no multiviewer input",
        )?;
        self.multiviewer(device, mv_sub::ROUTE_RC, &[source])
    }

    /// Sets how large the picture-in-picture window is.
    pub fn set_multiviewer_pip_size(
        &self,
        device: DeviceUid,
        size: MultiviewerPipSize,
    ) -> Result<(), ControlError> {
        let size = mv_setting(
            size.to_wire(),
            3,
            "the multiviewer has no such picture-in-picture size",
        )?;
        self.multiviewer(device, mv_sub::PIP_SIZE, &[size])
    }

    /// Sets which corner the picture-in-picture window sits in.
    pub fn set_multiviewer_pip_position(
        &self,
        device: DeviceUid,
        position: MultiviewerPipPosition,
    ) -> Result<(), ControlError> {
        let position = mv_setting(
            position.to_wire(),
            4,
            "the multiviewer has no such picture-in-picture position",
        )?;
        self.multiviewer(device, mv_sub::PIP_POSITION, &[position])
    }

    /// Sets the aspect ratio the windows are scaled to.
    pub fn set_multiviewer_aspect_ratio(
        &self,
        device: DeviceUid,
        aspect: MultiviewerAspectRatio,
    ) -> Result<(), ControlError> {
        let aspect = mv_setting(
            aspect.to_wire(),
            2,
            "the multiviewer has no such aspect ratio",
        )?;
        self.multiviewer(device, mv_sub::ASPECT, &[aspect])
    }

    /// Enables or disables switching windows on its own.
    pub fn set_multiviewer_auto_switch(
        &self,
        device: DeviceUid,
        enable: bool,
    ) -> Result<(), ControlError> {
        self.multiviewer(device, mv_sub::AUTO_SWITCH, &[u8::from(enable)])
    }

    /// Sets the output resolution and refresh rate.
    pub fn set_multiviewer_output_mode(
        &self,
        device: DeviceUid,
        mode: MultiviewerOutputMode,
    ) -> Result<(), ControlError> {
        let mode = mv_setting(
            mode.to_wire(),
            14,
            "the multiviewer has no such output mode",
        )?;
        self.multiviewer(device, mv_sub::OUTPUT_MODE, &[mode])
    }

    /// Sets the IT-content flag on the output.
    pub fn set_multiviewer_output_itc(
        &self,
        device: DeviceUid,
        mode: MultiviewerItcMode,
    ) -> Result<(), ControlError> {
        let mode = mv_setting(
            mode.to_wire(),
            2,
            "the multiviewer has no such IT-content mode",
        )?;
        self.multiviewer(device, mv_sub::OUTPUT_ITC_MODE, &[mode])
    }

    /// Sets the HDCP version negotiated on the output.
    pub fn set_multiviewer_hdcp_mode(
        &self,
        device: DeviceUid,
        mode: MultiviewerHdcpMode,
    ) -> Result<(), ControlError> {
        let mode = mv_setting(mode.to_wire(), 3, "the multiviewer has no such HDCP mode")?;
        self.multiviewer(device, mv_sub::HDCP_MODE, &[mode])
    }

    /// Maps a source device onto one of the multiviewer's inputs, counting
    /// inputs from zero.
    ///
    /// [`DeviceUid::ZERO`] clears the mapping on a multiviewer running module
    /// version 2026083100 or newer, and is stored as a mapping like any other
    /// on anything older. No version checks that a mapping names a device on
    /// the mesh.
    ///
    /// Which of the two happened shows in `mappings` on a later status report,
    /// where a cleared input reads as [`DeviceUid::ZERO`] only from that same
    /// version. It will not be the next frame this multiviewer sends: this is
    /// one of the two settings that schedule no status broadcast of their own,
    /// so the answer arrives whenever something else prompts one.
    pub fn set_multiviewer_input_source(
        &self,
        device: DeviceUid,
        input: u8,
        source: DeviceUid,
    ) -> Result<(), ControlError> {
        if usize::from(input) >= MULTIVIEWER_INPUTS {
            return Err(ControlError::InvalidRequest(
                "the multiviewer has no such input",
            ));
        }
        let mut args = Vec::with_capacity(24);
        args.extend_from_slice(source.as_bytes());
        args.push(input);
        // mv_config_source_t is 4-aligned behind its uid, so seven bytes of
        // padding follow the input index.
        args.extend_from_slice(&[0; 7]);
        self.multiviewer(device, mv_sub::CONFIG_SOURCE, &args)
    }

    /// Asks the multiviewer to route its sources itself.
    pub fn multiviewer_auto_route(&self, device: DeviceUid) -> Result<(), ControlError> {
        self.multiviewer(device, mv_sub::AUTO_ROUTE, &[])
    }

    fn multiviewer(&self, device: DeviceUid, sub: u8, args: &[u8]) -> Result<(), ControlError> {
        self.shared
            .command(|state| Ok(mv_command(multiviewer_of(state, device)?, sub, args)))
    }
}