-
Notifications
You must be signed in to change notification settings - Fork 20
/
audiocontrol2.py
421 lines (338 loc) · 14.4 KB
/
audiocontrol2.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
'''
Copyright (c) 2019 Modul 9/HiFiBerry
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
'''
This is the main audio control process that reads the configuration file,
initializes all subsystems and starts the required threads.
Functionality is implemented in the ac2.* modules
'''
import signal
import configparser
import logging
import os
import sys
import threading
import sys
from ac2.webserver import AudioControlWebserver
from usagecollector.client import report_activate
from ac2.controller import AudioController
import ac2.data.lastfm as lastfmdata
from ac2.plugins.metadata.lastfm import LastFMScrobbler
from ac2.alsavolume import ALSAVolume
from ac2.metadata import Metadata
import ac2.metadata
from ac2.data.mpd import MpdMetadataProcessor
from ac2.players.mpdcontrol import MPDControl
from ac2.players.vollibrespot import VollibspotifyControl
from ac2.players.vollibrespot import MYNAME as SPOTIFYNAME
from ac2.socketio import SocketioAPI
from ac2.processmapper import ProcessMapper
from ac2 import watchdog
mpris = AudioController()
startup_command = None
def pause_all(signalNumber=None, frame=None):
"""
Pause all players on SIGUSR1
"""
if mpris is not None:
mpris.pause_all()
def print_state(signalNumber=None, frame=None):
"""
Display state on USR2
"""
if mpris is not None:
print("\n" + str(mpris))
def create_object(classname, param=None):
# [module_name, class_name] = classname.rsplit(".", 1)
# module = __import__(module_name)
# my_class = getattr(module, class_name)
try:
import importlib
module_name, class_name = classname.rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
if param is None:
instance = MyClass()
else:
instance = MyClass(param)
return instance
except RuntimeError as e:
logging.exception(e)
except ModuleNotFoundError as e1:
logging.exception(e1)
return None
def parse_config(debugmode=False):
server = None
config = configparser.ConfigParser()
config.optionxform = lambda option: option
config.read("/etc/audiocontrol2.conf")
# Auto pause for mpris players
auto_pause = False
if "mpris" in config.sections():
auto_pause = config.getboolean("mpris", "auto_pause",
fallback=False)
loop_delay = config.getint("mpris", "loop_delay",
fallback=1)
mpris.loop_delay = loop_delay
ignore_players = []
for p in config.get("mpris", "ignore",
fallback="").split(","):
playername = p.strip()
ignore_players.append(playername)
logging.info("Ignoring player %s", playername)
mpris.ignore_players = ignore_players
logging.debug("setting auto_pause for MPRIS players to %s",
auto_pause)
mpris.auto_pause = auto_pause
# Web server
if config.getboolean("webserver", "enable", fallback=False):
logging.debug("starting webserver")
port = config.getint("webserver",
"port",
fallback=80)
token = config.get("webserver", "authtoken", fallback=None)
server = AudioControlWebserver(port=port, authtoken=token, debug=debugmode)
mpris.register_metadata_display(server)
server.set_player_control(mpris)
server.add_updater(mpris)
if config.getboolean("webserver", "socketio_enabled", fallback=False):
init_socketio_api(server)
server.start()
watchdog.add_monitored_thread(server, "webserver")
report_activate("audiocontrol_webserver")
logging.info("started web server on port %s", port)
else:
logging.error("web server disabled")
# LastFMScrobbler/LibreFM
if "lastfm" in config.sections():
network = config.get("lastfm", "network",
fallback="lastfm").lower()
username = config.get("lastfm", "username",
fallback=None)
password = config.get("lastfm", "password",
fallback=None)
if network == "lastfm":
apikey = "7d2431d8bb5608574b59ea9c7cfe5cbd"
apisecret = "4722fea27727367810eb550759fa479f"
elif network == "librefm":
apikey = "hifiberry"
apisecret = "hifiberryos"
logging.info("Last.FM network %s", network)
if network is not None:
anon = False
if username is None or username == "" or \
password is None or password == "":
logging.info("using %s anonymously, not scrobbling", network)
username = None
password = None
anon = True
if not(anon):
try:
lastfmscrobbler = LastFMScrobbler(apikey,
apisecret,
username,
password,
None,
network)
mpris.register_metadata_display(lastfmscrobbler)
logging.info("scrobbling to %s as %s", network, username)
lastfmdata.set_lastfmuser(username)
if server is not None:
server.add_lover(lastfmscrobbler)
Metadata.loveSupportedDefault = True
report_activate("audiocontrol_lastfm_scrobble")
except Exception as e:
logging.error("error setting up lastfm module: %s", e)
else:
logging.info("Last.FM not configured")
# Watchdog
if "watchdog" in config.sections():
for player in config["watchdog"]:
services = config["watchdog"][player].split(",")
watchdog.player_mapping[player] = services
logging.info("configuring watchdog %s: %s",
player, services)
# Volume
volume_control = None
if "volume" in config.sections():
mixer_name = config.get("volume",
"mixer_control",
fallback=None)
if mixer_name is not None:
volume_control = ALSAVolume(mixer_name)
logging.info("monitoring mixer %s", mixer_name)
if server is not None:
volume_control.add_listener(server)
server.set_volume_control(volume_control)
volume_control.start()
watchdog.add_monitored_thread(volume_control, "volume control")
mpris.set_volume_control(volume_control)
report_activate("audiocontrol_volume")
if volume_control is None:
logging.info("volume control not configured, "
"disabling volume control support")
# Additional controller modules
for section in config.sections():
if section.startswith("controller:"):
[_, classname] = section.split(":", 1)
logging.info("Controller class: %s", classname)
try:
params = config[section]
controller = create_object(classname, params)
if controller is not None:
controller.set_player_control(mpris)
controller.set_volume_control(volume_control)
mpris.register_state_display(controller)
controller.start()
logging.info("started controller %s", controller)
report_activate("audiocontrol_controller_" + classname)
else:
logging.error("could not create controller %s", classname)
except Exception as e:
logging.error("Exception during controller %s initialization",
classname)
logging.exception(e)
if section.startswith("metadata:"):
[_, classname] = section.split(":", 1)
try:
params = config[section]
metadata_display = create_object(classname, params)
mpris.register_metadata_display(metadata_display)
volume_control.add_listener(metadata_display)
logging.info("registered metadata display %s", metadata_display)
report_activate("audiocontrol_metadata_" + classname)
except Exception as e:
logging.error("Exception during controller %s initialization",
classname)
logging.exception(e)
# Metadata push to GUI
if "metadata_post" in config.sections():
try:
from ac2.plugins.metadata.http_post import MetadataHTTPRequest
url = config.get("metadata_post",
"url",
fallback=None)
if url is None:
logging.error("can't activate metadata_post, url missing")
else:
logging.info("posting metadata to %s", url)
metadata_pusher = MetadataHTTPRequest(url)
mpris.register_metadata_display(metadata_pusher)
except Exception as e:
logging.error("can't activate metadata_post: %s", e)
# Metadata push to GUI
if "volume_post" in config.sections():
if volume_control is None:
logging.info("volume control not configured, "
"can't use volume_post")
try:
from ac2.plugins.volume.http import VolumeHTTPRequest
url = config.get("volume_post",
"url",
fallback=None)
if url is None:
logging.error("can't activate volume_post, url missing")
else:
logging.info("posting volume changes to %s", url)
volume_pusher = VolumeHTTPRequest(url)
volume_control.add_listener(volume_pusher)
except Exception as e:
logging.error("can't activate volume_post: %s", e)
# Native MPD backend and metadata processor
if "mpd" in config.sections():
mpdc = MPDControl()
mpdc.start()
mpris.register_nonmpris_player("mpd", mpdc)
logging.info("registered non-MPRIS mpd backend")
mpddir = config.get("mpd", "musicdir", fallback=None)
if mpddir is not None:
mpdproc = MpdMetadataProcessor(mpddir)
mpris.register_metadata_processor(mpdproc)
logging.info("added MPD cover art handler on %s", mpddir)
# Vollibrespot
vlrctl = VollibspotifyControl()
vlrctl.start()
mpris.register_nonmpris_player(SPOTIFYNAME, vlrctl)
# Other settings
if "privacy" in config.sections():
extmd = config.getboolean("privacy",
"external_metadata",
fallback=True)
if extmd:
logging.info("external metadata enabled")
ac2.metadata.external_metadata = True
else:
logging.info("external metadata disabled")
ac2.metadata.external_metadata = False
else:
logging.info("no privacy settings found, using defaults")
logging.debug("ac2.md.extmd %s", ac2.metadata.external_metadata)
# Web server has to rewrite artwork URLs
if server is not None:
mpris.register_metadata_processor(server)
logging.info("enabled web server meta data processor")
# Other system settings
global startup_command
startup_command = config.get("system", "startup-finished", fallback=None)
# Process mapper
if "processes" in config.sections():
mapper = ProcessMapper()
mapper.load_mappings_from_config(config["processes"])
if debugmode:
from ac2.dev.dummydata import DummyMetadataCreator
dummy = DummyMetadataCreator(server, interval=3)
dummy.start()
def init_socketio_api(webserver):
socketio_api = SocketioAPI(webserver.bottle, mpris)
webserver.socketio_api = socketio_api
mpris.register_metadata_display(socketio_api.metadata_handler)
def main():
verbose = False
if len(sys.argv) > 1:
if "-v" in sys.argv:
verbose = True
if verbose:
logging.basicConfig(format='%(levelname)s: %(module)s - %(message)s',
level=logging.DEBUG)
logging.debug("enabled verbose logging")
else:
logging.basicConfig(format='%(levelname)s: %(module)s - %(message)s',
level=logging.INFO)
if ('DEBUG' in os.environ):
logging.warning("starting in debug mode...")
debugmode = True
else:
debugmode = False
parse_config(debugmode=debugmode)
monitor = threading.Thread(target=watchdog.monitor_threads_and_exit)
monitor.start()
logging.info("started thread monitor for %s",
",".join(watchdog.monitored_threads.keys()))
signal.signal(signal.SIGUSR1, pause_all)
signal.signal(signal.SIGUSR2, print_state)
logging.info("startup finished")
if startup_command is not None:
os.system(startup_command)
# mpris.print_players()
try:
mpris.main_loop()
except Exception as e:
logging.error("main loop crashed with exception %s", e)
logging.exception(e)
logging.info("Main thread stopped")
sys.exit(1)
main()