-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmidi-rubato
executable file
·198 lines (161 loc) · 6.07 KB
/
midi-rubato
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python3
"""
midi-rubato - inserts tempo change events into a .midi file
Copyright (C) 2013 Adam Spiers <[email protected]>
This program inserts MIDI tempo changes from a beat map file into a
MIDI file. A beat map file is a text file with a list of beats, one
per line, where each line is whitespace delimited with the following
fields:
- label, e.g. "C5" for the 5th measure of section C
- section, e.g. "3" for section C
- measure, e.g. "5" for the 5th measure of the section
- beat, e.g. "2" for the 2nd beat of the measure
- timestamp, e.g. "0:02:56.280" for just under 3 minutes
- tempo, e.g. "60" for 60 beats per minute
You can generate a beat map file from an .xsc file via the
xsc2beatmap found in the same location as this program.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
from optparse import OptionParser
import mido
def parse_args():
parser = OptionParser("Usage: %prog SRC-MIDI BEATMAP DST-MIDI")
# parser.add_option("-i", "--input", dest="input",
# help="input LilyPond project", metavar="FILE")
if len(sys.argv) != 4:
parser.print_help()
sys.exit(0)
src, beatmap, dst = sys.argv[1:]
return src, beatmap, dst
def main():
src, beatmap, dst = parse_args()
generate_adjusted_midi_file(src, dst, beatmap)
def make_time_abs(midiFile):
"""
Changes the time of all messages to absolute time in ticks
"""
for track in midiFile.tracks:
time = 0
for event in track:
time += event.time
event.time = time
def make_time_rel(midiFile):
"""
Changes the time of all messages to incremental time in ticks
"""
for track in midiFile.tracks:
prev_time = 0
for event in track:
tmp_time = event.time
event.time -= prev_time
prev_time = tmp_time
def get_tempos_from_beatmap(filename, resolution):
xsc = open(filename)
qpms = [ ] # quarter-notes per minute
tick = 0
for line in xsc.readlines():
fields = line.split()
label, section, measure, beat, timestamp = fields[0:5]
beat_value = float(fields[5]) / int(fields[6])
# There is no tempo for the final beat
if len(fields) == 8:
bpm = float(fields[7])
qpm = bpm * beat_value
qpms.append((tick, bpm, qpm, int(section), int(measure), int(beat)))
tick += int(resolution * beat_value)
else:
break
xsc.close()
return qpms
def new_tempo_event(tick, new_bpm, new_qpm, section, measure, beat):
print("inserting %6.2fbpm (%6.2fqpm) @ section %d bar %3d beat %d tick %6d" %
(new_bpm, new_qpm, section, measure, beat, tick))
tc = mido.MetaMessage('set_tempo', time=tick, tempo=mido.bpm2tempo(new_qpm))
# N.B. the midi library's API incorrectly refers to bpm when
# it actually means qpm:
return tc
def apply_rubato(tracks, tempos):
"""Splice MIDI tempo change events into control track 0."""
control = tracks[0]
# Delete EndOfTrackEvent and anything to the right of it
# (presumably there shouldn't be anything to the right but you
# never know).
for i in xrange(len(control)):
event = control[i]
if event.type == 'end_of_track':
del control[i:]
break
event_index = 0
while event_index < len(control):
event = control[event_index]
print("%d: existing %s" % (event_index, event))
# insert any new tempo changes before the current tick
while True:
if not tempos:
break
next_tempo = tempos[0]
next_tempo_tick = next_tempo[0]
if next_tempo_tick > event.time:
break
tc = new_tempo_event(*(tempos.pop(0)))
control.insert(event_index, tc)
event_index += 1
# remove any pre-existing SetTempoEvents
if event.type == 'set_tempo':
print(" - dropping SetTempoEvent")
del control[event_index]
else:
event_index += 1
final_tick = get_final_tick(tracks[1:])
while tempos:
next_tempo = tempos[0]
next_tempo_tick = next_tempo[0]
if next_tempo_tick > final_tick:
break # no point appending tempos after we ran out of notes
tc = new_tempo_event(*(tempos.pop(0)))
control.append(tc)
eot = mido.MetaMessage('end_of_track', time=control[-1].time)
control.append(eot)
def get_final_tick(tracks):
final_tick = None
for track in tracks:
for event in track:
if event.time > final_tick:
final_tick = event.time
return final_tick
def timestamp_to_secs(timestamp):
hours, mins, secs = timestamp.split(':')
return (int(hours)*60 + int(mins))*60.0 + float(secs)
def secs_to_timestamp(secs):
mins = secs / 60
secs = secs % 60
hours = mins / 60
mins = mins % 60
secs = str(secs)
if secs[1] == '.':
secs = '0' + secs
return "%d:%02d:%s" % (hours, mins, secs)
def generate_adjusted_midi_file(src, dst, beatmap):
midiFile = mido.MidiFile(src)
print("Read from %s" % src)
make_time_abs(midiFile)
beats = get_tempos_from_beatmap(beatmap, midiFile.ticks_per_beat)
apply_rubato(midiFile.tracks, beats)
from pprint import pprint
pprint(midiFile.tracks[0][-2])
pprint(midiFile.tracks[1][-2])
make_time_rel(midiFile)
midiFile.save(dst)
print("Wrote tempo-adjusted tracks to %s" % dst)
if __name__ == '__main__':
main()