1use std::collections::BTreeMap;
2
3mod score;
4mod write;
5
6pub use score::from_midi;
7pub use write::{ExportOptions, to_midi};
8
9use crate::{
10 defaults::{FloatType, IntegerType},
11 duration::Duration,
12 error::{Error, Result},
13 note::Note,
14 pitch::Pitch,
15 stream::{Stream, StreamElement},
16};
17
18pub const DEFAULT_TICKS_PER_QUARTER: u16 = 480;
20
21#[derive(Clone, Copy, Debug, PartialEq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24#[must_use]
25pub struct MidiNote {
26 pub pitch: u8,
28 pub velocity: u8,
30 pub channel: u8,
32 pub start: FloatType,
34 pub duration: FloatType,
36}
37
38impl MidiNote {
39 pub fn new(pitch: u8, start: FloatType, duration: FloatType, velocity: u8) -> Result<Self> {
41 Self::with_channel(pitch, start, duration, velocity, 0)
42 }
43
44 pub fn with_channel(
46 pitch: u8,
47 start: FloatType,
48 duration: FloatType,
49 velocity: u8,
50 channel: u8,
51 ) -> Result<Self> {
52 if pitch > 127 {
53 return Err(Error::Midi(format!("MIDI pitch out of range: {pitch}")));
54 }
55 if velocity > 127 {
56 return Err(Error::Midi(format!(
57 "MIDI velocity out of range: {velocity}"
58 )));
59 }
60 if channel > 15 {
61 return Err(Error::Midi(format!("MIDI channel out of range: {channel}")));
62 }
63 if !start.is_finite() || start < 0.0 {
64 return Err(Error::Midi(format!("invalid MIDI note start: {start}")));
65 }
66 if !duration.is_finite() || duration < 0.0 {
67 return Err(Error::Midi(format!(
68 "invalid MIDI note duration: {duration}"
69 )));
70 }
71
72 Ok(Self {
73 pitch,
74 velocity,
75 channel,
76 start,
77 duration,
78 })
79 }
80}
81
82pub fn midi_notes_from_stream(stream: &Stream) -> Result<Vec<MidiNote>> {
84 let mut notes = Vec::new();
85 for event in stream.flatten().events() {
88 let start = event.offset();
89 let duration = event.element().quarter_length();
90 match event.element() {
91 StreamElement::Note(note) => {
92 notes.push(note_to_midi_note(note, start, duration)?);
93 }
94 StreamElement::Chord(chord) => {
95 for note in chord.notes() {
96 notes.push(note_to_midi_note(note, start, duration)?);
97 }
98 }
99 StreamElement::Rest(_)
102 | StreamElement::Unpitched(_)
103 | StreamElement::PercussionChord(_)
104 | StreamElement::Stream(_)
105 | StreamElement::Clef(_)
106 | StreamElement::Instrument(_)
107 | StreamElement::KeySignature(_)
108 | StreamElement::Key(_)
109 | StreamElement::TimeSignature(_)
110 | StreamElement::MetronomeMark(_)
111 | StreamElement::TempoText(_)
112 | StreamElement::TextExpression(_)
113 | StreamElement::RepeatExpression(_)
114 | StreamElement::Dynamic(_)
115 | StreamElement::ChordSymbol(_)
116 | StreamElement::Barline(_)
117 | StreamElement::PedalObject(_)
118 | StreamElement::RehearsalMark(_)
119 | StreamElement::MetricModulation(_)
120 | StreamElement::Break(_)
121 | StreamElement::Layout(_)
122 | StreamElement::TextBox(_)
123 | StreamElement::Variant(_) => {}
124 }
125 }
126 Ok(notes)
127}
128
129pub fn stream_from_midi_notes(notes: &[MidiNote]) -> Result<Stream> {
131 let mut stream = Stream::new();
132 for midi_note in notes {
133 let note = Note::from_pitch(Pitch::from_midi(midi_note.pitch as IntegerType)?)
134 .with_duration(Duration::new(midi_note.duration)?);
135 stream.insert(midi_note.start, note);
136 }
137 Ok(stream)
138}
139
140pub fn write_midi_bytes(notes: &[MidiNote], tempo_bpm: FloatType) -> Result<Vec<u8>> {
142 if !tempo_bpm.is_finite() || tempo_bpm <= 0.0 {
143 return Err(Error::Midi(format!("invalid tempo: {tempo_bpm}")));
144 }
145
146 let mut events = Vec::new();
147 for note in notes {
148 validate_note(*note)?;
149 let start_tick = quarter_to_tick(note.start)?;
150 let end_tick = quarter_to_tick(note.start + note.duration)?;
151 events.push((
152 start_tick,
153 1_u8,
154 [0x90 | note.channel, note.pitch, note.velocity],
155 ));
156 events.push((end_tick, 0_u8, [0x80 | note.channel, note.pitch, 0]));
157 }
158 events.sort_by_key(|event| (event.0, event.1));
159
160 let mut track = Vec::new();
161 write_vlq(0, &mut track);
162 track.extend([0xFF, 0x51, 0x03]);
163 let micros_per_quarter = (60_000_000.0 / tempo_bpm).round() as u32;
164 track.extend([
165 ((micros_per_quarter >> 16) & 0xFF) as u8,
166 ((micros_per_quarter >> 8) & 0xFF) as u8,
167 (micros_per_quarter & 0xFF) as u8,
168 ]);
169
170 let mut last_tick = 0_u32;
171 for (tick, _, bytes) in events {
172 write_vlq(tick.saturating_sub(last_tick), &mut track);
173 track.extend(bytes);
174 last_tick = tick;
175 }
176 write_vlq(0, &mut track);
177 track.extend([0xFF, 0x2F, 0x00]);
178
179 let mut out = Vec::new();
180 out.extend(b"MThd");
181 out.extend(6_u32.to_be_bytes());
182 out.extend(0_u16.to_be_bytes());
183 out.extend(1_u16.to_be_bytes());
184 out.extend(DEFAULT_TICKS_PER_QUARTER.to_be_bytes());
185 out.extend(b"MTrk");
186 out.extend((track.len() as u32).to_be_bytes());
187 out.extend(track);
188 Ok(out)
189}
190
191pub fn read_midi_bytes(bytes: &[u8]) -> Result<Vec<MidiNote>> {
193 read_midi_bytes_with_tempo(bytes).map(|(notes, _tempo)| notes)
194}
195
196pub fn read_midi_bytes_with_tempo(bytes: &[u8]) -> Result<(Vec<MidiNote>, Option<FloatType>)> {
198 let mut pos = 0;
199 expect(bytes, &mut pos, b"MThd")?;
200 let header_len = read_u32(bytes, &mut pos)?;
201 if header_len < 6 {
202 return Err(Error::Midi("MIDI header is too short".to_string()));
203 }
204 let _format = read_u16(bytes, &mut pos)?;
205 let tracks = read_u16(bytes, &mut pos)?;
206 let division = read_u16(bytes, &mut pos)?;
207 pos += (header_len - 6) as usize;
208
209 if division & 0x8000 != 0 {
210 return Err(Error::Midi(
211 "SMPTE MIDI time division is not supported".to_string(),
212 ));
213 }
214
215 let mut all_notes = Vec::new();
216 let mut first_tempo = None;
217 for _ in 0..tracks {
218 expect(bytes, &mut pos, b"MTrk")?;
219 let len = read_u32(bytes, &mut pos)? as usize;
220 let end = pos
221 .checked_add(len)
222 .ok_or_else(|| Error::Midi("MIDI track length overflow".to_string()))?;
223 if end > bytes.len() {
224 return Err(Error::Midi("MIDI track exceeds file length".to_string()));
225 }
226 let (mut notes, tempo) = read_track(&bytes[pos..end], division)?;
227 if first_tempo.is_none() {
228 first_tempo = tempo;
229 }
230 all_notes.append(&mut notes);
231 pos = end;
232 }
233 all_notes.sort_by(|left, right| {
234 left.start
235 .partial_cmp(&right.start)
236 .unwrap_or(std::cmp::Ordering::Equal)
237 });
238 Ok((all_notes, first_tempo))
239}
240
241fn note_to_midi_note(note: &Note, start: FloatType, duration: FloatType) -> Result<MidiNote> {
242 let pitch = note.pitch().ps().round() as IntegerType;
243 if !(0..=127).contains(&pitch) {
244 return Err(Error::Midi(format!("pitch {pitch} is outside MIDI range")));
245 }
246 MidiNote::new(pitch as u8, start, duration, 64)
247}
248
249fn validate_note(note: MidiNote) -> Result<()> {
250 MidiNote::with_channel(
251 note.pitch,
252 note.start,
253 note.duration,
254 note.velocity,
255 note.channel,
256 )
257 .map(|_| ())
258}
259
260fn quarter_to_tick(value: FloatType) -> Result<u32> {
261 if !value.is_finite() || value < 0.0 {
262 return Err(Error::Midi(format!("invalid quarter offset: {value}")));
263 }
264 Ok((value * DEFAULT_TICKS_PER_QUARTER as FloatType).round() as u32)
265}
266
267fn tick_to_quarter(value: u32, division: u16) -> FloatType {
268 value as FloatType / division as FloatType
269}
270
271fn write_vlq(mut value: u32, out: &mut Vec<u8>) {
272 let mut buffer = [0_u8; 5];
273 let mut idx = buffer.len() - 1;
274 buffer[idx] = (value & 0x7F) as u8;
275 value >>= 7;
276 while value > 0 {
277 idx -= 1;
278 buffer[idx] = ((value & 0x7F) as u8) | 0x80;
279 value >>= 7;
280 }
281 out.extend(&buffer[idx..]);
282}
283
284fn read_vlq(bytes: &[u8], pos: &mut usize) -> Result<u32> {
285 let mut value = 0_u32;
286 for _ in 0..4 {
287 let byte = *bytes
288 .get(*pos)
289 .ok_or_else(|| Error::Midi("unexpected end of VLQ".to_string()))?;
290 *pos += 1;
291 value = (value << 7) | (byte & 0x7F) as u32;
292 if byte & 0x80 == 0 {
293 return Ok(value);
294 }
295 }
296 Err(Error::Midi("VLQ is too long".to_string()))
297}
298
299fn read_track(track: &[u8], division: u16) -> Result<(Vec<MidiNote>, Option<FloatType>)> {
300 let mut pos = 0;
301 let mut tick = 0_u32;
302 let mut running_status = None;
303 let mut active: BTreeMap<(u8, u8), Vec<(u32, u8)>> = BTreeMap::new();
304 let mut notes = Vec::new();
305 let mut tempo = None;
306
307 while pos < track.len() {
308 tick = tick.saturating_add(read_vlq(track, &mut pos)?);
309 let byte = *track
310 .get(pos)
311 .ok_or_else(|| Error::Midi("unexpected end of MIDI event".to_string()))?;
312 let status = if byte & 0x80 != 0 {
313 pos += 1;
314 running_status = Some(byte);
315 byte
316 } else {
317 running_status
318 .ok_or_else(|| Error::Midi("running status without status byte".to_string()))?
319 };
320
321 match status {
322 0xFF => {
323 let meta_type = read_byte(track, &mut pos)?;
324 let len = read_vlq(track, &mut pos)? as usize;
325 if pos + len > track.len() {
326 return Err(Error::Midi("meta event exceeds track length".to_string()));
327 }
328 if meta_type == 0x51 && len == 3 {
329 let micros = ((track[pos] as u32) << 16)
330 | ((track[pos + 1] as u32) << 8)
331 | track[pos + 2] as u32;
332 tempo = Some(60_000_000.0 / micros as FloatType);
333 } else if meta_type == 0x2F {
334 break;
335 }
336 pos += len;
337 }
338 0xF0 | 0xF7 => {
339 let len = read_vlq(track, &mut pos)? as usize;
340 pos = pos
341 .checked_add(len)
342 .ok_or_else(|| Error::Midi("sysex length overflow".to_string()))?;
343 if pos > track.len() {
344 return Err(Error::Midi("sysex event exceeds track length".to_string()));
345 }
346 }
347 _ => {
348 let event_type = status & 0xF0;
349 let channel = status & 0x0F;
350 let data_len = match event_type {
351 0xC0 | 0xD0 => 1,
352 0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => 2,
353 _ => return Err(Error::Midi(format!("unsupported MIDI status {status:#X}"))),
354 };
355 let data1 = read_byte(track, &mut pos)?;
356 let data2 = if data_len == 2 {
357 read_byte(track, &mut pos)?
358 } else {
359 0
360 };
361
362 if event_type == 0x90 && data2 > 0 {
363 active
364 .entry((channel, data1))
365 .or_default()
366 .push((tick, data2));
367 } else if (event_type == 0x80 || event_type == 0x90)
368 && let Some(stack) = active.get_mut(&(channel, data1))
369 && let Some((start_tick, velocity)) = stack.pop()
370 {
371 notes.push(MidiNote::with_channel(
372 data1,
373 tick_to_quarter(start_tick, division),
374 tick_to_quarter(tick.saturating_sub(start_tick), division),
375 velocity,
376 channel,
377 )?);
378 }
379 }
380 }
381 }
382
383 Ok((notes, tempo))
384}
385
386fn expect(bytes: &[u8], pos: &mut usize, expected: &[u8]) -> Result<()> {
387 if bytes.get(*pos..(*pos).saturating_add(expected.len())) == Some(expected) {
388 *pos += expected.len();
389 Ok(())
390 } else {
391 Err(Error::Midi(format!(
392 "expected MIDI chunk {:?}",
393 String::from_utf8_lossy(expected)
394 )))
395 }
396}
397
398fn read_byte(bytes: &[u8], pos: &mut usize) -> Result<u8> {
399 let byte = *bytes
400 .get(*pos)
401 .ok_or_else(|| Error::Midi("unexpected end of MIDI data".to_string()))?;
402 *pos += 1;
403 Ok(byte)
404}
405
406fn read_u16(bytes: &[u8], pos: &mut usize) -> Result<u16> {
407 let start = *pos;
408 *pos += 2;
409 let data = bytes
410 .get(start..*pos)
411 .ok_or_else(|| Error::Midi("unexpected end of MIDI u16".to_string()))?;
412 Ok(u16::from_be_bytes([data[0], data[1]]))
413}
414
415fn read_u32(bytes: &[u8], pos: &mut usize) -> Result<u32> {
416 let start = *pos;
417 *pos += 4;
418 let data = bytes
419 .get(start..*pos)
420 .ok_or_else(|| Error::Midi("unexpected end of MIDI u32".to_string()))?;
421 Ok(u32::from_be_bytes([data[0], data[1], data[2], data[3]]))
422}
423
424#[cfg(test)]
425mod tests {
426 #[test]
427 fn a_stream_round_trips_through_midi_bytes() {
428 use super::{
429 MidiNote, midi_notes_from_stream, read_midi_bytes, read_midi_bytes_with_tempo,
430 stream_from_midi_notes, write_midi_bytes,
431 };
432
433 let notes = vec![
434 MidiNote::new(60, 0.0, 1.0, 90).unwrap(),
435 MidiNote::new(64, 1.0, 0.5, 100).unwrap(),
436 ];
437 let bytes = write_midi_bytes(¬es, 120.0).unwrap();
438 let (read, tempo) = read_midi_bytes_with_tempo(&bytes).unwrap();
439 assert_eq!(tempo.map(|bpm| bpm.round()), Some(120.0));
440 assert_eq!(read.len(), 2);
441 assert_eq!(read[0].pitch, 60);
442 assert_eq!(read[1].start, 1.0);
443 assert_eq!(read_midi_bytes(&bytes).unwrap().len(), 2);
444
445 let stream = stream_from_midi_notes(¬es).unwrap();
446 assert_eq!(midi_notes_from_stream(&stream).unwrap().len(), 2);
447 assert!(read_midi_bytes(b"not a midi file").is_err());
448 assert!(read_midi_bytes(&bytes[..10]).is_err());
449 }
450
451 use super::*;
452
453 #[test]
454 fn midi_roundtrip_bytes() {
455 let notes = vec![MidiNote::new(60, 0.0, 1.0, 90).unwrap()];
456 let bytes = write_midi_bytes(¬es, 120.0).unwrap();
457 assert!(bytes.starts_with(b"MThd"));
458 let (roundtrip, tempo) = read_midi_bytes_with_tempo(&bytes).unwrap();
459 assert_eq!(tempo, Some(120.0));
460 assert_eq!(roundtrip, notes);
461 }
462
463 #[test]
464 fn stream_converts_to_midi_notes() {
465 let mut stream = Stream::new();
466 stream.push(
467 Note::from_name("C4")
468 .unwrap()
469 .with_duration(Duration::half()),
470 );
471 let notes = midi_notes_from_stream(&stream).unwrap();
472 assert_eq!(notes[0].pitch, 60);
473 assert_eq!(notes[0].duration, 2.0);
474 }
475
476 #[test]
477 fn midi_note_validation_rejects_invalid_values() {
478 assert!(MidiNote::with_channel(128, 0.0, 1.0, 64, 0).is_err());
479 assert!(MidiNote::with_channel(60, 0.0, 1.0, 128, 0).is_err());
480 assert!(MidiNote::with_channel(60, 0.0, 1.0, 64, 16).is_err());
481 assert!(MidiNote::with_channel(60, -0.25, 1.0, 64, 0).is_err());
482 assert!(MidiNote::with_channel(60, 0.0, FloatType::INFINITY, 64, 0).is_err());
483 assert!(write_midi_bytes(&[], 0.0).is_err());
484 }
485
486 #[test]
487 fn midi_reader_rejects_invalid_files() {
488 assert!(read_midi_bytes(b"not midi").is_err());
489
490 let mut short_header = Vec::new();
491 short_header.extend(b"MThd");
492 short_header.extend(4_u32.to_be_bytes());
493 short_header.extend([0, 0, 0, 1]);
494 assert!(read_midi_bytes(&short_header).is_err());
495
496 let mut smpte = Vec::new();
497 smpte.extend(b"MThd");
498 smpte.extend(6_u32.to_be_bytes());
499 smpte.extend(0_u16.to_be_bytes());
500 smpte.extend(0_u16.to_be_bytes());
501 smpte.extend(0x8000_u16.to_be_bytes());
502 assert!(read_midi_bytes(&smpte).is_err());
503 }
504}