-
Notifications
You must be signed in to change notification settings - Fork 1
/
midi_to_colab_audio.py
3090 lines (2740 loc) · 123 KB
/
midi_to_colab_audio.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
r'''#===================================================================================================================
#
# MIDI to Colab AUdio Python Module
#
# Converts any MIDI file to raw audio which is compatible
# with Google Colab or HUgging Face Gradio
#
# Version 1.0
#
# Includes full source code of MIDI, pyfluidsynth, and midi_synthesizer Python modules
#
# Original source code for all modules was retrieved on 10/23/2023
#
# Project Los Angeles
# Tegridy Code 2023
#
#===================================================================================================================
#
# Critical dependencies
#
# pip install numpy
# sudo apt install fluidsynth
#
#===================================================================================================================
#
# Example usage:
#
# from midi_to_colab_audio import midi_to_colab_audio
# from IPython.display import display, Audio
#
# raw_audio = midi_to_colab_audio('/content/input.mid')
#
# display(Audio(raw_audio, rate=16000, normalize=False))
#
#===================================================================================================================
#! /usr/bin/python3
# unsupported 20091104 ...
# ['set_sequence_number', dtime, sequence]
# ['raw_data', dtime, raw]
# 20150914 jimbo1qaz MIDI.py str/bytes bug report
# I found a MIDI file which had Shift-JIS titles. When midi.py decodes it as
# latin-1, it produces a string which cannot even be accessed without raising
# a UnicodeDecodeError. Maybe, when converting raw byte strings from MIDI,
# you should keep them as bytes, not improperly decode them. However, this
# would change the API. (ie: text = a "string" ? of 0 or more bytes). It
# could break compatiblity, but there's not much else you can do to fix the bug
# https://en.wikipedia.org/wiki/Shift_JIS
This module offers functions: concatenate_scores(), grep(),
merge_scores(), mix_scores(), midi2opus(), midi2score(), opus2midi(),
opus2score(), play_score(), score2midi(), score2opus(), score2stats(),
score_type(), segment(), timeshift() and to_millisecs(),
where "midi" means the MIDI-file bytes (as can be put in a .mid file,
or piped into aplaymidi), and "opus" and "score" are list-structures
as inspired by Sean Burke's MIDI-Perl CPAN module.
Warning: Version 6.4 is not necessarily backward-compatible with
previous versions, in that text-data is now bytes, not strings.
This reflects the fact that many MIDI files have text data in
encodings other that ISO-8859-1, for example in Shift-JIS.
Download MIDI.py from http://www.pjb.com.au/midi/free/MIDI.py
and put it in your PYTHONPATH. MIDI.py depends on Python3.
There is also a call-compatible translation into Lua of this
module: see http://www.pjb.com.au/comp/lua/MIDI.html
Backup web site: https://peterbillam.gitlab.io/miditools/
The "opus" is a direct translation of the midi-file-events, where
the times are delta-times, in ticks, since the previous event.
The "score" is more human-centric; it uses absolute times, and
combines the separate note_on and note_off events into one "note"
event, with a duration:
['note', start_time, duration, channel, note, velocity] # in a "score"
EVENTS (in an "opus" structure)
['note_off', dtime, channel, note, velocity] # in an "opus"
['note_on', dtime, channel, note, velocity] # in an "opus"
['key_after_touch', dtime, channel, note, velocity]
['control_change', dtime, channel, controller(0-127), value(0-127)]
['patch_change', dtime, channel, patch]
['channel_after_touch', dtime, channel, velocity]
['pitch_wheel_change', dtime, channel, pitch_wheel]
['text_event', dtime, text]
['copyright_text_event', dtime, text]
['track_name', dtime, text]
['instrument_name', dtime, text]
['lyric', dtime, text]
['marker', dtime, text]
['cue_point', dtime, text]
['text_event_08', dtime, text]
['text_event_09', dtime, text]
['text_event_0a', dtime, text]
['text_event_0b', dtime, text]
['text_event_0c', dtime, text]
['text_event_0d', dtime, text]
['text_event_0e', dtime, text]
['text_event_0f', dtime, text]
['end_track', dtime]
['set_tempo', dtime, tempo]
['smpte_offset', dtime, hr, mn, se, fr, ff]
['time_signature', dtime, nn, dd, cc, bb]
['key_signature', dtime, sf, mi]
['sequencer_specific', dtime, raw]
['raw_meta_event', dtime, command(0-255), raw]
['sysex_f0', dtime, raw]
['sysex_f7', dtime, raw]
['song_position', dtime, song_pos]
['song_select', dtime, song_number]
['tune_request', dtime]
DATA TYPES
channel = a value 0 to 15
controller = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html#cc )
dtime = time measured in "ticks", 0 to 268435455
velocity = a value 0 (soft) to 127 (loud)
note = a value 0 to 127 (middle-C is 60)
patch = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html )
pitch_wheel = a value -8192 to 8191 (0x1FFF)
raw = bytes, of length 0 or more (for sysex events see below)
sequence_number = a value 0 to 65,535 (0xFFFF)
song_pos = a value 0 to 16,383 (0x3FFF)
song_number = a value 0 to 127
tempo = microseconds per crochet (quarter-note), 0 to 16777215
text = bytes, of length 0 or more
ticks = the number of ticks per crochet (quarter-note)
In sysex_f0 events, the raw data must not start with a \xF0 byte,
since this gets added automatically;
but it must end with an explicit \xF7 byte!
In the very unlikely case that you ever need to split sysex data
into one sysex_f0 followed by one or more sysex_f7s, then only the
last of those sysex_f7 events must end with the explicit \xF7 byte
(again, the raw data of individual sysex_f7 events must not start
with any \xF7 byte, since this gets added automatically).
Since version 6.4, text data is in bytes, not in a ISO-8859-1 string.
GOING THROUGH A SCORE WITHIN A PYTHON PROGRAM
channels = {2,3,5,8,13}
itrack = 1 # skip 1st element which is ticks
while itrack < len(score):
for event in score[itrack]:
if event[0] == 'note': # for example,
pass # do something to all notes
# or, to work on events in only particular channels...
channel_index = MIDI.Event2channelindex.get(event[0], False)
if channel_index and (event[channel_index] in channels):
pass # do something to channels 2,3,5,8 and 13
itrack += 1
'''
import sys, struct, copy
# sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb')
Version = '6.7'
VersionDate = '20201120'
# 20201120 6.7 call to bytest() removed, and protect _unshift_ber_int
# 20160702 6.6 to_millisecs() now handles set_tempo across multiple Tracks
# 20150921 6.5 segment restores controllers as well as patch and tempo
# 20150914 6.4 text data is bytes or bytearray, not ISO-8859-1 strings
# 20150628 6.3 absent any set_tempo, default is 120bpm (see MIDI file spec 1.1)
# 20150101 6.2 all text events can be 8-bit; let user get the right encoding
# 20141231 6.1 fix _some_text_event; sequencer_specific data can be 8-bit
# 20141230 6.0 synth_specific data can be 8-bit
# 20120504 5.9 add the contents of mid_opus_tracks()
# 20120208 5.8 fix num_notes_by_channel() ; should be a dict
# 20120129 5.7 _encode handles empty tracks; score2stats num_notes_by_channel
# 20111111 5.6 fix patch 45 and 46 in Number2patch, should be Harp
# 20110129 5.5 add mix_opus_tracks() and event2alsaseq()
# 20110126 5.4 "previous message repeated N times" to save space on stderr
# 20110125 5.2 opus2score terminates unended notes at the end of the track
# 20110124 5.1 the warnings in midi2opus display track_num
# 21110122 5.0 if garbage, midi2opus returns the opus so far
# 21110119 4.9 non-ascii chars stripped out of the text_events
# 21110110 4.8 note_on with velocity=0 treated as a note-off
# 21110108 4.6 unknown F-series event correctly eats just one byte
# 21011010 4.2 segment() uses start_time, end_time named params
# 21011005 4.1 timeshift() must not pad the set_tempo command
# 21011003 4.0 pitch2note_event must be chapitch2note_event
# 21010918 3.9 set_sequence_number supported, FWIW
# 20100913 3.7 many small bugfixes; passes all tests
# 20100910 3.6 concatenate_scores enforce ticks=1000, just like merge_scores
# 20100908 3.5 minor bugs fixed in score2stats
# 20091104 3.4 tune_request now supported
# 20091104 3.3 fixed bug in decoding song_position and song_select
# 20091104 3.2 unsupported: set_sequence_number tune_request raw_data
# 20091101 3.1 document how to traverse a score within Python
# 20091021 3.0 fixed bug in score2stats detecting GM-mode = 0
# 20091020 2.9 score2stats reports GM-mode and bank msb,lsb events
# 20091019 2.8 in merge_scores, channel 9 must remain channel 9 (in GM)
# 20091018 2.7 handles empty tracks gracefully
# 20091015 2.6 grep() selects channels
# 20091010 2.5 merge_scores reassigns channels to avoid conflicts
# 20091010 2.4 fixed bug in to_millisecs which now only does opusses
# 20091010 2.3 score2stats returns channels & patch_changes, by_track & total
# 20091010 2.2 score2stats() returns also pitches and percussion dicts
# 20091010 2.1 bugs: >= not > in segment, to notice patch_change at time 0
# 20091010 2.0 bugs: spurious pop(0) ( in _decode sysex
# 20091008 1.9 bugs: ISO decoding in sysex; str( not int( in note-off warning
# 20091008 1.8 add concatenate_scores()
# 20091006 1.7 score2stats() measures nticks and ticks_per_quarter
# 20091004 1.6 first mix_scores() and merge_scores()
# 20090424 1.5 timeshift() bugfix: earliest only sees events after from_time
# 20090330 1.4 timeshift() has also a from_time argument
# 20090322 1.3 timeshift() has also a start_time argument
# 20090319 1.2 add segment() and timeshift()
# 20090301 1.1 add to_millisecs()
_previous_warning = '' # 5.4
_previous_times = 0 # 5.4
#------------------------------- Encoding stuff --------------------------
def opus2midi(opus=[]):
r'''The argument is a list: the first item in the list is the "ticks"
parameter, the others are the tracks. Each track is a list
of midi-events, and each event is itself a list; see above.
opus2midi() returns a bytestring of the MIDI, which can then be
written either to a file opened in binary mode (mode='wb'),
or to stdout by means of: sys.stdout.buffer.write()
my_opus = [
96,
[ # track 0:
['patch_change', 0, 1, 8], # and these are the events...
['note_on', 5, 1, 25, 96],
['note_off', 96, 1, 25, 0],
['note_on', 0, 1, 29, 96],
['note_off', 96, 1, 29, 0],
], # end of track 0
]
my_midi = opus2midi(my_opus)
sys.stdout.buffer.write(my_midi)
'''
if len(opus) < 2:
opus=[1000, [],]
tracks = copy.deepcopy(opus)
ticks = int(tracks.pop(0))
ntracks = len(tracks)
if ntracks == 1:
format = 0
else:
format = 1
my_midi = b"MThd\x00\x00\x00\x06"+struct.pack('>HHH',format,ntracks,ticks)
for track in tracks:
events = _encode(track)
my_midi += b'MTrk' + struct.pack('>I',len(events)) + events
_clean_up_warnings()
return my_midi
def score2opus(score=None):
r'''
The argument is a list: the first item in the list is the "ticks"
parameter, the others are the tracks. Each track is a list
of score-events, and each event is itself a list. A score-event
is similar to an opus-event (see above), except that in a score:
1) the times are expressed as an absolute number of ticks
from the track's start time
2) the pairs of 'note_on' and 'note_off' events in an "opus"
are abstracted into a single 'note' event in a "score":
['note', start_time, duration, channel, pitch, velocity]
score2opus() returns a list specifying the equivalent "opus".
my_score = [
96,
[ # track 0:
['patch_change', 0, 1, 8],
['note', 5, 96, 1, 25, 96],
['note', 101, 96, 1, 29, 96]
], # end of track 0
]
my_opus = score2opus(my_score)
'''
if len(score) < 2:
score=[1000, [],]
tracks = copy.deepcopy(score)
ticks = int(tracks.pop(0))
opus_tracks = []
for scoretrack in tracks:
time2events = dict([])
for scoreevent in scoretrack:
if scoreevent[0] == 'note':
note_on_event = ['note_on',scoreevent[1],
scoreevent[3],scoreevent[4],scoreevent[5]]
note_off_event = ['note_off',scoreevent[1]+scoreevent[2],
scoreevent[3],scoreevent[4],scoreevent[5]]
if time2events.get(note_on_event[1]):
time2events[note_on_event[1]].append(note_on_event)
else:
time2events[note_on_event[1]] = [note_on_event,]
if time2events.get(note_off_event[1]):
time2events[note_off_event[1]].append(note_off_event)
else:
time2events[note_off_event[1]] = [note_off_event,]
continue
if time2events.get(scoreevent[1]):
time2events[scoreevent[1]].append(scoreevent)
else:
time2events[scoreevent[1]] = [scoreevent,]
sorted_times = [] # list of keys
for k in time2events.keys():
sorted_times.append(k)
sorted_times.sort()
sorted_events = [] # once-flattened list of values sorted by key
for time in sorted_times:
sorted_events.extend(time2events[time])
abs_time = 0
for event in sorted_events: # convert abs times => delta times
delta_time = event[1] - abs_time
abs_time = event[1]
event[1] = delta_time
opus_tracks.append(sorted_events)
opus_tracks.insert(0,ticks)
_clean_up_warnings()
return opus_tracks
def score2midi(score=None):
r'''
Translates a "score" into MIDI, using score2opus() then opus2midi()
'''
return opus2midi(score2opus(score))
#--------------------------- Decoding stuff ------------------------
def midi2opus(midi=b''):
r'''Translates MIDI into a "opus". For a description of the
"opus" format, see opus2midi()
'''
my_midi=bytearray(midi)
if len(my_midi) < 4:
_clean_up_warnings()
return [1000,[],]
id = bytes(my_midi[0:4])
if id != b'MThd':
_warn("midi2opus: midi starts with "+str(id)+" instead of 'MThd'")
_clean_up_warnings()
return [1000,[],]
[length, format, tracks_expected, ticks] = struct.unpack(
'>IHHH', bytes(my_midi[4:14]))
if length != 6:
_warn("midi2opus: midi header length was "+str(length)+" instead of 6")
_clean_up_warnings()
return [1000,[],]
my_opus = [ticks,]
my_midi = my_midi[14:]
track_num = 1 # 5.1
while len(my_midi) >= 8:
track_type = bytes(my_midi[0:4])
if track_type != b'MTrk':
_warn('midi2opus: Warning: track #'+str(track_num)+' type is '+str(track_type)+" instead of b'MTrk'")
[track_length] = struct.unpack('>I', my_midi[4:8])
my_midi = my_midi[8:]
if track_length > len(my_midi):
_warn('midi2opus: track #'+str(track_num)+' length '+str(track_length)+' is too large')
_clean_up_warnings()
return my_opus # 5.0
my_midi_track = my_midi[0:track_length]
my_track = _decode(my_midi_track)
my_opus.append(my_track)
my_midi = my_midi[track_length:]
track_num += 1 # 5.1
_clean_up_warnings()
return my_opus
def opus2score(opus=[]):
r'''For a description of the "opus" and "score" formats,
see opus2midi() and score2opus().
'''
if len(opus) < 2:
_clean_up_warnings()
return [1000,[],]
tracks = copy.deepcopy(opus) # couple of slices probably quicker...
ticks = int(tracks.pop(0))
score = [ticks,]
for opus_track in tracks:
ticks_so_far = 0
score_track = []
chapitch2note_on_events = dict([]) # 4.0
for opus_event in opus_track:
ticks_so_far += opus_event[1]
if opus_event[0] == 'note_off' or (opus_event[0] == 'note_on' and opus_event[4] == 0): # 4.8
cha = opus_event[2]
pitch = opus_event[3]
key = cha*128 + pitch
if chapitch2note_on_events.get(key):
new_event = chapitch2note_on_events[key].pop(0)
new_event[2] = ticks_so_far - new_event[1]
score_track.append(new_event)
elif pitch > 127:
pass #_warn('opus2score: note_off with no note_on, bad pitch='+str(pitch))
else:
pass #_warn('opus2score: note_off with no note_on cha='+str(cha)+' pitch='+str(pitch))
elif opus_event[0] == 'note_on':
cha = opus_event[2]
pitch = opus_event[3]
key = cha*128 + pitch
new_event = ['note',ticks_so_far,0,cha,pitch, opus_event[4]]
if chapitch2note_on_events.get(key):
chapitch2note_on_events[key].append(new_event)
else:
chapitch2note_on_events[key] = [new_event,]
else:
opus_event[1] = ticks_so_far
score_track.append(opus_event)
# check for unterminated notes (Oisín) -- 5.2
for chapitch in chapitch2note_on_events:
note_on_events = chapitch2note_on_events[chapitch]
for new_e in note_on_events:
new_e[2] = ticks_so_far - new_e[1]
score_track.append(new_e)
pass #_warn("opus2score: note_on with no note_off cha="+str(new_e[3])+' pitch='+str(new_e[4])+'; adding note_off at end')
score.append(score_track)
_clean_up_warnings()
return score
def midi2score(midi=b''):
r'''
Translates MIDI into a "score", using midi2opus() then opus2score()
'''
return opus2score(midi2opus(midi))
def midi2ms_score(midi=b''):
r'''
Translates MIDI into a "score" with one beat per second and one
tick per millisecond, using midi2opus() then to_millisecs()
then opus2score()
'''
return opus2score(to_millisecs(midi2opus(midi)))
#------------------------ Other Transformations ---------------------
def to_millisecs(old_opus=None):
r'''Recallibrates all the times in an "opus" to use one beat
per second and one tick per millisecond. This makes it
hard to retrieve any information about beats or barlines,
but it does make it easy to mix different scores together.
'''
if old_opus == None:
return [1000,[],]
try:
old_tpq = int(old_opus[0])
except IndexError: # 5.0
_warn('to_millisecs: the opus '+str(type(old_opus))+' has no elements')
return [1000,[],]
new_opus = [1000,]
# 6.7 first go through building a table of set_tempos by absolute-tick
ticks2tempo = {}
itrack = 1
while itrack < len(old_opus):
ticks_so_far = 0
for old_event in old_opus[itrack]:
if old_event[0] == 'note':
raise TypeError('to_millisecs needs an opus, not a score')
ticks_so_far += old_event[1]
if old_event[0] == 'set_tempo':
ticks2tempo[ticks_so_far] = old_event[2]
itrack += 1
# then get the sorted-array of their keys
tempo_ticks = [] # list of keys
for k in ticks2tempo.keys():
tempo_ticks.append(k)
tempo_ticks.sort()
# then go through converting to millisec, testing if the next
# set_tempo lies before the next track-event, and using it if so.
itrack = 1
while itrack < len(old_opus):
ms_per_old_tick = 500.0 / old_tpq # float: will round later 6.3
i_tempo_ticks = 0
ticks_so_far = 0
ms_so_far = 0.0
previous_ms_so_far = 0.0
new_track = [['set_tempo',0,1000000],] # new "crochet" is 1 sec
for old_event in old_opus[itrack]:
# detect if ticks2tempo has something before this event
# 20160702 if ticks2tempo is at the same time, leave it
event_delta_ticks = old_event[1]
if (i_tempo_ticks < len(tempo_ticks) and
tempo_ticks[i_tempo_ticks] < (ticks_so_far + old_event[1])):
delta_ticks = tempo_ticks[i_tempo_ticks] - ticks_so_far
ms_so_far += (ms_per_old_tick * delta_ticks)
ticks_so_far = tempo_ticks[i_tempo_ticks]
ms_per_old_tick = ticks2tempo[ticks_so_far] / (1000.0*old_tpq)
i_tempo_ticks += 1
event_delta_ticks -= delta_ticks
new_event = copy.deepcopy(old_event) # now handle the new event
ms_so_far += (ms_per_old_tick * old_event[1])
new_event[1] = round(ms_so_far - previous_ms_so_far)
if old_event[0] != 'set_tempo':
previous_ms_so_far = ms_so_far
new_track.append(new_event)
ticks_so_far += event_delta_ticks
new_opus.append(new_track)
itrack += 1
_clean_up_warnings()
return new_opus
def event2alsaseq(event=None): # 5.5
r'''Converts an event into the format needed by the alsaseq module,
http://pp.com.mx/python/alsaseq
The type of track (opus or score) is autodetected.
'''
pass
def grep(score=None, channels=None):
r'''Returns a "score" containing only the channels specified
'''
if score == None:
return [1000,[],]
ticks = score[0]
new_score = [ticks,]
if channels == None:
return new_score
channels = set(channels)
global Event2channelindex
itrack = 1
while itrack < len(score):
new_score.append([])
for event in score[itrack]:
channel_index = Event2channelindex.get(event[0], False)
if channel_index:
if event[channel_index] in channels:
new_score[itrack].append(event)
else:
new_score[itrack].append(event)
itrack += 1
return new_score
def play_score(score=None):
r'''Converts the "score" to midi, and feeds it into 'aplaymidi -'
'''
if score == None:
return
import subprocess
pipe = subprocess.Popen(['aplaymidi','-'], stdin=subprocess.PIPE)
if score_type(score) == 'opus':
pipe.stdin.write(opus2midi(score))
else:
pipe.stdin.write(score2midi(score))
pipe.stdin.close()
def timeshift(score=None, shift=None, start_time=None, from_time=0, tracks={0,1,2,3,4,5,6,7,8,10,12,13,14,15}):
r'''Returns a "score" shifted in time by "shift" ticks, or shifted
so that the first event starts at "start_time" ticks.
If "from_time" is specified, only those events in the score
that begin after it are shifted. If "start_time" is less than
"from_time" (or "shift" is negative), then the intermediate
notes are deleted, though patch-change events are preserved.
If "tracks" are specified, then only those tracks get shifted.
"tracks" can be a list, tuple or set; it gets converted to set
internally.
It is deprecated to specify both "shift" and "start_time".
If this does happen, timeshift() will print a warning to
stderr and ignore the "shift" argument.
If "shift" is negative and sufficiently large that it would
leave some event with a negative tick-value, then the score
is shifted so that the first event occurs at time 0. This
also occurs if "start_time" is negative, and is also the
default if neither "shift" nor "start_time" are specified.
'''
#_warn('tracks='+str(tracks))
if score == None or len(score) < 2:
return [1000, [],]
new_score = [score[0],]
my_type = score_type(score)
if my_type == '':
return new_score
if my_type == 'opus':
_warn("timeshift: opus format is not supported\n")
# _clean_up_scores() 6.2; doesn't exist! what was it supposed to do?
return new_score
if not (shift == None) and not (start_time == None):
_warn("timeshift: shift and start_time specified: ignoring shift\n")
shift = None
if shift == None:
if (start_time == None) or (start_time < 0):
start_time = 0
# shift = start_time - from_time
i = 1 # ignore first element (ticks)
tracks = set(tracks) # defend against tuples and lists
earliest = 1000000000
if not (start_time == None) or shift < 0: # first find the earliest event
while i < len(score):
if len(tracks) and not ((i-1) in tracks):
i += 1
continue
for event in score[i]:
if event[1] < from_time:
continue # just inspect the to_be_shifted events
if event[1] < earliest:
earliest = event[1]
i += 1
if earliest > 999999999:
earliest = 0
if shift == None:
shift = start_time - earliest
elif (earliest + shift) < 0:
start_time = 0
shift = 0 - earliest
i = 1 # ignore first element (ticks)
while i < len(score):
if len(tracks) == 0 or not ((i-1) in tracks): # 3.8
new_score.append(score[i])
i += 1
continue
new_track = []
for event in score[i]:
new_event = list(event)
#if new_event[1] == 0 and shift > 0 and new_event[0] != 'note':
# pass
#elif new_event[1] >= from_time:
if new_event[1] >= from_time:
# 4.1 must not rightshift set_tempo
if new_event[0] != 'set_tempo' or shift<0:
new_event[1] += shift
elif (shift < 0) and (new_event[1] >= (from_time+shift)):
continue
new_track.append(new_event)
if len(new_track) > 0:
new_score.append(new_track)
i += 1
_clean_up_warnings()
return new_score
def segment(score=None, start_time=None, end_time=None, start=0, end=100000000,
tracks={0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}):
r'''Returns a "score" which is a segment of the one supplied
as the argument, beginning at "start_time" ticks and ending
at "end_time" ticks (or at the end if "end_time" is not supplied).
If the set "tracks" is specified, only those tracks will
be returned.
'''
if score == None or len(score) < 2:
return [1000, [],]
if start_time == None: # as of 4.2 start_time is recommended
start_time = start # start is legacy usage
if end_time == None: # likewise
end_time = end
new_score = [score[0],]
my_type = score_type(score)
if my_type == '':
return new_score
if my_type == 'opus':
# more difficult (disconnecting note_on's from their note_off's)...
_warn("segment: opus format is not supported\n")
_clean_up_warnings()
return new_score
i = 1 # ignore first element (ticks); we count in ticks anyway
tracks = set(tracks) # defend against tuples and lists
while i < len(score):
if len(tracks) and not ((i-1) in tracks):
i += 1
continue
new_track = []
channel2cc_num = {} # most recent controller change before start
channel2cc_val = {}
channel2cc_time = {}
channel2patch_num = {} # keep most recent patch change before start
channel2patch_time = {}
set_tempo_num = 500000 # most recent tempo change before start 6.3
set_tempo_time = 0
earliest_note_time = end_time
for event in score[i]:
if event[0] == 'control_change': # 6.5
cc_time = channel2cc_time.get(event[2]) or 0
if (event[1] <= start_time) and (event[1] >= cc_time):
channel2cc_num[event[2]] = event[3]
channel2cc_val[event[2]] = event[4]
channel2cc_time[event[2]] = event[1]
elif event[0] == 'patch_change':
patch_time = channel2patch_time.get(event[2]) or 0
if (event[1]<=start_time) and (event[1] >= patch_time): # 2.0
channel2patch_num[event[2]] = event[3]
channel2patch_time[event[2]] = event[1]
elif event[0] == 'set_tempo':
if (event[1]<=start_time) and (event[1]>=set_tempo_time): #6.4
set_tempo_num = event[2]
set_tempo_time = event[1]
if (event[1] >= start_time) and (event[1] <= end_time):
new_track.append(event)
if (event[0] == 'note') and (event[1] < earliest_note_time):
earliest_note_time = event[1]
if len(new_track) > 0:
new_track.append(['set_tempo', start_time, set_tempo_num])
for c in channel2patch_num:
new_track.append(['patch_change',start_time,c,channel2patch_num[c]],)
for c in channel2cc_num: # 6.5
new_track.append(['control_change',start_time,c,channel2cc_num[c],channel2cc_val[c]])
new_score.append(new_track)
i += 1
_clean_up_warnings()
return new_score
def score_type(opus_or_score=None):
r'''Returns a string, either 'opus' or 'score' or ''
'''
if opus_or_score == None or str(type(opus_or_score)).find('list')<0 or len(opus_or_score) < 2:
return ''
i = 1 # ignore first element
while i < len(opus_or_score):
for event in opus_or_score[i]:
if event[0] == 'note':
return 'score'
elif event[0] == 'note_on':
return 'opus'
i += 1
return ''
def concatenate_scores(scores):
r'''Concatenates a list of scores into one score.
If the scores differ in their "ticks" parameter,
they will all get converted to millisecond-tick format.
'''
# the deepcopys are needed if the input_score's are refs to the same obj
# e.g. if invoked by midisox's repeat()
input_scores = _consistentise_ticks(scores) # 3.7
output_score = copy.deepcopy(input_scores[0])
for input_score in input_scores[1:]:
output_stats = score2stats(output_score)
delta_ticks = output_stats['nticks']
itrack = 1
while itrack < len(input_score):
if itrack >= len(output_score): # new output track if doesn't exist
output_score.append([])
for event in input_score[itrack]:
output_score[itrack].append(copy.deepcopy(event))
output_score[itrack][-1][1] += delta_ticks
itrack += 1
return output_score
def merge_scores(scores):
r'''Merges a list of scores into one score. A merged score comprises
all of the tracks from all of the input scores; un-merging is possible
by selecting just some of the tracks. If the scores differ in their
"ticks" parameter, they will all get converted to millisecond-tick
format. merge_scores attempts to resolve channel-conflicts,
but there are of course only 15 available channels...
'''
input_scores = _consistentise_ticks(scores) # 3.6
output_score = [1000]
channels_so_far = set()
all_channels = {0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}
global Event2channelindex
for input_score in input_scores:
new_channels = set(score2stats(input_score).get('channels_total', []))
new_channels.discard(9) # 2.8 cha9 must remain cha9 (in GM)
for channel in channels_so_far & new_channels:
# consistently choose lowest avaiable, to ease testing
free_channels = list(all_channels - (channels_so_far|new_channels))
if len(free_channels) > 0:
free_channels.sort()
free_channel = free_channels[0]
else:
free_channel = None
break
itrack = 1
while itrack < len(input_score):
for input_event in input_score[itrack]:
channel_index=Event2channelindex.get(input_event[0],False)
if channel_index and input_event[channel_index]==channel:
input_event[channel_index] = free_channel
itrack += 1
channels_so_far.add(free_channel)
channels_so_far |= new_channels
output_score.extend(input_score[1:])
return output_score
def _ticks(event):
return event[1]
def mix_opus_tracks(input_tracks): # 5.5
r'''Mixes an array of tracks into one track. A mixed track
cannot be un-mixed. It is assumed that the tracks share the same
ticks parameter and the same tempo.
Mixing score-tracks is trivial (just insert all events into one array).
Mixing opus-tracks is only slightly harder, but it's common enough
that a dedicated function is useful.
'''
output_score = [1000, []]
for input_track in input_tracks: # 5.8
input_score = opus2score([1000, input_track])
for event in input_score[1]:
output_score[1].append(event)
output_score[1].sort(key=_ticks)
output_opus = score2opus(output_score)
return output_opus[1]
def mix_scores(scores):
r'''Mixes a list of scores into one one-track score.
A mixed score cannot be un-mixed. Hopefully the scores
have no undesirable channel-conflicts between them.
If the scores differ in their "ticks" parameter,
they will all get converted to millisecond-tick format.
'''
input_scores = _consistentise_ticks(scores) # 3.6
output_score = [1000, []]
for input_score in input_scores:
for input_track in input_score[1:]:
output_score[1].extend(input_track)
return output_score
def score2stats(opus_or_score=None):
r'''Returns a dict of some basic stats about the score, like
bank_select (list of tuples (msb,lsb)),
channels_by_track (list of lists), channels_total (set),
general_midi_mode (list),
ntracks, nticks, patch_changes_by_track (list of dicts),
num_notes_by_channel (list of numbers),
patch_changes_total (set),
percussion (dict histogram of channel 9 events),
pitches (dict histogram of pitches on channels other than 9),
pitch_range_by_track (list, by track, of two-member-tuples),
pitch_range_sum (sum over tracks of the pitch_ranges),
'''
bank_select_msb = -1
bank_select_lsb = -1
bank_select = []
channels_by_track = []
channels_total = set([])
general_midi_mode = []
num_notes_by_channel = dict([])
patches_used_by_track = []
patches_used_total = set([])
patch_changes_by_track = []
patch_changes_total = set([])
percussion = dict([]) # histogram of channel 9 "pitches"
pitches = dict([]) # histogram of pitch-occurrences channels 0-8,10-15
pitch_range_sum = 0 # u pitch-ranges of each track
pitch_range_by_track = []
is_a_score = True
if opus_or_score == None:
return {'bank_select':[], 'channels_by_track':[], 'channels_total':[],
'general_midi_mode':[], 'ntracks':0, 'nticks':0,
'num_notes_by_channel':dict([]),
'patch_changes_by_track':[], 'patch_changes_total':[],
'percussion':{}, 'pitches':{}, 'pitch_range_by_track':[],
'ticks_per_quarter':0, 'pitch_range_sum':0}
ticks_per_quarter = opus_or_score[0]
i = 1 # ignore first element, which is ticks
nticks = 0
while i < len(opus_or_score):
highest_pitch = 0
lowest_pitch = 128
channels_this_track = set([])
patch_changes_this_track = dict({})
for event in opus_or_score[i]:
if event[0] == 'note':
num_notes_by_channel[event[3]] = num_notes_by_channel.get(event[3],0) + 1
if event[3] == 9:
percussion[event[4]] = percussion.get(event[4],0) + 1
else:
pitches[event[4]] = pitches.get(event[4],0) + 1
if event[4] > highest_pitch:
highest_pitch = event[4]
if event[4] < lowest_pitch:
lowest_pitch = event[4]
channels_this_track.add(event[3])
channels_total.add(event[3])
finish_time = event[1] + event[2]
if finish_time > nticks:
nticks = finish_time
elif event[0] == 'note_off' or (event[0] == 'note_on' and event[4] == 0): # 4.8
finish_time = event[1]
if finish_time > nticks:
nticks = finish_time
elif event[0] == 'note_on':
is_a_score = False
num_notes_by_channel[event[2]] = num_notes_by_channel.get(event[2],0) + 1
if event[2] == 9:
percussion[event[3]] = percussion.get(event[3],0) + 1
else:
pitches[event[3]] = pitches.get(event[3],0) + 1
if event[3] > highest_pitch:
highest_pitch = event[3]
if event[3] < lowest_pitch:
lowest_pitch = event[3]
channels_this_track.add(event[2])
channels_total.add(event[2])
elif event[0] == 'patch_change':
patch_changes_this_track[event[2]] = event[3]
patch_changes_total.add(event[3])
elif event[0] == 'control_change':
if event[3] == 0: # bank select MSB
bank_select_msb = event[4]
elif event[3] == 32: # bank select LSB
bank_select_lsb = event[4]
if bank_select_msb >= 0 and bank_select_lsb >= 0:
bank_select.append((bank_select_msb,bank_select_lsb))
bank_select_msb = -1
bank_select_lsb = -1
elif event[0] == 'sysex_f0':
if _sysex2midimode.get(event[2], -1) >= 0:
general_midi_mode.append(_sysex2midimode.get(event[2]))
if is_a_score:
if event[1] > nticks:
nticks = event[1]
else:
nticks += event[1]
if lowest_pitch == 128:
lowest_pitch = 0
channels_by_track.append(channels_this_track)
patch_changes_by_track.append(patch_changes_this_track)
pitch_range_by_track.append((lowest_pitch,highest_pitch))
pitch_range_sum += (highest_pitch-lowest_pitch)
i += 1
return {'bank_select':bank_select,
'channels_by_track':channels_by_track,
'channels_total':channels_total,
'general_midi_mode':general_midi_mode,
'ntracks':len(opus_or_score)-1,
'nticks':nticks,
'num_notes_by_channel':num_notes_by_channel,
'patch_changes_by_track':patch_changes_by_track,
'patch_changes_total':patch_changes_total,
'percussion':percussion,
'pitches':pitches,
'pitch_range_by_track':pitch_range_by_track,
'pitch_range_sum':pitch_range_sum,
'ticks_per_quarter':ticks_per_quarter}
#----------------------------- Event stuff --------------------------
_sysex2midimode = {
"\x7E\x7F\x09\x01\xF7": 1,
"\x7E\x7F\x09\x02\xF7": 0,
"\x7E\x7F\x09\x03\xF7": 2,
}
# Some public-access tuples:
MIDI_events = tuple('''note_off note_on key_after_touch
control_change patch_change channel_after_touch
pitch_wheel_change'''.split())
Text_events = tuple('''text_event copyright_text_event
track_name instrument_name lyric marker cue_point text_event_08
text_event_09 text_event_0a text_event_0b text_event_0c
text_event_0d text_event_0e text_event_0f'''.split())
Nontext_meta_events = tuple('''end_track set_tempo
smpte_offset time_signature key_signature sequencer_specific
raw_meta_event sysex_f0 sysex_f7 song_position song_select
tune_request'''.split())
# unsupported: raw_data
# Actually, 'tune_request' is is F-series event, not strictly a meta-event...
Meta_events = Text_events + Nontext_meta_events
All_events = MIDI_events + Meta_events
# And three dictionaries:
Number2patch = { # General MIDI patch numbers:
0:'Acoustic Grand',
1:'Bright Acoustic',
2:'Electric Grand',
3:'Honky-Tonk',
4:'Electric Piano 1',
5:'Electric Piano 2',
6:'Harpsichord',
7:'Clav',
8:'Celesta',
9:'Glockenspiel',
10:'Music Box',
11:'Vibraphone',
12:'Marimba',
13:'Xylophone',
14:'Tubular Bells',
15:'Dulcimer',
16:'Drawbar Organ',
17:'Percussive Organ',
18:'Rock Organ',
19:'Church Organ',
20:'Reed Organ',
21:'Accordion',
22:'Harmonica',
23:'Tango Accordion',
24:'Acoustic Guitar(nylon)',
25:'Acoustic Guitar(steel)',
26:'Electric Guitar(jazz)',
27:'Electric Guitar(clean)',
28:'Electric Guitar(muted)',
29:'Overdriven Guitar',
30:'Distortion Guitar',
31:'Guitar Harmonics',
32:'Acoustic Bass',
33:'Electric Bass(finger)',
34:'Electric Bass(pick)',