-
Notifications
You must be signed in to change notification settings - Fork 5
/
ziffers.rb
1642 lines (1463 loc) · 63.4 KB
/
ziffers.rb
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
require_relative "load_libs.rb"
require_relative "./lib/enumerables.rb"
require_relative "./lib/monkeypatches.rb"
require_relative "./lib/parser/zgrammar.rb"
require_relative "./lib/ziffarray.rb"
require_relative "./lib/ziffhash.rb"
require_relative "./lib/common.rb"
require_relative "./lib/generators.rb"
require_relative "./lib/defaults.rb"
require_relative "./lib/pc_sets.rb"
'''
# For testing and debugging
load "~/ziffers/lib/enumerables.rb"
load "~/ziffers/lib/monkeypatches.rb"
load "~/ziffers/lib/parser/zgrammar.rb"
load "~/ziffers/lib/ziffarray.rb"
load "~/ziffers/lib/ziffhash.rb"
load "~/ziffers/lib/common.rb"
load "~/ziffers/lib/generators.rb"
load "~/ziffers/lib/defaults.rb"
load "~/ziffers/lib/pc_sets.rb"
'''
module Ziffers
include Ziffers::Enumerables
include Ziffers::Grammar
include Ziffers::Defaults
include Ziffers::Common
include Ziffers::Generators
@@slice_opts_keys = [:delta_midi, :scale, :key, :synth, :amp, :beats, :duration, :port, :channel, :vel, :vel_f, :chord_channel, :parse_cc, :cc, :value, :mapping, :midi, :note, :notes, :amp, :pan, :attack, :decay, :sustain, :release, :pc, :pcs, :rate, :beat_stretch,:pitch_stretch, :pitch, :rpitch, :window_size, :pitch_dis, :time_dis, :run_each, :method, :beat_stretch, :pitch_stretch, :start, :finish, :onset, :split, :amp_slide, :pan_slide, :pre_amp,:on,:slice,:num_slices,:norm,:lpf,:lpf_init_level,:lpf_attack_level,:lpf_decay_level,:lpf_sustain_level,:lpf_release_level,:lpf_attack,:lpf_decay,:lpf_sustain,:lpf_release,:lpf_min,:lpf_env_curve,:hpf,:hpf_init_level,:hpf_attack_level,:hpf_decay_level,:hpf_sustain_level,:hpf_release_level,:hpf_attack,:hpf_decay,:hpf_sustain,:hpf_release,:hpf_env_curve,:hpf_max,:rpitch,:pitch,:window_size,:pitch_dis,:time_dis,:compress,:threshold,:slope_below,:slope_above,:clamp_time,:relax_time,:slide,:bass,:quint,:fundamental,:oct,:nazard,:blockflute,:tierce,:larigot,:sifflute,:rs_freq,:rs_freq_var,:rs_pitch_depth,:rs_delay,:rs_onset,:rs_pan_depth,:rs_amplitude_depth]
@@opts_shorthands = {:c=>:channel, :p=>:port, :k=>:key, :s=>:scale, :sleep=>:duration}
def replace_shorthands opts
@@opts_shorthands.each do |short_key,long_key|
opts[long_key] = opts.delete short_key if opts[short_key]
end
opts
end
@@debug = false
@@set_keys = [:pc]
$easing = {
linear: -> (t, b, c, d) { c * t / d + b },
in_quad: -> (t, b, c, d) { c * (t/=d)*t + b },
out_quad: -> (t, b, c, d) { -c * (t/=d)*(t-2) + b },
quad: -> (t, b, c, d) { ((t/=d/2) < 1) ? c/2*t*t + b : -c/2 * ((t-=1)*(t-2) - 1) + b },
in_cubic: -> (t, b, c, d) { c * (t/=d)*t*t + b },
out_cubic: -> (t, b, c, d) { c * ((t=t/d-1)*t*t + 1) + b },
cubic: -> (t, b, c, d) { ((t/=d/2) < 1) ? c/2*t*t*t + b : c/2*((t-=2)*t*t + 2) + b },
in_quart: -> (t, b, c, d) { c * (t/=d)*t*t*t + b },
out_quart: -> (t, b, c, d) { -c * ((t=t/d-1)*t*t*t - 1) + b },
quart: -> (t, b, c, d) { ((t/=d/2) < 1) ? c/2*t*t*t*t + b : -c/2 * ((t-=2)*t*t*t - 2) + b },
in_quint: -> (t, b, c, d) { c * (t/=d)*t*t*t*t + b},
out_quint: -> (t, b, c, d) { c * ((t=t/d-1)*t*t*t*t + 1) + b },
quint: -> (t, b, c, d) { ((t/=d/2) < 1) ? c/2*t*t*t*t*t + b : c/2*((t-=2)*t*t*t*t + 2) + b },
in_sine: -> (t, b, c, d) { -c * Math.cos(t/d * (Math::PI/2)) + c + b },
out_sine: -> (t, b, c, d) { c * Math.sin(t/d * (Math::PI/2)) + b},
sine: -> (t, b, c, d) { -c/2 * (Math.cos(Math::PI*t/d) - 1) + b },
in_expo: -> (t, b, c, d) { (t==0) ? b : c * (2 ** (10 * (t/d - 1))) + b},
out_expo: -> (t, b, c, d) { (t==d) ? b+c : c * (-2**(-10 * t/d) + 1) + b },
expo: -> (t, b, c, d) { t == 0 ? b : (t == d ? b + c : (((t /= d/2) < 1) ? (c/2) * 2**(10 * (t-1)) + b : ((c/2) * (-2**(-10 * t-=1) + 2) + b))) },
in_circ: -> (t, b, c, d) { -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b },
out_circ: -> (t, b, c, d) { c * Math.sqrt(1 - (t=t/d-1)*t) + b },
circ: -> (t, b, c, d) { ((t/=d/2) < 1) ? -c/2 * (Math.sqrt(1 - t*t) - 1) + b : c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b },
out_back: -> (t, b, c, d, s=1.70158) { ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b },
in_back: -> (t, b, c, d, s=1.70158) { c*(t/=d)*t*((s+1)*t - s) + b },
back: -> (t, b, c, d, s=1.70158) { ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b},
out_bounce: -> (t, b, c, d) { ((t/=d) < (1/2.75)) ? c*(7.5625*t*t) + b : (t < (2/2.75)) ? c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b : (t < (2.5/2.75)) ? c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b : c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b },
in_bounce: -> (t, b, c, d) { c - ($easing[:out_bounce].call((d-t), 0, c, d)) + b },
bounce: -> (t, b, c, d) { (t < d/2) ? $easing[:in_bounce].call(t*2, 0, c, d) * 0.5 + b : $easing[:in_bounce].call(t*2-d, 0, c, d) * 0.5 + c*0.5 + b }
# Derived from:
# https://github.com/danro/jquery-easing/blob/master/jquery.easing.js
# https://github.com/Michaelangel007/easing/blob/master/js/core/easing.js
}
def debug(debug=!@@debug)
@@debug = debug
end
def set_eql_keys(keys)
@@set_keys = keys
end
def get_eql_keys
@@set_keys
end
def self.set_default_duration(duration)
@@default_duration[:duration] = duration.to_f
end
def self.durations
@@default_durs
end
def tweak(func,start,finish,duration,time=nil)
(1..duration).map { |t| time ? $easing[func].call(t.to_f,start.to_f,(finish-start).to_f, duration.to_f,time.to_f) : $easing[func].call(t.to_f,start.to_f,(finish-start).to_f, duration.to_f) }.ring
end
# TODO: Document or remove?
def zgroup(n, opts={}, shared={})
if n.is_a?(Array)
if !n[0].is_a?(Hash)
defaults = shared.merge(opts)
opts = get_default_opts.merge(opts)
n = normalize_melody n, opts, defaults
end
n = ZiffArray.new(n).deep_clone
n = n.each_with_index.map {|z,i| apply_transformation(z, opts, 1, i, n.length, true)}
n = apply_array_transformations n, nil, opts
print "T: "+n.to_s if @@debug
n
else
zparse(n,opts,shared)
end
end
# TODO: Document n.times.collect { zgen "(1,[4,6,7])" } etc. or remove?
def zgen(n, opts={}, shared=get_default_opts)
defaults = shared.merge(opts)
opts = defaults.slice(*@@slice_opts_keys)
n = parse_generative n, opts, defaults
n = n.squeeze(" ")
n.split(" ").flatten
end
def zparse(n, opts={}, shared={})
raise "Melody is nil?" if !n
opts = replace_shorthands opts
shared = replace_shorthands shared
if n.is_a?(String) or n.is_a?(Integer)
print "I: "+n.to_s if @@debug
defaults = shared.merge(opts)
opts = defaults.slice(*@@slice_opts_keys)
opt_lambdas = opts.select {|k,v| v.is_a?(Proc) }
#opt_lambdas = opt_lambdas.map {|v| [v[0],v[1].()] }.to_h
if !opt_lambdas.empty?
procs = opts.extract!(*opt_lambdas.keys)
defaults = defaults.merge(procs)
end
opt_arrays = opts.delete_if {|v| v.is_a?(Array) or v.is_a?(SonicPi::Core::RingVector) }
defaults = defaults.merge(opt_arrays)
opts = get_default_opts.merge(opts)
defaults[:rules] = defaults.delete(:replace) if defaults[:replace]
if n.is_a?(String)
parsed_use = defaults.select{|k,v| k.length<2 and /[[:upper:]]/.match(k)} # Parse capital letters from the opts
if !parsed_use.empty?
defaults[:use] = defaults[:use] ? defaults[:use].merge(parsed_use) : parsed_use
defaults.except!(*parsed_use.keys)
end
if defaults[:use]
defaults[:use].each do |key,val|
if (val.is_a? String) or (val.is_a?(Array) and (val[0].is_a?(Integer) or val[0].is_a?(String))) then
val = val[defaults[:loop_i]%val.length] if val.is_a?(Array)
n = n.gsub key.to_s, val
defaults[:use].delete(:key)
elsif val.is_a? Integer
defaults[:use][key] = {note: val}
end
end
end
n = zpreparse(n,defaults.delete(:parsekey)) if defaults[:parsekey]!=nil
if defaults[:rules] and !shared[:string_rewrite_loop] then
gen = defaults[:gen] ? defaults[:gen] : 1
n = string_rewrite_system(n,opts,defaults,gen,nil)[gen-1]
sleep defaults[:rewrite_time] ? defaults[:rewrite_time] : 1 if defaults[:normalized]
end
loop_name = shared[:loop_name]
if loop_name
# Store generative options back to loop opts. Used currently only by cycle indexes.
n = parse_generative n, opts, defaults, true
if n[1][:error]
# TODO: This is a quick fix for raise error bug where Sonic Pi loses focus.
$zloop_states[loop_name].delete(:melody_string)
raise loop_name.to_s + ": "+n[1][:error]
end
if n[1][:cycle_counters]
$zloop_states[loop_name][:defaults] = {} if !$zloop_states[loop_name][:defaults]
$zloop_states[loop_name][:defaults][:cycle_counters] = n[1][:cycle_counters]
end
n = n[0]
else
n = parse_generative n, opts, defaults
end
print "G: "+n if @@debug
end
if n.is_a?(Integer)
if defaults[:parse_chord] == true
n = n.to_s
elsif defaults[:parse_chord] == false
n = n.to_s
n = "{"+n+"}" if n.length>1
else # By default parse as sequence
n = (n<0 ? "-"+n.to_s[1..].split("").join(" -") : n.to_s.split("").join(" "))
end
if defaults[:rules] and !shared[:string_rewrite_loop] then
gen = defaults[:gen] ? defaults[:gen] : 1
n = string_rewrite_system(n,opts,defaults,gen,nil)[gen-1]
end
end
n = n.gsub(/(^|\s|[a-z\^_\'´`])([0-9]+)(?=(?:\s|$))/) {|m| "#{$1}{#{$2}}" } if defaults[:midi] or defaults[:parse_cc] or defaults[:xen] # Hack for midi & cc & xen
parsed = parse_ziffers(n, opts, defaults)
if parsed.kind_of?(Hash) and parsed[:error]
print parsed[:error]
stop
end
print "P: "+parsed.to_z if @@debug
parsed
else
normalize_melody n, opts, shared
end
end
def search_list(arr,query)
result = (Float(query) != nil rescue false) ? arr[query.to_i] : arr.find { |e| e.match( /\A#{Regexp.quote(query)}/)}
(result == nil ? query : result)
end
def zparams(hash, name)
hash.map{|x| x[name]}
end
def clean(ziff)
ziff.slice(*[:note,:notes,:note_slide,:amp,:amp_slide,:pan,:pan_slide,:attack,:decay,:sustain,:release,:attack_level,:decay_level,:sustain_level,:env_curve,:slide,:pitch,:rate,:on,:cutoff,:res,:env_curve,:vibrato_rate,:vibrato_depth,:vibrato_delay,:vibrato_onset,:width,:freq_band,:room,:reverb_time,:ring,:detune1,:detune2,:noise,:dpulse_width,:pulse_width,:sub_detune,:sub_amp,:divisor,:norm,:clickiness,:mod_phase,:mod_range,:mod_pulse_width,:mod_phase_offset,:mod_invert_wave,:mod_wave,:detune,:stereo_width,:hard,:vel,:coef,:pluck_delay,:noise_amp,:max_delay_time,:lfo_width,:lfo_rate,:seed,:disable_wave,:range,:invert_wave,:wave,:phase_offset,:phase,:bass,:quint,:fundamental,:oct,:nazard,:blockflute,:tierce,:larigot,:sifflute,:rs_freq,:rs_freq_var,:rs_pitch_depth,:rs_delay,:rs_onset,:rs_pan_depth,:rs_amplitude_depth])
end
def clean_sample(ziff)
ziff.slice(*[:rate,:beat_stretch,:pitch_stretch,:attack,:sustain,:release,:start,:finish,:pan,:pan_slide,:amp,:amp_slide,:pre_amp,:onset,:on,:slice,:num_slices,:norm,:lpf,:lpf_init_level,:lpf_attack_level,:lpf_decay_level,:lpf_sustain_level,:lpf_release_level,:lpf_attack,:lpf_decay,:lpf_sustain,:lpf_release,:lpf_min,:lpf_env_curve,:hpf,:hpf_init_level,:hpf_attack_level,:hpf_decay_level,:hpf_sustain_level,:hpf_release_level,:hpf_attack,:hpf_decay,:hpf_sustain,:hpf_release,:hpf_env_curve,:hpf_max,:rpitch,:pitch,:window_size,:pitch_dis,:time_dis,:compress,:threshold,:slope_below,:slope_above,:clamp_time,:relax_time,:slide,:bass,:quint,:fundamental,:oct,:nazard,:blockflute,:tierce,:larigot,:sifflute,:rs_freq,:rs_freq_var,:rs_pitch_depth,:rs_delay,:rs_onset,:rs_pan_depth,:rs_amplitude_depth])
end
def play_midi_out(md, opts)
# Todo: Experiment more with midi_sound_off
# midi_sound_off channel: opts[:channel]
midi_pitch_bend **opts.slice(:delta_midi, :channel, :port) if opts[:delta_midi]
midi md, opts
end
def play_midi_on_out(md, opts)
midi_pitch_bend **opts.slice(:delta_midi, :channel, :port) if opts[:delta_midi]
midi_note_on md, opts
end
def play_midi_off_out(md, opts)
midi_pitch_bend **opts.slice(:delta_midi, :channel, :port) if opts[:delta_midi]
midi_note_off md, opts
end
def normalize_ziff_methods(ziff,index,loop_i)
ziff.each do |key,val|
if val.is_a?(SonicPi::Core::RingVector) or val.kind_of?(Array) then
char_key = ziff[:chars] ? ziff[:chars].join("") : ziff[:char]
ziff[key] = val.tick(char_key+"-"+key.to_s)
elsif val.is_a? Proc then
case val.arity
when 0 then
ziff[key] = val.()
when 1 then
ziff[key] = val.(index)
when 2 then
ziff[key] = val.(index, loop_i)
end
end
end
end
def zthread(melody, opts={}, defaults={}, loop_i=0)
in_thread do
zplay(melody,opts,defaults,loop_i)
end
end
def zplay(melody,opts={},defaults={},loop_i=0)
loop_name = defaults[:loop_name]
if !loop_name
# Extract common options to defaults
defaults = defaults.merge(opts) # {|key, important, default| important } ?
opts = defaults.slice(*@@slice_opts_keys)
# TODO: Add global parameter for this
use_sched_ahead_time defaults[:sched_ahead] ? defaults[:sched_ahead] : 0.5
use_arg_bpm_scaling defaults[:use_arg_bpm_scaling] ? defaults[:use_arg_bpm_scaling] : false
end
loop_i = loop_name ? $zloop_states[loop_name][:loop_i] : loop_i
loop_n = (melody.is_a?(Array) ? melody.length : melody.to_s.length)*(loop_i+1)
defaults[:loop_i] = loop_i
defaults[:loop_n] = loop_i
if defaults[:store] and (loop_name and $zloop_states[loop_name][:parsed_melody] or $zloop_states[loop_name][:intervals])
if $zloop_states[loop_name][:intervals]
defaults[:intervals] = $zloop_states[loop_name][:intervals]
end
melody = $zloop_states[loop_name][:parsed_melody]
melody = normalize_melody(melody, opts, defaults)
elsif melody.is_a? Enumerator then
enum = melody
begin
melody = enum.next
while !melody
melody = enum.next
end
Thread.current[:enum_has_values] = true if melody
rescue StopIteration
stop
end
melody = normalize_melody(melody, opts, defaults)
elsif has_combinatorics(defaults)
melody = normalize_melody(melody, opts, defaults)
enum = parse_combinatorics(melody,defaults)
melody = enum.next if enum.size != 0
else
melody = normalize_melody(melody, opts, defaults)
end
if defaults[:bpm] then
if defaults[:run]
defaults[:run] = [defaults[:run]] if !defaults[:run].is_a?(Array)
defaults[:run] << {with_bpm: defaults.delete(:bpm)}
else
defaults[:run] = [{with_bpm: defaults.delete(:bpm)}]
end
end
loop do
# Default opts for enums & merge old defaults for intervals mode
defaults = $zloop_states[loop_name][:defaults].merge(defaults) {|key, important, default| important } if loop_name and $zloop_states[loop_name] and $zloop_states[loop_name][:defaults]
if !opts[:port] and defaults[:run] then
block_with_effects normalize_effects(defaults[:run]) do
zplayer(melody,opts,defaults,loop_i)
end
else
zplayer(melody,opts,defaults,loop_i)
end
print "Loop index: "+loop_i.to_s if @@debug and loop_i>0
break if !enum
# Enumeration prosessing starts here
defaults[:loop_i] = loop_i
break if defaults[:stop] or (defaults[:stop].is_a?(Integer) and defaults[:stop]<loop_i)
begin
melody = enum.next
while !melody
melody = enum.next
end
Thread.current[:enum_has_values] = true if melody
rescue StopIteration
if loop_name and Thread.current[:enum_has_values]
enum.rewind
melody = enum.next
while !melody
melody = enum.next
end
else
stop
end
end
melody = normalize_melody melody, opts, defaults
loop_i = loop_i+1
cue loop_name
end
end
def zplayer(melody,opts={},defaults={},loop_i=0)
melody = [melody] if !melody.kind_of?(Array)
if melody.length==0 then
$zloop_states.delete(defaults[:loop_name]) if defaults[:loop_name]
stop
end
melody.each_with_index do |ziff,index|
if !ziff[:skip] and ziff[:rest]
sleep ziff[:beats]
next
end
ziff = apply_transformation(ziff, defaults, loop_i, index, melody.length)
if ziff[:method] then
in_thread do
eval(ziff[:method])
end
elsif ziff[:methods]
mlen = ziff[:methods].length
1.upto(mlen) do |i|
if i<mlen
in_thread do
eval(ziff[:methods][mlen-i][:method])
end
else
eval(ziff[:methods][mlen-i][:method])
end
end
end
# TODO: Merge rate not working. Merges too much?
#ziff = opts.merge(merge_rate(ziff, defaults)) if defaults[:preparsed]
if defaults[:fade] or defaults[:fade_in] or defaults[:fade_out]
tick_reset(:adjust_amp) if defaults[:fade_reset]
fade = defaults[:fade] ? defaults.delete(:fade) : defaults[:fade_in] ? 0.0..1.0 : 1.0..0.0
fade_from = fade.begin
fade_to = fade.end
fade_in_cycles = defaults.delete(:fade_in) || defaults.delete(:fade_out)
fader = defaults.delete(:fader)
defaults[:adjust_amp] = tweak((fader ? fader : :quart), fade_from, fade_to, fade_in_cycles ? fade_in_cycles*melody.length : melody.length).to_a
end
if defaults[:adjust_amp] then
t_index = tick(:adjust_amp)
ziff[:amp] = defaults[:adjust_amp][t_index] ? defaults[:adjust_amp][t_index] : defaults[:adjust_amp][defaults[:adjust_amp].length-1]
end
# TODO: Better function to map amp to velocity
if ziff[:port]
if ziff[:amp]
if ziff[:amp] > 0.5
ziff[:vel_f] = 0.5 + ((ziff[:amp]>3.25?3.25:ziff[:amp]) - 0.5) / (3.25 - 0.5) * 0.5
else
ziff[:vel_f] = ziff[:amp]
end
else
ziff[:vel_f] = 0.5
end
end
if ziff[:run_each] then
block_with_effects normalize_effects(ziff[:run_each],ziff[:char]) do
play_ziff(ziff,defaults,index,loop_i)
end
else
play_ziff(ziff,defaults,index,loop_i)
end
if !ziff[:skip] and !ziff[:slide] and !(ziff[:notes] and ziff[:arpeggio])
sleep ziff[:beats]
midi_pitch_bend delta_midi: 8192, **ziff.slice(:port,:channel,:vel,:vel_f) if ziff[:port] and ziff[:delta_midi] and (melody[index+1] and !melody[index+1][:delta_midi])
end
end
# Save loop state
if defaults[:store] and defaults[:loop_name] then
if defaults[:intervals]
$zloop_states[defaults[:loop_name]][:intervals] = defaults[:intervals]
end
$zloop_states[defaults[:loop_name]][:parsed_melody] = melody
if @@debug then
print "Stored:"
print melody.pcs
end
end
end
def play_ziff(ziff,defaults={},index,loop_i)
cue ziff[:cue] if ziff[:cue]
ziff[:port] = @@default_port if ziff[:channel] and !ziff[:port] and @@default_port
# TODO: Add midi velocity to here?: ziff[:vel_f] = ziff[:amp] if ziff[:port] and (!ziff[:vel] and !ziff[:vel_f])
if ziff[:send] then
send(ziff[:send],ziff)
elsif ziff[:skip] then
print "Skipping note"
elsif ziff[:notes] then
# TODO: Deprecated arpeggio. Remove in future version?
if ziff[:arpeggio] then
ziff[:arpeggio].each do |cn|
if cn[:hpcs] then
arp_chord = cn[:hpcs].map do |d|
h = ZiffHash[ziff[:hpcs][d[:pc]%ziff[:hpcs].length].dup]
h = h.merge(d.slice(:amp))
h[:add] += d[:add] if d[:add]
h[:octave] += d[:octave] if d[:octave]
h.update_note
end
arp_notes = {notes: arp_chord}
else
arp_notes = ziff[:hpcs][cn[:pc]%ziff[:hpcs].length].dup
arp_notes = arp_notes.merge(cn.slice(:octave,:add,:amp))
arp_notes.update_note
end
arp_opts = cn.merge(arp_notes).except(:pcs, :pc)
if ziff[:port] then
sustain = ziff[:chord_release] ? ziff[:chord_release] : (ziff[:sustain] ? ziff[:sustain] : ziff[:beats])
if arp_notes[:notes] then
arp_notes[:notes].each_with_index do |arp_note,i|
ziff[:channel] = (arp_note[:chord_channel].is_a?(Integer) ? arp_note[:chord_channel] : arp_note[:chord_channel][i]) if arp_note[:chord_channel]
check_cc arp_note.merge(ziff.slice(:cc, :mapping, :port, :channel, :value))
play_midi_out arp_note[:note]+(cn[:pitch]?cn[:pitch]:0), ziff.slice(:port,:channel,:vel,:vel_f,:delta_midi).merge({sustain: sustain}).merge(arp_note.slice(:port,:channel,:vel,:vel_f,:delta_midi))
end
else
ziff[:channel] = ziff[:chord_channel][arp_notes.delete(:index)] if ziff[:chord_channel]
check_cc arp_notes.merge(ziff.slice(:cc, :mapping, :port, :channel, :value))
play_midi_out arp_notes[:note]+(cn[:pitch]?cn[:pitch]:0), ziff.slice(:port,:channel,:vel,:vel_f,:delta_midi).merge({sustain: sustain}).merge(cn.slice(:port,:channel,:vel,:vel_f,:delta_midi))
end
else
arp_opts[:notes] = arp_opts[:notes].map {|h| h[:note] } if arp_opts[:notes]
synth (ziff[:chord_synth]!=nil ? ziff[:chord_synth] : (ziff[:synth]!=nil ? ziff[:synth] : current_synth)), clean(arp_opts)
end
sleep cn[:beats]
midi_pitch_bend delta_midi: 8192, **cn.slice(:port,:channel,:vel,:vel_f) if cn[:delta_midi]
end
## TODO: Deprecated arpeggio ends to else
else
if ziff[:port]
sustain = ziff[:chord_release] ? ziff[:chord_release] : (ziff[:sustain] ? ziff[:sustain] : ziff[:beats])
ziff[:hpcs].each_with_index do |pc_note,i|
ziff[:channel] = (ziff[:chord_channel].is_a?(Integer) ? ziff[:chord_channel] : ziff[:chord_channel][i]) if ziff[:chord_channel]
check_cc pc_note
play_midi_out(pc_note[:note], ziff.slice(:port,:channel,:vel,:vel_f,:delta_midi).merge({sustain: sustain}).merge(pc_note.slice(:port,:channel,:vel,:vel_f,:delta_midi)))
end
else
synth (ziff[:chord_synth]!=nil ? ziff[:chord_synth] : (ziff[:synth]!=nil ? ziff[:synth] : current_synth)), clean(ziff)
end
end
elsif ziff[:method]
normalize_ziff_methods(ziff,index,loop_i)
elsif ziff[:port] and ziff[:note] then
ziff[:channel] = ziff[:chord_channel][0] if !ziff[:channel] and ziff[:chord_channel]
if ziff[:parse_cc]
midi_cc ziff[:parse_cc], ziff[:note], port: ziff[:port], channel: ziff[:channel]
else
check_cc ziff
sustain = ziff[:sustain] ? ziff[:sustain]*4 : ziff[:beats]
play_midi_out(ziff[:note], ziff.slice(:port,:channel,:vel,:vel_f,:delta_midi).merge({sustain: sustain}))
end
else
check_cc ziff
if ziff[:split] or ziff[:sample] or ziff[:samples] or ziff[:method] then
if ziff[:split] and ziff[:pc]
ziff[:sample] = ziff[:split]
ziff[:onset] = ziff[:pc]
elsif defaults[:rate_based] && ziff[:note]!=nil then
ziff[:rate] = pitch_to_ratio(ziff[:note]-note(ziff[:key]))
elsif ziff[:pc]!=nil then
ziff[:pitch] = (scale 0, ziff[:scale], num_octaves: 2)[ziff[:pc]]+(ziff[:octave])*12-0.001
end
if ziff[:cut] then
ziff[:finish] = [0.0,(ziff[:duration]/(sample_duration (ziff[:sample_dir] ? [ziff[:sample_dir], ziff[:sample]] : ziff[:sample])))*ziff[:cut],1.0].sort[1]
ziff[:finish]=ziff[:finish]+ziff[:start] if ziff[:start]
end
# Normalize sample parameters
if ziff[:samples]
ziff[:samples].each do |s|
if s[:method]
normalize_ziff_methods(s,index,loop_i)
else
normalize_ziff_methods(s,index,loop_i)
if respond_to?(s[:sample])
in_thread do
send(s[:sample])
end
else
sample (s[:sample_dir] ? [s[:sample_dir], s[:sample]] : s[:sample]), clean_sample(s)
end
end
end
else # Sample
normalize_ziff_methods(ziff,index,loop_i)
if respond_to?(ziff[:sample])
send(ziff[:sample])
else
c = sample (ziff[:sample_dir] ? [ziff[:sample_dir], ziff[:sample]] : ziff[:sample]), clean_sample(ziff)
end
end
elsif ziff[:note] or ziff[:notes]
if ziff[:synth] then
c = synth ziff[:synth], clean(ziff)
else
c = play clean(ziff)
end
end
if ziff[:slide] != nil then
first = ziff[:slide].clone
first[:note] = first.delete(:notes)[0]
first[:note_slide] = ziff[:note_slide] ? ziff[:note_slide] : 1.0
first[:sustain] = ziff[:beats]*0.5
if first[:port]
play_midi_on_out(first[:note], first.slice(:port, :channel))
elsif !first[:sample]
c = first[:synth] ? (synth first[:synth], clean(first)) : (play clean(first))
else
c = sample (ziff[:sample_dir] ? [ziff[:sample_dir], ziff[:sample]] : ziff[:sample]), clean_sample(ziff)
end
slide_beats = ziff[:beats]/ziff[:slide][:notes].length
sleep slide_beats
rest = ziff[:slide][:hpcs][1..]
rest.each_with_index do |rziff,i|
slide_ziff = rziff.clone
if first[:port]
play_midi_on_out(slide_ziff[:note], slide_ziff.slice(:port, :channel))
else
slide_ziff[:pitch] = (scale 0, slide_ziff[:scale], num_octaves: 2)[slide_ziff[:pc]]+(slide_ziff[:octave] ? (ziff[:octave]*12) : 0) if slide_ziff[:sample]!=nil && slide_ziff[:pc]!=nil
cc = clean(slide_ziff).except(:attack,:release,:sustain,:decay,:notes,:pcs)
control c, cc
end
sleep slide_beats
end
rest.each do |rziff|
play_midi_off_out(rziff[:note], rziff.slice(:port, :channel))
end
play_midi_off_out(first[:note], first.slice(:port, :channel))
end
end
end
def check_cc(ziff)
if ziff[:cc] && (ziff[:mapping] || ziff[:value])
if ziff[:value]
cc_value = ziff[:value]
elsif ziff[:mapping].is_a?(Hash)
cc_value = ziff[:mapping][ziff[:pc]]
else
cc_value = midi_to_cc_pitch(ziff[:mapping], ziff[:note])
end
midi_cc ziff[:cc], cc_value, port: ziff[:port], channel: ziff[:channel] if cc_value
end
end
def normalize_effects(run,char=nil)
run = [run] if run.is_a?(Hash)
run = [{with_fx: run}] if run.is_a?(Symbol)
run.map do |effect|
dup = {}
effect_name = effect[:with_fx] ? "run-"+effect[:with_fx].to_s : "run"
name = char ? char+"-"+effect_name : effect_name
effect.each do |key, val|
if val.is_a?(SonicPi::Core::RingVector) or val.kind_of?(Array) then
dup[key] = val.tick(name+"-"+key.to_s)
elsif val.is_a? Proc then
case val.arity
when 0 then
dup[key] = val.()
when 1 then
dup[key] = val.(tick(name+"-"+key.to_s))
end
end
end
if dup.size>0 then
effect.clone.merge(dup)
else
effect
end
end
end
def normalize_melody(melody, opts, defaults)
defaults[:normalized] = defaults[:is_enum] ? false : true
if melody.is_a?(Proc)
loop_i = defaults[:loop_name] ? $zloop_states[defaults[:loop_name]][:loop_i] : 0
case melody.arity
when 0 then
melody = melody.()
when 1 then
melody = melody.(loop_i)
end
end
if melody.is_a?(String)
return zparse(melody,opts,defaults)
elsif melody.is_a?(Symbol) and melody == :r
return zparse("r",opts,defaults)
elsif melody.is_a?(Numeric) # zplay 1 OR zmidi 85
if defaults[:midi] or defaults[:parse_cc] or (defaults[:parse_chord] and defaults[:parse_chord]==false) then
opts[:note] = melody
else
return zparse(melody,opts,defaults)
end
elsif melody.is_a?(Array)
defaults = defaults.merge(opts)
opts = defaults.slice(*@@slice_opts_keys)
melody = zarray(melody,opts,defaults)
melody = apply_array_transformations melody, opts, defaults
return melody
elsif melody.is_a?(Hash)
return [melody]
else
raise "Could not parse given melody!"
end
end
def create_loop_opts(opts, loop_opts)
opts.each do |key,val|
if key.to_s.length>1 and val.is_a? Proc then
loop_opts[:lambdas] = {} if !loop_opts[:lambdas]
loop_opts[:lambdas][key] = opts.delete(key)
end
end
end
def eval_loop_opts(opts,loop_opts)
if loop_opts[:lambdas] then
loop_opts[:lambdas].each do |key, val|
opts[key] = val.() if val.arity == 0
opts[key] = val.(loop_opts[:loop_i]) if val.arity == 1
end
end
end
# Looper for multi line notation
def ziffers(input, opts={})
start_time = Time.now
$run_counter = ($run_counter+1 || 0)
# Different randoms for each run
use_random_seed rand_i(10000)+$run_counter
parsed = parse_rows(input, true)
parse_time = Time.now - start_time
sleep parse_time+1.0
zloop :z0, "qr", parsed[0][1] # Metronome loop
parsed.each_with_index do |arr,i|
zloop ("z"+(i+1).to_s).to_sym, arr[0], arr[1]
end
end
def ziff(input, opts={})
start_time = Time.now
parsed = parse_rows(input,true)
parse_time = Time.now - start_time
sleep parse_time+1.0
parsed.each do |arr|
in_thread do
zplay arr[0], opts
end
end
end
def zplay_multi_line_measures(input, opts={}, shared={},merge_opts={})
idx = tick(:multi_line)
parsed = parse_rows_by_measures(input)
measures = parsed[:rows].transpose
row_options = parsed[:options]
# Parse measures
ziffs = measures.ring[idx].map.with_index do |m,i|
if m
m_index = parsed[:shared_options].filter_map.with_index { |e, i| i if !e }
shared_options = parsed[:shared_options].flatten[0..m_index[i]].compact.last
merge_opts.merge!(shared_options) if shared_options
ziff_opts = opts.merge(merge_opts)
if row_options && row_options[i]
row_opts = row_options[i].ring[look(:multi_line)]
ziff_opts = row_opts ? ziff_opts.merge(row_opts) : ziff_opts
end
zparse m, ziff_opts, shared
end
end
# Find longest measure
max = ziffs.map{|v| v ? v.duration : 0 }
max, max_i = max.each_with_index.max
blocking_melody = ziffs[max_i]
ziffs[max_i] = nil
ziffs.each_with_index do |z,i|
zthread z, opts, shared if z
end
zplay blocking_melody, opts, shared
merge_opts
end
def parse_rows(input, preparsed=false)
lines = input.split("\n")
lines = lines.map {|l| l.strip }.filter {|v| !v.empty? }
lines = lines.map{|l| l.split("//")[0] }.filter {|v| !v.empty?} # Ignore comments
parameters = lines.map {|l| l.start_with?("/ ") ? ["",l[2..]] : l.split(" / ") } # Get parameters
shared_options = parameters.map.with_index {|p,i| p[0]=="" ? parse_params(p[1],{:loop_name=>("z"+i.to_s).to_sym}) : {} }
last_opt = {}
shared_options = shared_options.each.collect do |v|
if v.keys.length!=0
last_opt = v
nil
else
last_opt
end
end
shared_options = shared_options.compact
options = parameters.map{|p| p[0].empty? ? false : (p[1] ? parse_params(p[1]) : {}) }.filter {|v| v!=false }
options = options.map.with_index {|v,i| shared_options[i].merge(v) }
parsed_rows = parameters.map{|p| p[0] }.filter {|v| !v.strip.empty? }
if preparsed
parsed_rows = parsed_rows.map.with_index do |v,i|
z_loop_name = ("z"+(i+1).to_s).to_sym
parsed_melody = zparse(v,options[i].merge({loop_name: z_loop_name}))
[parsed_melody, options[i]]
end
parsed_rows
else
parsed_rows.map.with_index{|p,i| [p,options[i]] }
end
end
def parse_rows_by_measures(input)
lines = input.split("\n").to_a.filter {|v| !v.strip.empty? }
lines = lines.filter {|n| !n.start_with? "//" }
parameters = lines.map {|l| l.start_with?("/ ") ? l.split("/ ") : l.split(" / ") }
rows = parameters.map{|p| p[0]}.filter {|v| !v.strip.empty? }.map {|l| l.split("|").filter {|v| !v.strip.empty? } }
rows_length = rows.map(&:length).max
rows = rows.map {|v| v.length<rows_length ? v+Array.new(rows_length-v.length){ nil } : v }
shared_options = parameters.map {|p| p[1].split("|").map{|sp| (sp && sp.strip.empty? ? nil : parse_params(sp))} if p[0]=="" }
options = parameters.map{|p| p[0].empty? ? false : (p[1] ? p[1].split("|").map{|sp| sp && sp.strip.empty? ? nil : parse_params(sp)} : nil) }.filter {|v| v!=false }
rows = rows.map {|v| v.map.with_index {|m,i| m and m.strip=="..." ? v[i] = v[i-1] : m }}
{rows: rows, shared_options: shared_options, options: options}
end
# Looper for track notation
def ztracker(m, opts={}, shared=nil)
live_loop :ztracker do
stop if opts[:stop]
shared = zplay_tracks(m, opts, shared)
end
end
def ztracks(input, opts={}, shared={})
length = input.split("|").to_a.filter {|v| !v.strip.empty? }.length
length.times do |i|
shared = zplay_tracks(input,opts, shared)
end
end
# Plays tracks notation
def zplay_tracks(m, opts={}, shared=nil)
lines = m.split("\n").to_a.filter {|v| !v.strip.empty? }
lines = lines.filter {|n| !n.start_with? "//" }
## TODO: Do ... continue syntax parsin here?
line = lines.ring[tick(:ztracker)]
result = zparse_tracks line, opts, shared, look(:ztracker)
while result[:shared_opts] do
if !shared
shared = result[:shared_opts]
elsif shared.is_a?(Hash)
if result[:shared_opts].is_a?(Hash)
shared = shared.merge(result[:shared_opts])
elsif result[:shared_opts].is_a?(Array)
result[:shared_opts][0] = result[:shared_opts][0].merge(shared)
shared = result[:shared_opts]
end
elsif shared.is_a?(Array)
shared = result[:shared_opts].map.with_index {|s,i| shared[i] ? shared[i].merge(s) : shared[i] = s } if result[:shared_opts].is_a?(Array)
shared = shared.map {|s| s.merge(result[:shared_opts]) } if result[:shared_opts].is_a?(Hash)
end
line = m.split("\n").to_a.filter {|v| !v.strip.empty? }.ring[tick(:ztracker)]
result = zparse_tracks line, opts, shared, look(:ztracker)
end
ziffs = result[:zthreads]
blocking_melody = result[:zthreads].select {|v| v[:blocking] }[0][:blocking]
ziffs.each_with_index do |z,i|
zthread z[:thread], opts, z[:merged_opts], look(:ztracker) if z and z[:thread]
end
zplay blocking_melody[:thread], opts, blocking_melody[:merged_opts], look(:ztracker)
shared
end
# Parse tracks to threads and blocking melody
def zparse_tracks(row, opts, shared_opts=nil, loop_i=0)
parsed = parse_tracks(row,opts)
return {shared_opts: parsed[:shared_options]} if parsed[:shared_options]
row_opts = parsed[:options]
tracks = parsed[:tracks]
ziffs = tracks.map.with_index do |t,i|
merged_opts = opts
merged_opts = (shared_opts.is_a?(Array)) ? (shared_opts[i] ? merged_opts.merge(shared_opts[i]) : merged_opts) : merged_opts.merge(shared_opts) if shared_opts
merged_opts = (row_opts.is_a?(Array)) ? (row_opts[i] ? merged_opts.merge(row_opts[i]) : merged_opts) : merged_opts.merge(row_opts) if row_opts
z = zparse t.strip, merged_opts, {loop_i: loop_i}
{thread: z, merged_opts: merged_opts}
end
# Find longest measure
max = ziffs.map{|v| v ? v[:thread].duration : 0 }
max, max_i = max.each_with_index.max
blocking_melody = ziffs[max_i]
ziffs[max_i] = {blocking: blocking_melody}
return {zthreads: ziffs}
end
# Parses track string to tracks and options
def parse_tracks(input, opts={})
parameters = input.split("/")
row = parameters[0] if parameters and parameters[0] and parameters[0].strip!=""
row_options = parameters[1].split("|").map {|v| v.strip.empty? ? nil : parse_params(v,opts) } if row and parameters[1]
shared_options = parameters[1].split("|").map {|v| v.strip.empty? ? nil : parse_params(v,opts) } if !row and parameters[1]
row_options = row_options[0] if row_options and row_options.length == 1
shared_options = shared_options[0] if shared_options and shared_options.length == 1
result = {}
result[:tracks] = row.split("|").filter {|v| !v.strip.empty? } if row
result[:options] = row_options if row_options
result[:shared_options] = shared_options if shared_options
result
end
# Original looper
def zloop(name, melody, opts={}, defaults={})
defaults[:loop_name] = name
defaults = defaults.merge(opts)
opts = defaults.slice(*@@slice_opts_keys)
defaults[:sync] = :z0 if $zloop_states and name!=:z0 and $zloop_states[:z0] and !defaults[:sync] # Automatic sync to :z0 if it exists
clean_loop_states # Clean unused loop states
$zloop_states.delete(name) if opts.delete(:reset)
raise "First parameter should be loop name as a symbol!" if !name.is_a?(Symbol)
raise "Third parameter should be options as hash object!" if !opts.kind_of?(Hash)
$zloop_states[name][:defaults] = defaults if defaults[:stop] and melody.is_a?(Enumerator) and $zloop_states[name]
if !defaults[:stop] or defaults[:stop].is_a?(Integer)
if !$zloop_states[name] then # If first time
$zloop_states[name] = {}
$zloop_states[name][:loop_i] = 0
end
$zloop_states[name][:cycle] = defaults.delete(:cycle) if defaults[:cycle]
create_loop_opts(opts,$zloop_states[name])
if defaults[:phase] then
defaults[:phase] = defaults[:phase].to_a if (defaults[:phase].is_a? SonicPi::Core::RingVector)
end
# Defaults for enumerations in loops
$zloop_states[name][:defaults] = defaults
if melody.is_a?(Enumerator) or ((defaults[:parse] or (has_combinatorics(defaults)) and !$zloop_states[name][:enumeration]) and (melody.is_a?(String) and !melody.start_with? "//") and !defaults[:seed])
if melody.is_a? Enumerator then
enumeration = melody
else
parsed_melody = normalize_melody melody, opts, defaults
enumeration = parse_combinatorics parsed_melody, defaults
end
if enumeration then
$zloop_states[name][:enumeration] = enumeration
defaults[:is_enum] = true
end
else
# Parse initial melody to loop states
if melody.is_a?(Array) && melody[0].is_a?(Hash)
$zloop_states[name][:melody] = melody # Melody is already parsed
else
$zloop_states[name][:melody] = zparse melody, opts, defaults.except(:rules) if !$zloop_states[name][:melody]
$zloop_states[name][:melody_string] = melody
end
end
end
live_loop name, defaults.slice(:init,:auto_cue,:delay,:sync,:sync_bpm,:seed) do
if defaults[:stop] and ((defaults[:stop].is_a? Numeric) and $zloop_states[name][:loop_i]>=defaults[:stop]) or ([true].include? defaults[:stop]) or (melody.is_a?(String) and (melody.start_with? "//" or melody.start_with? "# ")) then
$zloop_states.delete(name)
stop
end
use_sched_ahead_time (defaults[:sched_ahead] ? defaults[:sched_ahead] : 0.5)