-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeflow.py
More file actions
333 lines (271 loc) · 9.22 KB
/
timeflow.py
File metadata and controls
333 lines (271 loc) · 9.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""
timeflow.py
Tools for executing musically-important
callbacks at regular intervals.
"""
import time
import OSC
import os
import random
from sched import scheduler
import loader
class TempoClock(object):
"""
Converts between beats and timestamps.
"""
def __init__(self, start_time = None, bpm = 120):
self.bpm = bpm
self.start_time = start_time
if (self.start_time == None):
self.start_time = time.time()
def beats_in(self, span, subdiv=1):
beats = []
if(span["bottom"] < self.start_time):
return beats
seconds_per_beat = float(60) / self.bpm / subdiv
seconds_elapsed = span["bottom"] - self.start_time
beats_elapsed = seconds_elapsed / seconds_per_beat
if(beats_elapsed % 1 is not 0):
beats_elapsed = int(beats_elapsed) + 1
current_beat = beats_elapsed * seconds_per_beat + self.start_time
while(current_beat <= span["top"]):
beats.append(Beat(current_beat, beats_elapsed))
current_beat = current_beat + seconds_per_beat
return beats
def beat_at(self, num=None, time=None):
seconds_per_beat = float(60) / self.bpm
if time:
out_num = (time - self.start_time) / seconds_per_beat
return Beat(time, out_num)
beattime = seconds_per_beat * num + self.start_time
return Beat(beattime, num)
class Beat(object):
"""
A point in time, represented as a
.time timestamp as well as a
.num beat number.
"""
def __init__(self, time, num):
self.time = time
self.num = num
def synth_nodes():
"""
Generates unique node ids
"""
i = 0
while True:
i = i + 1
yield i
synth_nodes = synth_nodes()
class Group(object):
def __init__(self):
self.group_id = synth_nodes.next()
def get_message(self):
message = OSC.OSCMessage("/g_new")
message.append([self.group_id, 1, 0])
return message
def create_at(self, start_time):
bundle = OSC.OSCBundle()
bundle.setTimeTag(start_time)
message = OSC.OSCMessage("/g_new")
message.append([self.group_id, 1, 0])
bundle.append(message)
loader.client.send(bundle)
return self
class Synth(object):
"""
Representation of a SuperCollider Synth.
Its attributes are determined by the synthdefs file.
Use a Synth object if you're writing your own
SynthDef files, otherwise use a Ugen.
"""
def __init__(self, name, group=None, **kwargs):
self.synth_name = name
self.node_id = None
self.arg_dict = {}
self.set(**kwargs)
self.add_action = 1
self.group = group
self.node_id = synth_nodes.next()
self.has_played = False
def set(self, **kwargs):
for key in kwargs:
self.arg_dict[key] = kwargs[key]
def get(self, key):
return self.arg_dict.get(key)
def set_at(self, time, **kwargs):
bundle = OSC.OSCBundle()
bundle.setTimeTag(time)
for key in kwargs:
message = OSC.OSCMessage("/n_set")
message.append(self.node_id)
message.append([key, kwargs[key]])
bundle.append(message)
print 'setting:', self.node_id
loader.client.send(bundle)
def args_as_list(self):
args_list = []
for key in self.arg_dict:
args_list.append(key)
args_list.append(self.arg_dict[key])
return args_list
def get_message(self):
message = None
if self.has_played:
if not self.arg_dict:
return None
message = OSC.OSCMessage("/n_set")
message.append(self.node_id)
for key in self.arg_dict:
message.append([key, self.arg_dict[key]])
print 'setting:', self.node_id
else:
message = OSC.OSCMessage("/s_new")
target_id = 0
if self.group:
target_id = self.group.group_id
message.append([self.synth_name, self.node_id,
self.add_action, target_id])
message.append(self.args_as_list())
self.has_played = True
self.arg_dict = {}
return message
def play_at(self, start_time):
if self.has_played:
return self.set_at(start_time)
bundle = OSC.OSCBundle()
bundle.setTimeTag(start_time)
message = OSC.OSCMessage("/s_new")
self.node_id = synth_nodes.next()
target_id = 0
if self.group:
target_id = self.group.group_id
message.append([self.synth_name, self.node_id,
self.add_action, target_id])
message.append(self.args_as_list())
bundle.append(message)
loader.client.send(bundle)
self.has_played = True
return self
def release(self):
message = OSC.OSCMessage("/n_free")
message.append([self.node_id])
loader.client.send(message)
class AutomatorPool(object):
"""
Encapsulates a collection of 'automators'.
An automator is a generator function which
yields Beats. The automator expects to be
invoked before that beat is planned,
but after any previous beats are planned.
"""
def __init__(self):
self.automators = []
self.next = {'next_time':float("inf")}
def add(self, automator):
generator = automator()
self.automators.append({
'generator':generator,
'next_time':generator.next().time
})
self.next = self.find_next()
def find_next(self):
soonest = {'next_time':float("inf")}
for automator in self.automators:
if automator['next_time'] < soonest['next_time']:
soonest = automator
return soonest
def step(self):
auto = self.next
self.automators.remove(auto)
if not auto['generator']:
return
self.next = self.find_next()
try:
next_beat = auto['generator'].next()
except StopIteration:
pass
else:
self.automators.append({
'generator':auto['generator'],
'next_time':next_beat.time
})
finally:
self.next = self.find_next()
class Sequencer(object):
"""
A Seqeuncer has a list of MusicNodes,
and it periodically calls plan() on each
of the nodes if their enabled attribute is True.
It also contains an AutomatorPool, whose automators
are notified before all of the MusicNodes for a given beat.
"""
def __init__(self, clock=None):
self.nodes = []
self.automators = AutomatorPool()
self.buffer_length = 0.1
self.sched = scheduler(time.time, time.sleep)
self.default_clock = clock or TempoClock()
self._stopped = False
def on_wake(self):
next_sleep = self.last_sleep + self.buffer_length
bottom = self.last_sleep
while self.automators.next['next_time'] < next_sleep:
span = {
'bottom': bottom,
'top': self.automators.next['next_time']
}
self.notify_nodes(span)
self.automators.step()
bottom = span['top']
if self._stopped:
print "Sequencer stopped!"
return
span = {
'bottom': bottom,
'top': next_sleep
}
self.notify_nodes(span)
self.sched.enterabs(self.last_sleep, 1, self.on_wake, ())
self.last_sleep = next_sleep
def notify_nodes(self, span):
for node in self.nodes:
if hasattr(node, "read_input"):
node.read_input()
if not hasattr(node, "plan"):
continue
if hasattr(node, 'enabled') and not node.enabled:
return
for beat in self.default_clock.beats_in(span, subdiv=node.get_subdiv()):
node.plan(beat)
def run(self):
self.last_sleep = time.time() + self.buffer_length
self.on_wake()
self.sched.run()
def stop(self):
last_beat = self.last_sleep + self.buffer_length
beat = self.default_clock.beat_at(time=last_beat)
beat.num = int(beat.num)
print 'last beat~!', beat.num, beat.time
for node in self.nodes:
node.release_all(beat)
self._stopped = True
#TODO: these don't belong in this file
current_bufnum = 5
def read_buffer(filename, channels=1):
global current_bufnum
if filename.endswith(".mp3"):
filename = decode_mp3(filename)
current_bufnum += channels
message = OSC.OSCMessage("/b_allocRead")
message.append(current_bufnum)
message.append(filename)
loader.client.send(message)
return current_bufnum
def decode_mp3(filename):
new_filename = "/tmp/" + str(random.randint(0, 100000000)) + ".wav"
command = "ffmpeg -i " + filename + ' ' + new_filename
print "Converting to WAV:", command
os.system(command)
return new_filename
sequencer = Sequencer()