nord-format 0.6.0

Read and write Nord keyboard files from Rust, byte for byte
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
//! Piano libraries (`.npno`).
//!
//! The body is a `CNSP` stream: a metadata prefix carrying the name, a 128-entry
//! key map and ten per-note tables; then a directory of **strokes** — one
//! recorded note each — and the encoded audio those strokes own. [`Piano`] is the
//! file, body verbatim and checksum verified; [`Library`] is the container
//! parsed, a view whose writer re-lays the directory and the audio from the model
//! it holds. [`codec`] turns one stroke's audio back into samples.
//!
//! Offsets below are relative to the body's first byte, and the stream's own
//! integers are big-endian where the CBIN header's are little-endian.
//!
//! | body offset | field |
//! |---|---|
//! | `0x00` | `"CNSP"` |
//! | `0x04` | u16 stream version — `0x450` or `0x464` |
//! | `0x06` | u32, unique per file; meaning open |
//! | `0x1c` | `Name#Variant`, NUL-padded to 32 bytes |
//! | `0x3c` | the bare name, and at `0x5c` the variant — `0x464` streams only |
//! | `0x8c` | 128-entry key map: the root note that plays each key, `0xFF` uncovered |
//! | `0x18c` | 128-entry per-key fine tune, one of ten per-note tables from `0x10c` |
//! | `0x61c` | u16 stream version, echoed |
//! | `0x61e` | u16 channel count, 1 or 2 |
//! | `0x620` | u16 stroke count `N` |
//! | `0x622` | 128 × u16 strokes per root note, summing to `N` |
//! | `0x732` | `N` × 118-byte stroke records, grouped in ascending root order |
//!
//! The prefix's individual field placements: Inferred from specimens; not
//! confirmed on hardware. The container layout as [`Library::to_body`] writes it — a
//! library whose directory and audio this crate re-laid, and one whose audio
//! [`encode`] coded outright, load on the instrument and play at the original's
//! level — and, within it, the key map's value being the recording's root note, a
//! stroke's [`Bank`] being what it is played for, and [`Stroke::layer`] stating the
//! softness the velocity threshold reads: Confirmed on hardware.
//!
//! Audio follows the directory, one span per record in the directory's own order.
//! The first span starts at the next `1022 × channels` boundary offset by
//! [`AUDIO_ALIGN_BIAS`] (the bias is unexplained), the gap in front of it is zero,
//! each span abuts the one before, and the last ends at the body's end. Because a
//! stroke carries its own predictor seeds and its blocks overlap only each other, a
//! span is self-contained and moves verbatim — which is what makes the transforms
//! on [`Library`] no more than a re-lay.
//!
//! ⚠️ Real libraries are tens of megabytes and reading one allocates the body —
//! [`crate::cbin::inspect`] answers container questions in O(1) instead.
//!
//! ⚠️ The header's `location` and `aux` are unchecked here on purpose: this is a
//! library format, where those words hold something other than a bank/slot pair, and
//! no local specimen says what. Gating on them would refuse real files.

pub mod codec;
pub mod encode;
/// A library laid out from a description. Test-only: behind the `synthetic` feature,
/// and always available to this crate's own tests.
#[cfg(any(test, feature = "synthetic"))]
pub mod synthetic;

use crate::cbin::{self, Cbin, Header, RawBody};
use crate::error::{try_vec, Error, ParseError};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::io::{Read, Seek, Write};
use std::ops::RangeInclusive;

pub const FORMAT: &str = "npno";

/// The body's stream magic.
pub const CNSP_MAGIC: &[u8; 4] = b"CNSP";

/// MIDI notes the key map, the count table and each per-note table cover.
pub const NOTES: usize = 128;

/// A key map entry for a note the library does not cover.
pub const UNCOVERED: u8 = 0xff;

/// The stream versions the prefix offsets are validated against. A body with
/// another version still reads and writes verbatim; its fields are refused rather
/// than read from offsets that may not hold them.
pub const KNOWN_VERSIONS: &[u32] = &[0x450, 0x464];

/// The stream version that also carries a long name and a voicing of their own.
const VERSION_SPLIT_NAME: u16 = 0x464;

const KEY_MAP_AT: usize = 0x8c;
const FINE_TUNE_AT: usize = 0x18c;
const VERSION_AT: usize = 0x04;
const VERSION_ECHO_AT: usize = 0x61c;
const CHANNELS_AT: usize = 0x61e;
const STROKE_COUNT_AT: usize = 0x620;
const ROOT_COUNTS_AT: usize = 0x622;

/// The kind of instrument the library states; [`encode::Kind`] names the codes.
const KIND_AT: usize = 0x18;

/// A gain over the whole library, in tenths of a decibel and signed. Confirmed on
/// hardware.
const GAIN_AT: usize = 0x40c;

/// The highest key the instrument damps at note-off; keys above it ring on. Confirmed
/// on hardware.
const DAMPER_TOP_AT: usize = 0x40d;

/// First byte of the stroke directory, and so the length of the prefix.
const DIRECTORY_AT: usize = 0x732;

/// Bytes per stroke record.
const RECORD: usize = 118;

const REC_START: usize = 0x00;
const REC_BANK: usize = 0x04;
const REC_LAYER: usize = 0x05;
const REC_FRAMES: usize = 0x06;
const REC_BLOCKS: usize = 0x0a;
const REC_SEEDS: usize = 0x0c;
const REC_MARKS: usize = 0x1c;
const REC_MARK_BLOCK: usize = 0x2c;
const REC_DECAY: usize = 0x2e;
/// u16 holding the layer value again in vendor records. Sweeping it moved nothing
/// measurable. Confirmed on hardware.
const REC_WINDOW: usize = 0x32;
/// u16 the instrument attenuates the stroke by, one decibel per unit. Confirmed on
/// hardware.
const REC_TRIM: usize = 0x34;
const REC_DECAYS: usize = 0x36;
const REC_ID: usize = 0x6e;

/// Predictor seeds a record carries per channel.
const SEEDS: usize = 4;

/// Length marks a record carries at [`REC_MARKS`].
const MARKS: usize = 4;

/// One-pole decay coefficients a record carries after the one at [`REC_DECAY`], from
/// [`REC_DECAYS`] up to the identifier. This ladder is the decay the instrument applies
/// over the stroke's own; it is non-decreasing across its entries, and a stroke of any
/// bank carries it — including a release stroke, which zeroes only the coefficient at
/// [`REC_DECAY`]. Nothing here derives them from audio. Confirmed on hardware.
pub const DECAYS: usize = 14;
const _: () = assert!(REC_DECAYS + DECAYS * 4 == REC_ID);

/// One [`REC_DECAYS`] entry applying nothing: 1.0 in the ladder's fixed point, where
/// the vendor's own entries sit just below it.
pub const LADDER_UNITY: u32 = 0x0080_0000;

/// The audio grid's offset from a whole number of blocks.
///
/// Unexplained: every library holds it and nothing in the file derives it. The grid
/// it defines is the one the instrument reads. Confirmed on hardware. A library laid
/// out on it plays.
pub const AUDIO_ALIGN_BIAS: usize = 192;

/// Cents one unit of [`Library::fine_tune`] is worth. Measured between 0.6 and
/// 0.8 cents per unit; this is the midpoint. Confirmed on hardware.
pub const FINE_TUNE_CENTS_PER_UNIT: f32 = 0.7;

/// What a stroke is played for, from the record's `+0x04`.
///
/// Confirmed on hardware.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Bank {
    /// Played at note-on. Every library has these.
    Attack,
    /// Played in place of the attack when the sustain pedal is down at note-on, which
    /// the panel's acoustics bit 0 enables. Only the larger libraries carry them.
    Resonance,
    /// Played at note-off.
    Release,
}

impl Bank {
    pub const ALL: [Bank; 3] = [Bank::Attack, Bank::Resonance, Bank::Release];

    pub fn from_code(code: u8) -> Option<Bank> {
        match code {
            0 => Some(Bank::Attack),
            1 => Some(Bank::Resonance),
            2 => Some(Bank::Release),
            _ => None,
        }
    }

    pub fn code(self) -> u8 {
        match self {
            Bank::Attack => 0,
            Bank::Resonance => 1,
            Bank::Release => 2,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Bank::Attack => "attack",
            Bank::Resonance => "resonance",
            Bank::Release => "release",
        }
    }
}

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

/// Which velocity layers of a root to keep.
///
/// A root's layers are counted within one [`Bank`], since each bank indexes its
/// own set. Nothing is renumbered, and nothing should be: selection reads the value
/// a layer states rather than its rank among the layers left ([`Stroke::layer`]), so
/// the survivors keep their place in the velocity range and the softest one left
/// takes over the velocities below it. Confirmed on hardware.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Layers {
    /// The loudest `n` of each root and bank — the `n` lowest layer values.
    Loudest(usize),
    /// Exactly these layer values, wherever they occur.
    Only(BTreeSet<u8>),
}

/// What a transform removed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Change {
    pub strokes_removed: usize,
    pub roots_removed: usize,
    pub keys_uncovered: usize,
}

/// The character the `Name#Variant` field splits on. Neither half may hold it.
pub const NAME_SEPARATOR: char = '#';

/// A fixed-width, NUL-padded text field in the prefix.
#[derive(Clone, Copy)]
struct TextField {
    at: usize,
    len: usize,
}

impl TextField {
    /// `Name#Variant`, on every stream version.
    const COMBINED: TextField = TextField {
        at: 0x1c,
        len: 0x20,
    };
    /// The long name, present only on [`VERSION_SPLIT_NAME`] streams.
    const LONG_NAME: TextField = TextField {
        at: 0x3c,
        len: 0x20,
    };
    /// The voicing, present only on [`VERSION_SPLIT_NAME`] streams.
    const VOICING: TextField = TextField {
        at: 0x5c,
        len: 0x20,
    };

    /// Longest string the field holds, the terminator excluded.
    const fn capacity(self) -> usize {
        self.len - 1
    }

    fn read(self, prefix: &[u8]) -> String {
        let field = &prefix[self.at..self.at + self.len];
        let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
        String::from_utf8_lossy(&field[..end]).into_owned()
    }

    /// Text any of these fields carries back as it was written. The field is a fixed
    /// width of bytes ended by a NUL and read lossily, so a NUL, a control character
    /// and anything outside ASCII are all refused rather than stored.
    fn check_text(text: &str) -> Result<(), Error> {
        match text.chars().find(|&c| !c.is_ascii_graphic() && c != ' ') {
            None => Ok(()),
            Some(bad) => Err(ParseError::AssertFail(format!(
                "{text:?} holds {bad:?}, which the field would not read back as written; it \
                 carries printable ASCII"
            ))
            .into()),
        }
    }

    /// [`TextField::check_text`], and short enough to fit with its terminator.
    fn check(self, text: &str) -> Result<(), Error> {
        TextField::check_text(text)?;
        if text.len() > self.capacity() {
            return Err(ParseError::OutOfBounds {
                value: format!("{text:?} ({} bytes)", text.len()),
                bound: format!("at most {} bytes", self.capacity()),
            }
            .into());
        }
        Ok(())
    }

    fn write(self, prefix: &mut [u8], text: &str) -> Result<(), Error> {
        self.check(text)?;
        let field = &mut prefix[self.at..self.at + self.len];
        field.fill(0);
        field[..text.len()].copy_from_slice(text.as_bytes());
        Ok(())
    }
}

/// One half of `Name#Variant` as a caller supplies it. A separator inside a half
/// would move the split, so the halves that read back would not be the ones written.
fn check_half(what: &str, text: &str) -> Result<(), Error> {
    if text.contains(NAME_SEPARATOR) {
        return Err(ParseError::AssertFail(format!(
            "the {what} {text:?} holds {NAME_SEPARATOR:?}, which is what splits the name from \
             the variant in the field they share"
        ))
        .into());
    }
    TextField::check_text(text)
}

/// A piano library (`npno`): the CBIN container with the `CNSP` body verbatim.
///
/// Reads and writes byte-exactly, checksum verified. [`Piano::library`] parses the
/// body into the model the transforms and the writer work on.
pub struct Piano {
    pub file: Cbin<RawBody>,
}

impl Piano {
    pub fn new() -> Piano {
        Piano {
            file: Cbin {
                header: Header::new(FORMAT, (0, 0), 0),
                body: RawBody(Vec::new()),
            },
        }
    }

    pub fn read_from(reader: &mut (impl Read + Seek)) -> Result<Piano, Error> {
        Ok(Piano {
            file: cbin::read(reader, FORMAT)?,
        })
    }

    pub fn write_to(&self, writer: &mut (impl Write + Seek)) -> Result<(), Error> {
        self.file.write_to(writer)
    }

    /// The body bytes, after checking the magic and that the stream version is one
    /// the prefix offsets are pinned to.
    fn mapped(&self) -> Result<&[u8], Error> {
        let body = &self.file.body.0;
        check_mapped(body)?;
        Ok(body)
    }

    /// The stream version at body `0x04`.
    pub fn stream_version(&self) -> Result<u16, Error> {
        version_of(&self.file.body.0)
    }

    /// The `(name, variant)` pair from the `Name#Variant` field — for
    /// *Electric Grand 1 CP80*, `("Electric Grand 1", "CP80")`. The variant is
    /// empty when the field carries none.
    pub fn name(&self) -> Result<(String, String), Error> {
        let body = self.mapped()?;
        if body.len() < DIRECTORY_AT {
            return Err(short("the prefix"));
        }
        Ok(split_name(&TextField::COMBINED.read(body)))
    }

    /// The 128-entry key map: for each MIDI note, the root note whose strokes play
    /// it, or [`UNCOVERED`].
    pub fn key_map(&self) -> Result<&[u8], Error> {
        self.mapped()?
            .get(KEY_MAP_AT..KEY_MAP_AT + NOTES)
            .ok_or_else(|| short("the key map"))
    }

    /// The container parsed: the prefix, the stroke directory and each stroke's
    /// audio span.
    pub fn library(&self) -> Result<Library<'_>, Error> {
        Library::parse_body(self.file.header.clone(), &self.file.body.0)
    }
}

impl Default for Piano {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for Piano {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("npno::Piano")
            .field("header", &self.file.header)
            .field("body_len", &self.file.body.0.len())
            .finish()
    }
}

/// `Name#Variant` split on its separator, as the field spells each half. A field
/// carrying no separator is all name.
fn raw_halves(field: &str) -> (&str, &str) {
    field.split_once(NAME_SEPARATOR).unwrap_or((field, ""))
}

/// `Name#Variant` split on its separator, each half trimmed of the padding the
/// vendor lays either side of it.
fn split_name(field: &str) -> (String, String) {
    let (name, variant) = raw_halves(field);
    (name.trim().to_owned(), variant.trim().to_owned())
}

/// `key` as an index into a [`NOTES`]-entry table, or an error naming it.
///
/// Every accessor that reaches the key map or a per-note table goes through this: a
/// `u8` runs to 255, and past the table's last entry the byte belongs to the next
/// table.
fn midi_key(what: &str, key: u8) -> Result<usize, Error> {
    let index = usize::from(key);
    if index < NOTES {
        return Ok(index);
    }
    Err(ParseError::OutOfBounds {
        value: format!("{what} {key}"),
        bound: "a MIDI note from 0 through 127".into(),
    }
    .into())
}

fn short(what: &str) -> Error {
    ParseError::AssertFail(format!("the body ends inside {what}")).into()
}

/// The stream version at body `0x04`, the `CNSP` magic checked first.
fn version_of(body: &[u8]) -> Result<u16, Error> {
    if body.get(..4) != Some(CNSP_MAGIC.as_slice()) {
        return Err(ParseError::AssertFail(format!(
            "body opens {:02x?}, not the CNSP stream",
            body.get(..4).unwrap_or_default()
        ))
        .into());
    }
    let bytes = body
        .get(VERSION_AT..VERSION_AT + 2)
        .ok_or_else(|| ParseError::AssertFail("body ends inside the CNSP header".to_string()))?;
    Ok(u16::from_be_bytes(bytes.try_into().unwrap()))
}

/// The magic, and a stream version the prefix offsets are pinned to.
fn check_mapped(body: &[u8]) -> Result<(), Error> {
    let version = version_of(body)?;
    crate::formats::known_version(FORMAT, u32::from(version), KNOWN_VERSIONS)
}

fn overflow(what: &str) -> Error {
    ParseError::OutOfBounds {
        value: what.to_string(),
        bound: "an offset that fits this platform's address space".into(),
    }
    .into()
}

fn be16(bytes: &[u8], at: usize) -> u16 {
    u16::from_be_bytes(bytes[at..at + 2].try_into().unwrap())
}

fn be32(bytes: &[u8], at: usize) -> u32 {
    u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap())
}

/// Where the first audio span starts, given the directory's end and the block size.
///
/// The grid is whole blocks offset by [`AUDIO_ALIGN_BIAS`]; the bytes between the
/// directory and it are zero.
fn first_audio_offset(directory_end: usize, block: usize) -> Result<usize, Error> {
    directory_end
        .checked_add(AUDIO_ALIGN_BIAS)
        .map(|biased| biased.div_ceil(block))
        .and_then(|blocks| blocks.checked_mul(block))
        .and_then(|at| at.checked_sub(AUDIO_ALIGN_BIAS))
        .ok_or_else(|| overflow("the first audio offset"))
}

/// One recorded note: the directory record, and the audio bytes it owns.
///
/// The record is carried verbatim apart from its audio offset, which is a
/// placement and is recomputed every time a library is written.
#[derive(Clone)]
pub struct Stroke<'a> {
    /// The note the recording was made at. It comes from the record's position in
    /// the count table rather than from a field of the record itself. Confirmed on
    /// hardware.
    pub root: u8,
    record: [u8; RECORD],
    audio: Cow<'a, [u8]>,
}

impl<'a> Stroke<'a> {
    /// The `+0x04` bank byte. Specimens hold only the codes [`Bank`] names, but an
    /// unnamed one is carried rather than refused.
    pub fn bank_code(&self) -> u8 {
        self.record[REC_BANK]
    }

    pub fn bank(&self) -> Option<Bank> {
        Bank::from_code(self.bank_code())
    }

    /// Softness value within the root's bank; 0 is the loudest recording, and a
    /// bank's values need be neither dense nor start at zero.
    ///
    /// A key sounds the largest value the root holds that is at most
    /// `(127 − velocity)·31/127`, so 0 plays at the top of the velocity range and a
    /// value above 30 ([`encode::HIGHEST_PLAYED_LAYER`]) never plays at all. Confirmed
    /// on hardware. The 31 is measured to about ±2, so a layer sitting on the bound
    /// switches a few velocities either side of where the formula puts it. Vendor
    /// libraries spread a root over 0..[`encode::SOFTEST_LAYER`].
    pub fn layer(&self) -> u8 {
        self.record[REC_LAYER]
    }

    /// Frames the stroke owns, which is what [`codec::decode`] emits: the block
    /// overlap is excluded.
    pub fn frames(&self) -> u32 {
        be32(&self.record, REC_FRAMES)
    }

    pub fn blocks(&self) -> u16 {
        be16(&self.record, REC_BLOCKS)
    }

    /// The `+0x34` trim, in decibels the instrument attenuates the stroke by.
    pub fn trim(&self) -> u16 {
        be16(&self.record, REC_TRIM)
    }

    /// The `+0x2e` decay coefficient, which a release stroke zeroes.
    pub fn decay(&self) -> u32 {
        be32(&self.record, REC_DECAY)
    }

    /// The [`DECAYS`]-entry decay ladder from `+0x36`.
    pub fn ladder(&self) -> [u32; DECAYS] {
        std::array::from_fn(|entry| be32(&self.record, REC_DECAYS + entry * 4))
    }

    /// The identifier at `+0x6e`. Distinguishes a recording across libraries;
    /// what else it means is open. Inferred from specimens; not confirmed on
    /// hardware.
    pub fn id(&self) -> u32 {
        be32(&self.record, REC_ID)
    }

    /// The predictor's four seed samples per channel, oldest first. A mono
    /// stroke's second group is unused.
    pub fn seeds(&self) -> [[i16; SEEDS]; 2] {
        let mut out = [[0i16; SEEDS]; 2];
        for (channel, group) in out.iter_mut().enumerate() {
            for (i, slot) in group.iter_mut().enumerate() {
                *slot = be16(&self.record, REC_SEEDS + (channel * SEEDS + i) * 2) as i16;
            }
        }
        out
    }

    /// The encoded audio, `blocks × 1022 × channels` bytes.
    pub fn audio(&self) -> &[u8] {
        &self.audio
    }

    /// The record as stored, its audio offset excluded from any meaning: the
    /// writer replaces it.
    pub fn record(&self) -> &[u8; RECORD] {
        &self.record
    }
}

impl fmt::Debug for Stroke<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Stroke")
            .field("root", &self.root)
            .field("bank", &self.bank_code())
            .field("layer", &self.layer())
            .field("frames", &self.frames())
            .field("blocks", &self.blocks())
            .finish()
    }
}

/// A piano library parsed: the prefix, and every stroke with its audio.
///
/// Strokes borrow their audio from the [`Piano`] they were parsed from, so a
/// transform that drops strokes copies nothing. The fields the container derives —
/// the stroke count, the per-root counts and every audio offset — are not stored in
/// the model at all; [`Library::to_body`] computes them from the stroke list, which
/// is what makes an unmodified library rebuild to the bytes it was read from.
#[derive(Clone)]
pub struct Library<'a> {
    /// The container header, carried so a transform yields a whole file.
    pub header: Header,
    /// Body bytes before the directory. The setters edit it; the writer rewrites
    /// the counts within it.
    prefix: Vec<u8>,
    channels: u16,
    strokes: Vec<Stroke<'a>>,
}

impl<'a> Library<'a> {
    /// A whole `.npno` file parsed over a borrowed slice: the body is taken as a
    /// subslice, so every stroke's audio points into `file` rather than a copy of it.
    ///
    /// The container's checksum is not verified here — the caller has inspected the
    /// container.
    pub fn borrow(file: &'a [u8]) -> Result<Library<'a>, Error> {
        let mut head: &[u8] = file;
        let (header, _) = cbin::read_header(&mut head)?;
        if header.tag.as_slice() != FORMAT.as_bytes() {
            return Err(ParseError::WrongFormat {
                expected: FORMAT,
                got: String::from_utf8_lossy(&header.tag).into_owned(),
            }
            .into());
        }
        let start = usize::try_from(header.generation.body_start())
            .map_err(|_| overflow("the container's header"))?;
        let trailer = usize::try_from(header.generation.trailer_len())
            .map_err(|_| overflow("the container's checksum trailer"))?;
        let end = file
            .len()
            .checked_sub(trailer)
            .ok_or_else(|| short("the container's checksum trailer"))?;
        let body = file.get(start..end).ok_or_else(|| short("the header"))?;
        Library::parse_body(header, body)
    }

    fn parse_body(header: Header, body: &'a [u8]) -> Result<Library<'a>, Error> {
        check_mapped(body)?;
        let prefix = body
            .get(..DIRECTORY_AT)
            .ok_or_else(|| short("the prefix"))?;

        let version = be16(prefix, VERSION_AT);
        let echo = be16(prefix, VERSION_ECHO_AT);
        if echo != version {
            return Err(ParseError::AssertFail(format!(
                "the stream version {version:#06x} is echoed as {echo:#06x}"
            ))
            .into());
        }

        let channels = be16(prefix, CHANNELS_AT);
        if !(1..=2).contains(&channels) {
            return Err(ParseError::OutOfBounds {
                value: format!("{channels} channels"),
                bound: "1 or 2".into(),
            }
            .into());
        }
        let block = block_bytes(channels);

        let count = usize::from(be16(prefix, STROKE_COUNT_AT));
        let counts: Vec<u16> = (0..NOTES)
            .map(|n| be16(prefix, ROOT_COUNTS_AT + n * 2))
            .collect();
        let summed: usize = counts.iter().map(|&c| usize::from(c)).sum();
        if summed != count {
            return Err(ParseError::AssertFail(format!(
                "the per-root counts sum to {summed} where the stroke count is {count}"
            ))
            .into());
        }

        let directory_end = RECORD
            .checked_mul(count)
            .and_then(|len| DIRECTORY_AT.checked_add(len))
            .ok_or_else(|| overflow("the stroke directory"))?;
        let records = body
            .get(DIRECTORY_AT..directory_end)
            .ok_or_else(|| short("the stroke directory"))?;

        let first = first_audio_offset(directory_end, block)?;
        let pad = body
            .get(directory_end..first)
            .ok_or_else(|| short("the alignment gap before the audio"))?;
        if pad.iter().any(|&b| b != 0) {
            return Err(ParseError::AssertFail(
                "the alignment gap before the audio is not zero".into(),
            )
            .into());
        }

        let mut strokes = Vec::new();
        strokes
            .try_reserve_exact(count)
            .map_err(|_| overflow("the stroke list"))?;
        let mut at = first;
        let mut roots = counts
            .iter()
            .enumerate()
            .flat_map(|(note, &n)| std::iter::repeat_n(note as u8, usize::from(n)));
        for i in 0..count {
            let mut record = [0u8; RECORD];
            record.copy_from_slice(&records[i * RECORD..(i + 1) * RECORD]);
            let root = roots.next().expect("the counts sum to the stroke count");
            let start = be32(&record, REC_START);
            if usize::try_from(start) != Ok(at) {
                return Err(ParseError::AssertFail(format!(
                    "stroke {i} starts at {start:#x} where the spans before it end at {at:#x}"
                ))
                .into());
            }
            let span = usize::from(be16(&record, REC_BLOCKS))
                .checked_mul(block)
                .ok_or_else(|| overflow("a stroke's audio span"))?;
            let end = at.checked_add(span).ok_or_else(|| overflow("the audio"))?;
            let audio = body
                .get(at..end)
                .ok_or_else(|| short("a stroke's audio span"))?;
            strokes.push(Stroke {
                root,
                record,
                audio: Cow::Borrowed(audio),
            });
            at = end;
        }
        if at != body.len() {
            return Err(ParseError::AssertFail(format!(
                "the audio ends at {at:#x} where the body ends at {:#x}",
                body.len()
            ))
            .into());
        }

        let library = Library {
            header,
            prefix: prefix.to_vec(),
            channels,
            strokes,
        };
        library.check_key_map()?;
        Ok(library)
    }

    /// Every key map entry names a root the directory holds.
    fn check_key_map(&self) -> Result<(), Error> {
        let roots = self.roots();
        for (key, &root) in self.key_map().iter().enumerate() {
            if root != UNCOVERED && !roots.contains(&root) {
                return Err(ParseError::AssertFail(format!(
                    "key {key} plays root {root}, which no stroke records"
                ))
                .into());
            }
        }
        Ok(())
    }

    pub fn stream_version(&self) -> u16 {
        be16(&self.prefix, VERSION_AT)
    }

    pub fn channels(&self) -> u16 {
        self.channels
    }

    /// Bytes in one encoded block, `1022 × channels`.
    pub fn block_bytes(&self) -> usize {
        block_bytes(self.channels)
    }

    pub fn strokes(&self) -> &[Stroke<'a>] {
        &self.strokes
    }

    /// This library's prefix and stroke records with no audio behind them: what a
    /// [`encode::Donor::Template`] reads, and nothing [`Library::to_body`] can lay out.
    pub fn without_audio(&self) -> Library<'static> {
        Library {
            header: self.header.clone(),
            prefix: self.prefix.clone(),
            channels: self.channels,
            strokes: self
                .strokes
                .iter()
                .map(|stroke| Stroke {
                    root: stroke.root,
                    record: stroke.record,
                    audio: Cow::Owned(Vec::new()),
                })
                .collect(),
        }
    }

    /// Retrim the `index`-th stroke, in the decibels [`Stroke::trim`] reads.
    pub fn set_trim(&mut self, index: usize, decibels: u16) -> Result<(), Error> {
        let count = self.strokes.len();
        let stroke = self
            .strokes
            .get_mut(index)
            .ok_or_else(|| ParseError::OutOfBounds {
                value: format!("stroke {index}"),
                bound: format!("the {count} strokes the directory holds"),
            })?;
        stroke.record[REC_TRIM..REC_TRIM + 2].copy_from_slice(&decibels.to_be_bytes());
        Ok(())
    }

    /// The `(name, variant)` pair, from the same field [`Piano::name`] reads.
    pub fn name(&self) -> (String, String) {
        split_name(&TextField::COMBINED.read(&self.prefix))
    }

    /// The 128-entry key map: the root note that plays each key, or [`UNCOVERED`].
    pub fn key_map(&self) -> &[u8] {
        &self.prefix[KEY_MAP_AT..KEY_MAP_AT + NOTES]
    }

    fn key_map_mut(&mut self) -> &mut [u8] {
        &mut self.prefix[KEY_MAP_AT..KEY_MAP_AT + NOTES]
    }

    /// The root notes the directory records, ascending.
    pub fn roots(&self) -> BTreeSet<u8> {
        self.strokes.iter().map(|s| s.root).collect()
    }

    /// The root note whose strokes play `key`, or `None` where the map leaves the
    /// key uncovered.
    pub fn key_root(&self, key: u8) -> Result<Option<u8>, Error> {
        let root = self.key_map()[midi_key("key", key)?];
        Ok((root != UNCOVERED).then_some(root))
    }

    /// The keys the map routes to `root`, ascending. A root the map never names —
    /// including one outside the MIDI range — has no keys.
    pub fn keys_for(&self, root: u8) -> Vec<u8> {
        self.key_map()
            .iter()
            .enumerate()
            .filter(|&(_, &r)| r == root)
            .map(|(key, _)| key as u8)
            .collect()
    }

    /// The per-key fine tune at `0x18c + key`, in units worth
    /// [`FINE_TUNE_CENTS_PER_UNIT`] each. Confirmed on hardware.
    pub fn fine_tune(&self, key: u8) -> Result<i8, Error> {
        Ok(self.prefix[FINE_TUNE_AT + midi_key("key", key)?] as i8)
    }

    /// Retune one key, in the units [`Library::fine_tune`] reads.
    ///
    /// The unit's size and direction: Confirmed on hardware. That rewriting the byte
    /// retunes the key: Inferred from specimens; not confirmed on hardware.
    pub fn set_fine_tune(&mut self, key: u8, units: i8) -> Result<(), Error> {
        let at = FINE_TUNE_AT + midi_key("key", key)?;
        self.prefix[at] = units as u8;
        Ok(())
    }

    /// The gain over the whole library at `0x40c`, in tenths of a decibel.
    pub fn gain(&self) -> i8 {
        self.prefix[GAIN_AT] as i8
    }

    pub fn set_gain(&mut self, tenths: i8) {
        self.prefix[GAIN_AT] = tenths as u8;
    }

    /// The highest key the instrument damps at note-off, at `0x40d`.
    pub fn damper_top(&self) -> u8 {
        self.prefix[DAMPER_TOP_AT]
    }

    /// Move the damper limit. [`encode::ALL_KEYS_DAMPED`] leaves no key ringing; a
    /// key past the last MIDI note is refused.
    pub fn set_damper_top(&mut self, key: u8) -> Result<(), Error> {
        self.prefix[DAMPER_TOP_AT] = midi_key("damper limit", key)? as u8;
        Ok(())
    }

    /// The instrument kind the library states at `0x18`; [`encode::Kind::from_code`]
    /// names it.
    pub fn kind_code(&self) -> u8 {
        self.prefix[KIND_AT]
    }

    /// File the library under another kind of instrument.
    ///
    /// The byte changes nothing a library sounds like. Confirmed on hardware.
    pub fn set_kind(&mut self, kind: encode::Kind) {
        self.prefix[KIND_AT] = kind.code();
    }

    /// The long name at `0x3c` and the voicing at `0x5c`, which only
    /// [`VERSION_SPLIT_NAME`] streams carry. Both are `None` on the older stream.
    ///
    /// They are their own fields, not a split of the `Name#Variant` one: a library can
    /// spell the long name differently from the name before the `#`, and the voicing
    /// holds neither the padding nor the size suffix the variant does. Inferred from
    /// specimens; not confirmed on hardware.
    pub fn long_name(&self) -> Option<String> {
        self.split_field(TextField::LONG_NAME)
    }

    pub fn voicing(&self) -> Option<String> {
        self.split_field(TextField::VOICING)
    }

    fn split_field(&self, field: TextField) -> Option<String> {
        (self.stream_version() == VERSION_SPLIT_NAME).then(|| field.read(&self.prefix))
    }

    /// Rename the library, leaving the variant alone.
    ///
    /// A name holding [`NAME_SEPARATOR`], or text the field would not read back, is
    /// refused; so is one too long for the field it shares with the variant. Nothing
    /// is written unless every field the rename touches accepts its text.
    ///
    /// On a stream that carries one, the long name is set to the same text: both
    /// are the library's name, and a rename that moved only one would leave the
    /// old name showing wherever the instrument reads the other. Which of the two it
    /// reads: Inferred from specimens; not confirmed on hardware. That is why both
    /// move.
    pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
        let field = TextField::COMBINED.read(&self.prefix);
        let variant = raw_halves(&field).1.to_owned();
        self.set_name_and_variant(name, &variant)
    }

    /// Replace the variant — the text after [`NAME_SEPARATOR`], where the vendor
    /// records the voicing and the library's size — leaving both names alone. A
    /// variant holding the separator itself is refused.
    pub fn set_variant(&mut self, variant: &str) -> Result<(), Error> {
        check_half("variant", variant)?;
        let field = TextField::COMBINED.read(&self.prefix);
        let combined = format!("{}{NAME_SEPARATOR}{variant}", raw_halves(&field).0);
        TextField::COMBINED.write(&mut self.prefix, &combined)
    }

    /// Write both halves of the `Name#Variant` field at once, which is what a caller
    /// replacing both states.
    ///
    /// The name a caller gives is checked against the variant it will share the field
    /// with rather than the one the prefix holds, so a name that fits beside its own
    /// variant is not refused for a longer one it replaces. The long name follows the
    /// name as it does in [`Library::set_name`].
    fn set_name_and_variant(&mut self, name: &str, variant: &str) -> Result<(), Error> {
        check_half("name", name)?;
        check_half("variant", variant)?;
        let combined = format!("{name}{NAME_SEPARATOR}{variant}");
        let long = (self.stream_version() == VERSION_SPLIT_NAME).then_some(name);
        TextField::COMBINED.check(&combined)?;
        if let Some(long) = long {
            TextField::LONG_NAME.check(long)?;
        }
        TextField::COMBINED.write(&mut self.prefix, &combined)?;
        if let Some(long) = long {
            TextField::LONG_NAME.write(&mut self.prefix, long)?;
        }
        Ok(())
    }

    /// Replace the voicing at `0x5c`. Refused on a stream with no such field.
    pub fn set_voicing(&mut self, voicing: &str) -> Result<(), Error> {
        if self.stream_version() != VERSION_SPLIT_NAME {
            return Err(ParseError::AssertFail(format!(
                "stream {:#06x} carries no voicing field; the variant after the \
                 {NAME_SEPARATOR:?} is where it records one",
                self.stream_version()
            ))
            .into());
        }
        TextField::VOICING.write(&mut self.prefix, voicing)
    }

    /// Route `key` to `root`, or to nothing when `root` is `None`.
    ///
    /// A root the directory does not record is refused: the instrument would have
    /// no stroke to play.
    ///
    /// That the instrument follows a rewritten map — a key routed to another root, or
    /// to nothing: Inferred from specimens; not confirmed on hardware.
    pub fn set_key_root(&mut self, key: u8, root: Option<u8>) -> Result<(), Error> {
        let key = midi_key("key", key)?;
        if let Some(root) = root {
            midi_key("root", root)?;
            if !self.roots().contains(&root) {
                return Err(ParseError::OutOfBounds {
                    value: format!("root {root}"),
                    bound: "a root the directory records".into(),
                }
                .into());
            }
        }
        self.key_map_mut()[key] = root.unwrap_or(UNCOVERED);
        Ok(())
    }

    /// Drop every stroke of one bank — the resonance set turns a large library into
    /// a small one, the release set silences the note-off sample.
    ///
    /// For [`Bank::Release`], the instrument damps the note at note-off where the
    /// library it came from plays a release tail. Confirmed on hardware.
    pub fn drop_bank(&mut self, bank: Bank) -> Change {
        let code = bank.code();
        self.retain(|s| s.bank_code() != code)
    }

    /// Keep only the layers `keep` selects, per root and bank.
    ///
    /// Confirmed on hardware. A library with its softest layers dropped plays the
    /// softest one left at the velocities they had, and is unchanged at loud ones.
    pub fn keep_layers(&mut self, keep: &Layers) -> Change {
        match keep {
            Layers::Only(layers) => {
                let layers = layers.clone();
                self.retain(|s| layers.contains(&s.layer()))
            }
            Layers::Loudest(n) => {
                let mut groups: BTreeMap<(u8, u8), BTreeSet<u8>> = BTreeMap::new();
                for stroke in &self.strokes {
                    groups
                        .entry((stroke.root, stroke.bank_code()))
                        .or_default()
                        .insert(stroke.layer());
                }
                let kept: BTreeSet<(u8, u8, u8)> = groups
                    .into_iter()
                    .flat_map(|((root, bank), layers)| {
                        layers.into_iter().take(*n).map(move |l| (root, bank, l))
                    })
                    .collect();
                self.retain(|s| kept.contains(&(s.root, s.bank_code(), s.layer())))
            }
        }
    }

    /// Keep the strokes `keep` accepts and drop the rest, then uncover the keys whose
    /// root has gone.
    ///
    /// The selection every other transform here is a named case of, for a caller whose
    /// own is none of them — one layer on one root, say. A stroke carries its own
    /// predictor seeds and its blocks overlap only each other, so whichever subset is
    /// left re-lays into a library the writer can lay out.
    ///
    /// Inferred from specimens; not confirmed on hardware. [`Library::drop_bank`] and
    /// [`Library::keep_layers`] are the two selections a hardware read covers.
    pub fn retain_strokes(&mut self, keep: impl FnMut(&Stroke<'a>) -> bool) -> Change {
        self.retain(keep)
    }

    /// Uncover every key outside `range`, then drop the roots nothing plays any
    /// more. Keys inside the range keep the roots they had.
    ///
    /// That an uncovered key falls silent rather than reaching for a neighbouring
    /// root: Inferred from specimens; not confirmed on hardware.
    pub fn cut_range(&mut self, range: RangeInclusive<u8>) -> Result<Change, Error> {
        midi_key("the range's lowest key", *range.start())?;
        midi_key("the range's highest key", *range.end())?;
        Ok(self.restrict(|key| range.contains(&key)))
    }

    /// Two libraries, one covering the keys below `key` and one covering `key` and
    /// above, each cut the way [`Library::cut_range`] cuts.
    ///
    /// A root whose keys straddle `key` lands in both halves — each half has to be
    /// playable on its own — so the two together hold more strokes than the one they
    /// came from. Each half carries [`Library::cut_range`]'s provenance.
    pub fn split_at(&self, key: u8) -> Result<(Library<'a>, Library<'a>), Error> {
        midi_key("the split key", key)?;
        let mut low = self.clone();
        let mut high = self.clone();
        low.restrict(|k| k < key);
        high.restrict(|k| k >= key);
        Ok((low, high))
    }

    /// Uncover every key `keep` rejects, then drop the roots nothing plays.
    fn restrict(&mut self, keep: impl Fn(u8) -> bool) -> Change {
        let mut uncovered = 0;
        for (key, slot) in self.key_map_mut().iter_mut().enumerate() {
            if !keep(key as u8) && *slot != UNCOVERED {
                *slot = UNCOVERED;
                uncovered += 1;
            }
        }
        let live: BTreeSet<u8> = self.key_map().iter().copied().collect();
        let mut change = self.retain(|s| live.contains(&s.root));
        change.keys_uncovered += uncovered;
        change
    }

    /// Drop the strokes `keep` rejects, then uncover the keys whose root has gone.
    fn retain(&mut self, mut keep: impl FnMut(&Stroke<'a>) -> bool) -> Change {
        let strokes_before = self.strokes.len();
        let roots_before = self.roots().len();
        self.strokes.retain(|s| keep(s));
        let roots = self.roots();
        let mut keys_uncovered = 0;
        for slot in self.key_map_mut() {
            if *slot != UNCOVERED && !roots.contains(slot) {
                *slot = UNCOVERED;
                keys_uncovered += 1;
            }
        }
        Change {
            strokes_removed: strokes_before - self.strokes.len(),
            roots_removed: roots_before - roots.len(),
            keys_uncovered,
        }
    }

    /// Bytes the body would occupy.
    pub fn body_len(&self) -> Result<usize, Error> {
        let (_, len) = self.extent()?;
        Ok(len)
    }

    /// The first audio offset and the body length the current stroke list implies.
    ///
    /// A stroke holding anything other than the `blocks × block_bytes` its record states
    /// is refused: a body laid out around it is one a read of that body rejects.
    fn extent(&self) -> Result<(usize, usize), Error> {
        let directory_end = RECORD
            .checked_mul(self.strokes.len())
            .and_then(|len| DIRECTORY_AT.checked_add(len))
            .ok_or_else(|| overflow("the stroke directory"))?;
        let block = self.block_bytes();
        let first = first_audio_offset(directory_end, block)?;
        let mut len = first;
        for (index, stroke) in self.strokes.iter().enumerate() {
            let span = usize::from(stroke.blocks())
                .checked_mul(block)
                .ok_or_else(|| overflow("a stroke's audio span"))?;
            if stroke.audio.len() != span {
                return Err(ParseError::AssertFail(format!(
                    "stroke {index} holds {} audio bytes where the {} block(s) its record \
                     states span {span}",
                    stroke.audio.len(),
                    stroke.blocks()
                ))
                .into());
            }
            len = len.checked_add(span).ok_or_else(|| overflow("the audio"))?;
        }
        Ok((first, len))
    }

    /// Lay the body out: the prefix with its counts rewritten, the directory with
    /// every audio offset recomputed, the zero gap, then the audio spans in
    /// directory order.
    ///
    /// Confirmed on hardware. A body laid out here, with a directory the transforms
    /// shortened and every span moved, is accepted by the instrument and plays at the
    /// level the library it came from plays at.
    pub fn to_body(&self) -> Result<Vec<u8>, Error> {
        let count = u16::try_from(self.strokes.len()).map_err(|_| ParseError::OutOfBounds {
            value: format!("{} strokes", self.strokes.len()),
            bound: "the u16 stroke count the directory holds".into(),
        })?;
        if self.strokes.windows(2).any(|w| w[0].root > w[1].root) {
            return Err(ParseError::AssertFail(
                "the strokes are not in ascending root order, which is what the per-root \
                 counts index them by"
                    .into(),
            )
            .into());
        }

        let (first, len) = self.extent()?;
        let mut out = try_vec(len)?;
        out[..DIRECTORY_AT].copy_from_slice(&self.prefix);
        out[CHANNELS_AT..CHANNELS_AT + 2].copy_from_slice(&self.channels.to_be_bytes());
        out[STROKE_COUNT_AT..STROKE_COUNT_AT + 2].copy_from_slice(&count.to_be_bytes());
        for note in 0..NOTES {
            let n = self
                .strokes
                .iter()
                .filter(|s| usize::from(s.root) == note)
                .count();
            let n = u16::try_from(n).expect("a per-root count is at most the stroke count");
            let at = ROOT_COUNTS_AT + note * 2;
            out[at..at + 2].copy_from_slice(&n.to_be_bytes());
        }

        let mut at = first;
        for (i, stroke) in self.strokes.iter().enumerate() {
            let start = u32::try_from(at).map_err(|_| ParseError::OutOfBounds {
                value: format!("audio offset {at:#x}"),
                bound: "the u32 offset a stroke record holds".into(),
            })?;
            let record = DIRECTORY_AT + i * RECORD;
            out[record..record + RECORD].copy_from_slice(&stroke.record);
            out[record + REC_START..record + REC_START + 4].copy_from_slice(&start.to_be_bytes());
            out[at..at + stroke.audio.len()].copy_from_slice(&stroke.audio);
            at += stroke.audio.len();
        }
        Ok(out)
    }

    /// The library as a file, ready to write. The container recomputes its own
    /// checksum.
    ///
    /// The u32 at body `0x06` is unique per file and is not a checksum, a size or a
    /// hash of anything in it; with nothing to recompute it from, an edit carries
    /// it over rather than inventing a value. The hardware evidence reaches no further
    /// than this: a library carrying its source's word loads and plays. Confirmed on
    /// hardware. What the word means is open.
    pub fn to_piano(&self) -> Result<Piano, Error> {
        Ok(Piano {
            file: Cbin {
                header: self.header.clone(),
                body: RawBody(self.to_body()?),
            },
        })
    }
}

impl fmt::Debug for Library<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (name, variant) = self.name();
        f.debug_struct("npno::Library")
            .field("name", &name)
            .field("variant", &variant)
            .field(
                "stream_version",
                &format_args!("{:#06x}", self.stream_version()),
            )
            .field("channels", &self.channels)
            .field("strokes", &self.strokes.len())
            .field("roots", &self.roots().len())
            .finish()
    }
}

fn block_bytes(channels: u16) -> usize {
    codec::BLOCK_WORDS * 2 * usize::from(channels)
}

#[cfg(test)]
mod tests {
    use super::synthetic::{take, Build};
    use super::*;

    #[test]
    fn the_name_field_splits_on_the_separator() {
        let piano = Build::new().piano();
        assert_eq!(piano.stream_version().unwrap(), 0x450);
        assert_eq!(
            piano.name().unwrap(),
            ("Test Piano".to_string(), "Variant".to_string())
        );
    }

    #[test]
    fn an_unknown_stream_version_still_round_trips_but_does_not_decode() {
        let mut build = Build::new();
        build.version = 0x500;
        let piano = build.piano();
        assert_eq!(piano.stream_version().unwrap(), 0x500);
        assert!(
            piano.name().is_err(),
            "the name offset is only pinned on known versions"
        );
        assert!(piano.key_map().is_err());
        assert!(piano.library().is_err());
    }

    #[test]
    fn a_body_without_the_magic_is_refused() {
        let mut piano = Build::new().piano();
        piano.file.body.0[0] = b'Q';
        assert!(piano.name().is_err(), "a non-CNSP body has no name to read");
    }

    #[test]
    fn a_library_rebuilds_to_the_bytes_it_was_read_from() {
        let piano = Build::new().piano();
        let rebuilt = piano.library().unwrap().to_body().unwrap();
        assert_eq!(rebuilt, piano.file.body.0);
    }

    #[test]
    fn the_directory_reports_each_strokes_root_bank_and_layer() {
        let piano = Build::new().piano();
        let library = piano.library().unwrap();
        let seen: Vec<(u8, Option<Bank>, u8)> = library
            .strokes()
            .iter()
            .map(|s| (s.root, s.bank(), s.layer()))
            .collect();
        assert_eq!(
            seen,
            [
                (60, Some(Bank::Attack), 0),
                (60, Some(Bank::Release), 3),
                (72, Some(Bank::Attack), 0),
            ]
        );
        assert_eq!(library.keys_for(60), [60, 61]);
    }

    #[test]
    fn a_stroke_whose_start_does_not_abut_the_one_before_is_refused() {
        let mut piano = Build::new().piano();
        let second = DIRECTORY_AT + RECORD;
        let start = be32(&piano.file.body.0, second + REC_START);
        piano.file.body.0[second..second + 4].copy_from_slice(&(start + 2).to_be_bytes());
        let error = piano.library().unwrap_err().to_string();
        assert!(error.contains("stroke 1 starts at"), "{error}");
    }

    #[test]
    fn a_key_routed_to_a_root_no_stroke_records_is_refused() {
        let mut build = Build::new();
        build.map.push((80, 80));
        let error = build.piano().library().unwrap_err().to_string();
        assert!(error.contains("key 80 plays root 80"), "{error}");
    }

    #[test]
    fn a_count_table_that_does_not_sum_to_the_stroke_count_is_refused() {
        let mut piano = Build::new().piano();
        let at = ROOT_COUNTS_AT + 60 * 2;
        piano.file.body.0[at..at + 2].copy_from_slice(&5u16.to_be_bytes());
        let error = piano.library().unwrap_err().to_string();
        assert!(error.contains("per-root counts sum to"), "{error}");
    }

    #[test]
    fn dropping_a_bank_relays_the_audio_and_leaves_the_rest_verbatim() {
        let piano = Build::new().piano();
        let before = piano.library().unwrap();
        let mut after = piano.library().unwrap();
        let change = after.drop_bank(Bank::Release);
        assert_eq!(
            change,
            Change {
                strokes_removed: 1,
                roots_removed: 0,
                keys_uncovered: 0
            }
        );

        let body = after.to_body().unwrap();
        let trimmed = Piano {
            file: Cbin {
                header: after.header.clone(),
                body: RawBody(body),
            },
        };
        let reparsed = trimmed.library().unwrap();
        assert_eq!(reparsed.strokes().len(), 2);
        for (kept, moved) in before
            .strokes()
            .iter()
            .filter(|s| s.bank() != Some(Bank::Release))
            .zip(reparsed.strokes())
        {
            assert_eq!(kept.audio(), moved.audio(), "a span moved verbatim");
            assert_eq!(kept.id(), moved.id());
            assert_eq!(&kept.record()[REC_BANK..], &moved.record()[REC_BANK..]);
        }
    }

    #[test]
    fn dropping_every_stroke_of_a_root_uncovers_the_keys_it_played() {
        let mut build = Build::new();
        build.takes = vec![
            take(60, Bank::Attack, 0, 1),
            take(72, Bank::Resonance, 0, 1),
        ];
        let piano = build.piano();
        let mut library = piano.library().unwrap();
        let change = library.drop_bank(Bank::Resonance);
        assert_eq!(change.strokes_removed, 1);
        assert_eq!(change.roots_removed, 1);
        assert_eq!(change.keys_uncovered, 1);
        assert_eq!(library.key_map()[72], UNCOVERED);
        library.to_body().unwrap();
    }

    #[test]
    fn keeping_the_loudest_layer_keeps_one_per_root_and_bank() {
        let mut build = Build::new();
        build.takes = vec![
            take(60, Bank::Attack, 0, 1),
            take(60, Bank::Attack, 5, 1),
            take(60, Bank::Release, 26, 1),
            take(60, Bank::Release, 30, 1),
            take(72, Bank::Attack, 1, 1),
        ];
        let piano = build.piano();
        let mut library = piano.library().unwrap();
        library.keep_layers(&Layers::Loudest(1));
        let kept: Vec<(u8, u8, u8)> = library
            .strokes()
            .iter()
            .map(|s| (s.root, s.bank_code(), s.layer()))
            .collect();
        assert_eq!(kept, [(60, 0, 0), (60, 2, 26), (72, 0, 1)]);
    }

    #[test]
    fn keeping_named_layers_takes_them_wherever_they_occur() {
        let mut build = Build::new();
        build.takes = vec![
            take(60, Bank::Attack, 0, 1),
            take(60, Bank::Attack, 5, 1),
            take(72, Bank::Attack, 5, 1),
        ];
        let piano = build.piano();
        let mut library = piano.library().unwrap();
        library.keep_layers(&Layers::Only([5].into_iter().collect()));
        let kept: Vec<(u8, u8)> = library
            .strokes()
            .iter()
            .map(|s| (s.root, s.layer()))
            .collect();
        assert_eq!(kept, [(60, 5), (72, 5)]);
    }

    /// The stroke-level selection: one layer on one root, which no named transform
    /// expresses. What the predicate rejects goes, what it accepts stays verbatim, and
    /// a root left with no strokes at all stops answering its keys.
    #[test]
    fn retaining_strokes_drops_what_the_predicate_rejects_and_nothing_else() {
        let mut build = Build::new();
        build.takes = vec![
            take(60, Bank::Attack, 0, 1),
            take(60, Bank::Attack, 5, 1),
            take(72, Bank::Attack, 5, 2),
        ];
        let piano = build.piano();

        let mut kept_all = piano.library().unwrap();
        let unchanged = kept_all.retain_strokes(|_| true);
        assert_eq!(unchanged, Change::default());
        assert_eq!(
            kept_all.to_body().unwrap(),
            piano.file.body.0,
            "a predicate that rejects nothing re-lays the body it read"
        );

        let mut library = piano.library().unwrap();
        let change = library.retain_strokes(|s| !(s.root == 72 && s.layer() == 5));
        assert_eq!(
            change,
            Change {
                strokes_removed: 1,
                roots_removed: 1,
                keys_uncovered: 1,
            }
        );
        let left: Vec<(u8, u8)> = library
            .strokes()
            .iter()
            .map(|s| (s.root, s.layer()))
            .collect();
        assert_eq!(left, [(60, 0), (60, 5)]);
        assert_eq!(
            library.key_map()[72],
            UNCOVERED,
            "root 72 lost every stroke, so its key answers nothing"
        );
        assert_eq!(library.key_map()[60], 60, "and the other root is untouched");
        library.to_body().unwrap();
    }

    /// The builder hands back a file, not only a body: a `.npno` another crate's tests
    /// can read back through the front door.
    #[test]
    fn a_synthetic_library_reads_back_as_the_file_it_was_built_as() {
        let bytes = Build::new().bytes().unwrap();
        let entity = crate::from_stream(&mut std::io::Cursor::new(&bytes)).unwrap();
        let crate::Entity::Piano(piano) = &entity else {
            panic!("{entity:?} is no piano library");
        };
        assert_eq!(
            piano.name().unwrap(),
            ("Test Piano".to_string(), "Variant".to_string())
        );
        assert_eq!(piano.library().unwrap().strokes().len(), 3);
        assert_eq!(crate::to_bytes(&entity).unwrap(), bytes);
    }

    /// A borrowed library is a view over the caller's own bytes: tens of megabytes of
    /// audio stay where they were read, and what the view states is what the file
    /// states.
    #[test]
    fn borrowing_a_file_reads_it_without_copying_the_audio() {
        let bytes = Build::new().bytes().unwrap();
        let library = Library::borrow(&bytes).unwrap();

        let base = bytes.as_ptr() as usize;
        let within = base..base + bytes.len();
        for stroke in library.strokes() {
            let at = stroke.audio().as_ptr() as usize;
            assert!(
                within.contains(&at),
                "{stroke:?} holds a copy of its audio, not the caller's bytes"
            );
        }
        assert_eq!(library.name(), ("Test Piano".into(), "Variant".into()));
        assert_eq!(library.strokes().len(), 3);
        assert_eq!(library.to_body().unwrap(), Build::new().body());
    }

    #[test]
    fn borrowing_refuses_a_container_that_is_not_a_whole_piano_library() {
        let bytes = Build::new().bytes().unwrap();

        let mut other = bytes.clone();
        other[0x08..0x0c].copy_from_slice(b"nsmp");
        let error = Library::borrow(&other).unwrap_err().to_string();
        assert!(error.contains("expected a npno file, got nsmp"), "{error}");

        let error = Library::borrow(&bytes[..bytes.len() - 1])
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("ends inside a stroke's audio span"),
            "{error}"
        );
    }

    #[test]
    fn cutting_the_range_drops_the_roots_nothing_plays_any_more() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let change = library.cut_range(0..=70).unwrap();
        assert_eq!(change.keys_uncovered, 1);
        assert_eq!(change.roots_removed, 1);
        assert_eq!(library.roots(), [60].into_iter().collect());
        assert_eq!(library.key_map()[72], UNCOVERED);
        assert_eq!(library.key_map()[60], 60);
    }

    #[test]
    fn a_split_gives_each_half_the_roots_its_keys_play() {
        let piano = Build::new().piano();
        let (low, high) = piano.library().unwrap().split_at(70).unwrap();
        assert_eq!(low.roots(), [60].into_iter().collect());
        assert_eq!(high.roots(), [72].into_iter().collect());
        assert_eq!(low.keys_for(60), [60, 61]);
        assert_eq!(high.keys_for(72), [72]);
        let audio: usize = piano
            .library()
            .unwrap()
            .strokes()
            .iter()
            .map(|s| s.audio().len())
            .sum();
        let halves: usize = [&low, &high]
            .iter()
            .flat_map(|l| l.strokes())
            .map(|s| s.audio().len())
            .sum();
        assert_eq!(
            halves, audio,
            "a split shares every stroke out exactly once"
        );
    }

    #[test]
    fn a_rename_carries_the_long_name_with_it_and_leaves_the_voicing_alone() {
        let mut build = Build::new();
        build.version = VERSION_SPLIT_NAME;
        let piano = build.piano();
        let mut library = piano.library().unwrap();
        library.set_voicing("Nordiska").unwrap();
        library.set_name("Renamed").unwrap();
        library.set_variant("Nordiska  Sml").unwrap();
        assert_eq!(library.name(), ("Renamed".into(), "Nordiska  Sml".into()));
        assert_eq!(library.long_name().as_deref(), Some("Renamed"));
        assert_eq!(
            library.voicing().as_deref(),
            Some("Nordiska"),
            "the voicing is its own field, not the variant's head"
        );
    }

    #[test]
    fn the_older_stream_has_no_long_name_or_voicing_to_read_or_write() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert_eq!(library.stream_version(), 0x450);
        assert_eq!(library.long_name(), None);
        assert_eq!(library.voicing(), None);
        assert!(library.set_voicing("Nordiska").is_err());
    }

    #[test]
    fn a_name_past_the_field_is_refused_without_changing_it() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let too_long = "x".repeat(TextField::COMBINED.capacity());
        assert!(library.set_name(&too_long).is_err());
        assert_eq!(library.name().0, "Test Piano");
    }

    #[test]
    fn a_remap_to_a_root_the_directory_does_not_record_is_refused() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert!(library.set_key_root(64, Some(61)).is_err());
        library.set_key_root(64, Some(72)).unwrap();
        assert_eq!(library.keys_for(72), [64, 72]);
        assert_eq!(library.key_root(64).unwrap(), Some(72));
        library.set_key_root(64, None).unwrap();
        assert_eq!(library.keys_for(72), [72]);
        assert_eq!(library.key_root(64).unwrap(), None);
    }

    #[test]
    fn fine_tune_reads_and_writes_the_per_key_byte() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert_eq!(library.fine_tune(60).unwrap(), 0);
        library.set_fine_tune(60, -4).unwrap();
        assert_eq!(library.fine_tune(60).unwrap(), -4);
        assert_eq!(library.to_body().unwrap()[FINE_TUNE_AT + 60], 0xfc);
    }

    /// Offsets at which two bodies of the same length differ: an edit's footprint.
    fn changed(before: &[u8], after: &[u8]) -> Vec<usize> {
        assert_eq!(before.len(), after.len(), "the body changed length");
        (0..before.len())
            .filter(|&at| before[at] != after[at])
            .collect()
    }

    #[test]
    fn the_gain_and_the_damper_limit_each_write_one_byte_of_the_prefix() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let before = library.to_body().unwrap();

        library.set_gain(-20);
        let gained = library.to_body().unwrap();
        assert_eq!(library.gain(), -20);
        assert_eq!(gained[GAIN_AT], 0xec, "tenths of a decibel, signed");
        assert_eq!(changed(&before, &gained), [GAIN_AT]);

        library.set_damper_top(90).unwrap();
        let damped = library.to_body().unwrap();
        assert_eq!(library.damper_top(), 90);
        assert_eq!(changed(&gained, &damped), [DAMPER_TOP_AT]);
    }

    #[test]
    fn the_instrument_kind_writes_one_byte_and_reads_back_as_the_kind_it_was_given() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let before = library.to_body().unwrap();

        library.set_kind(encode::Kind::Wurlitzer);
        let filed = library.to_body().unwrap();
        assert_eq!(
            encode::Kind::from_code(library.kind_code()),
            Some(encode::Kind::Wurlitzer)
        );
        assert_eq!(changed(&before, &filed), [KIND_AT]);
    }

    #[test]
    fn a_damper_limit_past_the_last_midi_note_is_refused_without_moving_the_one_held() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        library.set_damper_top(encode::ALL_KEYS_DAMPED).unwrap();
        let before = library.to_body().unwrap();
        assert!(library.set_damper_top(NOTES as u8).is_err());
        assert_eq!(library.damper_top(), encode::ALL_KEYS_DAMPED);
        assert_eq!(library.to_body().unwrap(), before);
    }

    /// The trim is a u16, so a value that fits one byte and one that does not must each
    /// reach the field whole, and neither may touch the record beside it.
    #[test]
    fn a_retrim_writes_both_bytes_of_one_strokes_own_field() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert!(library.strokes().iter().all(|s| s.trim() == 0));
        let before = library.to_body().unwrap();
        let at = DIRECTORY_AT + RECORD + REC_TRIM;

        library.set_trim(1, 7).unwrap();
        let low = library.to_body().unwrap();
        assert_eq!(library.strokes()[1].trim(), 7);
        assert_eq!(changed(&before, &low), [at + 1]);

        library.set_trim(1, 0x0107).unwrap();
        let high = library.to_body().unwrap();
        assert_eq!(library.strokes()[1].trim(), 0x0107);
        assert_eq!(changed(&low, &high), [at]);

        let error = library.set_trim(3, 4).unwrap_err().to_string();
        assert!(error.contains("stroke 3"), "{error}");
        assert_eq!(
            library.to_body().unwrap(),
            high,
            "a refused retrim leaves the directory alone"
        );
    }

    #[test]
    fn a_key_above_the_last_midi_note_is_refused_by_every_entry_point() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let last = (NOTES - 1) as u8;
        let past = NOTES as u8;

        assert!(library.fine_tune(last).is_ok());
        assert!(library.key_root(last).is_ok());
        assert!(library.set_fine_tune(last, 1).is_ok());
        assert!(library.set_key_root(last, None).is_ok());
        assert!(library.cut_range(0..=last).is_ok());
        assert!(library.split_at(last).is_ok());

        assert!(library.fine_tune(past).is_err());
        assert!(library.key_root(past).is_err());
        assert!(library.set_fine_tune(past, 1).is_err());
        assert!(library.set_key_root(past, None).is_err());
        assert!(library.set_key_root(0, Some(past)).is_err());
        assert!(library.cut_range(0..=past).is_err());
        assert!(library.cut_range(past..=past).is_err());
        assert!(library.split_at(past).is_err());
    }

    #[test]
    fn a_key_past_the_tune_table_is_refused_rather_than_written_to_the_next_table() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        let before = library.to_body().unwrap();
        assert!(library.set_fine_tune(NOTES as u8, 32).is_err());
        assert_eq!(library.to_body().unwrap(), before);
    }

    #[test]
    fn a_separator_in_a_name_or_a_variant_is_refused() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert!(library.set_name("Upright#2").is_err());
        assert!(library.set_variant("Sml#XL").is_err());
        assert_eq!(library.name(), ("Test Piano".into(), "Variant".into()));
    }

    /// A library with its audio dropped is a donor, not a file: laying it out would
    /// write a directory whose block counts nothing in the body backs.
    #[test]
    fn a_stroke_holding_other_than_the_blocks_its_record_states_is_not_laid_out() {
        let piano = Build::new().piano();
        let library = piano.library().unwrap();
        assert!(library.to_body().is_ok());

        let skeleton = library.without_audio();
        let error = skeleton
            .to_body()
            .expect_err("expected a refusal")
            .to_string();
        assert!(error.contains("stroke 0 holds 0 audio bytes"), "{error}");
        assert!(skeleton.body_len().is_err());
    }

    /// The halves either side of the separator are the vendor's own bytes, padding and
    /// all: setting one leaves the other exactly as the field spells it.
    #[test]
    fn setting_one_half_of_the_name_field_leaves_the_other_as_it_was_written() {
        let mut piano = Build::new().piano();
        let at = TextField::COMBINED.at;
        let padded = b"Grand Imperial # Bdorf XL";
        piano.file.body.0[at..at + TextField::COMBINED.len].fill(0);
        piano.file.body.0[at..at + padded.len()].copy_from_slice(padded);

        assert_eq!(
            piano.library().unwrap().name(),
            ("Grand Imperial".into(), "Bdorf XL".into())
        );

        let mut renamed = piano.library().unwrap();
        renamed.set_name("Upright").unwrap();
        assert_eq!(
            TextField::COMBINED.read(&renamed.prefix),
            "Upright# Bdorf XL"
        );

        let mut revoiced = piano.library().unwrap();
        revoiced.set_variant("Sml").unwrap();
        assert_eq!(
            TextField::COMBINED.read(&revoiced.prefix),
            "Grand Imperial #Sml"
        );
    }

    #[test]
    fn text_the_field_would_not_read_back_is_refused() {
        let piano = Build::new().piano();
        let mut library = piano.library().unwrap();
        assert!(
            library.set_name("Flügel").is_err(),
            "the field is read as ASCII"
        );
        assert!(
            library.set_variant("Sml\0XL").is_err(),
            "a NUL ends the field, hiding everything after it"
        );
        assert_eq!(library.name(), ("Test Piano".into(), "Variant".into()));
    }

    #[test]
    fn the_first_audio_offset_sits_on_the_block_grid_less_the_bias() {
        for block in [1022, 2044] {
            for count in [0usize, 1, 38, 2196] {
                let end = DIRECTORY_AT + count * RECORD;
                let at = first_audio_offset(end, block).unwrap();
                assert!(at >= end, "the audio never overlaps the directory");
                assert_eq!((at + AUDIO_ALIGN_BIAS) % block, 0);
                assert!(at - end < block, "no whole spare block in the gap");
            }
        }
    }
}