/
base.py
1525 lines (1238 loc) · 50.3 KB
/
base.py
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: midi.base.py
# Purpose: music21 classes for dealing with midi data
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
# (Will Ware -- see docs)
#
# Copyright: Copyright © 2011-2012 Michael Scott Cuthbert and the music21 Project
# Some parts of this module are in the Public Domain, see details.
# License: LGPL, see license.txt
#-------------------------------------------------------------------------------
'''
Objects and tools for processing MIDI data. Converts from MIDI files to
:class:`~music21.midi.MidiEvent`, :class:`~music21.midi.MidiTrack`, and
:class:`~music21.midi.MidiFile` objects, and vice-versa.
Further conversion to-and-from MidiEvent/MidiTrack/MidiFile and music21 Stream,
Note, etc., objects takes place in :ref:`moduleMidiTranslate`.
This module uses routines from Will Ware's public domain midi.py library from 2001
see http://groups.google.com/group/alt.sources/msg/0c5fc523e050c35e
'''
import unittest
import unicodedata
import sys, os, string, types
import struct
try:
import StringIO # python 2
except ImportError:
from io import StringIO # python3 (also in python 2.6+)
from music21 import common
from music21 import exceptions21
from music21 import environment
_MOD = "midi.base.py"
environLocal = environment.Environment(_MOD)
# good midi reference:
# http://www.sonicspot.com/guide/midifiles.html
#-------------------------------------------------------------------------------
class EnumerationException(exceptions21.Music21Exception):
pass
class MidiException(exceptions21.Music21Exception):
pass
#-------------------------------------------------------------------------------
# def showstr(str, n=16):
# for x in str[:n]:
# print (('%02x' % ord(x)),)
# print("")
def charToBinary(char):
'''
Convert a char into its binary representation. Useful for debugging.
>>> midi.charToBinary('a')
'01100001'
'''
ascii = ord(char)
binaryDigits = []
while (ascii > 0):
if (ascii & 1) == 1:
binaryDigits.append("1")
else:
binaryDigits.append("0")
ascii = ascii >> 1
binaryDigits.reverse()
binary = ''.join(binaryDigits)
zerofix = (8 - len(binary)) * '0'
return zerofix + binary
def intsToHexString(intList):
'''
Convert a list of integers into a hex string, suitable for testing MIDI encoding.
>>> # note on, middle c, 120 velocity
>>> midi.intsToHexString([144, 60, 120])
'\\x90<x'
'''
# note off are 128 to 143
# note on messages are decimal 144 to 159
post = ''
for i in intList:
# B is an unsigned char
# this forces values between 0 and 255
# the same as chr(int)
post += struct.pack(">B", i)
return post
def getNumber(midiStr, length):
'''
Return the value of a string byte or bytes if length > 1
from an 8-bit string.
Then, return the remaining string.
The `length` is the number of chars to read.
This will sum a length greater than 1 if desired.
Note that MIDI uses big-endian for everything.
This is the inverse of Python's chr() function.
>>> midi.getNumber('test', 0)
(0, 'test')
>>> midi.getNumber('test', 2)
(29797, 'st')
>>> midi.getNumber('test', 4)
(1952805748, '')
'''
summation = 0
for i in range(length):
summation = (summation << 8) + ord(midiStr[i])
return summation, midiStr[length:]
def getVariableLengthNumber(midiStr):
r'''
Given a string of data, strip off a the first character, or all high-byte characters
terminating with one whose ord() function is < 0x80. Thus a variable number of bytes
might be read.
After finding the appropriate termination,
return the remaining string.
This necessary as DeltaTime times are given with variable size,
and thus may be if different numbers of characters are used.
>>> midi.getVariableLengthNumber('A-u')
(65, '-u')
>>> midi.getVariableLengthNumber('-u')
(45, 'u')
>>> midi.getVariableLengthNumber('u')
(117, '')
>>> midi.getVariableLengthNumber('test')
(116, 'est')
>>> midi.getVariableLengthNumber('E@-E')
(69, '@-E')
>>> midi.getVariableLengthNumber('@-E')
(64, '-E')
>>> midi.getVariableLengthNumber('-E')
(45, 'E')
>>> midi.getVariableLengthNumber('E')
(69, '')
Test that variable length characters work:
>>> midi.getVariableLengthNumber('\xff\x7f')
(16383, '')
>>> midi.getVariableLengthNumber(u'中xy')
(210638584, u'y')
If no low-byte character is encoded, raises an IndexError
>>> midi.getVariableLengthNumber(u'中国')
Traceback (most recent call last):
IndexError: string index out of range
'''
# from http://faydoc.tripod.com/formats/mid.htm
# This allows the number to be read one byte at a time, and when you see a msb of 0, you know that it was the last (least significant) byte of the number.
# additional reference here:
# http://253.ccarh.org/handout/vlv/
summation = 0
i = 0
while True:
x = ord(midiStr[i])
#environLocal.printDebug(['getVariableLengthNumber: examined char:', charToBinary(midiStr[i])])
summation = (summation << 7) + (x & 0x7F)
i += 1
if not (x & 0x80):
#environLocal.printDebug(['getVariableLengthNumber: depth read into string: %s' % i])
return summation, midiStr[i:]
def getNumbersAsList(midiStr):
'''
Translate each char into a number, return in a list.
Used for reading data messages where each byte encodes
a different discrete value.
>>> midi.getNumbersAsList('\\x00\\x00\\x00\\x03')
[0, 0, 0, 3]
'''
post = []
for i in range(len(midiStr)):
post.append(ord(midiStr[i]))
return post
def putNumber(num, length):
'''
Put a single number as a hex number at the end of a string `length` bytes long.
>>> midi.putNumber(3, 4)
'\\x00\\x00\\x00\\x03'
>>> midi.putNumber(0, 1)
'\\x00'
'''
lst = []
for i in range(length):
n = 8 * (length - 1 - i)
lst.append(chr((num >> n) & 0xFF))
return string.join(lst, "")
def putVariableLengthNumber(x):
'''
>>> midi.putVariableLengthNumber(4)
'\\x04'
>>> midi.putVariableLengthNumber(127)
'\\x7f'
>>> midi.putVariableLengthNumber(0)
'\\x00'
>>> midi.putVariableLengthNumber(1024)
'\\x88\\x00'
>>> midi.putVariableLengthNumber(8192)
'\\xc0\\x00'
>>> midi.putVariableLengthNumber(16383)
'\\xff\\x7f'
>>> midi.putVariableLengthNumber(-1)
Traceback (most recent call last):
MidiException: cannot putVariableLengthNumber() when number is negative: -1
'''
#environLocal.printDebug(['calling putVariableLengthNumber(x) with', x])
# note: negative numbers will cause an infinite loop here
if x < 0:
raise MidiException('cannot putVariableLengthNumber() when number is negative: %s' % x)
lst = [ ]
while True:
y, x = x & 0x7F, x >> 7
lst.append(chr(y + 0x80))
if x == 0:
break
lst.reverse()
lst[-1] = chr(ord(lst[-1]) & 0x7f)
return string.join(lst, "")
def putNumbersAsList(numList):
'''
Translate a list of numbers (0-255) into a character byte strings.
Used for encoding data messages where each byte encodes a different discrete value.
>>> midi.putNumbersAsList([0, 0, 0, 3])
'\\x00\\x00\\x00\\x03'
If a number is < 0 but >= -256 then it wraps around from the top.
>>> midi.putNumbersAsList([0, 0, 0, -3])
'\\x00\\x00\\x00\\xfd'
>>> midi.putNumbersAsList([0, 0, 0, -1])
'\\x00\\x00\\x00\\xff'
'''
post = []
for n in numList:
# assume if a number exceeds range count down from top?
if n < 0:
n = 256 + n # -1 will be 255
post.append(chr(n))
return ''.join(post)
#-------------------------------------------------------------------------------
class Enumeration(object):
'''
Utility object for defining binary MIDI message constants.
'''
def __init__(self, enumList = None):
if enumList is None:
enumList = []
lookup = { }
reverseLookup = {}
i = 0
uniqueNames = [ ]
uniqueValues = [ ]
for x in enumList:
if type(x) == types.TupleType:
x, i = x
if type(x) != types.StringType:
raise EnumerationException("enum name is not a string: " + x)
if type(i) != types.IntType:
raise EnumerationException("enum value is not an integer: " + i)
if x in uniqueNames:
raise EnumerationException("enum name is not unique: " + x)
if i in uniqueValues:
raise EnumerationException("enum value is not unique for " + x)
uniqueNames.append(x)
uniqueValues.append(i)
lookup[x] = i
reverseLookup[i] = x
i = i + 1
self.lookup = lookup
self.reverseLookup = reverseLookup
def __add__(self, other):
lst = [ ]
for k in self.lookup:
lst.append((k, self.lookup[k]))
for k in other.lookup:
lst.append((k, other.lookup[k]))
return Enumeration(lst)
def hasattr(self, attr):
if attr in self.lookup:
return True
return False
#return self.lookup.has_key(attr)
def hasValue(self, attr):
if attr in self.reverseLookup:
return True
return False
#return self.reverseLookup.has_key(attr)
def __getattr__(self, attr):
if not self.lookup.has_key(attr):
raise AttributeError
return self.lookup[attr]
def whatis(self, value):
post = self.reverseLookup[value]
#environLocal.printDebug(['whatis() call: post', post])
return post
channelVoiceMessages = Enumeration([("NOTE_OFF", 0x80),
("NOTE_ON", 0x90),
("POLYPHONIC_KEY_PRESSURE", 0xA0),
("CONTROLLER_CHANGE", 0xB0),
("PROGRAM_CHANGE", 0xC0),
("CHANNEL_KEY_PRESSURE", 0xD0),
("PITCH_BEND", 0xE0)])
channelModeMessages = Enumeration([("ALL_SOUND_OFF", 0x78),
("RESET_ALL_CONTROLLERS", 0x79),
("LOCAL_CONTROL", 0x7A),
("ALL_NOTES_OFF", 0x7B),
("OMNI_MODE_OFF", 0x7C),
("OMNI_MODE_ON", 0x7D),
("MONO_MODE_ON", 0x7E),
("POLY_MODE_ON", 0x7F)])
metaEvents = Enumeration([("SEQUENCE_NUMBER", 0x00),
("TEXT_EVENT", 0x01),
("COPYRIGHT_NOTICE", 0x02),
("SEQUENCE_TRACK_NAME", 0x03),
("INSTRUMENT_NAME", 0x04),
("LYRIC", 0x05),
("MARKER", 0x06),
("CUE_POINT", 0x07),
("PROGRAM_NAME", 0x08), #optional event is used to embed the patch/program name that is called up by the immediately subsequent Bank Select and Program Change messages. It serves to aid the end user in making an intelligent program choice when using different hardware.
("SOUND_SET_UNSUPPORTED", 0x09),
("MIDI_CHANNEL_PREFIX", 0x20),
("MIDI_PORT", 0x21),
("END_OF_TRACK", 0x2F),
("SET_TEMPO", 0x51),
("SMTPE_OFFSET", 0x54),
("TIME_SIGNATURE", 0x58),
("KEY_SIGNATURE", 0x59),
("SEQUENCER_SPECIFIC_META_EVENT", 0x7F)])
#-------------------------------------------------------------------------------
class MidiEvent(object):
'''
A model of a MIDI event, including note-on, note-off, program change,
controller change, any many others.
MidiEvent objects are paired (preceded) by :class:`~music21.midi.base.DeltaTime`
objects in the list of events in a MidiTrack object.
The `track` argument must be a :class:`~music21.midi.base.MidiTrack` object.
The `type` attribute is a string representation of a Midi event from the channelVoiceMessages
or metaEvents definitions.
The `channel` attribute is an integer channel id, from 1 to 16.
The `time` attribute is an integer duration of the event in ticks. This value
can be zero. This value is not essential, as ultimate time positioning is
determined by :class:`~music21.midi.base.DeltaTime` objects.
The `pitch` attribute is only defined for note-on and note-off messages.
The attribute stores an integer representation (0-127, with 60 = middle C).
The `velocity` attribute is only defined for note-on and note-off messages.
The attribute stores an integer representation (0-127). A note-on message with
velocity 0 is generally assumed to be the same as a note-off message.
The `data` attribute is used for storing other messages,
such as SEQUENCE_TRACK_NAME string values.
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> me1.type = "NOTE_ON"
>>> me1.channel = 3
>>> me1.time = 200
>>> me1.pitch = 60
>>> me1.velocity = 120
>>> me1
<MidiEvent NOTE_ON, t=200, track=1, channel=3, pitch=60, velocity=120>
>>> me2 = midi.MidiEvent(mt)
>>> me2.type = "SEQUENCE_TRACK_NAME"
>>> me2.time = 0
>>> me2.data = 'guitar'
>>> me2
<MidiEvent SEQUENCE_TRACK_NAME, t=0, track=1, channel=None, data='guitar'>
'''
def __init__(self, track, type=None, time=None, channel=None): #@ReservedAssignment
self.track = track # a MidiTrack object
self.type = type
self.time = time
self.channel = channel
self._parameter1 = None # pitch or first data value
self._parameter2 = None # velocity or second data value
# data is a property...
# if this is a Note on/off, need to store original
# pitch space value in order to determine if this is has a microtone
self.centShift = None
# store a reference to a corresponding event
# if a noteOn, store the note off, and vice versa
self.correspondingEvent = None
# store and pass on a running status if found
self.lastStatusByte = None
# need to store a sort order based on type
self.sortOrder = 0
self.updateSortOrder()
def updateSortOrder(self):
# update based on type; type may be set after init
if self.type == 'PITCH_BEND': #go before note events
self.sortOrder = -10
if self.type == 'NOTE_OFF': # should come before pitch bend
self.sortOrder = -20
def __cmp__(self, other):
return cmp(self.time, other.time)
def __repr__(self):
if self.track == None:
trackIndex = None
else:
trackIndex = self.track.index
r = ("<MidiEvent %s, t=%s, track=%s, channel=%s" %
(self.type, repr(self.time), trackIndex,
repr(self.channel)))
if self.type in ['NOTE_ON', 'NOTE_OFF']:
attrList = ["pitch", "velocity"]
else:
if self._parameter2 is None:
attrList = ['data']
else:
attrList = ['_parameter1', '_parameter2']
for attrib in attrList:
if getattr(self, attrib) is not None:
r = r + ", " + attrib + "=" + repr(getattr(self, attrib))
return r + ">"
# provide parameter access to pitch and velocity
def _setPitch(self, value):
self._parameter1 = value
def _getPitch(self):
# only return pitch if this is note on /off
if self.type in ['NOTE_ON', 'NOTE_OFF']:
return self._parameter1
else:
return None
pitch = property(_getPitch, _setPitch)
def _setVelocity(self, value):
self._parameter2 = value
def _getVelocity(self):
return self._parameter2
velocity = property(_getVelocity, _setVelocity)
# store generic data in parameter 1
def _setData(self, value):
self._parameter1 = value
def _getData(self):
return self._parameter1
data = property(_getData, _setData)
def setPitchBend(self, cents, bendRange=2):
'''Treat this event as a pitch bend value, and set the ._parameter1 and ._parameter2 fields appropriately given a specified bend value in cents.
The `bendRange` parameter gives the number of half steps in the bend range.
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> me1.setPitchBend(50)
>>> me1._parameter1, me1._parameter2
(0, 80)
>>> me1.setPitchBend(100)
>>> me1._parameter1, me1._parameter2
(0, 96)
>>> me1.setPitchBend(200)
>>> me1._parameter1, me1._parameter2
(127, 127)
>>> me1.setPitchBend(-50)
>>> me1._parameter1, me1._parameter2
(0, 48)
>>> me1.setPitchBend(-100)
>>> me1._parameter1, me1._parameter2
(0, 32)
'''
# value range is 0, 16383
# center should be 8192
centRange = bendRange * 100
center = 8192
topSpan = 16383 - center
bottomSpan = center
if cents > 0:
shiftScalar = cents / float(centRange)
shift = int(round(shiftScalar * topSpan))
elif cents < 0:
shiftScalar = cents / float(centRange) # will be negative
shift = int(round(shiftScalar * bottomSpan)) # will be negative
else: # cents is zero
shift = 0
target = center + shift
# produce a two-char value
charValue = putVariableLengthNumber(target)
d1, junk = getNumber(charValue[0], 1)
# need to convert from 8 bit to 7, so using & 0x7F
d1 = d1 & 0x7F
if len(charValue) > 1:
d2, junk = getNumber(charValue[1], 1)
d2 = d2 & 0x7F
else:
d2 = 0
#environLocal.printDebug(['got target char value', charValue, 'getVariableLengthNumber(charValue)', getVariableLengthNumber(charValue)[0], 'd1', d1, 'd2', d2,])
self._parameter1 = d2
self._parameter2 = d1 # d1 is msb here
def _parseChannelVoiceMessage(self, midiStr):
'''
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> remainder = me1._parseChannelVoiceMessage(midi.intsToHexString([144, 60, 120]))
>>> me1.channel
1
>>> remainder = me1._parseChannelVoiceMessage(midi.intsToHexString([145, 60, 120]))
>>> me1.channel
2
>>> me1.type
'NOTE_ON'
>>> me1.pitch
60
>>> me1.velocity
120
'''
# x, y, and z define characteristics of the first two chars
# for x: The left nybble (4 bits) contains the actual command, and the right nibble contains the midi channel number on which the command will be executed.
x = ord(midiStr[0]) # return the char number
y = x & 0xF0 # bitwise and to derive channel number
z = ord(midiStr[1])
thirdByte = midiStr[2]
self.channel = (x & 0x0F) + 1 # this is same as y + 1
self.type = channelVoiceMessages.whatis(y)
#environLocal.printDebug(['MidiEvent.read()', self.type])
if (self.type == "PROGRAM_CHANGE" or
self.type == "CHANNEL_KEY_PRESSURE"):
self.data = z
return midiStr[2:]
elif (self.type == "CONTROLLER_CHANGE"):
# for now, do nothing with this data
# for a note, str[2] is velocity; here, it is the control value
self.pitch = z # this is the controller id
self.velocity = ord(thirdByte) # this is the controller value
return midiStr[3:]
else:
self.pitch = z # the second byte
# read the third chart toi get velocity
self.velocity = ord(thirdByte)
# each MidiChannel object is accessed here
# using that channel, data for each event is added or
# removed
return midiStr[3:]
def read(self, time, midiStr):
'''
Parse the string that is given and take the beginning
section and convert it into data for this event and return the
now truncated string.
The `time` value is the number of ticks into the Track
at which this event happens. This is derived from reading
data the level of the track.
TODO: These instructions are inadequate.
>>> # all note-on messages (144-159) can be found
>>> 145 & 0xF0 # testing message type extraction
144
>>> 146 & 0xF0 # testing message type extraction
144
>>> (144 & 0x0F) + 1 # getting the channel
1
>>> (159 & 0x0F) + 1 # getting the channel
16
'''
if len(midiStr) < 2:
# often what we have here are null events:
# the string is simply: 0x00
environLocal.printDebug(['MidiEvent.read(): got bad data string', 'time', time, 'str', repr(midiStr)])
return ''
# x, y, and z define characteristics of the first two chars
# for x: The left nybble (4 bits) contains the actual command, and the right nibble contains the midi channel number on which the command will be executed.
x = ord(midiStr[0]) # given a string representation, get decimal number
# detect running status: if the status byte is less than 128, its
# not a status byte, but a data byte
if x < 128:
# environLocal.printDebug(['MidiEvent.read(): found running status even data', 'self.lastStatusByte:', self.lastStatusByte])
if self.lastStatusByte is not None:
rsb = self.lastStatusByte
else: # provide a default
rsb = chr(0x90)
#post = self._parseChannelVoiceMessage(str, runningStatusByte=rsb)
#return post
# add the running status byte to the front of the string
# and process as before
midiStr = rsb + midiStr
x = ord(midiStr[0]) # given a string representation, get decimal number
else:
# store last status byte
self.lastStatusByte = midiStr[0]
y = x & 0xF0 # bitwise and to derive message type
z = ord(midiStr[1])
#environLocal.printDebug(['MidiEvent.read(): trying to parse a MIDI event, looking at first two chars:', 'repr(x)', repr(x), 'charToBinary(str[0])', charToBinary(str[0]), 'charToBinary(str[1])', charToBinary(str[1])])
if channelVoiceMessages.hasValue(y):
return self._parseChannelVoiceMessage(midiStr)
elif y == 0xB0 and channelModeMessages.hasValue(z):
self.channel = (x & 0x0F) + 1
self.type = channelModeMessages.whatis(z)
if self.type == "LOCAL_CONTROL":
self.data = (ord(midiStr[2]) == 0x7F)
elif self.type == "MONO_MODE_ON":
self.data = ord(midiStr[2])
else:
environLocal.printDebug(['unhandled message:', midiStr[2]])
return midiStr[3:]
elif x == 0xF0 or x == 0xF7:
self.type = {0xF0: "F0_SYSEX_EVENT",
0xF7: "F7_SYSEX_EVENT"}[x]
length, midiStr = getVariableLengthNumber(midiStr[1:])
self.data = midiStr[:length]
return midiStr[length:]
# SEQUENCE_TRACK_NAME and other MetaEvents are here
elif x == 0xFF:
#environLocal.printDebug(['MidiEvent.read(): got a variable length meta event', charToBinary(str[0])])
if not metaEvents.hasValue(z):
environLocal.printDebug(["unknown meta event: FF %02X" % z])
sys.stdout.flush()
raise MidiException("Unknown midi event type: %r, %r" % (x, z))
self.type = metaEvents.whatis(z)
length, midiStr = getVariableLengthNumber(midiStr[2:])
self.data = midiStr[:length]
# return remainder
return midiStr[length:]
else:
# an uncaught message
environLocal.printDebug(['got unknown midi event type', repr(x), 'charToBinary(midiStr[0])', charToBinary(midiStr[0]), 'charToBinary(midiStr[1])', charToBinary(midiStr[1])])
raise MidiException("Unknown midi event type")
#return everything but the first character
return midiStr[1:] #
def write(self):
'''
Write out a midi track.
'''
sysex_event_dict = {"F0_SYSEX_EVENT": 0xF0,
"F7_SYSEX_EVENT": 0xF7}
if channelVoiceMessages.hasattr(self.type):
#environLocal.printDebug(['writing channelVoiceMessages', self.type])
x = chr((self.channel - 1) +
getattr(channelVoiceMessages, self.type))
# for writing note-on/note-off
if self.type not in ['PROGRAM_CHANGE',
'CHANNEL_KEY_PRESSURE']:
# this results in a two-part string, like '\x00\x00'
try:
data = chr(self._parameter1) + chr(self._parameter2)
except ValueError:
raise MidiException("Problem with representing either %d or %d" % (self._parameter1, self._parameter2))
elif self.type in ['PROGRAM_CHANGE']:
#environLocal.printDebug(['trying to add program change data: %s' % self.data])
try:
data = chr(self.data)
except TypeError:
raise MidiException("Got incorrect data for %s in .data: %s, cannot parse Program Change" % (self, self.data))
else: # all other messages
try:
data = chr(self.data)
except TypeError:
raise MidiException("Got incorrect data for %s in .data: %s, cannot parse Miscellaneous Message" % (self, self.data))
return x + data
elif channelModeMessages.hasattr(self.type):
x = getattr(channelModeMessages, self.type)
x = (chr(0xB0 + (self.channel - 1)) +
chr(x) +
chr(self.data))
return x
elif sysex_event_dict.has_key(self.type):
s = chr(sysex_event_dict[self.type])
s = s + putVariableLengthNumber(len(self.data))
return s + self.data
elif metaEvents.hasattr(self.type):
s = chr(0xFF) + chr(getattr(metaEvents, self.type))
s = s + putVariableLengthNumber(len(self.data))
try: # TODO: need to handle unicode
return s + self.data
except UnicodeDecodeError:
#environLocal.printDebug(['cannot decode data', self.data])
return s + unicodedata.normalize('NFKD',
self.data).encode('ascii','ignore')
else:
raise MidiException("unknown midi event type: %s" % self.type)
#---------------------------------------------------------------------------
def isNoteOn(self):
'''
Return a boolean if this is a note-on message and velocity is not zero.
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> me1.type = "NOTE_ON"
>>> me1.velocity = 120
>>> me1.isNoteOn()
True
>>> me1.isNoteOff()
False
'''
if self.type == "NOTE_ON" and self.velocity != 0:
return True
return False
def isNoteOff(self):
'''
Return a boolean if this is should be interpreted as a note-off message,
either as a real note-off or as a note-on with zero velocity.
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> me1.type = "NOTE_OFF"
>>> me1.isNoteOn()
False
>>> me1.isNoteOff()
True
>>> me2 = midi.MidiEvent(mt)
>>> me2.type = "NOTE_ON"
>>> me2.velocity = 0
>>> me2.isNoteOn()
False
>>> me2.isNoteOff()
True
'''
if self.type == "NOTE_OFF":
return True
elif self.type == "NOTE_ON" and self.velocity == 0:
return True
return False
def isDeltaTime(self):
'''
Return a boolean if this is a DeltaTime subclass.
>>> mt = midi.MidiTrack(1)
>>> dt = midi.DeltaTime(mt)
>>> dt.isDeltaTime()
True
'''
if self.type == "DeltaTime":
return True
return False
def matchedNoteOff(self, other):
'''
Returns True if `other` is a MIDI event that specifies
a note-off message for this message. That is, this event
is a NOTE_ON message, and the other is a NOTE_OFF message
for this pitch on this channel. Otherwise returns False
>>> mt = midi.MidiTrack(1)
>>> me1 = midi.MidiEvent(mt)
>>> me1.type = "NOTE_ON"
>>> me1.velocity = 120
>>> me1.pitch = 60
>>> me2 = midi.MidiEvent(mt)
>>> me2.type = "NOTE_ON"
>>> me2.velocity = 0
>>> me2.pitch = 60
>>> me1.matchedNoteOff(me2)
True
>>> me2.pitch = 61
>>> me1.matchedNoteOff(me2)
False
>>> me2.type = "NOTE_OFF"
>>> me1.matchedNoteOff(me2)
False
>>> me2.pitch = 60
>>> me1.matchedNoteOff(me2)
True
>>> me2.channel = 12
>>> me1.matchedNoteOff(me2)
False
'''
if other.isNoteOff:
# might check velocity here too?
if self.pitch == other.pitch and self.channel == other.channel:
return True
return False
class DeltaTime(MidiEvent):
'''
A :class:`~music21.midi.base.MidiEvent` subclass that stores the
time change (in ticks) since the start or since the last MidiEvent.
Pairs of DeltaTime and MidiEvent objects are the basic presentation of temporal data.
The `track` argument must be a :class:`~music21.midi.base.MidiTrack` object.
Time values are in integers, representing ticks.
The `channel` attribute, inherited from MidiEvent is not used and set to None
unless overridden (don't!).
>>> mt = midi.MidiTrack(1)
>>> dt = midi.DeltaTime(mt)
>>> dt.time = 380
>>> dt
<MidiEvent DeltaTime, t=380, track=1, channel=None>
'''
def __init__(self, track, time=None, channel=None):
MidiEvent.__init__(self, track, time=time, channel=channel)
self.type = "DeltaTime"
def read(self, oldstr):
self.time, newstr = getVariableLengthNumber(oldstr)
return self.time, newstr
def write(self):
midiStr = putVariableLengthNumber(self.time)
return midiStr
class MidiTrack(object):
'''
A MIDI Track. Each track contains a list of
:class:`~music21.midi.base.MidiChannel` objects, one for each channel.
All events are stored in the `events` list, in order.
An `index` is an integer identifier for this object.
TODO: Better Docs
>>> mt = midi.MidiTrack(0)
'''
def __init__(self, index):
self.index = index
self.events = []
self.length = 0 #the data length; only used on read()
# no longer need channel objects
# an object for each of 16 channels is created
# self.channels = []
# for i in range(16):
# self.channels.append(MidiChannel(self, i+1))
def read(self, midiStr):
'''
Read as much of the string (representing midi data) as necessary;
return the remaining string for reassignment and further processing.
The string should begin with `MTrk`, specifying a Midi Track
Creates and stores :class:`~music21.midi.base.DeltaTime`
and :class:`~music21.midi.base.MidiEvent` objects.
'''
time = 0 # a running counter of ticks
if not midiStr[:4] == "MTrk":
raise MidiException('badly formed midi string: missing leading MTrk')
# get the 4 chars after the MTrk encoding
length, midiStr = getNumber(midiStr[4:], 4)
#environLocal.printDebug(['MidiTrack.read(): got chunk size', length])
self.length = length
# all event data is in the track str
trackStr = midiStr[:length]
remainder = midiStr[length:]
ePrevious = None
while trackStr:
# shave off the time stamp from the event
delta_t = DeltaTime(self)
# return extracted time, as well as remaining string
dt, trackStrCandidate = delta_t.read(trackStr)
# this is the offset that this event happens at, in ticks
timeCandidate = time + dt
# pass self to event, set this MidiTrack as the track for this event
e = MidiEvent(self)
if ePrevious is not None: # set the last status byte
e.lastStatusByte = ePrevious.lastStatusByte
# some midi events may raise errors; simply skip for now
try:
trackStrCandidate = e.read(timeCandidate, trackStrCandidate)
except MidiException:
# assume that trackStr, after delta extraction, is still correct
#environLocal.printDebug(['forced to skip event; delta_t:', delta_t])
# set to result after taking delta time
trackStr = trackStrCandidate
continue
# only set after trying to read, which may raise exception
time = timeCandidate
trackStr = trackStrCandidate # remainder string
# only append if we get this far
self.events.append(delta_t)
self.events.append(e)
ePrevious = e