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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use std::error;
use std::io::{Error,Read};
use std::fmt;
use std::string::FromUtf8Error;
use reader::SMFReader;
use num::FromPrimitive;
use util::{read_byte,read_amount};
#[derive(Debug)]
pub enum MetaError {
InvalidCommand(u8),
OtherErr(&'static str),
Error(Error),
}
impl From<Error> for MetaError {
fn from(err: Error) -> MetaError {
MetaError::Error(err)
}
}
impl error::Error for MetaError {
fn description(&self) -> &str {
match *self {
MetaError::InvalidCommand(_) => "Invalid meta command",
MetaError::OtherErr(_) => "A general midi error has occured",
MetaError::Error(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
MetaError::Error(ref err) => Some(err as &error::Error),
_ => None,
}
}
}
impl fmt::Display for MetaError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
MetaError::InvalidCommand(ref c) => write!(f,"Invalid Meta command: {}",c),
MetaError::OtherErr(ref s) => write!(f,"Meta Error: {}",s),
MetaError::Error(ref e) => write!(f,"{}",e),
}
}
}
enum_from_primitive! {
#[derive(Clone,Copy,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub enum MetaCommand {
SequenceNumber = 0x00,
TextEvent = 0x01,
CopyrightNotice = 0x02,
SequenceOrTrackName = 0x03,
InstrumentName = 0x04,
LyricText = 0x05,
MarkerText = 0x06,
CuePoint = 0x07,
MIDIChannelPrefixAssignment = 0x20,
MIDIPortPrefixAssignment = 0x21,
EndOfTrack = 0x2F,
TempoSetting = 0x51,
SMPTEOffset = 0x54,
TimeSignature = 0x58,
KeySignature = 0x59,
SequencerSpecificEvent = 0x7F,
Unknown,
}
}
#[derive(Debug)]
pub struct MetaEvent {
pub command: MetaCommand,
pub length: u64,
pub data: Vec<u8>,
}
impl Clone for MetaEvent {
fn clone(&self) -> MetaEvent {
MetaEvent {
command: self.command,
length: self.length,
data: self.data.clone(),
}
}
}
impl fmt::Display for MetaEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Meta Event: {}",
match self.command {
MetaCommand::SequenceNumber => format!("Sequence Number"),
MetaCommand::TextEvent => {
format!("Text Event. Len: {} Text: Foo",self.length)
},
MetaCommand::CopyrightNotice => format!("Copyright Notice"),
MetaCommand::SequenceOrTrackName => {
let text = match String::from_utf8(self.data.clone()) {
Ok(s) => s,
Err(_) => format!("[invalid string data]"),
};
format!("Sequence/Track Name, length: {}, name: {}",self.length,text)
},
MetaCommand::InstrumentName => {
let text = match String::from_utf8(self.data.clone()) {
Ok(s) => s,
Err(_) => format!("[invalid string data]"),
};
format!("InstrumentName: {}",text)
},
MetaCommand::LyricText => format!("LyricText"),
MetaCommand::MarkerText => format!("MarkerText"),
MetaCommand::CuePoint => format!("CuePoint"),
MetaCommand::MIDIChannelPrefixAssignment => format!("MIDI Channel Prefix Assignment, channel: {}", self.data[0]+1),
MetaCommand::MIDIPortPrefixAssignment => format!("MIDI Port Prefix Assignment, port: {}", self.data[0]),
MetaCommand::EndOfTrack => format!("End Of Track"),
MetaCommand::TempoSetting => format!("Set Tempo, microseconds/quarter note: {}",self.data_as_u64(3)),
MetaCommand::SMPTEOffset => format!("SMPTEOffset"),
MetaCommand::TimeSignature => format!("Time Signature: {}/{}, {} ticks/metronome click, {} 32nd notes/quarter note",
self.data[0],
2usize.pow(self.data[1] as u32),
self.data[2],
self.data[3]),
MetaCommand::KeySignature => format!("Key Signature, {} sharps/flats, {}",
self.data[0] as i8,
match self.data[1] {
0 => "Major",
1 => "Minor",
_ => "Invalid Signature",
}),
MetaCommand::SequencerSpecificEvent => format!("SequencerSpecificEvent"),
MetaCommand::Unknown => format!("Unknown, length: {}",self.data.len()),
})
}
}
impl MetaEvent {
pub fn data_as_u64(&self,bytes: usize) -> u64 {
let mut res = 0;
for i in 0..bytes {
res <<= 8;
res |= self.data[i] as u64;
}
res
}
pub fn data_as_text(&self) -> Result<String,FromUtf8Error> {
String::from_utf8(self.data.clone())
}
pub fn next_event(reader: &mut Read) -> Result<MetaEvent, MetaError> {
let command =
match MetaCommand::from_u8(try!(read_byte(reader))) {
Some(c) => {c},
None => MetaCommand::Unknown,
};
let len = match SMFReader::read_vtime(reader) {
Ok(t) => { t }
Err(_) => { return Err(MetaError::OtherErr("Couldn't read time for meta command")); }
};
let mut data = Vec::new();
try!(read_amount(reader,&mut data,len as usize));
Ok(MetaEvent{
command: command,
length: len,
data: data
})
}
fn u16_to_vec(val: u16) -> Vec<u8> {
let mut res = Vec::with_capacity(2);
res.push((val >> 8) as u8);
res.push(val as u8);
res
}
fn u24_to_vec(val: u32) -> Vec<u8> {
assert!(val <= 2u32.pow(24));
let mut res = Vec::with_capacity(3);
res.push((val >> 16) as u8);
res.push((val >> 8) as u8);
res.push(val as u8);
res
}
pub fn sequence_number(sequence_number: u16) -> MetaEvent {
MetaEvent {
command: MetaCommand::SequenceNumber,
length: 0x02,
data: MetaEvent::u16_to_vec(sequence_number),
}
}
pub fn text_event(text: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::TextEvent,
length: text.len() as u64,
data: text.into_bytes(),
}
}
pub fn copyright_notice(copyright: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::CopyrightNotice,
length: copyright.len() as u64,
data: copyright.into_bytes(),
}
}
pub fn sequence_or_track_name(name: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::SequenceOrTrackName,
length: name.len() as u64,
data: name.into_bytes(),
}
}
pub fn instrument_name(name: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::InstrumentName,
length: name.len() as u64,
data: name.into_bytes(),
}
}
pub fn lyric_text(text: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::LyricText,
length: text.len() as u64,
data: text.into_bytes(),
}
}
pub fn marker_text(text: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::MarkerText,
length: text.len() as u64,
data: text.into_bytes(),
}
}
pub fn cue_point(text: String) -> MetaEvent {
MetaEvent {
command: MetaCommand::CuePoint,
length: text.len() as u64,
data: text.into_bytes(),
}
}
pub fn midichannel_prefix_assignment(channel: u8) -> MetaEvent {
MetaEvent {
command: MetaCommand::MIDIChannelPrefixAssignment,
length: 1,
data: vec![channel],
}
}
pub fn midiport_prefix_assignment(port: u8) -> MetaEvent {
MetaEvent {
command: MetaCommand::MIDIPortPrefixAssignment,
length: 1,
data: vec![port],
}
}
pub fn end_of_track() -> MetaEvent {
MetaEvent {
command: MetaCommand::EndOfTrack,
length: 0,
data: vec![],
}
}
pub fn tempo_setting(tempo: u32) -> MetaEvent {
MetaEvent {
command: MetaCommand::TempoSetting,
length: 3,
data: MetaEvent::u24_to_vec(tempo),
}
}
pub fn smpte_offset(hours: u8, minutes: u8, seconds: u8, frames: u8, fractional: u8) -> MetaEvent {
MetaEvent {
command: MetaCommand::SMPTEOffset,
length: 5,
data: vec![hours,minutes,seconds,frames,fractional],
}
}
pub fn time_signature(numerator: u8, denominator: u8, clocks_per_tick: u8, num_32nd_notes_per_24_clocks: u8) -> MetaEvent {
MetaEvent {
command: MetaCommand::TimeSignature,
length: 4,
data: vec![numerator,denominator,clocks_per_tick,num_32nd_notes_per_24_clocks],
}
}
pub fn key_signature(sharps_flats: u8, major_minor: u8) -> MetaEvent {
MetaEvent {
command: MetaCommand::KeySignature,
length: 2,
data: vec![sharps_flats, major_minor],
}
}
pub fn sequencer_specific_event(data: Vec<u8>) -> MetaEvent {
MetaEvent {
command: MetaCommand::SequencerSpecificEvent,
length: data.len() as u64,
data: data,
}
}
}