nord-format 0.5.0

Read and write Clavia / Nord keyboard file formats — programs, samples, set lists, settings, backups — with byte-exact round-trips
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
//! 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 are inferred from specimens; not
//! confirmed on hardware. Confirmed on hardware: the container layout as
//! [`Library::to_body`] writes it — a library whose directory and audio this crate
//! re-laid loads on the instrument and plays at the original's level — and, within
//! it, that the key map's value is the recording's root note, that a stroke's
//! [`Bank`] is what it is played for, and that [`Stroke::layer`] indexes softness.
//!
//! 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;

use crate::cbin::{self, Cbin, Header, RawBody};
use crate::error::{try_vec, Error, ParseError};
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: &[u16] = &[0x450, 0x464];
/// [`KNOWN_VERSIONS`] as the gate spells them.
const KNOWN_VERSIONS_U32: &[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;

/// 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_ID: usize = 0x6e;

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

/// The audio grid's offset from a whole number of blocks.
///
/// Unexplained: every library holds it and nothing in the file derives it. That the
/// grid it defines is the one the instrument reads is 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 from the note-on while the sustain pedal is down, 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: the layer values that survive keep the values
/// they had, which is safe because the instrument picks by rank among the layers a
/// root still holds rather than by matching a layer value. 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 they open with the `CNSP` magic.
    fn cnsp(&self) -> Result<&[u8], Error> {
        let body = &self.file.body.0;
        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());
        }
        Ok(body)
    }

    /// 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 version = self.stream_version()?;
        crate::formats::known_version(FORMAT, u32::from(version), KNOWN_VERSIONS_U32)?;
        self.cnsp()
    }

    /// The stream version at body `0x04`.
    pub fn stream_version(&self) -> Result<u16, Error> {
        let body = self.cnsp()?;
        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 `(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(self)
    }
}

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, each half trimmed of the padding the
/// vendor lays either side of it.
fn split_name(field: &str) -> (String, String) {
    let (name, variant) = field.split_once('#').unwrap_or((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()
}

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: &'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 index within the root's bank; 0 is the loudest recording, and a
    /// bank's values need be neither dense nor start at zero. Confirmed on
    /// hardware.
    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 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) -> &'a [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> {
    fn parse(piano: &'a Piano) -> Result<Library<'a>, Error> {
        let body = piano.mapped()?;
        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,
            });
            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: piano.file.header.clone(),
            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
    }

    /// 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 are confirmed on hardware from libraries as the
    /// vendor tuned them; that rewriting the byte retunes the key is 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 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: vendor
    /// libraries spell the long name differently from the name before the `#`
    /// (`EP5 BrightTines` against `EP5 Bright Tines`), and the voicing holds
    /// neither the padding nor the size suffix the variant does.
    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 is inferred from specimens; not confirmed on hardware — which is why
    /// both move.
    pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
        check_half("name", name)?;
        let (_, variant) = self.name();
        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 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 (name, _) = self.name();
        TextField::COMBINED.write(
            &mut self.prefix,
            &format!("{name}{NAME_SEPARATOR}{variant}"),
        )
    }

    /// 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 — is 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.
    ///
    /// Confirmed on hardware for [`Bank::Release`]: the instrument damps the note at
    /// note-off where the library it came from plays a release tail.
    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())))
            }
        }
    }

    /// 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 is 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.
    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 first = first_audio_offset(directory_end, self.block_bytes())?;
        let mut len = first;
        for stroke in &self.strokes {
            len = len
                .checked_add(stroke.audio.len())
                .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. Confirmed on hardware only in that a
    /// library carrying its source's word loads and plays; 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::*;

    /// A body shaped like a real one: prefix, directory and audio spans laid out
    /// by the same law the reader checks, with each stroke's audio filled with a
    /// byte naming it so a re-lay is visible.
    struct Build {
        version: u16,
        channels: u16,
        /// `(root, bank, layer, blocks)`, in ascending root order.
        strokes: Vec<(u8, u8, u8, u16)>,
        /// `(key, root)` routes.
        map: Vec<(u8, u8)>,
    }

    impl Build {
        fn new() -> Build {
            Build {
                version: 0x450,
                channels: 1,
                strokes: vec![(60, 0, 0, 1), (60, 2, 3, 1), (72, 0, 0, 2)],
                map: vec![(60, 60), (61, 60), (72, 72)],
            }
        }

        fn body(&self) -> Vec<u8> {
            let block = block_bytes(self.channels);
            let count = self.strokes.len();
            let directory_end = DIRECTORY_AT + count * RECORD;
            let first = first_audio_offset(directory_end, block).unwrap();
            let audio: usize = self
                .strokes
                .iter()
                .map(|&(_, _, _, blocks)| usize::from(blocks) * block)
                .sum();
            let mut body = vec![0u8; first + audio];
            body[..4].copy_from_slice(CNSP_MAGIC);
            body[VERSION_AT..VERSION_AT + 2].copy_from_slice(&self.version.to_be_bytes());
            body[VERSION_ECHO_AT..VERSION_ECHO_AT + 2].copy_from_slice(&self.version.to_be_bytes());
            body[CHANNELS_AT..CHANNELS_AT + 2].copy_from_slice(&self.channels.to_be_bytes());
            let name = b"Test Piano#Variant";
            body[0x1c..0x1c + name.len()].copy_from_slice(name);
            body[KEY_MAP_AT..KEY_MAP_AT + NOTES].fill(UNCOVERED);
            for &(key, root) in &self.map {
                body[KEY_MAP_AT + usize::from(key)] = root;
            }
            body[STROKE_COUNT_AT..STROKE_COUNT_AT + 2]
                .copy_from_slice(&(count as u16).to_be_bytes());
            for note in 0..NOTES {
                let n = self
                    .strokes
                    .iter()
                    .filter(|&&(root, ..)| usize::from(root) == note)
                    .count() as u16;
                let at = ROOT_COUNTS_AT + note * 2;
                body[at..at + 2].copy_from_slice(&n.to_be_bytes());
            }
            let mut at = first;
            for (i, &(_, bank, layer, blocks)) in self.strokes.iter().enumerate() {
                let rec = DIRECTORY_AT + i * RECORD;
                body[rec..rec + 4].copy_from_slice(&(at as u32).to_be_bytes());
                body[rec + REC_BANK] = bank;
                body[rec + REC_LAYER] = layer;
                body[rec + REC_BLOCKS..rec + REC_BLOCKS + 2].copy_from_slice(&blocks.to_be_bytes());
                body[rec + REC_ID..rec + REC_ID + 4].copy_from_slice(&(i as u32).to_be_bytes());
                let span = usize::from(blocks) * block;
                body[at..at + span].fill(0x40 + i as u8);
                at += span;
            }
            body
        }

        fn piano(&self) -> Piano {
            let body = self.body();
            Piano {
                file: Cbin {
                    header: Header::new(FORMAT, (0, 0), 530),
                    body: RawBody(body),
                },
            }
        }
    }

    #[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 library_owner = Build::new();
        library_owner.strokes = vec![(60, 0, 0, 1), (72, 1, 0, 1)];
        let piano = library_owner.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.strokes = vec![
            (60, 0, 0, 1),
            (60, 0, 5, 1),
            (60, 2, 26, 1),
            (60, 2, 30, 1),
            (72, 0, 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.strokes = vec![(60, 0, 0, 1), (60, 0, 5, 1), (72, 0, 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)]);
    }

    #[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);
    }

    #[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()));
    }

    #[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");
            }
        }
    }
}