Skip to main content

music21/midi/
score.rs

1//! A MIDI file read as a score: music21's `midi` reader and
2//! `midi.translate.midiFileToStream`.
3//!
4//! Every track holding notes becomes a part; the tracks holding none are
5//! read together as the conductor, whose meters, keys and tempos each part
6//! after them takes a copy of. A part's notes are gathered into chords where
7//! they start together and end together, moved onto the nearest sixteenth or
8//! triplet eighth, cut into measures, put into voices where they overlap,
9//! tied across barlines and filled out with rests.
10
11use std::collections::HashMap;
12
13use crate::chord::Chord;
14use crate::defaults::{FloatType, IntegerType};
15use crate::duration::Duration;
16use crate::error::FormatErrorKind::{Malformed, Unsupported};
17use crate::error::{Error, Position, Result};
18use crate::instrument::Instrument;
19use crate::key::KeySignature;
20use crate::makenotation::{
21    QUANTIZATION_DIVISORS, make_measures_by, make_rests, make_ties, make_voices, op_frac, quantize,
22    sorted_events,
23};
24use crate::meter::TimeSignature;
25use crate::note::Note;
26use crate::percussion::{PercussionChord, PercussionNote, Unpitched};
27use crate::pitch::Pitch;
28use crate::stream::{Stream, StreamElement, StreamEvent, StreamKind};
29use crate::tempo::MetronomeMark;
30use crate::volume::Volume;
31
32use super::base::EventType;
33use super::translate::{self, Mode, NoteMark, Source};
34
35fn midi_error(message: impl Into<String>) -> Error {
36    Error::midi(message.into())
37}
38
39/// What an event is, as far as a score cares.
40#[derive(Clone, Debug, PartialEq)]
41enum Kind {
42    NoteOn,
43    NoteOff,
44    ProgramChange,
45    /// Any other channel message.
46    Channel,
47    /// A meta event, with its type byte.
48    Meta(u8),
49    SysEx,
50    /// What is left when the data ran out mid-event.
51    Nothing,
52}
53
54/// One event of a track: music21's `MidiEvent`.
55#[derive(Clone, Debug)]
56struct Event {
57    kind: Kind,
58    /// Counted from one.
59    channel: u8,
60    /// The pitch of a note, or the program of a program change.
61    first: u8,
62    /// The velocity of a note.
63    second: u8,
64    data: Vec<u8>,
65}
66
67impl Event {
68    fn is_note_on(&self) -> bool {
69        self.kind == Kind::NoteOn && self.second != 0
70    }
71
72    fn is_note_off(&self) -> bool {
73        self.kind == Kind::NoteOff || (self.kind == Kind::NoteOn && self.second == 0)
74    }
75}
76
77const SEQUENCE_TRACK_NAME: u8 = 0x03;
78const INSTRUMENT_NAME: u8 = 0x04;
79const LYRIC: u8 = 0x05;
80const SET_TEMPO: u8 = 0x51;
81const TIME_SIGNATURE: u8 = 0x58;
82const KEY_SIGNATURE: u8 = 0x59;
83
84/// A number of so many bytes, high byte first, and what follows it.
85fn number(bytes: &[u8], length: usize) -> Result<(u64, &[u8])> {
86    if bytes.len() < length {
87        return Err(midi_error("the MIDI data ends inside a number").of_kind(Malformed));
88    }
89    let value = bytes[..length]
90        .iter()
91        .fold(0_u64, |total, byte| (total << 8) | u64::from(*byte));
92    Ok((value, &bytes[length..]))
93}
94
95/// A number written seven bits to a byte, and what follows it.
96fn variable_length(bytes: &[u8]) -> (u64, &[u8]) {
97    let mut value: u64 = 0;
98    for (index, byte) in bytes.iter().enumerate() {
99        value = (value << 7) | u64::from(byte & 0x7F);
100        if byte & 0x80 == 0 {
101            return (value, &bytes[index + 1..]);
102        }
103    }
104    (value, &[])
105}
106
107/// One event read off the front of a track's data: music21's
108/// `MidiEvent.read`. `status` is the running status, carried from the event
109/// before. Nothing is answered for a byte that starts no event music21
110/// knows.
111fn read_event<'a>(bytes: &'a [u8], status: &mut Option<u8>) -> Option<(Event, &'a [u8])> {
112    // music21's `MidiEvent` is on channel 1 until it reads a channel, and
113    // a meta event, which names none, stays there.
114    let mut event = Event {
115        kind: Kind::Nothing,
116        channel: 1,
117        first: 0,
118        second: 0,
119        data: Vec::new(),
120    };
121    if bytes.len() < 2 {
122        return Some((event, &[]));
123    }
124    // A data byte where a status byte should be runs on under the last
125    // status.
126    let (first, rest): (u8, &[u8]) = if bytes[0] < 0x80 {
127        (status.unwrap_or(0x90), bytes)
128    } else {
129        if bytes[0] != 0xFF {
130            *status = Some(bytes[0]);
131        }
132        (bytes[0], &bytes[1..])
133    };
134    let message = first & 0xF0;
135    if (0x80..=0xE0).contains(&message) {
136        event.channel = (first & 0x0F) + 1;
137        let one = *rest.first()?;
138        let two = rest.get(1).copied().unwrap_or(0);
139        return match message {
140            0xC0 | 0xD0 => {
141                if one > 127 {
142                    return None;
143                }
144                event.kind = if message == 0xC0 {
145                    Kind::ProgramChange
146                } else {
147                    Kind::Channel
148                };
149                event.first = one;
150                Some((event, &rest[1..]))
151            }
152            0x80 | 0x90 => {
153                event.kind = if message == 0x90 {
154                    Kind::NoteOn
155                } else {
156                    Kind::NoteOff
157                };
158                event.first = one;
159                event.second = two;
160                Some((event, rest.get(2..).unwrap_or(&[])))
161            }
162            _ => {
163                event.kind = Kind::Channel;
164                Some((event, rest.get(2..).unwrap_or(&[])))
165            }
166        };
167    }
168    if first == 0xF0 || first == 0xF7 {
169        let (length, after) = variable_length(rest);
170        let length = (length as usize).min(after.len());
171        event.kind = Kind::SysEx;
172        event.data = after[..length].to_vec();
173        return Some((event, &after[length..]));
174    }
175    if first == 0xFF {
176        let kind = *rest.first()?;
177        let (length, after) = variable_length(&rest[1..]);
178        let length = (length as usize).min(after.len());
179        event.kind = Kind::Meta(kind);
180        event.data = after[..length].to_vec();
181        return Some((event, &after[length..]));
182    }
183    None
184}
185
186/// A track: its events, each with the tick it happens at.
187type Track = Vec<(u64, Event)>;
188
189/// A track's events, each with the tick it happens at: music21's
190/// `processDataToEvents` and `getTimeForEvents`.
191fn track_events(mut data: &[u8]) -> Track {
192    let mut events = Vec::new();
193    let mut time: u64 = 0;
194    let mut status: Option<u8> = None;
195    while !data.is_empty() {
196        let (delta, after) = variable_length(data);
197        match read_event(after, &mut status) {
198            Some((event, rest)) => {
199                // Saturating, as a file this long is refused for its
200                // measures anyway.
201                time = time.saturating_add(delta);
202                events.push((time, event));
203                data = rest;
204            }
205            // What starts no event is passed over, its time with it.
206            None => data = after,
207        }
208    }
209    events
210}
211
212/// A file's tracks and how many ticks a quarter takes: music21's
213/// `MidiFile.readstr`.
214fn read_file(bytes: &[u8]) -> Result<(Vec<Track>, FloatType)> {
215    if bytes.get(..4) != Some(b"MThd") {
216        return Err(midi_error("badly formatted midi bytes: no MThd header").of_kind(Malformed));
217    }
218    let (length, rest) = number(&bytes[4..], 4)?;
219    if length != 6 {
220        return Err(midi_error("badly formatted midi bytes").of_kind(Malformed));
221    }
222    let (format, rest) = number(rest, 2)?;
223    if format > 1 {
224        return Err(
225            midi_error(format!("cannot handle midi file format: {format}")).of_kind(Unsupported),
226        );
227    }
228    let (count, rest) = number(rest, 2)?;
229    let (division, mut rest) = number(rest, 2)?;
230    if division & 0x8000 != 0 {
231        return Err(midi_error(
232            "a file timed in frames a second, not ticks a quarter, is not read",
233        )
234        .of_kind(Unsupported));
235    }
236    let ticks = (division & 0x7FFF) as FloatType;
237    if ticks == 0.0 {
238        return Err(midi_error("a quarter of no ticks"));
239    }
240    let mut tracks = Vec::new();
241    for index in 0..count as usize {
242        let here = || Position::track(index);
243        if rest.get(..4) != Some(b"MTrk") {
244            return Err(midi_error("badly formed midi string: missing leading MTrk")
245                .of_kind(Malformed)
246                .placed(here));
247        }
248        let (length, after) = number(&rest[4..], 4).map_err(|error| error.placed(here))?;
249        let length = (length as usize).min(after.len());
250        tracks.push(track_events(&after[..length]));
251        rest = &after[length..];
252    }
253    Ok((tracks, ticks))
254}
255
256/// A note as the file times it: when it starts, when it stops, and the
257/// event that started it.
258struct Timed<'a> {
259    on: u64,
260    off: u64,
261    event: &'a Event,
262}
263
264/// [`translate::notes_of`] over a track's events.
265fn notes_of(events: &[(u64, Event)]) -> Vec<Timed<'_>> {
266    let marks: Vec<(u64, NoteMark<(u8, u8)>)> = events
267        .iter()
268        .map(|(time, event)| {
269            let key = (event.first, event.channel);
270            let mark = if event.is_note_off() {
271                NoteMark::Off(key)
272            } else if event.is_note_on() {
273                NoteMark::On(key)
274            } else {
275                NoteMark::Other
276            };
277            (*time, mark)
278        })
279        .collect();
280    translate::notes_of(&marks)
281        .into_iter()
282        .map(|note| Timed {
283            on: note.on,
284            off: note.off,
285            event: &events[note.index].1,
286        })
287        .collect()
288}
289
290/// music21's `midiEventToInstrument`, through [`translate::instrument_of`].
291fn instrument_of(event: &Event) -> Instrument {
292    let source = match event.kind {
293        Kind::ProgramChange => Source::Program(event.first),
294        Kind::Meta(kind) => match std::str::from_utf8(&event.data) {
295            Ok(text) => translate::source_of(EventType::Meta(kind), text),
296            Err(_) => Source::Nothing,
297        },
298        _ => match std::str::from_utf8(&event.data) {
299            Ok(text) => Source::OtherName(text),
300            Err(_) => Source::Nothing,
301        },
302    };
303    translate::instrument_of(source, event.channel)
304}
305
306/// music21's `getMetaEvents`: the meters, keys, tempos and instruments a
307/// track states, each with its tick.
308fn meta_of(events: &[(u64, Event)]) -> Result<Vec<(u64, StreamElement)>> {
309    let mut found = Vec::new();
310    let mut last_program: Option<u8> = None;
311    for (time, event) in events {
312        let here = || Position::default().at_tick(*time);
313        let element: Option<StreamElement> = match event.kind {
314            Kind::Meta(TIME_SIGNATURE) if event.data.len() >= 2 => {
315                let (numerator, denominator) =
316                    translate::meter_of(&event.data).ok_or_else(|| {
317                        midi_error("a time signature over too large a value").placed(here)
318                    })?;
319                Some(TimeSignature::new(numerator, denominator)?.into())
320            }
321            Kind::Meta(KEY_SIGNATURE) => translate::key_of(&event.data).map(|(sharps, mode)| {
322                let mode = match mode {
323                    Mode::Minor => "minor",
324                    Mode::Major => "major",
325                };
326                StreamElement::Key(KeySignature::new(sharps).as_key(mode))
327            }),
328            Kind::Meta(SET_TEMPO) if event.data.len() >= 3 => {
329                let bpm = translate::tempo_of(&event.data)
330                    .ok_or_else(|| midi_error("a tempo of no time to the quarter").placed(here))?;
331                Some(MetronomeMark::new(bpm).into())
332            }
333            Kind::Meta(INSTRUMENT_NAME | SEQUENCE_TRACK_NAME) => {
334                let mut instrument = instrument_of(event);
335                if let Some(program) = last_program {
336                    instrument.set_midi_program(Some(program));
337                }
338                Some(instrument.into())
339            }
340            Kind::ProgramChange => {
341                last_program = Some(event.first);
342                Some(instrument_of(event).into())
343            }
344            _ => None,
345        };
346        if let Some(element) = element {
347            found.push((*time, element));
348        }
349    }
350    Ok(found)
351}
352
353/// music21's `instrument.deduplicate` over the events of one part: where
354/// every instrument standing at one offset is of one kind they are made one,
355/// the first, and a generic one among others of a kind goes.
356fn deduplicate(events: &mut Vec<StreamEvent>) {
357    let places: Vec<usize> = (0..events.len())
358        .filter(|index| matches!(events[*index].element(), StreamElement::Instrument(_)))
359        .collect();
360    let held: Vec<(FloatType, &Instrument)> = places
361        .iter()
362        .filter_map(|index| match events[*index].element() {
363            StreamElement::Instrument(instrument) => {
364                Some((events[*index].offset(), instrument.as_ref()))
365            }
366            _ => None,
367        })
368        .collect();
369    let settled = crate::instrument::settle_by_offset(&held);
370    for (place, becomes) in places.into_iter().zip(settled).rev() {
371        match becomes {
372            None => {}
373            Some(Some(named)) => {
374                events[place] = StreamEvent::new(events[place].offset(), named);
375            }
376            Some(None) => {
377                events.remove(place);
378            }
379        }
380    }
381}
382
383/// The length so many ticks last, or a grace note's where they are none.
384fn duration_of(ticks: u64, per_quarter: FloatType) -> Result<Duration> {
385    if ticks == 0 {
386        return Ok(Duration::quarter().grace_duration());
387    }
388    Duration::new(op_frac(ticks as FloatType / per_quarter))
389}
390
391fn volume_of(velocity: u8) -> Volume {
392    let mut volume = Volume::from_velocity(IntegerType::from(velocity));
393    volume.set_velocity_is_relative(false);
394    volume
395}
396
397/// A stroke of the instrument a percussion key plays.
398fn stroke_of(pitch: u8) -> Unpitched {
399    let mut stroke = Unpitched::new();
400    stroke
401        .written_mut()
402        .set_stored_instrument(Some(translate::percussion_instrument(pitch)));
403    stroke
404}
405
406/// One track as a part, or as more of the conductor where it has no notes:
407/// music21's `midiTrackToStream`. The answer is whether the track had notes.
408fn track_to_part(
409    events: &[(u64, Event)],
410    per_quarter: FloatType,
411    conductor: &[StreamEvent],
412    is_first: bool,
413) -> Result<(Stream, bool)> {
414    let notes = notes_of(events);
415    let mut lyrics: HashMap<u64, String> = HashMap::new();
416    for (time, event) in events {
417        if event.kind == Kind::Meta(LYRIC)
418            && let Ok(text) = std::str::from_utf8(&event.data)
419        {
420            lyrics.insert(*time, text.to_string());
421        }
422    }
423
424    let mut held: Vec<StreamEvent> = Vec::new();
425    for (tick, element) in meta_of(events)? {
426        held.push(StreamEvent::new(
427            op_frac(tick as FloatType / per_quarter),
428            element,
429        ));
430    }
431    deduplicate(&mut held);
432
433    // Notes starting together and ending together are one chord; ones that
434    // start together and end apart need voices.
435    let tolerance =
436        per_quarter / FloatType::from(QUANTIZATION_DIVISORS.into_iter().max().unwrap_or(4));
437    let mut gathered = vec![false; notes.len()];
438    let mut voices_required = false;
439    for index in 0..notes.len() {
440        if gathered[index] {
441            continue;
442        }
443        let start = notes[index].on;
444        let stop = notes[index].off;
445        let mut members = vec![index];
446        for other in index + 1..notes.len() {
447            if (notes[other].on as FloatType - start as FloatType).abs() >= tolerance {
448                break;
449            }
450            if (notes[other].off as FloatType - stop as FloatType).abs() > tolerance {
451                voices_required = true;
452                continue;
453            }
454            members.push(other);
455            gathered[other] = true;
456        }
457        let lyric = lyrics.get(&start);
458        let element: StreamElement = if members.len() > 1 {
459            // The chord is as long as the last note gathered.
460            let last = &notes[members[members.len() - 1]];
461            let duration = duration_of(last.off - last.on, per_quarter)?;
462            let percussion = members
463                .iter()
464                .any(|member| notes[*member].event.channel == 10);
465            if percussion {
466                let strokes: Vec<PercussionNote> = members
467                    .iter()
468                    .map(|member| PercussionNote::Unpitched(stroke_of(notes[*member].event.first)))
469                    .collect();
470                let mut chord = PercussionChord::new(strokes)?.with_duration(duration);
471                let volumes: Vec<Volume> = members
472                    .iter()
473                    .map(|member| volume_of(notes[*member].event.second))
474                    .collect();
475                chord.written_mut().set_volumes(&volumes)?;
476                chord.into()
477            } else {
478                let mut pitched = Vec::new();
479                for member in &members {
480                    let event = notes[*member].event;
481                    let mut note =
482                        Note::from_pitch(Pitch::from_midi(IntegerType::from(event.first))?);
483                    note.set_volume(Some(volume_of(event.second)));
484                    pitched.push(note);
485                }
486                let mut chord = Chord::new(pitched)?.with_duration(duration);
487                chord.set_midi_tick_start(Some(start));
488                // A chord's lyrics are kept on its first note.
489                if let (Some(lyric), Some(singer)) = (lyric, chord.notes_mut().first_mut()) {
490                    singer.set_lyric(Some(lyric))?;
491                }
492                chord.into()
493            }
494        } else {
495            let event = notes[index].event;
496            let duration = duration_of(stop - start, per_quarter)?;
497            if event.channel == 10 {
498                let mut stroke = stroke_of(event.first).with_duration(duration);
499                stroke
500                    .written_mut()
501                    .set_volume(Some(volume_of(event.second)));
502                if let Some(lyric) = lyric {
503                    stroke.written_mut().set_lyric(Some(lyric))?;
504                }
505                stroke.into()
506            } else {
507                let mut note = Note::from_pitch(Pitch::from_midi(IntegerType::from(event.first))?)
508                    .with_duration(duration);
509                note.set_volume(Some(volume_of(event.second)));
510                note.set_midi_tick_start(Some(start));
511                if let Some(lyric) = lyric {
512                    note.set_lyric(Some(lyric))?;
513                }
514                note.into()
515            }
516        };
517        held.push(StreamEvent::new(
518            op_frac(start as FloatType / per_quarter),
519            element,
520        ));
521    }
522
523    let mut part = Stream::with_kind(StreamKind::Part).with_events(sorted_events(held));
524    quantize(&mut part, &QUANTIZATION_DIVISORS)?;
525    if notes.is_empty() {
526        return Ok((part, false));
527    }
528
529    // The conductor's meters, keys and tempos, a copy for each part; only
530    // the first part shows the tempos.
531    let mut events = part.events().to_vec();
532    let mut meters: Vec<(FloatType, TimeSignature)> = Vec::new();
533    for event in conductor {
534        match event.element() {
535            StreamElement::TimeSignature(meter) => {
536                meters.push((event.offset(), meter.clone()));
537                events.push(event.clone());
538            }
539            StreamElement::Key(_) | StreamElement::KeySignature(_) => events.push(event.clone()),
540            StreamElement::MetronomeMark(mark) => {
541                let mut mark = mark.clone();
542                if !is_first {
543                    mark.set_number_implicit(true);
544                    mark.set_hidden(true);
545                }
546                events.push(StreamEvent::new(event.offset(), mark));
547            }
548            _ => {}
549        }
550    }
551    if !meters.is_empty() && !meters.iter().any(|(offset, _)| *offset == 0.0) {
552        meters.push((0.0, TimeSignature::new(4, 4)?));
553    }
554    let part = part.with_events(sorted_events(events));
555
556    let mut part = make_measures_by(&part, &meters)?;
557    if voices_required {
558        let mut events = part.events().to_vec();
559        for event in &mut events {
560            if let StreamElement::Stream(measure) = event.element_mut()
561                && measure.kind() == StreamKind::Measure
562            {
563                make_voices(measure);
564            }
565        }
566        part = part.with_events(events);
567    }
568    make_ties(&mut part)?;
569    make_rests(&mut part)?;
570    Ok((part, true))
571}
572
573/// Reads a standard MIDI file into a score: music21's
574/// `converter.parse` of one.
575///
576/// Every track with notes is a part. Notes are moved onto the nearest
577/// sixteenth or triplet eighth, gathered into chords and voices, cut into
578/// measures by the meters the file states (`4/4` where it states none),
579/// tied across barlines and filled out with rests. Channel 10 is read as
580/// unpitched percussion, each key the instrument General MIDI gives it. A
581/// file timed in frames a second is refused, as is a format 2 file.
582///
583/// The bytes are the file's own; the library opens no file.
584pub fn from_midi(bytes: &[u8]) -> Result<Stream> {
585    let (tracks, per_quarter) = read_file(bytes)?;
586    score_of(&tracks, per_quarter)
587}
588
589/// Reads tracks' data, each after its chunk's tag and length, as a score,
590/// as [`from_midi`] reads a file of them: music21's `midiTracksToStreams`.
591///
592/// # Errors
593///
594/// No tracks, no ticks to a quarter, or what [`from_midi`] refuses.
595pub fn from_tracks(tracks: &[&[u8]], ticks_per_quarter: u16) -> Result<Stream> {
596    let read: Vec<Track> = tracks.iter().map(|data| track_events(data)).collect();
597    score_of(&read, ticks_per(ticks_per_quarter)?)
598}
599
600/// Reads one track's data as a part, alone, with no conductor before it:
601/// music21's `midiTrackToStream`. A track with no notes comes back as a
602/// part holding its meters, keys, tempos and instruments, in no measures.
603///
604/// # Errors
605///
606/// No ticks to a quarter, or what [`from_midi`] refuses.
607pub fn part_from_track(data: &[u8], ticks_per_quarter: u16) -> Result<Stream> {
608    let events = track_events(data);
609    let (part, _) = track_to_part(&events, ticks_per(ticks_per_quarter)?, &[], true)?;
610    Ok(part)
611}
612
613/// Ticks to a quarter as a length, refusing none.
614fn ticks_per(ticks_per_quarter: u16) -> Result<FloatType> {
615    if ticks_per_quarter == 0 {
616        return Err(midi_error("a quarter of no ticks"));
617    }
618    Ok(FloatType::from(ticks_per_quarter))
619}
620
621/// Tracks read as a score: every track with notes a part, the others the
622/// conductor.
623fn score_of(tracks: &[Track], per_quarter: FloatType) -> Result<Stream> {
624    if tracks.is_empty() {
625        return Err(midi_error("no tracks are defined in this MIDI file."));
626    }
627    let mut conductor: Vec<StreamEvent> = Vec::new();
628    let mut parts: Vec<StreamEvent> = Vec::new();
629    let mut seen_notes = false;
630    for (index, track) in tracks.iter().enumerate() {
631        let here = |error: Error| error.placed(|| Position::track(index));
632        let has_notes = track.iter().any(|(_, event)| event.is_note_on());
633        if has_notes {
634            let is_first = !seen_notes;
635            seen_notes = true;
636            let (part, _) =
637                track_to_part(track, per_quarter, &conductor, is_first).map_err(here)?;
638            parts.push(StreamEvent::new(0.0, part));
639        } else {
640            // A track with no notes adds to the conductor, which is
641            // quantized again as a whole each time.
642            let (more, _) = track_to_part(track, per_quarter, &[], false).map_err(here)?;
643            conductor.extend(more.events().iter().cloned());
644            let mut all = Stream::new().with_events(sorted_events(conductor));
645            let mut events = all.events().to_vec();
646            deduplicate(&mut events);
647            all = all.with_events(events);
648            quantize(&mut all, &QUANTIZATION_DIVISORS)?;
649            conductor = all.events().to_vec();
650        }
651    }
652    Ok(Stream::with_kind(StreamKind::Score).with_events(parts))
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    /// A one-track file: a tempo, a meter, then these notes as
660    /// (delta, status, key, velocity).
661    fn file(events: &[(u8, u8, u8, u8)]) -> Vec<u8> {
662        let mut track: Vec<u8> = vec![
663            0, 0xFF, 0x51, 3, 0x07, 0xA1, 0x20, // 120 to the minute
664            0, 0xFF, 0x58, 4, 3, 2, 24, 8, // 3/4
665        ];
666        for (delta, status, key, velocity) in events {
667            track.extend([*delta, *status, *key, *velocity]);
668        }
669        track.extend([0, 0xFF, 0x2F, 0]);
670        let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\0\x60MTrk".to_vec();
671        bytes.extend((track.len() as u32).to_be_bytes());
672        bytes.extend(track);
673        bytes
674    }
675
676    #[test]
677    fn a_refusal_names_its_track_and_tick() {
678        // A second track promised and not there.
679        let mut bytes = file(&[(0, 0x90, 60, 80), (96, 0x80, 60, 0)]);
680        bytes[11] = 2;
681        let error = from_midi(&bytes).unwrap_err();
682        assert_eq!(
683            error.to_string(),
684            "Midi error: badly formed midi string: missing leading MTrk"
685        );
686        assert_eq!(error.format_error().unwrap().kind, Malformed);
687        assert_eq!(error.position(), Some(&Position::track(1)));
688
689        // A tempo of no time to the quarter, a beat in.
690        let mut track: Vec<u8> = vec![0, 0x90, 60, 80, 96, 0x80, 60, 0];
691        track.extend([0, 0xFF, 0x51, 3, 0, 0, 0, 0, 0xFF, 0x2F, 0]);
692        let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\0\x60MTrk".to_vec();
693        bytes.extend((track.len() as u32).to_be_bytes());
694        bytes.extend(track);
695        let error = from_midi(&bytes).unwrap_err();
696        assert_eq!(error.position(), Some(&Position::track(0).at_tick(96)));
697    }
698
699    #[test]
700    fn a_track_is_a_part_of_measures() {
701        // Four quarters in 3/4, 96 ticks each: a bar and a bar filled out
702        // with a rest.
703        let mut events = Vec::new();
704        for key in [60, 62, 64, 65] {
705            events.push((0, 0x90, key, 80));
706            events.push((96, 0x80, key, 0));
707        }
708        let score = from_midi(&file(&events)).unwrap();
709        let part = score.parts()[0];
710        let measures = part.measures();
711        assert_eq!(measures.len(), 2);
712        assert_eq!(measures[0].pitches().len(), 3);
713        let last: Vec<FloatType> = measures[1]
714            .events()
715            .iter()
716            .filter(|event| matches!(event.element(), StreamElement::Rest(_)))
717            .map(|event| event.element().quarter_length())
718            .collect();
719        assert_eq!(last, [2.0]);
720    }
721
722    #[test]
723    fn notes_together_are_a_chord_and_a_long_note_is_tied() {
724        // A triad for a beat, then one note for a whole 3/4 bar and a beat.
725        let events = [
726            (0, 0x90, 60, 80),
727            (0, 0x90, 64, 80),
728            (0, 0x90, 67, 80),
729            (96, 0x80, 60, 0),
730            (0, 0x80, 64, 0),
731            (0, 0x80, 67, 0),
732            (0, 0x90, 72, 80),
733            (127, 0x80, 72, 0),
734        ];
735        let mut bytes = file(&events[..7]);
736        // The last note lasts 288 ticks, which takes two bytes to say.
737        let end = bytes.len() - 4;
738        bytes.splice(end..end, [0x82, 0x20, 0x80, 72, 0]);
739        let length = (bytes.len() - 22) as u32;
740        bytes[18..22].copy_from_slice(&length.to_be_bytes());
741        let score = from_midi(&bytes).unwrap();
742        let part = score.parts()[0];
743        let measures = part.measures();
744        assert!(matches!(
745            measures[0]
746                .events()
747                .iter()
748                .find(|event| event.element().is_note_or_chord())
749                .map(StreamEvent::element),
750            Some(StreamElement::Chord(_))
751        ));
752        let ties: Vec<_> = part
753            .notes()
754            .into_iter()
755            .filter_map(|(_, element)| match element {
756                StreamElement::Note(note) => note.tie().map(|tie| tie.tie_type()),
757                _ => None,
758            })
759            .collect();
760        assert_eq!(
761            ties,
762            [
763                crate::notation::TieType::Start,
764                crate::notation::TieType::Stop
765            ]
766        );
767    }
768
769    /// A track named by a meta event, as most files name one: music21
770    /// reads its instrument on channel 0, the channel a meta event keeps
771    /// since it says none.
772    #[test]
773    fn an_instrument_named_by_a_meta_event_is_on_the_first_channel() {
774        let mut track: Vec<u8> = vec![0, 0xFF, 0x03, 5];
775        track.extend(b"Piano");
776        track.extend([0, 0x90, 60, 80, 96, 0x80, 60, 0, 0, 0xFF, 0x2F, 0]);
777        let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\0\x60MTrk".to_vec();
778        bytes.extend((track.len() as u32).to_be_bytes());
779        bytes.extend(track);
780        let score = from_midi(&bytes).unwrap();
781        let channels: Vec<Option<u8>> = score.parts()[0]
782            .instruments(true, false)
783            .iter()
784            .map(Instrument::midi_channel)
785            .collect();
786        assert_eq!(channels, [Some(0)]);
787    }
788
789    #[test]
790    fn what_is_no_midi_file_is_refused() {
791        assert!(from_midi(b"RIFF").is_err());
792    }
793
794    /// One note, or two notes far apart, at a tick a quarter: a few bytes
795    /// saying hundreds of millions of quarters.
796    #[test]
797    fn a_file_lasting_too_many_measures_is_refused() {
798        let long = [0x90, 60, 100, 0xFF, 0xFF, 0xFF, 0x7F, 0x80, 60, 0];
799        let apart = [
800            0x90, 60, 100, 0, 0x80, 60, 0, 0xFF, 0xFF, 0xFF, 0x7F, 0x90, 62, 100, 0, 0x80, 62, 0,
801        ];
802        for events in [&long[..], &apart[..]] {
803            let mut track = vec![0];
804            track.extend(events);
805            track.extend([0, 0xFF, 0x2F, 0]);
806            let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\0\x01MTrk".to_vec();
807            bytes.extend((track.len() as u32).to_be_bytes());
808            bytes.extend(track);
809            assert!(from_midi(&bytes).is_err());
810        }
811    }
812
813    /// Two waits each longer than u64 counts, which music21's unbounded
814    /// integers add up.
815    #[test]
816    fn waits_past_any_tick_are_refused() {
817        let mut track = Vec::new();
818        for key in [60, 62] {
819            track.extend([0xFF; 9]);
820            track.extend([0x7F, 0x90, key, 100, 0, 0x80, key, 0]);
821        }
822        track.extend([0, 0xFF, 0x2F, 0]);
823        let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\0\x60MTrk".to_vec();
824        bytes.extend((track.len() as u32).to_be_bytes());
825        bytes.extend(track);
826        assert!(from_midi(&bytes).is_err());
827    }
828}