forked from hansehv/SamplerBox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamplerbox.py
More file actions
1727 lines (1644 loc) · 87.5 KB
/
Copy pathsamplerbox.py
File metadata and controls
1727 lines (1644 loc) · 87.5 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
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# samplerbox.py: Main file
#
# SamplerBox extended by HansEhv (https://github.com/hansehv)
# see docs at https://homspace.nl/samplerbox
# changelog in /boot/samplerbox/changelist.txt
#
# Original SamplerBox :
# author: Joseph Ernest (twitter: @JosephErnest, mail: contact@samplerbox.org)
# url: http://www.samplerbox.org/
# license: Creative Commons ShareAlike 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)
#
##########################################################################
## IMPORT MODULES (generic, more can be loaded depending on local config)
## WARNING: GPIO modules in this build use mode=BCM. Do not mix modes!
## Miscellaneous generic procs (too small to split off), published via gv
##########################################################################
import sys
sys.path.append('./modules')
import gv
######## Have some debugging help first ########
print ( "=" *42 )
print ( " https://github.com/hansehv/SamplerBox" )
try:
with open('/boot/z_distbox.txt') as f:
print ( f.read().strip() )
gv.RUN_FROM_IMAGE = True
except:
print ( " Not running from distribution image" )
gv.RUN_FROM_IMAGE = False
print ( "no track of local changes, that's for you!" )
print ( "=" *42 )
######## continue importing ########
import wave,rtmidi2
from chunk import Chunk
import time,psutil,numpy,struct
import sys,os,re,operator,threading
from numpy import random
import ConfigParser
import samplerbox_audio # audio-module (cython)
import gp,getcsv
gv.rootprefix='/home/pi/samplerbox'
#gv.rootprefix='/home/pi/samplerbox/root/SamplerBox'
if not os.path.isdir(gv.rootprefix):
gv.rootprefix=""
######## Define local general functions ########
usleep = lambda x: time.sleep(x/1000000.0)
msleep = lambda x: time.sleep(x/1000.0)
def getindex(key, table, onecol=False, casesens=True):
for i in range(len(table)):
if onecol:
if casesens:
if key==table[i]: return i
else:
if key.lower()==table[i].lower(): return i
else:
if casesens:
if key==table[i][0]:return i
else:
if key.lower()==table[i][0].lower: return i
return -100000
def parseBoolean(val):
if val:
try:
val+=0 # is it an integer (~=boolean) ?
except: # text is True unless starting with: Of(f), Y(es), N(one), T(rue), F(alse)
if str(val)[0:2].title()=="Of" or str(val)[0].upper()=="N" or str(val)[0].upper()=="F":
return False
return val
notenames=["C","Cs","C#","Dk","D","Ds","D#","Ek","E","Es","F","Fs","F#","Gk","G","Gs","G#","Ak","A","As","A#","Bk","B","Bs"]
def notename2midinote(notename,fractions):
notename=notename.title()
if notename=="Ctrl": midinote=-2
elif notename=="None": midinote=-1
else:
if notename[:2]=="Ck": # normalize synonyms
notename="Bs%d" %(int(notename[-1])-1) # Octave number switches between B and C
elif notename[:2]=="Fk":
notename="Es%s"%notename[-1]
try:
x=notenames.index(format(notename[:len(notename)-1]))
if fractions==1: # we have undivided semi-tones = 12-tone scale
x,y=divmod(x,2) # so our range is half of what's tested
if y!=0: # and we can't process any found q's.
print "Ignored quartertone %s as we are in 12-tone mode" %notename
midinote=-1
# next statements places note C4 on 60
else: # 12 note logic
midinote = x + (int(notename[-1])+1) * 12
else: # 24 note logic
midinote = x + (int(notename[-1])-2) * 24 +12
except:
print "Ignored unrecognized notename '%s'" %notename
midinote=-128
return midinote
def midinote2notename(midinote,fractions):
notename=None
octave=None
note=None
if midinote==-2: notename="Ctrl"
elif midinote==-1: notename="None"
else:
if midinote<gv.stop127 and midinote>(127-gv.stop127):
if fractions==1:
octave,note=divmod(midinote,12)
octave-=1
note*=2
else:
octave,note=divmod(midinote+36,24)
notename="%s%d" %(notenames[note],octave)
else: notename="%d" %(midinote)
return notename
def setChord(x,*z):
y=getindex(x,gv.chordname,True)
if y>-1: # ignore if undefined
gv.currscale=0 # playing chords excludes scales
gv.currchord=y
display("")
def setScale(x,*z):
y=getindex(x,gv.scalename,True)
if y>-1: # ignore if undefined
gv.currchord=0 # playing chords excludes scales
gv.currscale=y
display("")
def setVoice(x,iv=0,*z):
if iv==0: # we got the index of the voice table
xvoice=int(x)
else: # we got the voicenumber
xvoice=getindex(int(x),gv.voicelist)
if xvoice <0: # no option :-(
print "Undefined voice", x
else:
voice=gv.voicelist[xvoice][0]
if voice!=gv.currvoice: # also ignore if active
gv.currvoice=voice
gv.sample_mode=gv.voicelist[xvoice][2]
if iv>-1: # -1 means map or multitimbral voice change: mappings should not be changed by voice def!
setNotemap(gv.voicelist[xvoice][3])
gv.CCmap = list(gv.CCmapBox) # construct this voice's CC setup
for i in xrange(len(gv.CCmapSet)):
found=False
if gv.CCmapSet[i][3]==0 or gv.CCmapSet[i][3]==voice:# voice applies
for j in xrange(len(gv.CCmap)): # so check if button is known
if gv.CCmapSet[i][0]==gv.CCmap[j][0]:
found=True
if (gv.CCmapSet[i][3]>=gv.CCmap[j][3]): # voice specific takes precedence
gv.CCmap[j]=gv.CCmapSet[i] # replace entry
continue
if not found:
gv.CCmap.append(gv.CCmapSet[i]) # else add entry
display("")
gv.menu_CCdef()
def setMTvoice(mididev,messagechannel,voice):
x=voice
voicemap=""
if gv.USE_SMFPLAYER: # smf files may have specific mapping
if smfplayer.issending(mididev):
voicemap=gv.smfseqs[gv.currsmf][4].lower()
else: # fallback to device mapping
voicemap=mididev.lower()
newvoice=voice #define the var
xvoice=-1 #define the var
fallback=True
for v in gv.voicemap:
if v[0]=="0" or v[0].lower()==voicemap.lower(): # because of sort generic precedes the names/details
if v[1]==0 or v[1]==messagechannel:
if v[2]==0 or v[2]==voice:
newvoice=v[3]
if v[0]!="0" or v[1]!=0 or v[2]!=0:
fallback=False
if fallback and getindex(voice,gv.voicelist)>-1:
newvoice=voice # the requested voice is in the sample set, so we don't need the full fallback (it can be a "straight" GM map)
else:
print "Use voice %d for channel %d, programchange %d" %(newvoice,messagechannel,voice)
voice=newvoice
xvoice=getindex(voice,gv.voicelist)
if xvoice <0: # still no succes, out of options :-(
voice=0
if voice==0: # pick first available
for m in gv.voicelist:
if m[0]>0:
print "Voice %d not in MT channelmap and samples, fall back to %d" %(voice,m[0])
voice=m[0]
break
return voice
def setNotemap(x, *z):
try:
y=x-1
except:
y=getindex(x,gv.notemaps,True)
if y>-1:
if gv.notemaps[y]!=gv.currnotemap:
gv.currnotemap=gv.notemaps[y]
gv.notemapping=[]
for notemap in gv.notemap: # do we have note mapping ?
if notemap[0]==gv.currnotemap:
gv.notemapping.append([notemap[2],notemap[1],notemap[3],notemap[4],notemap[5],notemap[6]])
else:
gv.currnotemap=""
gv.notemapping=[]
display("")
gv.getindex=getindex # and announce the procs to modules
gv.parseBoolean=parseBoolean
gv.notename2midinote=notename2midinote
gv.midinote2notename=midinote2notename
gv.setVoice=setVoice
gv.setNotemap=setNotemap
gv.setMC(gv.CHORDS,setChord)
gv.setMC(gv.SCALES,setScale)
gv.setMC(gv.VOICES,setVoice)
gv.setMC(gv.NOTEMAPS,setNotemap)
######## LITERALS used in the main module only ########
PLAYLIVE = "Keyb" # reacts on "keyboard" interaction
PLAYBACK = "Once" # ignores loop markers ("just play the sample with option to stop")
PLAYBACK2X = "Onc2" # ignores loop markers with note-off by same note
PLAYLOOP = "Loop" # recognize loop markers, note-off by 127-note
PLAYLOOP2X = "Loo2" # recognize loop markers, note-off by same note
BACKTRACK = "Back" # recognize loop markers, loop-off by same note or controller
VELSAMPLE = "Sample" # velocity equals sampled value, requires multiple samples to get differentation
VELACCURATE = "Accurate" # velocity as played, allows for multiple (normalized!) samples for timbre
VELOSTEPS = [127,64,32,16,8,4,2,1] # accepted numer of velocity layers
gv.SAMPLES_INBOX = gv.rootprefix+"/samples/" # Builtin directory containing the sample-sets.
gv.SAMPLES_ONUSB = gv.rootprefix+"/media/" # USB-Mount directory containing the sample-sets.
CONFIG_LOC = gv.rootprefix+"/boot/samplerbox/"
CHORDS_DEF = "chords.csv"
SCALES_DEF = "scales.csv"
CTRLCCS_DEF = "controllerCCs.csv"
KEYNAMES_DEF = "keynotes.csv"
MENU_DEF = "menu.csv"
########## Read LOCAL CONFIG (==> /boot/samplerbox/configuration.txt) for generic use,
# reading LOCAL CONFIG can be done elsewhere as well if it's one-time or local/optional.
gv.cp=ConfigParser.ConfigParser()
gv.cp.read(CONFIG_LOC + "configuration.txt")
USE_HTTP_GUI = gv.cp.getboolean(gv.cfg,"USE_HTTP_GUI".lower())
gv.USE_SMFPLAYER=gv.cp.getboolean(gv.cfg,"USE_SMFPLAYER".lower())
x=gv.cp.get(gv.cfg,"MULTI_TIMBRALS".lower()).split(',')
gv.MULTI_TIMBRALS={}
for i in xrange(len(x)):
gv.MULTI_TIMBRALS[x[i].strip()]=[0]*16 # init program=voice per channel#
gv.MIDI_CHANNEL = gv.cp.getint(gv.cfg,"MIDI_CHANNEL".lower())
DRUMPAD_CHANNEL = gv.cp.getint(gv.cfg,"DRUMPAD_CHANNEL".lower())
gv.NOTES_CC = gv.cp.getint(gv.cfg,"NOTES_CC".lower())
gv.PRESET = gv.cp.getint(gv.cfg,"PRESET".lower())
gv.PRESETBASE = gv.cp.getint(gv.cfg,"PRESETBASE".lower())
MAX_MEMLOAD = gv.cp.getint(gv.cfg,"MAX_MEMLOAD".lower())
BOXSAMPLE_MODE = gv.cp.get(gv.cfg,"BOXSAMPLE_MODE".lower())
BOXVELMODE = gv.cp.get(gv.cfg,"BOXVELOCITY_MODE".lower())
BOXVELOLEVS = gv.cp.getint(gv.cfg,"BOXVELOCITY_LEVELS".lower())
BOXSTOP127 = gv.cp.getint(gv.cfg,"BOXSTOP127".lower())
BOXRELEASE = gv.cp.getint(gv.cfg,"BOXRELEASE".lower())
BOXDAMP = gv.cp.getint(gv.cfg,"BOXDAMP".lower())
BOXDAMPNOISE = gv.cp.getboolean(gv.cfg,"BOXDAMPNOISE".lower())
BOXRETRIGGER = gv.cp.get(gv.cfg,"BOXRETRIGGER".lower())
BOXRELSAMPLE= gv.cp.get(gv.cfg,"BOXRELSAMPLE".lower())
BOXXFADEOUT = gv.cp.getint(gv.cfg,"BOXXFADEOUT".lower())
BOXXFADEIN = gv.cp.getint(gv.cfg,"BOXXFADEIN".lower())
BOXXFADEVOL = gv.cp.getfloat(gv.cfg,"BOXXFADEVOL".lower())
gv.volumeCC = gv.cp.getfloat(gv.cfg,"volumeCC".lower())
########## Initialize other internal globals
gv.GPIO=False
gv.samplesdir = gv.SAMPLES_INBOX
gv.stop127 = BOXSTOP127
gv.sample_mode = BOXSAMPLE_MODE
display=gv.NoProc # set display to dummy
########## read CONFIGURABLE TABLES from config dir
# Definition of notes, chords and scales
getcsv.readchords(CONFIG_LOC + CHORDS_DEF)
getcsv.readscales(CONFIG_LOC + SCALES_DEF)
# Midi controllers and keyboard definition
getcsv.readcontrollerCCs(CONFIG_LOC + CTRLCCS_DEF)
getcsv.readkeynames(CONFIG_LOC + KEYNAMES_DEF)
gv.CCmapBox = getcsv.readCCmap(CONFIG_LOC + gv.CTRLMAP_DEF)
gv.CCmap = list(gv.CCmapBox)
getcsv.readmenu(CONFIG_LOC + MENU_DEF)
#########################################
# Setup display routine (if any..)
#########################################
import UI
try:
if gv.cp.getboolean(gv.cfg,"USE_HD44780_16x2_LCD".lower()):
gv.GPIO=True
import lcd_16x2
lcd = lcd_16x2.HD44780()
def display(msg='',msg7seg='',menu1='',menu2='',menu3='',*z):
lcd.display(msg,menu1,menu2,menu3)
display('Start Samplerbox')
elif gv.cp.getboolean(gv.cfg,"USE_I2C_LCD".lower()):
import I2C_lcd
def display(msg='',msg7seg='',menu1='',menu2='',menu3='',*z):
I2C_lcd.display(msg,menu1,menu2,menu3)
display('Start Samplerbox')
elif gv.cp.getboolean(gv.cfg,"USE_OLED".lower()):
gv.GPIO=True
import OLED
oled = OLED.oled()
def display(msg='',msg7seg='',menu1='',menu2='',menu3='',*z):
oled.display(msg,menu1,menu2,menu3)
display('Start Samplerbox')
elif gv.cp.getboolean(gv.cfg,"USE_PIMORONI_LCD".lower()):
gv.GPIO=True
import PIM_LCD
pimlcd = PIM_LCD.pim_lcd()
def display(msg='',msg7seg='',menu1='',menu2='',menu3='',*z):
pimlcd.display(msg,menu1,menu2,menu3)
display('Start Samplerbox')
elif gv.cp.getboolean(gv.cfg,"USE_I2C_7SEGMENTDISPLAY".lower()):
import I2C_7segment
def display(msg,msg7seg='',*z):
I2C_7segment.display(msg7seg)
display('','----')
elif gv.cp.getboolean(gv.cfg,"USE_I2C_7SEGMENTDISPLAY_HT16K33".lower()):
import I2C_7segment_HT16K33
def display(msg,msg7seg='',*z):
I2C_7segment_HT16K33.display(msg7seg)
display('','----')
elif gv.cp.getboolean(gv.cfg,"USE_LEDS".lower()):
gv.GPIO=True
import LEDs
def display(*z):
LEDs.signal()
LEDs.green(False)
LEDs.red(True,True)
except:
print "Error activating requested display routine"
gp.GPIOcleanup()
gv.display=display # announce resulting proc to modules
UI.display=display
##################################################################################
# Audio, Effects/Filters/SMFplayer
##################################################################################
# Sounddevice setup (detect/determine/check soundcard etc) & callback routine (the actual sound generator)
# Alsamixer setup for volume control (optional)
#
import audio
UI.USE_ALSA_MIXER=audio.USE_ALSA_MIXER
# Arpeggiator (play chordnotes sequentially, ie open chords)
# Process replaces the note-on/off logic, so rather cheap
#
import arp
# Reverb, Moogladder, Wah (envelope, lfo, pedal), Delay (echo, flanger), Overdrive and PeakLimiter
# Based on changing the audio output which requires heavy processing
#
import Cpp
# Vibrato, tremolo, pan and rotate (poor man's single speaker leslie)
# Being input based, these effects are cheap: less than 1% CPU on PI3
#
import LFO # take notice: part of process in audio callback
# Chorus (add pitch modulated and delayed copies of notes)
# Process incorporated in the note-on logic, so rather cheap as well
#
import chorus # take notice: part of process in midi callback and ARP
# Plays standard MIDI files ("play part" of a sequencer)
# Parallel process of sending midinotes to samplerbox midi-in channels
#
if gv.USE_SMFPLAYER:
import smfplayer
#########################################
## SLIGHT MODIFICATION OF PYTHON'S WAVE MODULE
## TO READ CUE MARKERS & LOOP MARKERS if applicable in mode
#########################################
class waveread(wave.Wave_read):
#class waveread():
def initfp(self, file):
s="%s" %file
wavname = s.split(',')[0][11:]
self._convert = None
self._soundpos = 0
self._cue = []
self._loops = []
self._ieee = False
self._file = Chunk(file, bigendian=0)
if self._file.getname() != 'RIFF':
print '%s does not start with RIFF id' % (wavname)
raise Error, '%s does not start with RIFF id' % (wavname)
if self._file.read(4) != 'WAVE':
print '%s is not a WAVE file' % (wavname)
raise Error, '%s is not a WAVE file' % (wavname)
self._fmt_chunk_read = 0
self._data_chunk = None
self._cue=0
while 1:
self._data_seek_needed = 1
try:
chunk = Chunk(self._file, bigendian=0)
except EOFError:
break
except:
if self._fmt_chunk_read and self._data_chunk:
print "Read %s with errors" % (wavname)
break # we have sufficient data so leave the error as is
else:
print "Skipped %s because of chunk.skip error" %file
raise Error, "Error in chunk.skip in %s" % (wavname)
chunkname = chunk.getname()
if chunkname == 'fmt ':
try:
self._read_fmt_chunk(chunk)
self._fmt_chunk_read = 1
except:
print "Invalid fmt chunk in %s, please check: max sample rate = 44100, max bit rate = 24" % (wavname)
break
elif chunkname == 'data':
if not self._fmt_chunk_read:
print 'data chunk before fmt chunk in %s' % (wavname)
else:
self._data_chunk = chunk
self._nframes = chunk.chunksize // self._framesize
self._data_seek_needed = 0
elif chunkname == 'cue ':
try:
numcue = struct.unpack('<i',chunk.read(4))[0]
for i in range(numcue):
id, position, datachunkid, chunkstart, blockstart, sampleoffset = struct.unpack('<ii4siii',chunk.read(24))
if (sampleoffset>self._cue): self._cue=sampleoffset # we need the last one in the sample
#self._cue.append(sampleoffset) # so we don't collect them all anymore...
except:
print "invalid cue chunk in %s" % (wavname)
elif chunkname == 'smpl':
manuf, prod, sampleperiod, midiunitynote, midipitchfraction, smptefmt, smpteoffs, numsampleloops, samplerdata = struct.unpack('<iiiiiiiii',chunk.read(36))
#for i in range(numsampleloops):
if numsampleloops > 0: # we don't need the repeat loops...
cuepointid, type, start, end, fraction, playcount = struct.unpack('<iiiiii',chunk.read(24))
self._loops.append([start,end])
try:
chunk.skip()
except:
if self._fmt_chunk_read and self._data_chunk:
print "Read %s with errors" % (wavname)
break # we have sufficient data so leave the error as is
else:
print "Skipped %s because of chunk.skip error" %file
raise Error, "Error in chunk.skip in %s" % (wavname)
if not self._fmt_chunk_read or not self._data_chunk:
print 'fmt chunk and/or data chunk missing in %s' % (wavname)
raise Error, 'fmt chunk and/or data chunk missing in %s' % (wavname)
def getmarkers(self):
return self._cue
def getloops(self):
return self._loops
#########################################
## MIXER CLASSES and general procs
#########################################
def GetStopmode(mode):
stopmode = -2
if mode==PLAYLIVE:
stopmode = 128 # stop on note-off = release key
elif mode==PLAYBACK:
stopmode = -1 # don't stop, play sample at full length (unless restarted)
elif mode==PLAYLOOP:
stopmode = 127 # stop on 127-key
elif mode==PLAYBACK2X or mode==PLAYLOOP2X:
stopmode = 2 # stop on 2nd keypress
elif mode==BACKTRACK:
stopmode = 3 # finish looping+outtro on 2nd keypress or defined midi controller
return stopmode
def GetLoopmode(mode):
if mode==PLAYBACK or mode==PLAYBACK2X:
loopmode = -1
else:
loopmode = 1
return loopmode
class PlayingSound:
def __init__(self, sound, voice, playednote, note, velocity, pos, end, loop, stopnote, retune, channel=0):
self.sound = sound
self.pos = pos
self.end = end
self.loop = loop
self.fadeoutpos = 0
self.isfadeout = False
if pos>0 or voice<0:
self.isfadein = True
else:
self.isfadein = False
self.voice = voice
self.playednote = playednote
self.note = note
self.retune = retune
self.velocity = velocity
self.vel = velocity*gv.globalgain
self.stopnote = stopnote
self.channel = channel
def __str__(self):
return "<PlayingSound note: '%i', velocity: '%i', pos: '%i'>" %(self.note, self.vel, self.pos)
def playingnote(self):
return self.note
def playingretune(self):
return self.retune
def playingvelocity(self):
return self.velocity
def playingstopnote(self):
return self.stopnote
def playingmutegroup(self):
return self.sound.mutegroup
def playingstopmode(self):
return self.sound.stopmode
def playingrelsample(self):
return self.sound.relsample
def playingvoice(self):
return self.sound.voice
def playingretune(self):
return self.retune
def playingchannel(self):
return self.channel
def playingdampnoise(self):
return self.sound.dampnoise
def playing2end(self):
if self.loop==-1:
self.fadeout()
else:
self.loop=-1
self.end=self.sound.eof
def fadeout(self,sustain=True):
self.isfadeout=True
if sustain==False: # Damp is fadeout with shorter (=no sustained) release,
self.isfadein=True # ...a dirty misuse of this field :-)
#def stop(self):
# try: gv.playingsounds.remove(self)
# except: pass
class Sound:
def __init__(self,filename,voice,midinote,rnds,velocity,velmode,mode,release,damp,dampnoise,retrigger,gain,mutegroup,relsample,xfadeout,xfadein,xfadevol,fractions):
read = False
for m in gv.samples:
for i in xrange(len(gv.samples[m])):
if gv.samples[m][i].fname==filename:
read=True
self.loops=gv.samples[m][i].loops
self.relmark=gv.samples[m][i].relmark
self.eof=gv.samples[m][i].eof
self.sampwidth=gv.samples[m][i].sampwidth
self.nchannels=gv.samples[m][i].nchannels
self.data=gv.samples[m][i].data
if not read:
wf = waveread(filename)
self.loops = wf.getloops()
self.relmark = wf.getmarkers()
self.eof = wf.getnframes()
self.sampwidth = wf.getsampwidth()
self.nchannels = wf.getnchannels()
self.data = self.frames2array(wf.readframes(self.eof), self.sampwidth, self.nchannels)
wf.close()
self.fname = filename
self.voice = voice
self.rnds = rnds
self.midinote = midinote
self.velocity = velocity
self.velsample = True if velmode==VELSAMPLE else False
self.stopmode = GetStopmode(mode)
self.release = release
self.damp = damp
self.dampnoise = dampnoise
self.retrigger = retrigger
self.gain = gain
self.mutegroup = mutegroup
self.relsample = relsample
self.xfadein = xfadein
self.xfadeout = xfadeout
self.xfadevol = xfadevol
self.fractions = fractions
self.loop = GetLoopmode(mode) # if no loop requested it's useless to check the wav's capability
if voice<0:
self.loop=-1 # release samples (belong to relsample="S") don't loop
else:
self.loop = GetLoopmode(mode) # if no loop requested it's useless to check the wav's capability
if self.loop > 0 and self.loops:
self.loop = self.loops[0][0] # Yes! the wav can loop
endloop = self.loops[0][1]
self.nframes = endloop + 2
if self.relmark < endloop:
self.relmark = self.nframes # a potential release marker before loop-end cannot be right
if relsample == "E": # if embedded sample was configured, notify this is impossible
print "Release of %s set to normal as release marker was not present or invalid" %(filename)
else:
if relsample == "E": # we have found valid release marker with embedded release processing requested
self.release=damp if dampnoise else xfadeout # so we can confirm and setup this to operation !!
else:
self.loop = -1
if relsample == "E": # a release marker without loop is unpredictable, so forget it
print "Release of %s set to normal as embedded samples require loop" %(filename)
if self.loop == -1:
self.relmark = self.eof # no extra release processing
self.nframes = self.eof # and use full length (with default samplerbox release processing)
def play(self, playednote, note, velocity, startparm, retune, channel=0):
if self.velsample: velocity=127
if startparm < 0: # playing of sampled release is requested
loop = -1 # a release sample does not loop
end = self.eof # and it ends on sample end
stopnote = 128 # don't react on any artificial note-off's anymore
velocity = velocity*self.xfadevol # apply the defined volume correction
if startparm==-1: # the release sample is embedded
pos = self.relmark # so it starts at embed start = the marker
if startparm==-2: # the release sample is separate
pos=0 # starting at its beginning
else:
pos = startparm # normally 0, chorus needs small displacement
end = self.nframes # play till end of loop/file as
loop = self.loop # we loop if possible by the sample
if arp.active or channel>0: # arpeggiator and sequencer are keyboard robots
stopnote=128 # ..so force keyboardmode
else:
stopnote=self.stopmode # use stopmode to determine possible stopnote
if stopnote==2 or stopnote==3:
stopnote = playednote # let autochordnotes be turned off by their trigger only
elif stopnote==127:
stopnote = 127-note
if self.mutegroup > 0 and len(gv.playingsounds) > 0: #mute all sounds with same mutegroup of triggering/played key
for ps in gv.playingsounds:
if self.mutegroup==ps.playingmutegroup() and playednote!=ps.playednote: # don't mute notes played by ourself (like chords & chorus)
ps.fadeout(False) # fadeout the mutegroup sound(s) and cleanup admin where possible
try: gv.playingnotes[ps.playednote]=[]
except: pass
if ps.playednote>=gv.BTNOTES and ps.playednote<gv.MTCHNOTES:
gv.playingbacktracks-=1
try:
gv.triggernotes[ps.note]=128
gv.playingnotes[ps.note]=[]
for triggerednote in xrange(128): # also mute chordnotes triggered by this muted note
if gv.triggernotes[triggerednote] == ps.note: # did we make this one play ?
if triggerednote in gv.playingnotes:
for m in gv.playingnotes[triggerednote]:
m.fadeout()
gv.playingnotes[triggerednote] = []
gv.triggernotes[triggerednote] = 128 # housekeeping
except: pass
snd = PlayingSound(self, self.voice, playednote, note, velocity, pos, end, loop, stopnote, retune, channel)
gv.playingsounds.append(snd)
return snd
def frames2array(self, data, sampwidth, numchan):
if sampwidth == 2:
npdata = numpy.fromstring(data, dtype = numpy.int16)
elif sampwidth == 3: # convert 24bit to 16bit
npdata = samplerbox_audio.binary24_to_int16(data, len(data)/3)
if numchan == 1: # make a left and right track from a mone sample
npdata = numpy.repeat(npdata, 2)
return npdata
#########################################
## MIDI
## - general routines
## - CALLBACK
#########################################
def ControlChange(CCnum, CCval):
mc=False
for m in gv.CCmap: # look for mapped controllers
j=m[0]
if (gv.controllerCCs[j][1]==CCnum
and (gv.controllerCCs[j][2]==-1 or gv.controllerCCs[j][2]==CCval or gv.MC[m[1]][1]==3)):
if m[2]!=None: CCval=m[2]
#print "Recognized %d:%d<=>%s related to %s" %(CCnum, CCval, gv.controllerCCs[j][0], gv.MC[m[1]][0])
gv.MC[m[1]][2](CCval,gv.MC[m[1]][0])
mc=True
break
if not mc and (CCnum==120 or CCnum==123): # "All sounds off" or "all notes off"
AllNotesOff()
def AllNotesOff(scope=-1,*z):
# scope: see EffectsOff below
# stop the robots first
if gv.USE_SMFPLAYER:
smfplayer.loopit=False
smfplayer.stopit=True
if scope>-1: scope=-1
arp.power(False)
gv.playingbacktracks = 0
# empty all queues
gv.playingsounds = []
gv.playingnotes = {}
gv.sustainplayingnotes = []
gv.triggernotes = [128]*128 # fill with unplayable note
# turn off effects & reset display
EffectsOff(scope)
display("")
def EffectsOff(scope=-1,*z):
# scope:
# -1 = switch off effects without affecting parameters
# -2 = reset effects parameters to system default
# -3 = reset effects parameters to set default
# -4 = reset effects parameters to voice default
# - other values controlled by the subroutines, usually fallback to -1: just turn off
Cpp.ResetAll(scope)
LFO.reset(scope)
chorus.reset(scope)
#AutoChordOff()
def ProgramUp(CCval,*z):
x=gv.getindex(gv.PRESET,gv.presetlist)+1
if x>=len(gv.presetlist): x=0
gv.PRESET=gv.presetlist[x][0]
gv.LoadSamples()
def ProgramDown(CCval,*z):
x=gv.getindex(gv.PRESET,gv.presetlist)-1
if x<0: x=len(gv.presetlist)-1
gv.PRESET=gv.presetlist[x][0]
gv.LoadSamples()
def MidiVolume(CCval,*z):
gv.volumeCC = CCval / 127.0
def AutoChordOff(x=0,*z):
gv.currchord = 0
gv.currscale = 0
display("")
def PitchWheel(LSB,MSB=0,*z): # This allows for single and double precision.
try: MSB+=0 # If mapped to a double precision pitch wheel, it should work.
except: # But the use/result of double precision controllers does not
MSB=LSB # justify the complexity it will introduce in the mapping.
LSB=0 # So I ignore them here. If you want to try, plse share with me.
gv.PITCHBEND=(((128*MSB+LSB)/gv.pitchdiv)-gv.pitchneutral)*gv.pitchnotes
def PitchSens(CCval,*z):
gv.pitchnotes = (24*CCval+100)/127
sustain=False
def Sustain(CCval,*z):
global sustain
if gv.sample_mode==PLAYLIVE:
if (CCval == 0): # sustain off
sustain = False
for n in gv.sustainplayingnotes:
n.fadeout()
PlayRelSample(n.playingrelsample(),n.playingvoice(),n.playingnote(),n.playingvelocity(),n.playingretune(),n.playingchannel())
gv.sustainplayingnotes = []
else: # sustain on
sustain = True
damp=False
def Damp(CCval,*z):
global damp
if (CCval > 0):
damp = True
for m in gv.playingsounds: # get rid of fading notes
if m.isfadeout:
m.isfadein=True
for m in gv.sustainplayingnotes: # get rid of sustained notes
m.fadeout(False)
gv.sustainplayingnotes = []
for i in gv.playingnotes: # get rid of playing notes
for m in gv.playingnotes[i]:
if m.playingnote()>(127-gv.stop127) and m.playingnote()<gv.stop127:
if m.playingstopmode()!=3: # but exclude backtracks
m.fadeout(False)
gv.playingnotes[i] = []
gv.triggernotes[i] = 128 # housekeeping
DampNoise(m)
else: damp = False
def DampNew(CCval,*z):
global damp
damp=True if (CCval>0) else False
def DampLast(CCval,*z):
global sustain, damp
if (CCval>0):
damp = True
sustain = True
else:
damp = False
sustain = False
for m in gv.sustainplayingnotes: # get rid of gathered notes
m.fadeout(False)
DampNoise(m)
gv.sustainplayingnotes = []
def DampNoise(m):
if m.playingdampnoise():
PlayRelSample(m.playingrelsample(),m.playingvoice(),m.playingnote(),m.playingvelocity(),m.playingretune(),m.playingchannel(),True)
def PlayRelSample(relsample,voice,playnote,velocity,retune,channel=0,play_as_is=False):
if relsample in "ES":
if relsample=='E':
startparm=-1
else:
startparm=-2
voice=-voice
PlaySample(playnote,playnote,voice,velocity,startparm,retune,channel,play_as_is)
lastrnds = {}
def PlaySample(midinote,playnote,voice,velocity,startparm,retune,channel=0,play_as_is=False):
global lastrnds
velolevs=gv.voicelist[getindex(voice,gv.voicelist)][4]
velidx=int(1.0*(velocity*velolevs)/128+.9999) # roundup without math
if startparm==-1:
sample=lastrnds[playnote][0][lastrnds[playnote][1]] # use the same sample for the release sample
else:
notesamples=gv.samples[playnote,velidx,voice] # Get the list of available samples for this note/velocity/voice
gotcha=False
if startparm==-2: # try to find corresponding release sample
rnds=lastrnds[playnote][0][lastrnds[playnote][1]].rnds
for sample in notesamples: # the order may not be the same
if sample.rnds==rnds: # so pick the right entry
gothcha=True
break
if not gotcha: # for note-on's and absent separate release sample
rnd=random.randint(0,len(notesamples)) # no duplicates checking as David did, because we use random from NumPy
sample=notesamples[rnd] # still we need to save the choice for a possible release sample
lastrnds[playnote]=[notesamples,rnd]
#print "About to play note: %d=>%d, rnds: %s, relsamples: %s, play_as_is: %s, voice: %d, file: %s" % (midinote,playnote, sample.rnds, sample.relsample, play_as_is, sample.voice, sample.fname)
if play_as_is:
sample.play(midinote,playnote,velocity,startparm,retune,channel)
else:
gv.playingnotes.setdefault(channel*gv.MTCHNOTES+playnote,[]).append(sample.play(midinote,playnote,velocity,startparm,retune,channel))
gv.playingbacktracks=0
def playBackTrack(x,*z):
playnote=int(x)+gv.BTNOTES
if playnote in gv.playingnotes and gv.playingnotes[playnote]!=[]: # is the track playing?
gv.playingbacktracks-=1
for m in gv.playingnotes[playnote]:
m.playing2end() # let it finish
else:
try:
PlaySample(playnote,playnote,0,127,0,0)
gv.playingbacktracks+=1
except:
print 'Unassigned/unfilled track or other exception for backtrack %s->%d' % (x,playnote)
# and announce the procs to modules
gv.setMC(gv.PANIC,AllNotesOff)
gv.setMC(gv.EFFECTSOFF,EffectsOff)
gv.setMC(gv.PROGUP,ProgramUp)
gv.setMC(gv.PROGDN,ProgramDown)
gv.setMC(gv.VOLUME,MidiVolume)
gv.setMC(gv.AUTOCHORDOFF,AutoChordOff)
gv.setMC(gv.PITCHWHEEL,PitchWheel)
gv.setMC(gv.PITCHSENS,PitchSens)
gv.setMC(gv.SUSTAIN,Sustain)
gv.setMC(gv.DAMP,Damp)
gv.setMC(gv.DAMPNEW,DampNew)
gv.setMC(gv.DAMPLAST,DampLast)
gv.PlayRelSample=PlayRelSample
gv.PlaySample=PlaySample
gv.setMC(gv.BACKTRACKS,playBackTrack)
def MidiCallback(mididev, message, time_stamp):
# -------------------------------------------------------
# Deal with the midi-thru before anything else
# -------------------------------------------------------
#print '%s -> %s = Channel %d, message %d' % (mididev, message, messagechannel , messagetype)
for outport in gv.outports:
if mididev != gv.outports[outport][0]: # don't return to sender
#print ( " ... forwarding to '%s'" %( gv.outports[outport][0]) )
gv.outports[outport][1].send_raw(*message)
# -------------------------------------------------------
# Filter on current supported messages and do some inits
# -------------------------------------------------------
messagetype = message[0] >> 4
if messagetype==0xFF: # "realtime" reset has to reset all activity & settings
AllNotesOff() # (..other realtime will be ignored below..)
return
if messagetype not in [8,9,11,12,14]:
return
messagechannel = (message[0]&0xF) + 1 # make channel# human..
keyboardarea=True
# ----------------------------------------------------------------
# Multitimbrals identification and "hardware remap" of the drumpad
# ----------------------------------------------------------------
MT_in=False
if mididev in gv.MULTI_TIMBRALS:
if messagetype in [8,9,12]: # we only except note on/off and program change commands from the sequencers and other multitimbrals
MIDIchannel=messagechannel-1
if messagetype==12:
gv.MULTI_TIMBRALS[mididev][MIDIchannel]=setMTvoice(mididev,messagechannel,message[1]+1)
return
if gv.MULTI_TIMBRALS[mididev][MIDIchannel]==0: # if a channel hasn't sent a programchange, assume voice=channel. This is not uncommon from drumchannel=10
gv.MULTI_TIMBRALS[mididev][MIDIchannel]=setMTvoice(mididev,messagechannel,messagechannel)
MT_in=gv.MULTI_TIMBRALS[mididev][MIDIchannel]
elif (messagechannel==gv.MIDI_CHANNEL):
messagechannel=0
elif gv.drumpad: # using less compact coding in favor of performance...
if messagechannel==DRUMPAD_CHANNEL:
if messagetype==8 or messagetype==9: # We only remap notes
for i in xrange(len(gv.drumpadmap)):
if gv.drumpadmap[i][0]==message[1]:
message[1]=gv.drumpadmap[i][1]
messagechannel=0
break # found it, stop wasting time
# -------------------------------------------------------
# Then process channel commands if not muted
# -------------------------------------------------------
if ((messagechannel==0) or MT_in) and (gv.midi_mute==False) and len(message)>1:
midinote = message[1]
mtchnote = messagechannel*gv.MTCHNOTES+midinote
velocity = message[2] if len(message) > 2 else None
if messagetype==8 or messagetype==9: # We may have a note on/off
retune=0
if not MT_in:
i=getindex(midinote,gv.notemapping)
if i>-1: # do we have a mapped note ?
if gv.notemapping[i][2]==-2: # This key is actually a CC = control change
if velocity==0 or messagetype==8: midinote=0
ControlChange(gv.NOTES_CC, midinote)
return
midinote=gv.notemapping[i][2]
mtchnote=midinote
retune=gv.notemapping[i][3]
if gv.notemapping[i][4]>0:
setVoice(gv.notemapping[i][4],-1)
if velocity==0: messagetype=8 # prevent complexity in the rest of the checking
if MT_in or (midinote>(127-gv.stop127) and midinote<gv.stop127):
keyboardarea=True
else:
keyboardarea=False
#if gv.triggernotes[midinote]==midinote and velocity==64: # Older MIDI implementations
# messagetype=8 # (like Roland PT-3100)
if arp.active and keyboardarea and not MT_in:
arp.note_onoff(messagetype, midinote, velocity)
return
if messagetype==8 and not MT_in: # should this note-off be ignored?
if midinote in gv.playingnotes and gv.triggernotes[midinote]<128:
for m in gv.playingnotes[midinote]:
if m.playingstopnote() < 128: # are we in a special mode
return # if so, then ignore this note-off
else:
return # nothing's playing, so there is nothing to stop
if MT_in: # save voice and some effects, set voice according channel and reset those effects
gv.sqsav_chord=gv.currchord
gv.sqsav_chorus=chorus.effect
chorus.setType(False)
gv.sqsav_voice=gv.currvoice
setVoice(MT_in,-1)
if messagetype == 9: # is a note-off hidden in this note-on ?
if mtchnote in gv.playingnotes: # this can only be if the note is already playing
for m in gv.playingnotes[mtchnote]:
xnote=m.playingstopnote() # yes, so check it's stopnote
if xnote>-1 and xnote<128: # not in once or keyboard mode (covers "not MT_in")
if midinote==xnote: # could it be a push-twice stop?
if m.playingstopmode()==3: # backtracks end on sample end
m.playing2end() # so just let it finish
gv.playingbacktracks-=1
return
else:
messagetype = 8 # all the others have an instant end
elif midinote >= gv.stop127: # could it be mirrored stop?
if (midinote-127) in gv.playingnotes: # is the possible mirror note-on active?
for m in gv.playingnotes[midinote-127]:
if midinote==m.playingstopnote(): # and has it mirrored stop?
messagetype = 8
if messagetype == 9: # Note on
try:
gv.last_midinote=midinote # save original midinote for the webgui
if keyboardarea and not MT_in:
gv.last_musicnote=midinote-12*int(midinote/12) # do a "remainder midinote/12" without having to import the full math module
if gv.currscale>0: # scales require a chords mix
gv.currchord = gv.scalechord[gv.currscale][gv.last_musicnote]
playchord=gv.currchord
else:
gv.last_musicnote=12 # Set musicnotesymbol to "effects" in webgui
playchord=0 # no chords outside keyboardrange / in effects channel.
for n in range (len(gv.chordnote[playchord])):
playnote=midinote+gv.chordnote[playchord][n]
if sustain: # don't pile up sustain
for n in gv.sustainplayingnotes:
if n.playingnote() == playnote:
n.fadeout(True) # gracefully drop it
if gv.triggernotes[playnote]<128 and not MT_in: # cleanup in case of retrigger
if playnote in gv.playingnotes: # occurs in once/loops modes and chords
for m in gv.playingnotes[playnote]:
if m.sound.retrigger!='Y': # playing double notes not allowed
if m.sound.retrigger=='R':
m.fadeout(True) # ..either release
else:
m.fadeout(False) # ..or damp without optional dampnoise (considered unsuitable, based on current knowledge)
#gv.playingnotes[playnote]=[] # housekeeping, unnecessary as we will refill it immediately..
#print "start playingnotes playnote %d, velocity %d, gv.currvoice %d, retune %d" %(playnote, velocity, gv.currvoice, retune)
if chorus.effect:
PlaySample(midinote,playnote,gv.currvoice,velocity*chorus.gain,0,retune,messagechannel)
PlaySample(midinote,playnote,gv.currvoice,velocity*chorus.gain,2,retune-(chorus.depth/2+1),messagechannel)
PlaySample(midinote,playnote,gv.currvoice,velocity*chorus.gain,5,retune+chorus.depth,messagechannel)
else:
PlaySample(midinote,playnote,gv.currvoice,velocity,0,retune,messagechannel)