Skip to main content

music21/midi/
translate.rs

1//! music21's `midi.translate` below any score object: what a note, a chord,
2//! an instrument, a meter, a key or a tempo is as MIDI events, and what
3//! such events say back, timed in ticks.
4//!
5//! The events are laid out in the order music21's translating functions
6//! list them, each delta time before the event it times, so that a caller
7//! building music21's event objects builds the same list. The file reader
8//! and writer ([`from_midi`](super::from_midi), [`to_midi`](super::to_midi))
9//! use the same encodings.
10
11use std::collections::HashMap;
12use std::hash::Hash;
13
14use crate::defaults::{FloatType, IntegerType};
15use crate::error::{Error, Result};
16use crate::instrument::{Instrument, SearchLanguage};
17
18use super::base::{
19    CHANNEL_VOICE_MESSAGES, EventType, Param, ReadEvent, file_header_bytes, put_number,
20    put_variable_length_number,
21};
22
23/// music21's `defaults.ticksPerQuarter`, its MusicXML divisions.
24pub const TICKS_PER_QUARTER: i64 = 10080;
25
26/// music21's `defaults.ticksAtStart`: the delay before the first note and
27/// after the last, a quarter.
28pub const TICKS_AT_START: i64 = TICKS_PER_QUARTER;
29
30/// The channel General MIDI keeps for drums, counted from one.
31pub const PERCUSSION_CHANNEL: u8 = 10;
32
33/// MIDI clock pulses to a metronome click: one a quarter.
34const PULSES_PER_CLICK: u8 = 24;
35/// Thirty-second notes to a quarter.
36const THIRTY_SECONDS_PER_QUARTER: u8 = 8;
37/// What a tempo of a quarter a minute lasts, in microseconds.
38const MICROSECONDS_PER_MINUTE: FloatType = 60_000_000.0;
39/// The bytes a tempo is written in.
40const TEMPO_BYTES: usize = 3;
41/// The key a stroke sounds on where nothing names one.
42pub const DEFAULT_STROKE_KEY: u8 = 60;
43
44const NOTE_ON: u8 = 0x90;
45const NOTE_OFF: u8 = 0x80;
46const PROGRAM_CHANGE: u8 = 0xC0;
47const SEQUENCE_TRACK_NAME: u8 = 0x03;
48const INSTRUMENT_NAME: u8 = 0x04;
49const LYRIC: u8 = 0x05;
50const END_OF_TRACK: u8 = 0x2F;
51const SET_TEMPO: u8 = 0x51;
52const TIME_SIGNATURE: u8 = 0x58;
53const KEY_SIGNATURE: u8 = 0x59;
54
55/// Whether the first note waits a quarter: music21's `addStartDelay`.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum StartDelay {
58    /// The music starts at once.
59    Without,
60    /// The music starts [`TICKS_AT_START`] late.
61    Quarter,
62}
63
64/// Whether a track ends a quarter after its last event: music21's
65/// `addEndDelay`.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum EndDelay {
68    /// The track ends with its last event.
69    Without,
70    /// The track ends [`TICKS_AT_START`] later.
71    Quarter,
72}
73
74/// Whether a list of events carries a delta time before each:
75/// music21's `includeDeltaTime`.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum Deltas {
78    /// A delta time before each event.
79    Included,
80    /// The events alone.
81    Omitted,
82}
83
84/// A key's mode as MIDI writes it.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum Mode {
87    /// Written `0`; also any key that names no mode.
88    Major,
89    /// Written `1`.
90    Minor,
91}
92
93/// One entry of a translated list: a delta time or an event.
94#[derive(Clone, Debug, PartialEq)]
95pub enum Laid {
96    /// Ticks waited, and the channel music21 gives the delta time where it
97    /// gives one.
98    Delta {
99        /// Ticks since the event before.
100        ticks: i64,
101        /// Its channel, counted from one; `None` leaves music21's default.
102        channel: Option<u8>,
103    },
104    /// An event, and the cents its note is bent by where it is between
105    /// the keys.
106    Event {
107        /// The event itself.
108        event: ReadEvent,
109        /// music21's `centShift`.
110        cent_shift: Option<IntegerType>,
111    },
112}
113
114impl Laid {
115    fn delta(ticks: i64, channel: Option<u8>) -> Self {
116        Self::Delta { ticks, channel }
117    }
118
119    fn event(event_type: EventType, channel: Option<u8>, data: Param) -> Self {
120        Self::Event {
121            event: ReadEvent {
122                event_type,
123                channel,
124                parameter1: data,
125                parameter2: None,
126            },
127            cent_shift: None,
128        }
129    }
130
131    fn meta(kind: u8, data: Vec<u8>) -> Self {
132        Self::event(EventType::Meta(kind), None, Param::Bytes(data))
133    }
134
135    fn note(message: u8, channel: u8, sounding: &Sounding, velocity: u8) -> Self {
136        Self::Event {
137            event: ReadEvent {
138                event_type: EventType::ChannelVoice(message),
139                channel: Some(channel),
140                parameter1: Param::Int(i64::from(sounding.key)),
141                parameter2: Some(velocity),
142            },
143            cent_shift: sounding.cent_shift,
144        }
145    }
146}
147
148/// A key sounding: which, bent by how many cents, how loud.
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub struct Sounding {
151    /// The MIDI key.
152    pub key: u8,
153    /// The cents a pitch between the keys is bent by.
154    pub cent_shift: Option<IntegerType>,
155    /// The note-on's velocity.
156    pub velocity: u8,
157}
158
159/// An offset in ticks, a quarter later with the start delay: music21's
160/// `offsetToMidiTicks`, rounding as Python rounds.
161///
162/// ```
163/// use music21::midi::translate::{StartDelay, offset_ticks};
164///
165/// assert_eq!(offset_ticks(20.5, StartDelay::Without), 206640);
166/// assert_eq!(offset_ticks(0.0, StartDelay::Quarter), 10080);
167/// ```
168pub fn offset_ticks(offset: FloatType, delay: StartDelay) -> i64 {
169    let ticks = duration_ticks(offset);
170    match delay {
171        StartDelay::Without => ticks,
172        StartDelay::Quarter => ticks + TICKS_AT_START,
173    }
174}
175
176/// A length in quarters as ticks: music21's `durationToMidiTicks`.
177pub fn duration_ticks(quarter_length: FloatType) -> i64 {
178    (quarter_length * TICKS_PER_QUARTER as FloatType).round_ties_even() as i64
179}
180
181/// The four bytes of a meter, or nothing for a numerator MIDI cannot
182/// hold: music21's `timeSignatureToMidiEvents`.
183///
184/// ```
185/// use music21::midi::translate::meter_data;
186///
187/// assert_eq!(meter_data(5, 4), Some([5, 2, 24, 8]));
188/// assert_eq!(meter_data(267, 32), None);
189/// ```
190pub fn meter_data(numerator: u32, denominator: u32) -> Option<[u8; 4]> {
191    let numerator = u8::try_from(numerator).ok()?;
192    let power = FloatType::from(denominator).log2() as u8;
193    Some([
194        numerator,
195        power,
196        PULSES_PER_CLICK,
197        THIRTY_SECONDS_PER_QUARTER,
198    ])
199}
200
201/// The numerator and denominator a meter's bytes say, or nothing for too
202/// few bytes or a denominator past counting: music21's
203/// `midiEventsToTimeSignature`.
204pub fn meter_of(data: &[u8]) -> Option<(u32, u32)> {
205    let [numerator, power, ..] = data else {
206        return None;
207    };
208    let denominator = 2_u32.checked_pow(u32::from(*power))?;
209    Some((u32::from(*numerator), denominator))
210}
211
212/// The two bytes of a key: sharps, flats below nought, then the mode.
213///
214/// ```
215/// use music21::midi::translate::{Mode, key_data};
216///
217/// assert_eq!(key_data(-5, Mode::Minor), [0xFB, 1]);
218/// ```
219pub fn key_data(sharps: IntegerType, mode: Mode) -> [u8; 2] {
220    [sharps.rem_euclid(256) as u8, u8::from(mode == Mode::Minor)]
221}
222
223/// The sharps and mode a key's bytes say: music21's `midiEventsToKey`,
224/// which reads a first byte past twelve as flats.
225pub fn key_of(data: &[u8]) -> Option<(IntegerType, Mode)> {
226    let [sharps, mode, ..] = data else {
227        return None;
228    };
229    let sharps = if *sharps > 12 {
230        IntegerType::from(*sharps) - 256
231    } else {
232        IntegerType::from(*sharps)
233    };
234    let mode = if *mode == 1 { Mode::Minor } else { Mode::Major };
235    Some((sharps, mode))
236}
237
238/// The three bytes of a tempo of so many quarters a minute: the
239/// microseconds a quarter lasts.
240///
241/// ```
242/// use music21::midi::translate::tempo_data;
243///
244/// assert_eq!(tempo_data(90.0), *b"\n,+");
245/// ```
246pub fn tempo_data(quarter_bpm: FloatType) -> [u8; 3] {
247    let micros = (MICROSECONDS_PER_MINUTE / quarter_bpm).round_ties_even() as i128;
248    let written = put_number(micros, TEMPO_BYTES);
249    [written[0], written[1], written[2]]
250}
251
252/// The quarters a minute a tempo's bytes say, to two places, or nothing
253/// for too few bytes or a quarter lasting no time: music21's
254/// `midiEventsToTempo`.
255pub fn tempo_of(data: &[u8]) -> Option<FloatType> {
256    let bytes = data.get(..TEMPO_BYTES)?;
257    let micros = bytes
258        .iter()
259        .fold(0_u64, |total, byte| (total << 8) | u64::from(*byte));
260    if micros == 0 {
261        return None;
262    }
263    Some((MICROSECONDS_PER_MINUTE / micros as FloatType * 100.0).round_ties_even() / 100.0)
264}
265
266/// A delta time before an event where they are included.
267fn timed(out: &mut Vec<Laid>, deltas: Deltas, ticks: i64, channel: Option<u8>) {
268    if deltas == Deltas::Included {
269        out.push(Laid::delta(ticks, channel));
270    }
271}
272
273/// A note's events: its lyric where it has one, the note-on and the
274/// note-off `ticks` later: music21's `noteToMidiEvents`.
275pub fn note_events(
276    sounding: &Sounding,
277    lyric: &[u8],
278    ticks: i64,
279    channel: u8,
280    deltas: Deltas,
281) -> Vec<Laid> {
282    let mut out = Vec::new();
283    if !lyric.is_empty() {
284        timed(&mut out, deltas, 0, Some(channel));
285        out.push(Laid::meta(LYRIC, lyric.to_vec()));
286    }
287    timed(&mut out, deltas, 0, None);
288    out.push(Laid::note(NOTE_ON, channel, sounding, sounding.velocity));
289    timed(&mut out, deltas, ticks, Some(channel));
290    out.push(Laid::note(NOTE_OFF, channel, sounding, 0));
291    out
292}
293
294/// A chord's events: its lyric, every note-on, then every note-off, the
295/// first `ticks` later: music21's `chordToMidiEvents`, whose note-ons are
296/// all on the first channel whatever channel it is given.
297pub fn chord_events(
298    members: &[Sounding],
299    lyric: &[u8],
300    ticks: i64,
301    channel: u8,
302    deltas: Deltas,
303) -> Vec<Laid> {
304    let mut out = Vec::new();
305    if !lyric.is_empty() {
306        timed(&mut out, deltas, 0, None);
307        out.push(Laid::meta(LYRIC, lyric.to_vec()));
308    }
309    for member in members {
310        timed(&mut out, deltas, 0, None);
311        out.push(Laid::note(NOTE_ON, 1, member, member.velocity));
312    }
313    for (index, member) in members.iter().enumerate() {
314        let wait = if index == 0 { ticks } else { 0 };
315        timed(&mut out, deltas, wait, None);
316        out.push(Laid::note(NOTE_OFF, channel, member, 0));
317    }
318    out
319}
320
321/// A program change: music21's `instrumentToMidiEvents`.
322pub fn program_events(program: u8, channel: u8, deltas: Deltas) -> Vec<Laid> {
323    let mut out = Vec::new();
324    timed(&mut out, deltas, 0, Some(channel));
325    out.push(Laid::event(
326        EventType::ChannelVoice(PROGRAM_CHANGE),
327        Some(channel),
328        Param::Int(i64::from(program)),
329    ));
330    out
331}
332
333/// What a track starts with: its name, then its program where it has one:
334/// music21's `getStartEvents`.
335pub fn start_events(name: &[u8], program: Option<u8>, channel: u8) -> Vec<Laid> {
336    let mut out = vec![Laid::delta(0, Some(channel))];
337    out.push(Laid::event(
338        EventType::Meta(SEQUENCE_TRACK_NAME),
339        Some(channel),
340        Param::Bytes(name.to_vec()),
341    ));
342    if let Some(program) = program {
343        out.extend(program_events(program, channel, Deltas::Included));
344    }
345    out
346}
347
348/// What a track ends with: music21's `getEndEvents`.
349pub fn end_events(delay: EndDelay) -> Vec<Laid> {
350    let ticks = match delay {
351        EndDelay::Without => 0,
352        EndDelay::Quarter => TICKS_AT_START,
353    };
354    vec![
355        Laid::delta(ticks, None),
356        Laid::meta(END_OF_TRACK, Vec::new()),
357    ]
358}
359
360/// A meta event's single entry, a delta time before it where included.
361fn one_meta(kind: u8, data: Vec<u8>, deltas: Deltas) -> Vec<Laid> {
362    let mut out = Vec::new();
363    timed(&mut out, deltas, 0, None);
364    out.push(Laid::Event {
365        event: ReadEvent {
366            event_type: EventType::Meta(kind),
367            channel: Some(1),
368            parameter1: Param::Bytes(data),
369            parameter2: None,
370        },
371        cent_shift: None,
372    });
373    out
374}
375
376/// A meter's events, none where MIDI cannot hold it.
377pub fn meter_events(numerator: u32, denominator: u32, deltas: Deltas) -> Vec<Laid> {
378    match meter_data(numerator, denominator) {
379        Some(data) => one_meta(TIME_SIGNATURE, data.to_vec(), deltas),
380        None => Vec::new(),
381    }
382}
383
384/// A key's events. music21 names no channel on it.
385pub fn key_events(sharps: IntegerType, mode: Mode, deltas: Deltas) -> Vec<Laid> {
386    let mut out = Vec::new();
387    timed(&mut out, deltas, 0, None);
388    out.push(Laid::meta(KEY_SIGNATURE, key_data(sharps, mode).to_vec()));
389    out
390}
391
392/// A tempo's events.
393pub fn tempo_events(quarter_bpm: FloatType, deltas: Deltas) -> Vec<Laid> {
394    one_meta(SET_TEMPO, tempo_data(quarter_bpm).to_vec(), deltas)
395}
396
397/// What an instrument is read from: music21's `midiEventToInstrument`.
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399pub enum Source<'a> {
400    /// A program change's program.
401    Program(u8),
402    /// A name, decoded, from a track-name meta event.
403    TrackName(&'a str),
404    /// A name, decoded, from an instrument-name meta event.
405    InstrumentName(&'a str),
406    /// A name from any other event.
407    OtherName(&'a str),
408    /// Nothing an instrument can be told from.
409    Nothing,
410}
411
412/// The instrument a percussion key plays, a tambourine taken to be
413/// headless: music21's `_midiNumberToPercussionInstrument`.
414///
415/// A key the map says nothing of is a bare unpitched percussion
416/// instrument keeping that key.
417pub fn percussion_instrument(key: u8) -> Instrument {
418    let mut made = crate::instrument::for_percussion_key_or_unmapped(key);
419    made.set_headless(true);
420    made
421}
422
423/// Whether a name is one MIDI software writes for no instrument in
424/// particular: `Instrument`, `Inst 3`.
425fn is_placeholder(name: &str) -> bool {
426    let lower = name.to_lowercase();
427    let numbered = |prefix: &str| {
428        let rest = lower.replace(prefix, "");
429        !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit())
430    };
431    lower == "instrument" || lower == "inst" || numbered("instrument ") || numbered("inst ")
432}
433
434/// The instrument an event names, on its channel: music21's
435/// `midiEventToInstrument`. A name is cut at its first nul, as MuseScore
436/// ends them so, and kept as the part's or instrument's name unless it is
437/// a placeholder.
438pub fn instrument_of(source: Source<'_>, channel: u8) -> Instrument {
439    let name = match source {
440        Source::TrackName(name) | Source::InstrumentName(name) | Source::OtherName(name) => {
441            name.split('\0').next().unwrap_or("").trim()
442        }
443        _ => "",
444    };
445    let mut instrument = match source {
446        Source::Program(program) if channel == PERCUSSION_CHANNEL => {
447            let mut made = Instrument::of_kind("UnpitchedPercussion").unwrap_or_default();
448            made.set_midi_program(Some(program));
449            made
450        }
451        Source::Program(program) => {
452            Instrument::from_midi_program(program).unwrap_or_else(|_| Instrument::new())
453        }
454        Source::Nothing => Instrument::new(),
455        _ => Instrument::from_name(name, SearchLanguage::All).unwrap_or_else(|_| Instrument::new()),
456    };
457    // Counted from nought, as music21 counts it.
458    instrument.set_midi_channel(channel.checked_sub(1));
459    if name.is_empty() || is_placeholder(name) {
460        return instrument;
461    }
462    match source {
463        Source::TrackName(_) => instrument.set_part_name(Some(name.to_string())),
464        Source::InstrumentName(_) => instrument.set_name(Some(name.to_string())),
465        _ => {}
466    }
467    instrument
468}
469
470/// The source an event's type and data name, for [`instrument_of`].
471pub fn source_of(event_type: EventType, text: &str) -> Source<'_> {
472    match event_type {
473        EventType::Meta(SEQUENCE_TRACK_NAME) => Source::TrackName(text),
474        EventType::Meta(INSTRUMENT_NAME) => Source::InstrumentName(text),
475        _ => Source::OtherName(text),
476    }
477}
478
479/// Each event paired with the tick it falls on, from a list of delta times
480/// (`Some`) and events (`None`): music21's `getTimeForEvents`. An event
481/// counts only right after a delta time; anything out of that order is
482/// passed over. The answer is each event's tick and its place in the list.
483pub fn event_ticks(deltas: &[Option<u64>]) -> Vec<(u64, usize)> {
484    let mut out = Vec::new();
485    let mut now: u64 = 0;
486    let mut index = 0;
487    while index + 1 < deltas.len() {
488        let (Some(wait), None) = (deltas[index], deltas[index + 1]) else {
489            index += 1;
490            continue;
491        };
492        now = now.saturating_add(wait);
493        out.push((now, index + 1));
494        index += 2;
495    }
496    out
497}
498
499/// What an event is to a note: one starting or ending, keyed by its pitch
500/// and channel, or neither.
501#[derive(Clone, Copy, Debug, PartialEq, Eq)]
502pub enum NoteMark<K> {
503    /// A note-on of some velocity.
504    On(K),
505    /// A note-off, or a note-on of none.
506    Off(K),
507    /// Anything else.
508    Other,
509}
510
511/// A note as events time it.
512#[derive(Clone, Copy, Debug, PartialEq, Eq)]
513pub struct TimedNote {
514    /// The tick it starts on.
515    pub on: u64,
516    /// The tick it stops on.
517    pub off: u64,
518    /// Where its note-on stands in the list.
519    pub index: usize,
520}
521
522/// Each note-on with the nearest note-off of its key after it, in the
523/// order they start: music21's `getNotesFromEvents`. A note-on with no
524/// note-off after it is dropped.
525pub fn notes_of<K: Eq + Hash + Copy>(events: &[(u64, NoteMark<K>)]) -> Vec<TimedNote> {
526    let mut waiting: HashMap<K, u64> = HashMap::new();
527    let mut notes = Vec::new();
528    for (index, (time, mark)) in events.iter().enumerate().rev() {
529        match mark {
530            NoteMark::Off(key) => {
531                waiting.insert(*key, *time);
532            }
533            NoteMark::On(key) => {
534                if let Some(off) = waiting.get(key) {
535                    notes.push(TimedNote {
536                        on: *time,
537                        off: *off,
538                        index,
539                    });
540                }
541            }
542            NoteMark::Other => {}
543        }
544    }
545    notes.reverse();
546    notes
547}
548
549/// An instrument as channels are planned from it: its program and the
550/// channel it names, counted from nought as music21 counts it.
551#[derive(Clone, Copy, Debug, PartialEq, Eq)]
552pub struct Played {
553    /// Its program, where it names one.
554    pub program: Option<u8>,
555    /// Its channel, counted from nought, where it names one.
556    pub channel: Option<u8>,
557}
558
559/// An instrument that named a channel the plan could not give it, and
560/// was put on the first channel instead.
561#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct Misplaced {
563    /// Which part, of those planned for.
564    pub part: usize,
565    /// Which instrument of that part.
566    pub instrument: usize,
567    /// The channel it named, counted from one.
568    pub channel: u8,
569    /// The channels still free then.
570    pub acceptable: Vec<u8>,
571}
572
573/// Which channel each program plays on, and the channels left over to
574/// bend microtones on: music21's `channelInstrumentData`.
575#[derive(Clone, Debug, Default, PartialEq, Eq)]
576pub struct ChannelPlan {
577    /// Each program, `None` for a part with no instrument, and its
578    /// channel counted from one, in the order they were given channels.
579    pub by_program: Vec<(Option<u8>, u8)>,
580    /// The channels no program took.
581    pub dynamic: Vec<u8>,
582    /// The instruments put on the first channel against what they named.
583    pub misplaced: Vec<Misplaced>,
584}
585
586impl ChannelPlan {
587    /// The channel a program plays on.
588    pub fn channel(&self, program: Option<u8>) -> Option<u8> {
589        self.by_program
590            .iter()
591            .find(|(held, _)| *held == program)
592            .map(|(_, channel)| *channel)
593    }
594}
595
596/// The channels for the instruments of each part (a conductor's left
597/// out), on `acceptable` channels counted from one, every channel but the
598/// drums' where none are given: music21's `channelInstrumentData`.
599///
600/// An instrument naming a channel keeps it; the other programs take free
601/// channels in turn, always leaving one free, and share the first where
602/// too few are left.
603pub fn plan_channels(parts: &[Vec<Played>], acceptable: Option<&[u8]>) -> ChannelPlan {
604    let mut free: Vec<u8> = acceptable
605        .map(<[u8]>::to_vec)
606        .unwrap_or_else(|| (1..PERCUSSION_CHANNEL).chain(11..=16).collect());
607    let mut plan = ChannelPlan::default();
608    let mut programs: Vec<Option<u8>> = Vec::new();
609    let mut assigned: Vec<u8> = Vec::new();
610
611    // Instruments naming their own channels first.
612    for (part, instruments) in parts.iter().enumerate() {
613        for (index, played) in instruments.iter().enumerate() {
614            if let Some(named) = played.channel
615                && plan.channel(played.program).is_none()
616            {
617                let mut channel = named.saturating_add(1);
618                if let Some(place) = free.iter().position(|ok| *ok == channel) {
619                    free.remove(place);
620                } else if channel != PERCUSSION_CHANNEL {
621                    plan.misplaced.push(Misplaced {
622                        part,
623                        instrument: index,
624                        channel,
625                        acceptable: free.clone(),
626                    });
627                    channel = 1;
628                }
629                if !assigned.contains(&channel) {
630                    assigned.push(channel);
631                }
632                plan.by_program.push((played.program, channel));
633            }
634            if !programs.contains(&played.program) {
635                programs.push(played.program);
636            }
637        }
638        if instruments.is_empty() && !programs.contains(&None) {
639            programs.push(None);
640        }
641    }
642
643    // The rest in turn, one channel always left free.
644    let needed: Vec<Option<u8>> = programs
645        .into_iter()
646        .filter(|program| plan.channel(*program).is_none())
647        .collect();
648    for (index, program) in needed.into_iter().enumerate() {
649        let channel = if index + 1 < free.len() {
650            free[index]
651        } else {
652            free.first().copied().unwrap_or(1)
653        };
654        if !assigned.contains(&channel) {
655            assigned.push(channel);
656        }
657        plan.by_program.push((program, channel));
658    }
659    plan.dynamic = free
660        .into_iter()
661        .filter(|channel| !assigned.contains(channel))
662        .collect();
663    plan
664}
665
666/// An event of music21's text notation for MIDI that is not a note: its
667/// status, as written.
668#[derive(Clone, Debug, PartialEq, Eq)]
669pub enum Unsupported {
670    /// A meta event, `FF`.
671    Meta(String),
672    /// Any channel message but a note-on or note-off.
673    Channel(String),
674}
675
676/// A file written from music21's text notation for MIDI, and the events
677/// it left out: music21's `midiAsciiStringToBinaryString`.
678///
679/// Each track is a list of events, each `delta status key velocity`: the
680/// delta in decimal, the status and key in hexadecimal, the velocity in
681/// decimal. Only note-ons and note-offs are written, on the channel of the
682/// track's place, counted from one. A file of one track is format 1
683/// whatever `format` says.
684///
685/// ```
686/// use music21::midi::translate::ascii_file;
687///
688/// let (bytes, unsupported) = ascii_file(1, 960, &[vec!["0 90 31 15".to_string()]])?;
689/// assert_eq!(&bytes[14..], b"MTrk\x00\x00\x00\x04\x00\x901\x0f");
690/// assert!(unsupported.is_empty());
691/// # Ok::<(), music21::Error>(())
692/// ```
693///
694/// # Errors
695///
696/// An event of fewer than four fields, or a field that is no number.
697pub fn ascii_file(
698    format: i128,
699    ticks_per_quarter: i128,
700    tracks: &[Vec<String>],
701) -> Result<(Vec<u8>, Vec<Unsupported>)> {
702    let format = if tracks.len() == 1 { 1 } else { format };
703    let mut out = file_header_bytes(format, tracks.len(), ticks_per_quarter).map_err(midi_error)?;
704    let mut unsupported = Vec::new();
705    for (index, track) in tracks.iter().enumerate() {
706        let channel = u8::try_from(index % 16).unwrap_or(0);
707        let mut data = Vec::new();
708        for line in track {
709            let fields: Vec<&str> = line.split(' ').collect();
710            let [delta, status, key, velocity, ..] = fields[..] else {
711                return Err(Error::midi(format!("an event of too few fields: {line:?}")));
712            };
713            let delta: i128 = parsed(delta, 10)?;
714            let key = parsed(key, 16)?;
715            let velocity = parsed(velocity, 10)?;
716            let message = match status.chars().next() {
717                _ if status == "FF" => {
718                    unsupported.push(Unsupported::Meta(status.to_string()));
719                    continue;
720                }
721                Some('8') => NOTE_OFF,
722                Some('9') => NOTE_ON,
723                _ => {
724                    unsupported.push(Unsupported::Channel(status.to_string()));
725                    continue;
726                }
727            };
728            data.extend(put_variable_length_number(delta).map_err(midi_error)?);
729            let bytes = [message + channel, byte(key)?, byte(velocity)?];
730            data.extend_from_slice(&bytes);
731        }
732        out.extend_from_slice(super::base::TRACK_HEADER);
733        out.extend(put_number(data.len() as i128, 4));
734        out.extend(data);
735    }
736    Ok((out, unsupported))
737}
738
739/// A field of the text notation, read in `radix`.
740fn parsed(field: &str, radix: u32) -> Result<i128> {
741    i128::from_str_radix(field, radix)
742        .map_err(|_| Error::midi(format!("not a number in base {radix}: {field:?}")))
743}
744
745/// A number written as one byte.
746fn byte(value: i128) -> Result<u8> {
747    u8::try_from(value).map_err(|_| Error::midi(format!("not a byte: {value}")))
748}
749
750fn midi_error(error: super::base::MidiDataError) -> Error {
751    Error::midi(error.to_string())
752}
753
754/// The name music21 gives a channel message's status, for a warning.
755pub fn status_name(status: u8) -> Option<&'static str> {
756    super::base::name_of(CHANNEL_VOICE_MESSAGES, status & 0xF0)
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762
763    #[test]
764    fn a_meter_round_trips_through_its_bytes() {
765        let data = meter_data(3, 16).unwrap();
766        assert_eq!(meter_of(&data), Some((3, 16)));
767        assert_eq!(meter_of(&[3]), None);
768    }
769
770    #[test]
771    fn a_key_of_flats_reads_back_negative() {
772        assert_eq!(key_of(&key_data(-2, Mode::Minor)), Some((-2, Mode::Minor)));
773        assert_eq!(key_of(&[2, 0]), Some((2, Mode::Major)));
774    }
775
776    #[test]
777    fn a_tempo_reads_back_to_two_places() {
778        assert_eq!(tempo_of(&tempo_data(90.0)), Some(90.0));
779        assert_eq!(tempo_of(&[0, 0, 0]), None);
780    }
781
782    #[test]
783    fn a_note_is_four_entries_and_two_without_deltas() {
784        let sounding = Sounding {
785            key: 61,
786            cent_shift: None,
787            velocity: 90,
788        };
789        let laid = note_events(&sounding, b"", 25200, 1, Deltas::Included);
790        assert_eq!(laid.len(), 4);
791        assert_eq!(
792            laid[2],
793            Laid::Delta {
794                ticks: 25200,
795                channel: Some(1)
796            }
797        );
798        assert_eq!(
799            note_events(&sounding, b"la", 0, 9, Deltas::Omitted).len(),
800            3
801        );
802    }
803
804    #[test]
805    fn a_chord_turns_every_note_on_before_any_off() {
806        let member = |key| Sounding {
807            key,
808            cent_shift: None,
809            velocity: 90,
810        };
811        let laid = chord_events(&[member(48), member(68)], b"", 10080, 3, Deltas::Omitted);
812        let kinds: Vec<_> = laid
813            .iter()
814            .map(|entry| match entry {
815                Laid::Event { event, .. } => (event.event_type, event.channel),
816                Laid::Delta { .. } => unreachable!(),
817            })
818            .collect();
819        assert_eq!(
820            kinds,
821            [
822                (EventType::ChannelVoice(NOTE_ON), Some(1)),
823                (EventType::ChannelVoice(NOTE_ON), Some(1)),
824                (EventType::ChannelVoice(NOTE_OFF), Some(3)),
825                (EventType::ChannelVoice(NOTE_OFF), Some(3)),
826            ]
827        );
828    }
829
830    #[test]
831    fn events_are_timed_only_after_a_delta() {
832        let ticks = event_ticks(&[Some(5), None, None, Some(3), Some(2), None]);
833        assert_eq!(ticks, [(5, 1), (7, 5)]);
834    }
835
836    #[test]
837    fn a_note_on_takes_the_nearest_note_off_after_it() {
838        let events = [
839            (0, NoteMark::On(60)),
840            (1, NoteMark::On(62)),
841            (2, NoteMark::Off(62)),
842            (3, NoteMark::Off(60)),
843            (4, NoteMark::On(64)),
844        ];
845        let notes = notes_of(&events);
846        assert_eq!(
847            notes,
848            [
849                TimedNote {
850                    on: 0,
851                    off: 3,
852                    index: 0
853                },
854                TimedNote {
855                    on: 1,
856                    off: 2,
857                    index: 1
858                },
859            ]
860        );
861    }
862
863    #[test]
864    fn a_placeholder_name_names_nothing() {
865        let named = instrument_of(Source::TrackName("Inst 3"), 2);
866        assert_eq!(named.part_name(), None);
867        assert_eq!(named.midi_channel(), Some(1));
868    }
869
870    #[test]
871    fn a_named_channel_is_kept_and_one_left_free() {
872        let played = |program, channel| Played { program, channel };
873        let parts = [
874            vec![played(Some(0), Some(4))],
875            vec![played(Some(40), None)],
876            vec![],
877        ];
878        let plan = plan_channels(&parts, Some(&[1, 2, 4]));
879        assert_eq!(plan.by_program, [(Some(0), 1), (Some(40), 1), (None, 2)]);
880        assert_eq!(plan.misplaced.len(), 1);
881        assert_eq!(plan.dynamic, [4]);
882
883        let plan = plan_channels(&parts[1..], None);
884        assert_eq!(plan.by_program, [(Some(40), 1), (None, 2)]);
885        assert_eq!(plan.dynamic.len(), 13);
886    }
887
888    #[test]
889    fn text_notation_leaves_out_what_is_no_note() {
890        let tracks = [vec!["0 FF 2F 0".to_string(), "0 C0 05 0".to_string()]];
891        let (_, unsupported) = ascii_file(1, 960, &tracks).unwrap();
892        assert_eq!(
893            unsupported,
894            [
895                Unsupported::Meta("FF".into()),
896                Unsupported::Channel("C0".into())
897            ]
898        );
899    }
900}