deepmind-midi 26.5.2

Sans-IO protocol library for Behringer DeepMind synthesizers: SysEx, NRPN, programs and device state
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
//! The parameter table: what each of the 242 program parameters is, and how it
//! reaches the wire.
//!
//! One number does two jobs on this synthesizer. A parameter's 14-bit NRPN
//! number is also its byte offset in an unpacked program dump, so [`ParamId`] is
//! both the thing you edit and the place it lives. Everything else here hangs
//! off that one identifier.
//!
//! ```
//! use deepmind_midi::param::{Kind, ParamId};
//! use deepmind_midi::wire::Channel;
//!
//! let shape = ParamId::Lfo1Shape;
//! assert_eq!(shape.offset(), 2);
//! assert_eq!(shape.name(), "LFO 1 Shape");
//! assert_eq!(shape.max(), 6);
//! assert_eq!(shape.label(3), Some("Ramp Up"));
//!
//! let mut bytes = [0; 12];
//! let len = shape.edit(3)?.encode_into(Channel::ONE, &mut bytes)?;
//! assert_eq!(
//!     &bytes[..len],
//!     &[0xB0, 99, 0, 0xB0, 98, 2, 0xB0, 6, 0, 0xB0, 38, 3],
//! );
//! # Ok::<(), deepmind_midi::Error>(())
//! ```
//!
//! # What the table carries
//!
//! What a host needs in order to act: the name the synthesizer shows, the
//! section of the panel it belongs to, the range it accepts, and the named
//! values it decodes into. That is [`Parameter`], reached through
//! [`ParamId::info`].
//!
//! It carries the modulation matrix as a join. A `Mod n Destination` holds an
//! abbreviation the display prints, and [`ParamId::targets`] is which parameters
//! that abbreviation moves. It is empty where the destination names something no
//! program parameter addresses, which the specification records beside the entry.
//! [`ValueTable::values_naming`] is the same join read backwards, most specific
//! destination first, for a host that starts from the control. A source carries
//! which way it moves what it reaches, as [`ValueTable::swing_of`], and both
//! ends carry a picture the size of a character, as [`ValueTable::cell_of`] —
//! every source but `Off`, and every destination the join cannot picture.
//!
//! It carries what a raw value means beyond its range, wherever the manual says:
//! [`ParamId::shape`] is the point a bipolar parameter is read about,
//! [`ParamId::inactive`] the value that means "not set" rather than the smallest
//! one, and [`ParamId::bounded_by`] the parameter saying how many of a run are
//! played. Those three decide what a control is, so they are typed.
//!
//! The manual's own prose is reachable and costs nothing to ignore.
//! [`ParamId::note`], [`ParamId::display`] and [`ParamId::correction`] are each a
//! function over its own strings, referenced by nothing else, so a host that
//! never calls one does not carry it: any linker collecting unreachable sections
//! drops the 11 kB of manual between them. Value-table entries carry names and
//! not descriptions for the same reason in reverse, since a description would sit
//! inside a table every host already reaches.
//!
//! What a parameter does is [`ParamId::description`], and that one is behind the
//! `descriptions` feature rather than only behind a linker: every parameter has a
//! sentence, which is 30 kB, and a host that wants one would reach all of them.
//! It answers `None` with the feature off and keeps its signature either way, so
//! a host writes one code path. Those sentences are written for this
//! specification rather than transcribed, unlike
//! [`FxSlot::description`](crate::effect::FxSlot::description), which is the
//! manual's own words about an effect slot and is behind the same feature.
//!
//! It does not carry conversions from a raw value to the number the synthesizer
//! displays. The manual publishes the two ends of a range and almost never the
//! curve between them, so [`ParamId::display`] hands over the ends as printed and
//! stops there; an invented reading would be wrong in every host that trusted it.
//! Conversions arrive per parameter as they are measured. See the scaling section
//! of `docs/midi-spec.md`.
//!
//! # Firmware
//!
//! Firmware 1.1 renumbered three value tables rather than only appending to them,
//! so 17 of 23 modulation sources and 120 of 130 modulation destinations mean
//! something else on 1.0. Every lookup that touches a value table therefore comes
//! in two forms: a plain one that assumes [`DEFAULT_FIRMWARE`], and a `_for` one
//! that takes the [`Version`] a device inquiry reported. Nothing in a stored dump
//! says which firmware wrote it, so the older tables are reachable only when the
//! host knows the version another way.
//!
//! # Serde
//!
//! The tables are static: their strings are `&'static str` and their entries are
//! `&'static [ValueEntry]`. Under the `serde` feature they serialize, which is
//! what a host sending its parameter list somewhere needs. They do not
//! deserialize, which would only allocate names the library already holds.

mod generated;

pub use generated::{
    CONTROLLER_COUNT, CONTROLLERS, DEFAULT_FIRMWARE, Group, PARAMETER_COUNT, ParamId, TABLE_COUNT,
    TableId,
};

use generated::{CONTROLLER_OF_PARAMETER, NO_CONTROLLER};

use core::fmt;

use crate::error::{Error, Result};
use crate::pixels::{Glyph, Pixels};
use crate::sysex::inquiry::Version;
use crate::wire::{Channel, ChannelMessage};

/// Controller that carries the high seven bits of an NRPN number (CC 99).
pub const NRPN_NUMBER_MSB: u8 = 99;

/// Controller that carries the low seven bits of an NRPN number (CC 98).
pub const NRPN_NUMBER_LSB: u8 = 98;

/// Controller that carries the high seven bits of a value (CC 6).
pub const DATA_ENTRY_MSB: u8 = 6;

/// Controller that carries the low seven bits of a value (CC 38).
pub const DATA_ENTRY_LSB: u8 = 38;

/// The eight modulation depths, one per bus, in bus order.
const MOD_DEPTHS: [ParamId; 8] = [
    ParamId::Mod1Depth,
    ParamId::Mod2Depth,
    ParamId::Mod3Depth,
    ParamId::Mod4Depth,
    ParamId::Mod5Depth,
    ParamId::Mod6Depth,
    ParamId::Mod7Depth,
    ParamId::Mod8Depth,
];

/// Everything the specification says about one parameter.
///
/// Returned by value from [`ParamId::info`]; the fields are also reachable one
/// at a time through the methods of the same names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Parameter {
    /// Name as the synthesizer's display writes it.
    pub name: &'static str,
    /// Section of the instrument this parameter belongs to.
    pub group: Group,
    /// Lowest accepted value. Zero for every parameter but Program Transpose,
    /// which counts semitones either side of 128: -48 is 80 and +48 is 176.
    pub min: u16,
    /// Highest accepted value.
    pub max: u16,
    /// How the raw value is to be read.
    pub kind: Kind,
}

/// How a parameter's raw value is to be read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Kind {
    /// A sweep. The raw value is the value, and what the synthesizer displays
    /// for it is a curve this library does not guess at.
    Continuous,
    /// Two states: off at zero, on at one.
    Switch,
    /// One of a named set, listed in the value table named here.
    Enumerated(TableId),
}

/// What a parameter's raw value means beyond the range it sits in.
///
/// [`Kind`] says how a byte is read: a sweep, two states, or one of a named set.
/// This says where the middle of a sweep is, which is what decides how to draw
/// it. A bipolar value drawn from the bottom of its range shows as half full at
/// no modulation, so a matrix of eight depths set to nothing reads as a matrix
/// of half of it.
///
/// Reached through [`ParamId::shape`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Shape {
    /// Counts up from [`min`](ParamId::min), which is 197 of the 242.
    Unipolar,
    /// Signed about a centre: `centre` reads as zero, and the two ends of the
    /// range as the largest readings either side of it.
    ///
    /// The ends are [`min`](ParamId::min) and [`max`](ParamId::max), so a
    /// reading is `value - centre` and nothing else need be published here.
    /// There is no single `±extent` because the range is not always symmetric:
    /// ten of the forty-five bipolar parameters run -128 to +127 about 128, one
    /// further below the centre than above it.
    Bipolar {
        /// The raw value that reads as zero.
        centre: u16,
    },
}

/// Which way a modulation source moves the destination it reaches.
///
/// Reached through [`ValueTable::swing_of`] and [`ValueEntry::swing`]. It is a
/// fact about the source and the same for every routing that uses it: the sign
/// of a `Mod n Depth` says which way round the routing applies the source, and
/// an inverted LFO is still an LFO.
///
/// A host drawing how far the routings reaching a control can push it starts
/// the band here: either side of where the control sits for a
/// [`Centred`](Self::Centred) source, from where it sits one way for a
/// [`Rising`](Self::Rising) one.
///
/// `non_exhaustive` because a source may yet turn out to do a third thing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Swing {
    /// About the value: an LFO at depth moves its destination up and down, and
    /// so does the pitch bender, which rests in the middle of its travel.
    Centred,
    /// Up from the value and back: an envelope, a fade, an LFO taken unipolar,
    /// a wheel resting at one end of its travel, a velocity or a pressure.
    Rising,
}

/// One value of an enumerated parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ValueEntry {
    /// The value on the wire.
    pub value: u16,
    /// Name as the synthesizer displays it.
    pub name: &'static str,
    /// The program parameters this value names, where it names any.
    ///
    /// The modulation matrix is what this is for. A destination is an
    /// abbreviation the display prints, `VCF Freq` or `All Attack`, and this is
    /// the parameter table's answer to what that abbreviation moves. It is a
    /// slice because several destinations move more than one parameter, and it
    /// is empty where the destination names something no program parameter
    /// addresses, such as the pitch a key is playing or the amplitude of a
    /// voice.
    ///
    /// Empty for every other table, and for a mapping that has not been
    /// established. `docs/midi-spec.md` prints the reason beside the
    /// destinations that have one.
    pub parameters: &'static [ParamId],
    /// Which way this value, as a modulation source, moves what it reaches.
    ///
    /// `None` for every table but the modulation sources, and for a source
    /// the specification does not settle: where a note number counts from is
    /// not printed anywhere, and `Off` moves nothing.
    pub swing: Option<Swing>,
}

/// A named set of values, as of one firmware version.
///
/// Reached through [`TableId::table`] or [`TableId::table_for`]. Several tables
/// may share an identifier when firmware renumbered their entries; those two
/// methods are what pick between them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ValueTable {
    /// Identifier this table answers to.
    pub id: TableId,
    /// Human-readable table name.
    pub name: &'static str,
    /// `false` where the manual contradicts itself and hardware has not settled
    /// it. The entries are recorded as printed.
    pub confirmed: bool,
    /// `true` when [`ValueTable::entries`] lists only the start of a documented
    /// run, such as `SPREAD-1` standing for `SPREAD-1` through `SPREAD-254`.
    /// [`ValueTable::name_of`] answers `None` above the last listed entry rather
    /// than inventing the rest of the run.
    pub partial: bool,
    /// The values themselves, in value order.
    pub entries: &'static [ValueEntry],
    /// A dot-matrix cell per value that has one, in value order.
    ///
    /// The two ends of the modulation matrix have them: a picture of `LFO 1`
    /// or `Mod Wheel` the size of a character, for a patch bay drawn in
    /// pictures rather than in abbreviations. Every source but `Off` is drawn.
    /// A destination is drawn where [`ValueEntry::parameters`] leaves a host
    /// nothing to reach for — where it names none, or names a set with no one
    /// of them narrowest — and otherwise takes its picture from the one
    /// parameter it moves, through [`ParamId::glyph`]. Empty for every other
    /// table, and missing a value nobody has drawn, for which a host draws the
    /// name it already prints. `spec/cells.toml` says which are drawn and why
    /// the rest are not.
    ///
    /// Beside the entries rather than on them, so that the twenty-odd tables
    /// with no cells do not carry a blank per entry; reached through
    /// [`ValueTable::cell_of`].
    pub cells: &'static [(u16, Pixels)],
}

impl ValueTable {
    /// Returns the name this table gives `value`.
    ///
    /// `None` when the table does not list it, which for a
    /// [`partial`](ValueTable::partial) table includes values inside a
    /// documented run whose first entry is listed.
    #[must_use]
    pub fn name_of(&self, value: u16) -> Option<&'static str> {
        self.entry(value).map(|entry| entry.name)
    }

    /// Returns the program parameters this table's `value` names.
    ///
    /// Empty both for a value this table does not list and for one that names
    /// nothing a program parameter addresses; see
    /// [`ValueEntry::parameters`] for what the difference is and where it is
    /// written down.
    #[must_use]
    pub fn parameters_of(&self, value: u16) -> &'static [ParamId] {
        self.entry(value).map_or(&[], |entry| entry.parameters)
    }

    /// Returns which way this table's `value`, as a modulation source, moves
    /// what it reaches.
    ///
    /// `None` for a value this table does not list, for a table that is not
    /// the modulation sources, and for a source the specification does not
    /// settle; see [`ValueEntry::swing`].
    ///
    /// ```
    /// use deepmind_midi::param::{Swing, TableId};
    /// use deepmind_midi::program::ModSource;
    ///
    /// let sources = TableId::ModSource.table();
    /// let value = |source: ModSource| u16::from(source.raw());
    /// assert_eq!(sources.swing_of(value(ModSource::Lfo1)), Some(Swing::Centred));
    /// assert_eq!(sources.swing_of(value(ModSource::Env1)), Some(Swing::Rising));
    /// assert_eq!(sources.swing_of(value(ModSource::Off)), None);
    /// ```
    #[must_use]
    pub fn swing_of(&self, value: u16) -> Option<Swing> {
        self.entry(value)?.swing
    }

    /// Returns the dot-matrix cell drawn for this table's `value`, where one
    /// has been; see [`ValueTable::cells`].
    ///
    /// ```
    /// use deepmind_midi::param::{ParamId, TableId};
    /// use deepmind_midi::pixels::Glyph;
    /// use deepmind_midi::program::ModSource;
    ///
    /// let sources = TableId::ModSource.table();
    /// let lfo = sources.cell_of(u16::from(ModSource::Lfo1.raw())).expect("LFO 1 is drawn");
    /// assert!(lfo.rows().iter().any(|row| *row != 0));
    /// assert!(sources.cell_of(u16::from(ModSource::Off.raw())).is_none());
    ///
    /// // A destination that moves a set of parameters is drawn as the set:
    /// // `All Attack` is three envelopes' attack, drawn once.
    /// let destinations = TableId::ModDestination.table();
    /// let all_attack = destinations.cell_of(25).expect("All Attack is drawn");
    /// assert_eq!(all_attack, Glyph::Attack.pixels());
    /// // One that moves one parameter takes that parameter's own glyph.
    /// assert!(destinations.cell_of(35).is_none());
    /// assert_eq!(
    ///     destinations.parameters_of(35),
    ///     &[ParamId::VcaEnvelopeAttackTime],
    /// );
    /// assert_eq!(ParamId::VcaEnvelopeAttackTime.glyph(), Some(Glyph::Attack));
    /// ```
    #[must_use]
    pub fn cell_of(&self, value: u16) -> Option<&'static Pixels> {
        let index = self
            .cells
            .binary_search_by_key(&value, |&(drawn, _)| drawn)
            .ok()?;
        self.cells.get(index).map(|(_, cell)| cell)
    }

    /// Returns the values of this table that address `parameter`, most
    /// specific first.
    ///
    /// The join of [`ValueEntry::parameters`] read backwards: which
    /// destinations a host should offer when somebody points at a control.
    /// `VCF Envelope Attack Time` is moved by `Env2 Attack`, which moves only
    /// it, and by `All Attack`, which moves the three envelopes' attacks
    /// together, and somebody who took hold of the filter envelope's attack
    /// meant the filter's. So the order is by how many parameters a
    /// destination moves, fewest first, and `.next()` is the answer for a
    /// host wanting one destination. Two destinations moving the same number
    /// of parameters come in value order: `All Attack` moves three attacks
    /// and `Env2 Rates` moves the filter envelope's three times, and nothing
    /// in the specification makes one of those the narrower, so it says so
    /// rather than implying a preference.
    ///
    /// Empty for a parameter nothing in this table addresses, matching
    /// [`parameters_of`](Self::parameters_of). It is a search over the
    /// forward slices rather than a second table, which costs a walk over
    /// the entries per value yielded and runs once per control a host lights
    /// up.
    ///
    /// ```
    /// use deepmind_midi::param::{ParamId, TableId};
    ///
    /// let destinations = TableId::ModDestination.table();
    /// let mut naming = destinations.values_naming(ParamId::VcfEnvelopeAttackTime);
    ///
    /// // The one that moves only this, then the ones that move it with others.
    /// assert_eq!(naming.next().and_then(|v| destinations.name_of(v)), Some("Env2 Attack"));
    /// assert_eq!(naming.next().and_then(|v| destinations.name_of(v)), Some("All Attack"));
    /// assert_eq!(naming.next().and_then(|v| destinations.name_of(v)), Some("Env2 Rates"));
    /// assert_eq!(naming.next().and_then(|v| destinations.name_of(v)), Some("Env Rates"));
    /// assert_eq!(naming.next(), None);
    ///
    /// // A parameter the matrix cannot reach.
    /// assert_eq!(destinations.values_naming(ParamId::ArpPattern).next(), None);
    /// ```
    pub fn values_naming(&self, parameter: ParamId) -> impl Iterator<Item = u16> + 'static {
        let entries = self.entries;
        // The key each value is ordered by: how many parameters it moves, then
        // the value itself. Each step yields the smallest key past the last
        // one, which needs no buffer and so no bound on how many there are.
        let mut last: Option<(usize, u16)> = None;
        core::iter::from_fn(move || {
            let next = entries
                .iter()
                .filter(|entry| entry.parameters.contains(&parameter))
                .map(|entry| (entry.parameters.len(), entry.value))
                .filter(|key| last.is_none_or(|last| *key > last))
                .min()?;
            last = Some(next);
            Some(next.1)
        })
    }

    /// Returns this table's entry for `value`.
    ///
    /// A binary search: the entries are in ascending value order, which the
    /// specification checks when it loads, and the largest table has 133 of
    /// them. It runs once per control a panel redraws.
    #[must_use]
    pub fn entry(&self, value: u16) -> Option<&'static ValueEntry> {
        let index = self
            .entries
            .binary_search_by_key(&value, |entry| entry.value)
            .ok()?;
        self.entries.get(index)
    }
}

impl fmt::Display for ValueTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name)
    }
}

/// What a MIDI continuous controller reaches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ControllerKind {
    /// Drives one program parameter, named in [`Controller::parameter`].
    Parameter,
    /// A controller the MIDI specification defines, used as it is defined.
    Standard,
    /// Something else the synthesizer answers, such as an NRPN selector.
    Other,
}

/// A MIDI continuous controller the synthesizer answers.
///
/// Controllers are a shortcut, not a second address space: 90 of the 242
/// parameters have one, and a parameter whose range runs past 127 loses
/// resolution through it. NRPN is the general path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Controller {
    /// Controller number, `0..=127`.
    pub cc: u8,
    /// What it controls.
    pub name: &'static str,
    /// What kind of thing that is.
    pub kind: ControllerKind,
    /// The program parameter it drives, where it drives one.
    pub parameter: Option<ParamId>,
    /// The picture of what it does, where one fits.
    ///
    /// A controller that drives a parameter is pictured the way the parameter
    /// is, so the mod wheel and `LFO 1 Rate` look the same from a port as
    /// from a panel. The standard controllers are pictured by what the MIDI
    /// specification says they are: the modulation wheel is a wheel, the foot
    /// controller a treadle, expression the same treadle carrying a level, the
    /// breath controller air down a tube, and the sustain pedal a switch under
    /// a foot. `None` for the data entry and bank select controllers, which are
    /// addressing and not a control.
    ///
    /// ```
    /// use deepmind_midi::param::Controller;
    /// use deepmind_midi::pixels::Glyph;
    ///
    /// let sustain = Controller::for_cc(64).expect("the sustain pedal");
    /// assert_eq!(sustain.glyph, Some(Glyph::Footswitch));
    /// let foot = Controller::for_cc(4).expect("the foot controller");
    /// assert_eq!(foot.glyph, Some(Glyph::Pedal));
    /// let expression = Controller::for_cc(11).expect("expression");
    /// assert_eq!(expression.glyph, Some(Glyph::Expression));
    /// ```
    pub glyph: Option<Glyph>,
}

impl Controller {
    /// Returns the controller with this number, if the synthesizer answers it.
    ///
    /// The table is in controller number order, so this is a binary search;
    /// it runs on every control change a port delivers.
    #[must_use]
    pub fn for_cc(cc: u8) -> Option<&'static Self> {
        CONTROLLERS
            .binary_search_by_key(&cc, |controller| controller.cc)
            .ok()
            .and_then(|index| CONTROLLERS.get(index))
    }

    /// Returns the controller that drives this parameter, if one does.
    ///
    /// A table indexed by the parameter's own offset rather than a scan over
    /// the 128 controllers; a panel asks it once per control it draws. No two
    /// controllers claim the same parameter, which the specification checks
    /// when it loads and which is what makes the table one entry wide.
    #[must_use]
    pub fn for_parameter(parameter: ParamId) -> Option<&'static Self> {
        let index = CONTROLLER_OF_PARAMETER
            .get(usize::from(parameter.offset()))
            .copied()
            .filter(|index| *index != NO_CONTROLLER)?;
        CONTROLLERS.get(usize::from(index))
    }
}

impl fmt::Display for Controller {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CC {} ({})", self.cc, self.name)
    }
}

impl TryFrom<u8> for ParamId {
    type Error = Error;

    fn try_from(offset: u8) -> Result<Self> {
        Self::from_offset(offset)
    }
}

impl From<ParamId> for u8 {
    fn from(parameter: ParamId) -> Self {
        parameter.offset()
    }
}

impl ParamId {
    /// Returns the NRPN number, which is also the byte offset in a program dump.
    #[must_use]
    pub const fn offset(self) -> u8 {
        self as u8
    }

    /// Returns the parameter at this offset.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ParameterOutOfRange`] for an offset of 242 or more.
    /// Offsets 242 to 244 exist in a comms protocol version 7 dump; they are
    /// reserved, carry no parameter, and are preserved rather than decoded.
    pub fn from_offset(offset: u8) -> Result<Self> {
        Self::ALL
            .get(usize::from(offset))
            .copied()
            .ok_or(Error::ParameterOutOfRange(offset))
    }

    /// Returns the name the synthesizer's display writes.
    #[must_use]
    pub const fn name(self) -> &'static str {
        self.info().name
    }

    /// Returns the section of the instrument this parameter belongs to.
    #[must_use]
    pub const fn group(self) -> Group {
        self.info().group
    }

    /// Returns the name without the group's, where the name starts with it.
    ///
    /// `VCF Envelope Depth` is `Envelope Depth`, for a panel that prints its
    /// group once as a heading. A name that does not start with its group comes
    /// back whole, which is every parameter of the modulation matrix and of the
    /// arpeggiator.
    ///
    /// ```
    /// use deepmind_midi::param::ParamId;
    ///
    /// assert_eq!(ParamId::VcfEnvelopeDepth.short_name(), "Envelope Depth");
    /// assert_eq!(ParamId::Mod1Source.short_name(), "Mod 1 Source");
    /// ```
    #[must_use]
    pub fn short_name(self) -> &'static str {
        let name = self.name();
        name.strip_prefix(self.group().name())
            .map_or(name, |rest| rest.trim_start())
    }

    /// Returns how the raw value is to be read.
    #[must_use]
    pub const fn kind(self) -> Kind {
        self.info().kind
    }

    /// Returns the lowest accepted value.
    ///
    /// Zero for 241 of the 242 parameters; Program Transpose is the exception,
    /// running 80 to 176 for -48 to +48 semitones.
    #[must_use]
    pub const fn min(self) -> u16 {
        self.info().min
    }

    /// Returns the highest accepted value.
    #[must_use]
    pub const fn max(self) -> u16 {
        self.info().max
    }

    /// Returns whether this parameter accepts `value`.
    #[must_use]
    pub const fn accepts(self, value: u16) -> bool {
        let info = self.info();
        value >= info.min && value <= info.max
    }

    /// Returns `value` brought inside the accepted range.
    #[must_use]
    pub const fn clamp(self, value: u16) -> u16 {
        let info = self.info();
        if value < info.min {
            info.min
        } else if value > info.max {
            info.max
        } else {
            value
        }
    }

    /// Returns the name this parameter gives `value` on [`DEFAULT_FIRMWARE`].
    ///
    /// `None` for a continuous parameter, whose value has no name, and for a
    /// value its table does not list.
    #[must_use]
    pub fn label(self, value: u16) -> Option<&'static str> {
        self.label_for(value, DEFAULT_FIRMWARE)
    }

    /// Returns the name this parameter gives `value` on the firmware a device
    /// inquiry reported.
    ///
    /// Use this whenever the value came from a stored program. The three
    /// renumbered tables mean a 1.0 program read with 1.1 tables is mislabelled
    /// almost throughout.
    #[must_use]
    pub fn label_for(self, value: u16, firmware: Version) -> Option<&'static str> {
        match self.kind() {
            Kind::Continuous => None,
            Kind::Switch => match value {
                0 => Some("Off"),
                1 => Some("On"),
                _ => None,
            },
            Kind::Enumerated(table) => table.table_for(firmware).name_of(value),
        }
    }

    /// Returns the named values this parameter accepts, on
    /// [`DEFAULT_FIRMWARE`].
    ///
    /// `None` unless the parameter's table names **every** value it accepts,
    /// which is what a host has to know before drawing a list. A list built from
    /// a table that names only some of them would drop the rest, and reopening it
    /// on an unnamed value would move the sound. Where this answers `None`, show
    /// the raw value.
    ///
    /// Also `None` for a switch, whose two values [`label`](ParamId::label)
    /// names and which a host draws as a light rather than a list.
    ///
    /// ```
    /// use deepmind_midi::param::ParamId;
    ///
    /// let shapes = ParamId::Lfo1Shape.choices().expect("all seven are named");
    /// assert_eq!(shapes.len(), 7);
    /// assert_eq!(shapes.first().map(|entry| entry.name), Some("Sine"));
    ///
    /// // A table that only writes down the start of a documented run cannot
    /// // name the rest of it, and says so rather than guessing.
    /// assert!(ParamId::Lfo1MonoMode.choices().is_none());
    /// assert!(ParamId::Lfo1Rate.choices().is_none());
    /// ```
    #[must_use]
    pub fn choices(self) -> Option<&'static [ValueEntry]> {
        self.choices_for(DEFAULT_FIRMWARE)
    }

    /// Returns the named values this parameter accepts, on the firmware a
    /// device inquiry reported.
    ///
    /// Use this wherever [`label_for`](ParamId::label_for) applies: a list drawn
    /// from the wrong firmware's table is a list of the wrong names.
    #[must_use]
    pub fn choices_for(self, firmware: Version) -> Option<&'static [ValueEntry]> {
        let Kind::Enumerated(table) = self.kind() else {
            return None;
        };
        let entries = table.table_for(firmware).entries;
        // The entries are in value order, so the ones this parameter accepts
        // are one run of them. Counting the run and comparing it with the range
        // is what says the table covers the range rather than part of it.
        let first = entries.iter().position(|entry| self.accepts(entry.value))?;
        let run = entries.get(first..)?;
        let named = run
            .iter()
            .take_while(|entry| self.accepts(entry.value))
            .count();
        let span = usize::from(self.max() - self.min()) + 1;
        if named != span {
            return None;
        }
        run.get(..named)
    }

    /// Returns the controller that drives this parameter, if one does.
    #[must_use]
    pub fn controller(self) -> Option<&'static Controller> {
        Controller::for_parameter(self)
    }

    /// Returns the program parameters this parameter's `value` names, on
    /// [`DEFAULT_FIRMWARE`].
    ///
    /// The modulation matrix is what has an answer: a `Mod n Destination`
    /// holding 20 reads `VCF Freq` on the display and moves
    /// [`ParamId::VcfFrequency`]. Empty for every parameter whose values name no
    /// other parameter, and for a destination that names something no program
    /// parameter addresses.
    ///
    /// ```
    /// use deepmind_midi::param::ParamId;
    ///
    /// assert_eq!(
    ///     ParamId::Mod3Destination.targets(20),
    ///     &[ParamId::VcfFrequency],
    /// );
    /// assert!(ParamId::Mod3Destination.targets(0).is_empty());   // Off
    /// assert!(ParamId::Lfo1Rate.targets(64).is_empty());         // a sweep
    /// ```
    #[must_use]
    pub fn targets(self, value: u16) -> &'static [ParamId] {
        self.targets_for(value, DEFAULT_FIRMWARE)
    }

    /// Returns the program parameters this parameter's `value` names, on the
    /// firmware a device inquiry reported.
    ///
    /// Use this wherever [`label_for`](ParamId::label_for) applies, and for the
    /// same reason: firmware 1.1 renumbered the destination table, so 120 of its
    /// 130 entries mean something else on 1.0.
    #[must_use]
    pub fn targets_for(self, value: u16, firmware: Version) -> &'static [ParamId] {
        match self.kind() {
            Kind::Continuous | Kind::Switch => &[],
            Kind::Enumerated(table) => table.table_for(firmware).parameters_of(value),
        }
    }

    /// Returns how much of `destination`'s own range a full modulation depth
    /// on this parameter covers, where the specification establishes it.
    ///
    /// `self` is one of the eight `Mod n Depth` parameters and `destination`
    /// is a program parameter the matrix can reach. The answer is `None` for
    /// any other pair, and `None` for every pair today: the manual prints the
    /// depth's range, `-128` to `+127` about its centre, and nothing that
    /// relates a depth to what it does to the bytes at the other end of the
    /// routing. Whether full depth sweeps a destination over its whole range,
    /// half of it, or something that depends on the destination is not
    /// printed and has not been measured.
    ///
    /// The accessor exists so that a host has somewhere to ask, and keeps its
    /// assumption marked until the answer is a number rather than a guess. A
    /// measurement, when one is made, belongs in `spec/measurements.toml`
    /// beside the other readings and lands here.
    ///
    /// ```
    /// use deepmind_midi::param::ParamId;
    ///
    /// // Not established, so a host keeps saying so.
    /// assert_eq!(ParamId::Mod1Depth.modulation_reach(ParamId::VcfFrequency), None);
    /// // Not a depth, or not something the matrix reaches.
    /// assert_eq!(ParamId::VcfFrequency.modulation_reach(ParamId::VcfFrequency), None);
    /// assert_eq!(ParamId::Mod1Depth.modulation_reach(ParamId::ArpPattern), None);
    /// ```
    #[must_use]
    pub fn modulation_reach(self, destination: Self) -> Option<f32> {
        /// What has been established: nothing yet. A row is a destination and
        /// the fraction of its range a full depth covers.
        const REACH: [(ParamId, f32); 0] = [];

        if !MOD_DEPTHS.contains(&self) {
            return None;
        }
        TableId::ModDestination
            .table()
            .values_naming(destination)
            .next()?;
        REACH
            .iter()
            .find(|&&(reached, _)| reached == destination)
            .map(|&(_, fraction)| fraction)
    }

    /// Builds an NRPN edit setting this parameter to `value`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ValueOutOfRange`] when the parameter does not accept the
    /// value. [`ParamId::clamp`] is there for callers that would rather bend the
    /// value than refuse it.
    pub const fn edit(self, value: u16) -> Result<NrpnEdit> {
        NrpnEdit::new(self, value)
    }

    /// Returns `raw` scaled down to the seven bits a control change carries.
    ///
    /// The manual's rule is the value over its maximum, in 127ths. Here it is
    /// the value over its *range*, which is the same arithmetic for every
    /// parameter that starts at zero (all 90 that have a controller) and the
    /// only reading that means anything for one that does not.
    ///
    /// Lossy for a parameter whose range runs past 127, which is most of them.
    #[must_use]
    pub const fn to_cc_value(self, raw: u16) -> u8 {
        let info = self.info();
        let span = info.max - info.min;
        if span == 0 {
            return 0;
        }
        let scaled = ((self.clamp(raw) - info.min) as u32 * 127) / span as u32;
        // The numerator is at most `span * 127`, so the quotient is at most 127.
        (scaled & 0x7F) as u8
    }

    /// Returns the raw value a control change of `value` sets.
    ///
    /// The inverse of [`ParamId::to_cc_value`] at both ends, and not a round
    /// trip between them: a controller reaches 128 of the 256 values an NRPN can
    /// address.
    #[must_use]
    pub const fn from_cc_value(self, value: u8) -> u16 {
        let info = self.info();
        let span = (info.max - info.min) as u32;
        let raw = info.min as u32 + ((value & 0x7F) as u32 * span) / 127;
        // `value` is seven bits, so the quotient is at most `span`, and
        // `min + span` is `max`, which is a u16.
        self.clamp((raw & 0xFFFF) as u16)
    }
}

impl fmt::Display for ParamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl Group {
    /// Returns the parameters in this group, in offset order.
    ///
    /// Allocates nothing: it is a filter over [`ParamId::ALL`].
    pub fn parameters(self) -> impl Iterator<Item = ParamId> {
        ParamId::ALL
            .iter()
            .copied()
            .filter(move |parameter| parameter.group() == self)
    }
}

impl fmt::Display for Group {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl TableId {
    /// Returns this table as of [`DEFAULT_FIRMWARE`].
    #[must_use]
    pub const fn table(self) -> &'static ValueTable {
        self.table_for(DEFAULT_FIRMWARE)
    }
}

impl fmt::Display for TableId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.table().name)
    }
}

/// One parameter edit, as the four control changes that carry it.
///
/// The synthesizer keeps a selected-parameter register per interface, so a host
/// sweeping one control can send the selection once and then data entry pairs
/// alone. This type always sends all four, which is correct in every order and
/// after any other traffic; a host that wants the shorter form knows when it is
/// safe and can send the pairs itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NrpnEdit {
    /// The parameter being set.
    pub parameter: ParamId,
    /// The value it is being set to, inside the parameter's range.
    pub value: u16,
}

impl NrpnEdit {
    /// Bytes an edit encodes to, without running status.
    pub const LEN: usize = 12;

    /// Builds an edit.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ValueOutOfRange`] when the parameter does not accept the
    /// value.
    pub const fn new(parameter: ParamId, value: u16) -> Result<Self> {
        if parameter.accepts(value) {
            Ok(Self { parameter, value })
        } else {
            Err(Error::ValueOutOfRange {
                parameter: parameter.offset(),
                value,
                max: parameter.max(),
            })
        }
    }

    /// Returns the four controller and value pairs, in the order they are sent.
    ///
    /// The NRPN number needs both of its bytes: 114 of the 242 parameters sit
    /// past offset 127, where the number's high byte stops being zero.
    ///
    /// The value is split across data entry MSB and LSB even where the
    /// parameter's range would fit in the LSB alone. Sending both costs three
    /// bytes and cannot be misread.
    #[must_use]
    pub const fn controls(self) -> [(u8, u8); 4] {
        let offset = self.parameter.offset();
        [
            (NRPN_NUMBER_MSB, (offset >> 7) & 0x7F),
            (NRPN_NUMBER_LSB, offset & 0x7F),
            (DATA_ENTRY_MSB, ((self.value >> 7) & 0x7F) as u8),
            (DATA_ENTRY_LSB, (self.value & 0x7F) as u8),
        ]
    }

    /// Writes the edit into `out` and returns how many bytes it used.
    ///
    /// # Errors
    ///
    /// Returns [`Error::BufferTooSmall`] for a buffer shorter than
    /// [`NrpnEdit::LEN`].
    pub fn encode_into(self, channel: Channel, out: &mut [u8]) -> Result<usize> {
        if out.len() < Self::LEN {
            return Err(Error::BufferTooSmall {
                needed: Self::LEN,
                available: out.len(),
            });
        }
        let mut written = 0;
        for (slot, (controller, value)) in out.chunks_exact_mut(3).zip(self.controls()) {
            written +=
                ChannelMessage::ControlChange { controller, value }.encode_into(channel, slot)?;
        }
        Ok(written)
    }
}

impl fmt::Display for NrpnEdit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.parameter.label(self.value) {
            Some(label) => write!(f, "{} = {label}", self.parameter),
            None => write!(f, "{} = {}", self.parameter, self.value),
        }
    }
}

#[cfg(test)]
#[expect(
    clippy::expect_used,
    reason = "a failed expectation is the test failure"
)]
mod tests {
    use super::*;
    use crate::ids::ProtocolVersion;

    /// Firmware 1.0, the version the manual's NRPN appendix describes.
    const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };

    #[test]
    fn every_offset_names_exactly_one_parameter() {
        for (index, parameter) in ParamId::ALL.iter().copied().enumerate() {
            let offset = u8::try_from(index).expect("242 offsets fit in a byte");
            assert_eq!(parameter.offset(), offset);
            assert_eq!(ParamId::from_offset(offset), Ok(parameter));
        }
        assert_eq!(
            ParamId::from_offset(242),
            Err(Error::ParameterOutOfRange(242))
        );
    }

    /// The parameter table is the dump layout: one parameter per byte of a
    /// comms protocol version 6 program, with nothing left over.
    #[test]
    fn the_table_is_as_long_as_a_program_dump() {
        assert_eq!(
            ProtocolVersion::V6.program_data_len(),
            PARAMETER_COUNT,
            "every byte of a program is a parameter"
        );
    }

    #[test]
    fn every_parameter_belongs_to_exactly_one_group() {
        let counted: usize = Group::ALL
            .iter()
            .map(|group| group.parameters().count())
            .sum();
        assert_eq!(counted, PARAMETER_COUNT);
        assert_eq!(ParamId::Lfo1Rate.group(), Group::Lfo1);
        assert_eq!(Group::Lfo1.name(), "LFO 1");
    }

    #[test]
    fn an_nrpn_edit_is_four_control_changes() {
        let mut bytes = [0; NrpnEdit::LEN];
        let len = ParamId::Lfo1Shape
            .edit(3)
            .expect("3 is an LFO shape")
            .encode_into(Channel::ONE, &mut bytes)
            .expect("the buffer is long enough");
        assert_eq!(len, NrpnEdit::LEN);
        assert_eq!(
            bytes,
            [0xB0, 99, 0, 0xB0, 98, 2, 0xB0, 6, 0, 0xB0, 38, 3],
            "select parameter 2, then set it to 3"
        );
    }

    /// 114 parameters sit past offset 127, where the NRPN number needs its high
    /// byte. Zeroing it would edit a different parameter, quietly.
    #[test]
    fn a_parameter_past_offset_127_sets_the_number_high_byte() {
        let parameter = ParamId::from_offset(200).expect("200 is a parameter");
        let edit = parameter.edit(0).expect("zero is in range");
        assert_eq!(edit.controls()[0], (NRPN_NUMBER_MSB, 1));
        assert_eq!(edit.controls()[1], (NRPN_NUMBER_LSB, 72));
    }

    /// A value above 127 needs both data entry bytes, which is most of them:
    /// most parameters run to 255.
    #[test]
    fn a_value_past_127_sets_both_data_entry_bytes() {
        let edit = ParamId::Lfo1Rate.edit(200).expect("200 is in range");
        assert_eq!(edit.controls()[2], (DATA_ENTRY_MSB, 1));
        assert_eq!(edit.controls()[3], (DATA_ENTRY_LSB, 72));
    }

    #[test]
    fn a_value_outside_the_range_is_refused_rather_than_sent() {
        assert_eq!(
            ParamId::Lfo1Shape.edit(7),
            Err(Error::ValueOutOfRange {
                parameter: 2,
                value: 7,
                max: 6,
            })
        );
        assert_eq!(ParamId::Lfo1Shape.clamp(7), 6);
        assert!(ParamId::Lfo1Shape.accepts(6));
    }

    #[test]
    fn a_short_buffer_is_refused_rather_than_half_filled() {
        let mut bytes = [0; NrpnEdit::LEN - 1];
        assert_eq!(
            ParamId::Lfo1Rate
                .edit(0)
                .expect("zero is in range")
                .encode_into(Channel::ONE, &mut bytes),
            Err(Error::BufferTooSmall {
                needed: NrpnEdit::LEN,
                available: NrpnEdit::LEN - 1,
            })
        );
        assert_eq!(bytes, [0; NrpnEdit::LEN - 1]);
    }

    #[test]
    fn switches_and_value_tables_name_their_values_and_sweeps_do_not() {
        assert_eq!(ParamId::Lfo1KeySync.kind(), Kind::Switch);
        assert_eq!(ParamId::Lfo1KeySync.label(0), Some("Off"));
        assert_eq!(ParamId::Lfo1KeySync.label(1), Some("On"));
        assert_eq!(ParamId::Lfo1KeySync.label(2), None);

        assert_eq!(
            ParamId::Lfo1Shape.kind(),
            Kind::Enumerated(TableId::LfoShape)
        );
        assert_eq!(ParamId::Lfo1Shape.label(6), Some("Sample & Glide"));

        assert_eq!(ParamId::Lfo1Rate.kind(), Kind::Continuous);
        assert_eq!(ParamId::Lfo1Rate.label(64), None);
    }

    /// Every value a confirmed, complete table covers has a name. A gap would
    /// leave a host with a value it can address and cannot display.
    #[test]
    fn a_complete_value_table_names_every_value_its_parameter_accepts() {
        for parameter in ParamId::ALL.iter().copied() {
            let Kind::Enumerated(id) = parameter.kind() else {
                continue;
            };
            let table = id.table();
            if table.partial || !table.confirmed {
                continue;
            }
            for value in parameter.min()..=parameter.max() {
                assert!(
                    parameter.label(value).is_some(),
                    "{parameter} has no name for {value} in {table}"
                );
            }
        }
    }

    /// The renumbering that makes firmware a lookup key rather than a footnote:
    /// modulation source 6 is Expression on 1.1 and LFO 1 on 1.0.
    #[test]
    fn the_firmware_a_program_was_written_on_changes_what_its_values_mean() {
        assert_eq!(ParamId::Mod1Source.label(6), Some("Expression"));
        assert_eq!(ParamId::Mod1Source.label_for(6, FIRMWARE_1_0), Some("LFO1"));
        assert_eq!(TableId::ModSource.table_for(FIRMWARE_1_0).entries.len(), 23);
        assert_eq!(TableId::ModSource.table().entries.len(), 25);
    }

    /// The join the modulation matrix needs: a destination is an abbreviation
    /// the display prints, and this is what it addresses.
    #[test]
    fn a_modulation_destination_names_the_parameters_it_moves() {
        assert_eq!(ParamId::Mod3Destination.label(20), Some("VCF Freq"));
        assert_eq!(
            ParamId::Mod3Destination.targets(20),
            &[ParamId::VcfFrequency]
        );

        // Several destinations plainly move more than one, which is why this
        // is a slice.
        let attacks = ParamId::Mod1Destination.targets(25);
        assert_eq!(ParamId::Mod1Destination.label(25), Some("All Attack"));
        assert_eq!(attacks.len(), 3);
        assert!(attacks.contains(&ParamId::VcfEnvelopeAttackTime));
    }

    /// Empty is an answer here, and it means two different things: a
    /// destination that addresses nothing a program holds, and a parameter
    /// whose values name no parameter at all.
    #[test]
    fn a_destination_that_addresses_nothing_says_so_by_naming_nothing() {
        assert!(ParamId::Mod1Destination.targets(0).is_empty(), "Off");
        // Oscillator pitch is played rather than stored.
        assert_eq!(ParamId::Mod1Destination.label(11), Some("OSC1 Pitch"));
        assert!(ParamId::Mod1Destination.targets(11).is_empty());

        assert!(ParamId::Lfo1Rate.targets(64).is_empty(), "a sweep");
        assert!(ParamId::Lfo1KeySync.targets(1).is_empty(), "a switch");
        assert!(ParamId::Lfo1Shape.targets(3).is_empty(), "a named set");
    }

    /// The renumbering reaches the join as well as the names: destination 20 is
    /// the filter cutoff on 1.1 and the filter's LFO depth on 1.0.
    #[test]
    fn the_firmware_moves_what_a_destination_addresses() {
        assert_eq!(
            ParamId::Mod1Destination.targets(20),
            &[ParamId::VcfFrequency]
        );
        assert_eq!(
            ParamId::Mod1Destination.targets_for(20, FIRMWARE_1_0),
            &[ParamId::VcfLfoDepth]
        );
        assert_eq!(
            ParamId::Mod1Destination.targets_for(17, FIRMWARE_1_0),
            &[ParamId::VcfFrequency]
        );
    }

    /// Every FX slot a destination names is an FX slot parameter, which is what
    /// lets a host label the 48 bytes through the panel tables.
    #[test]
    fn every_effect_slot_is_reachable_from_the_matrix() {
        let table = TableId::ModDestination.table();
        let slots = table
            .entries
            .iter()
            .flat_map(|entry| entry.parameters.iter().copied())
            .filter(|parameter| parameter.group() == Group::Effects)
            .count();
        // Four engines of twelve slots, and the four output gains.
        assert_eq!(slots, 4 * 12 + 4);
    }

    /// The reverse join agrees with a scan of the forward one, parameter by
    /// parameter, and comes out narrowest first.
    #[test]
    fn the_destinations_naming_a_parameter_come_narrowest_first() {
        let table = TableId::ModDestination.table();
        for parameter in ParamId::ALL.iter().copied() {
            let mut previous: Option<(usize, u16)> = None;
            let mut yielded = 0;
            for value in table.values_naming(parameter) {
                let entry = table.entry(value).expect("a listed value");
                assert!(
                    entry.parameters.contains(&parameter),
                    "{parameter} by {value}"
                );
                let key = (entry.parameters.len(), value);
                assert!(
                    previous.is_none_or(|last| key > last),
                    "{parameter} out of order"
                );
                previous = Some(key);
                yielded += 1;
            }
            let scanned = table
                .entries
                .iter()
                .filter(|entry| entry.parameters.contains(&parameter))
                .count();
            assert_eq!(yielded, scanned, "{parameter}");
        }

        // The narrowest destination for an envelope time is the one that
        // moves only it, whatever its value.
        let one = table
            .values_naming(ParamId::ModEnvelopeReleaseTime)
            .next()
            .expect("the matrix reaches it");
        assert_eq!(table.parameters_of(one), &[ParamId::ModEnvelopeReleaseTime]);
        // And the firmware 1.0 table answers with its own numbering.
        let old = TableId::ModDestination.table_for(FIRMWARE_1_0);
        let first = old
            .values_naming(ParamId::VcfFrequency)
            .next()
            .expect("VCF Freq is on 1.0 too");
        assert_eq!(old.name_of(first), Some("VCF Freq"));
        assert_ne!(
            first,
            table
                .values_naming(ParamId::VcfFrequency)
                .next()
                .expect("and on 1.1")
        );
    }

    /// A source swings one way or the other where the specification settles
    /// it, on both firmware numberings, and the tables that are not sources
    /// swing nowhere.
    #[test]
    fn a_source_says_which_way_it_swings() {
        let sources = TableId::ModSource.table();
        assert_eq!(sources.swing_of(7), Some(Swing::Centred)); // LFO1
        assert_eq!(sources.swing_of(16), Some(Swing::Rising)); // LFO1 (Uni)
        assert_eq!(sources.swing_of(1), Some(Swing::Centred)); // Pitch Bend
        assert_eq!(sources.swing_of(2), Some(Swing::Rising)); // Mod Wheel
        assert_eq!(sources.swing_of(0), None); // Off
        assert_eq!(sources.swing_of(12), None); // Note Num
        assert_eq!(sources.swing_of(200), None);

        let old = TableId::ModSource.table_for(FIRMWARE_1_0);
        assert_eq!(old.name_of(6), Some("LFO1"));
        assert_eq!(old.swing_of(6), Some(Swing::Centred));

        for id in TableId::ALL.iter().copied() {
            if id == TableId::ModSource {
                continue;
            }
            assert!(
                id.table().entries.iter().all(|entry| entry.swing.is_none()),
                "{id:?} swings"
            );
        }
    }

    /// Both ends of the matrix carry cells and nothing else does; a cell is a
    /// drawing rather than a blank; every end a host cannot reach a picture
    /// through is drawn; and the two firmware tables draw an entry the same
    /// way, whatever number it has.
    #[test]
    fn a_matrix_entry_carries_a_cell_where_one_was_drawn() {
        for id in [TableId::ModSource, TableId::ModDestination] {
            let table = id.table();
            assert!(table.cell_of(0).is_none(), "{id:?}: Off is nothing to draw");
            // Every cell is drawn for a value the table lists, and the values
            // ascend, which is what lets `cell_of` search rather than scan.
            for (left, right) in table.cells.iter().zip(table.cells.iter().skip(1)) {
                assert!(
                    left.0 < right.0,
                    "{id:?}: cells out of order at {}",
                    right.0
                );
            }
            for (value, cell) in table.cells {
                assert!(
                    table.entry(*value).is_some(),
                    "{id:?}: a cell for nothing at {value}"
                );
                assert!(
                    cell.rows().iter().any(|row| *row != 0),
                    "{id:?}: {value} is blank"
                );
                assert!(
                    cell.rows().iter().any(|row| *row != 0x7f),
                    "{id:?}: {value} is solid"
                );
            }
            // A renumbered entry keeps its drawing, which is what joining the
            // two firmware tables by name is for.
            let old = id.table_for(FIRMWARE_1_0);
            for entry in table.entries {
                let Some(twin) = old.entries.iter().find(|e| e.name == entry.name) else {
                    continue;
                };
                assert_eq!(
                    table.cell_of(entry.value),
                    old.cell_of(twin.value),
                    "{}",
                    entry.name
                );
            }
        }

        // Every source but Off is drawn.
        let sources = TableId::ModSource.table();
        for entry in sources.entries.iter().filter(|e| e.name != "Off") {
            assert!(
                sources.cell_of(entry.value).is_some(),
                "the source {} is undrawn",
                entry.name
            );
        }

        // So is every destination a host cannot reach a picture through: the
        // ones naming no program parameter and the ones naming a set of them.
        // A destination naming exactly one is pictured by that parameter's own
        // glyph, which is where the effect slots' pictures come from too.
        let destinations = TableId::ModDestination.table();
        for entry in destinations.entries.iter().filter(|e| e.name != "Off") {
            if entry.parameters.len() == 1 {
                continue;
            }
            assert!(
                destinations.cell_of(entry.value).is_some(),
                "the destination {} is undrawn",
                entry.name
            );
        }

        for id in TableId::ALL.iter().copied() {
            if matches!(id, TableId::ModSource | TableId::ModDestination) {
                continue;
            }
            assert!(id.table().cells.is_empty(), "{id:?} carries a cell");
        }
    }

    /// Nothing relates a depth to a destination's range yet, and the accessor
    /// says so for every pair rather than for some.
    #[test]
    fn no_modulation_reach_is_established() {
        for depth in MOD_DEPTHS {
            for destination in ParamId::ALL.iter().copied() {
                assert_eq!(depth.modulation_reach(destination), None);
            }
        }
        assert_eq!(
            ParamId::Mod1Source.modulation_reach(ParamId::VcfFrequency),
            None
        );
    }

    /// A destination naming a parameter twice, or naming one that does not
    /// exist, is caught in the specification rather than here; what this
    /// checks is that nothing generated a name the table cannot resolve.
    #[test]
    fn every_parameter_a_table_names_is_a_parameter() {
        for id in TableId::ALL {
            for entry in id.table().entries {
                for parameter in entry.parameters {
                    assert_eq!(
                        ParamId::from_offset(parameter.offset()),
                        Ok(*parameter),
                        "{entry:?} in {id}"
                    );
                }
            }
        }
    }

    /// The order the panel is in, which a host would otherwise read off the
    /// offsets itself. `ALL` is alphabetical and is not that order.
    #[test]
    fn the_groups_are_listed_twice_in_two_different_orders() {
        assert_eq!(Group::ORDER.len(), Group::ALL.len());
        for group in Group::ALL {
            assert!(Group::ORDER.contains(group), "{group} is not laid out");
        }

        let starts = Group::ORDER.iter().map(|group| {
            group
                .parameters()
                .next()
                .expect("a group in the table has a parameter")
                .offset()
        });
        assert!(starts.is_sorted(), "the order is not the instrument's own");
        assert_eq!(Group::ORDER.first(), Some(&Group::Lfo1));
        assert_eq!(Group::ORDER.last(), Some(&Group::Program));
    }

    /// A list is only honest where the table names every value the parameter
    /// accepts; anywhere else the raw number is the reading.
    #[test]
    fn a_parameter_offers_a_list_only_when_every_value_has_a_name() {
        let shapes = ParamId::Lfo1Shape.choices().expect("all seven are named");
        assert_eq!(shapes.len(), usize::from(ParamId::Lfo1Shape.max()) + 1);
        assert_eq!(shapes.first().map(|entry| entry.name), Some("Sine"));
        assert_eq!(
            shapes.last().map(|entry| entry.name),
            Some("Sample & Glide")
        );

        // A table that writes down the start of a documented run names the
        // first of 254 values and not the rest.
        assert!(TableId::LfoMonoMode.table().partial);
        assert!(ParamId::Lfo1MonoMode.choices().is_none());

        assert!(ParamId::Lfo1Rate.choices().is_none(), "a sweep");
        assert!(ParamId::Lfo1KeySync.choices().is_none(), "a switch");
    }

    /// Whatever a list offers has a name, which is what makes it safe to draw
    /// as one: a host picking an entry never picks an unnamed value.
    #[test]
    fn every_value_a_list_offers_is_named_and_accepted() {
        for firmware in [DEFAULT_FIRMWARE, FIRMWARE_1_0] {
            for parameter in ParamId::ALL.iter().copied() {
                let Some(choices) = parameter.choices_for(firmware) else {
                    continue;
                };
                for entry in choices {
                    assert!(parameter.accepts(entry.value), "{parameter}");
                    assert_eq!(
                        parameter.label_for(entry.value, firmware),
                        Some(entry.name),
                        "{parameter}"
                    );
                }
                for value in parameter.min()..=parameter.max() {
                    assert!(
                        choices.iter().any(|entry| entry.value == value),
                        "{parameter} offers a list that skips {value}"
                    );
                }
            }
        }
    }

    #[test]
    fn a_parameter_name_drops_the_group_a_panel_already_prints() {
        assert_eq!(ParamId::VcfEnvelopeDepth.short_name(), "Envelope Depth");
        assert_eq!(ParamId::Lfo1Rate.short_name(), "Rate");
        assert_eq!(ParamId::ProgramNameChar1.short_name(), "Name Char 1");
        // A name that does not start with its group keeps all of itself.
        assert_eq!(ParamId::Mod1Source.short_name(), "Mod 1 Source");

        for parameter in ParamId::ALL.iter().copied() {
            let short = parameter.short_name();
            assert!(!short.is_empty(), "{parameter} shortens to nothing");
            assert!(parameter.name().ends_with(short), "{parameter}");
        }
    }

    #[test]
    fn a_table_answers_only_for_the_values_it_lists() {
        let partial = TableId::LfoMonoMode.table();
        assert!(partial.partial, "the SPREAD-n run is not written out");
        assert_eq!(partial.name_of(1), Some("Mono"));
        assert_eq!(partial.name_of(200), None);
    }

    /// `for_cc` is a binary search, which the table's order has to allow.
    #[test]
    fn the_controller_table_is_in_controller_number_order() {
        assert!(CONTROLLERS.windows(2).all(|pair| match pair {
            [a, b] => a.cc < b.cc,
            _ => true,
        }));
        assert_eq!(Controller::for_cc(255), None);
    }

    #[test]
    fn controllers_and_parameters_agree_in_both_directions() {
        for controller in &CONTROLLERS {
            assert_eq!(Controller::for_cc(controller.cc), Some(controller));
            let Some(parameter) = controller.parameter else {
                assert_ne!(controller.kind, ControllerKind::Parameter);
                continue;
            };
            assert_eq!(controller.kind, ControllerKind::Parameter);
            assert_eq!(parameter.controller(), Some(controller));
        }
        assert_eq!(Controller::for_cc(3), None, "CC 3 is undefined");
    }

    /// A controller carries seven bits, so it reaches 128 of the 256 values an
    /// NRPN can address. The two ends have to land exactly even so.
    #[test]
    fn a_control_change_reaches_the_ends_of_the_range_it_scales() {
        for parameter in ParamId::ALL.iter().copied() {
            assert_eq!(parameter.to_cc_value(parameter.min()), 0, "{parameter}");
            assert_eq!(parameter.to_cc_value(parameter.max()), 127, "{parameter}");
            assert_eq!(parameter.from_cc_value(0), parameter.min(), "{parameter}");
            assert_eq!(parameter.from_cc_value(127), parameter.max(), "{parameter}");
        }
    }

    /// A parameter that fits in seven bits round trips through a controller;
    /// one that does not loses the values between.
    #[test]
    fn scaling_is_lossless_only_where_the_range_fits_in_seven_bits() {
        let fine = ParamId::ProgramNameChar1;
        assert_eq!(fine.max(), 127);
        for raw in 0..=fine.max() {
            assert_eq!(fine.from_cc_value(fine.to_cc_value(raw)), raw);
        }

        let coarse = ParamId::Lfo1Rate;
        assert_eq!(coarse.max(), 255);
        assert_eq!(coarse.from_cc_value(coarse.to_cc_value(3)), 2);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn an_edit_prints_as_the_synthesizer_would_name_it() {
        let edit = ParamId::Lfo1Shape.edit(1).expect("1 is an LFO shape");
        assert_eq!(alloc::format!("{edit}"), "LFO 1 Shape = Triangle");
        let sweep = ParamId::Lfo1Rate.edit(64).expect("64 is in range");
        assert_eq!(alloc::format!("{sweep}"), "LFO 1 Rate = 64");
    }

    /// A centre outside the range would be a control drawn about a point it
    /// cannot reach, and a centre at either end would not be a centre.
    #[test]
    fn a_bipolar_centre_is_inside_the_range_and_not_at_an_end() {
        let mut bipolar = 0;
        for parameter in ParamId::ALL.iter().copied() {
            let Shape::Bipolar { centre } = parameter.shape() else {
                continue;
            };
            bipolar += 1;
            assert!(parameter.accepts(centre), "{parameter}");
            assert!(centre > parameter.min(), "{parameter} centres on its floor");
            assert!(centre < parameter.max(), "{parameter} centres on its top");
        }
        assert_eq!(bipolar, 45);

        assert_eq!(
            ParamId::Mod1Depth.shape(),
            Shape::Bipolar { centre: 128 },
            "-128 at 0 and +127 at 255"
        );
        assert_eq!(ParamId::Lfo1Rate.shape(), Shape::Unipolar);
    }

    /// The whole of what the sequencer strip needs: a centre to draw about, a
    /// value that is not a position, and the parameter that says how much of
    /// the run is played.
    #[test]
    fn a_sequencer_step_says_what_it_is() {
        let step = ParamId::SeqStepValue1;
        assert_eq!(step.shape(), Shape::Bipolar { centre: 128 });
        assert_eq!(step.inactive(), Some(0), "zero skips the step");
        assert_eq!(step.bounded_by(), Some(ParamId::SequenceLength));

        // All 32 of them, and nothing else in the table.
        let steps = || {
            ParamId::ALL
                .iter()
                .copied()
                .filter(|parameter| parameter.bounded_by().is_some())
        };
        assert_eq!(steps().count(), 32);
        for step in steps() {
            assert_eq!(step.group(), Group::ControlSequencer);
            assert_eq!(step.inactive(), Some(0));
            assert!(step.name().starts_with("Seq Step Value"));
        }
        assert_eq!(ParamId::SequenceLength.bounded_by(), None);
        assert_eq!(ParamId::Lfo1Rate.inactive(), None);
    }

    /// Two steps carried `kind = "switch"` while accepting 256 values, which
    /// their own range and their own note contradicted. Every step is the same
    /// sweep as every other, and the reason the table used to say otherwise is
    /// recorded where a host can show it.
    #[test]
    fn every_sequencer_step_reads_the_same_way() {
        for step in ParamId::ALL
            .iter()
            .copied()
            .filter(|p| p.name().starts_with("Seq Step Value"))
        {
            assert_eq!(step.kind(), Kind::Continuous, "{step}");
            assert_eq!(step.max(), 255, "{step}");
        }
        assert!(
            ParamId::SeqStepValue9
                .correction()
                .is_some_and(|text| text.contains("switch")),
            "the slip is recorded"
        );
        assert_eq!(ParamId::SeqStepValue1.correction(), None);
    }

    /// The prose is a getter over what the specification records, and it is
    /// there for every parameter the manual says anything about.
    #[test]
    fn the_manuals_own_words_are_reachable() {
        assert_eq!(
            ParamId::VcfFrequency.display(),
            Some("50.0 Hz to 20000.0 Hz")
        );
        assert_eq!(ParamId::Lfo1SlewRate.display(), None);
        assert_eq!(ParamId::Lfo1SlewRate.note(), None);
        assert!(
            ParamId::Lfo1Rate
                .note()
                .is_some_and(|note| note.contains("Arp Sync"))
        );

        let counted = |field: fn(ParamId) -> Option<&'static str>| {
            ParamId::ALL
                .iter()
                .copied()
                .filter(|parameter| field(*parameter).is_some())
                .count()
        };
        assert_eq!(counted(ParamId::display), 26);
        assert_eq!(counted(ParamId::note), 129);
        assert_eq!(counted(ParamId::correction), 37);
    }

    /// The description answers the same way for every parameter, whichever way
    /// the feature is set: the point of the `Option` is that a host writes one
    /// code path and not two.
    #[test]
    fn a_description_is_there_exactly_when_the_feature_is() {
        let described = ParamId::ALL
            .iter()
            .copied()
            .filter(|parameter| parameter.description().is_some())
            .count();
        assert_eq!(
            described,
            if cfg!(feature = "descriptions") {
                PARAMETER_COUNT
            } else {
                0
            }
        );
    }

    /// A description says what the control does. What a value decodes to is the
    /// note and the value table, and duplicating it here would be two places to
    /// correct the day one of them is wrong.
    #[cfg(feature = "descriptions")]
    #[test]
    fn a_description_says_what_the_control_does() {
        assert!(
            ParamId::VcfFrequency
                .description()
                .is_some_and(|text| text.contains("cutoff")),
        );
        for parameter in ParamId::ALL.iter().copied() {
            let text = parameter.description().expect("every parameter has one");
            assert!(text.ends_with('.'), "{parameter}: not a sentence");
            assert!(
                !text.is_empty() && text.starts_with(char::is_uppercase),
                "{parameter}: {text:?}"
            );
            assert_ne!(
                Some(text),
                parameter.note(),
                "{parameter}: repeats its note"
            );
        }
    }

    /// An unconfirmed reading says so, and says why in the same breath.
    #[test]
    fn an_inferred_reading_is_marked_and_explained() {
        assert!(!ParamId::PitchBendUpDepth.confirmed());
        assert!(ParamId::PitchBendUpDepth.correction().is_some());
        assert!(ParamId::VcfFrequency.confirmed());
        for parameter in ParamId::ALL.iter().copied() {
            assert!(
                parameter.confirmed() || parameter.correction().is_some(),
                "{parameter} is unconfirmed and does not say why"
            );
        }
    }
}