-
Notifications
You must be signed in to change notification settings - Fork 14
/
mixer.py
207 lines (175 loc) · 6.87 KB
/
mixer.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
import logging
import math
import select
import threading
import alsaaudio
import gi
import pykka
gi.require_version("GstAudio", "1.0") # noqa
from gi.repository import GstAudio # noqa isort:skip
from mopidy import exceptions, mixer # noqa isort:skip
logger = logging.getLogger(__name__)
class AlsaMixer(pykka.ThreadingActor, mixer.Mixer):
name = "alsamixer"
def __init__(self, config):
super().__init__()
self.config = config
self.control = self.config["alsamixer"]["control"]
self.device = self.config["alsamixer"]["device"]
card = self.config["alsamixer"]["card"]
self.min_volume = self.config["alsamixer"]["min_volume"]
self.max_volume = self.config["alsamixer"]["max_volume"]
self.volume_scale = self.config["alsamixer"]["volume_scale"]
self.device_title = f"device {self.device!r}"
if card is not None:
self.device = f"hw:{card:d}"
self.device_title = f"card {card:d}"
known_cards = alsaaudio.cards()
try:
known_controls = alsaaudio.mixers(device=self.device)
except alsaaudio.ALSAAudioError:
raise exceptions.MixerError(
f"Could not find ALSA {self.device_title}. "
"Known soundcards include: "
f"{', '.join(known_cards)}"
)
if self.control not in known_controls:
raise exceptions.MixerError(
"Could not find ALSA mixer control "
f"{self.control} on {self.device_title}. "
f"Known mixers on {self.device_title} include: "
f"{', '.join(known_controls)}"
)
self._last_volume = None
self._last_mute = None
logger.info(
f"Mixing using ALSA, {self.device_title}, "
f"mixer control {self.control!r}."
)
def on_start(self):
self._observer = AlsaMixerObserver(
device=self.device,
control=self.control,
callback=self.actor_ref.proxy().trigger_events_for_changed_values,
)
self._observer.start()
@property
def _mixer(self):
# The mixer must be recreated every time it is used to be able to
# observe volume/mute changes done by other applications.
return alsaaudio.Mixer(
device=self.device,
control=self.control,
)
def get_volume(self):
channels = self._mixer.getvolume()
if not channels:
return None
elif channels.count(channels[0]) == len(channels):
return self.mixer_volume_to_volume(channels[0])
else:
# Not all channels have the same volume
return None
def set_volume(self, volume):
self._mixer.setvolume(self.volume_to_mixer_volume(volume))
return True
def mixer_volume_to_volume(self, mixer_volume):
volume = mixer_volume
if self.volume_scale == "cubic":
volume = (
GstAudio.StreamVolume.convert_volume(
GstAudio.StreamVolumeFormat.CUBIC,
GstAudio.StreamVolumeFormat.LINEAR,
volume / 100.0,
)
* 100.0
)
elif self.volume_scale == "log":
# Uses our own formula rather than GstAudio.StreamVolume.
# convert_volume(GstAudio.StreamVolumeFormat.LINEAR,
# GstAudio.StreamVolumeFormat.DB, mixer_volume / 100.0)
# as the result is a DB value, which we can't work with as
# self._mixer provides a percentage.
volume = math.pow(10, volume / 50.0)
volume = (
(volume - self.min_volume)
* 100.0
/ (self.max_volume - self.min_volume)
)
return int(volume)
def volume_to_mixer_volume(self, volume):
mixer_volume = (
self.min_volume
+ volume * (self.max_volume - self.min_volume) / 100.0
)
if self.volume_scale == "cubic":
mixer_volume = (
GstAudio.StreamVolume.convert_volume(
GstAudio.StreamVolumeFormat.LINEAR,
GstAudio.StreamVolumeFormat.CUBIC,
mixer_volume / 100.0,
)
* 100.0
)
elif self.volume_scale == "log":
# Uses our own formula rather than GstAudio.StreamVolume.
# convert_volume(GstAudio.StreamVolumeFormat.LINEAR,
# GstAudio.StreamVolumeFormat.DB, mixer_volume / 100.0)
# as the result is a DB value, which we can't work with as
# self._mixer wants a percentage.
mixer_volume = 50 * math.log10(mixer_volume)
return int(mixer_volume)
def get_mute(self):
try:
channels_muted = self._mixer.getmute()
except alsaaudio.ALSAAudioError as exc:
logger.debug(f"Getting mute state failed: {exc}")
return None
if all(channels_muted):
return True
elif not any(channels_muted):
return False
else:
# Not all channels have the same mute state
return None
def set_mute(self, mute):
try:
self._mixer.setmute(int(mute))
return True
except alsaaudio.ALSAAudioError as exc:
logger.debug(f"Setting mute state failed: {exc}")
return False
def trigger_events_for_changed_values(self):
old_volume, self._last_volume = self._last_volume, self.get_volume()
old_mute, self._last_mute = self._last_mute, self.get_mute()
if old_volume != self._last_volume:
self.trigger_volume_changed(self._last_volume)
if old_mute != self._last_mute:
self.trigger_mute_changed(self._last_mute)
class AlsaMixerObserver(threading.Thread):
daemon = True
name = "AlsaMixerObserver"
def __init__(self, device, control, callback=None):
super().__init__()
self.running = True
# Keep the mixer instance alive for the descriptors to work
self.mixer = alsaaudio.Mixer(device=device, control=control)
descriptors = self.mixer.polldescriptors()
assert len(descriptors) == 1
self.fd = descriptors[0][0]
self.event_mask = descriptors[0][1]
self.callback = callback
def stop(self):
self.running = False
def run(self):
poller = select.epoll()
poller.register(self.fd, self.event_mask | select.EPOLLET)
while self.running:
try:
events = poller.poll(timeout=1)
if events and self.callback is not None:
self.callback()
except OSError as exc:
# poller.poll() will raise an IOError because of the
# interrupted system call when suspending the machine.
logger.debug(f"Ignored IO error: {exc}")