Skip to main content

music21/noteworthy/
binary.rs

1//! NoteWorthy Composer's binary format, `.nwc`: music21's
2//! `noteworthy.binaryTranslate`, which reads a file's staves and objects and
3//! writes each out as a line of the text format for the text reader.
4
5use super::{error, from_lines};
6use crate::error::Result;
7use crate::stream::Stream;
8
9/// What a compressed file starts with; zlib's stream follows.
10const COMPRESSED: &[u8] = b"[NWZ]\x00";
11
12/// Reads a NoteWorthy Composer `.nwc` file's bytes into a score, as music21's
13/// `converter.parse` reads one: each staff and object written out as a line
14/// of the text format ([`nwc_lines`]) and those read by
15/// [`super::from_noteworthy`]'s reader.
16///
17/// The file must be uncompressed. A compressed one starts `[NWZ]` and a nul
18/// byte, and what follows is a zlib stream: inflate it first, as this crate
19/// unpacks nothing.
20///
21/// music21 calls this reader beta, and what it leaves out is left out here:
22/// lyrics, dynamics, flow marks and performance marks are read past and not
23/// written.
24///
25/// # Errors
26///
27/// A compressed file, a file that ends early, an object of a kind music21
28/// does not know, a note or rest in a file older than music21 reads, or
29/// anything the text reader refuses.
30pub fn from_nwc(bytes: &[u8]) -> Result<Stream> {
31    let lines = nwc_lines(bytes)?;
32    from_lines(lines.iter().map(String::as_str), false)
33}
34
35/// The lines of NoteWorthy text a `.nwc` file's bytes stand for, as
36/// music21's `dumpToNWCText` writes them: the title and author, then for
37/// each staff its name, its instrument and its objects.
38///
39/// # Errors
40///
41/// As [`from_nwc`], but for what only the text reader refuses.
42pub fn nwc_lines(bytes: &[u8]) -> Result<Vec<String>> {
43    if bytes.starts_with(COMPRESSED) {
44        return Err(error(
45            "a compressed .nwc file: inflate the zlib stream after its first six bytes first",
46        ));
47    }
48    let mut reader = NwcReader::new(bytes, 200);
49    let header = reader.header()?;
50    let mut staves = Vec::new();
51    for _ in 0..header.number_of_staves {
52        staves.push(reader.staff()?);
53    }
54    Ok(dump_lines(&header, &staves))
55}
56
57/// music21's `dumpToNWCText`: the title and author, then each staff's
58/// lines.
59#[must_use]
60pub fn dump_lines(header: &NwcHeader, staves: &[NwcStaff]) -> Vec<String> {
61    let mut info = String::new();
62    if !header.title.is_empty() {
63        info.push_str("|SongInfo|Title:");
64        info.push_str(&latin1(&header.title));
65    }
66    if !header.author.is_empty() {
67        info.push_str("|Author:");
68        info.push_str(&latin1(&header.author));
69    }
70    let mut lines = vec![info];
71    for staff in staves {
72        lines.extend(staff.dump());
73    }
74    lines
75}
76
77/// Bytes read as latin-1, as music21 decodes every string in the file.
78fn latin1(bytes: &[u8]) -> String {
79    bytes.iter().map(|byte| char::from(*byte)).collect()
80}
81
82/// An index into a table as Python takes one: a negative one counts from
83/// the end.
84fn python_index<T: Copy>(table: &[T], index: i32) -> Option<T> {
85    let length = i32::try_from(table.len()).ok()?;
86    let index = if index < 0 { index + length } else { index };
87    usize::try_from(index)
88        .ok()
89        .and_then(|index| table.get(index).copied())
90}
91
92/// music21's `constants.ClefNames`.
93pub const CLEF_NAMES: [&str; 5] = ["Treble", "Bass", "Alto", "Tenor", "Percussion"];
94
95/// music21's `constants.OctaveShiftNames`.
96pub const OCTAVE_SHIFT_NAMES: [Option<&str>; 3] = [None, Some("Octave Up"), Some("Octave Down")];
97
98/// music21's `constants.FlatMask`.
99pub const FLAT_MASK: [(u8, &str); 8] = [
100    (0x00, ""),
101    (0x02, "Bb"),
102    (0x12, "Bb,Eb"),
103    (0x13, "Bb,Eb,Ab"),
104    (0x1B, "Bb,Eb,Ab,Db"),
105    (0x5B, "Bb,Eb,Ab,Db,Gb"),
106    (0x5F, "Bb,Eb,Ab,Db,Gb,Cb"),
107    (0x7F, "Bb,Eb,Ab,Db,Gb,Cb,Fb"),
108];
109
110/// music21's `constants.SharpMask`.
111pub const SHARP_MASK: [(u8, &str); 8] = [
112    (0x00, ""),
113    (0x20, "F#"),
114    (0x24, "F#,C#"),
115    (0x64, "F#,C#,G#"),
116    (0x6C, "F#,C#,G#,D#"),
117    (0x6D, "F#,C#,G#,D#,A#"),
118    (0x7D, "F#,C#,G#,D#,A#,E#"),
119    (0x7F, "F#,C#,G#,D#,A#,E#,B#"),
120];
121
122/// music21's `constants.AlterationTexts`: `x` is a double sharp, `v` a
123/// double flat.
124pub const ALTERATION_TEXTS: [&str; 6] = ["#", "b", "n", "x", "v", ""];
125
126/// music21's `constants.BarStyles`.
127pub const BAR_STYLES: [&str; 8] = [
128    "Single",
129    "Double",
130    "SectionOpen",
131    "SectionClose",
132    "LocalRepeatOpen",
133    "LocalRepeatClose",
134    "MasterRepeatOpen",
135    "MasterRepeatClose",
136];
137
138/// music21's `constants.DurationValues`.
139pub const DURATION_VALUES: [&str; 7] = ["Whole", "Half", "4th", "8th", "16th", "32nd", "64th"];
140
141/// music21's `constants.MidiInstruments`, the General MIDI names by program.
142pub const MIDI_INSTRUMENTS: [&str; 128] = [
143    "Acoustic Grand Piano",
144    "Bright Acoustic Piano",
145    "Electric Grand Piano",
146    "Honky-tonk Piano",
147    "Electric Piano 1",
148    "Electric Piano 2",
149    "Harpsichord",
150    "Clavi",
151    "Celesta",
152    "Glockenspiel",
153    "Music Box",
154    "Vibraphone",
155    "Marimba",
156    "Xylophone",
157    "Tubular Bells",
158    "Dulcimer",
159    "Drawbar Organ",
160    "Percussive Organ",
161    "Rock Organ",
162    "Church Organ",
163    "Reed Organ",
164    "Accordion",
165    "Harmonica",
166    "Tango Accordion",
167    "Acoustic Guitar (nylon)",
168    "Acoustic Guitar (steel)",
169    "Electric Guitar (jazz)",
170    "Electric Guitar (clean)",
171    "Electric Guitar (muted)",
172    "Overdriven Guitar",
173    "Distortion Guitar",
174    "Guitar harmonics",
175    "Acoustic Bass",
176    "Electric Bass (finger)",
177    "Electric Bass (pick)",
178    "Fretless Bass",
179    "Slap Bass 1",
180    "Slap Bass 2",
181    "Synth Bass 1",
182    "Synth Bass 2",
183    "Violin",
184    "Viola",
185    "Cello",
186    "Contrabass",
187    "Tremolo Strings",
188    "Pizzicato Strings",
189    "Orchestral Harp",
190    "Timpani",
191    "String Ensemble 1",
192    "String Ensemble 2",
193    "SynthStrings 1",
194    "SynthStrings 2",
195    "Choir Aahs",
196    "Voice Oohs",
197    "Synth Voice",
198    "Orchestra Hit",
199    "Trumpet",
200    "Trombone",
201    "Tuba",
202    "Muted Trumpet",
203    "French Horn",
204    "Brass Section",
205    "SynthBrass 1",
206    "SynthBrass 2",
207    "Soprano Sax",
208    "Alto Sax",
209    "Tenor Sax",
210    "Baritone Sax",
211    "Oboe",
212    "English Horn",
213    "Bassoon",
214    "Clarinet",
215    "Piccolo",
216    "Flute",
217    "Recorder",
218    "Pan Flute",
219    "Blown Bottle",
220    "Shakuhachi",
221    "Whistle",
222    "Ocarina",
223    "Lead 1 (square)",
224    "Lead 2 (sawtooth)",
225    "Lead 3 (calliope)",
226    "Lead 4 (chiff)",
227    "Lead 5 (charang)",
228    "Lead 6 (voice)",
229    "Lead 7 (fifths)",
230    "Lead 8 (bass + lead)",
231    "Pad 1 (new age)",
232    "Pad 2 (warm)",
233    "Pad 3 (polysynth)",
234    "Pad 4 (choir)",
235    "Pad 5 (bowed)",
236    "Pad 6 (metallic)",
237    "Pad 7 (halo)",
238    "Pad 8 (sweep)",
239    "FX 1 (rain)",
240    "FX 2 (soundtrack)",
241    "FX 3 (crystal)",
242    "FX 4 (atmosphere)",
243    "FX 5 (brightness)",
244    "FX 6 (goblins)",
245    "FX 7 (echoes)",
246    "FX 8 (sci-fi)",
247    "Sitar",
248    "Banjo",
249    "Shamisen",
250    "Koto",
251    "Kalimba",
252    "Bag pipe",
253    "Fiddle",
254    "Shanai",
255    "Tinkle Bell",
256    "Agogo",
257    "Steel Drums",
258    "Woodblock",
259    "Taiko Drum",
260    "Melodic Tom",
261    "Synth Drum",
262    "Reverse Cymbal",
263    "Guitar Fret Noise",
264    "Breath Noise",
265    "Seashore",
266    "Bird Tweet",
267    "Telephone Ring",
268    "Helicopter",
269    "Applause",
270    "Gunshot",
271];
272
273/// A font the header names: music21's `FontDict`.
274#[derive(Clone, Debug, PartialEq, Eq)]
275pub struct NwcFont {
276    /// Its name, `Times New Roman` where the file gives none.
277    pub name: Vec<u8>,
278    /// Regular, bold, italic or both, as the file numbers them.
279    pub style: u8,
280    /// Its size in points, 12 where the file gives none.
281    pub size: u8,
282    /// Its character set.
283    pub charset: u8,
284}
285
286/// What a file's header says: music21's `NWCConverter.parseHeader`.
287#[derive(Clone, Debug, Default, PartialEq, Eq)]
288#[allow(missing_docs)]
289pub struct NwcHeader {
290    pub version: u32,
291    pub user: Vec<u8>,
292    pub title: Vec<u8>,
293    pub author: Vec<u8>,
294    pub lyricist: Vec<u8>,
295    pub copyright1: Vec<u8>,
296    pub copyright2: Vec<u8>,
297    pub comment: Vec<u8>,
298    pub extend_last_system: u8,
299    pub increase_note_spacing: u8,
300    pub measure_numbers: u8,
301    pub measure_start: i32,
302    pub margins: Vec<u8>,
303    pub group_visibility: Vec<u8>,
304    pub allow_layering: u8,
305    pub notation_typeface: Vec<u8>,
306    pub staff_height: i32,
307    pub fonts: Vec<NwcFont>,
308    pub title_page_info: u8,
309    pub staff_labels: u8,
310    pub page_number_start: i32,
311    pub number_of_staves: u8,
312}
313
314/// A staff and its objects: music21's `NWCStaff`.
315#[derive(Clone, Debug, Default, PartialEq, Eq)]
316#[allow(missing_docs)]
317pub struct NwcStaff {
318    pub name: Vec<u8>,
319    pub label: Vec<u8>,
320    pub instrument_name: Vec<u8>,
321    pub group: Vec<u8>,
322    pub lines: u8,
323    pub layer_with_next_staff: Option<i32>,
324    /// Semitones up, where the file says; music21 writes `None` otherwise.
325    pub transposition: Option<i32>,
326    pub part_volume: Option<i32>,
327    pub stereo_pan: Option<i32>,
328    pub color: u8,
329    pub align_syllable: Option<i32>,
330    pub number_of_lyrics: i32,
331    pub lyric_alignment: i32,
332    pub staff_offset: i32,
333    /// Each verse's syllables.
334    pub lyrics: Vec<Vec<Vec<u8>>>,
335    pub number_of_objects: i32,
336    pub objects: Vec<NwcObject>,
337}
338
339impl NwcStaff {
340    /// music21's `NWCStaff.dump`: the staff and its instrument as text
341    /// lines, then each object that writes one.
342    #[must_use]
343    pub fn dump(&self) -> Vec<String> {
344        let instrument = if self.instrument_name.is_empty() {
345            "Acoustic Grand Piano".to_string()
346        } else {
347            latin1(&self.instrument_name)
348        };
349        let label = if self.label.is_empty() {
350            instrument.clone()
351        } else {
352            latin1(&self.label)
353        };
354        let mut lines = vec![format!("|AddStaff|Name:{label}")];
355        let mut staff_instrument = format!("|StaffInstrument|Name:{instrument}");
356        if let Some(patch) = MIDI_INSTRUMENTS.iter().position(|name| *name == instrument) {
357            staff_instrument.push_str(&format!("|Patch:{patch}"));
358        }
359        staff_instrument.push_str(&format!(
360            "|Trans:{}",
361            self.transposition
362                .map_or("None".to_string(), |semitones| semitones.to_string())
363        ));
364        lines.push(staff_instrument);
365        lines.extend(
366            self.objects
367                .iter()
368                .map(NwcObject::line)
369                .filter(|line| !line.is_empty()),
370        );
371        lines
372    }
373}
374
375/// One object of a staff: music21's `NWCObject`.
376#[derive(Clone, Debug, PartialEq, Eq)]
377pub struct NwcObject {
378    /// Whether and where it is shown; nought before version 1.70.
379    pub visible: u8,
380    /// What it is.
381    pub body: Object,
382}
383
384impl NwcObject {
385    /// music21's `type`: the name of the method that read it.
386    #[must_use]
387    pub fn type_name(&self) -> &'static str {
388        match &self.body {
389            Object::Silent(name) => name,
390            Object::Clef { .. } => "Clef",
391            Object::Key(_) => "KeySig",
392            Object::Bar(_) => "Barline",
393            Object::Ending(_) => "Ending",
394            Object::TimeSig(..) => "TimeSig",
395            Object::Tempo(_) => "Tempo",
396            Object::Note(_) => "Note",
397            Object::Rest(_) => "Rest",
398            Object::Chord { .. } => "NoteChordMember",
399            Object::RestChord { .. } => "RestChordMember",
400            Object::Text(..) => "Text",
401        }
402    }
403
404    /// music21's `dumpMethod`: the text line, or nothing.
405    #[must_use]
406    pub fn line(&self) -> String {
407        self.body.line()
408    }
409}
410
411/// What an object is, as much of it as is written out.
412#[derive(Clone, Debug, PartialEq, Eq)]
413pub enum Object {
414    /// Read past and written as nothing, with music21's `type` for it.
415    Silent(&'static str),
416    /// A clef by name, with its octave shift.
417    Clef {
418        /// Its name in `CLEF_NAMES`.
419        name: Option<&'static str>,
420        /// Its octave shift in `OCTAVE_SHIFT_NAMES`.
421        shift: Option<&'static str>,
422    },
423    /// A key signature's `Signature` text.
424    Key(&'static str),
425    /// A barline by its style's number in `BAR_STYLES`.
426    Bar(u8),
427    /// An ending by its number.
428    Ending(u8),
429    /// A meter's numerator and denominator.
430    TimeSig(i32, i64),
431    /// A tempo in beats a minute.
432    Tempo(i32),
433    /// A note.
434    Note(Member),
435    /// A rest's `Dur` text.
436    Rest(String),
437    /// A chord's notes, and the stem length its bytes give.
438    Chord {
439        /// Its notes.
440        members: Vec<Member>,
441        /// Its stem length.
442        stem_length: u8,
443    },
444    /// A rest's `Dur` text and the notes sounding with it.
445    RestChord {
446        /// The notes.
447        members: Vec<Member>,
448        /// The rest's length.
449        rest: String,
450    },
451    /// Words and their staff position.
452    Text(Vec<u8>, i32),
453}
454
455/// A note as a chord or a staff holds it.
456#[derive(Clone, Debug, PartialEq, Eq)]
457pub struct Member {
458    /// Its `Dur` text: music21's `durationStr`.
459    pub duration: String,
460    /// Its staff position: music21's `pos`.
461    pub position: i32,
462    /// The alteration in force there: music21's `alterationStr`.
463    pub alteration: String,
464    /// `^` where it is tied on: music21's `tieInfo`.
465    pub tie: &'static str,
466    /// Its stem length.
467    pub stem_length: u8,
468}
469
470impl Member {
471    /// Its `Pos` text: alteration, position and tie.
472    #[must_use]
473    pub fn pos_text(&self) -> String {
474        format!("{}{}{}", self.alteration, self.position, self.tie)
475    }
476}
477
478impl Object {
479    /// music21's `dumpMethod`: the text line, or nothing.
480    fn line(&self) -> String {
481        match self {
482            Self::Silent(_) => String::new(),
483            Self::Clef { name, shift } => {
484                let mut line = "|Clef|".to_string();
485                if let Some(name) = name {
486                    line.push_str(&format!("Type:{name}|"));
487                }
488                if let Some(shift) = shift {
489                    line.push_str(&format!("OctaveShift:{shift}|"));
490                }
491                line
492            }
493            Self::Key(signature) => format!("|Key|Signature:{signature}"),
494            Self::Bar(style) => {
495                let mut line = "|Bar|".to_string();
496                if *style > 0
497                    && let Some(name) = BAR_STYLES.get(usize::from(*style))
498                {
499                    line.push_str(&format!("|Style:{name}"));
500                }
501                line
502            }
503            Self::Ending(style) => format!("|Ending|Endings:{style}"),
504            Self::TimeSig(numerator, denominator) => {
505                format!("|TimeSig|Signature:{numerator}/{denominator}")
506            }
507            Self::Tempo(value) => format!("|Tempo|Tempo:{value}"),
508            Self::Note(member) => {
509                format!("|Note|Dur:{}|Pos:{}|", member.duration, member.pos_text())
510            }
511            Self::Rest(duration) => format!("|Rest|Dur:{duration}|"),
512            Self::Chord { members, .. } => {
513                let mut line = "|Chord".to_string();
514                for (duration, positions) in by_duration(members) {
515                    line.push_str(&format!("|Dur:{duration}|Pos:{positions}"));
516                }
517                line
518            }
519            Self::RestChord { members, rest } => match members.first() {
520                None => format!("|Rest|Dur:{rest}"),
521                Some(first) => {
522                    let positions: Vec<String> = members.iter().map(Member::pos_text).collect();
523                    format!(
524                        "|RestChord|Dur:{rest}|Dur2:{}|Pos2:{}",
525                        first.duration,
526                        positions.join(",")
527                    )
528                }
529            },
530            Self::Text(text, position) => {
531                format!("|Text|Text:{}|Pos:{position}", latin1(text))
532            }
533        }
534    }
535}
536
537/// The stem length music21 gives a note or chord whose bytes name none.
538const DEFAULT_STEM: u8 = 7;
539
540/// The bit of a note's or chord's last byte that says a stem length follows.
541const STEM_FOLLOWS: u8 = 0x40;
542
543/// The music21 `type` of each object kind, by the number the file gives.
544const OBJECT_TYPES: [&str; 19] = [
545    "Clef",
546    "KeySig",
547    "Barline",
548    "Ending",
549    "Instrument",
550    "TimeSig",
551    "Tempo",
552    "Dynamic",
553    "Note",
554    "Rest",
555    "NoteChordMember",
556    "Pedal",
557    "FlowDir",
558    "MPC",
559    "TempoVariation",
560    "DynamicVariation",
561    "Performance",
562    "Text",
563    "RestChordMember",
564];
565
566/// music21's `NWCConverter` as a reader: the file, where it has got to in
567/// it, its version, and the alteration last written on each staff
568/// position, by the position modulo seven, until a barline.
569#[derive(Clone, Debug)]
570pub struct NwcReader<'a> {
571    data: &'a [u8],
572    /// Where the next read starts: music21's `parsePosition`.
573    pub at: usize,
574    /// The file's version, as music21 numbers it: 175 for 1.75.
575    pub version: u32,
576    /// music21's `currentAlterations`.
577    pub alterations: Vec<(i32, String)>,
578}
579
580impl<'a> NwcReader<'a> {
581    /// A reader over a file's (inflated) bytes, at its start, taken to be
582    /// of `version` until its header says.
583    #[must_use]
584    pub fn new(data: &'a [u8], version: u32) -> Self {
585        Self {
586            data,
587            at: 0,
588            version,
589            alterations: Vec::new(),
590        }
591    }
592
593    fn ended() -> crate::error::Error {
594        error("the file ends before its last object")
595    }
596
597    /// A little-endian signed short: `readLEShort`.
598    fn short(&mut self) -> Result<i32> {
599        let bytes = self
600            .data
601            .get(self.at..self.at + 2)
602            .ok_or_else(Self::ended)?;
603        self.at += 2;
604        Ok(i32::from(i16::from_le_bytes([bytes[0], bytes[1]])))
605    }
606
607    /// `byteToInt`.
608    fn byte(&mut self) -> Result<u8> {
609        let byte = *self.data.get(self.at).ok_or_else(Self::ended)?;
610        self.at += 1;
611        Ok(byte)
612    }
613
614    /// `byteToSignedInt`.
615    fn signed(&mut self) -> Result<i32> {
616        Ok(i32::from(self.byte()? as i8))
617    }
618
619    /// `readBytes`: as many of the next `count` bytes as there are.
620    fn take(&mut self, count: usize) -> Vec<u8> {
621        let start = self.at.min(self.data.len());
622        let end = (self.at + count).min(self.data.len());
623        self.at += count;
624        self.data[start..end].to_vec()
625    }
626
627    fn skip(&mut self, count: usize) {
628        self.at += count;
629    }
630
631    /// `readToNUL`: the bytes up to the next nul, which is passed. With no
632    /// nul left, the rest -- and music21 then starts again from the file's
633    /// first byte.
634    fn until_nul(&mut self) -> Vec<u8> {
635        let start = self.at.min(self.data.len());
636        match self.data[start..].iter().position(|byte| *byte == 0) {
637            Some(length) => {
638                self.at = start + length + 1;
639                self.data[start..start + length].to_vec()
640            }
641            None => {
642                self.at = 0;
643                self.data[start..].to_vec()
644            }
645        }
646    }
647
648    /// `advanceToNotNUL`.
649    fn past_nuls(&mut self) {
650        while self.data.get(self.at) == Some(&0) {
651            self.at += 1;
652        }
653    }
654
655    /// music21's `parseHeader`, with `fileVersion` read where music21
656    /// reads it. The version read is kept.
657    ///
658    /// # Errors
659    ///
660    /// A file that ends inside its header.
661    pub fn header(&mut self) -> Result<NwcHeader> {
662        self.at = 45;
663        self.version = match self.short()? {
664            0x0114 => 120,
665            0x011E => 130,
666            0x0132 => 150,
667            0x0137 => 155,
668            0x0146 => 170,
669            0x014B => 175,
670            0x0200 => 200,
671            0x0201 => 201,
672            // Most likely a newer version.
673            _ => 201,
674        };
675        let mut header = NwcHeader {
676            version: self.version,
677            ..NwcHeader::default()
678        };
679        self.skip(4);
680        header.user = self.until_nul();
681        let _unknown = self.until_nul();
682        self.skip(10);
683        header.title = self.until_nul();
684        header.author = self.until_nul();
685        if self.version >= 200 {
686            header.lyricist = self.until_nul();
687        }
688        header.copyright1 = self.until_nul();
689        header.copyright2 = self.until_nul();
690        header.comment = self.until_nul();
691        header.extend_last_system = self.byte()?;
692        header.increase_note_spacing = self.byte()?;
693        self.take(5);
694        header.measure_numbers = self.byte()?;
695        self.take(1);
696        header.measure_start = self.short()?;
697        header.margins = if self.version >= 130 {
698            self.until_nul()
699        } else {
700            b"0.0 0.0 0.0 0.0".to_vec()
701        };
702        let _unused = self.byte()?;
703        self.take(2);
704        header.allow_layering = 1;
705        if self.version >= 130 {
706            header.group_visibility = self.take(32);
707            header.allow_layering = self.byte()?;
708        }
709        header.notation_typeface = if self.version >= 200 {
710            self.until_nul()
711        } else {
712            b"Maestro".to_vec()
713        };
714        header.staff_height = self.short()?;
715        let fonts = if self.version > 170 {
716            12
717        } else if self.version > 130 {
718            10
719        } else {
720            0
721        };
722        self.past_nuls();
723        self.skip(2);
724        for _ in 0..fonts {
725            let mut font = NwcFont {
726                name: self.until_nul(),
727                style: self.byte()?,
728                size: self.byte()?,
729                charset: 0,
730            };
731            let _unused = self.byte()?;
732            font.charset = self.byte()?;
733            if font.name.is_empty() {
734                font.name = b"Times New Roman".to_vec();
735            }
736            if font.size == 0 {
737                font.size = 12;
738            }
739            header.fonts.push(font);
740        }
741        header.title_page_info = self.byte()?;
742        header.staff_labels = self.byte()?;
743        header.page_number_start = self.short()?;
744        if self.version >= 200 {
745            self.skip(1);
746        }
747        header.number_of_staves = self.byte()?;
748        self.skip(1);
749        Ok(header)
750    }
751
752    /// music21's `NWCStaff.parse`: a staff's header, its verses and its
753    /// objects.
754    ///
755    /// # Errors
756    ///
757    /// A file that ends inside the staff, or an object music21 cannot read.
758    pub fn staff(&mut self) -> Result<NwcStaff> {
759        let mut staff = self.staff_header()?;
760        staff.lyrics = self.staff_lyrics(staff.number_of_lyrics)?;
761        (staff.number_of_objects, staff.objects) = self.staff_objects()?;
762        Ok(staff)
763    }
764
765    /// `NWCStaff.parseObjects`: how many objects the staff says it has,
766    /// and the objects.
767    ///
768    /// # Errors
769    ///
770    /// As [`Self::staff`].
771    pub fn staff_objects(&mut self) -> Result<(i32, Vec<NwcObject>)> {
772        let mut count = self.short()?;
773        if self.version > 150 {
774            count -= 2;
775        }
776        let mut objects = Vec::new();
777        for _ in 0..count.max(0) {
778            objects.push(self.object()?);
779        }
780        Ok((count, objects))
781    }
782
783    /// `NWCStaff.parseHeader`: a staff's names, settings and how many
784    /// verses it has.
785    ///
786    /// # Errors
787    ///
788    /// As [`Self::staff`].
789    pub fn staff_header(&mut self) -> Result<NwcStaff> {
790        let mut staff = NwcStaff {
791            name: self.until_nul(),
792            ..NwcStaff::default()
793        };
794        if self.version >= 200 {
795            staff.label = self.until_nul();
796            staff.instrument_name = self.until_nul();
797        }
798        staff.group = self.until_nul();
799        if self.version >= 200 {
800            self.skip(27);
801            staff.lines = self.byte()?;
802            staff.layer_with_next_staff = Some(self.short()?);
803            staff.transposition = Some(self.short()?);
804            staff.part_volume = Some(self.short()?);
805            staff.stereo_pan = Some(self.short()?);
806            staff.color = self.byte()?;
807            staff.align_syllable = Some(self.short()?);
808            staff.number_of_lyrics = self.short()?;
809        } else if self.version == 175 {
810            self.skip(11);
811            let patch = usize::from(self.byte()?);
812            let index = if patch > 0 && patch < MIDI_INSTRUMENTS.len() {
813                patch - 1
814            } else {
815                0
816            };
817            staff.instrument_name = MIDI_INSTRUMENTS[index].bytes().collect();
818            self.skip(10);
819            staff.transposition = Some(self.signed()?);
820            self.skip(6);
821            staff.align_syllable = Some(self.short()?);
822            staff.number_of_lyrics = self.short()?;
823        }
824        if staff.number_of_lyrics > 0 {
825            staff.lyric_alignment = self.short()?;
826            staff.staff_offset = self.short()?;
827        }
828        Ok(staff)
829    }
830
831    /// `NWCStaff.parseLyrics`: each verse's syllables.
832    ///
833    /// # Errors
834    ///
835    /// As [`Self::staff`].
836    pub fn staff_lyrics(&mut self, verses: i32) -> Result<Vec<Vec<Vec<u8>>>> {
837        let mut lyrics = Vec::new();
838        for _ in 0..verses {
839            let size = self.short().unwrap_or(0);
840            if size <= 0 {
841                continue;
842            }
843            let _length = self.short()?;
844            let start = self.at;
845            let _junk = self.short()?;
846            let mut syllables = Vec::new();
847            for _ in 0..1000 {
848                let syllable = self.until_nul();
849                if syllable.is_empty() {
850                    break;
851                }
852                syllables.push(syllable);
853            }
854            self.at = start.saturating_add_signed(size as isize);
855            lyrics.push(syllables);
856        }
857        if verses > 0 {
858            let _junk = self.short()?;
859        }
860        let _junk = self.short()?;
861        Ok(lyrics)
862    }
863
864    /// music21's `NWCObject.parse`: an object of the type its first short
865    /// names.
866    ///
867    /// # Errors
868    ///
869    /// An object of a kind music21 does not know, a file that ends inside
870    /// it, or a note or rest in a file older than music21 reads.
871    pub fn object(&mut self) -> Result<NwcObject> {
872        let kind = self.short()?;
873        let Some(name) = usize::try_from(kind)
874            .ok()
875            .and_then(|kind| OBJECT_TYPES.get(kind))
876        else {
877            return Err(error(format!(
878                "Cannot translate objectType: {kind}; max is {}",
879                OBJECT_TYPES.len()
880            )));
881        };
882        let visible = if self.version >= 170 { self.byte()? } else { 0 };
883        let body = match kind {
884            0 => self.clef()?,
885            1 => self.key()?,
886            2 => {
887                let style = self.byte()?;
888                let _repeats = self.byte()?;
889                self.alterations.clear();
890                Object::Bar(style)
891            }
892            3 => {
893                let style = self.byte()?;
894                self.skip(1);
895                Object::Ending(style)
896            }
897            4 => {
898                self.skip(8);
899                Object::Silent(name)
900            }
901            5 => {
902                let numerator = self.short()?;
903                let bits = self.short()?;
904                let _style = self.short()?;
905                let denominator = u32::try_from(bits)
906                    .ok()
907                    .and_then(|bits| 1_i64.checked_shl(bits))
908                    .ok_or_else(|| error(format!("a meter of 2 to the power {bits}")))?;
909                Object::TimeSig(numerator, denominator)
910            }
911            6 => {
912                let _position = self.byte()?;
913                let _placement = self.byte()?;
914                let value = self.short()?;
915                let _base = self.byte()?;
916                if self.version < 170 {
917                    let _junk = self.short()?;
918                }
919                let _text = self.until_nul();
920                Object::Tempo(value)
921            }
922            7 => {
923                if self.version >= 170 {
924                    self.take(3);
925                    let _velocity = self.short()?;
926                    let _volume = self.short()?;
927                }
928                Object::Silent(name)
929            }
930            8 => Object::Note(self.note()?),
931            9 => {
932                if self.version <= 150 {
933                    return Err(error("a rest in a file older than version 1.70"));
934                }
935                let duration = self.byte()?;
936                let data = self.take(5);
937                let _offset = self.short()?;
938                Object::Rest(duration_text(duration, &data, None)?)
939            }
940            10 => {
941                let (members, _, stem_length) = self.chord()?;
942                Object::Chord {
943                    members,
944                    stem_length,
945                }
946            }
947            11 => {
948                if self.version >= 170 {
949                    self.take(3);
950                }
951                Object::Silent(name)
952            }
953            12 => {
954                if self.version >= 170 {
955                    self.take(2);
956                }
957                let _style = self.short()?;
958                Object::Silent(name)
959            }
960            13 => {
961                self.take(2);
962                if self.version == 175 || self.version <= 155 {
963                    self.take(32);
964                } else {
965                    self.take(31);
966                }
967                Object::Silent(name)
968            }
969            14 => {
970                self.take(4);
971                Object::Silent(name)
972            }
973            15 | 16 => {
974                let _position = self.byte()?;
975                if self.version >= 170 {
976                    let _placement = self.byte()?;
977                }
978                let _style = self.byte()?;
979                Object::Silent(name)
980            }
981            17 => {
982                let position = self.signed()?;
983                let _data = self.byte()?;
984                let _font = self.byte()?;
985                Object::Text(self.until_nul(), position)
986            }
987            _ => self.rest_chord()?,
988        };
989        Ok(NwcObject { visible, body })
990    }
991
992    /// `clef`: its type and octave shift, named where music21 has a name.
993    fn clef(&mut self) -> Result<Object> {
994        let clef = self.short()?;
995        let shift = self.short()?;
996        let clef_count = i32::try_from(CLEF_NAMES.len()).unwrap_or(0);
997        let shift_count = i32::try_from(OCTAVE_SHIFT_NAMES.len()).unwrap_or(0);
998        let name = if clef < clef_count {
999            Some(
1000                python_index(&CLEF_NAMES, clef)
1001                    .ok_or_else(|| error(format!("no clef numbered {clef}")))?,
1002            )
1003        } else {
1004            None
1005        };
1006        let shift = if shift < shift_count {
1007            python_index(&OCTAVE_SHIFT_NAMES, shift)
1008                .ok_or_else(|| error(format!("no octave shift numbered {shift}")))?
1009        } else {
1010            None
1011        };
1012        Ok(Object::Clef { name, shift })
1013    }
1014
1015    /// `keySig`: the flats written, else the sharps.
1016    fn key(&mut self) -> Result<Object> {
1017        let flats = self.byte()?;
1018        self.skip(1);
1019        let sharps = self.byte()?;
1020        self.skip(7);
1021        let mask = |table: &[(u8, &'static str)], key: u8| {
1022            table
1023                .iter()
1024                .find(|(known, _)| *known == key)
1025                .map(|(_, text)| *text)
1026        };
1027        let signature = if flats > 0
1028            && let Some(text) = mask(&FLAT_MASK, flats)
1029        {
1030            text
1031        } else if sharps > 0
1032            && let Some(text) = mask(&SHARP_MASK, sharps)
1033        {
1034            text
1035        } else {
1036            ""
1037        };
1038        Ok(Object::Key(signature))
1039    }
1040
1041    /// `restChordMember`: a rest's bytes and the notes sounding with it.
1042    /// Only a file of version 1.75 writes one as it writes a chord; the
1043    /// others give the rest's length, its five bytes and its offset, then
1044    /// how many notes follow.
1045    fn rest_chord(&mut self) -> Result<Object> {
1046        let (members, data) = if 170 < self.version && self.version < 200 {
1047            let (members, data, _) = self.chord()?;
1048            (members, data)
1049        } else {
1050            let data = self.take(8);
1051            let notes = usize::try_from(self.short()?).unwrap_or(0);
1052            (self.members(notes)?, data)
1053        };
1054        let duration = *data.first().ok_or_else(Self::ended)?;
1055        let rest_data = data.get(1..6).ok_or_else(Self::ended)?;
1056        Ok(Object::RestChord {
1057            members,
1058            rest: duration_text(duration, rest_data, None)?,
1059        })
1060    }
1061
1062    /// `note`: a note's length, its position on the staff with the
1063    /// alteration in force there, whether it is tied on, and its stem.
1064    fn note(&mut self) -> Result<Member> {
1065        if self.version < 170 {
1066            return Err(error("a note in a file older than version 1.70"));
1067        }
1068        let duration = self.byte()?;
1069        let data = self.take(3);
1070        let attributes = self.take(2);
1071        let position = -self.signed()?;
1072        let second = self.byte()?;
1073        if self.version <= 170 {
1074            self.take(2);
1075        }
1076        let stem_length = if self.version >= 200 && second & STEM_FOLLOWS != 0 {
1077            self.byte()?
1078        } else {
1079            DEFAULT_STEM
1080        };
1081        let duration = duration_text(duration, &data, Some(&attributes))?;
1082        let mut alteration = ALTERATION_TEXTS
1083            .get(usize::from(second & 0x07))
1084            .copied()
1085            .unwrap_or("")
1086            .to_string();
1087        let place = position.rem_euclid(7);
1088        if alteration.is_empty() {
1089            alteration = self
1090                .alterations
1091                .iter()
1092                .find(|(known, _)| *known == place)
1093                .map(|(_, text)| text.clone())
1094                .unwrap_or_default();
1095        }
1096        self.alterations.retain(|(known, _)| *known != place);
1097        self.alterations.push((place, alteration.clone()));
1098        let tie = if attributes.first().is_some_and(|first| first & 0x10 != 0) {
1099            "^"
1100        } else {
1101            ""
1102        };
1103        Ok(Member {
1104            duration,
1105            position,
1106            alteration,
1107            tie,
1108            stem_length,
1109        })
1110    }
1111
1112    /// `noteChordMember`: the chord's notes, its own bytes and its stem
1113    /// length.
1114    fn chord(&mut self) -> Result<(Vec<Member>, Vec<u8>, u8)> {
1115        let mut notes = 0;
1116        let data = if self.version <= 170 {
1117            let data = self.take(12);
1118            notes = usize::try_from(self.short()?).unwrap_or(0);
1119            data
1120        } else if self.version == 175 {
1121            let data = self.take(10);
1122            notes = usize::from(*data.get(8).ok_or_else(Self::ended)?);
1123            data
1124        } else {
1125            self.take(8)
1126        };
1127        let mut stem_length = DEFAULT_STEM;
1128        if self.version >= 200 {
1129            if data.get(7).ok_or_else(Self::ended)? & STEM_FOLLOWS != 0 {
1130                stem_length = self.byte()?;
1131            }
1132            notes = usize::try_from(self.short()?).unwrap_or(0);
1133        }
1134        Ok((self.members(notes)?, data, stem_length))
1135    }
1136
1137    /// `_readChordNotes`: the notes of a chord.
1138    fn members(&mut self, notes: usize) -> Result<Vec<Member>> {
1139        let mut members = Vec::new();
1140        for _ in 0..notes {
1141            match self.object()?.body {
1142                Object::Note(member) => members.push(member),
1143                // A rest is written at position nought, as music21's
1144                // object starts out.
1145                Object::Rest(duration) => members.push(Member {
1146                    duration,
1147                    position: 0,
1148                    alteration: String::new(),
1149                    tie: "",
1150                    stem_length: 0,
1151                }),
1152                _ => return Err(error("a chord holding something other than a note")),
1153            }
1154        }
1155        Ok(members)
1156    }
1157}
1158
1159/// A chord's notes grouped by length, in the order each length first
1160/// appears, with their positions joined, as music21's chord `dump` writes
1161/// them.
1162fn by_duration(members: &[Member]) -> Vec<(&str, String)> {
1163    let mut groups: Vec<(&str, Vec<String>)> = Vec::new();
1164    for member in members {
1165        match groups
1166            .iter_mut()
1167            .find(|(duration, _)| *duration == member.duration)
1168        {
1169            Some((_, positions)) => positions.push(member.pos_text()),
1170            None => groups.push((&member.duration, vec![member.pos_text()])),
1171        }
1172    }
1173    groups
1174        .into_iter()
1175        .map(|(duration, positions)| (duration, positions.join(",")))
1176        .collect()
1177}
1178
1179/// `setDurationForObject`: a note's or rest's `Dur` text, from its length
1180/// and the bytes saying its dots, whether it is a grace note (a note's
1181/// `attributes`) and whether it is a triplet.
1182fn duration_text(duration: u8, data: &[u8], attributes: Option<&[u8]>) -> Result<String> {
1183    let mut text = DURATION_VALUES
1184        .get(usize::from(duration))
1185        .ok_or_else(|| error(format!("no note length numbered {duration}")))?
1186        .to_string();
1187    let (dots, grace) = match attributes {
1188        Some(attributes) => (
1189            *attributes.first().ok_or_else(NwcReader::ended)?,
1190            attributes.get(1).ok_or_else(NwcReader::ended)? & 0x20,
1191        ),
1192        None => (*data.get(3).ok_or_else(NwcReader::ended)?, 0),
1193    };
1194    let triplet = data.get(1).ok_or_else(NwcReader::ended)? & 0x0c;
1195    if dots & 0x01 != 0 {
1196        text.push_str(",DblDotted");
1197    } else if dots & 0x04 != 0 {
1198        text.push_str(",Dotted");
1199    }
1200    if grace != 0 {
1201        text.push_str(",Grace");
1202    }
1203    if triplet != 0 {
1204        text.push_str(",Triplet");
1205    }
1206    Ok(text)
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211    use super::*;
1212
1213    #[test]
1214    fn a_compressed_file_is_left_to_the_caller_to_inflate() {
1215        let error = nwc_lines(b"[NWZ]\x00\x78\x9c").unwrap_err();
1216        assert!(error.to_string().contains("inflate"), "{error}");
1217    }
1218
1219    #[test]
1220    fn a_table_is_indexed_as_python_indexes_one() {
1221        assert_eq!(python_index(&CLEF_NAMES, 1), Some("Bass"));
1222        assert_eq!(python_index(&CLEF_NAMES, -1), Some("Percussion"));
1223        assert_eq!(python_index(&CLEF_NAMES, 5), None);
1224        assert_eq!(python_index(&CLEF_NAMES, -6), None);
1225    }
1226
1227    fn read(data: &[u8]) -> String {
1228        NwcReader::new(data, 201).object().unwrap().line()
1229    }
1230
1231    #[test]
1232    fn a_tenor_and_a_percussion_clef_are_named() {
1233        // An object of kind 0, shown, a clef type and no octave shift.
1234        assert_eq!(read(&[0, 0, 0, 3, 0, 0, 0]), "|Clef|Type:Tenor|");
1235        assert_eq!(read(&[0, 0, 0, 4, 0, 0, 0]), "|Clef|Type:Percussion|");
1236    }
1237
1238    #[test]
1239    fn a_version_two_chord_reads_its_notes() {
1240        // A chord of quarters and its count, then two notes on positions
1241        // nought and minus two.
1242        let mut chord = vec![10, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0];
1243        for position in [0u8, (-2i8) as u8] {
1244            chord.extend([8, 0, 0, 2, 0, 0, 0, 0, 0, position, 5]);
1245        }
1246        assert_eq!(read(&chord), "|Chord|Dur:4th|Pos:0,2");
1247    }
1248
1249    #[test]
1250    fn a_chord_groups_its_notes_by_length() {
1251        let member = |duration: &str, position: i32, alteration: &str, tie| Member {
1252            duration: duration.to_string(),
1253            position,
1254            alteration: alteration.to_string(),
1255            tie,
1256            stem_length: DEFAULT_STEM,
1257        };
1258        let chord = Object::Chord {
1259            members: vec![
1260                member("4th", 1, "", ""),
1261                member("Half", 3, "", ""),
1262                member("4th", 5, "#", "^"),
1263            ],
1264            stem_length: DEFAULT_STEM,
1265        };
1266        assert_eq!(chord.line(), "|Chord|Dur:4th|Pos:1,#5^|Dur:Half|Pos:3");
1267    }
1268
1269    #[test]
1270    fn a_version_two_rest_chord_gives_its_rest_and_then_its_notes() {
1271        // A half rest, its five bytes, an offset of minus two and a count,
1272        // then a quarter on position nought.
1273        let mut chord = vec![18, 0, 0, 1, 0, 0, 0, 0, 0, 0xfe, 0xff, 1, 0];
1274        chord.extend([8, 0, 0, 2, 0, 0, 0, 0, 0, 0, 5]);
1275        assert_eq!(read(&chord), "|RestChord|Dur:Half|Dur2:4th|Pos2:0");
1276        // With no notes it is a rest, dotted where its fourth byte says so.
1277        assert_eq!(
1278            read(&[18, 0, 0, 1, 0, 0, 0, 0x04, 0, 0, 0, 0, 0]),
1279            "|Rest|Dur:Half,Dotted"
1280        );
1281    }
1282
1283    #[test]
1284    fn a_version_two_chord_may_give_its_stem_length() {
1285        // The last of the chord's eight bytes flags a stem length, which
1286        // comes before the count; a treble clef follows the two notes.
1287        let mut data = vec![10, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0x40, 5, 2, 0];
1288        for position in [0u8, (-2i8) as u8] {
1289            data.extend([8, 0, 0, 2, 0, 0, 0, 0, 0, position, 5]);
1290        }
1291        data.extend([0, 0, 0, 0, 0, 0, 0]);
1292        let mut reader = NwcReader::new(&data, 201);
1293        let chord = reader.object().unwrap();
1294        assert_eq!(chord.type_name(), "NoteChordMember");
1295        assert!(matches!(chord.body, Object::Chord { stem_length: 5, .. }));
1296        assert_eq!(reader.object().unwrap().type_name(), "Clef");
1297        assert_eq!(reader.at, data.len());
1298    }
1299
1300    #[test]
1301    fn a_length_says_its_dots_grace_and_triplet() {
1302        assert_eq!(
1303            duration_text(2, &[0, 0, 0, 0x04], None).unwrap(),
1304            "4th,Dotted"
1305        );
1306        assert_eq!(
1307            duration_text(3, &[0, 0x04, 0], Some(&[0x01, 0x20])).unwrap(),
1308            "8th,DblDotted,Grace,Triplet"
1309        );
1310        assert!(duration_text(7, &[0, 0, 0, 0], None).is_err());
1311    }
1312}