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
//! Parse and write Clavia / Nord keyboard binary file formats.
//!
//! > This is an unofficial, community project: **not affiliated with, endorsed
//! > by, or supported by Clavia DMI AB**. "Nord" and the instrument names are
//! > Clavia's trademarks, used here only to identify which files this crate
//! > reads.
//!
//! The formats — programs, live slots, songs, settings, presets, synth
//! patches, sample and piano libraries, across the Nord keyboard range — are
//! reverse engineered from specimen files and hardware observation, never
//! from Clavia's software, and are in varying states of completion: some
//! bodies decode to named fields, others are container-verified and kept
//! verbatim. [`formats`] is the map of what exists and how far each format's
//! decoding goes.
//!
//! Completeness never gates I/O. Every supported file reads and writes
//! whether its body decodes fully, partially, or not at all: decoded values
//! are views over a verbatim body, bits no field claims survive untouched,
//! and `to_bytes(from_stream(x)) == x` bit-for-bit (archives are read-only).
//! That invariant is tested against a private corpus of real files.
//!
//! [`from_path`] / [`from_stream`] sniff any supported file and decode it
//! into an [`Entity`]; [`to_bytes`] is the inverse.
//!
//! Runtime dependencies are `crcxx` and `thiserror` (plus `zip` behind the
//! `bundle` feature), and no I/O happens beyond `Read`/`Seek`/`Write`, so the
//! crate runs anywhere `std` does — wasm included. Device access lives in the
//! companion `nord-usb` crate, in the same repository.

pub mod accept;
pub mod bank;
pub mod bits;
pub mod cbin;
pub mod components;
pub mod crc;
pub mod error;
pub mod fields;
pub mod formats;
pub mod layout;
pub mod note;
pub mod panel;
pub mod types;
pub mod util;
pub mod wav;

use crate::cbin::{Cbin, RawBody};
use crate::formats::{
    cn3, midi, nc2, nc2d, nd2, nd3, ne3, ne4, ne5, ne6, ne7, ng2, nl4, nla1, no3, np, np2, np3,
    np4, np5, npip, npno, ns2, ns3, ns4, nsclassic, nsmp, nsmpproj, nw, nw2, sysex,
};
use std::fs::File;
use std::io::{BufReader, Read, Seek};
use std::path::Path;
use util::{peek, FileType};

use crate::error::{Error, ParseError};

/// A ZIP archive: an Electro 5 bundle or backup, or a Drum-family bank.
#[cfg(feature = "bundle")]
#[derive(Debug)]
pub enum Bundle {
    Drum2Bank(nd2::bank::Bank),
    Drum3KitBank(nd3::kit_bank::KitBank),
    Electro5(ne5::Bundle),
    /// A ZIP of CBIN files under any mix of tags — every model's bundle/backup
    /// shape. Reported by public documentation; not confirmed on hardware.
    /// Members are kept container-verified and raw, under their archive paths —
    /// which encode the slot, uninterpreted here.
    Members(Vec<(String, Cbin<RawBody>)>),
}

/// A stored program, one variant per model. Only the Electro 5 and the three
/// Stages decode anything of the body; the rest are container-verified stubs.
///
/// Left unboxed for the reason [`Entity`] gives.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Program {
    C2(Cbin<RawBody>),
    C2D(Cbin<RawBody>),
    /// A Nord Drum 2 program (`nd2p`), usually met inside a bank archive.
    Drum2(Cbin<RawBody>),
    /// A Nord Drum 3P kit (`nd3k`) — the model's program-equivalent.
    Drum3(Cbin<RawBody>),
    /// Electro 3 and 3HP — the file does not say which.
    Electro3(Cbin<RawBody>),
    /// Electro 4 and 4D — likewise.
    Electro4(Cbin<RawBody>),
    Electro5(Cbin<ne5::Program>),
    Electro6(Cbin<RawBody>),
    Electro7(Cbin<RawBody>),
    Grand(Cbin<RawBody>),
    Lead4(Cbin<RawBody>),
    LeadA1(Cbin<RawBody>),
    Organ3(Cbin<RawBody>),
    Piano1(Cbin<RawBody>),
    Piano2(Cbin<RawBody>),
    Piano3(Cbin<RawBody>),
    Piano4(Cbin<RawBody>),
    Piano5(Cbin<RawBody>),
    /// Stage 2 and 2 EX.
    Stage2(Cbin<ns2::Program>),
    Stage3(Cbin<ns3::Program>),
    Stage4(Cbin<ns4::Program>),
    /// Stage Classic and Stage EX.
    StageClassic(Cbin<RawBody>),
    Wave(Cbin<RawBody>),
    Wave2(Cbin<RawBody>),
}

/// The live buffer — the panel as it stands, not a saved program. Same body as
/// [`Program`], under its own format tag.
///
/// Left unboxed for the reason [`Entity`] gives.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Live {
    Electro4(Cbin<RawBody>),
    Electro5(Cbin<ne5::Program>),
    Electro6(Cbin<RawBody>),
    Electro7(Cbin<RawBody>),
    Grand(Cbin<RawBody>),
    Piano1(Cbin<RawBody>),
    Piano2(Cbin<RawBody>),
    Piano3(Cbin<RawBody>),
    Piano4(Cbin<RawBody>),
    Piano5(Cbin<RawBody>),
    Stage2(Cbin<ns2::Program>),
    Stage3(Cbin<ns3::Program>),
    Stage4(Cbin<ns4::Program>),
    Wave2(Cbin<RawBody>),
}

/// A stored song / set list, one variant per model that has them. Only the
/// Electro 5 body decodes; the Stage 3 is container-verified verbatim.
#[derive(Debug)]
pub enum Song {
    Electro5(Cbin<ne5::Song>),
    Stage3(Cbin<RawBody>),
}

/// The instrument's global settings, one variant per model. Only the Electro 5
/// body decodes; the rest are container-verified stubs.
#[derive(Debug)]
pub enum Settings {
    C2(Cbin<RawBody>),
    C2D(Cbin<RawBody>),
    Electro4(Cbin<RawBody>),
    Electro5(Cbin<ne5::Settings>),
    Electro6(Cbin<RawBody>),
    Electro7(Cbin<RawBody>),
    Grand(Cbin<RawBody>),
    Lead4(Cbin<RawBody>),
    LeadA1(Cbin<RawBody>),
    Organ3(Cbin<RawBody>),
    Piano1(Cbin<RawBody>),
    Piano2(Cbin<RawBody>),
    Piano3(Cbin<RawBody>),
    Piano4(Cbin<RawBody>),
    Piano5(Cbin<RawBody>),
    Stage2(Cbin<RawBody>),
    Stage3(Cbin<RawBody>),
    Stage4(Cbin<RawBody>),
    Wave(Cbin<RawBody>),
    Wave2(Cbin<RawBody>),
}

/// A synth patch, on the models that bank them separately from programs. Only
/// the Stage 4's decodes.
///
/// Left unboxed for the reason [`Entity`] gives.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Synth {
    Stage2(Cbin<RawBody>),
    Stage3(Cbin<ns3::SynthPreset>),
    Stage4(Cbin<ns4::synth::SynthPreset>),
    StageClassic(Cbin<RawBody>),
}

/// A Lead performance — the multi-slot layer above that family's programs.
#[derive(Debug)]
pub enum Performance {
    Lead4(Cbin<RawBody>),
    LeadA1(Cbin<RawBody>),
}

/// A stored organ preset, on the models that keep them as files.
///
/// Left unboxed for the reason [`Entity`] gives.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum OrganPreset {
    /// Electro 3 and 3HP (`neop`).
    Electro3(Cbin<RawBody>),
    /// Stage 4 (`ns4o`).
    Stage4(Cbin<ns4::organ_preset::OrganPreset>),
}

/// A stored piano preset, on the models that keep them as files.
#[derive(Debug)]
pub enum PianoPreset {
    /// Stage 4 (`ns4n`).
    Stage4(Cbin<ns4::piano_preset::PianoPreset>),
}

/// A sample instrument, decoded by generation: all three share the `nsmp` tag,
/// and the header version says which schema the body holds.
#[derive(Debug)]
pub enum Sample {
    V2(Cbin<nsmp::Sample>),
    /// The nsmp3/nsmp4 generations: section chain decoded, strokes stored
    /// verbatim and decodable through [`nsmp::codec`].
    V3(Cbin<nsmp::SampleV3>),
}

impl Sample {
    pub fn name(&self) -> Result<String, Error> {
        match self {
            Sample::V2(s) => s.name(),
            Sample::V3(s) => s.name(),
        }
    }

    /// Longest name this generation's field takes.
    pub fn max_name_len(&self) -> usize {
        match self {
            Sample::V2(_) => nsmp::MAX_NAME_LEN,
            Sample::V3(_) => nsmp::MAX_NAME_V3_LEN,
        }
    }

    pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
        match self {
            Sample::V2(s) => s.set_name(name),
            Sample::V3(s) => s.set_name(name),
        }
    }

    /// Move the note a zone's sample plays untransposed at.
    pub fn set_root_key(&mut self, index: usize, note: u8) -> Result<(), Error> {
        match self {
            Sample::V2(s) => s.set_root_key(index, note),
            Sample::V3(s) => s.set_root_key(index, note),
        }
    }

    pub fn set_zone_top_note(&mut self, index: usize, note: u8) -> Result<(), Error> {
        match self {
            Sample::V2(s) => s.set_zone_top_note(index, note),
            Sample::V3(s) => s.set_zone_top_note(index, note),
        }
    }

    /// Whether this generation stores a zone's lowest note.
    ///
    /// False where zones tile — a zone reaches down to one above the next-lower zone's
    /// top, so only the top note is stored — which is what makes
    /// [`Self::set_zone_low_note`] refuse there.
    pub fn has_low_note(&self) -> bool {
        matches!(self, Sample::V3(_))
    }

    /// Move a zone's lowest note, on the generations that store one — see
    /// [`Self::has_low_note`].
    pub fn set_zone_low_note(&mut self, index: usize, note: u8) -> Result<(), Error> {
        match self {
            Sample::V2(_) => Err(ParseError::AssertFail("v2 stores no low note".into()).into()),
            Sample::V3(s) => s.set_zone_low_note(index, note),
        }
    }

    /// Whether this instrument's zones can be retuned and remapped. Its name
    /// always can.
    ///
    /// False where the zone table does not read, or where a `map` that also
    /// describes the keyboard note by note cannot be recomputed from the layout.
    /// The setters say which at length.
    pub fn zones_are_editable(&self) -> bool {
        match self {
            Sample::V2(s) => s.zones().is_ok() && s.strokes().is_ok(),
            Sample::V3(s) => s.zones_are_editable(),
        }
    }

    /// Which section chain this body's sections form. A narrow body whose `map`
    /// version names no chain we have a specimen of reports the error.
    pub fn chain(&self) -> Result<nsmp::Chain, Error> {
        match self {
            Sample::V2(s) => s.chain(),
            Sample::V3(_) => Ok(nsmp::Chain::Wide),
        }
    }

    /// Which generation's units this body's stroke streams are in. A content version
    /// past the generations the codec describes is refused rather than guessed at.
    pub fn layout(&self) -> Result<nsmp::codec::Layout, Error> {
        match self {
            Sample::V2(_) => Ok(nsmp::codec::Layout::V2),
            Sample::V3(s) => nsmp::codec::Layout::from_version(s.header.version).ok_or_else(|| {
                ParseError::OutOfBounds {
                    value: format!("content version {}", s.header.version),
                    bound: format!(
                        "the generations this codec describes, below {}",
                        nsmp::codec::V5_FROM_VERSION
                    ),
                }
                .into()
            }),
        }
    }

    /// The generation to name in a report, taken from the content version rather
    /// than the file name.
    pub fn generation(&self) -> &'static str {
        match self {
            Sample::V2(_) => "v2",
            Sample::V3(s) if s.header.version >= nsmp::V4_FROM_VERSION => "v4",
            Sample::V3(_) => "v3",
        }
    }

    /// Every zone in stored order, paired with the stream that plays it.
    ///
    /// One codec reads all three generations, so the only thing that branches here
    /// is which accessors reach the zones and their streams.
    pub fn zones(&self) -> Result<Vec<nsmp::ZoneAudio<'_>>, Error> {
        match self {
            Sample::V2(s) => {
                let zones = s.zones()?;
                let strokes = s.strokes()?;
                zones
                    .iter()
                    .zip(&strokes)
                    .enumerate()
                    .map(|(i, (zone, stroke))| {
                        let (at, stream) = s.zone_stream(i)?;
                        Ok(nsmp::ZoneAudio {
                            root_key: stroke.root_key,
                            top_note: zone.top_note,
                            low_note: None,
                            at,
                            stream,
                        })
                    })
                    .collect()
            }
            Sample::V3(s) => {
                let zones = s.zones()?;
                zones
                    .iter()
                    .enumerate()
                    .map(|(i, zone)| {
                        let (at, stream) = s.zone_stream(i)?;
                        Ok(nsmp::ZoneAudio {
                            root_key: zone.root_key,
                            top_note: zone.top_note,
                            low_note: zone.low_note,
                            at,
                            stream,
                        })
                    })
                    .collect()
            }
        }
    }

    /// Every stroke's stream in file order, whether or not a zone names it.
    pub fn stroke_streams(&self) -> Vec<(usize, &[u8])> {
        match self {
            Sample::V2(s) => s.stroke_streams(),
            Sample::V3(s) => s.stroke_streams(),
        }
    }

    /// Serializes, recomputing the checksum over the body it just produced.
    pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        let mut out = std::io::Cursor::new(Vec::new());
        match self {
            Sample::V2(s) => s.write_to(&mut out),
            Sample::V3(s) => s.write_to(&mut out),
        }?;
        Ok(out.into_inner())
    }
}

/// One decoded file.
///
/// The decoded program variants are much the largest: a decoded panel holds its
/// fields *and* the bytes it came from. Left unboxed — one of these exists per
/// file being read, never in a collection.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Entity {
    /// An Electro 2 sample library — the one non-CBIN library format.
    Cne3(cn3::Cne3),
    Live(Live),
    /// A MIDI carrier for a Lead SysEx bank, verbatim.
    Midi(midi::Midi),
    OrganPreset(OrganPreset),
    /// A piano library (`npno`).
    Piano(npno::Piano),
    /// A Stage Classic piano library (`nsp`). ⚠️ Megabytes, allocated whole —
    /// [`cbin::inspect`] answers container questions in O(1).
    PianoLibrary(Cbin<RawBody>),
    PianoPreset(PianoPreset),
    /// A C2 pipe-organ library (`npip`). Same caution as [`Entity::PianoLibrary`].
    PipeLibrary(Cbin<RawBody>),
    Performance(Performance),
    Program(Program),
    Sample(Sample),
    /// A Nord Sample Editor project (`.nsmpproj`) — the text file the editor
    /// saves and generates an `nsmp` from.
    SampleProject(nsmpproj::Project),
    Settings(Settings),
    Song(Song),
    Synth(Synth),
    /// A Lead 1/2/2X/3 SysEx dump, verbatim.
    Sysex(sysex::Sysex),
    #[cfg(feature = "bundle")]
    Bundle(Bundle),
}

/// Sniff `reader` and decode one supported file into an [`Entity`] — the
/// counterpart to [`to_bytes`]. The container class comes from the leading
/// bytes; a CBIN body is then dispatched on the format tag at offset 8.
pub fn from_stream(reader: &mut (impl Read + Seek + Sized)) -> Result<Entity, Error> {
    let header = peek(reader)?;

    match header.file_type {
        #[cfg(feature = "bundle")]
        FileType::Zip => read_zip(reader),
        #[cfg(not(feature = "bundle"))]
        FileType::Zip => {
            Err(ParseError::UnknownFileType("zip (bundle feature disabled)".to_string()).into())
        }
        FileType::Sysex => Ok(Entity::Sysex(sysex::Sysex::read_from(reader)?)),
        FileType::Midi => Ok(Entity::Midi(midi::Midi::read_from(reader)?)),
        FileType::Cne3 => Ok(Entity::Cne3(cn3::Cne3::read_from(reader)?)),
        FileType::SampleProject => Ok(Entity::SampleProject(nsmpproj::Project::read_from(reader)?)),
        FileType::Cbin => read_cbin(reader, header.format.as_str()),
        e => Err(ParseError::UnknownFileType(e.as_str().to_string()).into()),
    }
}

/// One CBIN file, dispatched by the tag at offset 8.
fn read_cbin(reader: &mut (impl Read + Seek), tag: &str) -> Result<Entity, Error> {
    use Entity as E;

    Ok(match tag {
        nsmp::FORMAT => {
            let file: Cbin<nsmp::AnyBody> = cbin::read(reader, nsmp::FORMAT)?;
            let header = file.header;
            E::Sample(match file.body {
                nsmp::AnyBody::V2(body) => Sample::V2(Cbin { header, body }),
                nsmp::AnyBody::V3(body) => Sample::V3(Cbin { header, body }),
            })
        }
        npno::FORMAT => E::Piano(npno::Piano::read_from(reader)?),
        npip::pipe_library::FORMAT => E::PipeLibrary(npip::pipe_library::read_from(reader)?),
        nsclassic::piano_library::FORMAT => {
            E::PianoLibrary(nsclassic::piano_library::read_from(reader)?)
        }

        ne3::program::FORMAT => E::Program(Program::Electro3(ne3::program::read_from(reader)?)),
        ne3::organ_preset::FORMAT => {
            E::OrganPreset(OrganPreset::Electro3(ne3::organ_preset::read_from(reader)?))
        }
        ne4::program::FORMAT => E::Program(Program::Electro4(ne4::program::read_from(reader)?)),
        ne4::live::FORMAT => E::Live(Live::Electro4(ne4::live::read_from(reader)?)),
        ne4::settings::FORMAT => E::Settings(Settings::Electro4(ne4::settings::read_from(reader)?)),
        ne5::program::FORMAT => E::Program(Program::Electro5(ne5::program::read_from(reader)?)),
        ne5::live::FORMAT => E::Live(Live::Electro5(ne5::live::read_from(reader)?)),
        ne5::song::FORMAT => E::Song(Song::Electro5(ne5::song::read_from(reader)?)),
        ne5::settings::FORMAT => E::Settings(Settings::Electro5(ne5::settings::read_from(reader)?)),
        ne6::program::FORMAT => E::Program(Program::Electro6(ne6::program::read_from(reader)?)),
        ne6::live::FORMAT => E::Live(Live::Electro6(ne6::live::read_from(reader)?)),
        ne6::settings::FORMAT => E::Settings(Settings::Electro6(ne6::settings::read_from(reader)?)),
        ne7::program::FORMAT => E::Program(Program::Electro7(ne7::program::read_from(reader)?)),
        ne7::live::FORMAT => E::Live(Live::Electro7(ne7::live::read_from(reader)?)),
        ne7::settings::FORMAT => E::Settings(Settings::Electro7(ne7::settings::read_from(reader)?)),

        nsclassic::program::FORMAT => E::Program(Program::StageClassic(
            nsclassic::program::read_from(reader)?,
        )),
        nsclassic::synth::FORMAT => {
            E::Synth(Synth::StageClassic(nsclassic::synth::read_from(reader)?))
        }
        ns2::program::FORMAT => E::Program(Program::Stage2(ns2::program::read_from(reader)?)),
        ns2::live::FORMAT => E::Live(Live::Stage2(ns2::live::read_from(reader)?)),
        ns2::synth::FORMAT => E::Synth(Synth::Stage2(ns2::synth::read_from(reader)?)),
        ns2::settings::FORMAT => E::Settings(Settings::Stage2(ns2::settings::read_from(reader)?)),
        ns3::program::FORMAT => E::Program(Program::Stage3(ns3::program::read_from(reader)?)),
        ns3::live::FORMAT => E::Live(Live::Stage3(ns3::live::read_from(reader)?)),
        ns3::song::FORMAT => E::Song(Song::Stage3(ns3::song::read_from(reader)?)),
        ns3::synth::FORMAT => E::Synth(Synth::Stage3(ns3::synth::read_from(reader)?)),
        ns3::settings::FORMAT => E::Settings(Settings::Stage3(ns3::settings::read_from(reader)?)),
        ns4::program::FORMAT => E::Program(Program::Stage4(ns4::program::read_from(reader)?)),
        ns4::live::FORMAT => E::Live(Live::Stage4(ns4::live::read_from(reader)?)),
        ns4::synth::FORMAT => E::Synth(Synth::Stage4(ns4::synth::read_from(reader)?)),
        ns4::piano_preset::FORMAT => {
            E::PianoPreset(PianoPreset::Stage4(ns4::piano_preset::read_from(reader)?))
        }
        ns4::organ_preset::FORMAT => {
            E::OrganPreset(OrganPreset::Stage4(ns4::organ_preset::read_from(reader)?))
        }
        ns4::settings::FORMAT => E::Settings(Settings::Stage4(ns4::settings::read_from(reader)?)),

        np::program::FORMAT => E::Program(Program::Piano1(np::program::read_from(reader)?)),
        np::live::FORMAT => E::Live(Live::Piano1(np::live::read_from(reader)?)),
        np::settings::FORMAT => E::Settings(Settings::Piano1(np::settings::read_from(reader)?)),
        np2::program::FORMAT => E::Program(Program::Piano2(np2::program::read_from(reader)?)),
        np2::live::FORMAT => E::Live(Live::Piano2(np2::live::read_from(reader)?)),
        np2::settings::FORMAT => E::Settings(Settings::Piano2(np2::settings::read_from(reader)?)),
        np3::program::FORMAT => E::Program(Program::Piano3(np3::program::read_from(reader)?)),
        np3::live::FORMAT => E::Live(Live::Piano3(np3::live::read_from(reader)?)),
        np3::settings::FORMAT => E::Settings(Settings::Piano3(np3::settings::read_from(reader)?)),
        np4::program::FORMAT => E::Program(Program::Piano4(np4::program::read_from(reader)?)),
        np4::live::FORMAT => E::Live(Live::Piano4(np4::live::read_from(reader)?)),
        np4::settings::FORMAT => E::Settings(Settings::Piano4(np4::settings::read_from(reader)?)),
        np5::program::FORMAT => E::Program(Program::Piano5(np5::program::read_from(reader)?)),
        np5::live::FORMAT => E::Live(Live::Piano5(np5::live::read_from(reader)?)),
        np5::settings::FORMAT => E::Settings(Settings::Piano5(np5::settings::read_from(reader)?)),
        ng2::program::FORMAT => E::Program(Program::Grand(ng2::program::read_from(reader)?)),
        ng2::live::FORMAT => E::Live(Live::Grand(ng2::live::read_from(reader)?)),
        ng2::settings::FORMAT => E::Settings(Settings::Grand(ng2::settings::read_from(reader)?)),

        nw::program::FORMAT => E::Program(Program::Wave(nw::program::read_from(reader)?)),
        nw::settings::FORMAT => E::Settings(Settings::Wave(nw::settings::read_from(reader)?)),
        nw2::program::FORMAT => E::Program(Program::Wave2(nw2::program::read_from(reader)?)),
        nw2::live::FORMAT => E::Live(Live::Wave2(nw2::live::read_from(reader)?)),
        nw2::settings::FORMAT => E::Settings(Settings::Wave2(nw2::settings::read_from(reader)?)),

        nc2::program::FORMAT => E::Program(Program::C2(nc2::program::read_from(reader)?)),
        nc2::settings::FORMAT => E::Settings(Settings::C2(nc2::settings::read_from(reader)?)),
        nc2d::program::FORMAT => E::Program(Program::C2D(nc2d::program::read_from(reader)?)),
        nc2d::settings::FORMAT => E::Settings(Settings::C2D(nc2d::settings::read_from(reader)?)),
        no3::program::FORMAT => E::Program(Program::Organ3(no3::program::read_from(reader)?)),
        no3::settings::FORMAT => E::Settings(Settings::Organ3(no3::settings::read_from(reader)?)),

        // Leads (the CBIN generation; the older Leads ship SysEx).
        nl4::program::FORMAT => E::Program(Program::Lead4(nl4::program::read_from(reader)?)),
        nl4::performance::FORMAT => {
            E::Performance(Performance::Lead4(nl4::performance::read_from(reader)?))
        }
        nl4::settings::FORMAT => E::Settings(Settings::Lead4(nl4::settings::read_from(reader)?)),
        nla1::program::FORMAT => E::Program(Program::LeadA1(nla1::program::read_from(reader)?)),
        nla1::performance::FORMAT => {
            E::Performance(Performance::LeadA1(nla1::performance::read_from(reader)?))
        }
        nla1::settings::FORMAT => E::Settings(Settings::LeadA1(nla1::settings::read_from(reader)?)),

        nd2::program::FORMAT => E::Program(Program::Drum2(nd2::program::read_from(reader)?)),
        nd3::kit::FORMAT => E::Program(Program::Drum3(nd3::kit::read_from(reader)?)),

        e => return Err(ParseError::UnknownFormat(e.to_string()).into()),
    })
}

/// Which archive a ZIP is, from the members the walks below will see.
#[cfg(feature = "bundle")]
enum ZipKind {
    Electro5,
    Drum2,
    Drum3,
    Members,
}

/// One ZIP file: an Electro 5 bundle or backup (it carries a `meta.xml`
/// manifest), or a Drum bank (members are all one CBIN format).
#[cfg(feature = "bundle")]
fn read_zip(reader: &mut (impl Read + Seek)) -> Result<Entity, Error> {
    let start = reader.stream_position()?;
    let kind = {
        let zip = zip::ZipArchive::new(&mut *reader)?;
        // The entries the walks skip are not members: a directory holds no file, and a
        // backup manifest describes the archive. Classifying on them would call an
        // archive of directories a bundle of none, and a `kits/` entry would stop a drum
        // bank being one.
        let names: Vec<&str> = zip
            .file_names()
            .filter(|name| !is_dir_entry(name) && !name.ends_with("meta.xml"))
            .collect();
        // An archive with nothing in it would satisfy the all-members checks below
        // vacuously and read as a drum bank holding no programs.
        if names.is_empty() {
            return Err(ParseError::AssertFail("the archive holds no members".into()).into());
        }
        // ⚠️ `meta.xml` is shared across product families; only `.ne5*` members identify
        // an Electro 5 bundle.
        if names.iter().any(|n| {
            std::path::Path::new(n)
                .extension()
                .is_some_and(|e| e.to_string_lossy().starts_with("ne5"))
        }) {
            ZipKind::Electro5
        } else if names.iter().all(|n| n.ends_with(".nd2p")) {
            ZipKind::Drum2
        } else if names.iter().all(|n| n.ends_with(".nd3k")) {
            ZipKind::Drum3
        } else {
            // Anything else — a bundle only if every member is a CBIN file,
            // which `zip_raw_members` decides below.
            ZipKind::Members
        }
    };
    reader.seek(std::io::SeekFrom::Start(start))?;

    Ok(Entity::Bundle(match kind {
        ZipKind::Drum2 => Bundle::Drum2Bank(nd2::bank::read_from(reader)?),
        ZipKind::Drum3 => Bundle::Drum3KitBank(nd3::kit_bank::read_from(reader)?),
        ZipKind::Members => Bundle::Members(formats::zip_raw_members(reader)?),
        ZipKind::Electro5 => Bundle::Electro5(ne5::Bundle::read_from(reader)?),
    }))
}

/// A directory entry, spelled as `zip`'s own `is_dir` spells it — the name alone, since
/// classification reads the archive's names rather than its entries.
#[cfg(feature = "bundle")]
fn is_dir_entry(name: &str) -> bool {
    name.ends_with('/') || name.ends_with('\\')
}

/// [`from_stream`] over a buffered read of the file at `path`.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Entity, Error> {
    from_stream(&mut BufReader::new(File::open(path)?))
}

#[cfg(test)]
mod registry_tests {
    use super::*;

    /// A registry read and written through the entity lands on the same field the
    /// body's own accessors reach, so neither consumer needs to name the body type.
    #[test]
    fn the_entity_registry_reads_and_writes_the_body() {
        let mut entity = Entity::Program(Program::Electro5(ne5::program::new(
            (0, 0).try_into().unwrap(),
        )));

        let before = entity.registry().unwrap().fields();
        assert!(before.iter().any(|f| f.path == "center_panel.transpose"));

        entity
            .registry_mut()
            .unwrap()
            .set_field("center_panel.transpose", "-5")
            .unwrap();
        let after = entity.registry().unwrap().fields();
        let transpose = after
            .iter()
            .find(|f| f.path == "center_panel.transpose")
            .unwrap();
        assert_eq!(transpose.value, "-5");
    }

    /// A stub-backed entity has no registry, and says so the same way in both
    /// directions.
    #[test]
    fn a_stub_has_no_registry() {
        let file = Cbin {
            header: cbin::Header::new("ne6p", (0, 0), 1),
            body: RawBody(vec![0; 16]),
        };
        let mut entity = Entity::Program(Program::Electro6(file));
        assert!(entity.registry().is_none());
        assert!(entity.registry_mut().is_none());
    }

    /// A song's fields are private, so its registry would list nothing — it is
    /// deliberately not a registry entity, and `Song::set` is its editing surface.
    #[test]
    fn a_song_is_not_a_registry_entity() {
        let song = ne5::song::new(
            (0, 0).try_into().unwrap(),
            ne5::song::DEFAULT_VERSION,
            [(0, 0).try_into().unwrap(); 4],
        )
        .unwrap();
        assert!(Entity::Song(Song::Electro5(song)).registry().is_none());
    }
}

#[cfg(all(test, feature = "bundle"))]
mod bundle_tests {
    use super::*;
    use crate::cbin::{Cbin, Header, RawBody};
    use std::io::{Cursor, Write};

    fn member(tag: &str) -> Vec<u8> {
        let file = Cbin {
            header: Header::new(tag, (0, 0), 4),
            body: RawBody(vec![0x5A; 16]),
        };
        let mut out = Cursor::new(Vec::new());
        file.write_to(&mut out).unwrap();
        out.into_inner()
    }

    /// A stored archive of `members`; a name ending in `/` becomes a directory entry.
    fn archive(members: &[(&str, &[u8])]) -> Vec<u8> {
        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
        let stored = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        for (name, bytes) in members {
            match name.strip_suffix('/') {
                Some(directory) => zip.add_directory(directory, stored).unwrap(),
                None => {
                    zip.start_file(name.to_string(), stored).unwrap();
                    zip.write_all(bytes).unwrap();
                }
            }
        }
        zip.finish().unwrap().into_inner()
    }

    /// A ZIP of mixed CBIN members — the reported family bundle shape — reads
    /// as [`Bundle::Members`] with paths preserved.
    #[test]
    fn a_zip_of_mixed_cbin_members_is_a_bundle() {
        let a = member("ns3f");
        let b = member("ns3y");
        let bytes = archive(&[("Bank A/One.ns3f", &a), ("presets/Two.ns3y", &b)]);

        let entity = from_stream(&mut Cursor::new(bytes)).unwrap();
        let Entity::Bundle(Bundle::Members(members)) = entity else {
            panic!("decoded to something other than a member bundle");
        };
        assert_eq!(members.len(), 2);
        assert_eq!(members[0].0, "Bank A/One.ns3f");
        assert_eq!(&members[0].1.header.tag, b"ns3f");
        assert_eq!(&members[1].1.header.tag, b"ns3y");
    }

    /// An empty archive satisfies every all-members check vacuously, so it has to be
    /// refused up front rather than read as a drum bank holding no programs.
    #[test]
    fn an_empty_zip_is_refused() {
        let bytes = archive(&[]);
        assert!(from_stream(&mut Cursor::new(bytes)).is_err());
    }

    /// A directory entry holds no file and a manifest describes the archive, so an
    /// archive of nothing else holds no members — the same refusal as an empty one,
    /// rather than a bundle of none.
    #[test]
    fn a_zip_of_directories_and_a_manifest_is_refused() {
        let bytes = archive(&[("kits/", b""), ("meta.xml", b"<meta/>")]);
        let err = from_stream(&mut Cursor::new(bytes)).unwrap_err();
        assert!(
            err.to_string().contains("no members"),
            "refused for the wrong reason: {err}"
        );
    }

    /// A backup's directory entries are not members, so they do not stop a bank whose
    /// files are all one CBIN format being read as that bank.
    #[test]
    fn a_directory_entry_does_not_hide_a_drum_bank() {
        let program = member("nd2p");
        let bytes = archive(&[("kits/", b""), ("kits/One.nd2p", &program)]);
        let entity = from_stream(&mut Cursor::new(bytes)).unwrap();
        assert!(
            matches!(entity, Entity::Bundle(Bundle::Drum2Bank(_))),
            "a `kits/` entry left it classified as {}",
            entity.identity().kind,
        );
    }

    /// A ZIP holding anything that is not a CBIN file is not a bundle.
    #[test]
    fn a_zip_with_a_non_cbin_member_is_refused() {
        let a = member("ns3f");
        let bytes = archive(&[("One.ns3f", &a), ("readme.txt", b"hello")]);
        assert!(from_stream(&mut Cursor::new(bytes)).is_err());
    }

    #[test]
    fn a_zip_is_read_from_the_callers_current_position() {
        let member = member("ns3f");
        let bytes = archive(&[("Bank A/One.ns3f", &member)]);
        let prefix_len = 7;
        let mut prefixed = vec![0xa5; prefix_len];
        prefixed.extend(bytes);
        let mut reader = Cursor::new(prefixed);
        reader.set_position(prefix_len as u64);

        let entity = from_stream(&mut reader).unwrap();
        assert!(matches!(entity, Entity::Bundle(Bundle::Members(_))));
    }
}

/// Serialize an [`Entity`] back to the bytes of its file — the counterpart to
/// [`from_stream`].
///
/// For every format this crate reads, `to_bytes(from_stream(x)) == x` byte-for-byte,
/// whichever header generation `x` carries. That is the crate's central invariant —
/// decoded values are read-only views over a verbatim body, so a re-emit cannot
/// drift — and `nord verify` exists to check it against real specimens. Fixed-length
/// formats declare their body length on their [`cbin::Body`] impl, and the container
/// refuses to emit a wrong-sized file.
///
/// Bundles are unsupported: a bundle is a ZIP walk over other entities, not a
/// re-emittable structure.
pub fn to_bytes(entity: &Entity) -> Result<Vec<u8>, Error> {
    use std::io::Cursor;

    let mut out = Cursor::new(Vec::new());
    entity.write_to(&mut out)?;
    Ok(out.into_inner())
}

/// What an entity is: a human label and the format tag its file carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity {
    /// `"Electro 6 program"` — model then role, as the summary prints it.
    pub kind: &'static str,
    /// The CBIN tag, or the carrier name (`zip`, `syx`, `mid`, `cn3`).
    pub format: &'static str,
}

macro_rules! registry_bodies {
    ($($body:ty),* $(,)?) => {$(
        impl fields::Registry for Cbin<$body> {
            fn fields(&self) -> Vec<fields::Field> {
                self.body.fields()
            }
            fn field_values(&self) -> Vec<fields::FieldValue> {
                self.body.field_values()
            }
            fn set_field(&mut self, path: &str, value: &str) -> Result<(), fields::FieldError> {
                self.body.set_field(path, value)
            }
        }
    )*};
}

registry_bodies!(
    ne5::Program,
    ne5::Settings,
    ns2::Program,
    ns3::Program,
    ns3::SynthPreset,
    ns4::Program,
    ns4::organ_preset::OrganPreset,
    ns4::piano_preset::PianoPreset,
    ns4::synth::SynthPreset,
);

/// The registry-declaring entities, read through `&` or `&mut` as asked. One
/// list serving both directions. The live buffer is the program body under
/// another tag, so the two share an arm. `ne5::Song` declares no public
/// fields — its registry would be empty, so it is not one of these.
macro_rules! with_registry {
    ($entity:expr, $($reference:tt)*) => {
        match $entity {
            Entity::Program(Program::Electro5(f)) | Entity::Live(Live::Electro5(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            Entity::Program(Program::Stage2(f)) | Entity::Live(Live::Stage2(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            Entity::Program(Program::Stage3(f)) | Entity::Live(Live::Stage3(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            Entity::Program(Program::Stage4(f)) | Entity::Live(Live::Stage4(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            Entity::Settings(Settings::Electro5(f)) => Some(f as $($reference)* dyn fields::Registry),
            Entity::Synth(Synth::Stage3(f)) => Some(f as $($reference)* dyn fields::Registry),
            Entity::Synth(Synth::Stage4(f)) => Some(f as $($reference)* dyn fields::Registry),
            Entity::OrganPreset(OrganPreset::Stage4(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            Entity::PianoPreset(PianoPreset::Stage4(f)) => {
                Some(f as $($reference)* dyn fields::Registry)
            }
            _ => None,
        }
    };
}

impl Entity {
    /// The container of a stub-backed entity — every variant whose body is
    /// container-verified but undecoded. `None` for the decoded formats and the
    /// non-CBIN carriers.
    pub fn raw(&self) -> Option<&Cbin<RawBody>> {
        use {Live as L, OrganPreset as OP, Program as P, Settings as St, Synth as Sy};
        match self {
            Entity::Program(
                P::C2(f)
                | P::C2D(f)
                | P::Drum2(f)
                | P::Drum3(f)
                | P::Electro3(f)
                | P::Electro4(f)
                | P::Electro6(f)
                | P::Electro7(f)
                | P::Grand(f)
                | P::Lead4(f)
                | P::LeadA1(f)
                | P::Organ3(f)
                | P::Piano1(f)
                | P::Piano2(f)
                | P::Piano3(f)
                | P::Piano4(f)
                | P::Piano5(f)
                | P::StageClassic(f)
                | P::Wave(f)
                | P::Wave2(f),
            )
            | Entity::Live(
                L::Electro4(f)
                | L::Electro6(f)
                | L::Electro7(f)
                | L::Grand(f)
                | L::Piano1(f)
                | L::Piano2(f)
                | L::Piano3(f)
                | L::Piano4(f)
                | L::Piano5(f)
                | L::Wave2(f),
            )
            | Entity::Settings(
                St::C2(f)
                | St::C2D(f)
                | St::Electro4(f)
                | St::Electro6(f)
                | St::Electro7(f)
                | St::Grand(f)
                | St::Lead4(f)
                | St::LeadA1(f)
                | St::Organ3(f)
                | St::Piano1(f)
                | St::Piano2(f)
                | St::Piano3(f)
                | St::Piano4(f)
                | St::Piano5(f)
                | St::Stage2(f)
                | St::Stage3(f)
                | St::Stage4(f)
                | St::Wave(f)
                | St::Wave2(f),
            )
            | Entity::Song(Song::Stage3(f))
            | Entity::Synth(Sy::Stage2(f) | Sy::StageClassic(f))
            | Entity::Performance(Performance::Lead4(f) | Performance::LeadA1(f))
            | Entity::OrganPreset(OP::Electro3(f))
            | Entity::PianoLibrary(f)
            | Entity::PipeLibrary(f) => Some(f),
            _ => None,
        }
    }

    /// The generated field registry behind this entity, for reading.
    /// `None` for the container-verified stubs and the non-panel carriers.
    pub fn registry(&self) -> Option<&dyn fields::Registry> {
        with_registry!(self, &)
    }

    /// The registry again, for setting fields. The same bodies answer both:
    /// a body that lists its fields but refuses to set them cannot be
    /// declared here.
    pub fn registry_mut(&mut self) -> Option<&mut dyn fields::Registry> {
        with_registry!(self, &mut)
    }

    /// The entity's [`Identity`]: its human label and the tag its file carries.
    pub fn identity(&self) -> Identity {
        use {Live as L, Program as P, Settings as St};
        let id = |kind, format| Identity { kind, format };
        match self {
            Entity::Program(p) => match p {
                P::C2(_) => id("C2 program", nc2::program::FORMAT),
                P::C2D(_) => id("C2D program", nc2d::program::FORMAT),
                P::Drum2(_) => id("Drum 2 program", nd2::program::FORMAT),
                P::Drum3(_) => id("Drum 3P kit", nd3::kit::FORMAT),
                P::Electro3(_) => id("Electro 3 program", ne3::program::FORMAT),
                P::Electro4(_) => id("Electro 4 program", ne4::program::FORMAT),
                P::Electro5(_) => id("Electro 5 program", ne5::program::FORMAT),
                P::Electro6(_) => id("Electro 6 program", ne6::program::FORMAT),
                P::Electro7(_) => id("Electro 7 program", ne7::program::FORMAT),
                P::Grand(_) => id("Grand program", ng2::program::FORMAT),
                P::Lead4(_) => id("Lead 4 program", nl4::program::FORMAT),
                P::LeadA1(_) => id("Lead A1 program", nla1::program::FORMAT),
                P::Organ3(_) => id("no3 organ program", no3::program::FORMAT),
                P::Piano1(_) => id("Piano program", np::program::FORMAT),
                P::Piano2(_) => id("Piano 2 program", np2::program::FORMAT),
                P::Piano3(_) => id("Piano 3 program", np3::program::FORMAT),
                P::Piano4(_) => id("Piano 4 program", np4::program::FORMAT),
                P::Piano5(_) => id("Piano 5 program", np5::program::FORMAT),
                P::Stage2(_) => id("Stage 2 program", ns2::program::FORMAT),
                P::Stage3(_) => id("Stage 3 program", ns3::program::FORMAT),
                P::Stage4(_) => id("Stage 4 program", ns4::program::FORMAT),
                P::StageClassic(_) => id("Stage Classic program", nsclassic::program::FORMAT),
                P::Wave(_) => id("Wave program", nw::program::FORMAT),
                P::Wave2(_) => id("Wave 2 program", nw2::program::FORMAT),
            },
            Entity::Live(l) => match l {
                L::Electro4(_) => id("Electro 4 live slot", ne4::live::FORMAT),
                L::Electro5(_) => id("Electro 5 live slot", ne5::live::FORMAT),
                L::Electro6(_) => id("Electro 6 live slot", ne6::live::FORMAT),
                L::Electro7(_) => id("Electro 7 live slot", ne7::live::FORMAT),
                L::Grand(_) => id("Grand live slot", ng2::live::FORMAT),
                L::Piano1(_) => id("Piano live slot", np::live::FORMAT),
                L::Piano2(_) => id("Piano 2 live slot", np2::live::FORMAT),
                L::Piano3(_) => id("Piano 3 live slot", np3::live::FORMAT),
                L::Piano4(_) => id("Piano 4 live slot", np4::live::FORMAT),
                L::Piano5(_) => id("Piano 5 live slot", np5::live::FORMAT),
                L::Stage2(_) => id("Stage 2 live slot", ns2::live::FORMAT),
                L::Stage3(_) => id("Stage 3 live slot", ns3::live::FORMAT),
                L::Stage4(_) => id("Stage 4 live slot", ns4::live::FORMAT),
                L::Wave2(_) => id("Wave 2 live slot", nw2::live::FORMAT),
            },
            Entity::Settings(s) => match s {
                St::C2(_) => id("C2 settings", nc2::settings::FORMAT),
                St::C2D(_) => id("C2D settings", nc2d::settings::FORMAT),
                St::Electro4(_) => id("Electro 4 settings", ne4::settings::FORMAT),
                St::Electro5(_) => id("Electro 5 settings", ne5::settings::FORMAT),
                St::Electro6(_) => id("Electro 6 settings", ne6::settings::FORMAT),
                St::Electro7(_) => id("Electro 7 settings", ne7::settings::FORMAT),
                St::Grand(_) => id("Grand settings", ng2::settings::FORMAT),
                St::Lead4(_) => id("Lead 4 settings", nl4::settings::FORMAT),
                St::LeadA1(_) => id("Lead A1 settings", nla1::settings::FORMAT),
                St::Organ3(_) => id("no3 organ settings", no3::settings::FORMAT),
                St::Piano1(_) => id("Piano settings", np::settings::FORMAT),
                St::Piano2(_) => id("Piano 2 settings", np2::settings::FORMAT),
                St::Piano3(_) => id("Piano 3 settings", np3::settings::FORMAT),
                St::Piano4(_) => id("Piano 4 settings", np4::settings::FORMAT),
                St::Piano5(_) => id("Piano 5 settings", np5::settings::FORMAT),
                St::Stage2(_) => id("Stage 2 settings", ns2::settings::FORMAT),
                St::Stage3(_) => id("Stage 3 settings", ns3::settings::FORMAT),
                St::Stage4(_) => id("Stage 4 settings", ns4::settings::FORMAT),
                St::Wave(_) => id("Wave settings", nw::settings::FORMAT),
                St::Wave2(_) => id("Wave 2 settings", nw2::settings::FORMAT),
            },
            Entity::Song(Song::Electro5(_)) => id("Electro 5 song / set", ne5::song::FORMAT),
            Entity::Song(Song::Stage3(_)) => id("Stage 3 song", ns3::song::FORMAT),
            Entity::Synth(Synth::Stage2(_)) => id("Stage 2 synth patch", ns2::synth::FORMAT),
            Entity::Synth(Synth::Stage3(_)) => id("Stage 3 synth patch", ns3::synth::FORMAT),
            Entity::Synth(Synth::Stage4(_)) => id("Stage 4 synth preset", ns4::synth::FORMAT),
            Entity::Synth(Synth::StageClassic(_)) => {
                id("Stage Classic synth patch", nsclassic::synth::FORMAT)
            }
            Entity::Performance(Performance::Lead4(_)) => {
                id("Lead 4 performance", nl4::performance::FORMAT)
            }
            Entity::Performance(Performance::LeadA1(_)) => {
                id("Lead A1 performance", nla1::performance::FORMAT)
            }
            Entity::OrganPreset(OrganPreset::Electro3(_)) => {
                id("Electro 3 organ preset", ne3::organ_preset::FORMAT)
            }
            Entity::OrganPreset(OrganPreset::Stage4(_)) => {
                id("Stage 4 organ preset", ns4::organ_preset::FORMAT)
            }
            Entity::PianoPreset(PianoPreset::Stage4(_)) => {
                id("Stage 4 piano preset", ns4::piano_preset::FORMAT)
            }
            Entity::Piano(_) => id("piano library", npno::FORMAT),
            Entity::PianoLibrary(_) => id(
                "Stage Classic piano library",
                nsclassic::piano_library::FORMAT,
            ),
            Entity::PipeLibrary(_) => id("C2 pipe library", npip::pipe_library::FORMAT),
            Entity::Sample(Sample::V2(_)) => id("sample instrument", nsmp::FORMAT),
            Entity::Sample(Sample::V3(_)) => id("sample instrument (nsmp3/nsmp4)", nsmp::FORMAT),
            Entity::SampleProject(_) => id("Sample Editor project", nsmpproj::FORMAT),
            Entity::Sysex(_) => id("SysEx dump", "syx"),
            Entity::Midi(_) => id("MIDI file", "mid"),
            Entity::Cne3(_) => id("Electro 2 library", "cn3"),
            #[cfg(feature = "bundle")]
            Entity::Bundle(_) => id("bundle", "zip"),
        }
    }

    /// Re-encode to `w`, byte-exact for anything read and unedited.
    ///
    /// Bundles are the one exception: the archive layer does not re-encode, so a
    /// bundle refuses rather than writing something almost like its source.
    pub fn write_to(&self, w: &mut (impl std::io::Write + Seek)) -> Result<(), Error> {
        match self {
            Entity::Cne3(f) => f.write_to(w),
            Entity::Live(l) => match l {
                Live::Electro4(f)
                | Live::Electro6(f)
                | Live::Electro7(f)
                | Live::Grand(f)
                | Live::Piano1(f)
                | Live::Piano2(f)
                | Live::Piano3(f)
                | Live::Piano4(f)
                | Live::Piano5(f)
                | Live::Wave2(f) => f.write_to(w),
                Live::Electro5(f) => f.write_to(w),
                Live::Stage4(f) => f.write_to(w),
                Live::Stage2(f) => f.write_to(w),
                Live::Stage3(f) => f.write_to(w),
            },
            Entity::Midi(f) => f.write_to(w),
            Entity::OrganPreset(OrganPreset::Electro3(f))
            | Entity::PianoLibrary(f)
            | Entity::PipeLibrary(f) => f.write_to(w),
            Entity::OrganPreset(OrganPreset::Stage4(f)) => f.write_to(w),
            Entity::PianoPreset(PianoPreset::Stage4(f)) => f.write_to(w),
            Entity::Piano(f) => f.write_to(w),
            Entity::Performance(Performance::Lead4(f))
            | Entity::Performance(Performance::LeadA1(f)) => f.write_to(w),
            Entity::Program(p) => match p {
                Program::C2(f)
                | Program::C2D(f)
                | Program::Drum2(f)
                | Program::Drum3(f)
                | Program::Electro3(f)
                | Program::Electro4(f)
                | Program::Electro6(f)
                | Program::Electro7(f)
                | Program::Grand(f)
                | Program::Lead4(f)
                | Program::LeadA1(f)
                | Program::Organ3(f)
                | Program::Piano1(f)
                | Program::Piano2(f)
                | Program::Piano3(f)
                | Program::Piano4(f)
                | Program::Piano5(f)
                | Program::StageClassic(f)
                | Program::Wave(f)
                | Program::Wave2(f) => f.write_to(w),
                Program::Electro5(f) => f.write_to(w),
                Program::Stage2(f) => f.write_to(w),
                Program::Stage3(f) => f.write_to(w),
                Program::Stage4(f) => f.write_to(w),
            },
            Entity::Sample(Sample::V2(f)) => f.write_to(w),
            Entity::Sample(Sample::V3(f)) => f.write_to(w),
            Entity::SampleProject(f) => f.write_to(w),
            Entity::Settings(s) => match s {
                Settings::C2(f)
                | Settings::C2D(f)
                | Settings::Electro4(f)
                | Settings::Electro6(f)
                | Settings::Electro7(f)
                | Settings::Grand(f)
                | Settings::Lead4(f)
                | Settings::LeadA1(f)
                | Settings::Organ3(f)
                | Settings::Piano1(f)
                | Settings::Piano2(f)
                | Settings::Piano3(f)
                | Settings::Piano4(f)
                | Settings::Piano5(f)
                | Settings::Stage2(f)
                | Settings::Stage3(f)
                | Settings::Stage4(f)
                | Settings::Wave(f)
                | Settings::Wave2(f) => f.write_to(w),
                Settings::Electro5(f) => f.write_to(w),
            },
            Entity::Song(Song::Electro5(f)) => f.write_to(w),
            Entity::Song(Song::Stage3(f)) => f.write_to(w),
            Entity::Synth(Synth::Stage2(f)) | Entity::Synth(Synth::StageClassic(f)) => {
                f.write_to(w)
            }
            Entity::Synth(Synth::Stage3(f)) => f.write_to(w),
            Entity::Synth(Synth::Stage4(f)) => f.write_to(w),
            Entity::Sysex(f) => f.write_to(w),
            #[cfg(feature = "bundle")]
            Entity::Bundle(_) => Err(ParseError::AssertFail(
                "bundles are archives; re-encoding one is not supported".into(),
            )
            .into()),
        }
    }
}