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