-
-
Notifications
You must be signed in to change notification settings - Fork 942
/
Copy pathcore.rb
4977 lines (4141 loc) · 186 KB
/
core.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
## encoding: utf-8
#--
# This file is part of Sonic Pi: http://sonic-pi.net
# Full project source: https://github.com/samaaron/sonic-pi
# License: https://github.com/samaaron/sonic-pi/blob/main/LICENSE.md
#
# Copyright 2013, 2014, 2015, 2016 by Sam Aaron (http://sam.aaron.name).
# All rights reserved.
#
# Permission is granted for use, copying, modification, and
# distribution of modified versions of this work as long as this
# notice is included.
#++
require_relative 'support/docsystem'
require_relative "../version"
require_relative "../util"
require_relative "../runtime"
require_relative "western_theory"
require 'active_support/inflector'
## TODO: create _* equivalents of all fns - for silent (i.e computation) versions
module SonicPi
module Lang
module Core
include SonicPi::Lang::Support::DocSystem
include SonicPi::Util
include SonicPi::Lang::WesternTheory
class SonicPiError < StandardError ; end
class AssertionError < SonicPiError ; end
class TimingError < SonicPiError ; end
class ZeroTimeLoopError < TimingError ; end
class NotImmutableError < SonicPiError ; end
class TimeTravelError < SonicPiError ; end
class LiveLockError < SonicPiError ; end
class DeprecationError < SonicPiError ; end
class MapArgError < SonicPiError ; end
THREAD_RAND_SEED_MAX = 10e20
class TimeStateLookup
def initialize(blk)
@blk = blk
end
def [](*args)
@blk.call(*args)
end
end
# Wrap Time so that it always displays to millisecond precision
class MilliTime < Time
def at(*args)
MilliTime.new Time.at(*args)
end
def inspect()
strftime "%Y-%m-%d %H:%M:%S.%L %z"
end
end
def __cue_path_segment(s)
s = String.new(s.to_s)
s.gsub!(/[\s#*,?\/\[\]{}]/, '_')
s.freeze
end
def __cue_path(s, prefix='cue')
s = s.to_s
if s.start_with?('/')
s = String.new("#{s}")
else
s = String.new("/#{prefix}/#{s}")
end
# convert all characters not allowed in
# OSC path seg to underscores
s.gsub!(/[\s#*,?\[\]{}]/, '_')
s.freeze
end
def __sync_path(s)
if s.is_a?(Symbol)
return "/{cue,set,live_loop}/#{__cue_path_segment(s)}".freeze
end
s = s.to_s
if s.start_with?('/')
s = String.new("#{s}")
else
s = String.new("/cue/#{s}")
end
s.freeze
s
end
def live_state(*args)
get(*args)
end
def __cueset(k, val, prefix)
if k.is_a?(Symbol)
path = __cue_path(k, prefix)
cue_path = [path, k.inspect]
else
cue_path = __cue_path(k)
path = cue_path
end
t = __get_spider_time
b = __get_spider_beat
i = __current_thread_id
d = __system_thread_locals.get(:sonic_pi_spider_thread_delta)
__system_thread_locals.set_local(:sonic_pi_spider_thread_delta, d + 1)
p = __system_thread_locals.get(:sonic_pi_spider_thread_priority, 0)
m = current_bpm_mode
ce = CueEvent.new(t, p, i, d, b, m, cue_path, val)
# update thread local time state cache
cache = __system_thread_locals.get(:sonic_pi_spider_time_state_cache, [])
cache.unshift [path, ce]
__system_thread_locals.set_local(:sonic_pi_spider_time_state_cache, cache)
# TODO - correctly add sched ahead time here after thread
# waiting has been implemented
# @register_cue_event_lambda.call(t, p, i, d, b, m, cue_path, val, current_sched_ahead_time)
@register_cue_event_lambda.call(t, p, i, d, b, m, cue_path, val, __current_sched_ahead_time)
unless __thread_locals.get(:sonic_pi_suppress_cue_logging)
if val.nil?
__delayed_highlight_message "#{prefix} #{k.inspect}"
else
if is_list_like?(val)
__delayed_highlight_message "#{prefix} #{k.inspect}, #{val}"
else
__delayed_highlight_message "#{prefix} #{k.inspect}, #{val.sp_log_inspect}"
end
end
end
val
end
def set(k, val)
__cueset(k, val, "set")
end
doc name: :set,
introduced: Version.new(3,0,0),
summary: "Store information in the Time State",
doc: "Store information in the Time State for the current time for either the current or any other thread. If called multiple times without an intervening call to `sleep`, `sync`, `set` or `cue`, the last value set will prevail. The value will remain in the Time State until overwritten by another call to `set`, or until Sonic Pi quits.
May be used within a `time_warp` to set past/future events. Does not affect time.",
args: [[:time_state_key, :default],
[:value, :anything]],
accepts_block: false,
examples: ["
set :foo, 1 #=> Stores the value 1 with key :foo",
"
set :foo, 3 # Set :foo to 3
get[:foo] #=> returns 3",
"
in_thread do
set :foo, 3 # Set :foo to 3
end
in_thread do
puts get[:foo] #=> always returns 3 (no race conditions here!)
end
"]
def cue(k, *opts)
splat_map_or_arr = []
if opts.size == 1 && opts[0].is_a?(Hash)
opts[0].each do |k, v|
raise ArgumentError, "Invalid cue key type. Must be a Symbol" unless k.is_a? Symbol
raise ArgumentError, "Invalid cue argument #{v.inspect} with key #{k.inspect} due to unrecognised type: (#{v.class}). Must be immutable - currently accepted types: numbers, symbols, booleans, nil and frozen strings, or vectors/rings/frozen arrays/maps of immutable values" unless v.sp_thread_safe?
end
splat_map_or_arr = opts[0]
else
opts.each_with_index do |v, idx|
v = v.__sp_make_thread_safe
raise ArgumentError, "Invalid cue argument #{v.inspect} in position #{idx} due to unrecognised type: (#{v.class}). Must be immutable - currently accepted types: numbers, symbols, booleans, nil and frozen strings, or vectors/rings/frozen arrays/maps of immutable values" unless v.sp_thread_safe?
end
splat_map_or_arr = opts.freeze
end
__cueset(k, splat_map_or_arr, "cue")
end
doc name: :cue,
introduced: Version.new(2,0,0),
summary: "Cue other threads",
doc: "Send a heartbeat synchronisation message containing the (virtual) timestamp of the current thread. Useful for syncing up external threads via the `sync` fn. Any opts which are passed are given to the thread which syncs on the `cue_id`. The values of the opts must be immutable. Currently numbers, symbols, booleans, nil and frozen strings, or vectors/rings/frozen arrays/maps of immutable values are supported.",
args: [[:cue_id, :symbol]],
opts: {:your_key => "Your value",
:another_key => "Another value",
:key => "All these opts are passed through to the thread which syncs"},
accepts_block: false,
examples: ["
in_thread do
sync :foo # this parks the current thread waiting for a foo cue message to be received.
sample :ambi_lunar_land
end
sleep 5
cue :foo # We send a cue message from the main thread.
# This then unblocks the thread above and we then hear the sample",
"
in_thread do # Start a metronome thread
loop do # Loop forever:
cue :tick # sending tick heartbeat messages
sleep 0.5 # and sleeping for 0.5 beats between ticks
end
end
# We can now play sounds using the metronome.
loop do # In the main thread, just loop
sync :tick # waiting for :tick cue messages
sample :drum_heavy_kick # after which play the drum kick sample
end",
"
in_thread do # Start a metronome thread
loop do # Loop forever:
cue [:foo, :bar, :baz].choose # sending one of three tick heartbeat messages randomly
sleep 0.5 # and sleeping for 0.5 beats between ticks
end
end
# We can now play sounds using the metronome:
in_thread do
loop do # In the main thread, just loop
sync :foo # waiting for :foo cue messages
sample :elec_beep # after which play the elec beep sample
end
end
in_thread do
loop do # In the main thread, just loop
sync :bar # waiting for :bar cue messages
sample :elec_flip # after which play the elec flip sample
end
end
in_thread do
loop do # In the main thread, just loop
sync :baz # waiting for :baz cue messages
sample :elec_blup # after which play the elec blup sample
end
end",
"
in_thread do
loop do
cue :tick, foo: 64 # sending tick heartbeat messages with a value :foo
sleep 0.5
end
end
# The value for :foo can now be used in synced threads
loop do
values = sync :tick
play values[:foo] # play the note value from :foo
end",
]
def __osc_match(matcher_path, osc_path)
# returns true if matcher matches osc_path
t = 0
p = 0
i = 0
d = 0
b = 0
m = 60
v = []
n = matcher_path
ce = CueEvent.new(t, p, i, d, b, m, n, v)
SonicPi::EventMatcher.new(ce).path_match(osc_path)
end
def get_event(*args)
if args.empty?
lookup = lambda { |*args| get_event(*args) }
return TimeStateLookup.new(lookup)
else
k, _default = args
k = __sync_path(k)
# If we've time_warped into the future raise a timing exception
if __system_thread_locals.get(:sonic_pi_spider_in_time_warp)
if __system_thread_locals.get(:sonic_pi_spider_time_warp_start) < __get_spider_time
raise TimingError, "Sadly, you may not time_warp into the future to call get, then bring the result back in time to now."
end
end
cache = __system_thread_locals.get(:sonic_pi_spider_time_state_cache, [])
match_idx = cache.find_index { |x| __osc_match(k, x[0]) }
if match_idx
return cache[match_idx][1]
end
t = __get_spider_time
b = __get_spider_beat
i = __current_thread_id
d = __system_thread_locals.get(:sonic_pi_spider_thread_delta)
p = __system_thread_locals.get(:sonic_pi_spider_thread_priority, 1001)
m = current_bpm_mode
@event_history.get(t, p, i, d, b, m, k)
end
end
def get(*args)
if args.empty?
lookup = lambda { |*args| get(*args) }
return TimeStateLookup.new(lookup)
else
params, opts = split_params_and_merge_opts_array(args)
default = params[1] || opts[:default]
res = get_event(params[0])
return res.val if res
return default
end
end
doc name: :get,
introduced: Version.new(3,0,0),
summary: "Get information from the Time State",
doc: "Retrieve information from Time State set prior to the current time from either the current or any other thread. If called multiple times will always return the same value unless a call to `sleep`, `sync`, `set` or `cue` is interleaved. Also, calls to `get` will always return the same value across Runs for deterministic behaviour - which means you may safely use it in your compositions for repeatable music. If no value is stored with the relevant key, will return `nil`.
May be used within a `time_warp` to retrieve past events. If in a time warp, `get` can not be called from a future position. Does not advance time.",
args: [[:time_state_key, :default]],
accepts_block: false,
examples: ["
get :foo #=> returns the last value set as :foo, or nil",
"
set :foo, 3
get[:foo] #=> returns 3",
"
in_thread do
set :foo, 3
end
in_thread do
puts get[:foo] #=> always returns 3 (no race conditions here!)
end
"]
def current_beat
beat
end
def with_swing(*args, &blk)
raise ArgumentError, "with_swing must be called with a do/end block." unless blk
params, opts = split_params_and_merge_opts_array(args)
shift = params[0] || opts.fetch(:shift, 0.1)
pulse = params[1] || opts.fetch(:pulse, 4)
key = (params[2] || opts.fetch(:tick, :swing)).to_sym
offset = params[3] || opts.fetch(:offset, 0)
raise ArgumentError, "with_swing shift should be a number. Got: #{shift.inspect}" unless shift.is_a?(Numeric)
raise ArgumentError, "with_swing pulse should be a positive number. Got: #{pulse.inspect}" unless pulse.is_a?(Numeric) && pulse > 0
raise ArgumentError, "with_swing offset should be an integer. Got: #{offset.inspect}" unless offset.is_a?(Integer)
use_shift = ((tick(key) + offset) % pulse) == 0
if use_shift
time_warp shift do
blk.call
end
else
blk.call
end
nil
end
doc name: :with_swing,
introduced: Version.new(3,0,0),
summary: "Add swing to successive calls to do/end block",
args: [[:shift, :beats], [:pulse, :number], [:tick, :symbol], [:offset, :number]],
returns: nil,
opts: {shift: "How much time to delay/forward the block. Greater values produce more emphasised swing. Defaults to 0.1 beats.",
pulse: "How often to apply the swing. Defaults to 4.",
tick: "A key for the tick with which to count pulses. Override this if you have more than one `with_swing` block in your `live_loop` or thread to stop them interfering with each other.",
offset: "Count offset - before modding the count with the pulse size - integer offset to add to the result of calling `tick` with the specified tick key (via the `tick:` opt)"},
accepts_block: false,
doc: "Runs block within a `time_warp` except for once every `pulse` consecutive runs (defaulting to 4). When used for rhythmical purposes this results in one in every `pulse` calls of the block being 'on beat' and the rest shifted forward or backwards in time by `shift` beats.",
examples: ["
live_loop :foo do
with_swing 0.1 do
sample :elec_beep # plays the :elec_beep sample late except on the 1st beat of every 4
end
sleep 0.25
end
",
"
live_loop :foo do
with_swing -0.1 do
sample :elec_beep # plays the :elec_beep sample slightly early
end # on the 1st beat of every 4
sleep 0.25
end
",
"
live_loop :foo do
with_swing -0.1, pulse: 8 do
sample :elec_beep # plays the :elec_beep sample slightly early
end # on the 1st beat of every 8
sleep 0.25
end
",
"
# Use unique tick names if you plan on using with_swing
# more than once in any given live_loop or thread.
live_loop :foo do
with_swing 0.14, tick: :a do
sample :elec_beep # plays the :elec_beep sample slightly late
end # on the 1st beat of every 4
with_swing -0.1, tick: :b do
sample :elec_beep, rate: 2 # plays the :elec_beep sample at double rate
end # slightly early except on the 1st beat of every 4
sleep 0.25
end",
"
live_loop :foo do
with_swing 0.1 do
cue :tick # send out cue messages with swing timing
end
sleep 0.25
end
live_loop :bar do
sync :tick
sample :elec_beep # sync on the swing cue messages to bring the swing into
# another live loop (sync will match the timing and clock of
# the sending live loop)
end
",
"
live_loop :foo do
with_swing 0.1, offset: 2 do
sample :elec_beep # plays the :elec_beep sample slightly late
end # on the the 3rd beat of every 4
sleep 0.25
end
",
"
live_loop :foo do
with_swing 0.1, pulse: 2, offset: 1 do
sample :elec_beep # plays the :elec_beep sample slightly late
end # on the 2nd beat of every 2
sleep 0.25
end
"
]
def run_file(path)
path = File.expand_path(path.to_s)
raise IOError, "Unable to run file - no file found with path: #{path}" unless File.exist?(path)
__spider_eval(File.read(path))
end
doc name: :run_file,
introduced: Version.new(2,11,0),
summary: "Evaluate the contents of the file as a new Run",
args: [[:filename, :path]],
returns: nil,
opts: nil,
accepts_block: false,
doc: "Reads the full contents of the file with `path` and executes it in a new Run. This works as if the code in the file was in a buffer and Run button was pressed.",
examples: ["
run_file \"~/path/to/sonic-pi-code.rb\" #=> will run the contents of this file"]
def run_code(code)
__spider_eval(code.to_s)
end
doc name: :run_code,
introduced: Version.new(2,11,0),
summary: "Evaluate the code passed as a String as a new Run",
args: [[:code, :string]],
returns: nil,
opts: nil,
accepts_block: false,
doc: "Executes the code passed as a string in a new Run. This works as if the code was in a buffer and Run button was pressed.",
examples: ["
run_code \"sample :ambi_lunar_land\" #=> will play the :ambi_lunar_land sample",
"# Works with any amount of code:
run_code \"8.times do\nplay 60\nsleep 1\nend\" # will play 60 8 times"]
def eval_file(path)
path = File.expand_path(path.to_s)
raise IOError, "Unable to run file - no file found with path: #{path}" unless File.exist?(path)
eval(File.read(path))
end
doc name: :eval_file,
introduced: Version.new(3,2,0),
summary: "Evaluate the contents of the file inline in the current thread like a function.",
args: [[:filename, :path]],
returns: nil,
opts: nil,
accepts_block: false,
doc: "Reads the full contents of the file with `path` and executes within the current thread like a function call.",
examples: ["
eval_file \"~/path/to/sonic-pi-code.rb\" #=> will run the contents of this file"]
def use_osc_logging(v, &block)
raise DeprecationError, "use_osc_logging does not work with a do/end block. Perhaps you meant with_osc_logging" if block
__thread_locals.set(:sonic_pi_suppress_osc_logging, !v)
end
doc name: :use_osc_logging,
introduced: Version.new(3,0,0),
summary: "Enable and disable OSC logging",
doc: "Enable or disable log messages created on OSC functions. This does not disable the OSC functions themselves, it just stops them from being printed to the log",
args: [[:true_or_false, :boolean]],
opts: nil,
accepts_block: false,
examples: ["use_osc_logging true # Turn on OSC logging", "use_osc_logging false # Disable OSC logging"]
def with_osc_logging(v, &block)
raise ArgumentError, "with_osc_logging requires a do/end block. Perhaps you meant use_osc_logging" unless block
current = __thread_locals.get(:sonic_pi_suppress_osc_logging)
__thread_locals.set(:sonic_pi_suppress_osc_logging, !v)
block.call
__thread_locals.set(:sonic_pi_suppress_osc_logging, current)
end
doc name: :with_osc_logging,
introduced: Version.new(3,0,0),
summary: "Block-level enable and disable OSC logging",
doc: "Similar to use_osc_logging except only applies to code within supplied `do`/`end` block. Previous OSC log value is restored after block.",
args: [[:true_or_false, :boolean]],
opts: nil,
accepts_block: true,
requires_block: true,
examples: ["
# Turn on OSC logging:
use_osc_logging true
osc \"/foo\" # message is printed to log
with_osc_logging false do
#OSC logging is now disabled
osc \"/foo\" # OSC message *is* sent but not displayed in log
end
sleep 1
# Debug is re-enabled
osc \"/foo\" # message is displayed in log
"]
def use_osc(host, port=4560)
host = host.to_s.strip
host_and_port = (host.include? ":") ? host : (host + ":" + port.to_s)
__thread_locals.set :sonic_pi_osc_client, host_and_port.freeze
end
doc name: :use_osc,
introduced: Version.new(3,0,0),
summary: "Set the default hostname and port number for outgoing OSC messages.",
args: [[:hostname, :string], [:port, :number]],
returns: nil,
opts: nil,
accepts_block: false,
doc: "Sets the destination host and port that `osc` will send messages to. If no port number is specified - will default to port 4560 (Sonic Pi's default OSC listening port).
OSC (Open Sound Control) is a simple way of passing messages between two separate programs on the same computer or even on different computers via a local network or even the internet. `use_osc` allows you to specify which computer (`hostname`) and program (`port`) to send messages to.
It is possible to send messages to the same computer by using the host name `\"localhost\"`.
This is a thread-local setting - therefore each thread (or live loop) can have their own separate `use_osc` values.
Note that calls to `osc_send` will ignore these values.
",
examples: [
" # Send a simple OSC message to another program on the same machine
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
osc \"/foo/bar\" # Send an OSC message with path \"/foo/bar\"
# and no arguments
",
" # Send an OSC message with arguments to another program on the same machine
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
osc \"/foo/bar\" 1, 3.89, \"baz\" # Send an OSC message with path \"/foo/bar\"
# and three arguments:
# 1) The whole number (integer) 1
# 2) The fractional number (float) 3.89
# 3) The string \"baz\"
",
" # Send an OSC message with arguments to another program on a different machine
use_osc \"10.0.1.5\", 7000 # Specify port 7000 on the machine with address 10.0.1.5
osc \"/foo/bar\" 1, 3.89, \"baz\" # Send an OSC message with path \"/foo/bar\"
# and three arguments:
# 1) The whole number (integer) 1
# 2) The fractional number (float) 3.89
# 3) The string \"baz\"
",
" # use_osc only affects calls to osc until the next call to use_osc
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
osc \"/foo/bar\" # Send an OSC message to port 7000
osc \"/foo/baz\" # Send another OSC message to port 7000
use_osc \"localhost\", 7005 # Specify port 7005 on this machine
osc \"/foo/bar\" # Send an OSC message to port 7005
osc \"/foo/baz\" # Send another OSC message to port 7005
",
" # threads may have their own use_osc value
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
live_loop :foo do
osc \"/foo/bar\" # Thread inherits outside use_osc values
sleep 1 # and therefore sends OSC messages to port 7000
end
live_loop :bar do
use_osc \"localhost\", 7005 # Override OSC hostname and port for just this
# thread (live loop :bar). Live loop :foo is
# unaffected.
osc \"/foo/bar\" # Send OSC messages to port 7005
sleep 1
end
use_osc \"localhost\", 7010 # Specify port 7010
osc \"/foo/baz\" # Send another OSC message to port 7010
# Note that neither live loops :foo or :bar
# are affected (their use_osc values are
# independent and isolated.
",
]
def with_osc(host, port=4560, &block)
raise ArgumentError, "with_osc must be called with a do/end block. Perhaps you meant use_osc" unless block
host = host.to_s.strip
current_host_and_port = __thread_locals.get(:sonic_pi_osc_client)
use_osc(host, port)
res = block.call
__thread_locals.set(:sonic_pi_osc_client, current_host_and_port)
res
end
doc name: :with_osc,
introduced: Version.new(3,0,0),
summary: "Block-level setting for the default hostname and port number of outgoing OSC messages.",
args: [[:hostname, :string], [:port, :number]],
returns: nil,
opts: nil,
accepts_block: true,
doc: "Sets the destination host and port that `osc` will send messages to for the given do/end block.",
examples: [
"
use_osc \"localhost\", 7000 # Specify port 7000
osc \"/foo/baz\" # Send an OSC message to port 7000
with_osc \"localhost\", 7010 do # set hostname and port for the duration
# of this do/end block
osc \"/foo/baz\" # Send an OSC message to port 7010
end
osc \"/foo/baz\" # Send an OSC message to port 7000
# as old setting is restored outside
# do/end block
" ]
# def hydra(code)
# t = __get_spider_schedule_time
# @tau_api.hydra_eval_at(t, code)
# end
# doc name: :hydra,
# introduced: Version.new(5,0,0),
# summary: "Update Hydra sketch within Tau",
# args: [[:code, :string]],
# returns: nil,
# opts: nil,
# accepts_block: false,
# doc: "Update Hydra sketch running within Tau's main window and all connected browsers. See https://hydra.ojack.xyz/api for a list of available functions and examples.",
# examples: [
# "
# hydra \"osc(10,0,1).scrollY(0.5,0).out(o0)\"
# "
# ]
def osc_send(host, port, path, *args)
host = host.to_s.strip
t = __get_spider_schedule_time
@tau_api.send_osc_at(t, host, port, path, *args)
__delayed_message "OSC -> #{host}, #{port}, #{path}, #{args}" unless __thread_locals.get(:sonic_pi_suppress_osc_logging)
end
doc name: :osc_send,
introduced: Version.new(3,0,0),
summary: "Send an OSC message to a specific host and port",
args: [[:hostname, :string], [:port, :number], [:path, :osc_path], [:args, :list]],
returns: nil,
opts: nil,
accepts_block: true,
doc: "Similar to `osc` except ignores any `use_osc` settings and sends the OSC message directly to the specified `hostname` and `port`.
See `osc` for more information.",
examples: [
"
osc_send \"localhost\", 7000, \"/foo/baz\" # Send an OSC message to port 7000 on the same machine
",
"
use_osc \"localhost\", 7010 # set hostname and port
osc \"/foo/baz\" # Send an OSC message to port 7010
osc_send \"localhost\", 7000, \"/foo/baz\" # Send an OSC message to port 7000
# (ignores use_osc settings)
" ]
def osc(path, *args)
host_and_port = __thread_locals.get :sonic_pi_osc_client
raise ArgumentError, "Please specify a destination with use_osc or with_osc" unless host_and_port
path = "/#{path}" if path.is_a? Symbol
host, port = host_and_port.split ":"
port = port.to_i
t = __get_spider_schedule_time
@tau_api.send_osc_at(t, host, port, path, *args)
__delayed_message "OSC -> #{host}, #{port}, #{path}, #{args}" unless __thread_locals.get(:sonic_pi_suppress_osc_logging)
end
doc name: :osc,
introduced: Version.new(3,0,0),
summary: "Send an OSC message (Open Sound Control)",
args: [[:path, :arguments]],
returns: nil,
opts: nil,
accepts_block: false,
doc: "Sends an OSC message to the current host and port specified by `use_osc` or `with_osc`.
OSC (Open Sound Control) is a simple way of passing messages between two separate programs on the same computer or even on different computers via a local network or even the internet. `osc` enables you to send well-timed OSC messages from within Sonic Pi. `osc` will ensure that the OSC message is sent at the correct time using the same timing system shared with the synthesis functionality via `sample`, `synth` and friends. `osc` even works seamlessly within `time_warp` - see examples.
A typical OSC message has two parts: a descriptive `path` which looks similar to a URL (website address), and an optional list of `arguments` that are either numbers or strings.
For example, a hypothetical synth program might accept this OSC message:
`/set/filter lowpass 80 0.5`
where `/set/filter` is the path, and `lowpass`, `80`, and `0.5` are three
arguments. This can be sent from within Sonic Pi by writing:
`osc \"/set/filter\", \"lowpass\", 80, 0.5`
However, in order to send the OSC message you must first specify where to send it to. This is achieved by specifying both the host (the machine's internet address) and the port that the remote OSC server is listening on. This is configured using `use_osc` or `with_osc`. So, if our synth program was running on a machine on the local network with IP address `10.0.1.5` on port `5100` we could send our OSC message to it with the following:
`use_osc \"10.0.1.5\", 5100`
`osc \"/set/filter\", \"lowpass\", 80, 0.5`
Note, by default, Sonic Pi listens for OSC messages on port `4560`, so you may send messages to an external machine running Sonic Pi if you know the IP address of that external machine. Any OSC messages received on port `4560` are automatically converted to standard cue events and displayed in the GUI's cue log. This also means that you can use `sync` to wait for the next incoming OSC message with a given path (see example).
Finally, it is also very useful to send OSC messages to other programs on the same computer. This can be achieved by specifying \"localhost\" as the hostname and the port as normal (depending on which port the other program is listening on).
See `osc_send` for a version which allows you to specify the hostname and port directly (ignoring any values set via `use_osc` or `with_osc`).
For further information see the OSC spec: [https://opensoundcontrol.stanford.edu/spec-1_0.html](https://opensoundcontrol.stanford.edu/spec-1_0.html)
",
examples: [
" # Send a simple OSC message to another program on the same machine
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
osc \"/foo/bar\" # Send an OSC message with path \"/foo/bar\"
# and no arguments
",
" # Send an OSC message with arguments to another program on the same machine
use_osc \"localhost\", 7000 # Specify port 7000 on this machine
osc \"/foo/bar\", 1, 3.89, \"baz\" # Send an OSC message with path \"/foo/bar\"
# and three arguments:
# 1) The whole number (integer) 1
# 2) The fractional number (float) 3.89
# 3) The string \"baz\"
",
" # Send an OSC message with arguments to another program on a different machine
use_osc \"10.0.1.5\", 7000 # Specify port 7000 on the machine with address 10.0.1.5
osc \"/foo/bar\", 1, 3.89, \"baz\" # Send an OSC message with path \"/foo/bar\"
# and three arguments:
# 1) The whole number (integer) 1
# 2) The fractional number (float) 3.89
# 3) The string \"baz\"
",
" # OSC messages honour the timing system
osc \"/foo/bar\" # Send an OSC message with path /foo/bar at *exactly* the
play 60 # same time as note 60 is played
sleep 1 # Wait for 1 beat
osc \"/baz/quux\" # Send an OSC message with path /baz/quux at *exactly* the
play 72 # same time as note 72 is played
",
" # Send a incrementing OSC counter
live_loop :foo do # Start a live loop called :foo
osc \"/counter\", tick # Send an OSC message with the path /counter
# with successive whole numbers (0, 1, 2, 3.. etc.)
# each time round the live loop
sleep 1 # Repeat the live loop every 1 beat
end
",
" # OSC messages can be sent from within time_warp
time_warp 0.5 do
osc \"/foo/bar\" # Send an OSC message with path /foo/bar at 0.5 beats
end
sleep 1 # Wait for 1 beat
time_warp -0.1 do
osc \"/baz/quux\" # Send an OSC message with path /baz/quux at 0.9 beats
end
"
]
def reset
__thread_locals.reset!
end
doc name: :reset,
introduced: Version.new(2,11,0),
summary: "Reset all thread locals",
args: [],
returns: nil,
opts: nil,
accepts_block: false,
doc: "All settings such as the current synth, BPM, random stream and tick values will be reset to the values inherited from the parent thread. Consider using `clear` to reset all these values to their defaults.",
examples: ["
# Basic Reset
use_synth :blade
use_octave 3
puts \"before\" #=> \"before\"
puts current_synth #=> :blade
puts current_octave #=> 3
puts rand #=> 0.75006103515625
puts tick #=> 0
reset
puts \"after\" #=> \"after\"
puts current_synth #=> :beep
puts current_octave #=> 0
puts rand #=> 0.75006103515625
puts tick #=> 0",
"Reset remembers defaults from when the thread was created:
use_synth :blade
use_octave 3
puts \"before\" #=> \"before\"
puts current_synth #=> :blade
puts current_octave #=> 3
puts rand #=> 0.75006103515625
puts tick #=> 0
at do
use_synth :tb303
puts rand #=> 0.9287109375
reset
puts \"thread\" #=> \"thread\"
# The call to reset ensured that the current
# synth was returned to the the state at the
# time this thread was started. Thus any calls
# to use_synth between this line and the start
# of the thread are ignored
puts current_synth #=> :blade
puts current_octave #=> 3
# The call to reset ensured
# that the random stream was reset
# to the same state as it was when
# the current thread was started
puts rand #=> 0.9287109375
puts tick #=> 0
end"]
def clear
__thread_locals.clear!
__set_default_user_thread_locals!
end
doc name: :clear,
introduced: Version.new(2,11,0),
summary: "Clear all thread locals to defaults",
args: [],
returns: nil,
opts: nil,
accepts_block: false,
doc: "All settings such as the current synth, BPM, random stream and tick values will be reset to their defaults. Consider using `reset` to reset all these values to those inherited from the parent thread.",
examples: [
"Clear wipes out the threads locals
use_synth :blade
use_octave 3
puts \"before\" #=> \"before\"
puts current_synth #=> :blade
puts current_octave #=> 3
puts rand #=> 0.75006103515625
puts tick #=> 0
at do
use_synth :tb303
puts rand #=> 0.9287109375
clear
puts \"thread\" #=> \"thread\"
# The clear reset the current synth to the default
# of :beep. We are therefore ignoring any inherited
# synth settings. It is as if the thread was a completely
# new Run.
puts current_synth #=> :beep
# The current octave defaults back to 0
puts current_octave #=> 0
# The random stream defaults back to the standard
# stream used by every new Run.
puts rand #=> 0.75006103515625
puts tick #=> 0
end"
]
def time_warp(times=0, params=nil, &block)
__schedule_delayed_blocks_and_messages!
raise ArgumentError, "time_warp requires a do/end block" unless block
prev_ctl_deltas = __system_thread_locals.get(:sonic_pi_local_control_deltas)
prev_cache = __system_thread_locals.get(:sonic_pi_spider_time_state_cache, [])
prev_slept = __system_thread_locals.get(:sonic_pi_spider_slept)
prev_synced = __system_thread_locals.get(:sonic_pi_spider_synced)
had_params = params
times = [times] if times.is_a? Numeric
# When no params are specified, pass the times through as params
params ||= times
params_size = params.size
raise ArgumentError, "params needs to be a list-like thing" unless params.respond_to? :[]
raise ArgumentError, "times needs to be a list-like thing" unless times.respond_to? :each_with_index