annotate Syncopation models/midiparser.py @ 6:ac882f5e6a11

adding new bits for midi and music objects
author christopherh <christopher.harte@eecs.qmul.ac.uk>
date Tue, 31 Mar 2015 16:59:45 +0100
parents
children
rev   line source
christopher@6 1 """
christopher@6 2 midi.py -- MIDI classes and parser in Python
christopher@6 3 Placed into the public domain in December 2001 by Will Ware
christopher@6 4 Python MIDI classes: meaningful data structures that represent MIDI
christopher@6 5 events and other objects. You can read MIDI files to create such objects, or
christopher@6 6 generate a collection of objects and use them to write a MIDI file.
christopher@6 7 Helpful MIDI info:
christopher@6 8 http://crystal.apana.org.au/ghansper/midi_introduction/midi_file_form...
christopher@6 9 http://www.argonet.co.uk/users/lenny/midi/mfile.html
christopher@6 10 """
christopher@6 11 import sys, string, types, exceptions
christopher@6 12 debugflag = 0
christopher@6 13
christopher@6 14
christopher@6 15 def showstr(str, n=16):
christopher@6 16 for x in str[:n]:
christopher@6 17 print ('%02x' % ord(x)),
christopher@6 18 print
christopher@6 19
christopher@6 20 def getNumber(str, length):
christopher@6 21 # MIDI uses big-endian for everything
christopher@6 22 sum = 0
christopher@6 23 for i in range(length):
christopher@6 24 sum = (sum << 8) + ord(str[i])
christopher@6 25 return sum, str[length:]
christopher@6 26
christopher@6 27 def getVariableLengthNumber(str):
christopher@6 28 sum = 0
christopher@6 29 i = 0
christopher@6 30 while 1:
christopher@6 31 x = ord(str[i])
christopher@6 32 i = i + 1
christopher@6 33 sum = (sum << 7) + (x & 0x7F)
christopher@6 34 if not (x & 0x80):
christopher@6 35 return sum, str[i:]
christopher@6 36
christopher@6 37 def putNumber(num, length):
christopher@6 38 # MIDI uses big-endian for everything
christopher@6 39 lst = [ ]
christopher@6 40 for i in range(length):
christopher@6 41 n = 8 * (length - 1 - i)
christopher@6 42 lst.append(chr((num >> n) & 0xFF))
christopher@6 43 return string.join(lst, "")
christopher@6 44
christopher@6 45 def putVariableLengthNumber(x):
christopher@6 46 lst = [ ]
christopher@6 47 while 1:
christopher@6 48 y, x = x & 0x7F, x >> 7
christopher@6 49 lst.append(chr(y + 0x80))
christopher@6 50 if x == 0:
christopher@6 51 break
christopher@6 52 lst.reverse()
christopher@6 53 lst[-1] = chr(ord(lst[-1]) & 0x7f)
christopher@6 54 return string.join(lst, "")
christopher@6 55
christopher@6 56
christopher@6 57 class EnumException(exceptions.Exception):
christopher@6 58 pass
christopher@6 59
christopher@6 60 class Enumeration:
christopher@6 61 def __init__(self, enumList):
christopher@6 62 lookup = { }
christopher@6 63 reverseLookup = { }
christopher@6 64 i = 0
christopher@6 65 uniqueNames = [ ]
christopher@6 66 uniqueValues = [ ]
christopher@6 67 for x in enumList:
christopher@6 68 if type(x) == types.TupleType:
christopher@6 69 x, i = x
christopher@6 70 if type(x) != types.StringType:
christopher@6 71 raise EnumException, "enum name is not a string: " + x
christopher@6 72 if type(i) != types.IntType:
christopher@6 73 raise EnumException, "enum value is not an integer: " + i
christopher@6 74 if x in uniqueNames:
christopher@6 75 raise EnumException, "enum name is not unique: " + x
christopher@6 76 if i in uniqueValues:
christopher@6 77 raise EnumException, "enum value is not unique for " + x
christopher@6 78 uniqueNames.append(x)
christopher@6 79 uniqueValues.append(i)
christopher@6 80 lookup[x] = i
christopher@6 81 reverseLookup[i] = x
christopher@6 82 i = i + 1
christopher@6 83 self.lookup = lookup
christopher@6 84 self.reverseLookup = reverseLookup
christopher@6 85 def __add__(self, other):
christopher@6 86 lst = [ ]
christopher@6 87 for k in self.lookup.keys():
christopher@6 88 lst.append((k, self.lookup[k]))
christopher@6 89 for k in other.lookup.keys():
christopher@6 90 lst.append((k, other.lookup[k]))
christopher@6 91 return Enumeration(lst)
christopher@6 92 def hasattr(self, attr):
christopher@6 93 return self.lookup.has_key(attr)
christopher@6 94 def has_value(self, attr):
christopher@6 95 return self.reverseLookup.has_key(attr)
christopher@6 96 def __getattr__(self, attr):
christopher@6 97 if not self.lookup.has_key(attr):
christopher@6 98 raise AttributeError
christopher@6 99 return self.lookup[attr]
christopher@6 100 def whatis(self, value):
christopher@6 101 return self.reverseLookup[value]
christopher@6 102
christopher@6 103
christopher@6 104 channelVoiceMessages = Enumeration([("NOTE_OFF", 0x80),
christopher@6 105 ("NOTE_ON", 0x90),
christopher@6 106 ("POLYPHONIC_KEY_PRESSURE", 0xA0),
christopher@6 107 ("CONTROLLER_CHANGE", 0xB0),
christopher@6 108 ("PROGRAM_CHANGE", 0xC0),
christopher@6 109 ("CHANNEL_KEY_PRESSURE", 0xD0),
christopher@6 110 ("PITCH_BEND", 0xE0)])
christopher@6 111
christopher@6 112 channelModeMessages = Enumeration([("ALL_SOUND_OFF", 0x78),
christopher@6 113 ("RESET_ALL_CONTROLLERS", 0x79),
christopher@6 114 ("LOCAL_CONTROL", 0x7A),
christopher@6 115 ("ALL_NOTES_OFF", 0x7B),
christopher@6 116 ("OMNI_MODE_OFF", 0x7C),
christopher@6 117 ("OMNI_MODE_ON", 0x7D),
christopher@6 118 ("MONO_MODE_ON", 0x7E),
christopher@6 119 ("POLY_MODE_ON", 0x7F)])
christopher@6 120 metaEvents = Enumeration([("SEQUENCE_NUMBER", 0x00),
christopher@6 121 ("TEXT_EVENT", 0x01),
christopher@6 122 ("COPYRIGHT_NOTICE", 0x02),
christopher@6 123 ("SEQUENCE_TRACK_NAME", 0x03),
christopher@6 124 ("INSTRUMENT_NAME", 0x04),
christopher@6 125 ("LYRIC", 0x05),
christopher@6 126 ("MARKER", 0x06),
christopher@6 127 ("CUE_POINT", 0x07),
christopher@6 128 ("MIDI_CHANNEL_PREFIX", 0x20),
christopher@6 129 ("MIDI_PORT", 0x21),
christopher@6 130 ("END_OF_TRACK", 0x2F),
christopher@6 131 ("SET_TEMPO", 0x51),
christopher@6 132 ("SMTPE_OFFSET", 0x54),
christopher@6 133 ("TIME_SIGNATURE", 0x58),
christopher@6 134 ("KEY_SIGNATURE", 0x59),
christopher@6 135 ("SEQUENCER_SPECIFIC_META_EVENT", 0x7F)])
christopher@6 136
christopher@6 137
christopher@6 138 # runningStatus appears to want to be an attribute of a MidiTrack. But
christopher@6 139 # it doesn't seem to do any harm to implement it as a global.
christopher@6 140 runningStatus = None
christopher@6 141 class MidiEvent:
christopher@6 142 def __init__(self, track):
christopher@6 143 self.track = track
christopher@6 144 self.time = None
christopher@6 145 self.channel = self.pitch = self.velocity = self.data = None
christopher@6 146 def __cmp__(self, other):
christopher@6 147 # assert self.time != None and other.time != None
christopher@6 148 return cmp(self.time, other.time)
christopher@6 149 def __repr__(self):
christopher@6 150 r = ("<MidiEvent %s, t=%s, track=%s, channel=%s" %
christopher@6 151 (self.type,
christopher@6 152 repr(self.time),
christopher@6 153 self.track.index,
christopher@6 154 repr(self.channel)))
christopher@6 155 for attrib in ["pitch", "data", "velocity"]:
christopher@6 156 if getattr(self, attrib) != None:
christopher@6 157 r = r + ", " + attrib + "=" + repr(getattr(self, attrib))
christopher@6 158 return r + ">"
christopher@6 159 def read(self, time, str):
christopher@6 160 global runningStatus
christopher@6 161 self.time = time
christopher@6 162 # do we need to use running status?
christopher@6 163 if not (ord(str[0]) & 0x80):
christopher@6 164 str = runningStatus + str
christopher@6 165 runningStatus = x = str[0]
christopher@6 166 x = ord(x)
christopher@6 167 y = x & 0xF0
christopher@6 168 z = ord(str[1])
christopher@6 169 if channelVoiceMessages.has_value(y):
christopher@6 170 self.channel = (x & 0x0F) + 1
christopher@6 171 self.type = channelVoiceMessages.whatis(y)
christopher@6 172 if (self.type == "PROGRAM_CHANGE" or
christopher@6 173 self.type == "CHANNEL_KEY_PRESSURE"):
christopher@6 174 self.data = z
christopher@6 175 return str[2:]
christopher@6 176 else:
christopher@6 177 self.pitch = z
christopher@6 178 self.velocity = ord(str[2])
christopher@6 179 channel = self.track.channels[self.channel - 1]
christopher@6 180 if (self.type == "NOTE_OFF" or
christopher@6 181 (self.velocity == 0 and self.type == "NOTE_ON")):
christopher@6 182 channel.noteOff(self.pitch, self.time)
christopher@6 183 elif self.type == "NOTE_ON":
christopher@6 184 channel.noteOn(self.pitch, self.time, self.velocity)
christopher@6 185 return str[3:]
christopher@6 186 elif y == 0xB0 and channelModeMessages.has_value(z):
christopher@6 187 self.channel = (x & 0x0F) + 1
christopher@6 188 self.type = channelModeMessages.whatis(z)
christopher@6 189 if self.type == "LOCAL_CONTROL":
christopher@6 190 self.data = (ord(str[2]) == 0x7F)
christopher@6 191 elif self.type == "MONO_MODE_ON":
christopher@6 192 self.data = ord(str[2])
christopher@6 193 return str[3:]
christopher@6 194 elif x == 0xF0 or x == 0xF7:
christopher@6 195 self.type = {0xF0: "F0_SYSEX_EVENT",
christopher@6 196 0xF7: "F7_SYSEX_EVENT"}[x]
christopher@6 197 length, str = getVariableLengthNumber(str[1:])
christopher@6 198 self.data = str[:length]
christopher@6 199 return str[length:]
christopher@6 200 elif x == 0xFF:
christopher@6 201 if not metaEvents.has_value(z):
christopher@6 202 print "Unknown meta event: FF %02X" % z
christopher@6 203 sys.stdout.flush()
christopher@6 204 raise "Unknown midi event type"
christopher@6 205 self.type = metaEvents.whatis(z)
christopher@6 206 length, str = getVariableLengthNumber(str[2:])
christopher@6 207 self.data = str[:length]
christopher@6 208 return str[length:]
christopher@6 209 raise "Unknown midi event type"
christopher@6 210 def write(self):
christopher@6 211 sysex_event_dict = {"F0_SYSEX_EVENT": 0xF0,
christopher@6 212 "F7_SYSEX_EVENT": 0xF7}
christopher@6 213 if channelVoiceMessages.hasattr(self.type):
christopher@6 214 x = chr((self.channel - 1) +
christopher@6 215 getattr(channelVoiceMessages, self.type))
christopher@6 216 if (self.type != "PROGRAM_CHANGE" and
christopher@6 217 self.type != "CHANNEL_KEY_PRESSURE"):
christopher@6 218 data = chr(self.pitch) + chr(self.velocity)
christopher@6 219 else:
christopher@6 220 data = chr(self.data)
christopher@6 221 return x + data
christopher@6 222 elif channelModeMessages.hasattr(self.type):
christopher@6 223 x = getattr(channelModeMessages, self.type)
christopher@6 224 x = (chr(0xB0 + (self.channel - 1)) +
christopher@6 225 chr(x) +
christopher@6 226 chr(self.data))
christopher@6 227 return x
christopher@6 228 elif sysex_event_dict.has_key(self.type):
christopher@6 229 str = chr(sysex_event_dict[self.type])
christopher@6 230 str = str + putVariableLengthNumber(len(self.data))
christopher@6 231 return str + self.data
christopher@6 232 elif metaEvents.hasattr(self.type):
christopher@6 233 str = chr(0xFF) + chr(getattr(metaEvents, self.type))
christopher@6 234 str = str + putVariableLengthNumber(len(self.data))
christopher@6 235 return str + self.data
christopher@6 236 else:
christopher@6 237 raise "unknown midi event type: " + self.type
christopher@6 238
christopher@6 239
christopher@6 240
christopher@6 241 """
christopher@6 242 register_note() is a hook that can be overloaded from a script that
christopher@6 243 imports this module. Here is how you might do that, if you wanted to
christopher@6 244 store the notes as tuples in a list. Including the distinction
christopher@6 245 between track and channel offers more flexibility in assigning voices.
christopher@6 246 import midi
christopher@6 247 notelist = [ ]
christopher@6 248 def register_note(t, c, p, v, t1, t2):
christopher@6 249 notelist.append((t, c, p, v, t1, t2))
christopher@6 250 midi.register_note = register_note
christopher@6 251 """
christopher@6 252 def register_note(track_index, channel_index, pitch, velocity,
christopher@6 253 keyDownTime, keyUpTime):
christopher@6 254 pass
christopher@6 255
christopher@6 256
christopher@6 257
christopher@6 258 class MidiChannel:
christopher@6 259 """A channel (together with a track) provides the continuity connecting
christopher@6 260 a NOTE_ON event with its corresponding NOTE_OFF event. Together, those
christopher@6 261 define the beginning and ending times for a Note."""
christopher@6 262 def __init__(self, track, index):
christopher@6 263 self.index = index
christopher@6 264 self.track = track
christopher@6 265 self.pitches = { }
christopher@6 266 def __repr__(self):
christopher@6 267 return "<MIDI channel %d>" % self.index
christopher@6 268 def noteOn(self, pitch, time, velocity):
christopher@6 269 self.pitches[pitch] = (time, velocity)
christopher@6 270 def noteOff(self, pitch, time):
christopher@6 271 if self.pitches.has_key(pitch):
christopher@6 272 keyDownTime, velocity = self.pitches[pitch]
christopher@6 273 register_note(self.track.index, self.index, pitch, velocity,
christopher@6 274 keyDownTime, time)
christopher@6 275 del self.pitches[pitch]
christopher@6 276 # The case where the pitch isn't in the dictionary is illegal,
christopher@6 277 # I think, but we probably better just ignore it.
christopher@6 278
christopher@6 279
christopher@6 280 class DeltaTime(MidiEvent):
christopher@6 281 type = "DeltaTime"
christopher@6 282 def read(self, oldstr):
christopher@6 283 self.time, newstr = getVariableLengthNumber(oldstr)
christopher@6 284 return self.time, newstr
christopher@6 285 def write(self):
christopher@6 286 str = putVariableLengthNumber(self.time)
christopher@6 287 return str
christopher@6 288
christopher@6 289
christopher@6 290 class MidiTrack:
christopher@6 291 def __init__(self, index):
christopher@6 292 self.index = index
christopher@6 293 self.events = [ ]
christopher@6 294 self.channels = [ ]
christopher@6 295 self.length = 0
christopher@6 296 for i in range(16):
christopher@6 297 self.channels.append(MidiChannel(self, i+1))
christopher@6 298 def read(self, str):
christopher@6 299 time = 0
christopher@6 300 assert str[:4] == "MTrk"
christopher@6 301 length, str = getNumber(str[4:], 4)
christopher@6 302 self.length = length
christopher@6 303 mystr = str[:length]
christopher@6 304 remainder = str[length:]
christopher@6 305 while mystr:
christopher@6 306 delta_t = DeltaTime(self)
christopher@6 307 dt, mystr = delta_t.read(mystr)
christopher@6 308 time = time + dt
christopher@6 309 self.events.append(delta_t)
christopher@6 310 e = MidiEvent(self)
christopher@6 311 mystr = e.read(time, mystr)
christopher@6 312 self.events.append(e)
christopher@6 313 return remainder
christopher@6 314 def write(self):
christopher@6 315 time = self.events[0].time
christopher@6 316 # build str using MidiEvents
christopher@6 317 str = ""
christopher@6 318 for e in self.events:
christopher@6 319 str = str + e.write()
christopher@6 320 return "MTrk" + putNumber(len(str), 4) + str
christopher@6 321 def __repr__(self):
christopher@6 322 r = "<MidiTrack %d -- %d events\n" % (self.index, len(self.events))
christopher@6 323 for e in self.events:
christopher@6 324 r = r + " " + `e` + "\n"
christopher@6 325 return r + " >"
christopher@6 326
christopher@6 327
christopher@6 328
christopher@6 329 class MidiFile:
christopher@6 330 def __init__(self):
christopher@6 331 self.file = None
christopher@6 332 self.format = 1
christopher@6 333 self.tracks = [ ]
christopher@6 334 self.ticksPerQuarterNote = None
christopher@6 335 self.ticksPerSecond = None
christopher@6 336 def open(self, filename, attrib="rb"):
christopher@6 337 if filename == None:
christopher@6 338 if attrib in ["r", "rb"]:
christopher@6 339 self.file = sys.stdin
christopher@6 340 else:
christopher@6 341 self.file = sys.stdout
christopher@6 342 else:
christopher@6 343 self.file = open(filename, attrib)
christopher@6 344 def __repr__(self):
christopher@6 345 r = "<MidiFile %d tracks\n" % len(self.tracks)
christopher@6 346 for t in self.tracks:
christopher@6 347 r = r + " " + `t` + "\n"
christopher@6 348 return r + ">"
christopher@6 349 def close(self):
christopher@6 350 self.file.close()
christopher@6 351 def read(self):
christopher@6 352 self.readstr(self.file.read())
christopher@6 353 def readstr(self, str):
christopher@6 354 assert str[:4] == "MThd"
christopher@6 355 length, str = getNumber(str[4:], 4)
christopher@6 356 assert length == 6
christopher@6 357 format, str = getNumber(str, 2)
christopher@6 358 self.format = format
christopher@6 359 assert format == 0 or format == 1 # dunno how to handle 2
christopher@6 360 numTracks, str = getNumber(str, 2)
christopher@6 361 division, str = getNumber(str, 2)
christopher@6 362 if division & 0x8000:
christopher@6 363 framesPerSecond = -((division >> 8) | -128)
christopher@6 364 ticksPerFrame = division & 0xFF
christopher@6 365 assert ticksPerFrame == 24 or ticksPerFrame == 25 or \
christopher@6 366 ticksPerFrame == 29 or ticksPerFrame == 30
christopher@6 367 if ticksPerFrame == 29: ticksPerFrame = 30 # drop frame
christopher@6 368 self.ticksPerSecond = ticksPerFrame * framesPerSecond
christopher@6 369 else:
christopher@6 370 self.ticksPerQuarterNote = division & 0x7FFF
christopher@6 371 for i in range(numTracks):
christopher@6 372 trk = MidiTrack(i)
christopher@6 373 str = trk.read(str)
christopher@6 374 self.tracks.append(trk)
christopher@6 375 def write(self):
christopher@6 376 self.file.write(self.writestr())
christopher@6 377 def writestr(self):
christopher@6 378 division = self.ticksPerQuarterNote
christopher@6 379 # Don't handle ticksPerSecond yet, too confusing
christopher@6 380 assert (division & 0x8000) == 0
christopher@6 381 str = "MThd" + putNumber(6, 4) + putNumber(self.format, 2)
christopher@6 382 str = str + putNumber(len(self.tracks), 2)
christopher@6 383 str = str + putNumber(division, 2)
christopher@6 384 for trk in self.tracks:
christopher@6 385 str = str + trk.write()
christopher@6 386 return str
christopher@6 387
christopher@6 388
christopher@6 389 def main(argv):
christopher@6 390 global debugflag
christopher@6 391 import getopt
christopher@6 392 infile = None
christopher@6 393 outfile = None
christopher@6 394 printflag = 0
christopher@6 395 optlist, args = getopt.getopt(argv[1:], "i:o:pd")
christopher@6 396 for (option, value) in optlist:
christopher@6 397 if option == '-i':
christopher@6 398 infile = value
christopher@6 399 elif option == '-o':
christopher@6 400 outfile = value
christopher@6 401 elif option == '-p':
christopher@6 402 printflag = 1
christopher@6 403 elif option == '-d':
christopher@6 404 debugflag = 1
christopher@6 405 m = MidiFile()
christopher@6 406 m.open(infile)
christopher@6 407 m.read()
christopher@6 408 m.close()
christopher@6 409 if printflag:
christopher@6 410 print m
christopher@6 411 else:
christopher@6 412 m.open(outfile, "wb")
christopher@6 413 m.write()
christopher@6 414 m.close()
christopher@6 415
christopher@6 416
christopher@6 417 if __name__ == "__main__":
christopher@6 418 main(sys.argv)
christopher@6 419
christopher@6 420