midiharmony 26.1.27__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3637 @@
1
+ r'''#===================================================================================================================
2
+ #
3
+ # MIDI to Colab AUdio Python Module
4
+ #
5
+ # Converts any MIDI file to raw audio which is compatible
6
+ # with Google Colab or HUgging Face Gradio
7
+ #
8
+ # Version 2.0
9
+ #
10
+ # Includes full source code of MIDI and pyfluidsynth
11
+ #
12
+ # Original source code for all modules was retrieved on 07/31/2025
13
+ #
14
+ # Project Los Angeles
15
+ # Tegridy Code 2025
16
+ #
17
+ #===================================================================================================================
18
+ #
19
+ # Critical dependencies
20
+ #
21
+ # pip install numpy
22
+ # sudo apt install fluidsynth
23
+ #
24
+ #===================================================================================================================
25
+ #
26
+ # Example usage:
27
+ #
28
+ # from midi_to_colab_audio import midi_to_colab_audio
29
+ # from IPython.display import display, Audio
30
+ #
31
+ # raw_audio = midi_to_colab_audio('/content/input.mid')
32
+ #
33
+ # display(Audio(raw_audio, rate=16000, normalize=False))
34
+ #
35
+ #===================================================================================================================
36
+ #! /usr/bin/python3
37
+ # unsupported 20091104 ...
38
+ # ['set_sequence_number', dtime, sequence]
39
+ # ['raw_data', dtime, raw]
40
+
41
+ # 20150914 jimbo1qaz MIDI.py str/bytes bug report
42
+ # I found a MIDI file which had Shift-JIS titles. When midi.py decodes it as
43
+ # latin-1, it produces a string which cannot even be accessed without raising
44
+ # a UnicodeDecodeError. Maybe, when converting raw byte strings from MIDI,
45
+ # you should keep them as bytes, not improperly decode them. However, this
46
+ # would change the API. (ie: text = a "string" ? of 0 or more bytes). It
47
+ # could break compatiblity, but there's not much else you can do to fix the bug
48
+ # https://en.wikipedia.org/wiki/Shift_JIS
49
+
50
+ This module offers functions: concatenate_scores(), grep(),
51
+ merge_scores(), mix_scores(), midi2opus(), midi2score(), opus2midi(),
52
+ opus2score(), play_score(), score2midi(), score2opus(), score2stats(),
53
+ score_type(), segment(), timeshift() and to_millisecs(),
54
+ where "midi" means the MIDI-file bytes (as can be put in a .mid file,
55
+ or piped into aplaymidi), and "opus" and "score" are list-structures
56
+ as inspired by Sean Burke's MIDI-Perl CPAN module.
57
+
58
+ Warning: Version 6.4 is not necessarily backward-compatible with
59
+ previous versions, in that text-data is now bytes, not strings.
60
+ This reflects the fact that many MIDI files have text data in
61
+ encodings other that ISO-8859-1, for example in Shift-JIS.
62
+
63
+ Download MIDI.py from http://www.pjb.com.au/midi/free/MIDI.py
64
+ and put it in your PYTHONPATH. MIDI.py depends on Python3.
65
+
66
+ There is also a call-compatible translation into Lua of this
67
+ module: see http://www.pjb.com.au/comp/lua/MIDI.html
68
+
69
+ Backup web site: https://peterbillam.gitlab.io/miditools/
70
+
71
+ The "opus" is a direct translation of the midi-file-events, where
72
+ the times are delta-times, in ticks, since the previous event.
73
+
74
+ The "score" is more human-centric; it uses absolute times, and
75
+ combines the separate note_on and note_off events into one "note"
76
+ event, with a duration:
77
+ ['note', start_time, duration, channel, note, velocity] # in a "score"
78
+
79
+ EVENTS (in an "opus" structure)
80
+ ['note_off', dtime, channel, note, velocity] # in an "opus"
81
+ ['note_on', dtime, channel, note, velocity] # in an "opus"
82
+ ['key_after_touch', dtime, channel, note, velocity]
83
+ ['control_change', dtime, channel, controller(0-127), value(0-127)]
84
+ ['patch_change', dtime, channel, patch]
85
+ ['channel_after_touch', dtime, channel, velocity]
86
+ ['pitch_wheel_change', dtime, channel, pitch_wheel]
87
+ ['text_event', dtime, text]
88
+ ['copyright_text_event', dtime, text]
89
+ ['track_name', dtime, text]
90
+ ['instrument_name', dtime, text]
91
+ ['lyric', dtime, text]
92
+ ['marker', dtime, text]
93
+ ['cue_point', dtime, text]
94
+ ['text_event_08', dtime, text]
95
+ ['text_event_09', dtime, text]
96
+ ['text_event_0a', dtime, text]
97
+ ['text_event_0b', dtime, text]
98
+ ['text_event_0c', dtime, text]
99
+ ['text_event_0d', dtime, text]
100
+ ['text_event_0e', dtime, text]
101
+ ['text_event_0f', dtime, text]
102
+ ['end_track', dtime]
103
+ ['set_tempo', dtime, tempo]
104
+ ['smpte_offset', dtime, hr, mn, se, fr, ff]
105
+ ['time_signature', dtime, nn, dd, cc, bb]
106
+ ['key_signature', dtime, sf, mi]
107
+ ['sequencer_specific', dtime, raw]
108
+ ['raw_meta_event', dtime, command(0-255), raw]
109
+ ['sysex_f0', dtime, raw]
110
+ ['sysex_f7', dtime, raw]
111
+ ['song_position', dtime, song_pos]
112
+ ['song_select', dtime, song_number]
113
+ ['tune_request', dtime]
114
+
115
+ DATA TYPES
116
+ channel = a value 0 to 15
117
+ controller = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html#cc )
118
+ dtime = time measured in "ticks", 0 to 268435455
119
+ velocity = a value 0 (soft) to 127 (loud)
120
+ note = a value 0 to 127 (middle-C is 60)
121
+ patch = 0 to 127 (see http://www.pjb.com.au/muscript/gm.html )
122
+ pitch_wheel = a value -8192 to 8191 (0x1FFF)
123
+ raw = bytes, of length 0 or more (for sysex events see below)
124
+ sequence_number = a value 0 to 65,535 (0xFFFF)
125
+ song_pos = a value 0 to 16,383 (0x3FFF)
126
+ song_number = a value 0 to 127
127
+ tempo = microseconds per crochet (quarter-note), 0 to 16777215
128
+ text = bytes, of length 0 or more
129
+ ticks = the number of ticks per crochet (quarter-note)
130
+
131
+ In sysex_f0 events, the raw data must not start with a \xF0 byte,
132
+ since this gets added automatically;
133
+ but it must end with an explicit \xF7 byte!
134
+ In the very unlikely case that you ever need to split sysex data
135
+ into one sysex_f0 followed by one or more sysex_f7s, then only the
136
+ last of those sysex_f7 events must end with the explicit \xF7 byte
137
+ (again, the raw data of individual sysex_f7 events must not start
138
+ with any \xF7 byte, since this gets added automatically).
139
+
140
+ Since version 6.4, text data is in bytes, not in a ISO-8859-1 string.
141
+
142
+
143
+ GOING THROUGH A SCORE WITHIN A PYTHON PROGRAM
144
+ channels = {2,3,5,8,13}
145
+ itrack = 1 # skip 1st element which is ticks
146
+ while itrack < len(score):
147
+ for event in score[itrack]:
148
+ if event[0] == 'note': # for example,
149
+ pass # do something to all notes
150
+ # or, to work on events in only particular channels...
151
+ channel_index = MIDI.Event2channelindex.get(event[0], False)
152
+ if channel_index and (event[channel_index] in channels):
153
+ pass # do something to channels 2,3,5,8 and 13
154
+ itrack += 1
155
+
156
+ '''
157
+
158
+ import sys, struct, copy
159
+ # sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb')
160
+ Version = '6.7'
161
+ VersionDate = '20201120'
162
+ # 20201120 6.7 call to bytest() removed, and protect _unshift_ber_int
163
+ # 20160702 6.6 to_millisecs() now handles set_tempo across multiple Tracks
164
+ # 20150921 6.5 segment restores controllers as well as patch and tempo
165
+ # 20150914 6.4 text data is bytes or bytearray, not ISO-8859-1 strings
166
+ # 20150628 6.3 absent any set_tempo, default is 120bpm (see MIDI file spec 1.1)
167
+ # 20150101 6.2 all text events can be 8-bit; let user get the right encoding
168
+ # 20141231 6.1 fix _some_text_event; sequencer_specific data can be 8-bit
169
+ # 20141230 6.0 synth_specific data can be 8-bit
170
+ # 20120504 5.9 add the contents of mid_opus_tracks()
171
+ # 20120208 5.8 fix num_notes_by_channel() ; should be a dict
172
+ # 20120129 5.7 _encode handles empty tracks; score2stats num_notes_by_channel
173
+ # 20111111 5.6 fix patch 45 and 46 in Number2patch, should be Harp
174
+ # 20110129 5.5 add mix_opus_tracks() and event2alsaseq()
175
+ # 20110126 5.4 "previous message repeated N times" to save space on stderr
176
+ # 20110125 5.2 opus2score terminates unended notes at the end of the track
177
+ # 20110124 5.1 the warnings in midi2opus display track_num
178
+ # 21110122 5.0 if garbage, midi2opus returns the opus so far
179
+ # 21110119 4.9 non-ascii chars stripped out of the text_events
180
+ # 21110110 4.8 note_on with velocity=0 treated as a note-off
181
+ # 21110108 4.6 unknown F-series event correctly eats just one byte
182
+ # 21011010 4.2 segment() uses start_time, end_time named params
183
+ # 21011005 4.1 timeshift() must not pad the set_tempo command
184
+ # 21011003 4.0 pitch2note_event must be chapitch2note_event
185
+ # 21010918 3.9 set_sequence_number supported, FWIW
186
+ # 20100913 3.7 many small bugfixes; passes all tests
187
+ # 20100910 3.6 concatenate_scores enforce ticks=1000, just like merge_scores
188
+ # 20100908 3.5 minor bugs fixed in score2stats
189
+ # 20091104 3.4 tune_request now supported
190
+ # 20091104 3.3 fixed bug in decoding song_position and song_select
191
+ # 20091104 3.2 unsupported: set_sequence_number tune_request raw_data
192
+ # 20091101 3.1 document how to traverse a score within Python
193
+ # 20091021 3.0 fixed bug in score2stats detecting GM-mode = 0
194
+ # 20091020 2.9 score2stats reports GM-mode and bank msb,lsb events
195
+ # 20091019 2.8 in merge_scores, channel 9 must remain channel 9 (in GM)
196
+ # 20091018 2.7 handles empty tracks gracefully
197
+ # 20091015 2.6 grep() selects channels
198
+ # 20091010 2.5 merge_scores reassigns channels to avoid conflicts
199
+ # 20091010 2.4 fixed bug in to_millisecs which now only does opusses
200
+ # 20091010 2.3 score2stats returns channels & patch_changes, by_track & total
201
+ # 20091010 2.2 score2stats() returns also pitches and percussion dicts
202
+ # 20091010 2.1 bugs: >= not > in segment, to notice patch_change at time 0
203
+ # 20091010 2.0 bugs: spurious pop(0) ( in _decode sysex
204
+ # 20091008 1.9 bugs: ISO decoding in sysex; str( not int( in note-off warning
205
+ # 20091008 1.8 add concatenate_scores()
206
+ # 20091006 1.7 score2stats() measures nticks and ticks_per_quarter
207
+ # 20091004 1.6 first mix_scores() and merge_scores()
208
+ # 20090424 1.5 timeshift() bugfix: earliest only sees events after from_time
209
+ # 20090330 1.4 timeshift() has also a from_time argument
210
+ # 20090322 1.3 timeshift() has also a start_time argument
211
+ # 20090319 1.2 add segment() and timeshift()
212
+ # 20090301 1.1 add to_millisecs()
213
+
214
+ _previous_warning = '' # 5.4
215
+ _previous_times = 0 # 5.4
216
+ #------------------------------- Encoding stuff --------------------------
217
+
218
+ def opus2midi(opus=[]):
219
+ r'''The argument is a list: the first item in the list is the "ticks"
220
+ parameter, the others are the tracks. Each track is a list
221
+ of midi-events, and each event is itself a list; see above.
222
+ opus2midi() returns a bytestring of the MIDI, which can then be
223
+ written either to a file opened in binary mode (mode='wb'),
224
+ or to stdout by means of: sys.stdout.buffer.write()
225
+
226
+ my_opus = [
227
+ 96,
228
+ [ # track 0:
229
+ ['patch_change', 0, 1, 8], # and these are the events...
230
+ ['note_on', 5, 1, 25, 96],
231
+ ['note_off', 96, 1, 25, 0],
232
+ ['note_on', 0, 1, 29, 96],
233
+ ['note_off', 96, 1, 29, 0],
234
+ ], # end of track 0
235
+ ]
236
+ my_midi = opus2midi(my_opus)
237
+ sys.stdout.buffer.write(my_midi)
238
+ '''
239
+ if len(opus) < 2:
240
+ opus=[1000, [],]
241
+ tracks = copy.deepcopy(opus)
242
+ ticks = int(tracks.pop(0))
243
+ ntracks = len(tracks)
244
+ if ntracks == 1:
245
+ format = 0
246
+ else:
247
+ format = 1
248
+
249
+ my_midi = b"MThd\x00\x00\x00\x06"+struct.pack('>HHH',format,ntracks,ticks)
250
+ for track in tracks:
251
+ events = _encode(track)
252
+ my_midi += b'MTrk' + struct.pack('>I',len(events)) + events
253
+ _clean_up_warnings()
254
+ return my_midi
255
+
256
+
257
+ def score2opus(score=None):
258
+ r'''
259
+ The argument is a list: the first item in the list is the "ticks"
260
+ parameter, the others are the tracks. Each track is a list
261
+ of score-events, and each event is itself a list. A score-event
262
+ is similar to an opus-event (see above), except that in a score:
263
+ 1) the times are expressed as an absolute number of ticks
264
+ from the track's start time
265
+ 2) the pairs of 'note_on' and 'note_off' events in an "opus"
266
+ are abstracted into a single 'note' event in a "score":
267
+ ['note', start_time, duration, channel, pitch, velocity]
268
+ score2opus() returns a list specifying the equivalent "opus".
269
+
270
+ my_score = [
271
+ 96,
272
+ [ # track 0:
273
+ ['patch_change', 0, 1, 8],
274
+ ['note', 5, 96, 1, 25, 96],
275
+ ['note', 101, 96, 1, 29, 96]
276
+ ], # end of track 0
277
+ ]
278
+ my_opus = score2opus(my_score)
279
+ '''
280
+ if len(score) < 2:
281
+ score=[1000, [],]
282
+ tracks = copy.deepcopy(score)
283
+ ticks = int(tracks.pop(0))
284
+ opus_tracks = []
285
+ for scoretrack in tracks:
286
+ time2events = dict([])
287
+ for scoreevent in scoretrack:
288
+ if scoreevent[0] == 'note':
289
+ note_on_event = ['note_on',scoreevent[1],
290
+ scoreevent[3],scoreevent[4],scoreevent[5]]
291
+ note_off_event = ['note_off',scoreevent[1]+scoreevent[2],
292
+ scoreevent[3],scoreevent[4],scoreevent[5]]
293
+ if time2events.get(note_on_event[1]):
294
+ time2events[note_on_event[1]].append(note_on_event)
295
+ else:
296
+ time2events[note_on_event[1]] = [note_on_event,]
297
+ if time2events.get(note_off_event[1]):
298
+ time2events[note_off_event[1]].append(note_off_event)
299
+ else:
300
+ time2events[note_off_event[1]] = [note_off_event,]
301
+ continue
302
+ if time2events.get(scoreevent[1]):
303
+ time2events[scoreevent[1]].append(scoreevent)
304
+ else:
305
+ time2events[scoreevent[1]] = [scoreevent,]
306
+
307
+ sorted_times = [] # list of keys
308
+ for k in time2events.keys():
309
+ sorted_times.append(k)
310
+ sorted_times.sort()
311
+
312
+ sorted_events = [] # once-flattened list of values sorted by key
313
+ for time in sorted_times:
314
+ sorted_events.extend(time2events[time])
315
+
316
+ abs_time = 0
317
+ for event in sorted_events: # convert abs times => delta times
318
+ delta_time = event[1] - abs_time
319
+ abs_time = event[1]
320
+ event[1] = delta_time
321
+ opus_tracks.append(sorted_events)
322
+ opus_tracks.insert(0,ticks)
323
+ _clean_up_warnings()
324
+ return opus_tracks
325
+
326
+ def score2midi(score=None):
327
+ r'''
328
+ Translates a "score" into MIDI, using score2opus() then opus2midi()
329
+ '''
330
+ return opus2midi(score2opus(score))
331
+
332
+ #--------------------------- Decoding stuff ------------------------
333
+
334
+ def midi2opus(midi=b''):
335
+ r'''Translates MIDI into a "opus". For a description of the
336
+ "opus" format, see opus2midi()
337
+ '''
338
+ my_midi=bytearray(midi)
339
+ if len(my_midi) < 4:
340
+ _clean_up_warnings()
341
+ return [1000,[],]
342
+ id = bytes(my_midi[0:4])
343
+ if id != b'MThd':
344
+ _warn("midi2opus: midi starts with "+str(id)+" instead of 'MThd'")
345
+ _clean_up_warnings()
346
+ return [1000,[],]
347
+ [length, format, tracks_expected, ticks] = struct.unpack(
348
+ '>IHHH', bytes(my_midi[4:14]))
349
+ if length != 6:
350
+ _warn("midi2opus: midi header length was "+str(length)+" instead of 6")
351
+ _clean_up_warnings()
352
+ return [1000,[],]
353
+ my_opus = [ticks,]
354
+ my_midi = my_midi[14:]
355
+ track_num = 1 # 5.1
356
+ while len(my_midi) >= 8:
357
+ track_type = bytes(my_midi[0:4])
358
+ if track_type != b'MTrk':
359
+ _warn('midi2opus: Warning: track #'+str(track_num)+' type is '+str(track_type)+" instead of b'MTrk'")
360
+ [track_length] = struct.unpack('>I', my_midi[4:8])
361
+ my_midi = my_midi[8:]
362
+ if track_length > len(my_midi):
363
+ _warn('midi2opus: track #'+str(track_num)+' length '+str(track_length)+' is too large')
364
+ _clean_up_warnings()
365
+ return my_opus # 5.0
366
+ my_midi_track = my_midi[0:track_length]
367
+ my_track = _decode(my_midi_track)
368
+ my_opus.append(my_track)
369
+ my_midi = my_midi[track_length:]
370
+ track_num += 1 # 5.1
371
+ _clean_up_warnings()
372
+ return my_opus
373
+
374
+ def opus2score(opus=[]):
375
+ r'''For a description of the "opus" and "score" formats,
376
+ see opus2midi() and score2opus().
377
+ '''
378
+ if len(opus) < 2:
379
+ _clean_up_warnings()
380
+ return [1000,[],]
381
+ tracks = copy.deepcopy(opus) # couple of slices probably quicker...
382
+ ticks = int(tracks.pop(0))
383
+ score = [ticks,]
384
+ for opus_track in tracks:
385
+ ticks_so_far = 0
386
+ score_track = []
387
+ chapitch2note_on_events = dict([]) # 4.0
388
+ for opus_event in opus_track:
389
+ ticks_so_far += opus_event[1]
390
+ if opus_event[0] == 'note_off' or (opus_event[0] == 'note_on' and opus_event[4] == 0): # 4.8
391
+ cha = opus_event[2]
392
+ pitch = opus_event[3]
393
+ key = cha*128 + pitch
394
+ if chapitch2note_on_events.get(key):
395
+ new_event = chapitch2note_on_events[key].pop(0)
396
+ new_event[2] = ticks_so_far - new_event[1]
397
+ score_track.append(new_event)
398
+ elif pitch > 127:
399
+ pass #_warn('opus2score: note_off with no note_on, bad pitch='+str(pitch))
400
+ else:
401
+ pass #_warn('opus2score: note_off with no note_on cha='+str(cha)+' pitch='+str(pitch))
402
+ elif opus_event[0] == 'note_on':
403
+ cha = opus_event[2]
404
+ pitch = opus_event[3]
405
+ key = cha*128 + pitch
406
+ new_event = ['note',ticks_so_far,0,cha,pitch, opus_event[4]]
407
+ if chapitch2note_on_events.get(key):
408
+ chapitch2note_on_events[key].append(new_event)
409
+ else:
410
+ chapitch2note_on_events[key] = [new_event,]
411
+ else:
412
+ opus_event[1] = ticks_so_far
413
+ score_track.append(opus_event)
414
+ # check for unterminated notes (Oisín) -- 5.2
415
+ for chapitch in chapitch2note_on_events:
416
+ note_on_events = chapitch2note_on_events[chapitch]
417
+ for new_e in note_on_events:
418
+ new_e[2] = ticks_so_far - new_e[1]
419
+ score_track.append(new_e)
420
+ pass #_warn("opus2score: note_on with no note_off cha="+str(new_e[3])+' pitch='+str(new_e[4])+'; adding note_off at end')
421
+ score.append(score_track)
422
+ _clean_up_warnings()
423
+ return score
424
+
425
+ def midi2score(midi=b''):
426
+ r'''
427
+ Translates MIDI into a "score", using midi2opus() then opus2score()
428
+ '''
429
+ return opus2score(midi2opus(midi))
430
+
431
+ def midi2ms_score(midi=b''):
432
+ r'''
433
+ Translates MIDI into a "score" with one beat per second and one
434
+ tick per millisecond, using midi2opus() then to_millisecs()
435
+ then opus2score()
436
+ '''
437
+ return opus2score(to_millisecs(midi2opus(midi)))
438
+
439
+ #------------------------ Other Transformations ---------------------
440
+
441
+ def to_millisecs(old_opus=None):
442
+ r'''Recallibrates all the times in an "opus" to use one beat
443
+ per second and one tick per millisecond. This makes it
444
+ hard to retrieve any information about beats or barlines,
445
+ but it does make it easy to mix different scores together.
446
+ '''
447
+ if old_opus == None:
448
+ return [1000,[],]
449
+ try:
450
+ old_tpq = int(old_opus[0])
451
+ except IndexError: # 5.0
452
+ _warn('to_millisecs: the opus '+str(type(old_opus))+' has no elements')
453
+ return [1000,[],]
454
+ new_opus = [1000,]
455
+ # 6.7 first go through building a table of set_tempos by absolute-tick
456
+ ticks2tempo = {}
457
+ itrack = 1
458
+ while itrack < len(old_opus):
459
+ ticks_so_far = 0
460
+ for old_event in old_opus[itrack]:
461
+ if old_event[0] == 'note':
462
+ raise TypeError('to_millisecs needs an opus, not a score')
463
+ ticks_so_far += old_event[1]
464
+ if old_event[0] == 'set_tempo':
465
+ ticks2tempo[ticks_so_far] = old_event[2]
466
+ itrack += 1
467
+ # then get the sorted-array of their keys
468
+ tempo_ticks = [] # list of keys
469
+ for k in ticks2tempo.keys():
470
+ tempo_ticks.append(k)
471
+ tempo_ticks.sort()
472
+ # then go through converting to millisec, testing if the next
473
+ # set_tempo lies before the next track-event, and using it if so.
474
+ itrack = 1
475
+ while itrack < len(old_opus):
476
+ ms_per_old_tick = 500.0 / old_tpq # float: will round later 6.3
477
+ i_tempo_ticks = 0
478
+ ticks_so_far = 0
479
+ ms_so_far = 0.0
480
+ previous_ms_so_far = 0.0
481
+ new_track = [['set_tempo',0,1000000],] # new "crochet" is 1 sec
482
+ for old_event in old_opus[itrack]:
483
+ # detect if ticks2tempo has something before this event
484
+ # 20160702 if ticks2tempo is at the same time, leave it
485
+ event_delta_ticks = old_event[1]
486
+ if (i_tempo_ticks < len(tempo_ticks) and
487
+ tempo_ticks[i_tempo_ticks] < (ticks_so_far + old_event[1])):
488
+ delta_ticks = tempo_ticks[i_tempo_ticks] - ticks_so_far
489
+ ms_so_far += (ms_per_old_tick * delta_ticks)
490
+ ticks_so_far = tempo_ticks[i_tempo_ticks]
491
+ ms_per_old_tick = ticks2tempo[ticks_so_far] / (1000.0*old_tpq)
492
+ i_tempo_ticks += 1
493
+ event_delta_ticks -= delta_ticks
494
+ new_event = copy.deepcopy(old_event) # now handle the new event
495
+ ms_so_far += (ms_per_old_tick * old_event[1])
496
+ new_event[1] = round(ms_so_far - previous_ms_so_far)
497
+ if old_event[0] != 'set_tempo':
498
+ previous_ms_so_far = ms_so_far
499
+ new_track.append(new_event)
500
+ ticks_so_far += event_delta_ticks
501
+ new_opus.append(new_track)
502
+ itrack += 1
503
+ _clean_up_warnings()
504
+ return new_opus
505
+
506
+ def event2alsaseq(event=None): # 5.5
507
+ r'''Converts an event into the format needed by the alsaseq module,
508
+ http://pp.com.mx/python/alsaseq
509
+ The type of track (opus or score) is autodetected.
510
+ '''
511
+ pass
512
+
513
+ def grep(score=None, channels=None):
514
+ r'''Returns a "score" containing only the channels specified
515
+ '''
516
+ if score == None:
517
+ return [1000,[],]
518
+ ticks = score[0]
519
+ new_score = [ticks,]
520
+ if channels == None:
521
+ return new_score
522
+ channels = set(channels)
523
+ global Event2channelindex
524
+ itrack = 1
525
+ while itrack < len(score):
526
+ new_score.append([])
527
+ for event in score[itrack]:
528
+ channel_index = Event2channelindex.get(event[0], False)
529
+ if channel_index:
530
+ if event[channel_index] in channels:
531
+ new_score[itrack].append(event)
532
+ else:
533
+ new_score[itrack].append(event)
534
+ itrack += 1
535
+ return new_score
536
+
537
+ def play_score(score=None):
538
+ r'''Converts the "score" to midi, and feeds it into 'aplaymidi -'
539
+ '''
540
+ if score == None:
541
+ return
542
+ import subprocess
543
+ pipe = subprocess.Popen(['aplaymidi','-'], stdin=subprocess.PIPE)
544
+ if score_type(score) == 'opus':
545
+ pipe.stdin.write(opus2midi(score))
546
+ else:
547
+ pipe.stdin.write(score2midi(score))
548
+ pipe.stdin.close()
549
+
550
+ 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}):
551
+ r'''Returns a "score" shifted in time by "shift" ticks, or shifted
552
+ so that the first event starts at "start_time" ticks.
553
+
554
+ If "from_time" is specified, only those events in the score
555
+ that begin after it are shifted. If "start_time" is less than
556
+ "from_time" (or "shift" is negative), then the intermediate
557
+ notes are deleted, though patch-change events are preserved.
558
+
559
+ If "tracks" are specified, then only those tracks get shifted.
560
+ "tracks" can be a list, tuple or set; it gets converted to set
561
+ internally.
562
+
563
+ It is deprecated to specify both "shift" and "start_time".
564
+ If this does happen, timeshift() will print a warning to
565
+ stderr and ignore the "shift" argument.
566
+
567
+ If "shift" is negative and sufficiently large that it would
568
+ leave some event with a negative tick-value, then the score
569
+ is shifted so that the first event occurs at time 0. This
570
+ also occurs if "start_time" is negative, and is also the
571
+ default if neither "shift" nor "start_time" are specified.
572
+ '''
573
+ #_warn('tracks='+str(tracks))
574
+ if score == None or len(score) < 2:
575
+ return [1000, [],]
576
+ new_score = [score[0],]
577
+ my_type = score_type(score)
578
+ if my_type == '':
579
+ return new_score
580
+ if my_type == 'opus':
581
+ _warn("timeshift: opus format is not supported\n")
582
+ # _clean_up_scores() 6.2; doesn't exist! what was it supposed to do?
583
+ return new_score
584
+ if not (shift == None) and not (start_time == None):
585
+ _warn("timeshift: shift and start_time specified: ignoring shift\n")
586
+ shift = None
587
+ if shift == None:
588
+ if (start_time == None) or (start_time < 0):
589
+ start_time = 0
590
+ # shift = start_time - from_time
591
+
592
+ i = 1 # ignore first element (ticks)
593
+ tracks = set(tracks) # defend against tuples and lists
594
+ earliest = 1000000000
595
+ if not (start_time == None) or shift < 0: # first find the earliest event
596
+ while i < len(score):
597
+ if len(tracks) and not ((i-1) in tracks):
598
+ i += 1
599
+ continue
600
+ for event in score[i]:
601
+ if event[1] < from_time:
602
+ continue # just inspect the to_be_shifted events
603
+ if event[1] < earliest:
604
+ earliest = event[1]
605
+ i += 1
606
+ if earliest > 999999999:
607
+ earliest = 0
608
+ if shift == None:
609
+ shift = start_time - earliest
610
+ elif (earliest + shift) < 0:
611
+ start_time = 0
612
+ shift = 0 - earliest
613
+
614
+ i = 1 # ignore first element (ticks)
615
+ while i < len(score):
616
+ if len(tracks) == 0 or not ((i-1) in tracks): # 3.8
617
+ new_score.append(score[i])
618
+ i += 1
619
+ continue
620
+ new_track = []
621
+ for event in score[i]:
622
+ new_event = list(event)
623
+ #if new_event[1] == 0 and shift > 0 and new_event[0] != 'note':
624
+ # pass
625
+ #elif new_event[1] >= from_time:
626
+ if new_event[1] >= from_time:
627
+ # 4.1 must not rightshift set_tempo
628
+ if new_event[0] != 'set_tempo' or shift<0:
629
+ new_event[1] += shift
630
+ elif (shift < 0) and (new_event[1] >= (from_time+shift)):
631
+ continue
632
+ new_track.append(new_event)
633
+ if len(new_track) > 0:
634
+ new_score.append(new_track)
635
+ i += 1
636
+ _clean_up_warnings()
637
+ return new_score
638
+
639
+ def segment(score=None, start_time=None, end_time=None, start=0, end=100000000,
640
+ tracks={0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}):
641
+ r'''Returns a "score" which is a segment of the one supplied
642
+ as the argument, beginning at "start_time" ticks and ending
643
+ at "end_time" ticks (or at the end if "end_time" is not supplied).
644
+ If the set "tracks" is specified, only those tracks will
645
+ be returned.
646
+ '''
647
+ if score == None or len(score) < 2:
648
+ return [1000, [],]
649
+ if start_time == None: # as of 4.2 start_time is recommended
650
+ start_time = start # start is legacy usage
651
+ if end_time == None: # likewise
652
+ end_time = end
653
+ new_score = [score[0],]
654
+ my_type = score_type(score)
655
+ if my_type == '':
656
+ return new_score
657
+ if my_type == 'opus':
658
+ # more difficult (disconnecting note_on's from their note_off's)...
659
+ _warn("segment: opus format is not supported\n")
660
+ _clean_up_warnings()
661
+ return new_score
662
+ i = 1 # ignore first element (ticks); we count in ticks anyway
663
+ tracks = set(tracks) # defend against tuples and lists
664
+ while i < len(score):
665
+ if len(tracks) and not ((i-1) in tracks):
666
+ i += 1
667
+ continue
668
+ new_track = []
669
+ channel2cc_num = {} # most recent controller change before start
670
+ channel2cc_val = {}
671
+ channel2cc_time = {}
672
+ channel2patch_num = {} # keep most recent patch change before start
673
+ channel2patch_time = {}
674
+ set_tempo_num = 500000 # most recent tempo change before start 6.3
675
+ set_tempo_time = 0
676
+ earliest_note_time = end_time
677
+ for event in score[i]:
678
+ if event[0] == 'control_change': # 6.5
679
+ cc_time = channel2cc_time.get(event[2]) or 0
680
+ if (event[1] <= start_time) and (event[1] >= cc_time):
681
+ channel2cc_num[event[2]] = event[3]
682
+ channel2cc_val[event[2]] = event[4]
683
+ channel2cc_time[event[2]] = event[1]
684
+ elif event[0] == 'patch_change':
685
+ patch_time = channel2patch_time.get(event[2]) or 0
686
+ if (event[1]<=start_time) and (event[1] >= patch_time): # 2.0
687
+ channel2patch_num[event[2]] = event[3]
688
+ channel2patch_time[event[2]] = event[1]
689
+ elif event[0] == 'set_tempo':
690
+ if (event[1]<=start_time) and (event[1]>=set_tempo_time): #6.4
691
+ set_tempo_num = event[2]
692
+ set_tempo_time = event[1]
693
+ if (event[1] >= start_time) and (event[1] <= end_time):
694
+ new_track.append(event)
695
+ if (event[0] == 'note') and (event[1] < earliest_note_time):
696
+ earliest_note_time = event[1]
697
+ if len(new_track) > 0:
698
+ new_track.append(['set_tempo', start_time, set_tempo_num])
699
+ for c in channel2patch_num:
700
+ new_track.append(['patch_change',start_time,c,channel2patch_num[c]],)
701
+ for c in channel2cc_num: # 6.5
702
+ new_track.append(['control_change',start_time,c,channel2cc_num[c],channel2cc_val[c]])
703
+ new_score.append(new_track)
704
+ i += 1
705
+ _clean_up_warnings()
706
+ return new_score
707
+
708
+ def score_type(opus_or_score=None):
709
+ r'''Returns a string, either 'opus' or 'score' or ''
710
+ '''
711
+ if opus_or_score == None or str(type(opus_or_score)).find('list')<0 or len(opus_or_score) < 2:
712
+ return ''
713
+ i = 1 # ignore first element
714
+ while i < len(opus_or_score):
715
+ for event in opus_or_score[i]:
716
+ if event[0] == 'note':
717
+ return 'score'
718
+ elif event[0] == 'note_on':
719
+ return 'opus'
720
+ i += 1
721
+ return ''
722
+
723
+ def concatenate_scores(scores):
724
+ r'''Concatenates a list of scores into one score.
725
+ If the scores differ in their "ticks" parameter,
726
+ they will all get converted to millisecond-tick format.
727
+ '''
728
+ # the deepcopys are needed if the input_score's are refs to the same obj
729
+ # e.g. if invoked by midisox's repeat()
730
+ input_scores = _consistentise_ticks(scores) # 3.7
731
+ output_score = copy.deepcopy(input_scores[0])
732
+ for input_score in input_scores[1:]:
733
+ output_stats = score2stats(output_score)
734
+ delta_ticks = output_stats['nticks']
735
+ itrack = 1
736
+ while itrack < len(input_score):
737
+ if itrack >= len(output_score): # new output track if doesn't exist
738
+ output_score.append([])
739
+ for event in input_score[itrack]:
740
+ output_score[itrack].append(copy.deepcopy(event))
741
+ output_score[itrack][-1][1] += delta_ticks
742
+ itrack += 1
743
+ return output_score
744
+
745
+ def merge_scores(scores):
746
+ r'''Merges a list of scores into one score. A merged score comprises
747
+ all of the tracks from all of the input scores; un-merging is possible
748
+ by selecting just some of the tracks. If the scores differ in their
749
+ "ticks" parameter, they will all get converted to millisecond-tick
750
+ format. merge_scores attempts to resolve channel-conflicts,
751
+ but there are of course only 15 available channels...
752
+ '''
753
+ input_scores = _consistentise_ticks(scores) # 3.6
754
+ output_score = [1000]
755
+ channels_so_far = set()
756
+ all_channels = {0,1,2,3,4,5,6,7,8,10,11,12,13,14,15}
757
+ global Event2channelindex
758
+ for input_score in input_scores:
759
+ new_channels = set(score2stats(input_score).get('channels_total', []))
760
+ new_channels.discard(9) # 2.8 cha9 must remain cha9 (in GM)
761
+ for channel in channels_so_far & new_channels:
762
+ # consistently choose lowest avaiable, to ease testing
763
+ free_channels = list(all_channels - (channels_so_far|new_channels))
764
+ if len(free_channels) > 0:
765
+ free_channels.sort()
766
+ free_channel = free_channels[0]
767
+ else:
768
+ free_channel = None
769
+ break
770
+ itrack = 1
771
+ while itrack < len(input_score):
772
+ for input_event in input_score[itrack]:
773
+ channel_index=Event2channelindex.get(input_event[0],False)
774
+ if channel_index and input_event[channel_index]==channel:
775
+ input_event[channel_index] = free_channel
776
+ itrack += 1
777
+ channels_so_far.add(free_channel)
778
+
779
+ channels_so_far |= new_channels
780
+ output_score.extend(input_score[1:])
781
+ return output_score
782
+
783
+ def _ticks(event):
784
+ return event[1]
785
+ def mix_opus_tracks(input_tracks): # 5.5
786
+ r'''Mixes an array of tracks into one track. A mixed track
787
+ cannot be un-mixed. It is assumed that the tracks share the same
788
+ ticks parameter and the same tempo.
789
+ Mixing score-tracks is trivial (just insert all events into one array).
790
+ Mixing opus-tracks is only slightly harder, but it's common enough
791
+ that a dedicated function is useful.
792
+ '''
793
+ output_score = [1000, []]
794
+ for input_track in input_tracks: # 5.8
795
+ input_score = opus2score([1000, input_track])
796
+ for event in input_score[1]:
797
+ output_score[1].append(event)
798
+ output_score[1].sort(key=_ticks)
799
+ output_opus = score2opus(output_score)
800
+ return output_opus[1]
801
+
802
+ def mix_scores(scores):
803
+ r'''Mixes a list of scores into one one-track score.
804
+ A mixed score cannot be un-mixed. Hopefully the scores
805
+ have no undesirable channel-conflicts between them.
806
+ If the scores differ in their "ticks" parameter,
807
+ they will all get converted to millisecond-tick format.
808
+ '''
809
+ input_scores = _consistentise_ticks(scores) # 3.6
810
+ output_score = [1000, []]
811
+ for input_score in input_scores:
812
+ for input_track in input_score[1:]:
813
+ output_score[1].extend(input_track)
814
+ return output_score
815
+
816
+ def score2stats(opus_or_score=None):
817
+ r'''Returns a dict of some basic stats about the score, like
818
+ bank_select (list of tuples (msb,lsb)),
819
+ channels_by_track (list of lists), channels_total (set),
820
+ general_midi_mode (list),
821
+ ntracks, nticks, patch_changes_by_track (list of dicts),
822
+ num_notes_by_channel (list of numbers),
823
+ patch_changes_total (set),
824
+ percussion (dict histogram of channel 9 events),
825
+ pitches (dict histogram of pitches on channels other than 9),
826
+ pitch_range_by_track (list, by track, of two-member-tuples),
827
+ pitch_range_sum (sum over tracks of the pitch_ranges),
828
+ '''
829
+ bank_select_msb = -1
830
+ bank_select_lsb = -1
831
+ bank_select = []
832
+ channels_by_track = []
833
+ channels_total = set([])
834
+ general_midi_mode = []
835
+ num_notes_by_channel = dict([])
836
+ patches_used_by_track = []
837
+ patches_used_total = set([])
838
+ patch_changes_by_track = []
839
+ patch_changes_total = set([])
840
+ percussion = dict([]) # histogram of channel 9 "pitches"
841
+ pitches = dict([]) # histogram of pitch-occurrences channels 0-8,10-15
842
+ pitch_range_sum = 0 # u pitch-ranges of each track
843
+ pitch_range_by_track = []
844
+ is_a_score = True
845
+ if opus_or_score == None:
846
+ return {'bank_select':[], 'channels_by_track':[], 'channels_total':[],
847
+ 'general_midi_mode':[], 'ntracks':0, 'nticks':0,
848
+ 'num_notes_by_channel':dict([]),
849
+ 'patch_changes_by_track':[], 'patch_changes_total':[],
850
+ 'percussion':{}, 'pitches':{}, 'pitch_range_by_track':[],
851
+ 'ticks_per_quarter':0, 'pitch_range_sum':0}
852
+ ticks_per_quarter = opus_or_score[0]
853
+ i = 1 # ignore first element, which is ticks
854
+ nticks = 0
855
+ while i < len(opus_or_score):
856
+ highest_pitch = 0
857
+ lowest_pitch = 128
858
+ channels_this_track = set([])
859
+ patch_changes_this_track = dict({})
860
+ for event in opus_or_score[i]:
861
+ if event[0] == 'note':
862
+ num_notes_by_channel[event[3]] = num_notes_by_channel.get(event[3],0) + 1
863
+ if event[3] == 9:
864
+ percussion[event[4]] = percussion.get(event[4],0) + 1
865
+ else:
866
+ pitches[event[4]] = pitches.get(event[4],0) + 1
867
+ if event[4] > highest_pitch:
868
+ highest_pitch = event[4]
869
+ if event[4] < lowest_pitch:
870
+ lowest_pitch = event[4]
871
+ channels_this_track.add(event[3])
872
+ channels_total.add(event[3])
873
+ finish_time = event[1] + event[2]
874
+ if finish_time > nticks:
875
+ nticks = finish_time
876
+ elif event[0] == 'note_off' or (event[0] == 'note_on' and event[4] == 0): # 4.8
877
+ finish_time = event[1]
878
+ if finish_time > nticks:
879
+ nticks = finish_time
880
+ elif event[0] == 'note_on':
881
+ is_a_score = False
882
+ num_notes_by_channel[event[2]] = num_notes_by_channel.get(event[2],0) + 1
883
+ if event[2] == 9:
884
+ percussion[event[3]] = percussion.get(event[3],0) + 1
885
+ else:
886
+ pitches[event[3]] = pitches.get(event[3],0) + 1
887
+ if event[3] > highest_pitch:
888
+ highest_pitch = event[3]
889
+ if event[3] < lowest_pitch:
890
+ lowest_pitch = event[3]
891
+ channels_this_track.add(event[2])
892
+ channels_total.add(event[2])
893
+ elif event[0] == 'patch_change':
894
+ patch_changes_this_track[event[2]] = event[3]
895
+ patch_changes_total.add(event[3])
896
+ elif event[0] == 'control_change':
897
+ if event[3] == 0: # bank select MSB
898
+ bank_select_msb = event[4]
899
+ elif event[3] == 32: # bank select LSB
900
+ bank_select_lsb = event[4]
901
+ if bank_select_msb >= 0 and bank_select_lsb >= 0:
902
+ bank_select.append((bank_select_msb,bank_select_lsb))
903
+ bank_select_msb = -1
904
+ bank_select_lsb = -1
905
+ elif event[0] == 'sysex_f0':
906
+ if _sysex2midimode.get(event[2], -1) >= 0:
907
+ general_midi_mode.append(_sysex2midimode.get(event[2]))
908
+ if is_a_score:
909
+ if event[1] > nticks:
910
+ nticks = event[1]
911
+ else:
912
+ nticks += event[1]
913
+ if lowest_pitch == 128:
914
+ lowest_pitch = 0
915
+ channels_by_track.append(channels_this_track)
916
+ patch_changes_by_track.append(patch_changes_this_track)
917
+ pitch_range_by_track.append((lowest_pitch,highest_pitch))
918
+ pitch_range_sum += (highest_pitch-lowest_pitch)
919
+ i += 1
920
+
921
+ return {'bank_select':bank_select,
922
+ 'channels_by_track':channels_by_track,
923
+ 'channels_total':channels_total,
924
+ 'general_midi_mode':general_midi_mode,
925
+ 'ntracks':len(opus_or_score)-1,
926
+ 'nticks':nticks,
927
+ 'num_notes_by_channel':num_notes_by_channel,
928
+ 'patch_changes_by_track':patch_changes_by_track,
929
+ 'patch_changes_total':patch_changes_total,
930
+ 'percussion':percussion,
931
+ 'pitches':pitches,
932
+ 'pitch_range_by_track':pitch_range_by_track,
933
+ 'pitch_range_sum':pitch_range_sum,
934
+ 'ticks_per_quarter':ticks_per_quarter}
935
+
936
+ #----------------------------- Event stuff --------------------------
937
+
938
+ _sysex2midimode = {
939
+ "\x7E\x7F\x09\x01\xF7": 1,
940
+ "\x7E\x7F\x09\x02\xF7": 0,
941
+ "\x7E\x7F\x09\x03\xF7": 2,
942
+ }
943
+
944
+ # Some public-access tuples:
945
+ MIDI_events = tuple('''note_off note_on key_after_touch
946
+ control_change patch_change channel_after_touch
947
+ pitch_wheel_change'''.split())
948
+
949
+ Text_events = tuple('''text_event copyright_text_event
950
+ track_name instrument_name lyric marker cue_point text_event_08
951
+ text_event_09 text_event_0a text_event_0b text_event_0c
952
+ text_event_0d text_event_0e text_event_0f'''.split())
953
+
954
+ Nontext_meta_events = tuple('''end_track set_tempo
955
+ smpte_offset time_signature key_signature sequencer_specific
956
+ raw_meta_event sysex_f0 sysex_f7 song_position song_select
957
+ tune_request'''.split())
958
+ # unsupported: raw_data
959
+
960
+ # Actually, 'tune_request' is is F-series event, not strictly a meta-event...
961
+ Meta_events = Text_events + Nontext_meta_events
962
+ All_events = MIDI_events + Meta_events
963
+
964
+ # And three dictionaries:
965
+ Number2patch = { # General MIDI patch numbers:
966
+ 0:'Acoustic Grand',
967
+ 1:'Bright Acoustic',
968
+ 2:'Electric Grand',
969
+ 3:'Honky-Tonk',
970
+ 4:'Electric Piano 1',
971
+ 5:'Electric Piano 2',
972
+ 6:'Harpsichord',
973
+ 7:'Clav',
974
+ 8:'Celesta',
975
+ 9:'Glockenspiel',
976
+ 10:'Music Box',
977
+ 11:'Vibraphone',
978
+ 12:'Marimba',
979
+ 13:'Xylophone',
980
+ 14:'Tubular Bells',
981
+ 15:'Dulcimer',
982
+ 16:'Drawbar Organ',
983
+ 17:'Percussive Organ',
984
+ 18:'Rock Organ',
985
+ 19:'Church Organ',
986
+ 20:'Reed Organ',
987
+ 21:'Accordion',
988
+ 22:'Harmonica',
989
+ 23:'Tango Accordion',
990
+ 24:'Acoustic Guitar(nylon)',
991
+ 25:'Acoustic Guitar(steel)',
992
+ 26:'Electric Guitar(jazz)',
993
+ 27:'Electric Guitar(clean)',
994
+ 28:'Electric Guitar(muted)',
995
+ 29:'Overdriven Guitar',
996
+ 30:'Distortion Guitar',
997
+ 31:'Guitar Harmonics',
998
+ 32:'Acoustic Bass',
999
+ 33:'Electric Bass(finger)',
1000
+ 34:'Electric Bass(pick)',
1001
+ 35:'Fretless Bass',
1002
+ 36:'Slap Bass 1',
1003
+ 37:'Slap Bass 2',
1004
+ 38:'Synth Bass 1',
1005
+ 39:'Synth Bass 2',
1006
+ 40:'Violin',
1007
+ 41:'Viola',
1008
+ 42:'Cello',
1009
+ 43:'Contrabass',
1010
+ 44:'Tremolo Strings',
1011
+ 45:'Pizzicato Strings',
1012
+ 46:'Orchestral Harp',
1013
+ 47:'Timpani',
1014
+ 48:'String Ensemble 1',
1015
+ 49:'String Ensemble 2',
1016
+ 50:'SynthStrings 1',
1017
+ 51:'SynthStrings 2',
1018
+ 52:'Choir Aahs',
1019
+ 53:'Voice Oohs',
1020
+ 54:'Synth Voice',
1021
+ 55:'Orchestra Hit',
1022
+ 56:'Trumpet',
1023
+ 57:'Trombone',
1024
+ 58:'Tuba',
1025
+ 59:'Muted Trumpet',
1026
+ 60:'French Horn',
1027
+ 61:'Brass Section',
1028
+ 62:'SynthBrass 1',
1029
+ 63:'SynthBrass 2',
1030
+ 64:'Soprano Sax',
1031
+ 65:'Alto Sax',
1032
+ 66:'Tenor Sax',
1033
+ 67:'Baritone Sax',
1034
+ 68:'Oboe',
1035
+ 69:'English Horn',
1036
+ 70:'Bassoon',
1037
+ 71:'Clarinet',
1038
+ 72:'Piccolo',
1039
+ 73:'Flute',
1040
+ 74:'Recorder',
1041
+ 75:'Pan Flute',
1042
+ 76:'Blown Bottle',
1043
+ 77:'Skakuhachi',
1044
+ 78:'Whistle',
1045
+ 79:'Ocarina',
1046
+ 80:'Lead 1 (square)',
1047
+ 81:'Lead 2 (sawtooth)',
1048
+ 82:'Lead 3 (calliope)',
1049
+ 83:'Lead 4 (chiff)',
1050
+ 84:'Lead 5 (charang)',
1051
+ 85:'Lead 6 (voice)',
1052
+ 86:'Lead 7 (fifths)',
1053
+ 87:'Lead 8 (bass+lead)',
1054
+ 88:'Pad 1 (new age)',
1055
+ 89:'Pad 2 (warm)',
1056
+ 90:'Pad 3 (polysynth)',
1057
+ 91:'Pad 4 (choir)',
1058
+ 92:'Pad 5 (bowed)',
1059
+ 93:'Pad 6 (metallic)',
1060
+ 94:'Pad 7 (halo)',
1061
+ 95:'Pad 8 (sweep)',
1062
+ 96:'FX 1 (rain)',
1063
+ 97:'FX 2 (soundtrack)',
1064
+ 98:'FX 3 (crystal)',
1065
+ 99:'FX 4 (atmosphere)',
1066
+ 100:'FX 5 (brightness)',
1067
+ 101:'FX 6 (goblins)',
1068
+ 102:'FX 7 (echoes)',
1069
+ 103:'FX 8 (sci-fi)',
1070
+ 104:'Sitar',
1071
+ 105:'Banjo',
1072
+ 106:'Shamisen',
1073
+ 107:'Koto',
1074
+ 108:'Kalimba',
1075
+ 109:'Bagpipe',
1076
+ 110:'Fiddle',
1077
+ 111:'Shanai',
1078
+ 112:'Tinkle Bell',
1079
+ 113:'Agogo',
1080
+ 114:'Steel Drums',
1081
+ 115:'Woodblock',
1082
+ 116:'Taiko Drum',
1083
+ 117:'Melodic Tom',
1084
+ 118:'Synth Drum',
1085
+ 119:'Reverse Cymbal',
1086
+ 120:'Guitar Fret Noise',
1087
+ 121:'Breath Noise',
1088
+ 122:'Seashore',
1089
+ 123:'Bird Tweet',
1090
+ 124:'Telephone Ring',
1091
+ 125:'Helicopter',
1092
+ 126:'Applause',
1093
+ 127:'Gunshot',
1094
+ }
1095
+ Notenum2percussion = { # General MIDI Percussion (on Channel 9):
1096
+ 35:'Acoustic Bass Drum',
1097
+ 36:'Bass Drum 1',
1098
+ 37:'Side Stick',
1099
+ 38:'Acoustic Snare',
1100
+ 39:'Hand Clap',
1101
+ 40:'Electric Snare',
1102
+ 41:'Low Floor Tom',
1103
+ 42:'Closed Hi-Hat',
1104
+ 43:'High Floor Tom',
1105
+ 44:'Pedal Hi-Hat',
1106
+ 45:'Low Tom',
1107
+ 46:'Open Hi-Hat',
1108
+ 47:'Low-Mid Tom',
1109
+ 48:'Hi-Mid Tom',
1110
+ 49:'Crash Cymbal 1',
1111
+ 50:'High Tom',
1112
+ 51:'Ride Cymbal 1',
1113
+ 52:'Chinese Cymbal',
1114
+ 53:'Ride Bell',
1115
+ 54:'Tambourine',
1116
+ 55:'Splash Cymbal',
1117
+ 56:'Cowbell',
1118
+ 57:'Crash Cymbal 2',
1119
+ 58:'Vibraslap',
1120
+ 59:'Ride Cymbal 2',
1121
+ 60:'Hi Bongo',
1122
+ 61:'Low Bongo',
1123
+ 62:'Mute Hi Conga',
1124
+ 63:'Open Hi Conga',
1125
+ 64:'Low Conga',
1126
+ 65:'High Timbale',
1127
+ 66:'Low Timbale',
1128
+ 67:'High Agogo',
1129
+ 68:'Low Agogo',
1130
+ 69:'Cabasa',
1131
+ 70:'Maracas',
1132
+ 71:'Short Whistle',
1133
+ 72:'Long Whistle',
1134
+ 73:'Short Guiro',
1135
+ 74:'Long Guiro',
1136
+ 75:'Claves',
1137
+ 76:'Hi Wood Block',
1138
+ 77:'Low Wood Block',
1139
+ 78:'Mute Cuica',
1140
+ 79:'Open Cuica',
1141
+ 80:'Mute Triangle',
1142
+ 81:'Open Triangle',
1143
+ }
1144
+
1145
+ Event2channelindex = { 'note':3, 'note_off':2, 'note_on':2,
1146
+ 'key_after_touch':2, 'control_change':2, 'patch_change':2,
1147
+ 'channel_after_touch':2, 'pitch_wheel_change':2
1148
+ }
1149
+
1150
+ ################################################################
1151
+ # The code below this line is full of frightening things, all to
1152
+ # do with the actual encoding and decoding of binary MIDI data.
1153
+
1154
+ def _twobytes2int(byte_a):
1155
+ r'''decode a 16 bit quantity from two bytes,'''
1156
+ return (byte_a[1] | (byte_a[0] << 8))
1157
+
1158
+ def _int2twobytes(int_16bit):
1159
+ r'''encode a 16 bit quantity into two bytes,'''
1160
+ return bytes([(int_16bit>>8) & 0xFF, int_16bit & 0xFF])
1161
+
1162
+ def _read_14_bit(byte_a):
1163
+ r'''decode a 14 bit quantity from two bytes,'''
1164
+ return (byte_a[0] | (byte_a[1] << 7))
1165
+
1166
+ def _write_14_bit(int_14bit):
1167
+ r'''encode a 14 bit quantity into two bytes,'''
1168
+ return bytes([int_14bit & 0x7F, (int_14bit>>7) & 0x7F])
1169
+
1170
+ def _ber_compressed_int(integer):
1171
+ r'''BER compressed integer (not an ASN.1 BER, see perlpacktut for
1172
+ details). Its bytes represent an unsigned integer in base 128,
1173
+ most significant digit first, with as few digits as possible.
1174
+ Bit eight (the high bit) is set on each byte except the last.
1175
+ '''
1176
+ ber = bytearray(b'')
1177
+ seven_bits = 0x7F & integer
1178
+ ber.insert(0, seven_bits) # XXX surely should convert to a char ?
1179
+ integer >>= 7
1180
+ while integer > 0:
1181
+ seven_bits = 0x7F & integer
1182
+ ber.insert(0, 0x80|seven_bits) # XXX surely should convert to a char ?
1183
+ integer >>= 7
1184
+ return ber
1185
+
1186
+ def _unshift_ber_int(ba):
1187
+ r'''Given a bytearray, returns a tuple of (the ber-integer at the
1188
+ start, and the remainder of the bytearray).
1189
+ '''
1190
+ if not len(ba): # 6.7
1191
+ _warn('_unshift_ber_int: no integer found')
1192
+ return ((0, b""))
1193
+ byte = ba.pop(0)
1194
+ integer = 0
1195
+ while True:
1196
+ integer += (byte & 0x7F)
1197
+ if not (byte & 0x80):
1198
+ return ((integer, ba))
1199
+ if not len(ba):
1200
+ _warn('_unshift_ber_int: no end-of-integer found')
1201
+ return ((0, ba))
1202
+ byte = ba.pop(0)
1203
+ integer <<= 7
1204
+
1205
+ def _clean_up_warnings(): # 5.4
1206
+ # Call this before returning from any publicly callable function
1207
+ # whenever there's a possibility that a warning might have been printed
1208
+ # by the function, or by any private functions it might have called.
1209
+ global _previous_times
1210
+ global _previous_warning
1211
+ if _previous_times > 1:
1212
+ # E:1176, 0: invalid syntax (<string>, line 1176) (syntax-error) ???
1213
+ # print(' previous message repeated '+str(_previous_times)+' times', file=sys.stderr)
1214
+ # 6.7
1215
+ sys.stderr.write(' previous message repeated {0} times\n'.format(_previous_times))
1216
+ elif _previous_times > 0:
1217
+ sys.stderr.write(' previous message repeated\n')
1218
+ _previous_times = 0
1219
+ _previous_warning = ''
1220
+
1221
+ def _warn(s=''):
1222
+ global _previous_times
1223
+ global _previous_warning
1224
+ if s == _previous_warning: # 5.4
1225
+ _previous_times = _previous_times + 1
1226
+ else:
1227
+ _clean_up_warnings()
1228
+ sys.stderr.write(str(s)+"\n")
1229
+ _previous_warning = s
1230
+
1231
+ def _some_text_event(which_kind=0x01, text=b'some_text'):
1232
+ if str(type(text)).find("'str'") >= 0: # 6.4 test for back-compatibility
1233
+ data = bytes(text, encoding='ISO-8859-1')
1234
+ else:
1235
+ data = bytes(text)
1236
+ return b'\xFF'+bytes((which_kind,))+_ber_compressed_int(len(data))+data
1237
+
1238
+ def _consistentise_ticks(scores): # 3.6
1239
+ # used by mix_scores, merge_scores, concatenate_scores
1240
+ if len(scores) == 1:
1241
+ return copy.deepcopy(scores)
1242
+ are_consistent = True
1243
+ ticks = scores[0][0]
1244
+ iscore = 1
1245
+ while iscore < len(scores):
1246
+ if scores[iscore][0] != ticks:
1247
+ are_consistent = False
1248
+ break
1249
+ iscore += 1
1250
+ if are_consistent:
1251
+ return copy.deepcopy(scores)
1252
+ new_scores = []
1253
+ iscore = 0
1254
+ while iscore < len(scores):
1255
+ score = scores[iscore]
1256
+ new_scores.append(opus2score(to_millisecs(score2opus(score))))
1257
+ iscore += 1
1258
+ return new_scores
1259
+
1260
+
1261
+ ###########################################################################
1262
+
1263
+ def _decode(trackdata=b'', exclude=None, include=None,
1264
+ event_callback=None, exclusive_event_callback=None, no_eot_magic=False):
1265
+ r'''Decodes MIDI track data into an opus-style list of events.
1266
+ The options:
1267
+ 'exclude' is a list of event types which will be ignored SHOULD BE A SET
1268
+ 'include' (and no exclude), makes exclude a list
1269
+ of all possible events, /minus/ what include specifies
1270
+ 'event_callback' is a coderef
1271
+ 'exclusive_event_callback' is a coderef
1272
+ '''
1273
+ trackdata = bytearray(trackdata)
1274
+ if exclude == None:
1275
+ exclude = []
1276
+ if include == None:
1277
+ include = []
1278
+ if include and not exclude:
1279
+ exclude = All_events
1280
+ include = set(include)
1281
+ exclude = set(exclude)
1282
+
1283
+ # Pointer = 0; not used here; we eat through the bytearray instead.
1284
+ event_code = -1; # used for running status
1285
+ event_count = 0;
1286
+ events = []
1287
+
1288
+ while(len(trackdata)):
1289
+ # loop while there's anything to analyze ...
1290
+ eot = False # When True, the event registrar aborts this loop
1291
+ event_count += 1
1292
+
1293
+ E = []
1294
+ # E for events - we'll feed it to the event registrar at the end.
1295
+
1296
+ # Slice off the delta time code, and analyze it
1297
+ [time, remainder] = _unshift_ber_int(trackdata)
1298
+
1299
+ # Now let's see what we can make of the command
1300
+ first_byte = trackdata.pop(0) & 0xFF
1301
+
1302
+ if (first_byte < 0xF0): # It's a MIDI event
1303
+ if (first_byte & 0x80):
1304
+ event_code = first_byte
1305
+ else:
1306
+ # It wants running status; use last event_code value
1307
+ trackdata.insert(0, first_byte)
1308
+ if (event_code == -1):
1309
+ _warn("Running status not set; Aborting track.")
1310
+ return []
1311
+
1312
+ command = event_code & 0xF0
1313
+ channel = event_code & 0x0F
1314
+
1315
+ if (command == 0xF6): # 0-byte argument
1316
+ pass
1317
+ elif (command == 0xC0 or command == 0xD0): # 1-byte argument
1318
+ parameter = trackdata.pop(0) # could be B
1319
+ else: # 2-byte argument could be BB or 14-bit
1320
+ parameter = (trackdata.pop(0), trackdata.pop(0))
1321
+
1322
+ #################################################################
1323
+ # MIDI events
1324
+
1325
+ if (command == 0x80):
1326
+ if 'note_off' in exclude:
1327
+ continue
1328
+ E = ['note_off', time, channel, parameter[0], parameter[1]]
1329
+ elif (command == 0x90):
1330
+ if 'note_on' in exclude:
1331
+ continue
1332
+ E = ['note_on', time, channel, parameter[0], parameter[1]]
1333
+ elif (command == 0xA0):
1334
+ if 'key_after_touch' in exclude:
1335
+ continue
1336
+ E = ['key_after_touch',time,channel,parameter[0],parameter[1]]
1337
+ elif (command == 0xB0):
1338
+ if 'control_change' in exclude:
1339
+ continue
1340
+ E = ['control_change',time,channel,parameter[0],parameter[1]]
1341
+ elif (command == 0xC0):
1342
+ if 'patch_change' in exclude:
1343
+ continue
1344
+ E = ['patch_change', time, channel, parameter]
1345
+ elif (command == 0xD0):
1346
+ if 'channel_after_touch' in exclude:
1347
+ continue
1348
+ E = ['channel_after_touch', time, channel, parameter]
1349
+ elif (command == 0xE0):
1350
+ if 'pitch_wheel_change' in exclude:
1351
+ continue
1352
+ E = ['pitch_wheel_change', time, channel,
1353
+ _read_14_bit(parameter)-0x2000]
1354
+ else:
1355
+ _warn("Shouldn't get here; command="+hex(command))
1356
+
1357
+ elif (first_byte == 0xFF): # It's a Meta-Event! ##################
1358
+ #[command, length, remainder] =
1359
+ # unpack("xCwa*", substr(trackdata, $Pointer, 6));
1360
+ #Pointer += 6 - len(remainder);
1361
+ # # Move past JUST the length-encoded.
1362
+ command = trackdata.pop(0) & 0xFF
1363
+ [length, trackdata] = _unshift_ber_int(trackdata)
1364
+ if (command == 0x00):
1365
+ if (length == 2):
1366
+ E = ['set_sequence_number',time,_twobytes2int(trackdata)]
1367
+ else:
1368
+ _warn('set_sequence_number: length must be 2, not '+str(length))
1369
+ E = ['set_sequence_number', time, 0]
1370
+
1371
+ elif command >= 0x01 and command <= 0x0f: # Text events
1372
+ # 6.2 take it in bytes; let the user get the right encoding.
1373
+ # text_str = trackdata[0:length].decode('ascii','ignore')
1374
+ # text_str = trackdata[0:length].decode('ISO-8859-1')
1375
+ # 6.4 take it in bytes; let the user get the right encoding.
1376
+ text_data = bytes(trackdata[0:length]) # 6.4
1377
+ # Defined text events
1378
+ if (command == 0x01):
1379
+ E = ['text_event', time, text_data]
1380
+ elif (command == 0x02):
1381
+ E = ['copyright_text_event', time, text_data]
1382
+ elif (command == 0x03):
1383
+ E = ['track_name', time, text_data]
1384
+ elif (command == 0x04):
1385
+ E = ['instrument_name', time, text_data]
1386
+ elif (command == 0x05):
1387
+ E = ['lyric', time, text_data]
1388
+ elif (command == 0x06):
1389
+ E = ['marker', time, text_data]
1390
+ elif (command == 0x07):
1391
+ E = ['cue_point', time, text_data]
1392
+ # Reserved but apparently unassigned text events
1393
+ elif (command == 0x08):
1394
+ E = ['text_event_08', time, text_data]
1395
+ elif (command == 0x09):
1396
+ E = ['text_event_09', time, text_data]
1397
+ elif (command == 0x0a):
1398
+ E = ['text_event_0a', time, text_data]
1399
+ elif (command == 0x0b):
1400
+ E = ['text_event_0b', time, text_data]
1401
+ elif (command == 0x0c):
1402
+ E = ['text_event_0c', time, text_data]
1403
+ elif (command == 0x0d):
1404
+ E = ['text_event_0d', time, text_data]
1405
+ elif (command == 0x0e):
1406
+ E = ['text_event_0e', time, text_data]
1407
+ elif (command == 0x0f):
1408
+ E = ['text_event_0f', time, text_data]
1409
+
1410
+ # Now the sticky events -------------------------------------
1411
+ elif (command == 0x2F):
1412
+ E = ['end_track', time]
1413
+ # The code for handling this, oddly, comes LATER,
1414
+ # in the event registrar.
1415
+ elif (command == 0x51): # DTime, Microseconds/Crochet
1416
+ if length != 3:
1417
+ _warn('set_tempo event, but length='+str(length))
1418
+ E = ['set_tempo', time,
1419
+ struct.unpack(">I", b'\x00'+trackdata[0:3])[0]]
1420
+ elif (command == 0x54):
1421
+ if length != 5: # DTime, HR, MN, SE, FR, FF
1422
+ _warn('smpte_offset event, but length='+str(length))
1423
+ E = ['smpte_offset',time] + list(struct.unpack(">BBBBB",trackdata[0:5]))
1424
+ elif (command == 0x58):
1425
+ if length != 4: # DTime, NN, DD, CC, BB
1426
+ _warn('time_signature event, but length='+str(length))
1427
+ E = ['time_signature', time]+list(trackdata[0:4])
1428
+ elif (command == 0x59):
1429
+ if length != 2: # DTime, SF(signed), MI
1430
+ _warn('key_signature event, but length='+str(length))
1431
+ E = ['key_signature',time] + list(struct.unpack(">bB",trackdata[0:2]))
1432
+ elif (command == 0x7F): # 6.4
1433
+ E = ['sequencer_specific',time, bytes(trackdata[0:length])]
1434
+ else:
1435
+ E = ['raw_meta_event', time, command,
1436
+ bytes(trackdata[0:length])] # 6.0
1437
+ #"[uninterpretable meta-event command of length length]"
1438
+ # DTime, Command, Binary Data
1439
+ # It's uninterpretable; record it as raw_data.
1440
+
1441
+ # Pointer += length; # Now move Pointer
1442
+ trackdata = trackdata[length:]
1443
+
1444
+ ######################################################################
1445
+ elif (first_byte == 0xF0 or first_byte == 0xF7):
1446
+ # Note that sysexes in MIDI /files/ are different than sysexes
1447
+ # in MIDI transmissions!! The vast majority of system exclusive
1448
+ # messages will just use the F0 format. For instance, the
1449
+ # transmitted message F0 43 12 00 07 F7 would be stored in a
1450
+ # MIDI file as F0 05 43 12 00 07 F7. As mentioned above, it is
1451
+ # required to include the F7 at the end so that the reader of the
1452
+ # MIDI file knows that it has read the entire message. (But the F7
1453
+ # is omitted if this is a non-final block in a multiblock sysex;
1454
+ # but the F7 (if there) is counted in the message's declared
1455
+ # length, so we don't have to think about it anyway.)
1456
+ #command = trackdata.pop(0)
1457
+ [length, trackdata] = _unshift_ber_int(trackdata)
1458
+ if first_byte == 0xF0:
1459
+ # 20091008 added ISO-8859-1 to get an 8-bit str
1460
+ # 6.4 return bytes instead
1461
+ E = ['sysex_f0', time, bytes(trackdata[0:length])]
1462
+ else:
1463
+ E = ['sysex_f7', time, bytes(trackdata[0:length])]
1464
+ trackdata = trackdata[length:]
1465
+
1466
+ ######################################################################
1467
+ # Now, the MIDI file spec says:
1468
+ # <track data> = <MTrk event>+
1469
+ # <MTrk event> = <delta-time> <event>
1470
+ # <event> = <MIDI event> | <sysex event> | <meta-event>
1471
+ # I know that, on the wire, <MIDI event> can include note_on,
1472
+ # note_off, and all the other 8x to Ex events, AND Fx events
1473
+ # other than F0, F7, and FF -- namely, <song position msg>,
1474
+ # <song select msg>, and <tune request>.
1475
+ #
1476
+ # Whether these can occur in MIDI files is not clear specified
1477
+ # from the MIDI file spec. So, I'm going to assume that
1478
+ # they CAN, in practice, occur. I don't know whether it's
1479
+ # proper for you to actually emit these into a MIDI file.
1480
+
1481
+ elif (first_byte == 0xF2): # DTime, Beats
1482
+ # <song position msg> ::= F2 <data pair>
1483
+ E = ['song_position', time, _read_14_bit(trackdata[:2])]
1484
+ trackdata = trackdata[2:]
1485
+
1486
+ elif (first_byte == 0xF3): # <song select msg> ::= F3 <data singlet>
1487
+ # E = ['song_select', time, struct.unpack('>B',trackdata.pop(0))[0]]
1488
+ E = ['song_select', time, trackdata[0]]
1489
+ trackdata = trackdata[1:]
1490
+ # DTime, Thing (what?! song number? whatever ...)
1491
+
1492
+ elif (first_byte == 0xF6): # DTime
1493
+ E = ['tune_request', time]
1494
+ # What would a tune request be doing in a MIDI /file/?
1495
+
1496
+ #########################################################
1497
+ # ADD MORE META-EVENTS HERE. TODO:
1498
+ # f1 -- MTC Quarter Frame Message. One data byte follows
1499
+ # the Status; it's the time code value, from 0 to 127.
1500
+ # f8 -- MIDI clock. no data.
1501
+ # fa -- MIDI start. no data.
1502
+ # fb -- MIDI continue. no data.
1503
+ # fc -- MIDI stop. no data.
1504
+ # fe -- Active sense. no data.
1505
+ # f4 f5 f9 fd -- unallocated
1506
+
1507
+ r'''
1508
+ elif (first_byte > 0xF0) { # Some unknown kinda F-series event ####
1509
+ # Here we only produce a one-byte piece of raw data.
1510
+ # But the encoder for 'raw_data' accepts any length of it.
1511
+ E = [ 'raw_data',
1512
+ time, substr(trackdata,Pointer,1) ]
1513
+ # DTime and the Data (in this case, the one Event-byte)
1514
+ ++Pointer; # itself
1515
+
1516
+ '''
1517
+ elif first_byte > 0xF0: # Some unknown F-series event
1518
+ # Here we only produce a one-byte piece of raw data.
1519
+ # E = ['raw_data', time, bytest(trackdata[0])] # 6.4
1520
+ E = ['raw_data', time, trackdata[0]] # 6.4 6.7
1521
+ trackdata = trackdata[1:]
1522
+ else: # Fallthru.
1523
+ _warn("Aborting track. Command-byte first_byte="+hex(first_byte))
1524
+ break
1525
+ # End of the big if-group
1526
+
1527
+
1528
+ ######################################################################
1529
+ # THE EVENT REGISTRAR...
1530
+ if E and (E[0] == 'end_track'):
1531
+ # This is the code for exceptional handling of the EOT event.
1532
+ eot = True
1533
+ if not no_eot_magic:
1534
+ if E[1] > 0: # a null text-event to carry the delta-time
1535
+ E = ['text_event', E[1], '']
1536
+ else:
1537
+ E = [] # EOT with a delta-time of 0; ignore it.
1538
+
1539
+ if E and not (E[0] in exclude):
1540
+ #if ( $exclusive_event_callback ):
1541
+ # &{ $exclusive_event_callback }( @E );
1542
+ #else:
1543
+ # &{ $event_callback }( @E ) if $event_callback;
1544
+ events.append(E)
1545
+ if eot:
1546
+ break
1547
+
1548
+ # End of the big "Event" while-block
1549
+
1550
+ return events
1551
+
1552
+
1553
+ ###########################################################################
1554
+ def _encode(events_lol, unknown_callback=None, never_add_eot=False,
1555
+ no_eot_magic=False, no_running_status=False):
1556
+ # encode an event structure, presumably for writing to a file
1557
+ # Calling format:
1558
+ # $data_r = MIDI::Event::encode( \@event_lol, { options } );
1559
+ # Takes a REFERENCE to an event structure (a LoL)
1560
+ # Returns an (unblessed) REFERENCE to track data.
1561
+
1562
+ # If you want to use this to encode a /single/ event,
1563
+ # you still have to do it as a reference to an event structure (a LoL)
1564
+ # that just happens to have just one event. I.e.,
1565
+ # encode( [ $event ] ) or encode( [ [ 'note_on', 100, 5, 42, 64] ] )
1566
+ # If you're doing this, consider the never_add_eot track option, as in
1567
+ # print MIDI ${ encode( [ $event], { 'never_add_eot' => 1} ) };
1568
+
1569
+ data = [] # what I'll store the chunks of byte-data in
1570
+
1571
+ # This is so my end_track magic won't corrupt the original
1572
+ events = copy.deepcopy(events_lol)
1573
+
1574
+ if not never_add_eot:
1575
+ # One way or another, tack on an 'end_track'
1576
+ if events:
1577
+ last = events[-1]
1578
+ if not (last[0] == 'end_track'): # no end_track already
1579
+ if (last[0] == 'text_event' and len(last[2]) == 0):
1580
+ # 0-length text event at track-end.
1581
+ if no_eot_magic:
1582
+ # Exceptional case: don't mess with track-final
1583
+ # 0-length text_events; just peg on an end_track
1584
+ events.append(['end_track', 0])
1585
+ else:
1586
+ # NORMAL CASE: replace with an end_track, leaving DTime
1587
+ last[0] = 'end_track'
1588
+ else:
1589
+ # last event was neither 0-length text_event nor end_track
1590
+ events.append(['end_track', 0])
1591
+ else: # an eventless track!
1592
+ events = [['end_track', 0],]
1593
+
1594
+ # maybe_running_status = not no_running_status # unused? 4.7
1595
+ last_status = -1
1596
+
1597
+ for event_r in (events):
1598
+ E = copy.deepcopy(event_r)
1599
+ # otherwise the shifting'd corrupt the original
1600
+ if not E:
1601
+ continue
1602
+
1603
+ event = E.pop(0)
1604
+ if not len(event):
1605
+ continue
1606
+
1607
+ dtime = int(E.pop(0))
1608
+ # print('event='+str(event)+' dtime='+str(dtime))
1609
+
1610
+ event_data = ''
1611
+
1612
+ if ( # MIDI events -- eligible for running status
1613
+ event == 'note_on'
1614
+ or event == 'note_off'
1615
+ or event == 'control_change'
1616
+ or event == 'key_after_touch'
1617
+ or event == 'patch_change'
1618
+ or event == 'channel_after_touch'
1619
+ or event == 'pitch_wheel_change' ):
1620
+
1621
+ # This block is where we spend most of the time. Gotta be tight.
1622
+ if (event == 'note_off'):
1623
+ status = 0x80 | (int(E[0]) & 0x0F)
1624
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1625
+ elif (event == 'note_on'):
1626
+ status = 0x90 | (int(E[0]) & 0x0F)
1627
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1628
+ elif (event == 'key_after_touch'):
1629
+ status = 0xA0 | (int(E[0]) & 0x0F)
1630
+ parameters = struct.pack('>BB', int(E[1])&0x7F, int(E[2])&0x7F)
1631
+ elif (event == 'control_change'):
1632
+ status = 0xB0 | (int(E[0]) & 0x0F)
1633
+ parameters = struct.pack('>BB', int(E[1])&0xFF, int(E[2])&0xFF)
1634
+ elif (event == 'patch_change'):
1635
+ status = 0xC0 | (int(E[0]) & 0x0F)
1636
+ parameters = struct.pack('>B', int(E[1]) & 0xFF)
1637
+ elif (event == 'channel_after_touch'):
1638
+ status = 0xD0 | (int(E[0]) & 0x0F)
1639
+ parameters = struct.pack('>B', int(E[1]) & 0xFF)
1640
+ elif (event == 'pitch_wheel_change'):
1641
+ status = 0xE0 | (int(E[0]) & 0x0F)
1642
+ parameters = _write_14_bit(int(E[1]) + 0x2000)
1643
+ else:
1644
+ _warn("BADASS FREAKOUT ERROR 31415!")
1645
+
1646
+ # And now the encoding
1647
+ # w = BER compressed integer (not ASN.1 BER, see perlpacktut for
1648
+ # details). Its bytes represent an unsigned integer in base 128,
1649
+ # most significant digit first, with as few digits as possible.
1650
+ # Bit eight (the high bit) is set on each byte except the last.
1651
+
1652
+ data.append(_ber_compressed_int(dtime))
1653
+ if (status != last_status) or no_running_status:
1654
+ data.append(struct.pack('>B', status))
1655
+ data.append(parameters)
1656
+
1657
+ last_status = status
1658
+ continue
1659
+ else:
1660
+ # Not a MIDI event.
1661
+ # All the code in this block could be more efficient,
1662
+ # but this is not where the code needs to be tight.
1663
+ # print "zaz $event\n";
1664
+ last_status = -1
1665
+
1666
+ if event == 'raw_meta_event':
1667
+ event_data = _some_text_event(int(E[0]), E[1])
1668
+ elif (event == 'set_sequence_number'): # 3.9
1669
+ event_data = b'\xFF\x00\x02'+_int2twobytes(E[0])
1670
+
1671
+ # Text meta-events...
1672
+ # a case for a dict, I think (pjb) ...
1673
+ elif (event == 'text_event'):
1674
+ event_data = _some_text_event(0x01, E[0])
1675
+ elif (event == 'copyright_text_event'):
1676
+ event_data = _some_text_event(0x02, E[0])
1677
+ elif (event == 'track_name'):
1678
+ event_data = _some_text_event(0x03, E[0])
1679
+ elif (event == 'instrument_name'):
1680
+ event_data = _some_text_event(0x04, E[0])
1681
+ elif (event == 'lyric'):
1682
+ event_data = _some_text_event(0x05, E[0])
1683
+ elif (event == 'marker'):
1684
+ event_data = _some_text_event(0x06, E[0])
1685
+ elif (event == 'cue_point'):
1686
+ event_data = _some_text_event(0x07, E[0])
1687
+ elif (event == 'text_event_08'):
1688
+ event_data = _some_text_event(0x08, E[0])
1689
+ elif (event == 'text_event_09'):
1690
+ event_data = _some_text_event(0x09, E[0])
1691
+ elif (event == 'text_event_0a'):
1692
+ event_data = _some_text_event(0x0A, E[0])
1693
+ elif (event == 'text_event_0b'):
1694
+ event_data = _some_text_event(0x0B, E[0])
1695
+ elif (event == 'text_event_0c'):
1696
+ event_data = _some_text_event(0x0C, E[0])
1697
+ elif (event == 'text_event_0d'):
1698
+ event_data = _some_text_event(0x0D, E[0])
1699
+ elif (event == 'text_event_0e'):
1700
+ event_data = _some_text_event(0x0E, E[0])
1701
+ elif (event == 'text_event_0f'):
1702
+ event_data = _some_text_event(0x0F, E[0])
1703
+ # End of text meta-events
1704
+
1705
+ elif (event == 'end_track'):
1706
+ event_data = b"\xFF\x2F\x00"
1707
+
1708
+ elif (event == 'set_tempo'):
1709
+ #event_data = struct.pack(">BBwa*", 0xFF, 0x51, 3,
1710
+ # substr( struct.pack('>I', E[0]), 1, 3))
1711
+ event_data = b'\xFF\x51\x03'+struct.pack('>I',E[0])[1:]
1712
+ elif (event == 'smpte_offset'):
1713
+ # event_data = struct.pack(">BBwBBBBB", 0xFF, 0x54, 5, E[0:5] )
1714
+ event_data = struct.pack(">BBBbBBBB", 0xFF,0x54,0x05,E[0],E[1],E[2],E[3],E[4])
1715
+ elif (event == 'time_signature'):
1716
+ # event_data = struct.pack(">BBwBBBB", 0xFF, 0x58, 4, E[0:4] )
1717
+ event_data = struct.pack(">BBBbBBB", 0xFF, 0x58, 0x04, E[0],E[1],E[2],E[3])
1718
+ elif (event == 'key_signature'):
1719
+ event_data = struct.pack(">BBBbB", 0xFF, 0x59, 0x02, E[0],E[1])
1720
+ elif (event == 'sequencer_specific'):
1721
+ # event_data = struct.pack(">BBwa*", 0xFF,0x7F, len(E[0]), E[0])
1722
+ event_data = _some_text_event(0x7F, E[0])
1723
+ # End of Meta-events
1724
+
1725
+ # Other Things...
1726
+ elif (event == 'sysex_f0'):
1727
+ #event_data = struct.pack(">Bwa*", 0xF0, len(E[0]), E[0])
1728
+ #B=bitstring w=BER-compressed-integer a=null-padded-ascii-str
1729
+ event_data = bytearray(b'\xF0')+_ber_compressed_int(len(E[0]))+bytearray(E[0])
1730
+ elif (event == 'sysex_f7'):
1731
+ #event_data = struct.pack(">Bwa*", 0xF7, len(E[0]), E[0])
1732
+ event_data = bytearray(b'\xF7')+_ber_compressed_int(len(E[0]))+bytearray(E[0])
1733
+
1734
+ elif (event == 'song_position'):
1735
+ event_data = b"\xF2" + _write_14_bit( E[0] )
1736
+ elif (event == 'song_select'):
1737
+ event_data = struct.pack('>BB', 0xF3, E[0] )
1738
+ elif (event == 'tune_request'):
1739
+ event_data = b"\xF6"
1740
+ elif (event == 'raw_data'):
1741
+ _warn("_encode: raw_data event not supported")
1742
+ # event_data = E[0]
1743
+ continue
1744
+ # End of Other Stuff
1745
+
1746
+ else:
1747
+ # The Big Fallthru
1748
+ if unknown_callback:
1749
+ # push(@data, &{ $unknown_callback }( @$event_r ))
1750
+ pass
1751
+ else:
1752
+ _warn("Unknown event: "+str(event))
1753
+ # To surpress complaint here, just set
1754
+ # 'unknown_callback' => sub { return () }
1755
+ continue
1756
+
1757
+ #print "Event $event encoded part 2\n"
1758
+ if str(type(event_data)).find("'str'") >= 0:
1759
+ event_data = bytearray(event_data.encode('Latin1', 'ignore'))
1760
+ if len(event_data): # how could $event_data be empty
1761
+ # data.append(struct.pack('>wa*', dtime, event_data))
1762
+ # print(' event_data='+str(event_data))
1763
+ data.append(_ber_compressed_int(dtime)+event_data)
1764
+
1765
+ return b''.join(data)
1766
+
1767
+ #===============================================================================
1768
+
1769
+ """
1770
+ ================================================================================
1771
+
1772
+ pyFluidSynth
1773
+
1774
+ Python bindings for FluidSynth
1775
+
1776
+ Copyright 2008--2024, Nathan Whitehead <nwhitehe@gmail.com> and others.
1777
+
1778
+
1779
+ Released under the LGPL
1780
+
1781
+ This module contains python bindings for FluidSynth. FluidSynth is a
1782
+ software synthesizer for generating music. It works like a MIDI
1783
+ synthesizer. You load patches, set parameters, then send NOTEON and
1784
+ NOTEOFF events to play notes. Instruments are defined in SoundFonts,
1785
+ generally files with the extension SF2. FluidSynth can either be used
1786
+ to play audio itself, or you can call a function that returns chunks
1787
+ of audio data and output the data to the soundcard yourself.
1788
+ FluidSynth works on all major platforms, so pyFluidSynth should also.
1789
+
1790
+ ================================================================================
1791
+ """
1792
+
1793
+ import os
1794
+ from ctypes import (
1795
+ CDLL,
1796
+ CFUNCTYPE,
1797
+ POINTER,
1798
+ Structure,
1799
+ byref,
1800
+ c_char,
1801
+ c_char_p,
1802
+ c_double,
1803
+ c_float,
1804
+ c_int,
1805
+ c_short,
1806
+ c_uint,
1807
+ c_void_p,
1808
+ create_string_buffer,
1809
+ )
1810
+ from ctypes.util import find_library
1811
+
1812
+ # DLL search method changed in Python 3.8
1813
+ # https://docs.python.org/3/library/os.html#os.add_dll_directory
1814
+ if hasattr(os, 'add_dll_directory'): # Python 3.8+ on Windows only
1815
+ os.add_dll_directory(os.getcwd())
1816
+ os.add_dll_directory('C:\\tools\\fluidsynth\\bin')
1817
+ # Workaround bug in find_library, it doesn't recognize add_dll_directory
1818
+ os.environ['PATH'] += ';C:\\tools\\fluidsynth\\bin'
1819
+
1820
+ # A function to find the FluidSynth library
1821
+ # (mostly needed for Windows distributions of libfluidsynth supplied with QSynth)
1822
+ def find_libfluidsynth(debug_print: bool = False) -> str:
1823
+ r"""
1824
+ macOS X64:
1825
+ * 'fluidsynth' was found at /usr/local/opt/fluid-synth/lib/libfluidsynth.dylib.
1826
+ macOS ARM64:
1827
+ * 'fluidsynth' was found at /opt/homebrew/opt/fluid-synth/lib/libfluidsynth.dylib.
1828
+ Ubuntu X86:
1829
+ * 'fluidsynth' was found at libfluidsynth.so.3.
1830
+ Windows X86:
1831
+ * 'libfluidsynth-3' was found at C:\tools\fluidsynth\bin\libfluidsynth-3.dll. --or--
1832
+ * 'fluidsynth-3' was found as C:\tools\fluidsynth\bin\fluidsynth-3.dll. >= v2.4.5
1833
+ * https://github.com/FluidSynth/fluidsynth/issues/1543
1834
+ """
1835
+ libs = "fluidsynth fluidsynth-3 libfluidsynth libfluidsynth-3 libfluidsynth-2 libfluidsynth-1"
1836
+ for lib_name in libs.split():
1837
+ lib = find_library(lib_name)
1838
+ if lib:
1839
+ if debug_print:
1840
+ print(f"'{lib_name}' was found at {lib}.")
1841
+ return lib
1842
+
1843
+ # On macOS on Apple silicon, non-Homebrew Python distributions fail to locate
1844
+ # homebrew-installed instances of FluidSynth. This workaround addresses this.
1845
+ if homebrew_prefix := os.getenv("HOMEBREW_PREFIX"):
1846
+ lib = os.path.join(homebrew_prefix, "lib", "libfluidsynth.dylib")
1847
+ if os.path.exists(lib):
1848
+ return lib
1849
+
1850
+ raise ImportError("Couldn't find the FluidSynth library.")
1851
+
1852
+ lib = find_libfluidsynth()
1853
+
1854
+ # Dynamically link the FluidSynth library
1855
+ # Architecture (32-/64-bit) must match your Python version
1856
+ _fl = CDLL(lib)
1857
+
1858
+ # Helper function for declaring function prototypes
1859
+ def cfunc(name, result, *args):
1860
+ """Build and apply a ctypes prototype complete with parameter flags"""
1861
+ if hasattr(_fl, name):
1862
+ atypes = []
1863
+ aflags = []
1864
+ for arg in args:
1865
+ atypes.append(arg[1])
1866
+ aflags.append((arg[2], arg[0]) + arg[3:])
1867
+ return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags))
1868
+ else: # Handle Fluidsynth 1.x, 2.x, etc. API differences
1869
+ return None
1870
+
1871
+ # Bump this up when changing the interface for users
1872
+ api_version = '1.3.5'
1873
+
1874
+ # Function prototypes for C versions of functions
1875
+
1876
+ FLUID_OK = 0
1877
+ FLUID_FAILED = -1
1878
+
1879
+ fluid_version = cfunc('fluid_version', c_void_p,
1880
+ ('major', POINTER(c_int), 1),
1881
+ ('minor', POINTER(c_int), 1),
1882
+ ('micro', POINTER(c_int), 1))
1883
+
1884
+ majver = c_int()
1885
+ fluid_version(majver, c_int(), c_int())
1886
+ FLUIDSETTING_EXISTS = FLUID_OK if majver.value > 1 else 1
1887
+
1888
+ # fluid settings
1889
+ new_fluid_settings = cfunc('new_fluid_settings', c_void_p)
1890
+
1891
+ fluid_settings_setstr = cfunc('fluid_settings_setstr', c_int,
1892
+ ('settings', c_void_p, 1),
1893
+ ('name', c_char_p, 1),
1894
+ ('str', c_char_p, 1))
1895
+
1896
+ fluid_settings_setnum = cfunc('fluid_settings_setnum', c_int,
1897
+ ('settings', c_void_p, 1),
1898
+ ('name', c_char_p, 1),
1899
+ ('val', c_double, 1))
1900
+
1901
+ fluid_settings_setint = cfunc('fluid_settings_setint', c_int,
1902
+ ('settings', c_void_p, 1),
1903
+ ('name', c_char_p, 1),
1904
+ ('val', c_int, 1))
1905
+
1906
+ fluid_settings_copystr = cfunc('fluid_settings_copystr', c_int,
1907
+ ('settings', c_void_p, 1),
1908
+ ('name', c_char_p, 1),
1909
+ ('str', c_char_p, 1),
1910
+ ('len', c_int, 1))
1911
+
1912
+ fluid_settings_getnum = cfunc('fluid_settings_getnum', c_int,
1913
+ ('settings', c_void_p, 1),
1914
+ ('name', c_char_p, 1),
1915
+ ('val', POINTER(c_double), 1))
1916
+
1917
+ fluid_settings_getint = cfunc('fluid_settings_getint', c_int,
1918
+ ('settings', c_void_p, 1),
1919
+ ('name', c_char_p, 1),
1920
+ ('val', POINTER(c_int), 1))
1921
+
1922
+ delete_fluid_settings = cfunc('delete_fluid_settings', None,
1923
+ ('settings', c_void_p, 1))
1924
+
1925
+ fluid_synth_activate_key_tuning = cfunc('fluid_synth_activate_key_tuning', c_int,
1926
+ ('synth', c_void_p, 1),
1927
+ ('bank', c_int, 1),
1928
+ ('prog', c_int, 1),
1929
+ ('name', c_char_p, 1),
1930
+ ('pitch', POINTER(c_double), 1),
1931
+ ('apply', c_int, 1))
1932
+
1933
+ fluid_synth_activate_tuning = cfunc('fluid_synth_activate_tuning', c_int,
1934
+ ('synth', c_void_p, 1),
1935
+ ('chan', c_int, 1),
1936
+ ('bank', c_int, 1),
1937
+ ('prog', c_int, 1),
1938
+ ('apply', c_int, 1))
1939
+
1940
+ fluid_synth_deactivate_tuning = cfunc('fluid_synth_deactivate_tuning', c_int,
1941
+ ('synth', c_void_p, 1),
1942
+ ('chan', c_int, 1),
1943
+ ('apply', c_int, 1))
1944
+
1945
+ fluid_synth_tuning_dump = cfunc('fluid_synth_tuning_dump', c_int,
1946
+ ('synth', c_void_p, 1),
1947
+ ('bank', c_int, 1),
1948
+ ('prog', c_int, 1),
1949
+ ('name', c_char_p, 1),
1950
+ ('length', c_int, 1),
1951
+ ('pitch', POINTER(c_double), 1))
1952
+
1953
+ # fluid synth
1954
+ new_fluid_synth = cfunc('new_fluid_synth', c_void_p,
1955
+ ('settings', c_void_p, 1))
1956
+
1957
+ delete_fluid_synth = cfunc('delete_fluid_synth', None,
1958
+ ('synth', c_void_p, 1))
1959
+
1960
+ fluid_synth_sfload = cfunc('fluid_synth_sfload', c_int,
1961
+ ('synth', c_void_p, 1),
1962
+ ('filename', c_char_p, 1),
1963
+ ('update_midi_presets', c_int, 1))
1964
+
1965
+ fluid_synth_sfunload = cfunc('fluid_synth_sfunload', c_int,
1966
+ ('synth', c_void_p, 1),
1967
+ ('sfid', c_int, 1),
1968
+ ('update_midi_presets', c_int, 1))
1969
+
1970
+ fluid_synth_program_select = cfunc('fluid_synth_program_select', c_int,
1971
+ ('synth', c_void_p, 1),
1972
+ ('chan', c_int, 1),
1973
+ ('sfid', c_int, 1),
1974
+ ('bank', c_int, 1),
1975
+ ('preset', c_int, 1))
1976
+
1977
+ fluid_synth_noteon = cfunc('fluid_synth_noteon', c_int,
1978
+ ('synth', c_void_p, 1),
1979
+ ('chan', c_int, 1),
1980
+ ('key', c_int, 1),
1981
+ ('vel', c_int, 1))
1982
+
1983
+ fluid_synth_noteoff = cfunc('fluid_synth_noteoff', c_int,
1984
+ ('synth', c_void_p, 1),
1985
+ ('chan', c_int, 1),
1986
+ ('key', c_int, 1))
1987
+
1988
+ fluid_synth_pitch_bend = cfunc('fluid_synth_pitch_bend', c_int,
1989
+ ('synth', c_void_p, 1),
1990
+ ('chan', c_int, 1),
1991
+ ('val', c_int, 1))
1992
+
1993
+ fluid_synth_cc = cfunc('fluid_synth_cc', c_int,
1994
+ ('synth', c_void_p, 1),
1995
+ ('chan', c_int, 1),
1996
+ ('ctrl', c_int, 1),
1997
+ ('val', c_int, 1))
1998
+
1999
+ fluid_synth_get_cc = cfunc('fluid_synth_get_cc', c_int,
2000
+ ('synth', c_void_p, 1),
2001
+ ('chan', c_int, 1),
2002
+ ('num', c_int, 1),
2003
+ ('pval', POINTER(c_int), 1))
2004
+
2005
+ fluid_synth_program_change = cfunc('fluid_synth_program_change', c_int,
2006
+ ('synth', c_void_p, 1),
2007
+ ('chan', c_int, 1),
2008
+ ('prg', c_int, 1))
2009
+
2010
+ fluid_synth_unset_program = cfunc('fluid_synth_unset_program', c_int,
2011
+ ('synth', c_void_p, 1),
2012
+ ('chan', c_int, 1))
2013
+
2014
+ fluid_synth_get_program = cfunc('fluid_synth_get_program', c_int,
2015
+ ('synth', c_void_p, 1),
2016
+ ('chan', c_int, 1),
2017
+ ('sfont_id', POINTER(c_int), 1),
2018
+ ('bank_num', POINTER(c_int), 1),
2019
+ ('preset_num', POINTER(c_int), 1))
2020
+
2021
+ fluid_synth_bank_select = cfunc('fluid_synth_bank_select', c_int,
2022
+ ('synth', c_void_p, 1),
2023
+ ('chan', c_int, 1),
2024
+ ('bank', c_int, 1))
2025
+
2026
+ fluid_synth_sfont_select = cfunc('fluid_synth_sfont_select', c_int,
2027
+ ('synth', c_void_p, 1),
2028
+ ('chan', c_int, 1),
2029
+ ('sfid', c_int, 1))
2030
+
2031
+ fluid_synth_program_reset = cfunc('fluid_synth_program_reset', c_int,
2032
+ ('synth', c_void_p, 1))
2033
+
2034
+ fluid_synth_system_reset = cfunc('fluid_synth_system_reset', c_int,
2035
+ ('synth', c_void_p, 1))
2036
+
2037
+ fluid_synth_write_s16 = cfunc('fluid_synth_write_s16', c_void_p,
2038
+ ('synth', c_void_p, 1),
2039
+ ('len', c_int, 1),
2040
+ ('lbuf', c_void_p, 1),
2041
+ ('loff', c_int, 1),
2042
+ ('lincr', c_int, 1),
2043
+ ('rbuf', c_void_p, 1),
2044
+ ('roff', c_int, 1),
2045
+ ('rincr', c_int, 1))
2046
+
2047
+ fluid_synth_all_notes_off = cfunc('fluid_synth_all_notes_off', c_int,
2048
+ ('synth', c_void_p, 1),
2049
+ ('chan', c_int, 1))
2050
+
2051
+ fluid_synth_all_sounds_off = cfunc('fluid_synth_all_sounds_off', c_int,
2052
+ ('synth', c_void_p, 1),
2053
+ ('chan', c_int, 1))
2054
+
2055
+
2056
+ class fluid_synth_channel_info_t(Structure):
2057
+ _fields_ = [
2058
+ ('assigned', c_int),
2059
+ ('sfont_id', c_int),
2060
+ ('bank', c_int),
2061
+ ('program', c_int),
2062
+ ('name', c_char*32),
2063
+ ('reserved', c_char*32)]
2064
+
2065
+ fluid_synth_get_channel_info = cfunc('fluid_synth_get_channel_info', c_int,
2066
+ ('synth', c_void_p, 1),
2067
+ ('chan', c_int, 1),
2068
+ ('info', POINTER(fluid_synth_channel_info_t), 1))
2069
+
2070
+ fluid_synth_set_reverb_full = cfunc('fluid_synth_set_reverb_full', c_int,
2071
+ ('synth', c_void_p, 1),
2072
+ ('set', c_int, 1),
2073
+ ('roomsize', c_double, 1),
2074
+ ('damping', c_double, 1),
2075
+ ('width', c_double, 1),
2076
+ ('level', c_double, 1))
2077
+
2078
+ fluid_synth_set_chorus_full = cfunc('fluid_synth_set_chorus_full', c_int,
2079
+ ('synth', c_void_p, 1),
2080
+ ('set', c_int, 1),
2081
+ ('nr', c_int, 1),
2082
+ ('level', c_double, 1),
2083
+ ('speed', c_double, 1),
2084
+ ('depth_ms', c_double, 1),
2085
+ ('type', c_int, 1))
2086
+
2087
+ fluid_synth_set_reverb = cfunc('fluid_synth_set_reverb', c_int,
2088
+ ('synth', c_void_p, 1),
2089
+ ('roomsize', c_double, 1),
2090
+ ('damping', c_double, 1),
2091
+ ('width', c_double, 1),
2092
+ ('level', c_double, 1))
2093
+
2094
+ fluid_synth_set_chorus = cfunc('fluid_synth_set_chorus', c_int,
2095
+ ('synth', c_void_p, 1),
2096
+ ('nr', c_int, 1),
2097
+ ('level', c_double, 1),
2098
+ ('speed', c_double, 1),
2099
+ ('depth_ms', c_double, 1),
2100
+ ('type', c_int, 1))
2101
+
2102
+ fluid_synth_set_reverb_roomsize = cfunc('fluid_synth_set_reverb_roomsize', c_int,
2103
+ ('synth', c_void_p, 1),
2104
+ ('roomsize', c_double, 1))
2105
+
2106
+ fluid_synth_set_reverb_damp = cfunc('fluid_synth_set_reverb_damp', c_int,
2107
+ ('synth', c_void_p, 1),
2108
+ ('damping', c_double, 1))
2109
+
2110
+ fluid_synth_set_reverb_level = cfunc('fluid_synth_set_reverb_level', c_int,
2111
+ ('synth', c_void_p, 1),
2112
+ ('level', c_double, 1))
2113
+
2114
+ fluid_synth_set_reverb_width = cfunc('fluid_synth_set_reverb_width', c_int,
2115
+ ('synth', c_void_p, 1),
2116
+ ('width', c_double, 1))
2117
+
2118
+ fluid_synth_set_chorus_nr = cfunc('fluid_synth_set_chorus_nr', c_int,
2119
+ ('synth', c_void_p, 1),
2120
+ ('nr', c_int, 1))
2121
+
2122
+ fluid_synth_set_chorus_level = cfunc('fluid_synth_set_chorus_level', c_int,
2123
+ ('synth', c_void_p, 1),
2124
+ ('level', c_double, 1))
2125
+
2126
+ fluid_synth_set_chorus_speed = cfunc('fluid_synth_set_chorus_speed', c_int,
2127
+ ('synth', c_void_p, 1),
2128
+ ('speed', c_double, 1))
2129
+
2130
+ fluid_synth_set_chorus_depth = cfunc('fluid_synth_set_chorus_depth', c_int,
2131
+ ('synth', c_void_p, 1),
2132
+ ('depth_ms', c_double, 1))
2133
+
2134
+ fluid_synth_set_chorus_type = cfunc('fluid_synth_set_chorus_type', c_int,
2135
+ ('synth', c_void_p, 1),
2136
+ ('type', c_int, 1))
2137
+
2138
+ fluid_synth_get_reverb_roomsize = cfunc('fluid_synth_get_reverb_roomsize', c_double,
2139
+ ('synth', c_void_p, 1))
2140
+
2141
+ fluid_synth_get_reverb_damp = cfunc('fluid_synth_get_reverb_damp', c_double,
2142
+ ('synth', c_void_p, 1))
2143
+
2144
+ fluid_synth_get_reverb_level = cfunc('fluid_synth_get_reverb_level', c_double,
2145
+ ('synth', c_void_p, 1))
2146
+
2147
+ fluid_synth_get_reverb_width = cfunc('fluid_synth_get_reverb_width', c_double,
2148
+ ('synth', c_void_p, 1))
2149
+
2150
+
2151
+ fluid_synth_get_chorus_nr = cfunc('fluid_synth_get_chorus_nr', c_int,
2152
+ ('synth', c_void_p, 1))
2153
+
2154
+ fluid_synth_get_chorus_level = cfunc('fluid_synth_get_chorus_level', c_double,
2155
+ ('synth', c_void_p, 1))
2156
+
2157
+ fluid_synth_get_chorus_speed_Hz = cfunc('fluid_synth_get_chorus_speed_Hz', c_double,
2158
+ ('synth', c_void_p, 1))
2159
+
2160
+ fluid_synth_get_chorus_depth_ms = cfunc('fluid_synth_get_chorus_depth_ms', c_double,
2161
+ ('synth', c_void_p, 1))
2162
+
2163
+ fluid_synth_get_chorus_type = cfunc('fluid_synth_get_chorus_type', c_int,
2164
+ ('synth', c_void_p, 1))
2165
+
2166
+ fluid_synth_set_midi_router = cfunc('fluid_synth_set_midi_router', None,
2167
+ ('synth', c_void_p, 1),
2168
+ ('router', c_void_p, 1))
2169
+
2170
+ fluid_synth_handle_midi_event = cfunc('fluid_synth_handle_midi_event', c_int,
2171
+ ('data', c_void_p, 1),
2172
+ ('event', c_void_p, 1))
2173
+
2174
+ # fluid sequencer
2175
+ new_fluid_sequencer2 = cfunc('new_fluid_sequencer2', c_void_p,
2176
+ ('use_system_timer', c_int, 1))
2177
+
2178
+ fluid_sequencer_process = cfunc('fluid_sequencer_process', None,
2179
+ ('seq', c_void_p, 1),
2180
+ ('msec', c_uint, 1))
2181
+
2182
+ fluid_sequencer_register_fluidsynth = cfunc('fluid_sequencer_register_fluidsynth', c_short,
2183
+ ('seq', c_void_p, 1),
2184
+ ('synth', c_void_p, 1))
2185
+
2186
+ fluid_sequencer_register_client = cfunc('fluid_sequencer_register_client', c_short,
2187
+ ('seq', c_void_p, 1),
2188
+ ('name', c_char_p, 1),
2189
+ ('callback', CFUNCTYPE(None, c_uint, c_void_p, c_void_p, c_void_p), 1),
2190
+ ('data', c_void_p, 1))
2191
+
2192
+ fluid_sequencer_get_tick = cfunc('fluid_sequencer_get_tick', c_uint,
2193
+ ('seq', c_void_p, 1))
2194
+
2195
+ fluid_sequencer_set_time_scale = cfunc('fluid_sequencer_set_time_scale', None,
2196
+ ('seq', c_void_p, 1),
2197
+ ('scale', c_double, 1))
2198
+
2199
+ fluid_sequencer_get_time_scale = cfunc('fluid_sequencer_get_time_scale', c_double,
2200
+ ('seq', c_void_p, 1))
2201
+
2202
+ fluid_sequencer_send_at = cfunc('fluid_sequencer_send_at', c_int,
2203
+ ('seq', c_void_p, 1),
2204
+ ('evt', c_void_p, 1),
2205
+ ('time', c_uint, 1),
2206
+ ('absolute', c_int, 1))
2207
+
2208
+
2209
+ delete_fluid_sequencer = cfunc('delete_fluid_sequencer', None,
2210
+ ('seq', c_void_p, 1))
2211
+
2212
+ # fluid event
2213
+ new_fluid_event = cfunc('new_fluid_event', c_void_p)
2214
+
2215
+ fluid_event_set_source = cfunc('fluid_event_set_source', None,
2216
+ ('evt', c_void_p, 1),
2217
+ ('src', c_void_p, 1))
2218
+
2219
+ fluid_event_set_dest = cfunc('fluid_event_set_dest', None,
2220
+ ('evt', c_void_p, 1),
2221
+ ('dest', c_void_p, 1))
2222
+
2223
+ fluid_event_timer = cfunc('fluid_event_timer', None,
2224
+ ('evt', c_void_p, 1),
2225
+ ('data', c_void_p, 1))
2226
+
2227
+ fluid_event_note = cfunc('fluid_event_note', None,
2228
+ ('evt', c_void_p, 1),
2229
+ ('channel', c_int, 1),
2230
+ ('key', c_short, 1),
2231
+ ('vel', c_short, 1),
2232
+ ('duration', c_uint, 1))
2233
+
2234
+ fluid_event_noteon = cfunc('fluid_event_noteon', None,
2235
+ ('evt', c_void_p, 1),
2236
+ ('channel', c_int, 1),
2237
+ ('key', c_short, 1),
2238
+ ('vel', c_short, 1))
2239
+
2240
+ fluid_event_noteoff = cfunc('fluid_event_noteoff', None,
2241
+ ('evt', c_void_p, 1),
2242
+ ('channel', c_int, 1),
2243
+ ('key', c_short, 1))
2244
+
2245
+ delete_fluid_event = cfunc('delete_fluid_event', None,
2246
+ ('evt', c_void_p, 1))
2247
+
2248
+ fluid_midi_event_get_channel = cfunc('fluid_midi_event_get_channel', c_int,
2249
+ ('evt', c_void_p, 1))
2250
+
2251
+ fluid_midi_event_get_control = cfunc('fluid_midi_event_get_control', c_int,
2252
+ ('evt', c_void_p, 1))
2253
+
2254
+ fluid_midi_event_get_program = cfunc('fluid_midi_event_get_program', c_int,
2255
+ ('evt', c_void_p, 1))
2256
+
2257
+ fluid_midi_event_get_key = cfunc('fluid_midi_event_get_key', c_int,
2258
+ ('evt', c_void_p, 1))
2259
+
2260
+ fluid_midi_event_get_type = cfunc('fluid_midi_event_get_type', c_int,
2261
+ ('evt', c_void_p, 1))
2262
+
2263
+ fluid_midi_event_get_value = cfunc('fluid_midi_event_get_value', c_int,
2264
+ ('evt', c_void_p, 1))
2265
+
2266
+ fluid_midi_event_get_velocity = cfunc('fluid_midi_event_get_velocity', c_int,
2267
+ ('evt', c_void_p, 1))
2268
+
2269
+ # fluid modulator
2270
+ new_fluid_mod = cfunc("new_fluid_mod", c_void_p)
2271
+
2272
+ delete_fluid_mod = cfunc("delete_fluid_mod", c_void_p, ("mod", c_void_p, 1))
2273
+
2274
+ fluid_mod_clone = cfunc(
2275
+ "fluid_mod_clone", c_void_p, ("mod", c_void_p, 1), ("src", c_void_p, 1),
2276
+ )
2277
+
2278
+ fluid_mod_get_amount = cfunc("fluid_mod_get_amount", c_void_p, ("mod", c_void_p, 1))
2279
+
2280
+ fluid_mod_get_dest = cfunc("fluid_mod_get_dest", c_void_p, ("mod", c_void_p, 1))
2281
+
2282
+ fluid_mod_get_flags1 = cfunc("fluid_mod_get_flags1", c_void_p, ("mod", c_void_p, 1))
2283
+
2284
+ fluid_mod_get_flags2 = cfunc("fluid_mod_get_flags2", c_void_p, ("mod", c_void_p, 1))
2285
+
2286
+ fluid_mod_get_source1 = cfunc("fluid_mod_get_source1", c_void_p, ("mod", c_void_p, 1))
2287
+
2288
+ fluid_mod_get_source2 = cfunc("fluid_mod_get_source2", c_void_p, ("mod", c_void_p, 1))
2289
+
2290
+ fluid_mod_get_transform = cfunc(
2291
+ "fluid_mod_get_transform", c_void_p, ("mod", c_void_p, 1),
2292
+ )
2293
+
2294
+ fluid_mod_has_dest = cfunc(
2295
+ "fluid_mod_has_dest", c_void_p, ("mod", c_void_p, 1), ("gen", c_uint, 1),
2296
+ )
2297
+
2298
+ fluid_mod_has_source = cfunc(
2299
+ "fluid_mod_has_dest",
2300
+ c_void_p,
2301
+ ("mod", c_void_p, 1),
2302
+ ("cc", c_uint, 1),
2303
+ ("ctrl", c_uint, 1),
2304
+ )
2305
+
2306
+ fluid_mod_set_amount = cfunc(
2307
+ "fluid_mod_set_amount", c_void_p, ("mod", c_void_p, 1), ("amount", c_double, 1),
2308
+ )
2309
+
2310
+ fluid_mod_set_dest = cfunc(
2311
+ "fluid_mod_set_dest", c_void_p, ("mod", c_void_p, 1), ("dst", c_int, 1),
2312
+ )
2313
+
2314
+ fluid_mod_set_source1 = cfunc(
2315
+ "fluid_mod_set_source1",
2316
+ c_void_p,
2317
+ ("mod", c_void_p, 1),
2318
+ ("src", c_int, 1),
2319
+ ("flags", c_int, 1),
2320
+ )
2321
+
2322
+ fluid_mod_set_source2 = cfunc(
2323
+ "fluid_mod_set_source2",
2324
+ c_void_p,
2325
+ ("mod", c_void_p, 1),
2326
+ ("src", c_int, 1),
2327
+ ("flags", c_int, 1),
2328
+ )
2329
+
2330
+ fluid_mod_set_transform = cfunc(
2331
+ "fluid_mod_set_transform", c_void_p, ("mod", c_void_p, 1), ("type", c_int, 1),
2332
+ )
2333
+
2334
+ fluid_mod_sizeof = cfunc("fluid_mod_sizeof", c_void_p)
2335
+
2336
+ fluid_mod_test_identity = cfunc(
2337
+ "fluid_mod_test_identity", c_void_p, ("mod1", c_void_p, 1), ("mod2", c_void_p, 1),
2338
+ )
2339
+
2340
+ # fluid_player_status returned by fluid_player_get_status()
2341
+ FLUID_PLAYER_READY = 0
2342
+ FLUID_PLAYER_PLAYING = 1
2343
+ FLUID_PLAYER_STOPPING = 2
2344
+ FLUID_PLAYER_DONE = 3
2345
+
2346
+ # tempo_type used by fluid_player_set_tempo()
2347
+ FLUID_PLAYER_TEMPO_INTERNAL = 0
2348
+ FLUID_PLAYER_TEMPO_EXTERNAL_BPM = 1
2349
+ FLUID_PLAYER_TEMPO_EXTERNAL_MIDI = 2
2350
+
2351
+ new_fluid_player = cfunc('new_fluid_player', c_void_p,
2352
+ ('synth', c_void_p, 1))
2353
+
2354
+ delete_fluid_player = cfunc('delete_fluid_player', None,
2355
+ ('player', c_void_p, 1))
2356
+
2357
+ fluid_player_add = cfunc('fluid_player_add', c_int,
2358
+ ('player', c_void_p, 1),
2359
+ ('filename', c_char_p, 1))
2360
+
2361
+
2362
+ fluid_player_get_status = cfunc('fluid_player_get_status', c_int,
2363
+ ('player', c_void_p, 1))
2364
+ fluid_player_join = cfunc('fluid_player_join', c_int,
2365
+ ('player', c_void_p, 1))
2366
+
2367
+ fluid_player_play = cfunc('fluid_player_play', c_int,
2368
+ ('player', c_void_p, 1))
2369
+
2370
+ fluid_player_set_playback_callback = cfunc('fluid_player_set_playback_callback', c_int,
2371
+ ('player', c_void_p, 1),
2372
+ ('handler', CFUNCTYPE(c_int, c_void_p, c_void_p), 1),
2373
+ ('event_handler_data', c_void_p, 1))
2374
+
2375
+ fluid_player_set_tempo = cfunc('fluid_player_set_tempo', c_int,
2376
+ ('player', c_void_p, 1),
2377
+ ('tempo_type', c_int, 1),
2378
+ ('tempo', c_double, 1))
2379
+
2380
+ fluid_player_seek = cfunc('fluid_player_seek', c_int,
2381
+ ('player', c_void_p, 1),
2382
+ ('ticks', c_int, 1))
2383
+
2384
+ fluid_player_stop = cfunc('fluid_player_stop', c_int,
2385
+ ('player', c_void_p, 1))
2386
+
2387
+ # fluid audio driver
2388
+ new_fluid_audio_driver = cfunc('new_fluid_audio_driver', c_void_p,
2389
+ ('settings', c_void_p, 1),
2390
+ ('synth', c_void_p, 1))
2391
+
2392
+ delete_fluid_audio_driver = cfunc('delete_fluid_audio_driver', None,
2393
+ ('driver', c_void_p, 1))
2394
+
2395
+ # fluid midi driver
2396
+ new_fluid_midi_driver = cfunc('new_fluid_midi_driver', c_void_p,
2397
+ ('settings', c_void_p, 1),
2398
+ ('handler', CFUNCTYPE(c_int, c_void_p, c_void_p), 1),
2399
+ ('event_handler_data', c_void_p, 1))
2400
+
2401
+ delete_fluid_midi_driver = cfunc('delete_fluid_midi_driver', None,
2402
+ ('driver', c_void_p, 1))
2403
+
2404
+
2405
+ # fluid midi router rule
2406
+ class fluid_midi_router_t(Structure):
2407
+ _fields_ = [
2408
+ ('synth', c_void_p),
2409
+ ('rules_mutex', c_void_p),
2410
+ ('rules', c_void_p*6),
2411
+ ('free_rules', c_void_p),
2412
+ ('event_handler', c_void_p),
2413
+ ('event_handler_data', c_void_p),
2414
+ ('nr_midi_channels', c_int),
2415
+ ('cmd_rule', c_void_p),
2416
+ ('cmd_rule_type', POINTER(c_int))]
2417
+
2418
+ delete_fluid_midi_router_rule = cfunc('delete_fluid_midi_router_rule', c_int,
2419
+ ('rule', c_void_p, 1))
2420
+
2421
+ new_fluid_midi_router_rule = cfunc('new_fluid_midi_router_rule', c_void_p)
2422
+
2423
+ fluid_midi_router_rule_set_chan = cfunc('fluid_midi_router_rule_set_chan', None,
2424
+ ('rule', c_void_p, 1),
2425
+ ('min', c_int, 1),
2426
+ ('max', c_int, 1),
2427
+ ('mul', c_float, 1),
2428
+ ('add', c_int, 1))
2429
+
2430
+ fluid_midi_router_rule_set_param1 = cfunc('fluid_midi_router_rule_set_param1', None,
2431
+ ('rule', c_void_p, 1),
2432
+ ('min', c_int, 1),
2433
+ ('max', c_int, 1),
2434
+ ('mul', c_float, 1),
2435
+ ('add', c_int, 1))
2436
+
2437
+ fluid_midi_router_rule_set_param2 = cfunc('fluid_midi_router_rule_set_param2', None,
2438
+ ('rule', c_void_p, 1),
2439
+ ('min', c_int, 1),
2440
+ ('max', c_int, 1),
2441
+ ('mul', c_float, 1),
2442
+ ('add', c_int, 1))
2443
+
2444
+ # fluid midi router
2445
+ new_fluid_midi_router = cfunc('new_fluid_midi_router', POINTER(fluid_midi_router_t),
2446
+ ('settings', c_void_p, 1),
2447
+ ('handler', CFUNCTYPE(c_int, c_void_p, c_void_p), 1),
2448
+ ('event_handler_data', c_void_p, 1))
2449
+
2450
+ fluid_midi_router_handle_midi_event = cfunc('fluid_midi_router_handle_midi_event', c_int,
2451
+ ('data', c_void_p, 1),
2452
+ ('event', c_void_p, 1))
2453
+
2454
+ fluid_midi_router_clear_rules = cfunc('fluid_midi_router_clear_rules', c_int,
2455
+ ('router', POINTER(fluid_midi_router_t), 1))
2456
+
2457
+ fluid_midi_router_set_default_rules = cfunc('fluid_midi_router_set_default_rules', c_int,
2458
+ ('router', POINTER(fluid_midi_router_t), 1))
2459
+
2460
+ fluid_midi_router_add_rule = cfunc('fluid_midi_router_add_rule', c_int,
2461
+ ('router', POINTER(fluid_midi_router_t), 1),
2462
+ ('rule', c_void_p, 1),
2463
+ ('type', c_int, 1))
2464
+
2465
+ # fluid file renderer
2466
+ new_fluid_file_renderer = cfunc('new_fluid_file_renderer', c_void_p,
2467
+ ('synth', c_void_p, 1))
2468
+
2469
+ delete_fluid_file_renderer = cfunc('delete_fluid_file_renderer', None,
2470
+ ('renderer', c_void_p, 1))
2471
+
2472
+ fluid_file_renderer_process_block = cfunc('fluid_file_renderer_process_block', c_int,
2473
+ ('render', c_void_p, 1))
2474
+
2475
+ # fluidsynth 2.x
2476
+ new_fluid_cmd_handler=cfunc('new_fluid_cmd_handler', c_void_p,
2477
+ ('synth', c_void_p, 1),
2478
+ ('router', c_void_p, 1))
2479
+
2480
+ fluid_synth_get_sfont_by_id = cfunc('fluid_synth_get_sfont_by_id', c_void_p,
2481
+ ('synth', c_void_p, 1),
2482
+ ('id', c_int, 1))
2483
+
2484
+ fluid_sfont_get_preset = cfunc('fluid_sfont_get_preset', c_void_p,
2485
+ ('sfont', c_void_p, 1),
2486
+ ('banknum', c_int, 1),
2487
+ ('prenum', c_int, 1))
2488
+
2489
+ fluid_preset_get_name = cfunc('fluid_preset_get_name', c_char_p,
2490
+ ('preset', c_void_p, 1))
2491
+
2492
+ fluid_synth_set_reverb = cfunc('fluid_synth_set_reverb', c_int,
2493
+ ('synth', c_void_p, 1),
2494
+ ('roomsize', c_double, 1),
2495
+ ('damping', c_double, 1),
2496
+ ('width', c_double, 1),
2497
+ ('level', c_double, 1))
2498
+
2499
+ fluid_synth_set_chorus = cfunc('fluid_synth_set_chorus', c_int,
2500
+ ('synth', c_void_p, 1),
2501
+ ('nr', c_int, 1),
2502
+ ('level', c_double, 1),
2503
+ ('speed', c_double, 1),
2504
+ ('depth_ms', c_double, 1),
2505
+ ('type', c_int, 1))
2506
+
2507
+ fluid_synth_get_chorus_speed = cfunc('fluid_synth_get_chorus_speed', c_double,
2508
+ ('synth', c_void_p, 1))
2509
+
2510
+ fluid_synth_get_chorus_depth = cfunc('fluid_synth_get_chorus_depth', c_double,
2511
+ ('synth', c_void_p, 1))
2512
+
2513
+
2514
+ def fluid_synth_write_s16_stereo(synth, len):
2515
+ """Return generated samples in stereo 16-bit format
2516
+
2517
+ Return value is a Numpy array of samples.
2518
+
2519
+ """
2520
+ import numpy
2521
+ buf = create_string_buffer(len * 4)
2522
+ fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2)
2523
+ return numpy.frombuffer(buf[:], dtype=numpy.int16)
2524
+
2525
+
2526
+ # Object-oriented interface, simplifies access to functions
2527
+
2528
+ class Synth:
2529
+ """Synth represents a FluidSynth synthesizer"""
2530
+ def __init__(self, gain=0.2, samplerate=44100, channels=256, **kwargs):
2531
+ """Create new synthesizer object to control sound generation
2532
+
2533
+ Optional keyword arguments:
2534
+ gain : scale factor for audio output, default is 0.2
2535
+ lower values are quieter, allow more simultaneous notes
2536
+ samplerate : output samplerate in Hz, default is 44100 Hz
2537
+ added capability for passing arbitrary fluid settings using args
2538
+ """
2539
+ self.settings = new_fluid_settings()
2540
+ self.setting('synth.gain', gain)
2541
+ self.setting('synth.sample-rate', float(samplerate))
2542
+ self.setting('synth.midi-channels', channels)
2543
+ for opt,val in kwargs.items():
2544
+ self.setting(opt, val)
2545
+ self.synth = new_fluid_synth(self.settings)
2546
+ self.audio_driver = None
2547
+ self.midi_driver = None
2548
+ self.router = None
2549
+ self.custom_router_callback = None
2550
+ def setting(self, opt, val):
2551
+ """change an arbitrary synth setting, type-smart"""
2552
+ if isinstance(val, (str, bytes)):
2553
+ fluid_settings_setstr(self.settings, opt.encode(), val.encode())
2554
+ elif isinstance(val, int):
2555
+ fluid_settings_setint(self.settings, opt.encode(), val)
2556
+ elif isinstance(val, float):
2557
+ fluid_settings_setnum(self.settings, opt.encode(), c_double(val))
2558
+ def get_setting(self, opt):
2559
+ """get current value of an arbitrary synth setting"""
2560
+ val = c_int()
2561
+ if fluid_settings_getint(self.settings, opt.encode(), byref(val)) == FLUIDSETTING_EXISTS:
2562
+ return val.value
2563
+ strval = create_string_buffer(32)
2564
+ if fluid_settings_copystr(self.settings, opt.encode(), strval, 32) == FLUIDSETTING_EXISTS:
2565
+ return strval.value.decode()
2566
+ num = c_double()
2567
+ if fluid_settings_getnum(self.settings, opt.encode(), byref(num)) == FLUIDSETTING_EXISTS:
2568
+ return round(num.value, 6)
2569
+ return None
2570
+
2571
+ def start(self, driver=None, device=None, midi_driver=None, midi_router=None):
2572
+ """Start audio output driver in separate background thread
2573
+
2574
+ Call this function any time after creating the Synth object.
2575
+ If you don't call this function, use get_samples() to generate
2576
+ samples.
2577
+
2578
+ Optional keyword argument:
2579
+ driver : which audio driver to use for output
2580
+ device : the device to use for audio output
2581
+ midi_driver : the midi driver to use for communicating with midi devices
2582
+ see http://www.fluidsynth.org/api/fluidsettings.xml for allowed values and defaults by platform
2583
+ """
2584
+ driver = driver or self.get_setting('audio.driver')
2585
+ device = device or self.get_setting(f'audio.{driver}.device')
2586
+ midi_driver = midi_driver or self.get_setting('midi.driver')
2587
+
2588
+ self.setting('audio.driver', driver)
2589
+ self.setting(f'audio.{driver}.device', device)
2590
+ self.audio_driver = new_fluid_audio_driver(self.settings, self.synth)
2591
+ self.setting('midi.driver', midi_driver)
2592
+ self.router = new_fluid_midi_router(self.settings, fluid_synth_handle_midi_event, self.synth)
2593
+ if new_fluid_cmd_handler:
2594
+ new_fluid_cmd_handler(self.synth, self.router)
2595
+ else:
2596
+ fluid_synth_set_midi_router(self.synth, self.router)
2597
+ if midi_router is None: ## Use fluidsynth to create a MIDI event handler
2598
+ self.midi_driver = new_fluid_midi_driver(self.settings, fluid_midi_router_handle_midi_event, self.router)
2599
+ self.custom_router_callback = None
2600
+ else: ## Supply an external MIDI event handler
2601
+ self.custom_router_callback = CFUNCTYPE(c_int, c_void_p, c_void_p)(midi_router)
2602
+ self.midi_driver = new_fluid_midi_driver(self.settings, self.custom_router_callback, self.router)
2603
+ return FLUID_OK
2604
+
2605
+ def delete(self):
2606
+ if self.audio_driver:
2607
+ delete_fluid_audio_driver(self.audio_driver)
2608
+ if self.midi_driver:
2609
+ delete_fluid_midi_driver(self.midi_driver)
2610
+ delete_fluid_synth(self.synth)
2611
+ delete_fluid_settings(self.settings)
2612
+ def sfload(self, filename, update_midi_preset=0):
2613
+ """Load SoundFont and return its ID"""
2614
+ return fluid_synth_sfload(self.synth, filename.encode(), update_midi_preset)
2615
+ def sfunload(self, sfid, update_midi_preset=0):
2616
+ """Unload a SoundFont and free memory it used"""
2617
+ return fluid_synth_sfunload(self.synth, sfid, update_midi_preset)
2618
+ def program_select(self, chan, sfid, bank, preset):
2619
+ """Select a program"""
2620
+ return fluid_synth_program_select(self.synth, chan, sfid, bank, preset)
2621
+ def program_unset(self, chan):
2622
+ """Set the preset of a MIDI channel to an unassigned state"""
2623
+ return fluid_synth_unset_program(self.synth, chan)
2624
+ def channel_info(self, chan):
2625
+ """get soundfont, bank, prog, preset name of channel"""
2626
+ if fluid_synth_get_channel_info is not None:
2627
+ info=fluid_synth_channel_info_t()
2628
+ fluid_synth_get_channel_info(self.synth, chan, byref(info))
2629
+ return (info.sfont_id, info.bank, info.program, info.name)
2630
+ else:
2631
+ (sfontid, banknum, presetnum) = self.program_info(chan)
2632
+ presetname = self.sfpreset_name(sfontid, banknum, presetnum)
2633
+ return (sfontid, banknum, presetnum, presetname)
2634
+ def program_info(self, chan):
2635
+ """get active soundfont, bank, prog on a channel"""
2636
+ if fluid_synth_get_program is not None:
2637
+ sfontid=c_int()
2638
+ banknum=c_int()
2639
+ presetnum=c_int()
2640
+ fluid_synth_get_program(self.synth, chan, byref(sfontid), byref(banknum), byref(presetnum))
2641
+ return (sfontid.value, banknum.value, presetnum.value)
2642
+ else:
2643
+ (sfontid, banknum, prognum, presetname) = self.channel_info(chan)
2644
+ return (sfontid, banknum, prognum)
2645
+ def sfpreset_name(self, sfid, bank, prenum):
2646
+ """Return name of a soundfont preset"""
2647
+ if fluid_synth_get_sfont_by_id is not None:
2648
+ sfont=fluid_synth_get_sfont_by_id(self.synth, sfid)
2649
+ preset=fluid_sfont_get_preset(sfont, bank, prenum)
2650
+ if not preset:
2651
+ return None
2652
+ return fluid_preset_get_name(preset).decode('ascii')
2653
+ else:
2654
+ return None
2655
+ def router_clear(self):
2656
+ if self.router is not None:
2657
+ fluid_midi_router_clear_rules(self.router)
2658
+ def router_default(self):
2659
+ if self.router is not None:
2660
+ fluid_midi_router_set_default_rules(self.router)
2661
+ def router_begin(self, type):
2662
+ """types are [note|cc|prog|pbend|cpress|kpress]"""
2663
+ if self.router is not None:
2664
+ if type=='note':
2665
+ self.router.cmd_rule_type=0
2666
+ elif type=='cc':
2667
+ self.router.cmd_rule_type=1
2668
+ elif type=='prog':
2669
+ self.router.cmd_rule_type=2
2670
+ elif type=='pbend':
2671
+ self.router.cmd_rule_type=3
2672
+ elif type=='cpress':
2673
+ self.router.cmd_rule_type=4
2674
+ elif type=='kpress':
2675
+ self.router.cmd_rule_type=5
2676
+ if 'self.router.cmd_rule' in globals():
2677
+ delete_fluid_midi_router_rule(self.router.cmd_rule)
2678
+ self.router.cmd_rule = new_fluid_midi_router_rule()
2679
+ def router_end(self):
2680
+ if self.router is not None:
2681
+ if self.router.cmd_rule is None:
2682
+ return
2683
+ if fluid_midi_router_add_rule(self.router, self.router.cmd_rule, self.router.cmd_rule_type)<0:
2684
+ delete_fluid_midi_router_rule(self.router.cmd_rule)
2685
+ self.router.cmd_rule=None
2686
+ def router_chan(self, min, max, mul, add):
2687
+ if self.router is not None:
2688
+ fluid_midi_router_rule_set_chan(self.router.cmd_rule, min, max, mul, add)
2689
+ def router_par1(self, min, max, mul, add):
2690
+ if self.router is not None:
2691
+ fluid_midi_router_rule_set_param1(self.router.cmd_rule, min, max, mul, add)
2692
+ def router_par2(self, min, max, mul, add):
2693
+ if self.router is not None:
2694
+ fluid_midi_router_rule_set_param2(self.router.cmd_rule, min, max, mul, add)
2695
+ def set_reverb(self, roomsize=-1.0, damping=-1.0, width=-1.0, level=-1.0):
2696
+ """
2697
+ roomsize Reverb room size value (0.0-1.0)
2698
+ damping Reverb damping value (0.0-1.0)
2699
+ width Reverb width value (0.0-100.0)
2700
+ level Reverb level value (0.0-1.0)
2701
+ """
2702
+ if fluid_synth_set_reverb is not None:
2703
+ return fluid_synth_set_reverb(self.synth, roomsize, damping, width, level)
2704
+ else:
2705
+ flags=0
2706
+ if roomsize>=0:
2707
+ flags+=0b0001
2708
+ if damping>=0:
2709
+ flags+=0b0010
2710
+ if width>=0:
2711
+ flags+=0b0100
2712
+ if level>=0:
2713
+ flags+=0b1000
2714
+ return fluid_synth_set_reverb_full(self.synth, flags, roomsize, damping, width, level)
2715
+ def set_chorus(self, nr=-1, level=-1.0, speed=-1.0, depth=-1.0, type=-1):
2716
+ """
2717
+ nr Chorus voice count (0-99, CPU time consumption proportional to this value)
2718
+ level Chorus level (0.0-10.0)
2719
+ speed Chorus speed in Hz (0.29-5.0)
2720
+ depth_ms Chorus depth (max value depends on synth sample rate, 0.0-21.0 is safe for sample rate values up to 96KHz)
2721
+ type Chorus waveform type (0=sine, 1=triangle)
2722
+ """
2723
+ if fluid_synth_set_chorus is not None:
2724
+ return fluid_synth_set_chorus(self.synth, nr, level, speed, depth, type)
2725
+ else:
2726
+ set=0
2727
+ if nr>=0:
2728
+ set+=0b00001
2729
+ if level>=0:
2730
+ set+=0b00010
2731
+ if speed>=0:
2732
+ set+=0b00100
2733
+ if depth>=0:
2734
+ set+=0b01000
2735
+ if type>=0:
2736
+ set+=0b10000
2737
+ return fluid_synth_set_chorus_full(self.synth, set, nr, level, speed, depth, type)
2738
+ def set_reverb_roomsize(self, roomsize):
2739
+ if fluid_synth_set_reverb_roomsize is not None:
2740
+ return fluid_synth_set_reverb_roomsize(self.synth, roomsize)
2741
+ else:
2742
+ return self.set_reverb(roomsize=roomsize)
2743
+ def set_reverb_damp(self, damping):
2744
+ if fluid_synth_set_reverb_damp is not None:
2745
+ return fluid_synth_set_reverb_damp(self.synth, damping)
2746
+ else:
2747
+ return self.set_reverb(damping=damping)
2748
+ def set_reverb_level(self, level):
2749
+ if fluid_synth_set_reverb_level is not None:
2750
+ return fluid_synth_set_reverb_level(self.synth, level)
2751
+ else:
2752
+ return self.set_reverb(level=level)
2753
+ def set_reverb_width(self, width):
2754
+ if fluid_synth_set_reverb_width is not None:
2755
+ return fluid_synth_set_reverb_width(self.synth, width)
2756
+ else:
2757
+ return self.set_reverb(width=width)
2758
+ def set_chorus_nr(self, nr):
2759
+ if fluid_synth_set_chorus_nr is not None:
2760
+ return fluid_synth_set_chorus_nr(self.synth, nr)
2761
+ else:
2762
+ return self.set_chorus(nr=nr)
2763
+ def set_chorus_level(self, level):
2764
+ if fluid_synth_set_chorus_level is not None:
2765
+ return fluid_synth_set_chorus_level(self.synth, level)
2766
+ else:
2767
+ return self.set_chorus(level=level)
2768
+ def set_chorus_speed(self, speed):
2769
+ if fluid_synth_set_chorus_speed is not None:
2770
+ return fluid_synth_set_chorus_speed(self.synth, speed)
2771
+ else:
2772
+ return self.set_chorus(speed=speed)
2773
+ def set_chorus_depth(self, depth_ms):
2774
+ if fluid_synth_set_chorus_depth is not None:
2775
+ return fluid_synth_set_chorus_depth(self.synth, depth_ms)
2776
+ else:
2777
+ return self.set_chorus(depth=depth_ms)
2778
+ def set_chorus_type(self, type):
2779
+ if fluid_synth_set_chorus_type is not None:
2780
+ return fluid_synth_set_chorus_type(self.synth, type)
2781
+ else:
2782
+ return self.set_chorus(type=type)
2783
+ def get_reverb_roomsize(self):
2784
+ return fluid_synth_get_reverb_roomsize(self.synth)
2785
+ def get_reverb_damp(self):
2786
+ return fluid_synth_get_reverb_damp(self.synth)
2787
+ def get_reverb_level(self):
2788
+ return fluid_synth_get_reverb_level(self.synth)
2789
+ def get_reverb_width(self):
2790
+ return fluid_synth_get_reverb_width(self.synth)
2791
+ def get_chorus_nr(self):
2792
+ return fluid_synth_get_chorus_nr(self.synth)
2793
+ def get_chorus_level(self):
2794
+ return fluid_synth_get_reverb_level(self.synth)
2795
+ def get_chorus_speed(self):
2796
+ if fluid_synth_get_chorus_speed is not None:
2797
+ return fluid_synth_get_chorus_speed(self.synth)
2798
+ else:
2799
+ return fluid_synth_get_chorus_speed_Hz(self.synth)
2800
+ def get_chorus_depth(self):
2801
+ if fluid_synth_get_chorus_depth is not None:
2802
+ return fluid_synth_get_chorus_depth(self.synth)
2803
+ else:
2804
+ return fluid_synth_get_chorus_depth_ms(self.synth)
2805
+ def get_chorus_type(self):
2806
+ return fluid_synth_get_chorus_type(self.synth)
2807
+ def noteon(self, chan, key, vel):
2808
+ """Play a note"""
2809
+ if key < 0 or key > 127:
2810
+ return False
2811
+ if chan < 0:
2812
+ return False
2813
+ if vel < 0 or vel > 127:
2814
+ return False
2815
+ return fluid_synth_noteon(self.synth, chan, key, vel)
2816
+ def noteoff(self, chan, key):
2817
+ """Stop a note"""
2818
+ if key < 0 or key > 127:
2819
+ return False
2820
+ if chan < 0:
2821
+ return False
2822
+ return fluid_synth_noteoff(self.synth, chan, key)
2823
+ def pitch_bend(self, chan, val):
2824
+ """Adjust pitch of a playing channel by small amounts
2825
+
2826
+ A pitch bend value of 0 is no pitch change from default.
2827
+ A value of -2048 is 1 semitone down.
2828
+ A value of 2048 is 1 semitone up.
2829
+ Maximum values are -8192 to +8191 (transposing by 4 semitones).
2830
+
2831
+ """
2832
+ return fluid_synth_pitch_bend(self.synth, chan, max(0, min(val + 8192, 16383)))
2833
+ def cc(self, chan, ctrl, val):
2834
+ """Send control change value
2835
+
2836
+ The controls that are recognized are dependent on the
2837
+ SoundFont. Values are always 0 to 127. Typical controls
2838
+ include:
2839
+ 1 : vibrato
2840
+ 7 : volume
2841
+ 10 : pan (left to right)
2842
+ 11 : expression (soft to loud)
2843
+ 64 : sustain
2844
+ 91 : reverb
2845
+ 93 : chorus
2846
+ """
2847
+ return fluid_synth_cc(self.synth, chan, ctrl, val)
2848
+ def get_cc(self, chan, num):
2849
+ i=c_int()
2850
+ fluid_synth_get_cc(self.synth, chan, num, byref(i))
2851
+ return i.value
2852
+ def program_change(self, chan, prg):
2853
+ """Change the program"""
2854
+ return fluid_synth_program_change(self.synth, chan, prg)
2855
+ def bank_select(self, chan, bank):
2856
+ """Choose a bank"""
2857
+ return fluid_synth_bank_select(self.synth, chan, bank)
2858
+ def all_notes_off(self, chan):
2859
+ """Turn off all notes on a channel (release all keys)"""
2860
+ return fluid_synth_all_notes_off(self.synth, chan)
2861
+ def all_sounds_off(self, chan):
2862
+ """Turn off all sounds on a channel (equivalent to mute)"""
2863
+ return fluid_synth_all_sounds_off(self.synth, chan)
2864
+ def sfont_select(self, chan, sfid):
2865
+ """Choose a SoundFont"""
2866
+ return fluid_synth_sfont_select(self.synth, chan, sfid)
2867
+ def program_reset(self):
2868
+ """Reset the programs on all channels"""
2869
+ return fluid_synth_program_reset(self.synth)
2870
+ def system_reset(self):
2871
+ """Stop all notes and reset all programs"""
2872
+ return fluid_synth_system_reset(self.synth)
2873
+ def get_samples(self, len=1024):
2874
+ """Generate audio samples
2875
+
2876
+ The return value will be a NumPy array containing the given
2877
+ length of audio samples. If the synth is set to stereo output
2878
+ (the default) the array will be size 2 * len.
2879
+
2880
+ """
2881
+ return fluid_synth_write_s16_stereo(self.synth, len)
2882
+ def tuning_dump(self, bank, prog):
2883
+ """Get tuning information for given bank and preset
2884
+
2885
+ Return value is an array of length 128 with tuning factors for each MIDI note.
2886
+ Tuning factor of 0.0 in each position is standard tuning. Measured in cents.
2887
+ """
2888
+ pitch = (c_double * 128)()
2889
+ fluid_synth_tuning_dump(self.synth, bank, prog, None, 0, pitch)
2890
+ return pitch[:]
2891
+
2892
+ def midi_event_get_type(self, event):
2893
+ return fluid_midi_event_get_type(event)
2894
+ def midi_event_get_velocity(self, event):
2895
+ return fluid_midi_event_get_velocity(event)
2896
+ def midi_event_get_key(self, event):
2897
+ return fluid_midi_event_get_key(event)
2898
+ def midi_event_get_channel(self, event):
2899
+ return fluid_midi_event_get_channel(event)
2900
+ def midi_event_get_control(self, event):
2901
+ return fluid_midi_event_get_control(event)
2902
+ def midi_event_get_program(self, event):
2903
+ return fluid_midi_event_get_program(event)
2904
+ def midi_event_get_value(self, event):
2905
+ return fluid_midi_event_get_value(event)
2906
+
2907
+ def play_midi_file(self, filename):
2908
+ self.player = new_fluid_player(self.synth)
2909
+ if self.player is None:
2910
+ return FLUID_FAILED
2911
+ if self.custom_router_callback is not None:
2912
+ fluid_player_set_playback_callback(self.player, self.custom_router_callback, self.synth)
2913
+ status = fluid_player_add(self.player, filename.encode())
2914
+ if status == FLUID_FAILED:
2915
+ return status
2916
+ status = fluid_player_play(self.player)
2917
+ return status
2918
+
2919
+ def play_midi_stop(self):
2920
+ status = fluid_player_stop(self.player)
2921
+ if status == FLUID_FAILED:
2922
+ return status
2923
+ status = fluid_player_seek(self.player, 0)
2924
+ delete_fluid_player(self.player)
2925
+ return status
2926
+
2927
+ def player_set_tempo(self, tempo_type, tempo):
2928
+ return fluid_player_set_tempo(self.player, tempo_type, tempo)
2929
+
2930
+ def midi2audio(self, midifile, audiofile = "output.wav"):
2931
+ """Convert a midi file to an audio file"""
2932
+ self.setting("audio.file.name", audiofile)
2933
+ player = new_fluid_player(self.synth)
2934
+ fluid_player_add(player, midifile.encode())
2935
+ fluid_player_play(player)
2936
+ renderer = new_fluid_file_renderer(self.synth)
2937
+ while fluid_player_get_status(player) == FLUID_PLAYER_PLAYING:
2938
+ if fluid_file_renderer_process_block(renderer) != FLUID_OK:
2939
+ break
2940
+ delete_fluid_file_renderer(renderer)
2941
+ delete_fluid_player(player)
2942
+
2943
+ # flag values
2944
+ FLUID_MOD_POSITIVE = 0
2945
+ FLUID_MOD_NEGATIVE = 1
2946
+ FLUID_MOD_UNIPOLAR = 0
2947
+ FLUID_MOD_BIPOLAR = 2
2948
+ FLUID_MOD_LINEAR = 0
2949
+ FLUID_MOD_CONCAVE = 4
2950
+ FLUID_MOD_CONVEX = 8
2951
+ FLUID_MOD_SWITCH = 12
2952
+ FLUID_MOD_GC = 0
2953
+ FLUID_MOD_CC = 16
2954
+ FLUID_MOD_SIN = 0x80
2955
+
2956
+ # src values
2957
+ FLUID_MOD_NONE = 0
2958
+ FLUID_MOD_VELOCITY = 2
2959
+ FLUID_MOD_KEY = 3
2960
+ FLUID_MOD_KEYPRESSURE = 10
2961
+ FLUID_MOD_CHANNELPRESSURE = 13
2962
+ FLUID_MOD_PITCHWHEEL = 14
2963
+ FLUID_MOD_PITCHWHEELSENS = 16
2964
+
2965
+ # Transforms
2966
+ FLUID_MOD_TRANSFORM_LINEAR = 0
2967
+ FLUID_MOD_TRANSFORM_ABS = 2
2968
+
2969
+ class Modulator:
2970
+ def __init__(self):
2971
+ """Create new modulator object"""
2972
+ self.mod = new_fluid_mod()
2973
+
2974
+ def clone(self, src):
2975
+ response = fluid_mod_clone(self.mod, src)
2976
+ if response == FLUID_FAILED:
2977
+ raise Exception("Modulation clone failed")
2978
+ return response
2979
+
2980
+ def get_amount(self):
2981
+ response = fluid_mod_get_amount(self.mod)
2982
+ if response == FLUID_FAILED:
2983
+ raise Exception("Modulation amount get failed")
2984
+ return response
2985
+
2986
+ def get_dest(self):
2987
+ response = fluid_mod_get_dest(self.mod)
2988
+ if response == FLUID_FAILED:
2989
+ raise Exception("Modulation destination get failed")
2990
+ return response
2991
+
2992
+ def get_flags1(self):
2993
+ response = fluid_mod_get_flags1(self.mod)
2994
+ if response == FLUID_FAILED:
2995
+ raise Exception("Modulation flags1 get failed")
2996
+ return response
2997
+
2998
+ def get_flags2(self):
2999
+ response = fluid_mod_get_flags2(self.mod)
3000
+ if response == FLUID_FAILED:
3001
+ raise Exception("Modulation flags2 get failed")
3002
+ return response
3003
+
3004
+ def get_source1(self):
3005
+ response = fluid_mod_get_source1(self.mod)
3006
+ if response == FLUID_FAILED:
3007
+ raise Exception("Modulation source1 get failed")
3008
+ return response
3009
+
3010
+ def get_source2(self):
3011
+ response = fluid_mod_get_source2(self.mod)
3012
+ if response == FLUID_FAILED:
3013
+ raise Exception("Modulation source2 get failed")
3014
+ return response
3015
+
3016
+ def get_transform(self):
3017
+ response = fluid_mod_get_transform(self.mod)
3018
+ if response == FLUID_FAILED:
3019
+ raise Exception("Modulation transform get failed")
3020
+ return response
3021
+
3022
+ def has_dest(self, gen):
3023
+ response = fluid_mod_has_dest(self.mod, gen)
3024
+ if response == FLUID_FAILED:
3025
+ raise Exception("Modulation has destination check failed")
3026
+ return response
3027
+
3028
+ def has_source(self, cc, ctrl):
3029
+ response = fluid_mod_has_source(self.mod, cc, ctrl)
3030
+ if response == FLUID_FAILED:
3031
+ raise Exception("Modulation has source check failed")
3032
+ return response
3033
+
3034
+ def set_amount(self, amount):
3035
+ response = fluid_mod_set_amount(self.mod, amount)
3036
+ if response == FLUID_FAILED:
3037
+ raise Exception("Modulation set amount failed")
3038
+ return response
3039
+
3040
+ def set_dest(self, dest):
3041
+ response = fluid_mod_set_dest(self.mod, dest)
3042
+ if response == FLUID_FAILED:
3043
+ raise Exception("Modulation set dest failed")
3044
+ return response
3045
+
3046
+ def set_source1(self, src, flags):
3047
+ response = fluid_mod_set_source1(self.mod, src, flags)
3048
+ if response == FLUID_FAILED:
3049
+ raise Exception("Modulation set source 1 failed")
3050
+ return response
3051
+
3052
+ def set_source2(self, src, flags):
3053
+ response = fluid_mod_set_source2(self.mod, src, flags)
3054
+ if response == FLUID_FAILED:
3055
+ raise Exception("Modulation set source 2 failed")
3056
+ return response
3057
+
3058
+ def set_transform(self, type):
3059
+ response = fluid_mod_set_transform(self.mod, type)
3060
+ if response == FLUID_FAILED:
3061
+ raise Exception("Modulation set transform failed")
3062
+ return response
3063
+
3064
+ def sizeof(self):
3065
+ response = fluid_mod_sizeof()
3066
+ if response == FLUID_FAILED:
3067
+ raise Exception("Modulation sizeof failed")
3068
+ return response
3069
+
3070
+ def test_identity(self, mod2):
3071
+ response = fluid_mod_sizeof(self.mod, mod2)
3072
+ if response == FLUID_FAILED:
3073
+ raise Exception("Modulation identity check failed")
3074
+ return response
3075
+
3076
+ class Sequencer:
3077
+ def __init__(self, time_scale=1000, use_system_timer=True):
3078
+ """Create new sequencer object to control and schedule timing of midi events
3079
+
3080
+ Optional keyword arguments:
3081
+ time_scale: ticks per second, defaults to 1000
3082
+ use_system_timer: whether the sequencer should advance by itself
3083
+ """
3084
+ self.client_callbacks = []
3085
+ self.sequencer = new_fluid_sequencer2(use_system_timer)
3086
+ fluid_sequencer_set_time_scale(self.sequencer, time_scale)
3087
+
3088
+ def register_fluidsynth(self, synth):
3089
+ response = fluid_sequencer_register_fluidsynth(self.sequencer, synth.synth)
3090
+ if response == FLUID_FAILED:
3091
+ raise Exception("Registering fluid synth failed")
3092
+ return response
3093
+
3094
+ def register_client(self, name, callback, data=None):
3095
+ c_callback = CFUNCTYPE(None, c_uint, c_void_p, c_void_p, c_void_p)(callback)
3096
+ response = fluid_sequencer_register_client(self.sequencer, name.encode(), c_callback, data)
3097
+ if response == FLUID_FAILED:
3098
+ raise Exception("Registering client failed")
3099
+
3100
+ # store in a list to prevent garbage collection
3101
+ self.client_callbacks.append(c_callback)
3102
+
3103
+ return response
3104
+
3105
+ def note(self, time, channel, key, velocity, duration, source=-1, dest=-1, absolute=True):
3106
+ evt = self._create_event(source, dest)
3107
+ fluid_event_note(evt, channel, key, velocity, duration)
3108
+ self._schedule_event(evt, time, absolute)
3109
+ delete_fluid_event(evt)
3110
+
3111
+ def note_on(self, time, channel, key, velocity=127, source=-1, dest=-1, absolute=True):
3112
+ evt = self._create_event(source, dest)
3113
+ fluid_event_noteon(evt, channel, key, velocity)
3114
+ self._schedule_event(evt, time, absolute)
3115
+ delete_fluid_event(evt)
3116
+
3117
+ def note_off(self, time, channel, key, source=-1, dest=-1, absolute=True):
3118
+ evt = self._create_event(source, dest)
3119
+ fluid_event_noteoff(evt, channel, key)
3120
+ self._schedule_event(evt, time, absolute)
3121
+ delete_fluid_event(evt)
3122
+
3123
+ def timer(self, time, data=None, source=-1, dest=-1, absolute=True):
3124
+ evt = self._create_event(source, dest)
3125
+ fluid_event_timer(evt, data)
3126
+ self._schedule_event(evt, time, absolute)
3127
+ delete_fluid_event(evt)
3128
+
3129
+ def _create_event(self, source=-1, dest=-1):
3130
+ evt = new_fluid_event()
3131
+ fluid_event_set_source(evt, source)
3132
+ fluid_event_set_dest(evt, dest)
3133
+ return evt
3134
+
3135
+ def _schedule_event(self, evt, time, absolute=True):
3136
+ response = fluid_sequencer_send_at(self.sequencer, evt, time, absolute)
3137
+ if response == FLUID_FAILED:
3138
+ raise Exception("Scheduling event failed")
3139
+
3140
+ def get_tick(self):
3141
+ return fluid_sequencer_get_tick(self.sequencer)
3142
+
3143
+ def process(self, msec):
3144
+ fluid_sequencer_process(self.sequencer, msec)
3145
+
3146
+ def delete(self):
3147
+ delete_fluid_sequencer(self.sequencer)
3148
+
3149
+ def raw_audio_string(data):
3150
+ """Return a string of bytes to send to soundcard
3151
+
3152
+ Input is a numpy array of samples. Default output format
3153
+ is 16-bit signed (other formats not currently supported).
3154
+
3155
+ """
3156
+ import numpy
3157
+ return (data.astype(numpy.int16)).tobytes()
3158
+
3159
+ #===============================================================================
3160
+
3161
+ import numpy as np
3162
+ import wave
3163
+
3164
+ #===============================================================================
3165
+
3166
+ def normalize_audio(audio: np.ndarray,
3167
+ method: str = 'peak',
3168
+ target_level_db: float = -1.0,
3169
+ per_channel: bool = False,
3170
+ eps: float = 1e-9
3171
+ ) -> np.ndarray:
3172
+
3173
+ """
3174
+ Normalize audio to a target dBFS level.
3175
+
3176
+ Parameters
3177
+ ----------
3178
+ audio : np.ndarray
3179
+ Float-valued array in range [-1, 1] with shape (channels, samples)
3180
+ or (samples,) for mono.
3181
+ method : {'peak', 'rms'}
3182
+ - 'peak': scale so that max(|audio|) = target_level_lin
3183
+ - 'rms' : scale so that RMS(audio) = target_level_lin
3184
+ target_level_db : float
3185
+ Desired output level, in dBFS (0 dBFS = max digital full scale).
3186
+ e.g. -1.0 dBFS means ~0.8913 linear gain.
3187
+ per_channel : bool
3188
+ If True, normalize each channel independently. Otherwise, use a
3189
+ global measure across all channels.
3190
+ eps : float
3191
+ Small constant to avoid division by zero.
3192
+
3193
+ Returns
3194
+ -------
3195
+ normalized : np.ndarray
3196
+ Audio array of same shape, scaled so that levels meet the target.
3197
+ """
3198
+
3199
+ # Convert target dB to linear gain
3200
+ target_lin = 10 ** (target_level_db / 20.0)
3201
+
3202
+ # Ensure audio is float
3203
+ audio = audio.astype(np.float32)
3204
+
3205
+ # if mono, make it (1, N)
3206
+ if audio.ndim == 1:
3207
+ audio = audio[np.newaxis, :]
3208
+
3209
+ # Choose measurement axis
3210
+ axis = 1 if per_channel else None
3211
+
3212
+ if method == 'peak':
3213
+ # Compute peak per channel or global
3214
+ peak = np.max(np.abs(audio), axis=axis, keepdims=True)
3215
+ peak = np.maximum(peak, eps)
3216
+ scales = target_lin / peak
3217
+
3218
+ elif method == 'rms':
3219
+ # Compute RMS per channel or global
3220
+ rms = np.sqrt(np.mean(audio ** 2, axis=axis, keepdims=True))
3221
+ rms = np.maximum(rms, eps)
3222
+ scales = target_lin / rms
3223
+
3224
+ else:
3225
+ raise ValueError(f"Unsupported method '{method}'; choose 'peak' or 'rms'.")
3226
+
3227
+ # Broadcast scales back to audio shape
3228
+ normalized = audio * scales
3229
+
3230
+ # Clip just in case of rounding
3231
+ return np.clip(normalized, -1.0, 1.0)
3232
+
3233
+ #===============================================================================
3234
+
3235
+ def midi_opus_to_colab_audio(midi_opus,
3236
+ soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',
3237
+ sample_rate=16000, # 44100
3238
+ volume_level_db=-1,
3239
+ trim_silence=True,
3240
+ silence_threshold=0.1,
3241
+ enable_reverb=False,
3242
+ reverb_param_dic={'roomsize': 0,
3243
+ 'damping': 0,
3244
+ 'width': 0,
3245
+ 'level': 0
3246
+ },
3247
+ enable_chorus=False,
3248
+ chorus_param_dic={'nr': 0,
3249
+ 'level': 0,
3250
+ 'speed': 0.1,
3251
+ 'depth': 0,
3252
+ 'type': 0},
3253
+ output_for_gradio=False,
3254
+ write_audio_to_WAV=False,
3255
+ output_WAV_name=''
3256
+ ):
3257
+
3258
+ if midi_opus[1]:
3259
+
3260
+ ticks_per_beat, *tracks = midi_opus
3261
+ if not tracks:
3262
+ return None
3263
+
3264
+ # Flatten & convert delta-times to absolute-time
3265
+ events = []
3266
+ for track in tracks:
3267
+ abs_t = 0
3268
+ for name, dt, *data in track:
3269
+ abs_t += dt
3270
+ events.append([name, abs_t, *data])
3271
+ events.sort(key=lambda e: e[1])
3272
+
3273
+ # Setup FluidSynth
3274
+ fl = Synth(samplerate=float(sample_rate))
3275
+ sfid = fl.sfload(soundfont_path)
3276
+ for chan in range(16):
3277
+ # channel 9 = percussion GM bank 128
3278
+ fl.program_select(chan, sfid, 128 if chan == 9 else 0, 0)
3279
+
3280
+ if enable_reverb:
3281
+ fl.set_reverb(roomsize=reverb_param_dic['roomsize'],
3282
+ damping=reverb_param_dic['damping'],
3283
+ width=reverb_param_dic['width'],
3284
+ level=reverb_param_dic['level']
3285
+ )
3286
+
3287
+ """
3288
+ roomsize Reverb room size value (0.0-1.0)
3289
+ damping Reverb damping value (0.0-1.0)
3290
+ width Reverb width value (0.0-100.0)
3291
+ level Reverb level value (0.0-1.0)
3292
+ """
3293
+
3294
+ if enable_chorus:
3295
+ fl.set_chorus(nr=chorus_param_dic['nr'],
3296
+ level=chorus_param_dic['level'],
3297
+ speed=chorus_param_dic['speed'],
3298
+ depth=chorus_param_dic['depth'],
3299
+ type=chorus_param_dic['type']
3300
+ )
3301
+
3302
+ """
3303
+ nr Chorus voice count (0-99, CPU time consumption proportional to this value)
3304
+ level Chorus level (0.0-10.0)
3305
+ speed Chorus speed in Hz (0.29-5.0)
3306
+ depth_ms Chorus depth (max value depends on synth sample rate, 0.0-21.0 is safe for sample rate values up to 96KHz)
3307
+ type Chorus waveform type (0=sine, 1=triangle)
3308
+ """
3309
+
3310
+ # Playback vars
3311
+ tempo = int((60 / 120) * 1e6) # default 120bpm
3312
+ last_t = 0
3313
+ ss = np.empty((0, 2), dtype=np.int16)
3314
+
3315
+ for name, cur_t, *data in events:
3316
+ # compute how many samples have passed since the last event
3317
+ delta_ticks = cur_t - last_t
3318
+ last_t = cur_t
3319
+ dt_seconds = (delta_ticks / ticks_per_beat) * (tempo / 1e6)
3320
+ sample_len = int(dt_seconds * sample_rate)
3321
+ if sample_len > 0:
3322
+ buf = fl.get_samples(sample_len).reshape(-1, 2)
3323
+ ss = np.concatenate([ss, buf], axis=0)
3324
+
3325
+ # Dispatch every known event
3326
+ if name == "note_on" and data[2] > 0:
3327
+ chan, note, vel = data
3328
+ fl.noteon(chan, note, vel)
3329
+
3330
+ elif name == "note_off" or (name == "note_on" and data[2] == 0):
3331
+ chan, note = data[:2]
3332
+ fl.noteoff(chan, note)
3333
+
3334
+ elif name == "patch_change":
3335
+ chan, patch = data[:2]
3336
+ bank = 128 if chan == 9 else 0
3337
+ fl.program_select(chan, sfid, bank, patch)
3338
+
3339
+ elif name == "control_change":
3340
+ chan, ctrl, val = data[:3]
3341
+ fl.cc(chan, ctrl, val)
3342
+
3343
+ elif name == "key_after_touch":
3344
+ chan, note, vel = data
3345
+ # fl.key_pressure(chan, note, vel)
3346
+
3347
+ elif name == "channel_after_touch":
3348
+ chan, vel = data
3349
+ # fl.channel_pressure(chan, vel)
3350
+
3351
+ elif name == "pitch_wheel_change":
3352
+ chan, wheel = data
3353
+ fl.pitch_bend(chan, wheel)
3354
+
3355
+ elif name == "song_position":
3356
+ # song_pos = data[0]; # often not needed for playback
3357
+ pass
3358
+
3359
+ elif name == "song_select":
3360
+ # song_number = data[0]
3361
+ pass
3362
+
3363
+ elif name == "tune_request":
3364
+ # typically resets tuning; FS handles internally
3365
+ pass
3366
+
3367
+ elif name in ("sysex_f0", "sysex_f7"):
3368
+ raw_bytes = data[0]
3369
+ # fl.sysex(raw_bytes)
3370
+ pass
3371
+
3372
+ # Meta events & others—no direct audio effect, so we skip or log
3373
+ elif name in (
3374
+ "set_tempo", # handled below
3375
+ "end_track",
3376
+ "text_event", "text_event_08", "text_event_09", "text_event_0a",
3377
+ "text_event_0b", "text_event_0c", "text_event_0d", "text_event_0e", "text_event_0f",
3378
+ "copyright_text_event", "track_name", "instrument_name",
3379
+ "lyric", "marker", "cue_point",
3380
+ "smpte_offset", "time_signature", "key_signature",
3381
+ "sequencer_specific", "raw_meta_event"
3382
+ ):
3383
+ if name == "set_tempo":
3384
+ tempo = data[0]
3385
+ # else: skip all other meta & text; you could hook in logging here
3386
+ continue
3387
+
3388
+ else:
3389
+ # unknown event type
3390
+ continue
3391
+
3392
+ # Cleanup synth
3393
+ fl.delete()
3394
+
3395
+ if ss.size:
3396
+ maxv = np.abs(ss).max()
3397
+ if maxv:
3398
+ ss = (ss / maxv) * np.iinfo(np.int16).max
3399
+ ss = ss.astype(np.int16)
3400
+
3401
+ # Optional trimming of trailing silence
3402
+ if trim_silence and ss.size:
3403
+ thresh = np.std(np.abs(ss)) * silence_threshold
3404
+ idx = np.where(np.abs(ss) > thresh)[0]
3405
+ if idx.size:
3406
+ ss = ss[: idx[-1] + 1]
3407
+
3408
+ # For Gradio you might want raw int16 PCM
3409
+ if output_for_gradio:
3410
+ return ss
3411
+
3412
+ # Swap to (channels, samples) and normalize for playback
3413
+ ss = ss.T
3414
+ raw_audio = normalize_audio(ss, target_level_db=volume_level_db)
3415
+
3416
+ # Optionally write WAV to disk
3417
+ if write_audio_to_WAV:
3418
+ wav_name = midi_file.rsplit('.', 1)[0] + '.wav'
3419
+ if output_WAV_name != '':
3420
+ wav_name = output_WAV_name
3421
+ pcm = np.int16(raw_audio.T / np.max(np.abs(raw_audio)) * 32767)
3422
+ with wave.open(wav_name, 'wb') as wf:
3423
+ wf.setframerate(sample_rate)
3424
+ wf.setsampwidth(2)
3425
+ wf.setnchannels(pcm.shape[1])
3426
+ wf.writeframes(pcm.tobytes())
3427
+
3428
+ return raw_audio
3429
+
3430
+ else:
3431
+ return None
3432
+
3433
+ #===============================================================================
3434
+
3435
+ def midi_to_colab_audio(midi_file,
3436
+ soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',
3437
+ sample_rate=16000,
3438
+ volume_level_db=-1,
3439
+ trim_silence=True,
3440
+ silence_threshold=0.1,
3441
+ enable_reverb=False,
3442
+ reverb_param_dic={'roomsize': 0,
3443
+ 'damping': 0,
3444
+ 'width': 0,
3445
+ 'level': 0
3446
+ },
3447
+ enable_chorus=False,
3448
+ chorus_param_dic={'nr': 0,
3449
+ 'level': 0,
3450
+ 'speed': 0.1,
3451
+ 'depth': 0,
3452
+ 'type': 0},
3453
+ output_for_gradio=False,
3454
+ write_audio_to_WAV=False,
3455
+ output_WAV_name=''
3456
+ ):
3457
+ """
3458
+ Returns raw audio to pass to IPython.disaply.Audio func
3459
+
3460
+ Example usage:
3461
+
3462
+ from IPython.display import Audio
3463
+
3464
+ display(Audio(raw_audio, rate=16000, normalize=False))
3465
+ """
3466
+
3467
+ # Read and decode MIDI → opus event list
3468
+ ticks_per_beat, *tracks = midi2opus(open(midi_file, 'rb').read())
3469
+ if not tracks:
3470
+ return None
3471
+
3472
+ # Flatten & convert delta-times to absolute-time
3473
+ events = []
3474
+ for track in tracks:
3475
+ abs_t = 0
3476
+ for name, dt, *data in track:
3477
+ abs_t += dt
3478
+ events.append([name, abs_t, *data])
3479
+ events.sort(key=lambda e: e[1])
3480
+
3481
+ # Setup FluidSynth
3482
+ fl = Synth(samplerate=float(sample_rate))
3483
+ sfid = fl.sfload(soundfont_path)
3484
+ for chan in range(16):
3485
+ # channel 9 = percussion GM bank 128
3486
+ fl.program_select(chan, sfid, 128 if chan == 9 else 0, 0)
3487
+
3488
+ if enable_reverb:
3489
+ fl.set_reverb(roomsize=reverb_param_dic['roomsize'],
3490
+ damping=reverb_param_dic['damping'],
3491
+ width=reverb_param_dic['width'],
3492
+ level=reverb_param_dic['level']
3493
+ )
3494
+
3495
+ """
3496
+ roomsize Reverb room size value (0.0-1.0)
3497
+ damping Reverb damping value (0.0-1.0)
3498
+ width Reverb width value (0.0-100.0)
3499
+ level Reverb level value (0.0-1.0)
3500
+ """
3501
+
3502
+ if enable_chorus:
3503
+ fl.set_chorus(nr=chorus_param_dic['nr'],
3504
+ level=chorus_param_dic['level'],
3505
+ speed=chorus_param_dic['speed'],
3506
+ depth=chorus_param_dic['depth'],
3507
+ type=chorus_param_dic['type']
3508
+ )
3509
+
3510
+ """
3511
+ nr Chorus voice count (0-99, CPU time consumption proportional to this value)
3512
+ level Chorus level (0.0-10.0)
3513
+ speed Chorus speed in Hz (0.29-5.0)
3514
+ depth_ms Chorus depth (max value depends on synth sample rate, 0.0-21.0 is safe for sample rate values up to 96KHz)
3515
+ type Chorus waveform type (0=sine, 1=triangle)
3516
+ """
3517
+ # Playback vars
3518
+ tempo = int((60 / 120) * 1e6) # default 120bpm
3519
+ last_t = 0
3520
+ ss = np.empty((0, 2), dtype=np.int16)
3521
+
3522
+ for name, cur_t, *data in events:
3523
+ # compute how many samples have passed since the last event
3524
+ delta_ticks = cur_t - last_t
3525
+ last_t = cur_t
3526
+ dt_seconds = (delta_ticks / ticks_per_beat) * (tempo / 1e6)
3527
+ sample_len = int(dt_seconds * sample_rate)
3528
+ if sample_len > 0:
3529
+ buf = fl.get_samples(sample_len).reshape(-1, 2)
3530
+ ss = np.concatenate([ss, buf], axis=0)
3531
+
3532
+ # Dispatch every known event
3533
+ if name == "note_on" and data[2] > 0:
3534
+ chan, note, vel = data
3535
+ fl.noteon(chan, note, vel)
3536
+
3537
+ elif name == "note_off" or (name == "note_on" and data[2] == 0):
3538
+ chan, note = data[:2]
3539
+ fl.noteoff(chan, note)
3540
+
3541
+ elif name == "patch_change":
3542
+ chan, patch = data[:2]
3543
+ bank = 128 if chan == 9 else 0
3544
+ fl.program_select(chan, sfid, bank, patch)
3545
+
3546
+ elif name == "control_change":
3547
+ chan, ctrl, val = data[:3]
3548
+ fl.cc(chan, ctrl, val)
3549
+
3550
+ elif name == "key_after_touch":
3551
+ chan, note, vel = data
3552
+ # fl.key_pressure(chan, note, vel)
3553
+
3554
+ elif name == "channel_after_touch":
3555
+ chan, vel = data
3556
+ # fl.channel_pressure(chan, vel)
3557
+
3558
+ elif name == "pitch_wheel_change":
3559
+ chan, wheel = data
3560
+ fl.pitch_bend(chan, wheel)
3561
+
3562
+ elif name == "song_position":
3563
+ # song_pos = data[0]; # often not needed for playback
3564
+ pass
3565
+
3566
+ elif name == "song_select":
3567
+ # song_number = data[0]
3568
+ pass
3569
+
3570
+ elif name == "tune_request":
3571
+ # typically resets tuning; FS handles internally
3572
+ pass
3573
+
3574
+ elif name in ("sysex_f0", "sysex_f7"):
3575
+ raw_bytes = data[0]
3576
+ # fl.sysex(raw_bytes)
3577
+ pass
3578
+
3579
+ # Meta events & others—no direct audio effect, so we skip or log
3580
+ elif name in (
3581
+ "set_tempo", # handled below
3582
+ "end_track",
3583
+ "text_event", "text_event_08", "text_event_09", "text_event_0a",
3584
+ "text_event_0b", "text_event_0c", "text_event_0d", "text_event_0e", "text_event_0f",
3585
+ "copyright_text_event", "track_name", "instrument_name",
3586
+ "lyric", "marker", "cue_point",
3587
+ "smpte_offset", "time_signature", "key_signature",
3588
+ "sequencer_specific", "raw_meta_event"
3589
+ ):
3590
+ if name == "set_tempo":
3591
+ tempo = data[0]
3592
+ # else: skip all other meta & text; you could hook in logging here
3593
+ continue
3594
+
3595
+ else:
3596
+ # unknown event type
3597
+ continue
3598
+
3599
+ # Cleanup synth
3600
+ fl.delete()
3601
+
3602
+ if ss.size:
3603
+ maxv = np.abs(ss).max()
3604
+ if maxv:
3605
+ ss = (ss / maxv) * np.iinfo(np.int16).max
3606
+ ss = ss.astype(np.int16)
3607
+
3608
+ # Optional trimming of trailing silence
3609
+ if trim_silence and ss.size:
3610
+ thresh = np.std(np.abs(ss)) * silence_threshold
3611
+ idx = np.where(np.abs(ss) > thresh)[0]
3612
+ if idx.size:
3613
+ ss = ss[: idx[-1] + 1]
3614
+
3615
+ # For Gradio you might want raw int16 PCM
3616
+ if output_for_gradio:
3617
+ return ss
3618
+
3619
+ # Swap to (channels, samples) and normalize for playback
3620
+ ss = ss.T
3621
+ raw_audio = normalize_audio(ss, target_level_db=volume_level_db)
3622
+
3623
+ # Optionally write WAV to disk
3624
+ if write_audio_to_WAV:
3625
+ wav_name = midi_file.rsplit('.', 1)[0] + '.wav'
3626
+ if output_WAV_name != '':
3627
+ wav_name = output_WAV_name
3628
+ pcm = np.int16(raw_audio.T / np.max(np.abs(raw_audio)) * 32767)
3629
+ with wave.open(wav_name, 'wb') as wf:
3630
+ wf.setframerate(sample_rate)
3631
+ wf.setsampwidth(2)
3632
+ wf.setnchannels(pcm.shape[1])
3633
+ wf.writeframes(pcm.tobytes())
3634
+
3635
+ return raw_audio
3636
+
3637
+ #===================================================================================================================