rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! RIFF-wrapped MIDI (RMID, usually `.rmi`) must load like the Standard MIDI
//! File it contains.
//!
//! `fixtures/rmid.rmi` (126 bytes) is shaped like real-world RMID files: a
//! `RIFF`/`RMID` container whose `data` chunk holds a Format-1 SMF (a tempo
//! track at 100 BPM, then program 40 + A4 on channel 1 and a kick on channel
//! 10, both one quarter long). The `data` chunk has an odd length, so it is
//! followed by a RIFF pad byte, then a `LIST`/`INFO` chunk with a title.

use std::path::Path;

use rumpl::midi::{self, Event};

const FIXTURE: &str =
  concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/rmid.rmi");

/// The SMF inside the RIFF `data` chunk, located by walking the RIFF chunks
/// directly (independently of the MIDI parser under test).
fn unwrap_rmid(bytes: &[u8]) -> &[u8] {
  assert_eq!(&bytes[0..4], b"RIFF");
  assert_eq!(&bytes[8..12], b"RMID");
  let mut pos = 12;
  while pos + 8 <= bytes.len() {
    let tag = &bytes[pos..pos + 4];
    let len =
      u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize;
    let body = &bytes[pos + 8..pos + 8 + len];
    if tag == b"data" {
      return body;
    }
    pos += 8 + len + (len & 1);
  }
  panic!("no data chunk in RMID fixture");
}

#[test]
fn loads_rmid_like_the_smf_it_wraps() {
  let path = Path::new(FIXTURE);
  let bytes = std::fs::read(path).unwrap();
  let smf = unwrap_rmid(&bytes);
  assert_eq!(&smf[0..4], b"MThd");
  assert_eq!(
    smf.len() % 2,
    1,
    "fixture should exercise the RIFF pad byte"
  );

  let wrapped = midi::load(path).expect("load RMID");
  let plain = midi::parse(smf).expect("parse unwrapped SMF");

  assert_eq!(wrapped.events.len(), plain.events.len());
  for (w, p) in wrapped.events.iter().zip(&plain.events) {
    assert_eq!(w.time, p.time);
    assert_eq!(format!("{:?}", w.event), format!("{:?}", p.event));
  }
  assert_eq!(wrapped.duration, plain.duration);

  // And it is the music we wrote: violin A4 + kick for one quarter at 100 BPM.
  let notes: Vec<_> = wrapped
    .events
    .iter()
    .filter_map(|e| match e.event {
      Event::NoteOn { channel, note, .. } => Some((channel, note, e.time)),
      _ => None,
    })
    .collect();
  assert_eq!(notes, vec![(0, 69, 0.0), (9, 36, 0.0)]);
  assert!(
    (wrapped.duration - 0.6).abs() < 1e-6,
    "{}",
    wrapped.duration
  );
}

#[test]
fn reports_rmid_info() {
  let info = midi::info(Path::new(FIXTURE)).expect("info of RMID");
  assert_eq!(info.format, 1);
  assert_eq!(info.track_count, 2);
  assert_eq!(info.ppq, Some(480));
  assert_eq!(info.note_count, 2);
  assert_eq!(info.tempos_bpm.len(), 1);
  assert!((info.tempos_bpm[0] - 100.0).abs() < 1e-3);
  assert_eq!(info.channels.len(), 2);
  assert_eq!(info.channels[0].program, 40);
  assert!(info.channels[1].is_drums);
}