-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdooper.py
437 lines (345 loc) · 14.1 KB
/
dooper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""
A Python library for interfacing with SooperLooper.
Tracks full state and provides interface to all loop commands. Almost a complete client, just missing changing loop count, saving sessions, and modifying midi bindings.
"""
import liblo
from threading import Event, Lock
# Quantize and relative sync are actually global looper parameters, but SL handles them via the loop interface. We handle them separately as special cases so they are commented below but left for reference.
loop_parameters_settable = (
'rec_thresh', # expected range is 0 -> 1
'feedback', # range 0 -> 1
'dry', # range 0 -> 1
'wet', # range 0 -> 1
'input_gain', # range 0 -> 1
'rate', # range 0.25 -> 4.0
'scratch_pos', # 0 -> 1
'delay_trigger', # any changes
# 'quantize', # 0 = off, 1 = cycle, 2 = 8th, 3 = loop
'round', # 0 = off, not 0 = on
'redo_is_tap', # 0 = off, not 0 = on
'sync', # 0 = off, not 0 = on
'playback_sync', # 0 = off, not 0 = on
'use_rate', # 0 = off, not 0 = on
'fade_samples', # 0 -> ...
'use_feedback_play', # 0 = off, not 0 = on
'use_common_ins', # 0 = off, not 0 = on
'use_common_outs', # 0 = off, not 0 = on
# 'relative_sync', # 0 = off, not 0 = on
'use_safety_feedback', # 0 = off, not 0 = on
'pan_1', # range 0 -> 1
'pan_2', # range 0 -> 1
'pan_3', # range 0 -> 1
'pan_4', # range 0 -> 1
'input_latency', # range 0 -> ...
'output_latency', # range 0 -> ...
'trigger_latency', # range 0 -> ...
'autoset_latency', # 0 = off, not 0 = on
'mute_quantized', # 0 = off, not 0 = on
'overdub_quantized', # 0 == off, not 0 = on
)
loop_parameters_gettable = (
'state', # codes mapped below
'next_state', # same as state
'loop_len', # in seconds
# 'loop_pos', # in seconds
'cycle_len', # in seconds
'free_time', # in seconds
'total_time', # in seconds
'rate_output',
'in_peak_meter', # absolute float sample value 0.0 -> 1.0 (or higher)
'out_peak_meter', # absolute float sample value 0.0 -> 1.0 (or higher)
'is_soloed', # 1 if soloed, 0 if not
)
loop_parameters = loop_parameters_gettable + loop_parameters_settable
loop_commands = (
'record',
'overdub',
'multiply',
'insert',
'replace',
'reverse',
'mute',
'undo',
'redo',
'oneshot',
'trigger',
'substitute',
'undo_all',
'redo_all',
'mute_on',
'mute_off',
'solo',
'pause',
'solo_next',
'solo_prev',
'record_solo',
'record_solo_next',
'record_solo_prev',
'set_sync_pos',
'reset_sync_pos'
)
looper_parameters = (
'tempo',
'eighth_per_cycle',
'dry', # range 0 -> 1 affects common input passthru
'wet', # range 0 -> 1 affects common output level
'input_gain', # range 0 -> 1 affects common input gain
'sync_source', # -3 = internal, -2 = midi, -1 = jack, 0 = none, # > 0 = loop number (1 indexed)
'tap_tempo', # any changes
'save_loop', # any change triggers quick save, be careful
'auto_disable_latency', # when 1, disables compensation when monitoring main inputs
'select_next_loop', # any changes
'select_prev_loop', # any changes
'select_all_loops', # any changes
'selected_loop_num' # -1 = all, 0->N selects loop instances (first loop is 0, etc)
)
# Map sl's integer codes to loop states
state_codes = {-1: 'unknown',
0: 'Off',
1: 'WaitStart', # Waiting to start recording
2: 'Recording',
3: 'WaitStop', # Waiting to stop recording
4: 'Playing', # Or maybe waiting to mute
5: 'Overdubbing',
6: 'Multiplying',
7: 'Inserting',
8: 'Replacing',
9: 'Delay',
10: 'Muted', # Or maybe waiting to play
11: 'Scratching',
12: 'OneShot',
13: 'Substitute',
14: 'Paused',
20: 'Off and muted'} #20 isn't documented...
class LooperThread:
"""
Handles I/O with SooperLooper via OSC. Organizes loops.
Uses a threaded liblo server to register for updates and automatically track looper and loop state.
See documentation here: http://essej.net/sooperlooper/doc_osc.html
"""
def __init__(self, port=9950, sl_port=9951, verbose=False):
self.port = port
self.sl_port = sl_port
self.verbose = verbose
self.server = liblo.ServerThread(self.port) #Define liblo server for replies
self.ping_flag = Event()
self.loop_count = 0
self.loops = []
self.loop_callbacks = []
self.looper_callbacks = []
self.ping_callbacks = []
#self.start_server()
def __repr__(self):
return 'LooperThread(port={}, sl_port={}, verbose={})'.format(self.port, self.sl_port, self.verbose)
def __setattr__(self, name, val):
if name in ['sync_source', 'quantize', 'selected_loop_num']:
super().__setattr__(name, val)
elif name in looper_parameters:
self.set(name, val)
else:
self.__dict__[name] = val
def start_server(self):
self.server.add_method('/sl/ping', None, self.ping_responder)
self.server.add_method('/sl/loop', None, self.loop_responder)
self.server.add_method('/sl/looper', None, self.looper_responder)
self.server.start()
self.initialize()
self.register_updates()
def initialize(self):
if not self.ping():
print("No ping reply from SooperLooper")
return
for param in looper_parameters:
self.send_osc('/get', param, self.server.url, '/sl/looper')
#Quantize and relative sync are global, but control relies on a loop
self.send_osc('/sl/0/get', 'quantize', self.server.url, '/sl/looper')
self.send_osc('/sl/0/get', 'relative_sync', self.server.url, '/sl/looper')
if self.loop_count:
for i in range(self.loop_count):
self.loops.append(Loop(self, i))
for param in loop_parameters:
self.loops[i].get(param)
else:
print("Loop count is zero")
def send_osc(self, path, *args):
if self.verbose:
print('Sending OSC message: {} {}'.format(path, args))
liblo.send(self.sl_port, liblo.Message(path, *args))
def ping_responder(self, path, args):
if self.verbose:
print('Received OSC message: {} {}'.format(path, args))
self.loop_count = args[2]
self.ping_flag.set()
for f in self.ping_callbacks:
f(args)
def loop_responder(self, path, args):
""" Listens for replies from SL about loops, then updates loop object accordingly."""
if self.verbose:
print('Received OSC message: {} {}'.format(path, args))
loop = self.loops[args[0]]
control, value = args[1:]
loop.__dict__[control] = value
for f in self.loop_callbacks:
f(args)
def looper_responder(self, path, args):
""" Listens for replies from SL about looper global state"""
if self.verbose:
print('Received OSC message: {} {}'.format(path, args))
self.__dict__[args[1]] = args[2]
for f in self.looper_callbacks:
f(args)
def send(self, path1, path2, *args):
message = '/sl/' + str(path1)
if path2:
message += '/' + str(path2)
self.send_osc(message, *args)
def set(self, control, value):
self.send_osc('/set', control, value)
def register_updates(self):
""" Ask SL to updates us on changes to global and loop states. While the documentation indicates that register_update should trigger whenever any client updates an input control, in practice the auto variety seems necessary to catch changes not initiated from SL's frontend. Auto is always necessary for loop states. We pass a polling interval of 100ms, but this is actually fixed on the backend. Updates only fire if the value has been changed. """
for param in looper_parameters:
self.send_osc('/register_auto_update', param, 100, self.server.url, '/sl/looper')
self.send_osc('/sl/0/register_auto_update', 'quantize', 100, self.server.url, '/sl/looper')
for loop in self.loops:
for param in loop_parameters:
self.send_osc('/sl/' + str(loop.number) + '/register_auto_update', param, 100, self.server.url, '/sl/loop')
def ping(self, timeout=1):
self.ping_flag.clear()
self.send_osc('/ping', self.server.url, '/sl/ping')
return self.ping_flag.wait(timeout)
def select_loop(self, n):
self.selected_loop_num = n
@property
def quantize(self):
return ('off', 'cycle', '8th', 'loop')[int(self.__dict__['quantize'])]
@quantize.setter
def quantize(self, val):
q = ('off', 'cycle', '8th', 'loop').index(val)
self.send_osc('/sl/0/set', 'quantize', q)
@property
def selected_loop_num(self):
n = self.__dict__['selected_loop_num']
if n == -1:
return 'all'
else:
return int(n)
@selected_loop_num.setter
def selected_loop_num(self, val):
if val == 'all':
n = -1
else:
n = val
self.set('selected_loop_num', n)
@property
def selected_loop(self):
n = self.selected_loop_num
if isinstance(n, int):
return self.loops[n]
@property
def sync_source(self):
s = self.__dict__['sync_source']
if s > 0:
return int(s)
else:
return ('none', 'internal', 'midi', 'jack')[i]
@sync_source.setter
def sync_source(self, val):
if isinstance(val, str):
s = - ('none', 'jack', 'midi', 'internal').index(val)
else:
s = val
self.set('sync_source', s)
class Loop:
def __init__(self, looper, number, state='Off'):
self.looper = looper
self.number = number
#self.state = state
def __repr__(self):
#return 'Loop(looper={}, number={}, state={})'.format(
# self.looper.sl_port, self.number, self.state)
return 'Loop({}, {})'.format(self.number, self.state)
def __str__(self):
return 'Loop({}, {})'.format(self.number, self.state)
def __getattr__(self, name):
if name in loop_commands:
return lambda: self.hit(name)
# elif name in loop_parameters:
def __setattr__(self, name, val):
if name in loop_parameters_settable:
self.send('set', name, val)
else:
self.__dict__[name] = val
def set(self, control, value):
self.looper.send('set', control, value)
def get(self, control):
self.send('get', control, self.looper.server.url, '/sl/loop')
def send(self, action, *args):
self.looper.send(self.number, action, *args)
def hit(self, command):
self.send('hit', command)
@property
def state(self):
return state_codes[int(self.__dict__['state'])]
@property
def next_state(self):
return state_codes[int(self.__dict__['next_state'])]
class Looper:
"""
The original, unthreaded looper class. It's missing features that have been added to the threaded version and will likely be merged to a single class with both options at some point.
"""
def __init__(self, port=9950, sl_port=9951, verbose=False):
self.port = port
self.sl_port = sl_port
self.verbose = verbose
def __repr__(self):
return 'Looper(port={}, sl_port={}, verbose={})'.format(self.port, self.sl_port, self.verbose)
def start_server(self):
self.server = liblo.Server(self.port) #Define liblo server for replies
self.server.add_method('/sl/ping', None, self.ping_responder)
self.server.add_method('/sl/loop', None, self.loop_responder)
self.init_loops()
def init_loops(self):
self.loop_count = 0
self.loops = []
if self.ping() and self.loop_count:
for i in range(self.loop_count):
self.loops.append(Loop(self, i))
self.loops[i].get('state')
self.receive()
else:
print("Couldn't initialize loops. Either ping to SooperLooper failed, or loop count is zero.")
def send_osc(self, path, *args):
if self.verbose:
print('Sending OSC message: {} {}'.format(path, args))
liblo.send(self.sl_port, liblo.Message(path, *args))
def ping_responder(self, path, args):
self.loop_count = args[2]
if self.verbose:
print('Received OSC message: {} {}'.format(path, args))
def loop_responder(self, path, args):
""" Listens for replies from SL about loops (probably set all loop replies to come to one path, like '/sl/loop'), then update loop object accordingly."""
loop = self.loops[args[0]]
control, value = args[1:]
if control == 'state':
loop.state = state_codes[value]
else:
pass
if self.verbose:
print('Received OSC message: {} {}'.format(path, args))
def send(self, path1, path2, *args):
message = '/sl/' + str(path1)
if path2:
message += '/' + str(path2)
self.send_osc(message, *args)
def receive(self, timeout=1):
#Timeout of 0 is too small to reliably receive replies, and there's no way to recover from blocking in the main thread, at least in this case
return self.server.recv(timeout)
def register_updates(self):
# Int is update interval, currently ignored and set to 100ms
# We have to auto update to get state info but it only sends with change
# Don't forget to receive messages
for n in len(self.loops):
self.send_osc('/sl/' + str(loop.number) + '/register_auto_update', 'state', 100, self.server.url, '/sl/loop')
def ping(self, timeout=1):
self.send_osc('/ping', self.server.url, '/sl/ping')
return self.receive(timeout)