-
Notifications
You must be signed in to change notification settings - Fork 65
/
host.py
2729 lines (2196 loc) · 102 KB
/
host.py
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
# -*- coding: utf-8 -*-
# Copyright 2012-2013 AGR Audio, Industria e Comercio LTDA. <contato@portalmod.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module works as an interface for mod-host, it uses a socket to communicate
with mod-host, the protocol is described in <http://github.com/portalmod/mod-host>
The module relies on tornado.ioloop stuff, but you need to start the ioloop
by yourself:
>>> from tornado import ioloop
>>> ioloop.IOLoop.instance().start()
This will start the mainloop and will handle the callbacks and the async functions
"""
from collections import OrderedDict
from random import randint
from shutil import rmtree
from tornado import gen, iostream, ioloop
import os, json, socket, logging
from mod import get_hardware, symbolify
from mod.bank import list_banks, get_last_bank_and_pedalboard, save_last_bank_and_pedalboard
from mod.protocol import Protocol, ProtocolError, process_resp
from mod.utils import (charPtrToString,
is_bundle_loaded, add_bundle_to_lilv_world, remove_bundle_from_lilv_world, rescan_plugin_presets,
get_plugin_info, get_plugin_control_inputs_and_monitored_outputs,
get_pedalboard_info, get_state_port_values, list_plugins_in_bundle,
get_all_pedalboards, get_pedalboard_plugin_values,
init_jack, close_jack, get_jack_data, init_bypass,
get_jack_port_alias, get_jack_hardware_ports, has_serial_midi_input_port, has_serial_midi_output_port,
connect_jack_ports, disconnect_jack_ports, get_truebypass_value, set_util_callbacks)
from mod.settings import (DEFAULT_PEDALBOARD, LV2_PEDALBOARDS_DIR,
TUNER_URI, TUNER_INSTANCE, TUNER_INPUT_PORT, TUNER_MONITOR_PORT)
from mod.tuner import find_freqnotecents
ADDRESSING_CTYPE_LINEAR = 0
ADDRESSING_CTYPE_BYPASS = 1
ADDRESSING_CTYPE_TAP_TEMPO = 2
ADDRESSING_CTYPE_ENUMERATION = 4 # implies scalepoints
ADDRESSING_CTYPE_SCALE_POINTS = 8
ADDRESSING_CTYPE_TRIGGER = 16
ADDRESSING_CTYPE_TOGGLED = 32
ADDRESSING_CTYPE_LOGARITHMIC = 64
ADDRESSING_CTYPE_INTEGER = 128
ACTUATOR_TYPE_FOOTSWITCH = 1
ACTUATOR_TYPE_KNOB = 2
ACTUATOR_TYPE_POT = 3
BANK_CONFIG_NOTHING = 0
BANK_CONFIG_TRUE_BYPASS = 1
BANK_CONFIG_PEDALBOARD_UP = 2
BANK_CONFIG_PEDALBOARD_DOWN = 3
HARDWARE_TYPE_MOD = 0
HARDWARE_TYPE_PEDAL = 1
HARDWARE_TYPE_TOUCH = 2
HARDWARE_TYPE_ACCEL = 3
HARDWARE_TYPE_CUSTOM = 4
# Special URI for non-addressed controls
kNullAddressURI = "null"
# Special URIs for midi-learn
kMidiLearnURI = "/midi-learn"
kMidiUnmapURI = "/midi-unmap"
kMidiCustomPrefixURI = "/midi-custom_" # to show current one
# Limits
kMaxAddressableScalepoints = 50
def get_all_good_pedalboards():
allpedals = get_all_pedalboards()
goodpedals = []
for pb in allpedals:
if not pb['broken']:
goodpedals.append(pb)
return goodpedals
# class to map between numeric ids and string instances
class InstanceIdMapper(object):
def __init__(self):
self.clear()
def clear(self):
# last used id, always incrementing
self.last_id = 0
# map id <-> instances
self.id_map = {}
# map instances <-> ids
self.instance_map = {}
# get a numeric id from a string instance
def get_id(self, instance):
# check if it already exists
if instance in self.instance_map.keys():
return self.instance_map[instance]
# increment last id
idx = self.last_id
self.last_id += 1
# create mapping
self.instance_map[instance] = idx
self.id_map[idx] = instance
# ready
return self.instance_map[instance]
def get_id_without_creating(self, instance):
return self.instance_map[instance]
# get a string instance from a numeric id
def get_instance(self, id):
return self.id_map[id]
class Host(object):
def __init__(self, hmi, msg_callback):
if False:
from mod.hmi import HMI
self.hmi = HMI()
self.hmi = hmi
self.addr = ("localhost", 5555)
self.readsock = None
self.writesock = None
self.crashed = False
self.connected = False
self.current_tuner_port = 1
self._queue = []
self._idle = True
self.mapper = InstanceIdMapper()
self.banks = list_banks()
self.allpedalboards = None
self.bank_id = 0
self.plugins = {}
self.connections = []
self.audioportsIn = []
self.audioportsOut = []
self.midiports = [] # [symbol, alias, pending-connections]
self.hasSerialMidiIn = False
self.hasSerialMidiOut = False
self.pedalboard_empty = True
self.pedalboard_modified = False
self.pedalboard_name = ""
self.pedalboard_path = ""
self.pedalboard_size = [0,0]
self.pedalboard_presets = []
self.next_hmi_pedalboard = None
self.statstimer = ioloop.PeriodicCallback(self.statstimer_callback, 1000)
if os.path.exists("/proc/meminfo"):
self.memfile = open("/proc/meminfo", 'r')
self.memtotal = 0.0
self.memfseek = 0
self.memfskip = False
wasFreeBefore = False
for line in self.memfile.readlines():
if line.startswith("MemTotal:"):
self.memtotal = float(int(line.replace("MemTotal:","",1).replace("kB","",1).strip()))
elif line.startswith("MemFree:"):
wasFreeBefore = True
continue
elif wasFreeBefore:
if line.startswith("MemAvailable:"):
self.memfskip = True
break
elif line.startswith("Buffers:"):
break
wasFreeBefore = False
self.memfseek += len(line)
else:
self.memfseek = 0
if self.memtotal != 0.0 and self.memfseek != 0:
self.memtimer = ioloop.PeriodicCallback(self.memtimer_callback, 5000)
else:
self.memtimer = None
self.msg_callback = msg_callback
set_util_callbacks(self.midi_port_appeared, self.midi_port_deleted, self.true_bypass_changed)
# Register HMI protocol callbacks
self._init_addressings()
Protocol.register_cmd_callback("hw_con", self.hmi_hardware_connected)
Protocol.register_cmd_callback("hw_dis", self.hmi_hardware_disconnected)
Protocol.register_cmd_callback("banks", self.hmi_list_banks)
Protocol.register_cmd_callback("pedalboards", self.hmi_list_bank_pedalboards)
Protocol.register_cmd_callback("pedalboard", self.hmi_load_bank_pedalboard)
Protocol.register_cmd_callback("control_get", self.hmi_parameter_get)
Protocol.register_cmd_callback("control_set", self.hmi_parameter_set)
Protocol.register_cmd_callback("control_next", self.hmi_parameter_addressing_next)
Protocol.register_cmd_callback("pedalboard_save", self.hmi_save_current_pedalboard)
Protocol.register_cmd_callback("pedalboard_reset", self.hmi_reset_current_pedalboard)
Protocol.register_cmd_callback("tuner", self.hmi_tuner)
Protocol.register_cmd_callback("tuner_input", self.hmi_tuner_input)
ioloop.IOLoop.instance().add_callback(self.init_host)
def __del__(self):
self.msg_callback("stop")
self.close_jack()
def midi_port_appeared(self, name, isOutput):
name = charPtrToString(name)
isOutput = bool(isOutput)
alias = get_jack_port_alias(name)
if not alias:
return
alias = alias.split("-",5)[-1].replace("-"," ").replace(";",".")
if not isOutput:
connect_jack_ports(name, "mod-host:midi_in")
for i in range(len(self.midiports)):
port_symbol, port_alias, port_conns = self.midiports[i]
if alias == port_alias or (";" in port_alias and alias in port_alias.split(";",1)):
split = port_symbol.split(";")
if len(split) == 1:
oldnode = "/graph/" + port_symbol.split(":",1)[-1]
port_symbol = name
else:
if isOutput:
oldnode = "/graph/" + split[1].split(":",1)[-1]
split[1] = name
else:
oldnode = "/graph/" + split[0].split(":",1)[-1]
split[0] = name
port_symbol = ";".join(split)
self.midiports[i][0] = port_symbol
break
else:
return
index = int(name[-1])
title = self.get_port_name_alias(name).replace("-","_").replace(" ","_")
newnode = "/graph/" + name.split(":",1)[-1]
if name.startswith("nooice"):
index += 100
self.msg_callback("add_hw_port /graph/%s midi %i %s %i" % (name.split(":",1)[-1], int(isOutput), title, index))
for i in reversed(range(len(port_conns))):
if port_conns[i][0] == oldnode:
port_conns[i] = (newnode, port_conns[i][1])
elif port_conns[i][1] == oldnode:
port_conns[i] = (port_conns[i][0], newnode)
connection = port_conns[i]
if newnode not in connection:
continue
if not connect_jack_ports(self._fix_host_connection_port(connection[0]),
self._fix_host_connection_port(connection[1])):
continue
self.connections.append(connection)
self.msg_callback("connect %s %s" % (connection[0], connection[1]))
port_conns.pop(i)
def midi_port_deleted(self, name):
name = charPtrToString(name)
removed_conns = []
for ports in self.connections:
jackports = (self._fix_host_connection_port(ports[0]), self._fix_host_connection_port(ports[1]))
if name not in jackports:
continue
disconnect_jack_ports(jackports[0], jackports[1])
removed_conns.append(ports)
for ports in removed_conns:
self.connections.remove(ports)
disconnect_jack_ports(ports[0], ports[1])
for port_symbol, port_alias, port_conns in self.midiports:
if name == port_symbol or (";" in port_symbol and name in port_symbol.split(";",1)):
port_conns += removed_conns
break
self.msg_callback("remove_hw_port /graph/%s" % (name.split(":",1)[-1]))
def true_bypass_changed(self, left, right):
self.msg_callback("truebypass %i %i" % (left, right))
# -----------------------------------------------------------------------------------------------------------------
# Initialization
@gen.coroutine
def init_host(self):
self.init_jack()
self.open_connection_if_needed(None)
if self.allpedalboards is None:
self.allpedalboards = get_all_good_pedalboards()
bank_id, pedalboard = get_last_bank_and_pedalboard()
yield gen.Task(self.send_notmodified, "remove -1", datatype='boolean')
# FIXME: ensure HMI is initialized by now
if pedalboard:
self.bank_id = bank_id
self.load(pedalboard)
else:
self.bank_id = 0
if os.path.exists(DEFAULT_PEDALBOARD):
self.load(DEFAULT_PEDALBOARD, True)
if self.bank_id > 0 and pedalboard and self.bank_id <= len(self.banks):
bank = self.banks[self.bank_id-1]
navigateFootswitches = bank['navigateFootswitches']
navigateChannel = int(bank['navigateChannel'])-1 if "navigateChannel" in bank.keys() and not navigateFootswitches else 15
else:
navigateFootswitches = False
navigateChannel = 15
self.send_notmodified("midi_program_listen %d %d" % (int(not navigateFootswitches), navigateChannel))
self.send_notmodified("output_data_ready")
init_bypass()
def init_jack(self):
self.audioportsIn = []
self.audioportsOut = []
if not init_jack():
return
for port in get_jack_hardware_ports(True, False):
self.audioportsIn.append(port.split(":",1)[-1])
for port in get_jack_hardware_ports(True, True):
self.audioportsOut.append(port.split(":",1)[-1])
def close_jack(self):
close_jack()
def open_connection_if_needed(self, websocket):
if self.readsock is not None and self.writesock is not None:
self.report_current_state(websocket)
return
def reader_check_response():
self.process_read_queue()
def writer_check_response():
self.connected = True
self.report_current_state(websocket)
self.statstimer.start()
if self.memtimer is not None:
self.memtimer_callback()
self.memtimer.start()
if len(self._queue):
self.process_write_queue()
else:
self._idle = True
self._idle = False
# Main socket, used for sending messages
self.writesock = iostream.IOStream(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
self.writesock.set_close_callback(self.writer_connection_closed)
self.writesock.set_nodelay(True)
self.writesock.connect(self.addr, writer_check_response)
# Extra socket, used for receiving messages
self.readsock = iostream.IOStream(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
self.readsock.set_close_callback(self.reader_connection_closed)
self.readsock.set_nodelay(True)
self.readsock.connect((self.addr[0], self.addr[1]+1), reader_check_response)
def reader_connection_closed(self):
self.readsock = None
def writer_connection_closed(self):
self.writesock = None
self.crashed = True
self.statstimer.stop()
if self.memtimer is not None:
self.memtimer.stop()
self.msg_callback("stop")
# -----------------------------------------------------------------------------------------------------------------
def setNavigateWithFootswitches(self, enabled, callback):
def foot2_callback(ok):
acthw = self._uri2hw_map["/hmi/footswitch2"]
cfgact = BANK_CONFIG_PEDALBOARD_UP if enabled else BANK_CONFIG_NOTHING
self.hmi.bank_config(acthw[0], acthw[1], acthw[2], acthw[3], cfgact, callback)
acthw = self._uri2hw_map["/hmi/footswitch1"]
cfgact = BANK_CONFIG_PEDALBOARD_DOWN if enabled else BANK_CONFIG_NOTHING
self.hmi.bank_config(acthw[0], acthw[1], acthw[2], acthw[3], cfgact, foot2_callback)
def initialize_hmi(self, uiConnected, callback):
# If UI is already connected, do nothing
if uiConnected:
callback(True)
return
bank_id, pedalboard = get_last_bank_and_pedalboard()
# report pedalboard and banks
if bank_id > 0 and pedalboard and bank_id <= len(self.banks):
bank = self.banks[bank_id-1]
pedalboards = bank['pedalboards']
navigateFootswitches = bank['navigateFootswitches']
if "navigateChannel" in bank.keys() and not navigateFootswitches:
navigateChannel = int(bank['navigateChannel'])-1
else:
navigateChannel = 15
else:
if self.allpedalboards is None:
self.allpedalboards = get_all_good_pedalboards()
bank_id = 0
pedalboard = DEFAULT_PEDALBOARD
pedalboards = self.allpedalboards
navigateFootswitches = False
navigateChannel = 15
num = 0
for pb in pedalboards:
if pb['bundle'] == pedalboard:
pedalboard_id = num
break
num += 1
else:
bank_id = 0
pedalboard_id = 0
pedalboard = ""
pedalboards = []
def footswitch_callback(ok):
self.setNavigateWithFootswitches(True, callback)
def midi_prog_callback(ok):
self.send_notmodified("midi_program_listen 1 %d" % navigateChannel, callback, datatype='boolean')
def initial_state_callback(ok):
cb = footswitch_callback if navigateFootswitches else midi_prog_callback
self.hmi.initial_state(bank_id, pedalboard_id, pedalboards, cb)
self.setNavigateWithFootswitches(False, initial_state_callback)
def start_session(self, callback):
if not self.hmi.initialized:
callback(True)
return
def footswitch_addr2_callback(ok):
acthw = self._uri2hw_map["/hmi/footswitch2"]
self._address_next(acthw, callback)
def footswitch_addr1_callback(ok):
acthw = self._uri2hw_map["/hmi/footswitch1"]
self._address_next(acthw, footswitch_addr2_callback)
def footswitch_bank_callback(ok):
self.setNavigateWithFootswitches(False, footswitch_addr1_callback)
self.send_notmodified("midi_program_listen 0 -1")
self.banks = []
self.allpedalboards = []
self.hmi.ui_con(footswitch_bank_callback)
def end_session(self, callback):
if not self.hmi.initialized:
callback(True)
return
def initialize_callback(ok):
self.initialize_hmi(False, callback)
self.banks = list_banks()
self.allpedalboards = get_all_good_pedalboards()
self.hmi.ui_dis(initialize_callback)
# -----------------------------------------------------------------------------------------------------------------
# Message handling
def process_read_queue(self):
def check_message(msg):
msg = msg[:-1].decode("utf-8", errors="ignore")
logging.info("[host] received <- %s" % repr(msg))
msg = msg.split()
cmd = msg[0]
if cmd == "param_set":
instance_id = int(msg[1])
portsymbol = msg[2]
value = float(msg[3])
try:
instance = self.mapper.get_instance(instance_id)
plugin = self.plugins[instance_id]
except:
pass
else:
if portsymbol == ":bypass":
plugin['bypassed'] = bool(value)
else:
plugin['ports'][portsymbol] = value
self.pedalboard_modified = True
self.msg_callback("param_set %s %s %f" % (instance, portsymbol, value))
elif cmd == "output_set":
instance_id = int(msg[1])
portsymbol = msg[2]
value = float(msg[3])
if instance_id == TUNER_INSTANCE:
self.set_tuner_value(value)
else:
try:
instance = self.mapper.get_instance(instance_id)
plugin = self.plugins[instance_id]
except:
pass
else:
plugin['outputs'][portsymbol] = value
self.msg_callback("output_set %s %s %f" % (instance, portsymbol, value))
elif cmd == "midi_mapped":
instance_id = int(msg[1])
portsymbol = msg[2]
channel = int(msg[3])
controller = int(msg[4])
value = float(msg[5])
minimum = float(msg[6])
maximum = float(msg[7])
instance = self.mapper.get_instance(instance_id)
if portsymbol == ":bypass":
self.plugins[instance_id]['bypassCC'] = (channel, controller)
self.plugins[instance_id]['bypassed'] = bool(value)
else:
self.plugins[instance_id]['midiCCs'][portsymbol] = (channel, controller, minimum, maximum)
self.plugins[instance_id]['ports'][portsymbol] = value
self.pedalboard_modified = True
self.msg_callback("midi_map %s %s %i %i %f %f" % (instance, portsymbol,
channel, controller,
minimum, maximum))
self.msg_callback("param_set %s %s %f" % (instance, portsymbol, value))
elif cmd == "midi_program":
program = int(msg[1])
bank_id = self.bank_id
if self.bank_id > 0 and self.bank_id <= len(self.banks):
pedalboards = self.banks[self.bank_id-1]['pedalboards']
else:
pedalboards = self.allpedalboards
if program >= 0 and program < len(pedalboards):
bundlepath = pedalboards[program]['bundle']
def load_callback(ok):
self.bank_id = bank_id
self.load(bundlepath)
def hmi_clear_callback(ok):
self.hmi.clear(load_callback)
self.reset(hmi_clear_callback)
elif cmd == "data_finish":
self.send_output_data_ready()
else:
logging.error("[host] unrecognized command: %s" % cmd)
self.process_read_queue()
if self.readsock is None:
return
self.readsock.read_until(b"\0", check_message)
@gen.coroutine
def send_output_data_ready(self):
yield gen.Task(self.send_notmodified, "output_data_ready", datatype='boolean')
def process_write_queue(self):
try:
msg, callback, datatype = self._queue.pop(0)
logging.info("[host] popped from queue: %s" % msg)
except IndexError:
self._idle = True
return
if self.writesock is None:
self.process_write_queue()
return
def check_response(resp):
if callback is not None:
resp = resp.decode("utf-8", errors="ignore")
logging.info("[host] received <- %s" % repr(resp))
if datatype == 'string':
r = resp
elif not resp.startswith("resp"):
logging.error("[host] protocol error: %s" % ProtocolError(resp))
r = None
else:
r = resp.replace("resp ", "").replace("\0", "").strip()
callback(process_resp(r, datatype))
self.process_write_queue()
self._idle = False
logging.info("[host] sending -> %s" % msg)
encmsg = "%s\0" % str(msg)
self.writesock.write(encmsg.encode("utf-8"))
self.writesock.read_until(b"\0", check_response)
# send data to host, set modified flag to true
def send_modified(self, msg, callback=None, datatype='int'):
self.pedalboard_modified = True
self._queue.append((msg, callback, datatype))
if self._idle:
self.process_write_queue()
# send data to host, don't change modified flag
def send_notmodified(self, msg, callback=None, datatype='int'):
self._queue.append((msg, callback, datatype))
if self._idle:
self.process_write_queue()
# -----------------------------------------------------------------------------------------------------------------
# Host stuff
def mute(self):
disconnect_jack_ports("mod-host:monitor-out_1", "system:playback_1")
disconnect_jack_ports("mod-host:monitor-out_2", "system:playback_2")
disconnect_jack_ports("mod-host:monitor-out_1", "mod-peakmeter:in_3")
disconnect_jack_ports("mod-host:monitor-out_2", "mod-peakmeter:in_4")
def unmute(self):
connect_jack_ports("mod-host:monitor-out_1", "system:playback_1")
connect_jack_ports("mod-host:monitor-out_2", "system:playback_2")
connect_jack_ports("mod-host:monitor-out_1", "mod-peakmeter:in_3")
connect_jack_ports("mod-host:monitor-out_2", "mod-peakmeter:in_4")
def report_current_state(self, websocket):
if websocket is None:
return
data = get_jack_data()
websocket.write_message("mem_load " + self.get_free_memory_value())
websocket.write_message("stats %0.1f %i" % (data['cpuLoad'], data['xruns']))
websocket.write_message("truebypass %i %i" % (get_truebypass_value(False), get_truebypass_value(True)))
websocket.write_message("loading_start %d %d" % (self.pedalboard_empty, self.pedalboard_modified))
websocket.write_message("size %d %d" % (self.pedalboard_size[0], self.pedalboard_size[1]))
crashed = self.crashed
self.crashed = False
if crashed:
self.init_jack()
midiports = []
for port_id, port_alias, _ in self.midiports:
if ";" in port_id:
inp, outp = port_id.split(";",1)
midiports.append(inp)
midiports.append(outp)
else:
midiports.append(port_id)
self.hasSerialMidiIn = has_serial_midi_input_port()
self.hasSerialMidiOut = has_serial_midi_output_port()
# Audio In
for i in range(len(self.audioportsIn)):
name = self.audioportsIn[i]
title = name.title().replace(" ","_")
websocket.write_message("add_hw_port /graph/%s audio 0 %s %i" % (name, title, i+1))
# Audio Out
for i in range(len(self.audioportsOut)):
name = self.audioportsOut[i]
title = name.title().replace(" ","_")
websocket.write_message("add_hw_port /graph/%s audio 1 %s %i" % (name, title, i+1))
# MIDI In
if self.hasSerialMidiIn:
websocket.write_message("add_hw_port /graph/serial_midi_in midi 0 Serial_MIDI_In 0")
ports = get_jack_hardware_ports(False, False)
for i in range(len(ports)):
name = ports[i]
if name not in midiports:
continue
alias = get_jack_port_alias(name)
if alias:
title = alias.split("-",5)[-1].replace("-","_").replace(";",".")
else:
title = name.split(":",1)[-1].title().replace(" ","_")
websocket.write_message("add_hw_port /graph/%s midi 0 %s %i" % (name.split(":",1)[-1], title, i+1))
# MIDI Out
if self.hasSerialMidiOut:
websocket.write_message("add_hw_port /graph/serial_midi_out midi 1 Serial_MIDI_Out 0")
ports = get_jack_hardware_ports(False, True)
for i in range(len(ports)):
name = ports[i]
if name not in midiports:
continue
alias = get_jack_port_alias(name)
if alias:
title = alias.split("-",5)[-1].replace("-","_").replace(";",".")
else:
title = name.split(":",1)[-1].title().replace(" ","_")
websocket.write_message("add_hw_port /graph/%s midi 1 %s %i" % (name.split(":",1)[-1], title, i+1))
for instance_id, plugin in self.plugins.items():
websocket.write_message("add %s %s %.1f %.1f %d" % (plugin['instance'], plugin['uri'],
plugin['x'], plugin['y'], int(plugin['bypassed'])))
if -1 not in plugin['bypassCC']:
mchnnl, mctrl = plugin['bypassCC']
websocket.write_message("midi_map %s :bypass %i %i 0.0 1.0" % (plugin['instance'], mchnnl, mctrl))
if plugin['preset']:
websocket.write_message("preset %s %s" % (plugin['instance'], plugin['preset']))
if crashed:
self.send_notmodified("add %s %d" % (plugin['uri'], instance_id))
if plugin['bypassed']:
self.send_notmodified("bypass %d 1" % (instance_id,))
if -1 not in plugin['bypassCC']:
mchnnl, mctrl = plugin['bypassCC']
self.send_notmodified("midi_map %d :bypass %i %i 0.0 1.0" % (instance_id, mchnnl, mctrl))
if plugin['preset']:
self.send_notmodified("preset_load %d %s" % (instance_id, plugin['preset']))
for symbol, value in plugin['ports'].items():
websocket.write_message("param_set %s %s %f" % (plugin['instance'], symbol, value))
if crashed:
self.send_notmodified("param_set %d %s %f" % (instance_id, symbol, value))
for symbol, value in plugin['outputs'].items():
if value is None:
continue
websocket.write_message("output_set %s %s %f" % (plugin['instance'], symbol, value))
if crashed:
self.send_notmodified("monitor_output %d %s" % (instance_id, symbol))
for symbol, data in plugin['midiCCs'].items():
mchnnl, mctrl, minimum, maximum = data
if -1 in (mchnnl, mctrl):
continue
# don't address "bad" ports
if symbol in plugin['badports']:
continue
websocket.write_message("midi_map %s %s %i %i %f %f" % (plugin['instance'], symbol,
mchnnl, mctrl,
minimum, maximum))
if crashed:
self.send_notmodified("midi_map %d %s %i %i %f %f" % (instance_id, symbol,
mchnnl, mctrl, minimum, maximum))
for port_from, port_to in self.connections:
websocket.write_message("connect %s %s" % (port_from, port_to))
if crashed:
self.send_notmodified("connect %s %s" % (self._fix_host_connection_port(port_from),
self._fix_host_connection_port(port_to)))
websocket.write_message("loading_end")
# -----------------------------------------------------------------------------------------------------------------
# Host stuff - add & remove bundles
def add_bundle(self, bundlepath, callback):
if is_bundle_loaded(bundlepath):
print("SKIPPED add_bundle, already in world")
callback((False, "Bundle already loaded"))
return
def host_callback(ok):
plugins = add_bundle_to_lilv_world(bundlepath)
callback((True, plugins))
self.send_notmodified("bundle_add \"%s\"" % bundlepath.replace('"','\\"'), host_callback, datatype='boolean')
def remove_bundle(self, bundlepath, isPluginBundle, callback):
if not is_bundle_loaded(bundlepath):
print("SKIPPED remove_bundle, not in world")
callback((False, "Bundle not loaded"))
return
if isPluginBundle and len(self.plugins) > 0:
plugins = list_plugins_in_bundle(bundlepath)
for plugin in self.plugins.values():
if plugin['uri'] in plugins:
callback((False, "Plugin is currently in use, cannot remove"))
return
def host_callback(ok):
plugins = remove_bundle_from_lilv_world(bundlepath)
callback((True, plugins))
self.send_notmodified("bundle_remove \"%s\"" % bundlepath.replace('"','\\"'), host_callback, datatype='boolean')
# -----------------------------------------------------------------------------------------------------------------
# Host stuff - reset, add, remove
def reset(self, callback):
def host_callback(ok):
self.msg_callback("remove :all")
callback(ok)
self.bank_id = 0
self.plugins = {}
self.connections = []
self.mapper.clear()
self._init_addressings()
self.pedalboard_empty = True
self.pedalboard_modified = False
self.pedalboard_name = ""
self.pedalboard_path = ""
self.pedalboard_size = [0,0]
self.pedalboard_presets = []
save_last_bank_and_pedalboard(0, "")
self.send_notmodified("remove -1", host_callback, datatype='boolean')
def add_plugin(self, instance, uri, x, y, callback):
self.pedalboard_presets = []
instance_id = self.mapper.get_id(instance)
def host_callback(resp):
if resp < 0:
callback(False)
return
bypassed = False
allports = get_plugin_control_inputs_and_monitored_outputs(uri)
badports = []
valports = {}
enabled_symbol = None
freewheel_symbol = None
for port in allports['inputs']:
symbol = port['symbol']
valports[symbol] = port['ranges']['default']
# skip notOnGUI controls
if "notOnGUI" in port['properties']:
badports.append(symbol)
# skip special designated controls
elif port['designation'] == "http://lv2plug.in/ns/lv2core#enabled":
enabled_symbol = symbol
badports.append(symbol)
valports[symbol] = 0.0 if bypassed else 1.0
elif port['designation'] == "http://lv2plug.in/ns/lv2core#freeWheeling":
freewheel_symbol = symbol
badports.append(symbol)
valports[symbol] = 0.0
self.plugins[instance_id] = {
"instance" : instance,
"uri" : uri,
"bypassed" : bypassed,
"bypassCC" : (-1,-1),
"x" : x,
"y" : y,
"addressings" : {}, # symbol: addressing
"midiCCs" : dict((p['symbol'], (-1,-1,0.0,1.0)) for p in allports['inputs']),
"ports" : valports,
"badports" : badports,
"designations": (enabled_symbol, freewheel_symbol),
"outputs" : dict((symbol, None) for symbol in allports['monitoredOutputs']),
"preset" : "",
"mapPresets" : []
}
for output in allports['monitoredOutputs']:
self.send_notmodified("monitor_output %d %s" % (instance_id, output))
callback(True)
self.msg_callback("add %s %s %.1f %.1f %d" % (instance, uri, x, y, int(bypassed)))
self.send_modified("add %s %d" % (uri, instance_id), host_callback, datatype='int')
@gen.coroutine
def remove_plugin(self, instance, callback):
self.pedalboard_presets = []
instance_id = self.mapper.get_id_without_creating(instance)
try:
data = self.plugins.pop(instance_id)
except KeyError:
callback(False)
return
used_actuators = []
for symbol in [symbol for symbol in data['addressings'].keys()]:
actuator_uri = self._unaddress(data, symbol)
if actuator_uri is not None and actuator_uri not in used_actuators:
used_actuators.append(actuator_uri)
for actuator_uri in used_actuators:
actuator_hw = self._uri2hw_map[actuator_uri]
yield gen.Task(self._address_next, actuator_hw)
def host_callback(ok):
callback(ok)
removed_connections = []
for ports in self.connections:
if ports[0].rsplit("/",1)[0] == instance or ports[1].rsplit("/",1)[0] == instance:
removed_connections.append(ports)
for ports in removed_connections:
self.connections.remove(ports)
self.msg_callback("disconnect %s %s" % (ports[0], ports[1]))
self.msg_callback("remove %s" % (instance))
def hmi_callback(ok):
self.send_modified("remove %d" % instance_id, host_callback, datatype='boolean')
if self.hmi.initialized:
self.hmi.control_rm(instance_id, ":all", hmi_callback)
else:
hmi_callback(True)
# -----------------------------------------------------------------------------------------------------------------
# Host stuff - plugin values
def bypass(self, instance, bypassed, callback):
instance_id = self.mapper.get_id_without_creating(instance)
self.plugins[instance_id]['bypassed'] = bypassed
self.send_modified("bypass %d %d" % (instance_id, int(bypassed)), callback, datatype='boolean')
enabled_symbol = self.plugins[instance_id]['designations'][0]
if enabled_symbol is None:
return
value = 0.0 if bypassed else 1.0
self.plugins[instance_id]['ports'][enabled_symbol] = value
self.send_modified("param_set %d %s %f" % (instance_id, enabled_symbol, value), callback, datatype='boolean')