Skip to main content

music21/midi/
write.rs

1//! A score written as a standard MIDI file: music21's
2//! `midi.translate.streamToMidiFile` and the byte writing of `midi.base`.
3
4use crate::defaults::{FloatType, IntegerType};
5use crate::error::{Error, Result};
6use crate::instrument::Instrument;
7use crate::notation::Lyric;
8use crate::note::Note;
9use crate::stream::{Stream, StreamElement, StreamEvent};
10use crate::volume::Volume;
11
12use super::translate::{self, Mode, Played, TICKS_AT_START, TICKS_PER_QUARTER};
13
14const NOTE_OFF: u8 = 0x80;
15const NOTE_ON: u8 = 0x90;
16const PROGRAM_CHANGE: u8 = 0xC0;
17const PITCH_BEND: u8 = 0xE0;
18const SEQUENCE_TRACK_NAME: u8 = 0x03;
19const LYRIC: u8 = 0x05;
20const END_OF_TRACK: u8 = 0x2F;
21const SET_TEMPO: u8 = 0x51;
22const TIME_SIGNATURE: u8 = 0x58;
23const KEY_SIGNATURE: u8 = 0x59;
24
25/// How [`to_midi`] writes a score: music21's `streamToMidiFile` keywords.
26#[derive(Clone, Debug, PartialEq, Eq)]
27#[non_exhaustive]
28pub struct ExportOptions {
29    /// Whether the notes start a quarter late, leaving a beat of silence
30    /// before the first: music21's `addStartDelay`, off by default.
31    pub add_start_delay: bool,
32    /// Whether each track ends a quarter after its last event: music21's
33    /// `addEndDelay`, on by default.
34    pub add_end_delay: bool,
35    /// The channels, counted from one, a part may be given:
36    /// music21's `acceptableChannelList`. `None` is every channel but the
37    /// tenth, which is the drums'.
38    pub acceptable_channels: Option<Vec<u8>>,
39}
40
41impl Default for ExportOptions {
42    fn default() -> Self {
43        Self {
44            add_start_delay: false,
45            add_end_delay: true,
46            acceptable_channels: None,
47        }
48    }
49}
50
51/// Writes a stream as a standard MIDI file, as music21's
52/// `streamToMidiFile(...).writestr()` writes it.
53///
54/// A score is a track for each part after a conductor track holding every
55/// tempo, meter and key signature, the first of each at any one time; any
56/// other stream is one part. The conductor says a tempo of 120 and a meter
57/// of `4/4` where the score says neither. Each part names itself after its
58/// first instrument, takes a channel for each instrument's program, and
59/// plays each note at the velocity its volume comes to under the dynamic
60/// in force where it stands and its articulations; tied notes sound as one.
61/// A pitch between the keys is played on a channel of its own, bent from
62/// the key below. Unpitched strokes sound on the tenth channel, as the drum
63/// their instrument's percussion map names. Chord symbols sound as the
64/// chords they are, for as long as they last.
65///
66/// ```
67/// use music21::midi::{from_midi, to_midi, ExportOptions};
68/// use music21::{Duration, Note, Stream, StreamKind};
69///
70/// let mut part = Stream::with_kind(StreamKind::Part);
71/// part.push(Note::from_name("C4")?.with_duration(Duration::half()));
72/// part.push(Note::from_name("E4")?.with_duration(Duration::half()));
73/// let bytes = to_midi(&part, &ExportOptions::default())?;
74/// assert_eq!(&bytes[..4], b"MThd");
75/// assert_eq!(from_midi(&bytes)?.notes().len(), 2);
76/// # Ok::<(), music21::Error>(())
77/// ```
78///
79/// Repeats are played out first, as [`Stream::expand_repeats`] plays them.
80///
81/// # Errors
82///
83/// Repeats music21 cannot make sense of; more pitches between the keys
84/// sounding at once than there are channels to bend; and a run of tied
85/// notes after the first lasting no time.
86pub fn to_midi(stream: &Stream, options: &ExportOptions) -> Result<Vec<u8>> {
87    let tracks = midi_tracks(stream, options)?;
88    let mut bytes = Vec::new();
89    bytes.extend_from_slice(b"MThd");
90    put_number(&mut bytes, 6, 4);
91    put_number(&mut bytes, 1, 2);
92    put_number(&mut bytes, tracks.len() as i64, 2);
93    put_number(&mut bytes, TICKS_PER_QUARTER, 2);
94    for track in tracks {
95        bytes.extend_from_slice(b"MTrk");
96        put_number(&mut bytes, track.len() as i64, 4);
97        bytes.extend_from_slice(&track);
98    }
99    Ok(bytes)
100}
101
102// ------------------------------------------------------------------ events
103
104#[derive(Clone, Debug)]
105enum Kind {
106    NoteOn,
107    NoteOff,
108    PitchBend,
109    ProgramChange,
110    Meta(u8),
111}
112
113#[derive(Clone, Debug)]
114struct Event {
115    kind: Kind,
116    channel: Option<u8>,
117    /// A note's key or a bend's low seven bits; a program's number.
118    first: u8,
119    /// A note's velocity or a bend's high seven bits.
120    second: u8,
121    /// A meta event's data.
122    data: Vec<u8>,
123    cent_shift: Option<IntegerType>,
124    /// The note-off of a note-on, and the other way round.
125    corresponding: Option<usize>,
126}
127
128impl Event {
129    fn new(kind: Kind) -> Self {
130        Self {
131            kind,
132            channel: Some(1),
133            first: 0,
134            second: 0,
135            data: Vec::new(),
136            cent_shift: None,
137            corresponding: None,
138        }
139    }
140
141    fn meta(kind: u8, data: Vec<u8>) -> Self {
142        Self {
143            data,
144            ..Self::new(Kind::Meta(kind))
145        }
146    }
147
148    /// music21's `MidiEvent.sortOrder`: a note-off before a bend, a bend
149    /// before anything else at one time.
150    fn sort_order(&self) -> i32 {
151        match self.kind {
152            Kind::NoteOff => -20,
153            Kind::PitchBend => -10,
154            _ => 0,
155        }
156    }
157
158    /// music21's `MidiEvent.setPitchBend`, over two semitones either way.
159    fn bend(cents: FloatType) -> Self {
160        let range = 200.0;
161        let cents = cents.clamp(-range, range);
162        let center = 0x2000;
163        let shift = if cents > 0.0 {
164            (cents / range * FloatType::from(0x4000 - 1 - center)).round_ties_even()
165        } else if cents < 0.0 {
166            (cents / range * FloatType::from(center)).round_ties_even()
167        } else {
168            0.0
169        };
170        let target = center + shift as i32;
171        Self {
172            first: (target & 0x7F) as u8,
173            second: ((target >> 7) & 0x7F) as u8,
174            ..Self::new(Kind::PitchBend)
175        }
176    }
177
178    /// music21's `MidiEvent.getBytes`.
179    fn write(&self, out: &mut Vec<u8>) {
180        let channel = self.channel.unwrap_or(1).saturating_sub(1);
181        match self.kind {
182            Kind::NoteOn | Kind::NoteOff | Kind::PitchBend => {
183                let status = match self.kind {
184                    Kind::NoteOn => NOTE_ON,
185                    Kind::NoteOff => NOTE_OFF,
186                    _ => PITCH_BEND,
187                };
188                out.extend_from_slice(&[status + channel, self.first, self.second]);
189            }
190            Kind::ProgramChange => out.extend_from_slice(&[PROGRAM_CHANGE + channel, self.first]),
191            Kind::Meta(kind) => {
192                out.extend_from_slice(&[0xFF, kind]);
193                put_variable_length(out, self.data.len() as i64);
194                out.extend_from_slice(&self.data);
195            }
196        }
197    }
198}
199
200/// music21's `putNumber`: `length` bytes, the most significant first.
201fn put_number(out: &mut Vec<u8>, number: i64, length: usize) {
202    for index in 0..length {
203        out.push(((number >> (8 * (length - 1 - index))) & 0xFF) as u8);
204    }
205}
206
207/// music21's `putVariableLengthNumber`.
208fn put_variable_length(out: &mut Vec<u8>, mut number: i64) {
209    let mut bytes = vec![(number & 0x7F) as u8];
210    number >>= 7;
211    while number > 0 {
212        bytes.push((number & 0x7F) as u8 | 0x80);
213        number >>= 7;
214    }
215    bytes.reverse();
216    out.extend_from_slice(&bytes);
217}
218
219/// music21's `offsetToMidiTicks` and `durationToMidiTicks`, rounding as
220/// Python rounds.
221fn ticks(quarter_length: FloatType) -> i64 {
222    translate::duration_ticks(quarter_length)
223}
224
225// ------------------------------------------------------------------ prepare
226
227/// One track's elements, flattened, with the instrument it starts with.
228struct Track {
229    elements: Vec<(FloatType, StreamElement)>,
230    conductor: bool,
231    /// The part's id, by which the staves read from one part on several
232    /// know one another: `P1-Staff1`, `P1-Staff2`.
233    id: Option<String>,
234}
235
236impl Track {
237    /// The staff a part on several staves was split into, as the part it
238    /// was split from.
239    fn split_from(&self) -> Option<&str> {
240        self.id
241            .as_deref()
242            .and_then(|id| id.rsplit_once("-Staff").map(|(part, _)| part))
243    }
244
245    /// The scalar of the last dynamic at or before an offset.
246    fn dynamic_at_or_before(&self, offset: FloatType) -> Option<(FloatType, FloatType)> {
247        self.elements
248            .iter()
249            .rev()
250            .find(|(at, element)| *at <= offset && matches!(element, StreamElement::Dynamic(_)))
251            .and_then(|(at, element)| match element {
252                StreamElement::Dynamic(dynamic) => Some((*at, dynamic.volume_scalar())),
253                _ => None,
254            })
255    }
256}
257
258/// music21's `prepareStreamForMidi` and the walk of
259/// `streamHierarchyToMidiTracks` up to its packets: the conductor first,
260/// then each part, ties stripped and flattened.
261fn tracks_of(stream: &Stream) -> Result<Vec<Track>> {
262    // music21 plays the repeats out of anything holding measures.
263    let holds_measures = stream.recurse().iter().any(|(_, element)| {
264        matches!(element, StreamElement::Stream(inner) if inner.kind() == crate::stream::StreamKind::Measure)
265    });
266    let mut stream = if holds_measures {
267        stream.expand_repeats()?
268    } else {
269        stream.clone()
270    };
271    let conductor = conductor_of(&mut stream);
272    let mut parts: Vec<Stream> = if stream.has_part_like_streams() {
273        stream
274            .events()
275            .iter()
276            .filter_map(|event| event.element().as_stream().cloned())
277            .collect()
278    } else {
279        vec![stream]
280    };
281    let mut tracks = vec![Track {
282        elements: conductor,
283        conductor: true,
284        id: None,
285    }];
286    for part in &mut parts {
287        part.strip_ties(true)?;
288        tracks.push(Track {
289            elements: flattened(part),
290            conductor: false,
291            id: part.id().map(str::to_string),
292        });
293    }
294    Ok(tracks)
295}
296
297/// music21's `conductorStream`: every tempo, meter and key signature taken
298/// out of the stream, keeping for each kind the first at each later time,
299/// with a tempo of 120 and a meter of `4/4` where there are none.
300fn conductor_of(stream: &mut Stream) -> Vec<(FloatType, StreamElement)> {
301    let kinds: [fn(&StreamElement) -> bool; 3] = [
302        |element| matches!(element, StreamElement::MetronomeMark(_)),
303        |element| matches!(element, StreamElement::TimeSignature(_)),
304        |element| {
305            matches!(
306                element,
307                StreamElement::KeySignature(_) | StreamElement::Key(_)
308            )
309        },
310    ];
311    let mut conductor: Vec<StreamEvent> = Vec::new();
312    for kind in kinds {
313        let mut last = -1.0;
314        for (offset, element) in stream.recurse() {
315            if !kind(element) {
316                continue;
317            }
318            if offset > last {
319                conductor.push(StreamEvent::new(offset, element.clone()));
320            }
321            last = offset;
322        }
323    }
324    stream.retain_leaves(&mut |_, element| !kinds.iter().any(|kind| kind(element)));
325    if !conductor
326        .iter()
327        .any(|event| matches!(event.element(), StreamElement::MetronomeMark(_)))
328    {
329        conductor.push(StreamEvent::new(
330            0.0,
331            StreamElement::MetronomeMark(crate::tempo::MetronomeMark::new(120.0)),
332        ));
333    }
334    if !conductor
335        .iter()
336        .any(|event| matches!(event.element(), StreamElement::TimeSignature(_)))
337    {
338        conductor.push(StreamEvent::new(
339            0.0,
340            StreamElement::TimeSignature(
341                crate::meter::TimeSignature::new(4, 4).expect("four-four is a meter"),
342            ),
343        ));
344    }
345    conductor.sort_by(crate::makenotation::event_order);
346    conductor
347        .into_iter()
348        .map(|event| (event.offset(), event.element().clone()))
349        .collect()
350}
351
352/// A stream's leaves in the order music21's `flatten` gives them, each at
353/// its offset as music21's fractions hold it, so that a note and a dynamic
354/// reached by different sums stand at one time.
355fn flattened(stream: &Stream) -> Vec<(FloatType, StreamElement)> {
356    let mut events: Vec<StreamEvent> = stream
357        .leaves()
358        .into_iter()
359        .map(|(offset, element)| {
360            StreamEvent::new(crate::makenotation::op_frac(offset), element.clone())
361        })
362        .collect();
363    events.sort_by(crate::makenotation::event_order);
364    events
365        .into_iter()
366        .map(|event| (event.offset(), event.element().clone()))
367        .collect()
368}
369
370// ------------------------------------------------------------------ packets
371
372#[derive(Clone, Debug)]
373struct Packet {
374    track: usize,
375    offset: i64,
376    event: usize,
377    cent_shift: Option<IntegerType>,
378    duration: i64,
379    last_instrument: Option<Instrument>,
380    initial_channel: Option<u8>,
381}
382
383/// The first instrument of a track as music21's `packetStorage` keeps it:
384/// one standing at the start with a program, unpitched percussion for a
385/// track of strokes, the conductor, or whatever came first.
386#[derive(Clone, Debug)]
387enum Initial {
388    None,
389    Conductor,
390    Percussion,
391    Instrument(Box<Instrument>),
392}
393
394impl Initial {
395    fn program(&self) -> Option<u8> {
396        match self {
397            Self::Instrument(instrument) => instrument.midi_program(),
398            _ => None,
399        }
400    }
401}
402
403fn midi_tracks(stream: &Stream, options: &ExportOptions) -> Result<Vec<Vec<u8>>> {
404    let tracks = tracks_of(stream)?;
405    let (by_program, dynamic) = channel_instrument_data(&tracks, options);
406
407    let mut events: Vec<Event> = Vec::new();
408    let mut packets: Vec<Packet> = Vec::new();
409    let mut initials: Vec<(Initial, Option<u8>)> = Vec::new();
410    for (id, track) in tracks.iter().enumerate() {
411        let first = track
412            .elements
413            .iter()
414            .find_map(|(offset, element)| match element {
415                StreamElement::Instrument(instrument) => {
416                    Some((*offset, instrument.as_ref().clone()))
417                }
418                _ => None,
419            });
420        let initial = match first {
421            Some((offset, instrument)) if offset == 0.0 && instrument.midi_program().is_some() => {
422                Initial::Instrument(Box::new(instrument))
423            }
424            first => {
425                let strokes = track.elements.iter().any(|(_, element)| {
426                    matches!(
427                        element,
428                        StreamElement::Unpitched(_) | StreamElement::PercussionChord(_)
429                    )
430                });
431                let sounds = track
432                    .elements
433                    .iter()
434                    .any(|(_, element)| crate::makenotation::is_general_note(element));
435                if strokes {
436                    Initial::Percussion
437                } else if id == 0 && !sounds {
438                    Initial::Conductor
439                } else {
440                    first.map_or(Initial::None, |(_, instrument)| {
441                        Initial::Instrument(Box::new(instrument))
442                    })
443                }
444            }
445        };
446        let channel = match &initial {
447            Initial::None => Some(by_program.get(&None).copied().unwrap_or(1)),
448            Initial::Percussion => Some(10),
449            Initial::Conductor => None,
450            Initial::Instrument(instrument) => Some(
451                by_program
452                    .get(&instrument.midi_program())
453                    .copied()
454                    .unwrap_or(1),
455            ),
456        };
457        let mut track_packets = track_packets(id, &tracks, options, &mut events)?;
458        for packet in &mut track_packets {
459            packet.initial_channel = channel;
460        }
461        packets.extend(track_packets);
462        initials.push((initial, channel));
463    }
464
465    let packets = assign_channels(packets, &mut events, &dynamic, &initials)?;
466
467    let mut written = Vec::new();
468    for (id, (initial, channel)) in initials.iter().enumerate() {
469        let mut out: Vec<u8> = Vec::new();
470        start_events(&mut out, initial, *channel);
471        let mut last = 0;
472        for packet in packets.iter().filter(|packet| packet.track == id) {
473            let delta = packet.offset - last;
474            if delta < 0 {
475                return Err(Error::midi("got a negative delta time".to_string()));
476            }
477            put_variable_length(&mut out, delta);
478            events[packet.event].write(&mut out);
479            last = packet.offset;
480        }
481        put_variable_length(
482            &mut out,
483            if options.add_end_delay {
484                TICKS_AT_START
485            } else {
486                0
487            },
488        );
489        Event::meta(END_OF_TRACK, Vec::new()).write(&mut out);
490        written.push(out);
491    }
492    Ok(written)
493}
494
495/// music21's `getStartEvents`: the track's name, and the first
496/// instrument's program where it has one.
497fn start_events(out: &mut Vec<u8>, initial: &Initial, channel: Option<u8>) {
498    let name = match initial {
499        Initial::Conductor => return,
500        Initial::Instrument(instrument) => instrument.best_name().unwrap_or("").to_string(),
501        Initial::Percussion => percussion().best_name().unwrap_or("").to_string(),
502        Initial::None => String::new(),
503    };
504    put_variable_length(out, 0);
505    Event::meta(SEQUENCE_TRACK_NAME, name.into_bytes()).write(out);
506    if let Some(program) = initial.program() {
507        put_variable_length(out, 0);
508        Event {
509            first: program,
510            channel,
511            ..Event::new(Kind::ProgramChange)
512        }
513        .write(out);
514    }
515}
516
517/// music21's `UnpitchedPercussion()`, which a track of strokes with no
518/// instrument of its own is named after.
519fn percussion() -> Instrument {
520    Instrument::of_kind("UnpitchedPercussion").unwrap_or_default()
521}
522
523/// music21's `channelInstrumentData` over the tracks, through
524/// [`translate::plan_channels`].
525fn channel_instrument_data(
526    tracks: &[Track],
527    options: &ExportOptions,
528) -> (Vec<(Option<u8>, u8)>, Vec<u8>) {
529    let parts: Vec<Vec<Played>> = tracks
530        .iter()
531        .filter(|track| !track.conductor)
532        .map(|track| {
533            track
534                .elements
535                .iter()
536                .filter_map(|(_, element)| match element {
537                    StreamElement::Instrument(instrument) => Some(Played {
538                        program: instrument.midi_program(),
539                        channel: instrument.midi_channel(),
540                    }),
541                    _ => None,
542                })
543                .collect()
544        })
545        .collect();
546    let plan = translate::plan_channels(&parts, options.acceptable_channels.as_deref());
547    (plan.by_program, plan.dynamic)
548}
549
550/// A list of pairs read as a map, in the order its keys were added.
551trait Keyed<K, V> {
552    fn get(&self, key: &K) -> Option<&V>;
553}
554
555impl<K: PartialEq, V> Keyed<K, V> for Vec<(K, V)> {
556    fn get(&self, key: &K) -> Option<&V> {
557        self.iter()
558            .find(|(held, _)| held == key)
559            .map(|(_, value)| value)
560    }
561}
562
563/// music21's `streamToPackets` over one flattened track.
564fn track_packets(
565    id: usize,
566    tracks: &[Track],
567    options: &ExportOptions,
568    events: &mut Vec<Event>,
569) -> Result<Vec<Packet>> {
570    let track = &tracks[id];
571    // music21 realizes the notes of a chord that each carry a volume when
572    // it writes them, each volume answering to the chord: against the
573    // dynamic the chord's context search finds -- the last at or before it
574    // in its own part, or else in the part it was split from, which holds
575    // every staff of it -- and the chord's articulations.
576    let context_dynamic = |offset: FloatType| -> Option<FloatType> {
577        track
578            .dynamic_at_or_before(offset)
579            .map(|(_, scalar)| scalar)
580            .or_else(|| {
581                let part = track.split_from()?;
582                tracks
583                    .iter()
584                    .filter(|other| other.split_from() == Some(part))
585                    .filter_map(|other| other.dynamic_at_or_before(offset))
586                    .fold(
587                        None,
588                        |best: Option<(FloatType, FloatType)>, found| match best {
589                            Some(best) if best.0 > found.0 => Some(best),
590                            _ => Some(found),
591                        },
592                    )
593                    .map(|(_, scalar)| scalar)
594            })
595    };
596    let as_stream = Stream::from_events(
597        track
598            .elements
599            .iter()
600            .map(|(offset, element)| StreamEvent::new(*offset, element.clone()))
601            .collect::<Vec<_>>(),
602    );
603    let in_force = crate::volume::dynamics_in_force(&as_stream);
604    let leaves = as_stream.leaves();
605    let dynamic_at = |index: usize| -> Option<FloatType> {
606        in_force[index].and_then(|position| match leaves[position].1 {
607            StreamElement::Dynamic(dynamic) => Some(dynamic.volume_scalar()),
608            _ => None,
609        })
610    };
611
612    let mut packets = Vec::new();
613    let mut last_instrument: Option<Instrument> = None;
614    let mut percussion_in_force: Option<u8> = None;
615    for (index, (offset, element)) in track.elements.iter().enumerate() {
616        if let StreamElement::Instrument(instrument) = element {
617            last_instrument = Some(instrument.as_ref().clone());
618            // music21 reads the percussion map of any instrument in it,
619            // a `Whistle` -- a `Flute` -- among them.
620            if instrument.is_a("MidiPercussionMapMixin")
621                && let Some(pitch) = instrument.percussion_pitch()
622            {
623                percussion_in_force = Some(pitch);
624            }
625        }
626        let list = element_events(
627            element,
628            dynamic_at(index),
629            context_dynamic(*offset),
630            percussion_in_force,
631        )?;
632        let Some(list) = list else {
633            continue;
634        };
635        let duration = ticks(element.quarter_length());
636        let mut note_played = false;
637        // The note-offs come in the order of the note-ons they end.
638        let mut waiting: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
639        for mut event in list {
640            if matches!(event.kind, Kind::NoteOn) {
641                note_played = true;
642            }
643            let mut at = ticks(*offset);
644            if note_played && options.add_start_delay {
645                at += TICKS_AT_START;
646            }
647            let is_off = matches!(event.kind, Kind::NoteOff);
648            if is_off {
649                at += duration;
650            }
651            let index = events.len();
652            if matches!(event.kind, Kind::NoteOn) {
653                waiting.push_back(index);
654            } else if is_off {
655                let on = waiting.pop_front().expect("a note-off follows its note-on");
656                events[on].corresponding = Some(index);
657                event.corresponding = Some(on);
658            }
659            packets.push(Packet {
660                track: id,
661                offset: at,
662                event: index,
663                cent_shift: event.cent_shift,
664                duration: if is_off { 0 } else { duration },
665                last_instrument: last_instrument.clone(),
666                initial_channel: None,
667            });
668            events.push(event);
669        }
670    }
671    packets.sort_by_key(|packet| (packet.offset, events[packet.event].sort_order()));
672    Ok(packets)
673}
674
675/// music21's `elementToMidiEventList`: what an element says as events, in
676/// the order music21 lists them, or nothing.
677fn element_events(
678    element: &StreamElement,
679    dynamic: Option<FloatType>,
680    context_dynamic: Option<FloatType>,
681    percussion_in_force: Option<u8>,
682) -> Result<Option<Vec<Event>>> {
683    let shift = |articulations: &[crate::articulations::Articulation]| -> FloatType {
684        articulations
685            .iter()
686            .map(crate::articulations::Articulation::volume_shift)
687            .sum()
688    };
689    let velocity = |volume: &Volume, dynamic: Option<FloatType>, shift: FloatType| -> u8 {
690        (volume.realized_with(dynamic, shift, 0.5, true) * 127.0).round_ties_even() as u8
691    };
692    let stroke_pitch = |stored: Option<&Instrument>| -> u8 {
693        stored
694            .filter(|instrument| instrument.is_a("MidiPercussionMapMixin"))
695            .and_then(Instrument::percussion_pitch)
696            .or(percussion_in_force)
697            .unwrap_or(60)
698    };
699    Ok(Some(match element {
700        StreamElement::Note(note) => single(
701            note,
702            note.pitch().midi(),
703            pitch_shift(note.pitch()),
704            velocity(&note.volume(), dynamic, shift(note.articulations())),
705            1,
706        ),
707        StreamElement::Unpitched(stroke) => {
708            let note = stroke.written();
709            single(
710                note,
711                IntegerType::from(stroke_pitch(stroke.stored_instrument())),
712                None,
713                velocity(&note.volume(), dynamic, shift(note.articulations())),
714                10,
715            )
716        }
717        StreamElement::Chord(chord) => {
718            let members: Vec<(IntegerType, Option<IntegerType>, u8)> =
719                if chord.has_component_volumes() {
720                    chord
721                        .notes()
722                        .iter()
723                        .map(|note| {
724                            (
725                                note.pitch().midi(),
726                                pitch_shift(note.pitch()),
727                                velocity(
728                                    &note.volume(),
729                                    context_dynamic,
730                                    shift(chord.articulations()),
731                                ),
732                            )
733                        })
734                        .collect()
735                } else {
736                    let loud = velocity(&chord.volume(), dynamic, shift(chord.articulations()));
737                    chord
738                        .notes()
739                        .iter()
740                        .map(|note| (note.pitch().midi(), pitch_shift(note.pitch()), loud))
741                        .collect()
742                };
743            together(&lyric_text(chord.lyrics()), &members, 1)
744        }
745        StreamElement::ChordSymbol(symbol) => {
746            let loud = velocity(&Volume::default(), dynamic, 0.0);
747            let members: Vec<_> = symbol
748                .pitches()
749                .unwrap_or_default()
750                .iter()
751                .map(|pitch| (pitch.midi(), pitch_shift(pitch), loud))
752                .collect();
753            together("", &members, 1)
754        }
755        StreamElement::PercussionChord(chord) => {
756            let written = chord.written();
757            let component = written.has_component_volumes();
758            let loud = velocity(&written.volume(), dynamic, shift(written.articulations()));
759            let members: Vec<_> = written
760                .notes()
761                .iter()
762                .enumerate()
763                .map(|(index, note)| {
764                    let velocity = if component {
765                        velocity(
766                            &note.volume(),
767                            context_dynamic,
768                            shift(written.articulations()),
769                        )
770                    } else {
771                        loud
772                    };
773                    if chord.is_unpitched(index) {
774                        (
775                            IntegerType::from(stroke_pitch(written.stored_instrument())),
776                            None,
777                            velocity,
778                        )
779                    } else {
780                        (note.pitch().midi(), pitch_shift(note.pitch()), velocity)
781                    }
782                })
783                .collect();
784            together(&lyric_text(written.lyrics()), &members, 10)
785        }
786        StreamElement::TimeSignature(meter) => {
787            let Some(data) = translate::meter_data(meter.numerator(), meter.denominator()) else {
788                return Ok(Some(Vec::new()));
789            };
790            vec![Event::meta(TIME_SIGNATURE, data.to_vec())]
791        }
792        StreamElement::KeySignature(signature) => key_events(signature.sharps(), Mode::Major),
793        StreamElement::Key(key) => {
794            let mode = if key.mode() == "minor" {
795                Mode::Minor
796            } else {
797                Mode::Major
798            };
799            key_events(key.key_signature().sharps(), mode)
800        }
801        StreamElement::MetronomeMark(mark) => {
802            if mark.number().is_none() && mark.number_sounding().is_none() {
803                return Ok(None);
804            }
805            let Some(bpm) = mark.sounding_quarter_bpm() else {
806                return Ok(None);
807            };
808            vec![Event::meta(SET_TEMPO, translate::tempo_data(bpm).to_vec())]
809        }
810        StreamElement::Instrument(instrument) => vec![Event {
811            first: instrument.midi_program().unwrap_or(0),
812            ..Event::new(Kind::ProgramChange)
813        }],
814        _ => return Ok(None),
815    }))
816}
817
818fn key_events(sharps: IntegerType, mode: Mode) -> Vec<Event> {
819    vec![Event::meta(
820        KEY_SIGNATURE,
821        translate::key_data(sharps, mode).to_vec(),
822    )]
823}
824
825/// The cents a pitch between the keys is bent by, from the key it is
826/// played on.
827fn pitch_shift(pitch: &crate::pitch::Pitch) -> Option<IntegerType> {
828    (!pitch.is_twelve_tone()).then(|| pitch.cent_shift_from_midi())
829}
830
831/// music21's `GeneralNote.lyric`: every lyric's text, a line each.
832fn lyric_text(lyrics: &[Lyric]) -> String {
833    lyrics
834        .iter()
835        .filter_map(Lyric::explicit_text)
836        .collect::<Vec<_>>()
837        .join("\n")
838}
839
840/// music21's `noteToMidiEvents`.
841fn single(
842    note: &Note,
843    key: IntegerType,
844    cent_shift: Option<IntegerType>,
845    velocity: u8,
846    channel: u8,
847) -> Vec<Event> {
848    let mut events = Vec::new();
849    let lyric = lyric_text(note.lyrics());
850    if !lyric.is_empty() {
851        events.push(Event::meta(LYRIC, lyric.into_bytes()));
852    }
853    let on = Event {
854        first: key as u8,
855        second: velocity,
856        channel: Some(channel),
857        cent_shift,
858        ..Event::new(Kind::NoteOn)
859    };
860    let off = Event {
861        kind: Kind::NoteOff,
862        second: 0,
863        ..on.clone()
864    };
865    events.push(on);
866    events.push(off);
867    events
868}
869
870/// music21's `chordToMidiEvents`: every note-on, then every note-off.
871fn together(
872    lyric: &str,
873    members: &[(IntegerType, Option<IntegerType>, u8)],
874    channel: u8,
875) -> Vec<Event> {
876    let mut events = Vec::new();
877    if !lyric.is_empty() {
878        events.push(Event::meta(LYRIC, lyric.as_bytes().to_vec()));
879    }
880    for (key, cent_shift, velocity) in members {
881        events.push(Event {
882            first: *key as u8,
883            second: *velocity,
884            cent_shift: *cent_shift,
885            ..Event::new(Kind::NoteOn)
886        });
887    }
888    for (key, cent_shift, _) in members {
889        events.push(Event {
890            first: *key as u8,
891            second: 0,
892            channel: Some(channel),
893            cent_shift: *cent_shift,
894            ..Event::new(Kind::NoteOff)
895        });
896    }
897    events
898}
899
900/// music21's `assignPacketsToChannels`: every event given its track's
901/// channel, a note sounding a pitch between the keys moved to a channel of
902/// its own while another note sounds, and a bend before it and after it.
903fn assign_channels(
904    packets: Vec<Packet>,
905    events: &mut Vec<Event>,
906    dynamic: &[u8],
907    initials: &[(Initial, Option<u8>)],
908) -> Result<Vec<Packet>> {
909    let mut unique: Vec<((i64, i64, u8), Vec<IntegerType>)> = Vec::new();
910    let mut post: Vec<Packet> = Vec::new();
911    let mut used_tracks: Vec<usize> = Vec::new();
912    let bend = |events: &mut Vec<Event>, cents: FloatType, channel: Option<u8>| {
913        events.push(Event {
914            channel,
915            ..Event::bend(cents)
916        });
917        events.len() - 1
918    };
919    let plain = |track: usize, offset: i64, event: usize| Packet {
920        track,
921        offset,
922        event,
923        cent_shift: None,
924        duration: 0,
925        last_instrument: None,
926        initial_channel: None,
927    };
928    for packet in packets {
929        if !used_tracks.contains(&packet.track) {
930            used_tracks.push(packet.track);
931        }
932        let kind = events[packet.event].kind.clone();
933        if !matches!(kind, Kind::NoteOn) {
934            if !matches!(kind, Kind::NoteOff) {
935                events[packet.event].channel = packet.initial_channel;
936            }
937            let (track, offset, shift, channel) = (
938                packet.track,
939                packet.offset,
940                packet.cent_shift,
941                events[packet.event].channel,
942            );
943            post.push(packet);
944            if matches!(kind, Kind::NoteOff) && shift.is_some_and(|shift| shift != 0) {
945                let event = bend(events, 0.0, channel);
946                post.push(plain(track, offset, event));
947            }
948            continue;
949        }
950        events[packet.event].channel = packet.initial_channel;
951        let start = packet.offset;
952        let end = packet.offset + packet.duration;
953        let shift = packet.cent_shift.filter(|shift| *shift != 0);
954        let mut exclude: Vec<u8> = Vec::new();
955        for ((used_start, used_stop, used_channel), shifts) in &unique {
956            let (used_start, used_stop) = (*used_start, *used_stop);
957            let overlaps = (start <= used_start && used_start < end)
958                || (start < used_stop && used_stop < end)
959                || (used_start <= start && start < used_stop)
960                || (used_start < end && end < used_stop);
961            if overlaps
962                && (!shifts.is_empty() || shift.is_some())
963                && !exclude.contains(used_channel)
964            {
965                exclude.push(*used_channel);
966            }
967        }
968        let corresponding = events[packet.event]
969            .corresponding
970            .expect("a note-on has its note-off");
971        let channel = if exclude.is_empty() {
972            let channel = events[packet.event].channel;
973            events[corresponding].channel = channel;
974            channel
975        } else {
976            let channel = dynamic
977                .iter()
978                .copied()
979                .find(|channel| !exclude.contains(channel))
980                .ok_or_else(|| {
981                    Error::midi(
982                        "no unused channels available for microtone/instrument assignment"
983                            .to_string(),
984                    )
985                })?;
986            events[packet.event].channel = Some(channel);
987            events[corresponding].channel = Some(channel);
988            if let Some(instrument) = &packet.last_instrument {
989                events.push(Event {
990                    first: instrument.midi_program().unwrap_or(0),
991                    channel: Some(channel),
992                    ..Event::new(Kind::ProgramChange)
993                });
994                post.push(plain(packet.track, start, events.len() - 1));
995            }
996            Some(channel)
997        };
998        if let Some(shift) = shift {
999            let event = bend(events, FloatType::from(shift), channel);
1000            post.push(plain(packet.track, start, event));
1001        }
1002        let key = (
1003            packet.offset,
1004            packet.offset + packet.duration,
1005            channel.unwrap_or(1),
1006        );
1007        let held = match unique.iter().position(|(held, _)| *held == key) {
1008            Some(index) => index,
1009            None => {
1010                unique.push((key, Vec::new()));
1011                unique.len() - 1
1012            }
1013        };
1014        if let Some(shift) = shift {
1015            unique[held].1.push(shift);
1016        }
1017        post.push(packet);
1018    }
1019    for track in used_tracks {
1020        if track == 0 {
1021            continue;
1022        }
1023        let Some(channel) = initials.get(track).and_then(|(_, channel)| *channel) else {
1024            continue;
1025        };
1026        let event = bend(events, 0.0, Some(channel));
1027        post.push(plain(track, 0, event));
1028    }
1029    post.sort_by_key(|packet| (packet.offset, events[packet.event].sort_order()));
1030    Ok(post)
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035    use super::*;
1036    use crate::notation::{Tie, TieType};
1037    use crate::{Duration, Note, StreamKind};
1038
1039    fn variable_length(number: i64) -> Vec<u8> {
1040        let mut out = Vec::new();
1041        put_variable_length(&mut out, number);
1042        out
1043    }
1044
1045    /// The key a stroke sounds on: music21 reads the percussion map of any
1046    /// instrument in it, a `Whistle` among them though it is a `Flute`.
1047    #[test]
1048    fn a_whistle_stroke_plays_its_percussion_key() {
1049        let key_of = |stored: Option<Instrument>, in_force: Option<u8>| {
1050            let mut stroke = crate::percussion::Unpitched::new();
1051            stroke.written_mut().set_stored_instrument(stored);
1052            let events = element_events(&StreamElement::Unpitched(stroke), None, None, in_force)
1053                .unwrap()
1054                .unwrap();
1055            events
1056                .iter()
1057                .find(|event| matches!(event.kind, Kind::NoteOn))
1058                .map(|event| event.first)
1059        };
1060        let mut long = Instrument::of_kind("Whistle").unwrap();
1061        long.set_modifier("long");
1062        assert_eq!(key_of(Some(long), None), Some(72));
1063        assert_eq!(
1064            key_of(Some(Instrument::of_kind("Whistle").unwrap()), None),
1065            Some(71)
1066        );
1067        assert_eq!(
1068            key_of(Some(Instrument::of_kind("Flute").unwrap()), None),
1069            Some(60)
1070        );
1071    }
1072
1073    #[test]
1074    fn numbers_are_written_seven_bits_a_byte() {
1075        assert_eq!(variable_length(0), [0x00]);
1076        assert_eq!(variable_length(0x7F), [0x7F]);
1077        assert_eq!(variable_length(0x80), [0x81, 0x00]);
1078        assert_eq!(variable_length(10080), [0xCE, 0x60]);
1079    }
1080
1081    #[test]
1082    fn a_bend_spans_two_semitones_either_way() {
1083        let middle = Event::bend(0.0);
1084        assert_eq!((middle.first, middle.second), (0x00, 0x40));
1085        let up = Event::bend(200.0);
1086        assert_eq!((up.first, up.second), (0x7F, 0x7F));
1087        let down = Event::bend(-300.0);
1088        assert_eq!((down.first, down.second), (0x00, 0x00));
1089    }
1090
1091    #[test]
1092    fn tied_notes_sound_once_after_a_conductor_saying_120_and_four_four() {
1093        let mut part = Stream::with_kind(StreamKind::Part);
1094        let mut first = Note::from_name("C4").unwrap();
1095        first.set_tie(Some(Tie::new(TieType::Start)));
1096        let mut second = Note::from_name("C4")
1097            .unwrap()
1098            .with_duration(Duration::half());
1099        second.set_tie(Some(Tie::new(TieType::Stop)));
1100        part.push(first);
1101        part.push(second);
1102        let bytes = to_midi(&part, &ExportOptions::default()).unwrap();
1103        // Two tracks.
1104        assert_eq!(&bytes[10..12], [0, 2]);
1105        // 500,000 microseconds a quarter, and four-four.
1106        assert!(
1107            bytes
1108                .windows(6)
1109                .any(|window| window == [0xFF, 0x51, 0x03, 0x07, 0xA1, 0x20])
1110        );
1111        assert!(
1112            bytes
1113                .windows(7)
1114                .any(|window| window == [0xFF, 0x58, 0x04, 0x04, 0x02, 0x18, 0x08])
1115        );
1116        let note_ons = bytes
1117            .windows(2)
1118            .filter(|window| window == &[0x90, 60])
1119            .count();
1120        assert_eq!(note_ons, 1);
1121        // The one note lasts three quarters.
1122        assert!(
1123            bytes
1124                .windows(4)
1125                .any(|window| window == [0x81, 0xEC, 0x20, 0x80])
1126        );
1127    }
1128}