mx-remote-ffi 6.3.0

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

//! What a device reports about one of its subsystems.
//!
//! These are the values that do not fit in a device or bay snapshot: streams,
//! statistics, the audio tree, the network ports. Each has an event that says
//! it moved and a call here that says what it is now, which is why the events
//! carry only an identifier - what they would carry instead is this, and a
//! copy taken at event time could only be staler than a read.
//!
//! A call returns `MXR_ERR_NOT_REPORTED` when the device exists but has not
//! sent that subsystem, which is a different answer from a device that has
//! never been heard from at all.

use std::ffi::c_char;
use std::net::Ipv4Addr;
use std::time::UNIX_EPOCH;

use mx_remote::{
    AmpDolbySettings, AudioEndpoint, DeviceV2ipDetails, DeviceV2ipSink, FirmwareVersion,
    MultiviewerStatus, NetworkPortStatus, RcSettings, StreamKind, TopologyEntry, UtpCableStatus,
    V2ipDecoderDetail, V2ipDeviceSettings, V2ipDeviceStats, V2ipFpgaFeature, V2ipRxStats,
    V2ipStreamSource, V2ipStreamSources, V2ipTestSync, V2ipTestTone, V2ipTestcard,
    V2ipTilingConfig, V2ipToneMode, V2ipTxStats, V2ipVlan, VctStatus, MULTIVIEWER_INPUTS,
};

use crate::abi::{fail, guard, mxr_result_t, mxr_uid_t, put_str};
use crate::control::mxr_audio_format_t;
use crate::info::{copy_into, not_heard_from, null_out, MXR_NAME_LEN, MXR_VERSION_LEN};
use crate::remote::{mxr_remote_t, with, MXR_IP_STRING_LEN};

/// How many inputs a multiviewer has.
///
/// Written as a literal because the generated header needs one, and checked
/// against the core crate's value below so the two cannot drift apart.
pub const MXR_MULTIVIEWER_INPUTS: usize = 4;

const _: () = assert!(MXR_MULTIVIEWER_INPUTS == MULTIVIEWER_INPUTS);

/// How many pairs a UTP cable diagnostic covers.
pub const MXR_UTP_PAIRS: usize = 4;

/// Which of a V2IP device's streams an address describes.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum mxr_stream_kind_t {
    /// The video stream.
    MXR_STREAM_VIDEO = 0,
    /// The audio stream.
    MXR_STREAM_AUDIO = 1,
    /// The ancillary-data stream.
    MXR_STREAM_ANC = 2,
    /// The audio-return stream.
    MXR_STREAM_ARC = 3,
}

impl From<StreamKind> for mxr_stream_kind_t {
    fn from(kind: StreamKind) -> Self {
        match kind {
            StreamKind::Video => Self::MXR_STREAM_VIDEO,
            StreamKind::Audio => Self::MXR_STREAM_AUDIO,
            StreamKind::Anc => Self::MXR_STREAM_ANC,
            StreamKind::Arc => Self::MXR_STREAM_ARC,
        }
    }
}

/// One multicast stream address.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_stream_source_t {
    /// Which stream this address is for.
    pub kind: mxr_stream_kind_t,
    /// The multicast group, as a dotted quad.
    pub ip: [c_char; MXR_IP_STRING_LEN],
    /// The destination UDP port.
    pub port: u16,
    /// Whether this carries a usable address: a multicast group and a non-zero
    /// port, both. A slot a device has not filled in is not an error, so this
    /// is what separates an address from an empty slot.
    pub valid: bool,
}

impl From<V2ipStreamSource> for mxr_stream_source_t {
    fn from(s: V2ipStreamSource) -> Self {
        let mut out = Self {
            kind: s.kind.into(),
            ip: [0; MXR_IP_STRING_LEN],
            port: s.port,
            valid: s.is_valid(),
        };
        put_str(&mut out.ip, &s.ip.to_string());
        out
    }
}

/// The streams one V2IP source advertises.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_stream_sources_t {
    /// The originating device, zero when it is not known.
    pub uid: mxr_uid_t,
    /// The video stream.
    pub video: mxr_stream_source_t,
    /// The audio stream.
    pub audio: mxr_stream_source_t,
    /// The ancillary-data stream.
    pub anc: mxr_stream_source_t,
    /// Whether an audio-return stream is advertised.
    pub has_arc: bool,
    /// The audio-return stream, meaningful only when `has_arc` is set.
    pub arc: mxr_stream_source_t,
}

impl From<V2ipStreamSources> for mxr_stream_sources_t {
    fn from(s: V2ipStreamSources) -> Self {
        Self {
            uid: s.uid.into(),
            video: s.video.into(),
            audio: s.audio.into(),
            anc: s.anc.into(),
            has_arc: s.arc.is_some(),
            arc: s.arc.unwrap_or_default().into(),
        }
    }
}

/// A V2IP device's own encoder configuration.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_details_t {
    /// The video stream this device sources.
    pub video: mxr_stream_source_t,
    /// The audio stream this device sources.
    pub audio: mxr_stream_source_t,
    /// The ancillary-data stream this device sources.
    pub anc: mxr_stream_source_t,
    /// The audio-return stream this device sources.
    pub arc: mxr_stream_source_t,
    /// Encoder rate in units of 10Mb/s, or -1 when no rate has been reported.
    pub tx_rate: i16,
    /// DSCP marking for the video stream, or -1 when unmarked.
    pub dscp_video: i16,
    /// DSCP marking for the audio stream, or -1 when unmarked.
    pub dscp_audio: i16,
    /// DSCP marking for the ancillary-data stream, or -1 when unmarked.
    pub dscp_anc: i16,
    /// The signal type the output scales to.
    pub scaling_mode: u16,
    /// Refresh rate in Hz.
    pub scaling_refresh: u16,
    /// `MXR_SCALING_FLAG_*` bits. Bits outside those are undefined and are not
    /// reliably zero: firmware predating the fix builds this frame over an
    /// uninitialised stack local.
    pub scaling_flags: u8,
}

/// Set when the frame carries a scaling mode and refresh rate.
pub const MXR_SCALING_FLAG_MODE_VALID: u8 = 1 << 0;
/// Set when the frame carries the scaling options.
pub const MXR_SCALING_FLAG_OPTIONS_VALID: u8 = 1 << 1;
/// Set when the frame carries the second group of scaling options.
///
/// Firmware with those options sets this on every configuration it sends about
/// itself, so it doubles as the report that the device has them at all. It is
/// read only from a sender that says it initialises its configuration: on one
/// that does not, this bit is uninitialised stack and the settings behind it
/// would be invented rather than misread.
pub const MXR_SCALING_FLAG_OPTIONS2_VALID: u8 = 1 << 4;
/// Set when the output follows its source's format instead of a fixed one.
pub const MXR_SCALING_FLAG_MATCH_SOURCE: u8 = 1 << 5;
/// Set when the output declines 4:2:0 rather than scaling it.
pub const MXR_SCALING_FLAG_SKIP_420: u8 = 1 << 6;
/// Set when the output scales automatically.
pub const MXR_SCALING_FLAG_AUTO_SCALING: u8 = 1 << 7;

/// The streams a V2IP sink is subscribed to.
///
/// **Addresses that read as unset mean "no route, or the sink could not work
/// one out" - never "definitely not subscribed".** This is the one part of a
/// device configuration with no validity marker of its own, so a sender with
/// nothing to say sends zeros and every receiver stores them. A sender leaves
/// it empty whenever its own stream configuration does not resolve, which
/// covers more than having no route: a selected source whose record has not
/// arrived yet, the state after a restart at either end, missing audio bay
/// configuration, or a stream failing its validity check.
///
/// Expect it rather than guard against it. Any scaling change makes the device
/// rebuild and rebroadcast this block - so the empty reading turns up most
/// often during exactly the no-signal troubleshooting that prompted the change.
/// A device's periodic report puts a real route back within a minute of it
/// having one, so a reader that needs certainty should wait one out rather than
/// treat the first empty reading as an answer.
///
/// Only the device's own report sets this. A controller writing another
/// device's configuration sends the block zeroed, and that frame is ignored.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_sink_t {
    /// The streams the sink subscribes to.
    pub addresses: mxr_stream_sources_t,
    /// Whether the sender reported a resolved audio format.
    pub has_audio_format: bool,
    /// The audio format, meaningful only when `has_audio_format` is set.
    pub audio_format: mxr_audio_format_t,
}

/// Transmitter stream statistics.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_tx_stats_t {
    /// Video packets sent.
    pub video: u32,
    /// Audio packets sent.
    pub audio: u32,
    /// Ancillary-data packets sent.
    pub anc: u32,
    /// Times the stream went down.
    pub stream_down: u32,
    /// Transmit overflows.
    pub overflow: u32,
}

impl From<V2ipTxStats> for mxr_v2ip_tx_stats_t {
    fn from(s: V2ipTxStats) -> Self {
        Self {
            video: s.video,
            audio: s.audio,
            anc: s.anc,
            stream_down: s.stream_down,
            overflow: s.overflow,
        }
    }
}

/// Receiver stream statistics.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_rx_stats_t {
    /// Video packets received.
    pub video_total: u32,
    /// Video packets dropped.
    pub video_dropped: u32,
    /// Video sequence errors.
    pub video_seq_errors: u32,
    /// Watchdog timeouts.
    pub wdt_timeout: u32,
    /// Audio packets received.
    pub audio_total: u32,
    /// Audio packets dropped.
    pub audio_dropped: u32,
    /// Audio sequence errors.
    pub audio_seq_errors: u32,
    /// Ancillary-data packets received.
    pub anc_total: u32,
    /// Ancillary-data packets dropped.
    pub anc_dropped: u32,
    /// Ancillary-data sequence errors.
    pub anc_seq_errors: u32,
    /// The decoder's health state: 0 unknown, 1 healthy, 2 bad, 3 starting.
    ///
    /// Only healthy and bad are verdicts. Reading failure as "not healthy"
    /// counts a decoder that is merely coming up as one that failed, which is
    /// what every sink reports for a moment after a route change.
    pub decoder_state: u8,
}

impl From<V2ipRxStats> for mxr_v2ip_rx_stats_t {
    fn from(s: V2ipRxStats) -> Self {
        Self {
            video_total: s.video_total,
            video_dropped: s.video_dropped,
            video_seq_errors: s.video_seq_errors,
            wdt_timeout: s.wdt_timeout,
            audio_total: s.audio_total,
            audio_dropped: s.audio_dropped,
            audio_seq_errors: s.audio_seq_errors,
            anc_total: s.anc_total,
            anc_dropped: s.anc_dropped,
            anc_seq_errors: s.anc_seq_errors,
            decoder_state: s.decoder_state.to_wire(),
        }
    }
}

/// What a statistics report says about a sink's decoder.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum mxr_v2ip_decoder_detail_t {
    /// The report carried no decoder block: the sender's firmware predates it.
    MXR_V2IP_DECODER_ABSENT = 0,
    /// The block is there and the decoder has never answered.
    MXR_V2IP_DECODER_NEVER_ANSWERED = 1,
    /// The block carries a reading.
    MXR_V2IP_DECODER_ANSWERED = 2,
}

/// What a sink's decoder recovered from the codestream it is being given.
///
/// This is what the decoder understood, read ahead of the scaler: the geometry
/// is unrounded and is not what the display is being sent. Every field but
/// `detail` is zero unless `detail` is `MXR_V2IP_DECODER_ANSWERED`.
///
/// `detail` follows the sink being configured rather than the sink being
/// enabled, so a sink that is switched off still reports - as reason 10, or
/// from an older sender as reason 1, which is the same reading a sink whose
/// source has died produces. Nothing here answers whether a sink is enabled.
///
/// Colour depth is absent on purpose and will stay absent: the video processor
/// answers that from a driver constant rather than from the codestream, so
/// there is no reading to carry. Assert depth at the encoder's input bay
/// instead.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_decoder_t {
    /// Which of the three states this report is in.
    pub detail: mxr_v2ip_decoder_detail_t,
    /// The primary cause of the state the decoder is in, by the sender's own
    /// names: 0 OK, 1 NO_PACKETS, 2 PACKETS_DEGRADED, 3 NO_FORMAT, 4
    /// FORMAT_MISMATCH, 5 FORMAT_REJECTED, 6 DECODER_BLOCKED, 7
    /// SWITCH_PENDING, 8 PTP_UNLOCKED, 9 TX_BRIDGE_UNLOCKED, 10 IDLE.
    /// Firmware adds causes, so an unrecognised value is passed through as it
    /// arrived.
    ///
    /// The primary cause only, and the numbers are identities rather than
    /// ranks: several causes can be true at once and a fixed priority order in
    /// the firmware decides which lands here. Classify on `flags`, which
    /// carries all of them; a test against this field asks which cause won
    /// instead. Reason 10 is the exception and is read here: it outranks the
    /// whole word, and testing it first is what stops a switched-off sink
    /// being reported as broken. Reason 9 is the one most often hidden here —
    /// see `flags`.
    ///
    /// A pending switch is a step in an operation someone asked for rather
    /// than a fault, and PTP unlocked costs audio alone: audio cannot enable
    /// and the picture is unaffected, so reporting it as a fault puts an
    /// overlay over a good picture. Reason 10 says the sink is switched off,
    /// and carries no implication about `width` and `height`: those are read
    /// before any cause is decided, so a switched-off sink still detecting a
    /// codestream reports a real geometry. An older sender reports reason 1
    /// for the same sink, so an absent reason 10 is not evidence a sink is
    /// enabled - nothing here answers that, which comes from
    /// `mxr_v2ip_details()` or the device's HTTP status.
    pub reason: u8,
    /// The converter watchdog is holding the stream back.
    pub blocking: bool,
    /// The recovered picture width, and 0 when none was recovered.
    pub width: u16,
    /// The recovered picture height, and 0 when none was recovered.
    pub height: u16,
    /// The recovered colour space: 0 RGB, 1 YCbCr 4:4:4, 2 YCbCr 4:2:2,
    /// 3 YCbCr 4:2:0, 255 the decoder cannot name it.
    ///
    /// No value here means "no signal": a decoder with nothing to decode
    /// reports 0, which is indistinguishable from a real RGB reading. A zero
    /// `width` or `height` is what says the decoder recovered nothing - which
    /// is not the same as the sink being switched off, and does not imply it. The 255
    /// is its own value rather than the 0xF a signal report uses for an
    /// unknown colour space.
    pub format: u16,
    /// How many readings the sink has stored. Monotonic, wrapping at 65535
    /// after some 36 hours, and never reset.
    ///
    /// A sink reads its video processor every two seconds and reports every
    /// second, so roughly every other report repeats a reading already seen:
    /// a frame arriving says nothing about how fresh the values in it are.
    /// This counter moves only when a reading is stored, so a processor that
    /// stopped answering leaves it still rather than implying a refresh.
    ///
    /// After pointing a sink at something else, wait for this to advance by
    /// two before trusting the geometry. It ticks when a reply lands rather
    /// than when a query is sent, so the first tick can carry an answer the
    /// processor read fractionally before the switch; the second cannot,
    /// because at most one query is outstanding at a time.
    pub updates: u16,
    /// Every cause that applies, as bit N for reason N, where `reason` carries
    /// the primary one. Bit 0 is cleared by the sender, so an empty word means
    /// nothing beyond the primary cause applies.
    ///
    /// This is what to classify on, once reason 10 has been ruled out. That
    /// cause outranks the whole word and leaves the bits below it set - a sink
    /// switched off while running keeps the bits the decoder genuinely saw on
    /// the way down - so a fault mask over `flags` reports a deliberately
    /// disabled sink as broken.
    ///
    /// A cause that is true can be missing from
    /// `reason` and present here: reason 9, the pipeline rebuilding after the
    /// transmitter bridge stayed unlocked, sits below every input-side cause,
    /// so a pipeline restarting in a loop shows an input-side cause in
    /// `reason` and bit 9 here alone - always, rather than briefly. Bit 9
    /// needs a sustained five seconds to appear at all, and sustained across
    /// reports it means a restart loop rather than one event, because the
    /// sender's debounce restarts each time it elapses.
    ///
    /// Reasons 3 and 4 are the two arms of one decision and never appear
    /// together.
    pub flags: u32,
    /// How many times the converter watchdog has triggered.
    pub blocked_count: u32,
}

impl From<V2ipDecoderDetail> for mxr_v2ip_decoder_t {
    fn from(detail: V2ipDecoderDetail) -> Self {
        let empty = Self {
            detail: mxr_v2ip_decoder_detail_t::MXR_V2IP_DECODER_ABSENT,
            reason: 0,
            blocking: false,
            width: 0,
            height: 0,
            format: 0,
            updates: 0,
            flags: 0,
            blocked_count: 0,
        };
        match detail {
            V2ipDecoderDetail::Absent => empty,
            V2ipDecoderDetail::NeverAnswered => Self {
                detail: mxr_v2ip_decoder_detail_t::MXR_V2IP_DECODER_NEVER_ANSWERED,
                ..empty
            },
            V2ipDecoderDetail::Answered(r) => Self {
                detail: mxr_v2ip_decoder_detail_t::MXR_V2IP_DECODER_ANSWERED,
                reason: r.reason.to_wire(),
                blocking: r.blocking,
                width: r.width,
                height: r.height,
                format: r.format.to_wire(),
                updates: r.updates,
                flags: r.flags,
                blocked_count: r.blocked_count,
            },
        }
    }
}

/// A device's V2IP statistics, cumulative and over the last minute.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_stats_t {
    /// Transmit totals since boot.
    pub tx: mxr_v2ip_tx_stats_t,
    /// Transmit counts over the last minute.
    pub tx_per_minute: mxr_v2ip_tx_stats_t,
    /// Receive totals since boot.
    pub rx: mxr_v2ip_rx_stats_t,
    /// Receive counts over the last minute.
    pub rx_per_minute: mxr_v2ip_rx_stats_t,
    /// What the sink's decoder recovered from the codestream it is decoding.
    pub decoder: mxr_v2ip_decoder_t,
}

/// The window a sink is currently told to show.
///
/// This is the pollable view of a sink's window, not the persisted video wall
/// setting: on a sink running the wall module a write here is transient,
/// because that module pushes its own target window back within about a
/// second.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_tiling_config_t {
    /// The sink this window belongs to.
    pub target: mxr_uid_t,
    /// Window origin, horizontal.
    pub pos_x: u16,
    /// Window origin, vertical.
    pub pos_y: u16,
    /// Window width.
    pub width: u16,
    /// Window height.
    pub height: u16,
}

/// What a multiviewer reports about itself.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_multiviewer_status_t {
    /// The multiviewer.
    pub uid: mxr_uid_t,
    /// The source device mapped to each input.
    pub mappings: [mxr_uid_t; MXR_MULTIVIEWER_INPUTS],
    /// The MCU firmware version.
    pub mcu_version: [c_char; MXR_NAME_LEN],
    /// The scaler firmware version.
    pub scaler_version: [c_char; MXR_NAME_LEN],
    /// The view mode the hardware reports, which is its own numbering rather
    /// than `view_mode`'s.
    pub hw_view_mode: u8,
    /// The window layout.
    pub view_mode: u8,
    /// Which corner the picture-in-picture window sits in.
    pub pip_position: u8,
    /// The size of the picture-in-picture window.
    pub pip_size: u8,
    /// The output resolution.
    pub output_mode: u8,
    /// The HDCP mode.
    pub hdcp_mode: u8,
    /// The IT content flag.
    pub output_itc: u8,
    /// The EDID presented to sources.
    pub edid_template: u8,
    /// How a source is fitted into its window.
    pub aspect_ratio: u8,
    /// Whether automatic source switching is on.
    pub auto_switch: u8,
    /// Which window the audio is taken from.
    pub audio_source: u8,
    /// Whether a volume has been reported.
    pub has_audio_volume: bool,
    /// The output volume.
    pub audio_volume: u8,
    /// Whether the output is muted.
    pub audio_muted: u8,
    /// The source shown in each window.
    pub video_sources: [u8; MXR_MULTIVIEWER_INPUTS],
    /// Which window remote control is forwarded to.
    pub remote_control: u8,
}

/// One node of a device's audio tree.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_audio_endpoint_t {
    /// The endpoint's identifier on its device.
    pub id: u8,
    /// What the endpoint can do, as `MXR_AUDIO_*` bits.
    pub features: u32,
    /// Whether the endpoint carries a stream address.
    pub has_address: bool,
    /// The stream address, meaningful only when `has_address` is set.
    pub address: mxr_stream_source_t,
    /// The endpoint this one hangs off, or -1 at a root.
    pub parent: i16,
    /// How many children this endpoint has; read them with
    /// `mxr_audio_endpoint_children()`.
    pub child_count: usize,
    /// Whether the device reported which inputs are selectable.
    pub has_inputs_available: bool,
    /// Bitmask of the endpoints this one may be switched to.
    pub inputs_available: u32,
    /// Whether the device reported which input is selected.
    pub has_inputs_routed: bool,
    /// Bitmask of the endpoint this one is listening to.
    pub inputs_routed: u32,
    /// The device at the other end of the link, zero when unlinked.
    pub linked_device: mxr_uid_t,
    /// The endpoint at the other end of the link, or -1 when unlinked.
    pub linked_endpoint: i16,
}

impl From<&AudioEndpoint> for mxr_audio_endpoint_t {
    fn from(e: &AudioEndpoint) -> Self {
        Self {
            id: e.id,
            features: e.features.bits(),
            has_address: e.address.is_some(),
            address: e.address.unwrap_or_default().into(),
            // An endpoint id is a byte on the wire, so -1 cannot collide.
            parent: e.parent.map_or(-1, i16::from),
            child_count: e.children.len(),
            has_inputs_available: e.inputs_available.is_some(),
            inputs_available: e.inputs_available.unwrap_or(0),
            has_inputs_routed: e.inputs_routed.is_some(),
            inputs_routed: e.inputs_routed.unwrap_or(0),
            linked_device: e.linked_device.into(),
            linked_endpoint: e.linked_endpoint.map_or(-1, i16::from),
        }
    }
}

/// The diagnostic result for one UTP cable pair.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_cable_status_t {
    /// Whether the pair is wired with normal polarity.
    pub polarity: bool,
    /// Which pair this describes.
    pub pair: u8,
    /// Measured skew.
    pub skew: u32,
    /// Measured length.
    pub length: u32,
}

impl From<UtpCableStatus> for mxr_cable_status_t {
    fn from(c: UtpCableStatus) -> Self {
        Self {
            polarity: c.polarity,
            pair: c.pair,
            skew: c.skew,
            length: c.length,
        }
    }
}

/// The link state and diagnostics of one network port.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_network_port_t {
    /// Port number.
    pub port: u16,
    /// Port name.
    pub name: [c_char; MXR_NAME_LEN],
    /// Negotiated link speed.
    pub link_speed: u8,
    /// Whether the link negotiated full duplex.
    pub link_full_duplex: bool,
    /// The port's own address, empty when it has not reported one.
    pub ip: [c_char; MXR_IP_STRING_LEN],
    /// The IGMP querier the port sees, empty when it sees none.
    pub querier: [c_char; MXR_IP_STRING_LEN],
    /// Whether the port reported a hardware address.
    pub has_mac_address: bool,
    /// The hardware address, meaningful only when `has_mac_address` is set.
    pub mac_address: [u8; 6],
    /// Whether the port reported link errors.
    pub has_errors: bool,
    /// Input errors.
    pub in_error: bool,
    /// Input frame check errors.
    pub in_fcs_error: bool,
    /// Input collisions.
    pub in_collision: bool,
    /// Deferred transmissions.
    pub out_deferred: bool,
    /// Excessive transmissions.
    pub out_excessive: bool,
    /// Polarity errors.
    pub polarity_error: bool,
    /// Skew warning.
    pub skew_warning: bool,
    /// Length warning.
    pub length_warning: bool,
    /// Whether the port reported a virtual cable test.
    pub has_vct_status: bool,
    /// Whether each pair raised a warning, meaningful only when
    /// `has_vct_status` is set.
    pub vct_warning: [bool; MXR_UTP_PAIRS],
    /// How many entries of `cable_status` the port filled in.
    pub cable_status_count: usize,
    /// Cable diagnostics per pair.
    pub cable_status: [mxr_cable_status_t; MXR_UTP_PAIRS],
}

/// One device in a topology report.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_topology_entry_t {
    /// The device this entry describes.
    pub uid: mxr_uid_t,
    /// Bitmask of the devices it is connected to.
    pub mask: u32,
}

impl From<TopologyEntry> for mxr_topology_entry_t {
    fn from(e: TopologyEntry) -> Self {
        Self {
            uid: e.uid.into(),
            mask: e.mask,
        }
    }
}

/// One firmware component a device reports.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_firmware_version_t {
    /// Which component this describes.
    pub firmware_type: u8,
    /// Build timestamp, in seconds since the Unix epoch.
    pub timestamp: u32,
    /// Source revision hash.
    pub hash: u32,
    /// Human-readable version string.
    pub version: [c_char; MXR_VERSION_LEN],
}

/// A ProAmp8's Dolby settings.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_dolby_settings_t {
    /// 0 = standard, 1 = 3-zone Dolby, 2 = 4-zone Dolby.
    pub mode: u8,
    /// Whether PCM is up-mixed to 5.1 rather than passed through.
    pub pcm_upmix: bool,
    /// Whether a Dolby stream was detected.
    pub dolby_detected: bool,
    /// Whether up-mixing is currently running.
    pub pcm_upmix_active: bool,
}

impl From<AmpDolbySettings> for mxr_dolby_settings_t {
    fn from(s: AmpDolbySettings) -> Self {
        Self {
            mode: s.mode,
            pcm_upmix: s.pcm_upmix,
            dolby_detected: s.dolby_detected,
            pcm_upmix_active: s.pcm_upmix_active,
        }
    }
}

/// The remote-control configuration of a source bay.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_rc_settings_t {
    /// The device this configuration belongs to.
    pub target: mxr_uid_t,
    /// The control method, as the wire value.
    ///
    /// Zero is infrared, a method a bay really uses, so it is not a stand-in
    /// for "not reported". Check that `mxr_rc_settings()` returned `MXR_OK`
    /// before reading this: a device that has not sent its settings yet
    /// leaves the struct as the caller allocated it, and a zeroed one then
    /// reads as a bay set to infrared. `mxr_bay_info_t` answers the same
    /// question with a `has_rc_type` flag beside its `rc_type`.
    pub rc_target: u8,
    /// The control target's address, empty when unset.
    pub ip: [c_char; MXR_IP_STRING_LEN],
    /// Whether CEC is enabled.
    pub cec_enabled: bool,
    /// Whether CEC powers the sink on automatically.
    pub cec_auto_on: bool,
    /// Whether remote-control commands are forwarded.
    pub forward_rc: bool,
    /// Whether infrared is forwarded.
    pub forward_ir: bool,
    /// The driver state on the source, as the wire value. One above the last
    /// this library knows is passed through as it arrived.
    pub rc_status: u8,
    /// The driver-reported status string, empty when unknown.
    pub status_name: [c_char; MXR_NAME_LEN],
}

/// Writes an address into a fixed-width field, leaving it empty when there is
/// none.
fn put_ip(dst: &mut [c_char], ip: Option<Ipv4Addr>) {
    put_str(dst, &ip.map(|ip| ip.to_string()).unwrap_or_default());
}

/// Declares a getter for one subsystem of a device.
///
/// Each has the same three answers - no such device, the device has not sent
/// this, here it is - and writing them out once keeps a getter that answers
/// differently visible as one.
/// Writes a subsystem reading through `out`, or reports why there is none.
///
/// # Safety
///
/// `out` is null or points at a writable `T`.
unsafe fn fill<T>(
    r: &mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut T,
    what: &str,
    value: Option<T>,
) -> mxr_result_t {
    if out.is_null() {
        return null_out(what);
    }
    match value {
        Some(value) => {
            // SAFETY: the caller guarantees a writable T, and it is not null.
            unsafe { *out = value };
            mxr_result_t::MXR_OK
        }
        None => not_reported(r, uid, what),
    }
}

/// Reports why a subsystem read found nothing: no such device, or a device
/// that has not sent this.
fn not_reported(r: &mxr_remote_t, uid: mxr_uid_t, what: &str) -> mxr_result_t {
    if r.remote.device(uid.into()).is_none() {
        return not_heard_from(uid);
    }
    fail(
        mxr_result_t::MXR_ERR_NOT_REPORTED,
        &format!("the device has reported no {what}"),
    )
}

/// Fills `out` with a device's V2IP statistics.
///
/// A device sends these only while subscribed; see
/// `mxr_subscribe_v2ip_stats()`.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_v2ip_stats_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_stats(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_stats_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_stats(uid.into())
            .map(|s: V2ipDeviceStats| mxr_v2ip_stats_t {
                tx: s.tx.into(),
                tx_per_minute: s.tx_per_minute.into(),
                rx: s.rx.into(),
                rx_per_minute: s.rx_per_minute.into(),
                decoder: s.decoder.into(),
            });
        // SAFETY: the caller guarantees a writable mxr_v2ip_stats_t or null.
        unsafe { fill(r, uid, out, "V2IP statistics", value) }
    })
}

/// Fills `out` with a V2IP device's own encoder configuration.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_v2ip_details_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_details(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_details_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_details(uid.into())
            .map(|d: DeviceV2ipDetails| mxr_v2ip_details_t {
                video: d.video.into(),
                audio: d.audio.into(),
                anc: d.anc.into(),
                arc: d.arc.into(),
                // A rate and a marking are both bytes on the wire, so -1 cannot
                // collide with a value a device could report.
                tx_rate: d.tx_rate.map_or(-1, i16::from),
                dscp_video: d.dscp.video.map_or(-1, i16::from),
                dscp_audio: d.dscp.audio.map_or(-1, i16::from),
                dscp_anc: d.dscp.anc.map_or(-1, i16::from),
                scaling_mode: d.scaling.mode.to_wire(),
                scaling_refresh: d.scaling.refresh,
                scaling_flags: d.scaling.flags,
            });
        // SAFETY: the caller guarantees a writable mxr_v2ip_details_t or null.
        unsafe { fill(r, uid, out, "V2IP encoder configuration", value) }
    })
}

/// Fills `out` with the streams a V2IP sink is subscribed to.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_v2ip_sink_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_sink(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_sink_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_sink(uid.into())
            .map(|s: DeviceV2ipSink| mxr_v2ip_sink_t {
                addresses: s.addresses.into(),
                has_audio_format: s.audio_fmt.is_some(),
                audio_format: {
                    let f = s.audio_fmt.unwrap_or_default();
                    mxr_audio_format_t {
                        sample_rate: f.sample_rate,
                        channels: f.channels,
                    }
                },
            });
        // SAFETY: the caller guarantees a writable mxr_v2ip_sink_t or null.
        unsafe { fill(r, uid, out, "V2IP sink route", value) }
    })
}

/// Fills `out` with what a V2IP device's video processor supports.
///
/// Reports `MXR_ERR_NOT_REPORTED` while the device has not said: a processor
/// that has yet to answer and one with none of the optional commands send the
/// same empty mask, so neither is reported as a capability set.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `uint64_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_features(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut u64,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_features(uid.into())
            .map(V2ipFpgaFeature::bits);
        // SAFETY: the caller guarantees a writable uint64_t or null.
        unsafe { fill(r, uid, out, "processor features", value) }
    })
}

/// A V2IP device's settings.
///
/// A setting is reported only when its `MXR_V2IP_SETTING_*` bit is set in
/// `valid`, and a device reports every setting it has.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_device_settings_t {
    /// `MXR_V2IP_SETTING_*` bits of the settings reported so far.
    pub valid: u32,
    /// `MXR_V2IP_SETTING_*` values of the on/off settings among `valid`.
    pub flags: u32,
    /// The infrared profiles stored on the device, bit n for profile n, when
    /// `valid` has `MXR_V2IP_SETTING_IR_PROFILES`.
    pub ir_profiles: u32,
    /// The global infrared port's profile, when `valid` has
    /// `MXR_V2IP_SETTING_IR_PROFILE`.
    pub ir_profile: i8,
    /// The output infrared port's profile, when `valid` has
    /// `MXR_V2IP_SETTING_IR_PROFILE_SINK`. `MXR_V2IP_IR_PROFILE_NOT_SET` means
    /// it follows the global one.
    pub ir_profile_sink: i8,
}

/// The output infrared port follows the global one.
pub const MXR_V2IP_IR_PROFILE_NOT_SET: i8 = -1;
/// One past the highest infrared profile.
pub const MXR_V2IP_IR_PROFILE_MAX: i8 = 18;

// The header carries these as literals, so they are held to the core's here.
const _: () = assert!(MXR_V2IP_IR_PROFILE_NOT_SET == mx_remote::V2IP_IR_PROFILE_NOT_SET);
const _: () = assert!(MXR_V2IP_IR_PROFILE_MAX == mx_remote::V2IP_IR_PROFILE_MAX);

/// Fills `out` with a V2IP device's settings.
///
/// Reports `MXR_ERR_NOT_REPORTED` until the device has reported any. A change
/// is announced through `on_device_update`.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `mxr_v2ip_device_settings_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_device_settings(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_device_settings_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_device_settings(uid.into())
            .map(|s: V2ipDeviceSettings| mxr_v2ip_device_settings_t {
                valid: s.valid.bits(),
                flags: s.flags.bits(),
                ir_profiles: s.ir_profiles,
                ir_profile: s.ir_profile,
                ir_profile_sink: s.ir_profile_sink,
            });
        // SAFETY: the caller guarantees a writable struct or null.
        unsafe { fill(r, uid, out, "device settings", value) }
    })
}

/// A V2IP device's power save settings, beside `mxr_v2ip_device_settings_t`
/// rather than in it so that struct keeps its size.
///
/// Which of them the device has reported is in that struct's `valid`.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_power_save_t {
    /// The idle minutes before the device powers down by itself, 0 for never,
    /// when `valid` has `MXR_V2IP_SETTING_AUTO_POWER_SAVE`.
    pub auto_minutes: u16,
    /// When each day's power save window starts, Monday first, in minutes
    /// after midnight in the device's time zone, when `valid` has
    /// `MXR_V2IP_SETTING_POWER_SAVE_SCHEDULE`.
    pub start: [u16; 7],
    /// When each day's window ends. A window ending before it starts runs
    /// past midnight, and one ending where it starts means none that day.
    pub end: [u16; 7],
}

/// Minutes in a day: every power save time is below this.
pub const MXR_V2IP_MINUTES_PER_DAY: u16 = 1440;

const _: () = assert!(MXR_V2IP_MINUTES_PER_DAY == mx_remote::V2IP_MINUTES_PER_DAY);

/// Fills `out` with a V2IP device's power save settings.
///
/// Reports `MXR_ERR_NOT_REPORTED` until the device has reported any settings;
/// `mxr_v2ip_device_settings()` says which of these it has.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `mxr_v2ip_power_save_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_power_save(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_power_save_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_device_settings(uid.into())
            .map(|s: V2ipDeviceSettings| mxr_v2ip_power_save_t {
                auto_minutes: s.auto_power_save,
                start: s.power_save.start,
                end: s.power_save.end,
            });
        // SAFETY: the caller guarantees a writable struct or null.
        unsafe { fill(r, uid, out, "device settings", value) }
    })
}

/// Bytes in `mxr_time_zone_t.zone`, its NUL included.
pub const MXR_TIME_ZONE_NAME_LEN: usize = 48;
/// Bytes in `mxr_time_zone_t.rule`, its NUL included.
pub const MXR_TIME_ZONE_RULE_LEN: usize = 64;

const _: () = assert!(MXR_TIME_ZONE_NAME_LEN == mx_remote::TIME_ZONE_NAME_LEN);
const _: () = assert!(MXR_TIME_ZONE_RULE_LEN == mx_remote::TIME_ZONE_RULE_LEN);

/// The time zone a device announces for its mesh. An empty name and rule mean
/// the controller has none, and the devices keep UTC.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_time_zone_t {
    /// The IANA name, such as `Europe/Amsterdam`.
    pub zone: [c_char; MXR_TIME_ZONE_NAME_LEN],
    /// The POSIX TZ rule the devices keep time by.
    pub rule: [c_char; MXR_TIME_ZONE_RULE_LEN],
}

/// Fills `out` with the time zone a device announced for its mesh.
///
/// Reports `MXR_ERR_NOT_REPORTED` until it has announced one; the mesh
/// controller does with every periodic broadcast. A change is announced
/// through `on_device_update`.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `mxr_time_zone_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_time_zone(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_time_zone_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r.remote.time_zone(uid.into()).map(|tz| {
            let mut out = mxr_time_zone_t {
                zone: [0; MXR_TIME_ZONE_NAME_LEN],
                rule: [0; MXR_TIME_ZONE_RULE_LEN],
            };
            put_str(&mut out.zone, &tz.zone);
            put_str(&mut out.rule, &tz.rule);
            out
        });
        // SAFETY: the caller guarantees a writable struct or null.
        unsafe { fill(r, uid, out, "time zone", value) }
    })
}

/// Fills `out` with a device's clock as of now, in seconds since 1970 UTC:
/// the time it last announced, advanced by how long ago that arrived.
///
/// Reports `MXR_ERR_NOT_REPORTED` until it has announced one; the mesh
/// controller does with every periodic broadcast once its clock is set.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `uint64_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_device_clock(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut u64,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .device_clock(uid.into())
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs());
        // SAFETY: the caller guarantees a writable uint64_t or null.
        unsafe { fill(r, uid, out, "clock", value) }
    })
}

/// VLAN tagging on a V2IP device's uplink.
///
/// Only the device knows what it runs, so this is what it reported about
/// itself. A change written to it is applied at once and carries
/// `MXR_V2IP_VLAN_PENDING` until the mesh controller confirms it; unconfirmed,
/// the device reverts it.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_vlan_t {
    /// `MXR_V2IP_VLAN_*` bits.
    pub flags: u16,
    /// The VLAN id of the device's own traffic, 0 for untagged.
    pub device: u16,
    /// The VLAN id each downlink port carries, 0 to share the device's
    /// untagged traffic: the SFP port, the UTP port with PoE, then the UTP
    /// port.
    pub port: [u16; MXR_V2IP_VLAN_PORTS],
    /// The port pinned as the uplink as 1 + its index in `port`, 0 to detect
    /// it.
    pub uplink: u8,
    /// Reported by the device: the port in use as the uplink, as 1 + its
    /// index in `port`.
    pub active_uplink: u8,
    /// Reported by the device: the seconds before a pending configuration is
    /// reverted.
    pub revert_s: u8,
}

/// The ports in `mxr_v2ip_vlan_t::port`.
pub const MXR_V2IP_VLAN_PORTS: usize = 3;
/// The index of the SFP port in `mxr_v2ip_vlan_t::port`.
pub const MXR_V2IP_VLAN_PORT_SFP: usize = 0;
/// The highest VLAN id: 0 means untagged, and 4095 is reserved by IEEE 802.1Q.
pub const MXR_V2IP_VLAN_ID_MAX: u16 = 4094;

const _: () = assert!(MXR_V2IP_VLAN_PORTS == mx_remote::V2IP_VLAN_PORTS);
const _: () = assert!(MXR_V2IP_VLAN_PORT_SFP == mx_remote::V2IP_VLAN_PORT_SFP);
const _: () = assert!(MXR_V2IP_VLAN_ID_MAX == mx_remote::V2IP_VLAN_ID_MAX);

/// Fills `out` with the VLAN configuration a V2IP device last reported.
///
/// Reports `MXR_ERR_NOT_REPORTED` until the device has reported one. A change
/// is announced through `on_device_update`.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `mxr_v2ip_vlan_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_vlan(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_vlan_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_vlan(uid.into())
            .map(|v: V2ipVlan| mxr_v2ip_vlan_t {
                flags: v.flags.bits(),
                device: v.device,
                port: v.port,
                uplink: v.uplink,
                active_uplink: v.active_uplink,
                revert_s: v.revert_s,
            });
        // SAFETY: the caller guarantees a writable struct or null.
        unsafe { fill(r, uid, out, "VLAN configuration", value) }
    })
}

/// A V2IP sink's test tone.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_test_tone_t {
    /// `MXR_V2IP_TONE_MODE_*`.
    pub mode: u8,
    /// The level, in dBFS, `MXR_V2IP_TONE_LEVEL_MIN` to 0.
    pub level: i8,
    /// The channels it plays on, 1 to `MXR_V2IP_TONE_CHANNELS_MAX`; a line-up
    /// tone needs 2 or more.
    pub channels: u8,
    /// The frequency, `MXR_V2IP_TONE_FREQ_MIN` to `MXR_V2IP_TONE_FREQ_MAX` Hz.
    pub freq: u16,
    /// The sample rate: 44100, 48000 or 96000 Hz.
    pub rate: u32,
}

/// A V2IP sink's lip-sync flash: a pattern frame is marked every `period`,
/// the frame `lead` after a mark flashes white, and a beep tone starts
/// `offset` sample periods after it.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_test_sync_t {
    /// Every this many pattern frames is marked, 0 for none.
    pub period: u16,
    /// The frame this many after a mark flashes; below `period`, or 0 without
    /// one.
    pub lead: u16,
    /// Sample periods between a mark and the beep, at most
    /// `MXR_V2IP_SYNC_OFFSET_MAX`.
    pub offset: u32,
    /// How long the beep lasts, `MXR_V2IP_SYNC_BEEP_MS_MIN` to
    /// `MXR_V2IP_SYNC_BEEP_MS_MAX` ms.
    pub beep_ms: u16,
}

/// The test card a V2IP sink last reported. The counters run free and wrap.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct mxr_v2ip_testcard_t {
    /// `MXR_V2IP_TESTCARD_*` bits.
    pub flags: u8,
    /// `MXR_V2IP_TEST_PATTERN_*`.
    pub pattern: u8,
    /// The colour of a flat pattern, `0xRRGGBB`.
    pub colour: u32,
    /// The tone.
    pub tone: mxr_v2ip_test_tone_t,
    /// The lip-sync flash.
    pub sync: mxr_v2ip_test_sync_t,
    /// Pattern frames sent.
    pub frames: u32,
    /// Sample periods since the tone started.
    pub periods: u32,
    /// Lip-sync marks the tone has seen.
    pub marks: u32,
}

/// The lowest test tone frequency, in Hz.
pub const MXR_V2IP_TONE_FREQ_MIN: u16 = 20;
/// The highest test tone frequency, in Hz.
pub const MXR_V2IP_TONE_FREQ_MAX: u16 = 20000;
/// The quietest test tone level, in dBFS.
pub const MXR_V2IP_TONE_LEVEL_MIN: i8 = -60;
/// The most channels a test tone plays on.
pub const MXR_V2IP_TONE_CHANNELS_MAX: u8 = 8;
/// The largest lip-sync beep offset, in sample periods.
pub const MXR_V2IP_SYNC_OFFSET_MAX: u32 = 0xFFFFFF;
/// The shortest lip-sync beep, in milliseconds.
pub const MXR_V2IP_SYNC_BEEP_MS_MIN: u16 = 1;
/// The longest lip-sync beep, in milliseconds.
pub const MXR_V2IP_SYNC_BEEP_MS_MAX: u16 = 10000;

const _: () = assert!(MXR_V2IP_TONE_FREQ_MIN == mx_remote::V2IP_TONE_FREQ_MIN);
const _: () = assert!(MXR_V2IP_TONE_FREQ_MAX == mx_remote::V2IP_TONE_FREQ_MAX);
const _: () = assert!(MXR_V2IP_TONE_LEVEL_MIN == mx_remote::V2IP_TONE_LEVEL_MIN);
const _: () = assert!(MXR_V2IP_TONE_CHANNELS_MAX == mx_remote::V2IP_TONE_CHANNELS_MAX);
const _: () = assert!(MXR_V2IP_SYNC_OFFSET_MAX == mx_remote::V2IP_SYNC_OFFSET_MAX);
const _: () = assert!(MXR_V2IP_SYNC_BEEP_MS_MIN == mx_remote::V2IP_SYNC_BEEP_MS_MIN);
const _: () = assert!(MXR_V2IP_SYNC_BEEP_MS_MAX == mx_remote::V2IP_SYNC_BEEP_MS_MAX);

impl From<V2ipTestTone> for mxr_v2ip_test_tone_t {
    fn from(t: V2ipTestTone) -> Self {
        Self {
            mode: t.mode.to_wire(),
            level: t.level,
            channels: t.channels,
            freq: t.freq,
            rate: t.rate,
        }
    }
}

impl From<mxr_v2ip_test_tone_t> for V2ipTestTone {
    fn from(t: mxr_v2ip_test_tone_t) -> Self {
        Self {
            mode: V2ipToneMode::from_wire(t.mode),
            freq: t.freq,
            level: t.level,
            channels: t.channels,
            rate: t.rate,
        }
    }
}

impl From<V2ipTestSync> for mxr_v2ip_test_sync_t {
    fn from(s: V2ipTestSync) -> Self {
        Self {
            period: s.period,
            lead: s.lead,
            offset: s.offset,
            beep_ms: s.beep_ms,
        }
    }
}

impl From<mxr_v2ip_test_sync_t> for V2ipTestSync {
    fn from(s: mxr_v2ip_test_sync_t) -> Self {
        Self {
            period: s.period,
            lead: s.lead,
            offset: s.offset,
            beep_ms: s.beep_ms,
        }
    }
}

/// Fills `out` with the test card a V2IP sink last reported.
///
/// Reports `MXR_ERR_NOT_REPORTED` until the sink has answered
/// `mxr_request_v2ip_testcard()` or a change. A change is announced through
/// `on_device_update`.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `mxr_v2ip_testcard_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_testcard(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_v2ip_testcard_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .v2ip_testcard(uid.into())
            .map(|t: V2ipTestcard| mxr_v2ip_testcard_t {
                flags: t.flags.bits(),
                pattern: t.pattern.to_wire(),
                colour: t.colour,
                tone: t.tone.into(),
                sync: t.sync.into(),
                frames: t.frames,
                periods: t.periods,
                marks: t.marks,
            });
        // SAFETY: the caller guarantees a writable struct or null.
        unsafe { fill(r, uid, out, "test card", value) }
    })
}

/// Fills `out` with the window a sink is told to show.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_tiling_config_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_tiling(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_tiling_config_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value =
            r.remote
                .v2ip_tiling(uid.into())
                .map(|t: V2ipTilingConfig| mxr_tiling_config_t {
                    target: t.target.into(),
                    pos_x: t.pos_x,
                    pos_y: t.pos_y,
                    width: t.width,
                    height: t.height,
                });
        // SAFETY: the caller guarantees a writable mxr_tiling_config_t or null.
        unsafe { fill(r, uid, out, "window", value) }
    })
}

/// Fills `out` with what a multiviewer reports about itself.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_multiviewer_status_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_multiviewer_status(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_multiviewer_status_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r.remote.multiviewer_status(uid.into()).map(multiviewer_of);
        // SAFETY: the caller guarantees a writable mxr_multiviewer_status_t or null.
        unsafe { fill(r, uid, out, "multiviewer status", value) }
    })
}

/// Copies a multiviewer's report into the C shape.
fn multiviewer_of(s: MultiviewerStatus) -> mxr_multiviewer_status_t {
    let mut out = mxr_multiviewer_status_t {
        uid: s.uid.into(),
        mappings: [mxr_uid_t::default(); MXR_MULTIVIEWER_INPUTS],
        mcu_version: [0; MXR_NAME_LEN],
        scaler_version: [0; MXR_NAME_LEN],
        hw_view_mode: s.hw_view_mode,
        view_mode: s.view_mode.to_wire(),
        pip_position: s.pip_position.to_wire(),
        pip_size: s.pip_size.to_wire(),
        output_mode: s.output_mode.to_wire(),
        hdcp_mode: s.hdcp_mode.to_wire(),
        output_itc: s.output_itc.to_wire(),
        edid_template: s.edid_template.to_wire(),
        aspect_ratio: s.aspect_ratio.to_wire(),
        auto_switch: s.auto_switch.to_wire(),
        audio_source: s.audio_source.to_wire(),
        has_audio_volume: s.audio_volume.is_some(),
        audio_volume: s.audio_volume.unwrap_or(0),
        audio_muted: s.audio_muted.to_wire(),
        video_sources: [0; MXR_MULTIVIEWER_INPUTS],
        remote_control: s.remote_control.to_wire(),
    };
    for (slot, uid) in out.mappings.iter_mut().zip(s.mappings) {
        *slot = uid.into();
    }
    for (slot, source) in out.video_sources.iter_mut().zip(s.video_sources) {
        *slot = source.to_wire();
    }
    put_str(&mut out.mcu_version, &s.mcu_version);
    put_str(&mut out.scaler_version, &s.scaler_version);
    out
}

/// Fills `out` with a ProAmp8's Dolby settings.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_dolby_settings_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_dolby_settings(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_dolby_settings_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r
            .remote
            .dolby_settings(uid.into())
            .map(mxr_dolby_settings_t::from);
        // SAFETY: the caller guarantees a writable mxr_dolby_settings_t or null.
        unsafe { fill(r, uid, out, "Dolby settings", value) }
    })
}

/// Fills `out` with a source bay's remote-control configuration.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// [`mxr_rc_settings_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_rc_settings(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_rc_settings_t,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        let value = r.remote.rc_settings(uid.into()).map(rc_settings_of);
        // SAFETY: the caller guarantees a writable mxr_rc_settings_t or null.
        unsafe { fill(r, uid, out, "remote-control configuration", value) }
    })
}

/// Copies a remote-control configuration into the C shape.
fn rc_settings_of(s: RcSettings) -> mxr_rc_settings_t {
    let mut out = mxr_rc_settings_t {
        target: s.target.into(),
        rc_target: s.rc_target,
        ip: [0; MXR_IP_STRING_LEN],
        cec_enabled: s.cec_enabled,
        cec_auto_on: s.cec_auto_on,
        forward_rc: s.forward_rc,
        forward_ir: s.forward_ir,
        rc_status: s.rc_status,
        status_name: [0; MXR_NAME_LEN],
    };
    put_ip(&mut out.ip, s.ip);
    put_str(&mut out.status_name, &s.status_name);
    out
}

/// Writes the streams a device's source bays advertise, and returns how many
/// there are.
///
/// Returns the full count even when it exceeds `cap`, so calling with `cap`
/// zero sizes the buffer.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable [`mxr_stream_sources_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_v2ip_sources(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_stream_sources_t,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let Some(sources) = r.remote.v2ip_sources(uid.into()) else {
            not_reported(r, uid, "V2IP stream sources");
            return 0;
        };
        // SAFETY: the caller guarantees cap writable elements at out.
        unsafe { copy_into(&sources, out, cap) }
    })
}

/// Writes a device's network ports, and returns how many there are.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable [`mxr_network_port_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_network_status(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_network_port_t,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let ports: Vec<mxr_network_port_t> = r
            .remote
            .network_status(uid.into())
            .iter()
            .map(port_of)
            .collect();
        // SAFETY: the caller guarantees cap writable elements at out.
        unsafe { copy_into(&ports, out, cap) }
    })
}

/// Copies one port report into the C shape.
fn port_of(p: &NetworkPortStatus) -> mxr_network_port_t {
    let errors = p.errors.unwrap_or_default();
    let mut out = mxr_network_port_t {
        port: p.port,
        name: [0; MXR_NAME_LEN],
        link_speed: p.link_speed.to_wire(),
        link_full_duplex: p.link_full_duplex,
        ip: [0; MXR_IP_STRING_LEN],
        querier: [0; MXR_IP_STRING_LEN],
        has_mac_address: p.mac_address.is_some(),
        mac_address: p.mac_address.unwrap_or_default().0,
        has_errors: p.errors.is_some(),
        in_error: errors.in_error,
        in_fcs_error: errors.in_fcs_error,
        in_collision: errors.in_collision,
        out_deferred: errors.out_deferred,
        out_excessive: errors.out_excessive,
        polarity_error: errors.polarity_error,
        skew_warning: errors.skew_warning,
        length_warning: errors.length_warning,
        has_vct_status: p.vct_status.is_some(),
        vct_warning: [false; MXR_UTP_PAIRS],
        cable_status_count: p.cable_status.len().min(MXR_UTP_PAIRS),
        cable_status: [mxr_cable_status_t {
            polarity: false,
            pair: 0,
            skew: 0,
            length: 0,
        }; MXR_UTP_PAIRS],
    };
    put_str(&mut out.name, &p.name);
    put_ip(&mut out.ip, p.ip);
    put_ip(&mut out.querier, p.querier);
    if let Some(vct) = p.vct_status {
        for (slot, status) in out.vct_warning.iter_mut().zip(vct) {
            *slot = status == VctStatus::Warning;
        }
    }
    for (slot, cable) in out.cable_status.iter_mut().zip(&p.cable_status) {
        *slot = (*cable).into();
    }
    out
}

/// Writes a device's view of the mesh topology, and returns how many entries
/// there are.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable [`mxr_topology_entry_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_topology(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_topology_entry_t,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let topology = r.remote.topology(uid.into());
        // SAFETY: the caller guarantees cap writable elements at out.
        unsafe { copy_into(&topology, out, cap) }
    })
}

/// Writes the firmware versions a device reports, and returns how many there
/// are.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable [`mxr_firmware_version_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_device_firmware(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_firmware_version_t,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let versions: Vec<mxr_firmware_version_t> = r
            .remote
            .firmware(uid.into())
            .iter()
            .map(|(_, v)| firmware_of(v))
            .collect();
        // SAFETY: the caller guarantees cap writable elements at out.
        unsafe { copy_into(&versions, out, cap) }
    })
}

/// Copies one firmware report into the C shape.
fn firmware_of(v: &FirmwareVersion) -> mxr_firmware_version_t {
    let mut out = mxr_firmware_version_t {
        firmware_type: v.firmware_type.to_wire(),
        timestamp: v.timestamp,
        hash: v.hash,
        version: [0; MXR_VERSION_LEN],
    };
    put_str(&mut out.version, &v.version);
    out
}

/// Writes a device's audio endpoints, in the order it reported them, and
/// returns how many there are.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable [`mxr_audio_endpoint_t`].
#[no_mangle]
pub unsafe extern "C" fn mxr_audio_endpoints(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    out: *mut mxr_audio_endpoint_t,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let Some(endpoints) = r.remote.audio_endpoints(uid.into()) else {
            not_reported(r, uid, "audio endpoints");
            return 0;
        };
        let list: Vec<mxr_audio_endpoint_t> = endpoints.list().map(Into::into).collect();
        // SAFETY: the caller guarantees cap writable elements at out.
        unsafe { copy_into(&list, out, cap) }
    })
}

/// Fills `out` with the state an audio endpoint reports, on the bits of its
/// features: `MXR_AUDIO_MUTE` while it is muted, `MXR_AUDIO_TRIGGER` while
/// its trigger is active, and `MXR_AUDIO_AUDIO_LOCK` while its source is
/// locked. Beside `mxr_audio_endpoint_t` rather than in it, so that struct
/// keeps its size.
///
/// Reports `MXR_ERR_NOT_REPORTED` until the device has reported its audio
/// endpoints, and `MXR_ERR_NOT_FOUND` for an endpoint it did not report.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` points at a writable
/// `uint32_t`.
#[no_mangle]
pub unsafe extern "C" fn mxr_audio_endpoint_status(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    endpoint: u8,
    out: *mut u32,
) -> mxr_result_t {
    // SAFETY: the caller guarantees a live handle or null.
    let handle = unsafe { remote.as_ref() };
    with(handle, |r| {
        if out.is_null() {
            return null_out("audio endpoint status");
        }
        let Some(endpoints) = r.remote.audio_endpoints(uid.into()) else {
            return not_reported(r, uid, "audio endpoints");
        };
        let Some(status) = endpoints.status(endpoint) else {
            return fail(
                mxr_result_t::MXR_ERR_NOT_FOUND,
                "the device reported no such audio endpoint",
            );
        };
        // SAFETY: the caller guarantees a writable uint32_t or null.
        unsafe { fill(r, uid, out, "audio endpoint status", Some(status.bits())) }
    })
}

/// Writes the endpoints hanging off one audio endpoint, and returns how many
/// there are.
///
/// # Safety
///
/// `remote` is null or a live handle, and `out` is null or points at `cap`
/// writable bytes.
#[no_mangle]
pub unsafe extern "C" fn mxr_audio_endpoint_children(
    remote: *const mxr_remote_t,
    uid: mxr_uid_t,
    endpoint: u8,
    out: *mut u8,
    cap: usize,
) -> usize {
    guard(0, || {
        // SAFETY: the caller guarantees a live handle or null.
        let Some(r) = (unsafe { remote.as_ref() }) else {
            return no_handle();
        };
        let children = match r.remote.audio_endpoints(uid.into()) {
            Some(endpoints) => match endpoints.get(endpoint) {
                Some(e) => e.children.clone(),
                None => {
                    fail(
                        mxr_result_t::MXR_ERR_NOT_FOUND,
                        &format!("the device has no audio endpoint {endpoint}"),
                    );
                    return 0;
                }
            },
            None => {
                not_reported(r, uid, "audio endpoints");
                return 0;
            }
        };
        // SAFETY: the caller guarantees cap writable bytes at out.
        unsafe { copy_into(&children, out, cap) }
    })
}

/// Reports a null handle from a call whose answer is a count.
fn no_handle() -> usize {
    fail(
        mxr_result_t::MXR_ERR_INVALID_ARGUMENT,
        "the client handle is null",
    );
    0
}