1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
use std::collections::BTreeMap;
use crate::errors::ScoreError;
use crate::errors::ToMidiConversionError;
use crate::num::*;
use crate::Instrument;
use crate::Part;
use crate::PhraseEntry;
use crate::Result;
use crate::midly::{
Format, Header, MetaMessage, MidiMessage, Smf, Timing, TrackEvent, TrackEventKind,
};
/// Describes the scale mode (Major or Minor, other modes are not specified)
pub enum Mode {
Major = 0,
Minor = 1,
}
/// Contains information about the score that aren't needed for MIDI play
/// such as time signature, key signature (number of accidentals), and mode
pub struct Metadata {
/// Describes the number of accidentals of the `Score`.
/// Should always be between -7 and 7. Negative numbers are
/// Flats, positive numbers are Sharps
pub key_signature: i8,
/// Describes the mode of the scale
pub mode: Mode,
/// Describes the numerator in the time signature
pub time_numerator: u8,
/// Describes the denominator in the time signature
pub time_denominator: u8,
}
/// Describes the tempo of a score in beats per minute
pub struct Tempo(u32);
impl Tempo {
/// Returns a new tempo if non null, otherwise, returns an error
///
/// # Errors
///
/// Returns `ScoreError::InvalidTempo` if tempo is 0
pub fn new(tempo: u32) -> Result<Self> {
if tempo == 0 {
return Err(ScoreError::InvalidTempo.into());
}
Ok(Self(tempo))
}
}
/// Describes a full `Score`
pub struct Score {
/// Title of the `Score`
name: String,
/// List of `Part`s in the `Score`
parts: Vec<Part>,
/// Tempo (beats per minute) at which the `Score` should be played
tempo: u32,
/// Optional information about the `Score`
metadata: Option<Metadata>,
/// Duration in beats of the `Score`
duration: f64,
}
impl Score {
/// Returns a new empty `Score` from the given arguments
///
/// # Arguments
///
/// * `name` - Title of the `Score`
/// * `tempo` - Tempo of the `Score`
/// * `Metadata` - Optional information
pub fn new<S: ToString>(name: S, tempo: Tempo, metadata: Option<Metadata>) -> Score {
Score {
name: name.to_string(),
parts: Vec::new(),
tempo: tempo.0,
metadata,
duration: 0.,
}
}
/// Adds a `Part` to the `Score`.
/// Warning: q Score can contain unlimited Parts but if exporting to
/// Standard MIDI File, any Score with more than 16 Parts will fail
/// because MIDI only supports 16 channels.
pub fn add_part(&mut self, part: Part) {
self.duration = self.duration.max(part.duration());
self.parts.push(part);
}
/// Modifies the tempo of the `Score`
///
/// # Errors
///
/// Returns `ScoreError::InvalidTempo` if tempo is 0
pub fn set_tempo(&mut self, tempo: u32) -> Result<()> {
if tempo == 0 {
return Err(ScoreError::InvalidTempo.into());
}
self.tempo = tempo;
Ok(())
}
pub fn write_midi_file<W: std::io::Write>(&self, w: W) -> Result<()> {
let smf: Smf = self.try_into()?;
Ok(smf.write_std(w)?)
}
/// Returns the title of the `Score`
pub fn name(&self) -> &str {
self.name.as_str()
}
/// Returns the `Part`s of the `Score`
pub fn parts(&self) -> &[Part] {
self.parts.as_slice()
}
/// Returns the tempo of the `Score`
pub fn tempo(&self) -> u32 {
self.tempo
}
/// Returns the metadata
pub fn metadata(&self) -> Option<&Metadata> {
self.metadata.as_ref()
}
// Returns the total duration (in beats, i.e. the "rhythm" unit) of the `Score`.
// This corresponds to the end of the `Part` that finishes the latest.
pub fn duration(&self) -> f64 {
self.duration
}
}
impl<'a> TryFrom<&'a Score> for Smf<'a> {
type Error = crate::Error;
/// Converts a Score into a Standard MIDI File (midly::Smf)
///
/// # Arguments
///
/// * `score` - Score to convert
///
/// # Errors
///
/// Returns `ToMidiConversionError`
/// TODO: complete errors description
fn try_from(score: &'a Score) -> Result<Smf<'a>> {
if score.parts.len() > 16 {
return Err(ToMidiConversionError::TooManyParts(score.parts.len()).into());
}
let header = Header {
format: if score.parts().len() == 1 {
Format::SingleTrack
} else {
Format::Parallel
},
timing: Timing::Metrical(u15::from(480)),
};
let mut metadata_events = vec![
TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Meta(MetaMessage::TrackName(score.name.as_bytes())),
},
TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Meta(MetaMessage::Tempo(u24::from(60_000_000 / score.tempo))),
},
];
if let Some(mdata) = score.metadata() {
metadata_events.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Meta(MetaMessage::TimeSignature(
mdata.time_numerator,
mdata.time_denominator,
24u8,
32u8,
)),
});
metadata_events.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Meta(MetaMessage::KeySignature(
mdata.key_signature,
matches!(mdata.mode, Mode::Minor),
)),
});
// TODO: Handle more metadata (copyright, text fields, etc.)
}
let mut tracks = Vec::new();
for (channel, part) in score.parts().iter().enumerate() {
let mut notes_per_time: BTreeMap<u64, (Vec<TrackEvent>, Vec<TrackEvent>)> =
BTreeMap::new();
for phrase in part.phrases() {
let mut cur_time = (phrase.0 * 480.).round() as u64;
for phrase_entry in phrase.1.entries() {
match phrase_entry {
PhraseEntry::Chord(c) => {
notes_per_time.entry(cur_time).or_default().0.extend(
c.notes().iter().map(|n| TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Midi {
channel: u4::new(channel as u8),
message: MidiMessage::NoteOn {
key: n.pitch(),
vel: n.dynamic(),
},
},
}),
);
for n in c.notes() {
notes_per_time
.entry(cur_time + (n.rhythm() * 480.).round() as u64)
.or_default()
.1
.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Midi {
channel: u4::new(channel as u8),
message: MidiMessage::NoteOff {
key: n.pitch(),
vel: u7::default(),
},
},
})
}
cur_time += (c.rhythm() * 480.).round() as u64;
}
PhraseEntry::Note(n) => {
notes_per_time
.entry(cur_time)
.or_default()
.0
.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Midi {
channel: u4::new(channel as u8),
message: MidiMessage::NoteOn {
key: n.pitch(),
vel: n.dynamic(),
},
},
});
notes_per_time
.entry(cur_time + (n.rhythm() * 480.).round() as u64)
.or_default()
.1
.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Midi {
channel: u4::new(channel as u8),
message: MidiMessage::NoteOff {
key: n.pitch(),
vel: u7::default(),
},
},
});
cur_time += (n.rhythm() * 480.).round() as u64;
}
PhraseEntry::Rest(r) => {
cur_time += (r * 480.).round() as u64;
}
};
}
}
// TODO: investigate if the usage of `round` on the time value (in ticks) can cause issues
if notes_per_time.is_empty() {
continue;
}
let mut track = metadata_events.clone();
let part_instrument = part.instrument();
if !matches!(part_instrument, Instrument::None) {
track.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Midi {
channel: u4::new(channel as u8),
message: MidiMessage::ProgramChange {
program: u7::new(part_instrument as u8),
},
},
});
}
let mut previous_time = 0;
for (current_time, track_events) in notes_per_time {
let mut delta = current_time - previous_time;
// do NoteOffs first
for mut te in track_events.1 {
// TODO: raise error if > maxu28 (use `std::num::Wrapping`?)
te.delta = u28::new(delta as u32);
delta = 0; // the first event at this time has the whole delta but the others have 0
track.push(te);
}
// then NoteOns
for mut te in track_events.0 {
// TODO: raise error if > maxu28
te.delta = u28::new(delta as u32);
delta = 0;
track.push(te);
}
previous_time = current_time;
}
track.push(TrackEvent {
delta: u28::default(),
kind: TrackEventKind::Meta(MetaMessage::EndOfTrack),
});
tracks.push(track);
}
Ok(Smf { header, tracks })
}
}