File: core.rb

package info (click to toggle)
sonic-pi 3.2.2~repack-12
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 71,960 kB
  • sloc: ruby: 30,548; cpp: 8,490; sh: 963; ansic: 461; erlang: 360; lisp: 141; makefile: 28
file content (1164 lines) | stat: -rwxr-xr-x 24,992 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
#!/usr/bin/env ruby
#--
# 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/master/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.
#++

raise "Sonic Pi requires Ruby 2.4+ to be installed. You are using version #{RUBY_VERSION}" if RUBY_VERSION < "2.4"

begin
  require 'did_you_mean'
rescue LoadError
  warn "Non-critical error: Could not load did_you_mean"
end

require 'wavefile'

module SonicPi
  module Core
    class ThreadLocal
      attr_reader :vars, :local_vars

      def initialize(parent=nil, overrides=nil)
        raise "ThreadLocal can only be initialized with nil or a parent ThreadLocal" unless parent.nil? || parent.is_a?(ThreadLocal)
        @parent_visible = true

        if parent && !parent.vars.empty?
          if overrides
            @parent_vars = parent.vars.merge(overrides)
            @vars = parent.vars.merge(overrides)
          else
            @parent_vars = parent.vars.dup
            @vars = parent.vars.dup
          end
        else
          overrides = {} unless overrides
          @parent_vars = overrides
          @vars = overrides
        end

        @local_vars = {}
      end

      def to_s
        "<ThreadLocal @vars: #{@vars}, @local_vars: #{@local_vars}"
      end

      def set(name, val)
        raise "Error setting Thread Local - value must be immutable. Got: #{val.inspect} for #{name.inspect}" unless val.sp_thread_safe?
        @vars[name] = val
        @local_vars.delete name
        val
      end

      def reset!
        @parent_visible = true
        @vars = @parent_vars.clone
        @local_vars = {}
      end

      def clear!
        @parent_visible = false
        @vars = {}
        @local_vars = {}
      end

      # These values will not be inherited
      def set_local(name, val)
        @local_vars[name] = val
        @vars.delete name
        val
      end

      def get(name, default=nil)
        if @local_vars.has_key? name
          return @local_vars[name]
        elsif @vars.has_key? name
          return @vars[name]
        elsif @parent_visible
          return @parent_vars.fetch(name, default)
        else
          return default
        end
      end

    end
  end
end



module SonicPi
  module Core
    module SPRand
      # Read in same random numbers as server for random stream sync
      @@random_numbers = ::WaveFile::Reader.new(File.exist?(File.expand_path("../../../../etc/buffers/rand-stream.wav", __FILE__)) ? File.expand_path("../../../../etc/buffers/rand-stream.wav", __FILE__) : "/usr/share/sonic-pi/buffers/rand-stream.wav", ::WaveFile::Format.new(:mono, :float, 44100)).read(441000).samples.freeze

      def self.tl_seed_map(seed, idx=0)
        {:sonic_pi_spider_random_gen_seed => seed,
          :sonic_pi_spider_random_gen_idx => idx}
      end

      def self.__thread_locals(t = Thread.current)
        tls = t.thread_variable_get(:sonic_pi_thread_locals)
        tls = t.thread_variable_set(:sonic_pi_thread_locals, SonicPi::Core::ThreadLocal.new) unless tls
        return tls
      end

      def self.to_a
        @@random_numbers
      end

      def self.inc_idx!(increment=1, init=0)
        ridx = __thread_locals.get(:sonic_pi_spider_random_gen_idx, init)
        __thread_locals.set :sonic_pi_spider_random_gen_idx, ridx + increment
        ridx
      end

      def self.dec_idx!(decrement=1, init=0)
        ridx = __thread_locals.get(:sonic_pi_spider_random_gen_idx, init)
        __thread_locals.set :sonic_pi_spider_random_gen_idx, ridx - decrement
        ridx
      end

      def self.set_seed!(seed, idx=0)
        __thread_locals.set :sonic_pi_spider_random_gen_seed, seed
        __thread_locals.set :sonic_pi_spider_random_gen_idx, idx
      end

      def self.set_idx!(idx)
        __thread_locals.set :sonic_pi_spider_random_gen_idx, idx
      end

      def self.get_seed_and_idx
        [__thread_locals.get(:sonic_pi_spider_random_gen_seed),
          __thread_locals.get(:sonic_pi_spider_random_gen_idx)]
      end

      def self.get_seed
        __thread_locals.get(:sonic_pi_spider_random_gen_seed) || 0
      end

      def self.get_idx
        __thread_locals.get(:sonic_pi_spider_random_gen_idx) || 0
      end

      def self.get_seed_plus_idx
        (__thread_locals.get(:sonic_pi_spider_random_gen_idx) || 0) +
          __thread_locals.get(:sonic_pi_spider_random_gen_seed) || 0
      end

      def self.rand!(max=1, idx=nil)
        idx = inc_idx! unless idx
        rand_peek(max, idx)
      end

      def self.rand_peek(max=1, idx=nil, seed=nil)
        idx = get_idx unless idx
        seed = get_seed unless seed
        idx = seed + idx
        # we know that the fixed rand stream has length 441000
        # also, scsynth server seems to swallow first rand
        # so always add 1 to index
        idx = (idx + 1) % 441000
        @@random_numbers[idx] * max
      end

      def self.rand_i!(max, idx=nil)
        rand!(max, idx).to_i
      end

    end

    module TLMixin
      def tick(*args)
        idx = SonicPi::Core::ThreadLocalCounter.tick(*args)
        self.ring[idx]
      end

      def look(*args)
        idx = SonicPi::Core::ThreadLocalCounter.look(*args)
        self.ring[idx]
      end
    end

    module ThreadLocalCounter

      def self.__thread_locals(t = Thread.current)
        tls = t.thread_variable_get(:sonic_pi_thread_locals)
        tls = t.thread_variable_set(:sonic_pi_thread_locals, SonicPi::Core::ThreadLocal.new) unless tls
        return tls
      end

      def self.get_or_create_counters
        counters = __thread_locals.get(:sonic_pi_local_core_thread_local_counters)
        return counters if counters
        counters = {}
        __thread_locals.set_local(:sonic_pi_local_core_thread_local_counters, counters)
        counters
      end

      def self.tick(k = :___sonic_pi_default_tick_key___, *args)
        k = (k && k.is_a?(String)) ? k.to_sym : k
        if k.is_a? Symbol
          opts = args.first || {}
        else
          opts = k
          k = :___sonic_pi_default_tick_key___
        end

        raise "Tick key must be a symbol, got #{k.class}: #{k.inspect}" unless k.is_a? Symbol
        raise "Tick opts must be key value pairs, got: #{opts.inspect}" unless opts.is_a? Hash
        step = opts[:step] || 1
        offset = opts[:offset] || 0
        counters = get_or_create_counters
        if counters[k]
          _, next_val = *counters[k]
          counters[k] = [next_val + step-1, next_val + step]
          return next_val + step-1 + offset
        else
          counters[k] = [step-1, step]
          return step-1 + offset
        end
      end

      def self.look(k = :___sonic_pi_default_tick_key___, *args)
        k = (k && k.is_a?(String)) ? k.to_sym : k
        if k.is_a? Symbol
          opts = args.first || {}
        else
          opts = k
          k = :___sonic_pi_default_tick_key___
        end

        raise "Tick key must be a symbol, got #{k.class}: #{k.inspect}" unless k.is_a? Symbol
        offset = opts[:offset] || 0
        counters = get_or_create_counters
        val, _ = *counters[k]
        return (val || 0) + offset
      end

      def self.set(k=:___sonic_pi_default_tick_key___, v)
        if k.is_a? Numeric
          v = k
          k = :___sonic_pi_default_tick_key___
        end
        raise "Tick key must be a symbol, got #{k.class}: #{k.inspect}" unless k.is_a? Symbol
        raise "Tick value must be a number, got #{v.class}: #{v.inspect}" unless v.is_a? Numeric
        counters = get_or_create_counters
        counters[k] = [v, v]
        v
      end

      def self.rm(k=:___sonic_pi_default_tick_key___)
        raise "Tick key must be a symbol, got #{k.class}: #{k.inspect}" unless k.is_a? Symbol
        counters = get_or_create_counters
        counters.delete(k)
        nil
      end

      def self.reset_all
        __thread_locals.set_local(:sonic_pi_local_core_thread_local_counters, {})
        nil
      end
    end
  end
end


module SonicPi
  module Core
    class EmptyVectorError < StandardError ; end
    class InvalidIndexError < StandardError ; end
    class NotThreadSafeError < StandardError ; end


    class SPMap
      attr_reader :map

      def initialize(*args)
        @map = Hash[*args]
        @map.freeze
        res = @map.all? {|k, v| k.sp_thread_safe? && v.sp_thread_safe?}
        @sp_thread_safe = !!res
      end

      def sp_thread_safe?
        @sp_thread_safe
      end

      def sp_log_inspect
        if @map.empty?
          return "(map)"
        else
          s = String.new("(map ")
          longest_key = keys.to_a.map(&:to_s).map(&:size).sort[-1] + 2
          @map.each do |k, v|
            if k.is_a?(Symbol)
              pk = "#{k.to_s}:".ljust(longest_key)
              s << "#{pk} #{v.inspect},\n       "
            else
              s << "#{k.inspect.ljust(longest_key)} => #{v.inspect},\n       "
            end
          end
          s.strip!.chomp!(",")
          s << ")"
        end
        return s
      end

      def inspect
        if @map.empty?
          return "(map)"
        else
          s = String.new("(map ")
          @map.each do |k, v|
            if k.is_a?(Symbol)
              pk = "#{k.to_s}:"
              s << "#{pk} #{v.inspect}, "
            else
              s << "#{k.inspect} => #{v.inspect}, "
            end
          end
          s.chomp!(", ")
          s << ")"
        end
        return s
      end

      def <(other)
        @map < other.map
      end

      def <=(other)
        @map <= other.map
      end


      def ==(other)
        other.map == @map
      end

      def >(other)
        @map > other.map
      end

      def >=(other)
        @map >= other.map
      end

      def [](key)
        @map[key]
      end

      def any?(&block)
        @map.any?(&block)
      end

      def assoc(o)
        @map.assoc(o)
      end

      def compact
        self.class.new(@map.compact)
      end

      def dig(*keys)
        @map.dig(*keys)
      end

      def each(&block)
        @map.each(&block)
      end

      def each_key(&block)
        @map.each_key(&block)
      end

      def each_pair(&block)
        @map.each_pair(&block)
      end

      def empty?
        @map.empty?
      end

      def eql?(other)
        @map.eql?(other)
      end

      def fetch(*args, &block)
        @map.fetch(*args, &block)
      end

      def fetch_values(*args, &block)
        @map.fetch_values(*args, &block)
      end

      def filter(&block)
        self.class.new(@map.filter(&block))
      end

      def select(&block)
        self.class.new(@map.select(&block))
      end

      def flatten(*args)
        @map.flatten(*args)
      end

      def has_key?(k)
        @map.has_key?(k)
      end

      def has_value?(v)
        @map.has_value?(v)
      end

      def include?(k)
        @map.include?(k)
      end

      def invert
        self.class.new(@map.invert)
      end

      def key(v)
        @map.key(v)
      end

      def key?(v)
        @map.key?(v)
      end

      def keys
        SPVector.new(@map.keys)
      end

      def length
        @map.length
      end

      def size
        @map.size
      end

      def merge(*hs, &block)
        self.class.new(@map.merge(*hs, &block))
      end

      def rassoc(o)
        SPVector.new(@map.rassoc(o))
      end

      def reject(&block)
        self.class.new(@map.reject(&block))
      end

      def select(&block)
        self.class.new(@map.select(&block))
      end

      def slice(*keys)
        self.class.new(@map.slice(*keys))
      end

      def to_h
        @map.dup
      end

      def to_s
        inspect
      end

    end

    class SPVector
      include TLMixin
      attr_reader :vec

      def initialize(list)
        @vec = list
        @vec.freeze
        res = @vec.all? {|el| el.sp_thread_safe?}
        @thread_safe = !!res
      end

      def to_a
        @vec.dup
      end

      alias :to_ary :to_a

      def [](*idx)
        if idx.size == 1
          i = idx[0]
          case i
          when Range
            res = @vec[i.min, i.max]
            self.class.new(res) if res
          else
            @vec[map_index(i)]
          end
        else
          res = @vec[*idx]
          self.class.new(res) if res
        end
      end

      def *(i)
        self.class.new(@vec * i)
      end

      def &(v)
          self.class.new(@vec & v)
      end

      def +(other)
        case other
        when SPVector
          return self.class.new(@vec + other.vec)
        when Array
          return self.class.new(@vec + other)
        else
          o = other.to_f
          return self.class.new(@vec.map{|el| el + o})
        end
      end

      def -(other)
        case other
        when SPVector
          return self.class.new(@vec - other.vec)
        when Array
          return self.class.new(@vec - other)
        else
          o = other.to_f
          return self.class.new(@vec.map{|el| el - o})
        end
      end

      def <=>(other)
        @vec <=> other
      end

      def ==(other)
        other.class == self.class && other.vec == @vec
      end

      def all?(&block)
        @vec.all?(&block)
      end

      def any?(&block)
        @vec.any?(&block)
      end

      def compact
        self.class.new(@vec.compact)
      end

      def drop(n)
        self.class.new(@vec.drop(n))
      end

      def drop_last(n=1)
        self.class.new(@vec[0...(size-n)])
      end

      def each(&block)
        @vec.each(&block)
      end

      def each_with_index(&block)
        @vec.each_with_index(&block)
      end

      def empty?
        @vec.empty?
      end

      def eql?(other)
        other.class == self.class && @vec.eql?(other.vec)
      end

      def filter(&block)
        self.class.new(@vec.select(&block))
      end

      def first(n=nil)
        if n
          self.class.new(@vec.first(n))
        else
          @vec.first
        end
      end

      def flatten(*args)
        self.class.new(@vec.flatten(*args))
      end

      def flat_map(&block)
        self.class.new(@vec.flat_map(&block))
      end

      def index(*args, &block)
        @vec.index(*args, &block)
      end

      def join(*args)
        @vec.join(*args)
      end

      def last(n=nil)
        if n
          self.class.new(@vec.last(n))
        else
          @vec.last
        end
      end

      def length
        @vec.length
      end

      def map(&block)
        @vec.map(&block)
      end

      def max(n=nil, &block)
        if n
          self.class.new(@vec.max(n, &block))
        else
          @vec.max(&block)
        end
      end

      def min(n=nil, &block)
        if n
          self.class.new(@vec.min(n, &block))
        else
          @vec.min(&block)
        end
      end

      def reverse
        self.class.new(@vec.reverse)
      end

      def rotate(*args)
        self.class.new(@vec.rotate(*args))
      end

      def choose
        self[SonicPi::Core::SPRand.rand_i!(@vec.size)]
      end

      def sample
        choose
      end

      def size
        @vec.size
      end

      def shuffle
        self.class.new(@vec.shuffle)
      end

      def sort(&block)
        self.class.new(@vec.sort(&block))
      end

      def uniq(&block)
        self.class.new(@vec.uniq(&block))
      end

      def values_at(*args)
        self.class.new(@vec.values_at(*args))
      end

      def sp_thread_safe?
        return @thread_safe
      end

      def ___sp_vector_name
        "vector"
      end

      def __sp_make_thread_safe
        return self if @thread_safe
        self.class.new(map {|v| v.__sp_make_thread_safe })
      end

      def list_diff(other)
        self.class.new(@vec.to_a - other.to_a)
      end

      def list_concat(other)
        self.class.new(@vec.to_a + other.to_a)
      end

      def scale(val)
        val = val.to_f
        return self.class.new(@vec.map{|el| el * val})
      end

      def ring
        if is_a?(SonicPi::Core::SPVector)
          self
        else
          SonicPi::Core::RingVector.new(self)
        end
      end

      def ramp
        if is_a?(SonicPi::Core::RampVector)
          self
        else
          SonicPi::Core::RampVector.new(self)
        end
      end

      def to_s
        inspect
      end

      def reflect(n=1)
        res = self + self.reverse.drop(1)
        res = res + (res.drop(1) * (n - 1)) if n > 1
        res
      end

      def mirror(n=1)
        (self + self.reverse) * n
      end

      def repeat(n=2)
        n = 1 if n < 1
        self * n
      end

      def take_last(n=1)
        self if n >= size
        self[(size-n)..-1]
      end

      def butlast
        drop_last(1)
      end

      def take(n)
        return self.class.new([]) if n == 0
        return self.reverse.take(-n) if n < 0
        return self.class.new([]) if @vec.size < 1
        return self.class.new(@vec.take(n)) if n <= @vec.size
        self.class.new(@vec.cycle.take(n))
      end





      def pick(n=nil, *opts)
        # mangle args to extract nice behaviour
        if !n.is_a?(Numeric) && opts.empty?
          opts = n
          n = nil
        else
          opts = opts[0]
        end

        if opts.is_a?(Hash)
          s = opts[:skip]
        else
          s = nil
        end

        n = 1 unless n
        raise "pick requires n to be a number, got: #{n.inspect}" unless n.is_a? Numeric

        res = []

        if s
          raise "skip: opt needs to be a number, got: #{s.inspect}" unless s.is_a? Numeric
          s.times do
            self.choose
          end
        end

        n.times { res << self.choose }

        res.ring
      end

      def inspect
        a = self.to_a
        if a.empty?
          "(#{___sp_vector_name})"
        else
          "(#{___sp_vector_name} #{a.inspect[1...-1]})"
        end
      end

      def stretch(num_its)
        res = []
        self.each do |v|
          num_its.times do
            res << v
          end
        end
        self.class.new(res)
      end

      def map_index(idx)
        idx
      end
    end

    class RingVector < SPVector
      def map_index(idx)
        idx = idx % size
        return idx
      end

      def ___sp_vector_name
        "ring"
      end
    end

    class RampVector < SPVector
      def map_index(idx)
        idx = idx.to_i
        idx = [idx, size - 1].min
        idx = [idx, 0].max
        return idx
      end

      def ___sp_vector_name
        "ramp"
      end
    end


    # An immutable map which when used in a splat will
    # yield its vals
    class SPSplatMap < SPMap

      def initialize(h)
        raise "SPSplatMaps may only be initialised with a Hash. You supplied a #{h.class} with value #{h.inspect}" unless h.is_a?(Hash)
        super

        # as h is a standard Hash, the value insertion order is
        # preserved at this point. By sticking it into an array, we
        # guarantee preservation of this ofder after conversion to an
        # immutable Map
        @sp_orig_vals = h.values
      end

      def to_ary
        @sp_orig_vals.to_ary
      end
    end

  end
end

class Time
  def __sp_make_thread_safe
    return self if frozen?
    self.clone.freeze
  end
end


class String
  def sp_thread_safe?
    frozen?
  end

  def __sp_make_thread_safe
    return self if frozen?
    self.clone.freeze
  end

  def shuffle
    self.chars.to_a.shuffle.join
  end

  def ring
    self.chars.ring
  end
end

class Numeric
  # Upper bound - will clamp the value
  # to a value below max
  def max(other)
    return self if self <= other
    other
  end

  # Minimum bound - will clamp the value
  # to a value above min
  def min(other)
    return self if self >= other
    other
  end

  # Max and minimum bound - will clamp other
  # to a value below other and above -1 * other
  def clamp(other)
    self.max(other).min(other * -1)
  end
end

class Symbol
  def sp_thread_safe?
    true
  end

  def shuffle
    self.to_s.shuffle.to_sym
  end

  def ring
    self.to_s.ring
  end
end

class Float

  def sp_thread_safe?
    true
  end

  def times(&block)
    self.to_i.times do |idx|
      yield idx.to_f
    end
  end
end


require 'rubame'

## Teach Rubame::Server#run to block on IO.select
## and therefore not thrash round in a loop
module Rubame

  class Server
    def run(time = 0, &blk)
      readable, _ = IO.select(@reading, @writing)

      if readable
        readable.each do |socket|
          client = @clients[socket]
          if socket == @socket
            client = accept
          else
            msg = read(client)
            client.messaged = msg
          end

          blk.call(client) if client and blk
        end
      end

      # Check for lazy send items
      timer_start = Time.now
      time_passed = 0
      begin
        @clients.each do |s, c|
          c.send_some_lazy(5)
        end
        time_passed = Time.now - timer_start
      end while time_passed < time
    end
  end
end



class Array
  include SonicPi::Core::TLMixin

  def __sp_make_thread_safe
    res = map {|v| v.__sp_make_thread_safe}
    res.freeze
  end

  def sp_thread_safe?
    frozen? && self.all? {|el| el.sp_thread_safe?}
  end

  def to_spv
    SonicPi::Core::SPVector.new(self)
  end

  def ring
    SonicPi::Core::RingVector.new(self)
  end

  def ramp
    SonicPi::Core::RampVector.new(self)
  end

  def choose
    self[SonicPi::Core::SPRand.rand_i!(self.size)]
  end

  def pick(n=nil, *opts)
    # mangle args to extract nice behaviour
    if !n.is_a?(Numeric) && opts.empty?
      opts = n
      n = nil
    else
      opts = opts[0]
    end

    if opts.is_a?(Hash)
      s = opts[:skip]
    else
      s = nil
    end

    n = 1 unless n
    raise "pick requires n to be a number, got: #{n.inspect}" unless n.is_a? Numeric

    res = []
    if s
      raise "skip: opt needs to be a number, got: #{s.inspect}" unless s.is_a? Numeric
      s.times do
        self.choose
      end
    end

    n.times { res << self.choose }

    res
  end


  alias_method :__orig_sample__, :sample
  def sample(*args, &blk)

    if Thread.current.thread_variable_get(:sonic_pi_thread_locals)
      self[SonicPi::Core::SPRand.rand!(self.size)]
    else
      __orig_sample__(*args, &blk)
    end
  end

  alias_method :__orig_shuffle__, :shuffle
  def shuffle(*args, &blk)
    if Thread.current.thread_variable_get(:sonic_pi_thread_locals)
      orig_seed, orig_idx = SonicPi::Core::SPRand.get_seed_and_idx
      SonicPi::Core::SPRand.set_seed!(SonicPi::Core::SPRand.rand_i!(441000))
      new_a = self.dup
      s = new_a.size
      s.times do
        idx_a = SonicPi::Core::SPRand.rand!(s)
        idx_b = SonicPi::Core::SPRand.rand!(s)
        new_a[idx_a], new_a[idx_b] = new_a[idx_b], new_a[idx_a]
      end
      SonicPi::Core::SPRand.set_seed!(orig_seed, orig_idx + 1)
      return new_a
    else
      __orig_shuffle__(*args, &blk)
    end
  end

  alias_method :__orig_shuffle_bang__, :shuffle!
  def shuffle!(*args, &blk)
    if Thread.current.thread_variable_get(:sonic_pi_thread_locals)
      new_a = self.shuffle
      self.replace(new_a)
    else
      __orig_shuffle_bang__(*args, &blk)
    end
  end
end

class Time
  def sp_thread_safe?
    frozen?
  end
end

class Hash
  def to_sp_map
    SonicPi::Core::SPMap.new(self)
  end

  def __sp_make_thread_safe
    res = {}
    each do |k, v|
      res[k.__sp_make_thread_safe] = v.__sp_make_thread_safe
    end
    res.to_sp_map
  end

  def sp_thread_safe?
    frozen? && all? {|k, v| k.sp_thread_safe? && v.sp_thread_safe?}
  end
end

class Object

  def sp_log_inspect
    inspect
  end

  def sp_thread_safe?
      self.is_a?(Numeric) ||
      self.is_a?(Symbol) ||
      self.is_a?(TrueClass) ||
      self.is_a?(FalseClass) ||
      self.is_a?(NilClass) ||
      (self.is_a?(SonicPi::Core::SPVector) && self.all? {|el| el.sp_thread_safe?})
  end

  def __sp_make_thread_safe
    return self if self.sp_thread_safe?

    raise SonicPi::Core::NotThreadSafeError, "Sorry, unable to make a #{self.class} thread safe"
  end


  def ring
    self.to_a.ring
  end

  def tick(*args)
    self.ring.tick(*args)
  end

  def look(*args)
    self.ring.look(*args)
  end

  # Meta-glasses from our hero Why to help us
  # see more clearly..

  # The hidden singleton lurks behind everyone
  def metaclass; class << self; self; end; end

  def meta_eval(&blk); metaclass.instance_eval(&blk); end
  # Adds methods to a metaclass
  def meta_def name, &blk
    meta_eval { define_method name, &blk }
  end
  # Defines an instance method within a class
  def class_def name, &blk
    class_eval { define_method name, &blk }
  end
end