-
Notifications
You must be signed in to change notification settings - Fork 57
/
zynthian_autoconnect.py
executable file
·603 lines (491 loc) · 16.4 KB
/
zynthian_autoconnect.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
# -*- coding: utf-8 -*-
#********************************************************************
# ZYNTHIAN PROJECT: Zynthian Autoconnector
#
# Autoconnect Jack clients
#
# Copyright (C) 2015-2016 Fernando Moyano <jofemodo@zynthian.org>
#
#********************************************************************
#
# 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 2 of
# the License, or 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.
#
# For a full copy of the GNU General Public License see the LICENSE.txt file.
#
#********************************************************************
import sys
import os
import jack
import copy
import logging
from time import sleep
from threading import Thread, Lock
from collections import OrderedDict
# Zynthian specific modules
from zyngui import zynthian_gui_config
#-------------------------------------------------------------------------------
# Configure logging
#-------------------------------------------------------------------------------
log_level = logging.ERROR
logger=logging.getLogger(__name__)
logger.setLevel(log_level)
#if log_level==logging.DEBUG:
# import inspect
#-------------------------------------------------------------------------------
# Define some Constants and Global Variables
#-------------------------------------------------------------------------------
refresh_time = 2
jclient = None
thread = None
exit_flag = False
last_hw_str = None
#------------------------------------------------------------------------------
def get_port_alias_id(midi_port):
try:
alias_id='_'.join(midi_port.aliases[0].split('-')[5:])
except:
alias_id=midi_port.name
return alias_id
#Dirty hack for having MIDI working with PureData & CSound: #TODO => Improve it!!
def get_fixed_midi_port_name(port_name):
if port_name=="pure_data":
port_name = "Pure Data"
elif port_name=="csound6":
port_name = "Csound"
return port_name
#------------------------------------------------------------------------------
def midi_autoconnect(force=False):
global last_hw_str
#Get Mutex Lock
acquire_lock()
logger.info("ZynAutoConnect: MIDI ...")
#------------------------------------
# Get Input/Output MIDI Ports:
# - outputs are inputs for jack
# - inputs are outputs for jack
#------------------------------------
#Get Physical MIDI input ports ...
hw_out=jclient.get_ports(is_output=True, is_physical=True, is_midi=True)
if len(hw_out)==0:
hw_out=[]
#Get Physical MIDI output ports ...
hw_in=jclient.get_ports(is_input=True, is_physical=True, is_midi=True)
if len(hw_in)==0:
hw_in=[]
#Add ZynthStep out port ...
zynthstep_out=jclient.get_ports("zynthstep", is_output=True, is_physical=False, is_midi=True)
try:
hw_out.append(zynthstep_out[0])
except:
pass
#Add Aubio MIDI out port ...
if zynthian_gui_config.midi_aubionotes_enabled:
aubio_out=jclient.get_ports("aubio", is_output=True, is_physical=False, is_midi=True)
try:
hw_out.append(aubio_out[0])
except:
pass
#Add TouchOSC out ports ...
if zynthian_gui_config.midi_touchosc_enabled:
rtmidi_out=jclient.get_ports("RtMidiOut Client", is_output=True, is_physical=False, is_midi=True)
for port in rtmidi_out:
try:
hw_out.append(port)
except:
pass
#logger.debug("Input Device Ports: {}".format(hw_out))
#logger.debug("Output Device Ports: {}".format(hw_in))
#Calculate device list fingerprint (HW & virtual)
hw_str=""
for hw in hw_out:
hw_str += hw.name + "\n"
for hw in hw_in:
hw_str += hw.name + "\n"
#Get RTP-MIDI input/output ports ...
if zynthian_gui_config.midi_rtpmidi_enabled:
try:
rtpmidi_out=jclient.get_ports("jackrtpmidid", is_output=True, is_physical=False, is_midi=True)
#logger.debug("RTP-MIDI Input Port: {}".format(rtpmidi_out))
for p in rtpmidi_out:
hw_str += p.name + "\n"
except:
pass
try:
rtpmidi_in=jclient.get_ports("jackrtpmidid", is_input=True, is_physical=False, is_midi=True)
#logger.debug("RTP-MIDI Output Port: {}".format(rtpmidi_in))
for p in rtpmidi_in:
hw_str += p.name + "\n"
except:
pass
#Get QMidiNet input/output ports ...
if zynthian_gui_config.midi_network_enabled:
try:
qmidinet_out=jclient.get_ports("QmidiNet", is_output=True, is_physical=False, is_midi=True)
#logger.debug("QMidiNet Input Port: {}".format(qmidinet_out))
for qmp in qmidinet_out:
hw_str += qmp.name + "\n"
except:
pass
try:
qmidinet_in=jclient.get_ports("QmidiNet", is_input=True, is_physical=False, is_midi=True)
#logger.debug("QMidiNet Output Port: {}".format(qmidinet_in))
for qmp in qmidinet_in:
hw_str += qmp.name + "\n"
except:
pass
#Get Engines list from UI
zyngine_list=zynthian_gui_config.zyngui.screens["engine"].zyngines
#Get Engines MIDI input ports
engines_in=[]
for k, zyngine in zyngine_list.items():
if zyngine.jackname:
port_name = get_fixed_midi_port_name(zyngine.jackname)
else:
continue
#logger.debug("Zyngine (MIDI-IN): {}".format(port_name))
ports = jclient.get_ports(port_name, is_input=True, is_midi=True, is_physical=False)
try:
port=ports[0]
#Dirty hack for zynaddsubfx: #TODO => Improve it!!!
if port_name=="zynaddsubfx" and port.shortname=='osc':
port=ports[1]
#logger.debug("Engine {}:{} found".format(zyngine.jackname,port.short_name))
#List of tuples => [port, active_channels]
engines_in.append([port, zyngine.get_active_midi_channels()])
except:
#logger.warning("Engine {} is not present".format(zyngine.jackname))
pass
#logger.debug("Synth Engine Input Ports: {}".format(engines_in))
#Check for new devices (HW and virtual)...
if not force and hw_str==last_hw_str:
last_hw_str = hw_str
#Release Mutex Lock
release_lock()
return
else:
last_hw_str = hw_str
#Get Synth Engines MIDI output ports
engines_out=[]
for k, zyngine in zyngine_list.items():
if zyngine.jackname:
port_name = get_fixed_midi_port_name(zyngine.jackname)
else:
continue
#logger.debug("Zyngine MIDI-OUT: {}".format(port_name))
ports=jclient.get_ports(port_name, is_output=True, is_midi=True, is_physical=False)
try:
port=ports[0]
#logger.debug("Engine {}:{} found".format(zyngine.jackname,port.short_name))
#List of tuples => [port, active_channels]
engines_out.append([port, zyngine.get_active_midi_channels()])
except:
#logger.warning("Engine {} is not present".format(zyngine.jackname))
pass
#logger.debug("Synth Engine Output Ports: {}".format(engines_out))
#Get Zynthian Midi Router MIDI ports
zmr_out=OrderedDict()
for p in jclient.get_ports("ZynMidiRouter", is_output=True, is_midi=True):
zmr_out[p.shortname]=p
zmr_in=OrderedDict()
for p in jclient.get_ports("ZynMidiRouter", is_input=True, is_midi=True):
zmr_in[p.shortname]=p
#logger.debug("ZynMidiRouter Input Ports: {}".format(zmr_out))
#logger.debug("ZynMidiRouter Output Ports: {}".format(zmr_in))
#------------------------------------
# Auto-Connect MIDI Ports
#------------------------------------
#Connect "Not Disabled" Input Device Ports to ZynMidiRouter:main_in
for hw in hw_out:
#logger.debug("Connecting MIDI Input {} => {}".format(hw,zmr_in['main_in']))
try:
if get_port_alias_id(hw) in zynthian_gui_config.disabled_midi_in_ports:
jclient.disconnect(hw,zmr_in['main_in'])
else:
jclient.connect(hw,zmr_in['main_in'])
except Exception as e:
#logger.debug("Exception {}".format(e))
pass
#logger.debug("Connecting RTP-MIDI & QMidiNet to ZynMidiRouter:net_in ...")
#Connect RTP-MIDI Input Port to ZynMidiRouter:net_in
try:
jclient.connect(rtpmidi_out[0],zmr_in['net_in'])
except:
pass
#Connect QMidiNet Input Port to ZynMidiRouter:net_in
try:
jclient.connect(qmidinet_out[0],zmr_in['net_in'])
except:
pass
#Connect Engine's Controller-FeedBack to ZynMidiRouter:ctrl_in
try:
for eop in engines_out:
jclient.connect(eop[0],zmr_in['ctrl_in'])
except:
pass
#logger.debug("Connecting ZynMidiRouter to engines ...")
#Connect ZynMidiRouter to engines
for eip in engines_in:
if eip[1] is None:
try:
jclient.connect(zmr_out['main_out'],eip[0])
except:
pass
for ch in range(0,16):
try:
jclient.disconnect(zmr_out['ch{}_out'.format(ch)],eip[0])
except:
pass
else:
try:
jclient.disconnect(zmr_out['main_out'],eip[0])
except:
pass
for ch in range(0,16):
if ch in eip[1]:
try:
jclient.connect(zmr_out['ch{}_out'.format(ch)],eip[0])
except:
pass
else:
try:
jclient.disconnect(zmr_out['ch{}_out'.format(ch)],eip[0])
except:
pass
#Connect ZynMidiRouter:midi_out to enabled MIDI-OUT ports
for hw in hw_in:
try:
if get_port_alias_id(hw) in zynthian_gui_config.enabled_midi_out_ports:
jclient.connect(zmr_out['midi_out'],hw)
else:
jclient.disconnect(zmr_out['midi_out'],hw)
except:
pass
#Connect ZynMidiRouter:net_out to QMidiNet Output Port
try:
jclient.connect(zmr_out['net_out'],qmidinet_in[0])
except:
pass
#Connect ZynMidiRouter:net_out to RTP-MIDI Output Port
try:
jclient.connect(zmr_out['net_out'],rtpmidi_in[0])
except:
pass
#Connect ZynMidiRouter:ctrl_out to enabled MIDI-FB ports (MIDI-Controller FeedBack)
for hw in hw_in:
try:
if get_port_alias_id(hw) in zynthian_gui_config.enabled_midi_fb_ports:
jclient.connect(zmr_out['ctrl_out'],hw)
else:
jclient.disconnect(zmr_out['ctrl_out'],hw)
except:
pass
# Connect MIDI clock to ZynthStep
if zynthian_gui_config.midi_clock_enabled:
try:
jclient.connect("jack_midi_clock:mclk_out","zynthstep:input")
except:
logger.error("Failed to connect internal MIDI clock to ZynthStep")
else:
try:
# TODO: This should be configured from webconf ...
jclient.connect("a2j:MidiSport 2x2 [20] (capture): MidiSport 2x2 MIDI 1", "zynthstep:input")
except:
logger.error("Failed to connect external MIDI clock to ZynthStep")
#Release Mutex Lock
release_lock()
def audio_autoconnect(force=False):
if not force:
logger.info("ZynAutoConnect: Escaped for Audio ...")
return
#Get Mutex Lock
acquire_lock()
logger.info("ZynAutoConnect: Audio ...")
#Get Audio Input Ports (ports receiving audio => inputs => you write on it!!)
input_ports=get_audio_input_ports()
#Disconnect Monitor from System Output
mon_in=jclient.get_ports("mod-monitor", is_output=True, is_audio=True)
try:
jclient.disconnect(mon_in[0],input_ports['system'][0])
jclient.disconnect(mon_in[1],input_ports['system'][1])
except:
pass
#Get layers list from UI
layers_list=zynthian_gui_config.zyngui.screens["layer"].layers
#Connect Synth Engines to assigned outputs
for i, layer in enumerate(layers_list):
if not layer.get_jackname():
continue
ports=jclient.get_ports(layer.get_jackname(), is_output=True, is_audio=True, is_physical=False)
if ports:
#logger.debug("Num of {} Audio Ports: {}".format(layer.get_jackname(), len(ports)))
if len(ports)==1:
ports.append(ports[0])
#logger.debug("Converting to Stereo Output {} ...".format(layer.get_jackname()))
#logger.debug("Autoconnecting Engine {} ...".format(layer.get_jackname()))
#Connect to assigned ports and disconnect from the rest ...
for ao in input_ports:
if ao in layer.get_audio_out():
if len(input_ports[ao])==1:
input_ports[ao].append(input_ports[ao][0])
#logger.debug(" => Connecting to {}".format(ao))
for j in range(len(ports)):
try:
jclient.connect(ports[j],input_ports[ao][j%2])
except:
pass
else:
for j in range(len(ports)):
try:
jclient.disconnect(ports[j],input_ports[ao][j%2])
except:
pass
#Setup dpmeter connections if enabled ...
if not zynthian_gui_config.show_cpu_status:
#Prepare for setup dpmeter connections
dpmeter_out = jclient.get_ports("jackpeak", is_input=True, is_audio=True)
dpmeter_conports_1=jclient.get_all_connections("jackpeak:input_a")
dpmeter_conports_2=jclient.get_all_connections("jackpeak:input_b")
sysout_conports_1 = jclient.get_all_connections("system:playback_1")
sysout_conports_2 = jclient.get_all_connections("system:playback_2")
#Disconnect ports from dpmeter (those that are not connected to System Out, if any ...)
for cp in dpmeter_conports_1:
if cp not in sysout_conports_1:
try:
jclient.disconnect(cp,dpmeter_out[0])
except:
pass
for cp in dpmeter_conports_2:
if cp not in sysout_conports_2:
try:
jclient.disconnect(cp,dpmeter_out[1])
except:
pass
#Connect ports to dpmeter (those currently connected to System Out)
for cp in sysout_conports_1:
try:
jclient.connect(cp,dpmeter_out[0])
except:
pass
for cp in sysout_conports_2:
try:
jclient.connect(cp,dpmeter_out[1])
except:
pass
#Get System Capture ports => jack output ports!!
system_capture=jclient.get_ports(is_output=True, is_audio=True, is_physical=True)
if len(system_capture)>0:
#Connect system capture to effect root layers ...
root_layers=zynthian_gui_config.zyngui.screens["layer"].get_fxchain_roots()
for rl in root_layers:
if not rl.get_jackname():
continue
#Get Root Layer Input ports ...
rl_in=jclient.get_ports(rl.get_jackname(), is_input=True, is_audio=True)
#Connect System Capture to Root Layer ports
if len(rl_in)>0:
if len(rl_in)==1:
rl_in.append(rl_in[0])
try:
jclient.connect(system_capture[0],rl_in[0])
jclient.connect(system_capture[1],rl_in[1])
except:
pass
if zynthian_gui_config.midi_aubionotes_enabled:
#Get Aubio Input ports ...
aubio_in=jclient.get_ports("aubio", is_input=True, is_audio=True)
#Connect System Capture to Aubio ports
if len(aubio_in)>0:
if len(aubio_in)==1:
aubio_in.append(aubio_in[0])
try:
jclient.connect(system_capture[0],aubio_in[0])
jclient.connect(system_capture[1],aubio_in[1])
except:
pass
#Release Mutex Lock
release_lock()
def audio_disconnect_sysout():
sysout_ports=jclient.get_ports("system", is_input=True, is_audio=True)
for sop in sysout_ports:
conports = jclient.get_all_connections(sop)
for cp in conports:
try:
jclient.disconnect(cp, sop)
except:
pass
def get_audio_input_ports():
res=OrderedDict()
try:
for aip in jclient.get_ports(is_input=True, is_audio=True, is_physical=False):
parts=aip.name.split(':')
client_name=parts[0]
if client_name[:7]=="effect_" or client_name=="jack_capture" or client_name=="jackpeak":
continue
if client_name not in res:
res[client_name]=[aip]
#logger.debug("AUDIO INPUT PORT: {}".format(client_name))
else:
res[client_name].append(aip)
except:
pass
return res
def autoconnect(force=False):
midi_autoconnect(force)
audio_autoconnect(force)
def autoconnect_thread():
while not exit_flag:
try:
autoconnect()
except Exception as err:
logger.error("ZynAutoConnect ERROR: {}".format(err))
sleep(refresh_time)
def acquire_lock():
#if log_level==logging.DEBUG:
# calframe = inspect.getouterframes(inspect.currentframe(), 2)
# logger.debug("Waiting for lock, requested from '{}'...".format(format(calframe[1][3])))
lock.acquire()
#logger.debug("... lock acquired!!")
def release_lock():
#if log_level==logging.DEBUG:
# calframe = inspect.getouterframes(inspect.currentframe(), 2)
# logger.debug("Lock released from '{}'".format(calframe[1][3]))
lock.release()
def start(rt=2):
global refresh_time, exit_flag, jclient, thread, lock
refresh_time=rt
exit_flag=False
try:
jclient=jack.Client("Zynthian_autoconnect")
jclient.set_xrun_callback(cb_jack_xrun)
jclient.activate()
except Exception as e:
logger.error("ZynAutoConnect ERROR: Can't connect with Jack Audio Server ({})".format(e))
# Create Lock object (Mutex) to avoid concurrence problems
lock=Lock();
# Start Autoconnect Thread
thread=Thread(target=autoconnect_thread, args=())
thread.daemon = True # thread dies with the program
thread.start()
def stop():
global exit_flag
exit_flag=True
acquire_lock()
audio_disconnect_sysout()
release_lock()
def is_running():
global thread
return thread.is_alive()
def cb_jack_xrun(delayed_usecs: float):
logger.error("Jack Audio XRUN!")
zynthian_gui_config.zyngui.status_info['xrun'] = True
def get_jack_cpu_load():
return jclient.cpu_load()
#------------------------------------------------------------------------------