/
daemon.rb
executable file
·1545 lines (1332 loc) · 51.3 KB
/
daemon.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
#!/usr/bin/env ruby
#--
# This file is part of Sonic Pi: http://sonic-pi.net
# Full project source: https://github.com/sonic-pi-net/sonic-pi
# License: https://github.com/sonic-pi-net/sonic-pi/blob/main/LICENSE.md
#
# Copyright 2021 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 'socket'
require 'shellwords'
require 'open3'
require 'fileutils'
require 'time'
require 'securerandom'
require_relative "../lib/sonicpi/osc/osc"
require_relative "../lib/sonicpi/promise"
# Make sure vendored tomlrb lib is on the Ruby path so it can be required
Dir["#{File.expand_path("../../vendor", __FILE__)}/*/lib/"].each do |vendor_lib|
$:.unshift vendor_lib
end
require 'tomlrb'
require_relative '../paths'
Thread::abort_on_exception = true
# The Sonic Pi Boot Daemon.
# =========================
#
# Process Spawning
# ----------------
#
# The Daemon launches and watches over the following long-living
# processes (necessary for Sonic Pi to work):
#
# +--> Tau - the Erlang IO server
# +--> Scsynth - the SuperCollider audio engine
# +--> Spider - the Ruby Runtime server
#
# The Daemon does all the work necessary to figure out the correct
# process paths and flags - even considering config files such as
# `audio-settings.toml and tau-settings.toml`
#
#
# Zombie Kill Switch
# ------------------
#
# It is the Daemon's responsibility to ensure that the processes it
# boots are always terminated and are not left to turn into zombies and
# stick around continuing to accidentally run on your computer consuming
# resources.
#
# This is achieved via a "Zombie Kill Switch" - a UDP connection with an
# external process (such as the GUI) to monitor its status by
# continually receiving keep_alive messages. If these messages stop
# being received (for example, if the GUI process exited normally or
# even crashed) then the Daemon will ensure all the processes it spawned
# (Spider, Tau and Scsynth) are terminated.
#
# The port number of this kill switch UDP connection is printed to
# STDOUT. A external process (such as the GUI) must connect promptly and
# periodically send an OSC message with the path /daemon/keep-alive (more
# frequently than every 3s) otherwise a timeout will trigger the kill
# switch and kill all the spawned processes.
#
# If the client wants to explicitly trigger the kill switch directly
# rather than via a timeout it can send an OSC message with path
# /daemon/exit along with a single integer argument which is the comms
# token (also printed to STDOUT - see below).
#
#
# Port Allocations & Comms Token
# ------------------------------
#
# The Daemon figures out appropriate (and currently free) values for all
# the ports used by various processes within Sonic Pi to communicate
# with each other. These ports are used to create the correct process
# arguments for spawning and are also passed to STDOUT.
#
# Some of these port numbers need to be known by the client process
# so that it can both send code to run and receive log updates via UDP.
#
# The final value printed to stdout is the comms token which is a random
# 32 bit signed integer. This must be used as the first argument to all
# OSC messages sent from the GUI to Daemon such as: /daemon/keep-alive
# and /daemon/exit.
#
# The current allocations of these external port numbers are printed to
# STDOUT in the following order:
#
# daemon-keep-alive gui-listen-to-server gui-send-to-server scsynth osc-cues tau-api tau-phx token
#
#
# Stdout Parameter Descriptions
# -----------------------------
#
# daemon: UDP port Daemon is listening on. This is used for
# receiving /daemon/keep-alive OSC messages amongst
# other things.
#
# gui-listen-to-server: UDP port which the GUI uses to listen to messages
# from the Spider Server.
#
# gui-send-to-server: UDP port which the GUI uses to send messages to
# the Spider Server.
#
# scsynth: UDP port on which scsynth listens (necessary for
# connecting to the boost shared memory for scope data)
#
# osc-cues: UDP port used to receive OSC cue messages from external
# processes.
#
# tau-api: UDP port used to send OSC messages to trigger the
# Tau API
#
# tau-phx: HTTP port used by Tau's Phoenix web server
#
#
# token: 32 bit signed integer used as a token to authenticate
# OSC messages. All OSC messages sent from the GUI
# must include this token as the first argument
module SonicPi
module Daemon
class Init
def initialize(opts={})
@no_scsynth_inputs = opts[:no_scsynth_inputs]
@exit_prom = Promise.new
@restart_tau_mut = Mutex.new
@booting_tau = false
@safe_exit = SafeExit.new do
@exit_prom.deliver! true
# Register exit routine
# This will only be called once
Util.log "Daemon Booter is now exiting."
Util.log "Cleaning up any running processes..."
cleanup_any_running_processes
Util.log "Daemon Booter - Over and Out."
Util.close_log
end
# This is where the Daemon begins and ends.
@scsynth_booter = nil
@tau_booter = nil
@spider_booter = nil
@compton_booter = nil
# use a value within the valid range for a 32 bit signed complement integer
@daemon_token = rand(-2147483647..2147483647)
if @no_scsynth_inputs
Util.log "SuperCollider inputs disabled by GUI"
else
Util.log "SuperCollider inputs enabled by GUI"
end
#start compton to handle transparency (needs to be after Util.open_log)
@compton_booter = ComptonBooter.new if Util.os == :raspberry
# Get a map of port numbers to use
#
# Note that the program will safe_exit here
# if there are problems detecting port numbers to use.
@ports = PortDiscovery.new(@safe_exit).ports
Util.log "Selected ports: "
Util.log @ports.inspect
@kill_switch = KillSwitch.new(@safe_exit)
@api_server = SonicPi::OSC::UDPServer.new(@ports["daemon"], suppress_errors: false, name: "Daemon API Server")
# For debugging purposes:
# @api_server = SonicPi::OSC::UDPServer.new(@ports["daemon"], suppress_errors: false, name: "Daemon API Server") do |address, args, sender_addrinfo|
# Util.log "Kill switch ##{@ports["daemon"] Received UDP data #{[address, args, sender_addrinfo].inspect}"
# end
@api_server.add_method("/daemon/keep-alive") do |args|
if args[0] == @daemon_token
@kill_switch.keep_alive!
end
end
@api_server.add_method("/daemon/exit") do |args|
if args[0] == @daemon_token
Util.log "[EXIT] Kill switch for port #{@ports["daemon"]} remotely activated using token #{@daemon_token}"
@safe_exit.exit
else
Util.log "Kill switch for port #{@ports["daemon"]} received incorrect token. Ignoring #{args[0]}"
end
end
@api_server.add_method("/daemon/restart-tau") do |args|
if args[0] && args[0] == @daemon_token
Util.log "Restarting Tau"
restart_tau!
end
end
@api_server.add_method("/tau/pid") do |args|
Util.log "Daemon received Pid from Tau: #{args.inspect}"
# Util.log "token: #{@daemon_token}"
if args[0] && args[0] == @daemon_token
@tau_booter.update_pid!(args[1])
end
end
Util.log "Booting Scsynth"
@scsynth_booter = ScsynthBooter.new(@ports, @no_scsynth_inputs)
Util.log "Extracting Scsynth info"
success, info = @scsynth_booter.read_info
if success
Thread.new do
# Give GUI chance to start OSC handlers
Kernel.sleep 5
send_scsynth_info_to_gui!(info)
end
else
Util.log "sending ERROR to gui"
# Note that this first line has to match sonicpi_api.cpp
# within SonicPiAPI::StartBootDaemon()
puts "SuperCollider Audio Server Boot Error\n#{info.to_s}"
STDOUT.flush
@safe_exit.exit
end
boot_tau!(false)
Util.log "Booting Spider Server"
@spider_booter = SpiderBooter.new(@ports, @daemon_token)
# Let the calling process (likely the GUI) know which port to
# listen to and communicate on with the Ruby spider server via
# STDOUT.
puts "#{@ports["daemon"]} #{@ports["gui-listen-to-spider"]} #{@ports["gui-send-to-spider"]} #{@ports["scsynth"]} #{@ports["osc-cues"]} #{@ports["tau"]} #{@tau_booter.phx_port} #{@daemon_token}"
Util.log "#{@ports["daemon"]} #{@ports["gui-listen-to-spider"]} #{@ports["gui-send-to-spider"]} #{@ports["scsynth"]} #{@ports["osc-cues"]} #{@ports["tau"]} #{@tau_booter.phx_port} #{@daemon_token}"
STDOUT.flush
Util.log "Blocking main thread until exit signal received..."
begin
@exit_prom.get
Util.log "Exit signal received..."
rescue
# Way Out
end
end
def extract_scsynth_log_info_macos(info)
# Number of Devices: 8
# 0 : "NDI Audio"
# 1 : "MacBook Pro Microphone"
# 2 : "MacBook Pro Speakers"
# 3 : "NDI Audio"
# 4 : "Loopback Audio"
# 5 : "Loopback Audio 2"
# 6 : "ZoomAudioD"
# 7 : "Aggregate Device"
# "MacBook Pro Microphone" Input Device
# Streams: 1
# 0 channels 1
# "MacBook Pro Speakers" Output Device
# Streams: 1
# 0 channels 2
# SC_AudioDriver: sample rate = 48000.000000, driver's block size = 32
# SuperCollider 3 server ready.
res = info.match /.*^"(.*)" Input Device\s+Streams: [0-9]+\s+0\s+channels (.*)\s+^"(.*)" Output Device\s+Streams: [0-9]+\s+0\s+channels (.*)\s/u
##<MatchData
# "\"MacBook Pro Microphone\" Input Device\n Streams: 1\n 0 channels 1\n\n\"MacBook Pro Speakers\" Output Device\n Streams: 1\n 0 channels 2\n"
# 1:"MacBook Pro Microphone"
# 2:"1"
# 3:"MacBook Pro Speakers"
# 4:"2">
if res
if @scsynth_booter.num_inputs == 0
hw_in = "Not connected"
hw_in_chans = 0
else
hw_in = res[1]
hw_in_chans = res[2].to_i
end
if @scsynth_booter.num_outputs == 0
hw_out = "Not connected"
hw_out_chans = 0
else
hw_out = res[3]
hw_out_chans = res[4].to_i
end
info_m = {
hw_in: hw_in,
hw_out: hw_out,
hw_in_chans: hw_in_chans,
hw_out_chans: hw_out_chans
}
else
info_m = {}
end
res2 = info.match /.*SC_AudioDriver: sample rate = (.*), driver's block size = (.*)\s/u #'
##<MatchData "SC_AudioDriver: sample rate = 48000.000000, driver's block size = 32\n" 1:"48000.000000" 2:"32">
if res2
return info_m.merge({
sc_sample_rate: res2[1].to_i,
sc_block_size: res2[2].to_i
})
else
return info_m
end
end
def extract_scsynth_log_info_windows(info)
# Device options:
# - MME : Microsoft Sound Mapper - Input (device #0 with 2 ins 0 outs)
# - MME : In 1-2 (MOTU Pro Audio) (device #1 with 2 ins 0 outs)
# - MME : Line (NewTek NDI Audio) (device #2 with 2 ins 0 outs)
# - MME : In 1-24 (MOTU Pro Audio) (device #3 with 24 ins 0 outs)
# - MME : Microsoft Sound Mapper - Output (device #4 with 0 ins 2 outs)
# - MME : Realtek Digital Output (Realtek (device #5 with 0 ins 2 outs)
# - MME : Out 1-24 (MOTU Pro Audio) (device #6 with 0 ins 24 outs)
# - MME : LG HDR 4K (NVIDIA High Definiti (device #7 with 0 ins 2 outs)
# - MME : Speakers (MOTU Pro Audio) (device #8 with 0 ins 2 outs)
# - MME : VP3268-4K (NVIDIA High Definiti (device #9 with 0 ins 2 outs)
# - Windows DirectSound : Primary Sound Capture Driver (device #10 with 2 ins 0 outs)
# - Windows DirectSound : In 1-2 (MOTU Pro Audio) (device #11 with 2 ins 0 outs)
# - Windows DirectSound : Line (NewTek NDI Audio) (device #12 with 2 ins 0 outs)
# - Windows DirectSound : In 1-24 (MOTU Pro Audio) (device #13 with 24 ins 0 outs)
# - Windows DirectSound : Primary Sound Driver (device #14 with 0 ins 2 outs)
# - Windows DirectSound : Realtek Digital Output (Realtek High Definition Audio) (device #15 with 0 ins 2 outs)
# - Windows DirectSound : Out 1-24 (MOTU Pro Audio) (device #16 with 0 ins 24 outs)
# - Windows DirectSound : LG HDR 4K (NVIDIA High Definition Audio) (device #17 with 0 ins 2 outs)
# - Windows DirectSound : Speakers (MOTU Pro Audio) (device #18 with 0 ins 2 outs)
# - Windows DirectSound : VP3268-4K (NVIDIA High Definition Audio) (device #19 with 0 ins 2 outs)
# - ASIO : MOTU Pro Audio (device #20 with 24 ins 6 outs)
# - Windows WASAPI : Out 1-24 (MOTU Pro Audio) (device #21 with 0 ins 24 outs)
# - Windows WASAPI : Realtek Digital Output (Realtek High Definition Audio) (device #22 with 0 ins 2 outs)
# - Windows WASAPI : LG HDR 4K (NVIDIA High Definition Audio) (device #23 with 0 ins 2 outs)
# - Windows WASAPI : Speakers (MOTU Pro Audio) (device #24 with 0 ins 2 outs)
# - Windows WASAPI : VP3268-4K (NVIDIA High Definition Audio) (device #25 with 0 ins 2 outs)
# - Windows WASAPI : Line (NewTek NDI Audio) (device #26 with 2 ins 0 outs)
# - Windows WASAPI : In 1-2 (MOTU Pro Audio) (device #27 with 2 ins 0 outs)
# - Windows WASAPI : In 1-24 (MOTU Pro Audio) (device #28 with 24 ins 0 outs)
# - Windows WDM-KS : Microphone (Realtek HD Audio Mic input) (device #29 with 2 ins 0 outs)
# - Windows WDM-KS : SPDIF Out (Realtek HDA SPDIF Out) (device #30 with 0 ins 2 outs)
# - Windows WDM-KS : Speakers (Realtek HD Audio output) (device #31 with 0 ins 8 outs)
# - Windows WDM-KS : Line In (Realtek HD Audio Line input) (device #32 with 2 ins 0 outs)
# - Windows WDM-KS : Stereo Mix (Realtek HD Audio Stereo input) (device #33 with 2 ins 0 outs)
# - Windows WDM-KS : Output (NVIDIA High Definition Audio) (device #34 with 0 ins 2 outs)
# - Windows WDM-KS : Output (NVIDIA High Definition Audio) (device #35 with 0 ins 2 outs)
# - Windows WDM-KS : In 1-2 (In 1-2) (device #36 with 2 ins 0 outs)
# - Windows WDM-KS : In 1-24 (In 1-24) (device #37 with 24 ins 0 outs)
# - Windows WDM-KS : Out 1-2 (Out 1-2) (device #38 with 0 ins 2 outs)
# - Windows WDM-KS : Out 1-24 (Out 1-24) (device #39 with 0 ins 24 outs)
# - Windows WDM-KS : Line (Aud #1) (device #40 with 2 ins 0 outs)
# Requested devices:
# In (matching device found):
# - ASIO : MOTU Pro Audio
# Out (matching device found):
# - ASIO : MOTU Pro Audio
# Booting with:
# In: ASIO : MOTU Pro Audio
# Out: ASIO : MOTU Pro Audio
# Sample rate: 48000.000
# Latency (in/out): 0.003 / 0.004 sec
# SC_AudioDriver: sample rate = 48000.000000, driver's block size = 64
# SuperCollider 3 server ready.
booting_with = info.split("Booting with")[1] || ""
res = booting_with.match /^\s+In: (.*)\s+^\s+Out: (.*)\s+^\s+Sample rate: (.*)\s+^\s+Latency \(in\/out\): (.*) \/ (.*) sec/u
res_no_input = booting_with.match /^\s+Out: (.*)\s+^\s+Sample rate: (.*)\s+^\s+Latency \(in\/out\): (.*) \/ (.*) sec/u
res_no_output = booting_with.match /^\s+In: (.*)\s+^\s+Sample rate: (.*)\s+^\s+Latency \(in\/out\): (.*) \/ (.*) sec/u
#<MatchData
# " In: ASIO : MOTU Pro Audio\n Out: ASIO : MOTU Pro Audio\n Sample rate: 48000.000\n Latency (in/out): 0.003 / 0.004 sec"
# 1:"ASIO : MOTU Pro Audio"
# 2:"ASIO : MOTU Pro Audio"
# 3:"48000.000"
# 4:"0.003"
# 5:"0.004">
Util.log "scsynth log match - res: #{res.inspect}, res_no_input: #{res_no_input.inspect}, res_no_output: #{res_no_output.inspect}"
if res
info_m = {
hw_in: res[1],
hw_out: res[2],
hw_sample_rate: res[3].to_i,
hw_latency_in: res[4].to_f,
hw_latency_out: res[5].to_f
}
Util.log "Extracted Windows in/out audio hw: #{info_m}"
elsif res_no_input
info_m = {
hw_in: "Not connected",
hw_out: res_no_input[1],
hw_sample_rate: res_no_input[2].to_i,
hw_latency_in: res_no_input[3].to_f,
hw_latency_out: res_no_input[4].to_f
}
Util.log "Extracted Windows in audio hw only: #{info_m}"
elsif res_no_output
info_m = {
hw_in: res_no_output[1],
hw_out: "Not connected",
hw_sample_rate: res_no_output[2].to_i,
hw_latency_in: res_no_output[3].to_f,
hw_latency_out: res_no_output[4].to_f
}
Util.log "Extracted Windows out audio hw only: #{info_m}"
else
info_m = {}
end
res2 = booting_with.match /.*SC_AudioDriver: sample rate = (.*), driver's block size = (.*)\s/u #'
##<MatchData "SC_AudioDriver: sample rate = 48000.000000, driver's block size = 64\n" 1:"48000.000000" 2:"64">
if res2
return info_m.merge({ sc_sample_rate: res2[1].to_i,
sc_block_size: res2[2].to_i })
else
return info_m
end
end
def extract_scsynth_log_info_linux(info)
# # Starting SuperCollider 2022-04-12 23:23:04
# Found 0 LADSPA plugins
# jackdmp 1.9.19
# Copyright 2001-2005 Paul Davis and others.
# Copyright 2004-2016 Grame.
# Copyright 2016-2021 Filipe Coelho.
# jackdmp comes with ABSOLUTELY NO WARRANTY
# This is free software, and you are welcome to redistribute it
# under certain conditions; see the file COPYING for details
# JackDriver: client name is 'SuperCollider'
# SC_AudioDriver: sample rate = 48000.000000, driver's block size = 2048
# SuperCollider 3 server ready."
res = info.match(/.*sample rate = (.*?), driver's block size = (.*?)\nSuperCollider 3/u)
if res
return {sc_sample_rate: res[1].to_i, sc_block_size: res[2].to_i}
else
return {}
end
end
def extract_scsynth_log_info(info)
case Util.os
when :macos
return extract_scsynth_log_info_macos(info)
when :windows
return extract_scsynth_log_info_windows(info)
when :linux, :raspberry
return extract_scsynth_log_info_linux(info)
else
return {}
end
end
def scsynth_log_str(info_m)
i = info_m
res = String.new("")
if i[:hw_out]
if i[:hw_out_chans]
res += "Out [#{i[:hw_out_chans]} ch]: #{i[:hw_out]}"
else
res += "Out: #{i[:hw_out]}"
end
end
if i[:hw_in]
if i[:hw_in_chans]
res += "\nIn [#{i[:hw_in_chans]} ch]: #{i[:hw_in]}"
else
res += "\nIn: #{i[:hw_in]}"
end
end
latency_in = i[:hw_latency_in]
latency_out = i[:hw_latency_out]
block_size = i[:sc_block_size]
res += "\nSample Rate: #{i[:hw_sample_rate] || i[:sc_sample_rate]}"
res += "\nBlock Size: #{block_size}" if block_size && block_size > 0
res += "\nLatency In: #{latency_in}" if latency_in && latency_in > 0
res += "\nLatency Out: #{latency_out}" if latency_out && latency_out > 0
res.strip!
res
end
def send_scsynth_info_to_gui!(info_s)
begin
info_m = extract_scsynth_log_info(info_s)
hw_info_s = scsynth_log_str(info_m)
Util.log "Sending scsynth info to GUI..."
Util.log info_m
Util.log hw_info_s
@api_server.send("localhost", @ports["gui-listen-to-spider"], "/scsynth/info", hw_info_s)
rescue => e
Util.log "Exception sending scsynth info to gui:"
Util.log_error(e)
end
end
def boot_tau!(wait_for_pid = true)
@booting_tau = true
Util.log "Booting Tau..."
begin
@tau_booter = TauBooter.new(@ports, @kill_switch, @daemon_token)
@tau_booter.wait_for_pid! if wait_for_pid
@booting_tau = false
rescue StandardError => e
Util.log "Oh no, something went wrong booting Tau"
Util.log_error(e)
puts "Oh no, something went wrong booting Tau"
puts "Error Class: #{e.class}"
puts "Error Message: #{e.message}"
puts "Error Backtrace: #{e.backtrace.join("\n")}"
puts 'hi'
STDOUT.flush
@safe_exit.exit
end
end
def restart_tau!
return if @booting_tau
Thread.new do
@restart_tau_mut.synchronize do
return if @booting_tau
@booting_tau = true
Util.log "Restarting Tau..."
@tau_booter.kill
boot_tau!
end
end
end
def cleanup_any_running_processes
[@spider_booter, @scsynth_booter, @tau_booter, @compton_booter].map do |p|
Thread.new do
begin
p.kill if p
rescue StandardError => e
Util.log "Error attempting to kill process #{p.inspect}"
Util.log_error(e)
end
end
end.each { |t| t.join }
end
end
module Util
def self.open_log
begin
@@log_file = File.open(Paths.daemon_log_path, 'a')
rescue StandardError => e
STDERR.puts "Unable to open log file #{Paths.daemon_log_path}"
STDERR.puts e.inspect
STDERR.puts "----\n\n"
@@log_file = nil
end
end
def self.close_log
@@log_file.close if @@log_file
end
def self.timestamp_for_log
"[#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}]"
end
def self.log(msg)
begin
if @@log_file
@@log_file.puts("#{timestamp_for_log} #{msg}")
@@log_file.flush
end
rescue IOError => e
STDERR.puts "Error. Unable to write to log file: #{e.message}"
STDERR.puts e.inspect
end
end
def self.log_error(e)
spacer = "\n " + (" " * timestamp_for_log.size)
log "#{e.class}"
log "#{e.message}"
log "##{e.backtrace.join(spacer)}"
end
def self.os
case RUBY_PLATFORM
when /.*linux.*/
if File.exist?('/etc/rpi-issue')
:raspberry
else
:linux
end
when /.*darwin.*/
:macos
when /.*mingw.*/
:windows
else
raise "Unsupported platform #{RUBY_PLATFORM}"
end
end
def self.pipewire?
`which pw-link`
$?.success?
end
end
class KillSwitch
def initialize(safe_exit)
@safe_exit = safe_exit
@kill_switch_prom = Promise.new
@queue = Queue.new
activate
@timer_thread = Thread.new do
attempts = 0
max_attempts = 4
Kernel.sleep 40
loop do
Kernel.sleep 10
if @queue.empty?
attempts += 1
else
attempts = 0
@queue.clear
end
break if attempts > max_attempts
end
Util.log "Kill switch timed out..."
@kill_switch_prom.deliver!(true)
end
end
def keep_alive!
@queue << true
end
def wait
@kill_switch_prom.get
end
def activate
return if @armed_thread
@armed_thread = Thread.new do
wait
Util.log "[EXIT] Daemon kill switch triggered. Exiting..."
@timer_thread.kill
@safe_exit.exit
end
end
def deactivate
@armed_thread.kill
end
end
class SafeExit
def initialize(&cleanup_procedure)
@exit_mut = Mutex.new
@exit_cleanup_mut = Mutex.new
@exit_in_progress = false
@exit_cleanup_completed = false
@cleanup_procedure = cleanup_procedure
at_exit do
Util.log "[EXIT] Daemon Process has completed:"
@exit_mut.synchronize do
@exit_in_progress = true
idempotent_exit_cleanup
end
end
end
def exit
Thread.current.kill if @exit_in_progress
@exit_mut.synchronize do
if @exit_in_progress
Thread.current.kill
else
@exit_in_progress = true
idempotent_exit_cleanup
Kernel.exit
end
end
end
private
def idempotent_exit_cleanup
@exit_cleanup_mut.synchronize do
unless @exit_cleanup_completed
@cleanup_procedure.call
@exit_cleanup_completed = true
end
end
end
end
class ProcessBooter
attr_reader :pid, :args, :cmd, :log
def initialize(cmd, args, log_path, record_log=false, env=nil)
@env = env
@pid = nil
@log_file = nil
@args = args.map {|el| el.to_s}
@cmd = cmd
@log = ""
@record_log = record_log
if log_path
begin
@log_file = File.open(log_path, 'a')
rescue StandardError => e
STDERR.puts "Unable to open log file #{log_path}"
STDERR.puts e.inspect
STDERR.puts "----\n\n"
@log_file = nil
end
end
begin
boot
rescue StandardError => e
Util.log "Error: something went wrong booting process: #{cmd}, #{args}, #{log_path}"
Util.log_error(e)
@log_file.close if @log_file
end
end
def inspect
"<ProcessBooter - cmd: #{@cmd}, pid: #{@pid.inspect}, args: #{@args.inspect}>"
end
def enable_internal_log_recording!
@record_log = true
end
def disable_internal_log_recording!
@record_log = false
end
def boot
Util.log "Process Booter - booting #{@cmd} with args #{@args.inspect}"
Util.log "#{@cmd} #{@args.join(' ')}"
if @env
@stdin, @stdout_and_err, @wait_thr = Open3.popen2e @env, @cmd, *@args
else
@stdin, @stdout_and_err, @wait_thr = Open3.popen2e @cmd, *@args
end
@pid = @wait_thr.pid
if @log_file
@io_thr = Thread.new do
@stdout_and_err.each do |line|
begin
line = line.force_encoding("UTF-8")
@log_file << line
@log_file.flush
@log << line if @record_log
Util.log "[#{File.basename(@cmd, ".*")}] #{line}"
rescue IOError
# don't attempt to write
end
end
end
end
end
def process_running?
return false unless @wait_thr
@wait_thr.status
end
def wait
begin
@wait_thr.join if @wait_thr
rescue Interrupt => e
Util.log "Got interrupted waiting for #{@cmd} to complete"
end
end
def kill
if process_running? && @pid
Util.log "Process Booter - killing #{@cmd} with pid #{@pid} and args #{@args.inspect}, wait_thr status: #{@wait_thr}, #{@wait_thr.status}"
unless Util.os == :windows
begin
Util.log "Sending TERM kill command to #{@pid.inspect}"
Process.kill("TERM", @pid)
rescue Errno::ESRCH
Util.log "Unable to send TERM kill command to #{@pid.inspect} as it's no longer running"
end
countdown = 5
while process_running? && countdown >= 0
Util.log "Process #{@pid.inspect} still running, waiting for it to finish... [#{countdown}]"
sleep 1
countdown -= 1
end
end
if process_running?
# We're either running on Windows (which doesn't seem to
# support SIGTERM) or we attempted to kill the process nicely,
# but unfortunately that didn't work, so let's forcefully kill
# it
begin
Util.log "Sending KILL kill command to #{@pid.inspect}"
Process.kill("KILL", @pid)
rescue Errno::ESRCH
Util.log "Unable to send KILL kill command to #{@pid.inspect} as it's no longer running"
end
countdown = 5
while process_running? && countdown >= 0
Util.log "Process #{@pid.inspect} still running, waiting for it to finish... [#{countdown}]"
sleep 1
countdown -= 1
end
end
if process_running?
Util.log "Unable to terminate process #{@pid.inspect}"
else
Util.log "Process #{@pid.inspect} terminated"
end
else
Util.log "Process Booter - no need to kill #{@cmd} with pid #{@pid} and args #{@args.inspect} - already terminated, wait_thr status: #{@wait_thr}, #{@wait_thr.status}"
end
unless @pid
Util.log "Process Booter - Unfortunately we don't have a @pid for #{@cmd} with args #{@args.inspect}. wait_thr: #{@wait_thr}"
end
@io_thr.kill if @io_thr
@log_file.close if @log_file
end
end
class SpiderBooter < ProcessBooter
def initialize(ports, token)
args = [
"--enable-frozen-string-literal", "-E", "utf-8",
Paths.spider_server_path,
"-u",
ports["spider-listen-to-gui"],
ports["spider-send-to-gui"],
ports["scsynth"],
ports["scsynth-send"],
ports["osc-cues"],
ports["tau"],
ports["spider-listen-to-tau"],
token
]
super(Paths.ruby_path, args, Paths.spider_log_path)
end
end
class TauBooter < ProcessBooter
attr_reader :phx_port
def initialize(ports, kill_switch, token)
@tau_pid = Promise.new
@pid_requester = SonicPi::OSC::UDPClient.new('localhost', ports["tau"])
@pid_updater_thread = Thread.new do
while !@tau_pid.delivered?
Util.log "Requesting tau send us its pid. Sending /send-pid-to-daemon, #{token} to localhost:#{ports['tau']}"
begin
@pid_requester.send("/send-pid-to-daemon", token)
rescue Errno::ECONNREFUSED
Util.log "Error talking to Tau - connection refused (perhaps Tau is still booting?)"
rescue StandardError => e
Util.log "Error talking to Tau"
Util.log_error(e)
end
Kernel.sleep 1
end
end
begin
Util.log "Fetching Tau toml opts..."
toml_opts_hash = Tomlrb.load_file(Paths.user_tau_settings_path, symbolize_keys: true).freeze
Util.log "Got Tau toml opts: #{toml_opts_hash}"
unified_opts = unify_tau_toml_opts(toml_opts_hash)
Util.log "Unified Tau toml opts: #{unified_opts}"
rescue StandardError
unified_opts = {}
end
@phx_port = unified_opts[:phx_port] || ports["phx"]
Util.log "Daemon listening to info from Tau on port #{ports["daemon"]}"
ENV["TAU_CUES_ON"] = "true"
ENV["TAU_OSC_IN_UDP_LOOPBACK_RESTRICTED"] = "true"
ENV["TAU_MIDI_ON"] = "true"
ENV["TAU_LINK_ON"] = "true"
ENV["TAU_OSC_IN_UDP_PORT"] = "#{ports["osc-cues"]}"
ENV["TAU_API_PORT"] = "#{ports["tau"]}"
ENV["TAU_SPIDER_PORT"] = "#{ports["spider-listen-to-tau"]}"
ENV["TAU_DAEMON_PORT"] = "#{ports["daemon"]}"
ENV["TAU_MIDI_ENABLED"] = "true"
ENV["TAU_LINK_ENABLED"] = "true"
ENV["SECRET_KEY_BASE"] = "#{SecureRandom.base64(64)}"
ENV["TAU_DAEMON_TOKEN"] = "#{token}"
ENV["TAU_ENV"] = "#{ENV["SONIC_PI_ENV"] || unified_opts[:env] || "prod"}"
ENV["MIX_ENV"] = ENV["TAU_ENV"]
ENV["TAU_PHX_PORT"] = "#{@phx_port}"
ENV["TAU_LOG_PATH"] = "#{Paths.tau_log_path}"
ENV["TAU_BOOT_LOG_PATH"] = "#{Paths.tau_boot_log_path}"
if Util.os == :windows
if ENV["TAU_ENV"] == "prod"
ENV["RELEASE_SYS_CONFIG"] = "#{Paths.tau_release_sys_config_path}"
ENV["RELEASE_ROOT"] = "#{Paths.tau_release_root}"
cmd = "#{Paths.tau_release_erl_bin_path}".gsub('/', '\\')
args = ["-config", "#{Paths.tau_release_sys_path}".gsub('/', "\\"),
"-boot", "#{Paths.tau_release_start_path}".gsub('/', "\\"),
"-boot_var", "RELEASE_LIB", "#{Paths.tau_release_lib_path}".gsub('/', "\\"),
"-args_file", "#{Paths.tau_release_vm_args_path}".gsub('/', "\\"),
"-noshell",
"-s", "elixir", "start_cli",
"-mode", "embedded",
"-extra", "--no-halt"]
else
cmd = Paths.tau_boot_path
args = []
end
else
cmd = "sh"
args = [Paths.tau_boot_path]
end
super(cmd, args, Paths.tau_boot_log_path)
end
def restart!
@tau_pid = Promise.new
end
def update_pid!(pid)
@tau_pid.deliver!(pid, false)
end
def wait_for_pid!()