-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwicked.mmckpy
526 lines (448 loc) · 17.6 KB
/
wicked.mmckpy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"""
_ _ _
__ _(_) ___| | _____ __| |
\ \ /\ / / |/ __| |/ / _ \/ _` |
Hear the drummer get... \ V V /| | (__| < __/ (_| |
\_/\_/ |_|\___|_|\_\___|\__,_|
NOTE: You can't use this with Solar Sails unless you run it
with SciPy. We are working on better WAV support that doesn't
require SciPy.
"""
from collections import OrderedDict
from itertools import cycle
from random import Random
import py
from rv.api import m, NOTE, NOTECMD, Pattern, PatternClone
# -[ Parameters ]----------------------------------------------------------------------------
MAX_RAND = 2 ** 30
SEED_RANGE = dict(range=(0, MAX_RAND))
DIGITS = [
'0123456789',
'0123456789abcdef',
'0123456789abcdefghijklmnopqrstuvwxyz',
]
SLOT_KIT_NOTES = [
['C3'], # kick
['D3', 'E3'], # snare
['C4', 'A3', 'G3'], # toms
['G4', 'c4'], # crash1
['E4', 'A4'], # crash2
['a1', 'D2'], # hihat
['B4', 'd4', 'F4'], # ride
[],
]
def set_parameters(p, P):
print('Available performers: {}'.format(', '.join(PERFORMERS)))
p.name = P.String(label='Project Name')
p.kit_mode = P.Integer(0, range=(0, 1))
p.rhythm_seed = P.Integer(0, **SEED_RANGE)
p.sample_seed = P.Integer(0, **SEED_RANGE)
p.relative_note = P.Integer(48, (0, 128))
p.bpm = P.Integer(500, range=(20, 999))
p.tpl = P.Integer(24, range=(1, 32))
p.swing = P.Integer(0, range=(0, 7))
p.accent_threshold = P.Integer(127, range=(0, 255))
p.digits = P.String(DIGITS[0], choices=DIGITS)
p.variations = P.Integer(1, range=(1, 16))
p.measures = P.String('4444,4444,4444,4444')
p.loops = P.Integer(1, range=(1, 32))
p.global_performance = P.KeyValuePairs([
('performer', PERFORMERS[0]),
])
for slot in range(8):
def setslot(name, value, slot=slot):
p['slot{}_{}'.format(slot + 1, name)] = value
setslot('name', P.String('slot{}'.format(slot + 1)))
setslot('paths', P.PathList())
setslot('seed', P.Integer(0, **SEED_RANGE))
setslot('samples', P.Integer(1, range=(1, 15)))
setslot('performance', P.KeyValuePairs(OrderedDict([
('measure_strength', '0'),
('measure_wild', '0'),
('beat_accent', '0'),
('note_chance', '0'),
('note_accent', '0'),
('note_variation', '0'),
('velocity_variation', '0'),
])))
p.slot1_name.default = 'kick'
p.slot1_performance.default.update(
measure_strength='9',
measure_wild='0109',
beat_accent='9',
note_chance='9132',
note_accent='9555',
note_variation='0555',
)
p.slot2_name.default = 'snare'
p.slot2_performance.default.update(
measure_strength='9995',
measure_wild='1159',
beat_accent='09',
note_chance='21149214',
note_accent='53339333',
note_variation='55550555',
)
p.slot3_name.default = 'toms'
p.slot3_performance.default.update(
measure_strength='1117',
measure_wild='1419',
beat_accent='5',
note_chance='864',
note_accent='522',
note_variation='64215',
)
# -[ Project builder ]----------------------------------------------------------------------------
def udc_assignments(p):
yield 'master.variation'
def var(name, slot):
return p['slot{}_{}'.format(slot + 1, name)]
for ctl in ['transpose', 'finetune', 'amp']:
for slot in range(8):
paths = var('paths', slot)
if not paths:
continue
name = var('name', slot)
yield '{}.{}'.format(name, ctl)
def build_project(p, c, project):
project.name = p.name or '{}-{}-synth'.format(p.rhythm_seed, p.sample_seed)
project.initial_bpm = p.bpm
project.initial_tpl = p.tpl
note_in = project.new_module(m.MultiSynth, ignore_notes_with_zero_velocity=True)
rrandom = Random(p.rhythm_seed)
srandom = Random(p.sample_seed)
new_seed = lambda x: (srandom.randint(0, MAX_RAND) + x) % MAX_RAND
new_random = lambda x: Random(new_seed(x))
slot_srandom = [
new_random(p['slot{}_seed'.format(x)])
for x in range(1, 9)
]
samplefinders = [
samplefinder(
p['slot{}_paths'.format(x)],
new_random(p['slot{}_seed'.format(x)]),
)
for x in range(1, 9)
]
slot_rrandom = [
new_random(p['slot{}_seed'.format(x)] + p.rhythm_seed)
for x in range(1, 9)
]
slot_notes = [[] for _ in range(8)]
slot_notegates = [[] for _ in range(8)]
slot_samplepaths = [[] for _ in range(8)]
slot_samplers = [[] for _ in range(8)]
slot_transposers = [[] for _ in range(8)]
def var(name, slot):
return p['slot{}_{}'.format(slot + 1, name)]
# Find samples; create groups.
for slot, (find_sample, samples) in enumerate(
zip(samplefinders, slot_samplepaths)):
name = var('name', slot)
sample_count = var('samples', slot)
for i in range(sample_count):
path = find_sample()
if not path:
continue
samples.append(path)
if not samples:
continue
group = c[name]
# Do this after creating slot-specific groups.
master_amp = project.new_module(m.Amplifier, name='master amp')
master_amp >> project.output
c.master.amp = (master_amp, 'volume')
# Create samplers; load samples; wire them up.
for slot, (paths, notegates, samplers, transposers) in enumerate(
zip(slot_samplepaths, slot_notegates, slot_samplers, slot_transposers)):
if not paths:
continue
name = var('name', slot)
group = c[name]
slot_amp = project.new_module(m.Amplifier, name='{} amp'.format(slot + 1))
slot_amp >> master_amp
group.amp = (slot_amp, 'volume')
notegates = slot_notegates[slot]
transposers = slot_transposers[slot]
# Accent switch
accents = project.new_module(
m.MultiSynth, name='accents', ignore_notes_with_zero_velocity=True)
no_accents = project.new_module(
m.MultiSynth,
name='no accents',
velocity=0,
vv_curve_active=True,
ignore_notes_with_zero_velocity=True,
)
no_accents.vv_curve.set_via_fn(lambda v: min(p.accent_threshold, v))
accent_gates = [accents, no_accents]
accent_switch = m.MultiCtl.macro(
project,
(accents, 'velocity'),
(no_accents, 'velocity'),
name='accent',
)
accent_switch.quantization = 2
mapping = accent_switch.mappings.values[1]
mapping.min, mapping.max = mapping.max, mapping.min
accent_switch.value = 32768
accented = project.new_module(m.MultiSynth, name='accented', ignore_notes_with_zero_velocity=True)
accent_switch >> accent_gates
note_in >> accent_gates >> accented
group.accent = (accent_switch, 'value')
for i, path in enumerate(paths):
# Wiring.
notegate = project.new_module(m.MultiSynth, name='note gate', ignore_notes_with_zero_velocity=True)
transposer = project.new_module(m.MultiSynth, name='transposer', ignore_notes_with_zero_velocity=True)
sampler = project.new_module(m.Sampler, name='{}.{} - {}'.format(slot + 1, i + 1, path.basename))
notegates.append(notegate)
transposers.append(transposer)
samplers.append(sampler)
accented >> notegate >> transposer >> sampler >> slot_amp
# Sample loading
printed(path.basename, 'Reading {}'.format(name))
load_wav_to_sampler_slot(path, sampler, 0, finetune=0, relative_note=p.relative_note)
c.samples['{}_{}_vol'.format(name, i + 1)] = (sampler, 'volume')
# Assign notes
if p.kit_mode:
for slot, (notes, notegates, kitnotes) in enumerate(zip(slot_notes, slot_notegates, SLOT_KIT_NOTES)):
for current_note, notegate in zip(kitnotes, notegates):
current_note = getattr(NOTE, current_note)
notes.append(current_note)
notegate.nv_curve.set_via_fn(lambda n: 0xff if n + 1 == current_note.value else 0x00)
else:
current_note = STARTING_NOTE
for slot, (notes, notegates) in enumerate(zip(slot_notes, slot_notegates)):
for notegate in notegates:
notes.append(current_note)
notegate.nv_curve.set_via_fn(lambda n: 0xff if n + 1 == current_note.value else 0x00)
current_note = NOTE(current_note + 1)
# Wire up transposers
for slot, transposers in enumerate(slot_transposers):
if not transposers:
continue
name = var('name', slot)
group = c[name]
transpose = m.MultiCtl.macro(project, *[(t, 'transpose') for t in transposers], name='transpose')
for mapping in transpose.mappings.values:
mapping.min, mapping.max = (128 - 32, 128 + 32)
finetune = m.MultiCtl.macro(project, *[(t, 'finetune') for t in transposers], name='finetune')
group.transpose = (transpose, 'value')
group.finetune = (finetune, 'value')
transpose.value = 0x4000
finetune.value = 0x4000
# Fill out UI to 8 controllers per slot
macro = project.new_module(m.MultiCtl, name='_')
for slot in range(8):
if not slot_samplers[slot]:
continue
name = var('name', slot)
group = c[name]
while len(group) < 8:
group['__{}__'.format(len(group) + 1)] = (macro, 'value')
# General pattern stuff.
lines = pattern_lines(p.measures)
# Swing pattern.
swing = Pattern(name='swing', tracks=1, x=0, y=-64, lines=lines)
project += swing
speeds = [p.tpl + p.swing, p.tpl - p.swing]
for line, speed in zip(range(swing.lines), cycle(speeds)):
n = swing.data[line][0]
n.effect = 0x0f
n.val_yy = speed
# Variation trigger pattern.
variation_triggers = Pattern(name='variation triggers', tracks=1, x=0, y=-32, lines=lines)
variation_transposer = project.new_module(m.MultiSynth, name='variation transposer')
project += variation_triggers
for line in range(variation_triggers.lines):
n = variation_triggers.data[line][0]
n.note = NOTECMD.C0
n.vel = 129
n.module = variation_transposer.index + 1
variation_selector = m.MultiCtl.macro(
project, (variation_transposer, 'transpose'), name='variation')
variation_selector.gain = 256 + int(256 / (p.variations + 1))
mapping = variation_selector.mappings.values[0]
mapping.min, mapping.max = 128, 128 + p.variations
c.master.variation = (variation_selector, 'value')
# Initialize variations.
variation_gates = []
variation_patterns = []
for i in range(p.variations + 1):
pattern = Pattern(name=str(i + 1), tracks=8, x=0, y=32 * i, lines=lines)
project += pattern
variation_patterns.append(pattern)
notegate = project.new_module(m.MultiSynth, name='note gate')
notegate.nv_curve.set_via_fn(lambda n: 0xff if n == i else 0x00)
vgate = project.new_module(m.MultiSynth, name='variation gate')
variation_gates.append(vgate)
v2c = project.new_module(m.Velocity2Ctl, name='velocity switch')
v2c.out_controller = vgate.controllers['velocity'].number
variation_transposer >> notegate >> v2c >> vgate >> note_in
vgate.velocity = 256 if i == 0 else 0
# Perform variations.
def gentrack(pattern, mod, slot, rrandom, notes):
def v(name):
performance = dict(p.global_performance)
performance.update(var('performance', slot))
return performance[name]
def dv(name):
return list(decoded(v(name), p.digits))
performer = globals().get(v('performer'), None)
if not callable(performer):
print("{} didn't show up for work; dummer will perform instead".format(v('performer')))
performer = dummer
performance = performer(
pattern=pattern,
mod=mod,
slot=slot,
random=rrandom,
notes=notes,
p=p,
measure_strength=dv('measure_strength'),
measure_wild=dv('measure_wild'),
beat_accent=dv('beat_accent'),
note_chance=dv('note_chance'),
note_accent=dv('note_accent'),
note_variation=dv('note_variation'),
velocity_variation=dv('measure_strength'),
)
for line, (note, vel) in zip(range(pattern.lines), performance):
if note:
n = pattern.data[line][slot]
n.note = note
n.module = vgate.index + 1
n.vel = 1 + vel
for pattern, vgate in zip(variation_patterns, variation_gates):
for slot, (rrandom, notes) in enumerate(zip(slot_rrandom, slot_notes)):
if not notes:
continue
gentrack(
pattern=pattern,
mod=vgate,
slot=slot,
rrandom=rrandom,
notes=notes,
)
# Loop patterns.
for i, pattern in enumerate(project.patterns[:]):
if isinstance(pattern, Pattern):
for loop in range(1, p.loops):
project += PatternClone(
source=i,
x=pattern.x + (pattern.lines * loop),
y=pattern.y,
)
# Make it pretty!
project.layout()
# -[ Performers ]----------------------------------------------------------------------------
PERFORMERS = []
def performer(fn):
PERFORMERS.append(fn.__name__)
return fn
@performer
def phrasier(notes, random, p, measure_strength, measure_wild, beat_accent, note_chance, note_accent, note_variation, velocity_variation, **kwargs):
# TODO: wild
basenote = random.choice(notes)
for measure, beat, line, measureline, beatline in measure_counters(p.measures, p.digits):
nc = cyclevalue(note_chance, measureline)
ms = cyclevalue(measure_strength, measure)
if nc == 0 or ms == 0 or random.random() > nc * ms:
yield (None, None)
continue
ba = cyclevalue(beat_accent, beatline) * 0.25
na = cyclevalue(note_accent, measureline) * 0.25
vv = cyclevalue(velocity_variation, measureline) - 0.5
vel = int((0.5 + ba + na + vv) * 128)
vel = min(128, max(0, vel))
nv = cyclevalue(note_variation, measureline)
if random.random() <= nv:
note = random.choice(notes)
else:
note = basenote
yield (note, vel)
@performer
def dummer(notes, random, p, **kwargs):
for _ in range(pattern_lines(p.measures)):
if random.random() > 0.5:
yield (random.choice(notes), random.randint(0, 128))
else:
yield (None, None)
@performer
def silence(p, **kwargs):
return [(None, None)] * pattern_lines(p.measures)
# -[ Utils ]----------------------------------------------------------------------------
FILE_URL_PREFIX = 'file://'
STARTING_NOTE = NOTE.C4
def printed(value, label=None, mute=False):
if not mute:
if label:
print('{}: {!r}'.format(label, value))
else:
print(repr(value))
return value
def samplefinder(paths, random):
all_paths = set()
for path in paths:
if path.startswith(FILE_URL_PREFIX):
path = path[len(FILE_URL_PREFIX):]
try:
all_paths.update(set(py.path.local(path).visit('*.wav')))
except py.error.ENOENT:
print('WARNING: path not found: {}'.format(path))
pass
all_paths = sorted(list(all_paths))
def fn():
choice = random.choice(all_paths) if all_paths else None
return choice
return fn
def pattern_lines(measures):
length = 0
for c in measures:
if c in '123456789':
length += int(c)
return length
def measure_counters(measures, digits):
# yields 3-tuple of indices: (measure, beat, line, measureline, beatline)
line = 0
for measure, beats in enumerate(measures.lower().split(',')):
beats = beats.strip()
measureline = 0
for beat, lines in enumerate(int(d) for d in beats):
for beatline in range(lines):
yield (measure, beat, line, measureline, beatline)
line += 1
measureline += 1
def decoded(values, digits):
for c in values.lower():
value = digits.find(c)
if value != -1:
yield value / (len(digits) - 1)
def cyclevalue(values, line):
return values[line % len(values)]
# -[ WAV loading ]----------------------------------------------------------------------
from scipy.io import wavfile
def load_wav_to_sampler_slot(path, sampler, slot, **kwargs):
sample = sampler.Sample()
freq, snd = wavfile.read(str(path))
if snd.dtype.name == 'int16':
sample.format = sampler.Format.int16
elif snd.dtype.name == 'float32':
sample.format = sampler.Format.float32
else:
raise Exception('Not supported')
if len(snd.shape) == 1:
size, = snd.shape
channels = 1
else:
size, channels = snd.shape
sample.rate = freq
sample.channels = {
1: m.Sampler.Channels.mono,
2: m.Sampler.Channels.stereo,
}[channels]
sample.data = snd.data.tobytes()
for key, value in kwargs.items():
setattr(sample, key, value)
sampler.samples[slot] = sample
return sample