File: alsasync.py

package info (click to toggle)
hifiberry-dsp 0.21-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 22,456 kB
  • sloc: xml: 6,099; python: 4,248; sh: 70; makefile: 2
file content (280 lines) | stat: -rw-r--r-- 8,973 bytes parent folder | download
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
'''
Copyright (c) 2018 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.
'''
import time
import logging
import select
import tempfile
import os

from threading import Thread

from hifiberrydsp.hardware.adau145x import Adau145x
from hifiberrydsp.filtering.volume import percent2amplification, amplification2percent
from hifiberrydsp import datatools
from hifiberrydsp.hardware.spi import SpiHandler

DIRECTION_TO_DSP = 1
DIRECTION_TO_ALSA = 2
DIRECTION_TWO_WAY = 3

ALSA_STATE_FILE = """
state.sndrpihifiberry {
        control.99 {
                iface MIXER
                name %VOLUME%
                value.0 255
                value.1 255
                comment {
                        access 'read write user'
                        type INTEGER
                        count 2
                        range '0 - 255'
                        tlv '0000000100000008ffffdcc400000023'
                        dbmin -9020
                        dbmax -95
                        dbvalue.0 -95
                        dbvalue.1 -95
                }
        }
}
"""


class AlsaSync(Thread):
    '''
    Synchronises a dummy ALSA mixer control with a volume control 
    register of the DSP.
    '''

    def __init__(self):

        self.alsa_control = None
        self.volume_register = None
        self.dsp = Adau145x
        self.volume_register_length = self.dsp.WORD_LENGTH
        self.finished = False
        self.pollinterval = 1000  # milliseconds
        self.spi = SpiHandler
        self.dspdata = None
        self.dspvol = None
        self.alsavol = None
        self.softvol = None
        self.mixername = None

        Thread.__init__(self)

    def set_volume_register(self, volume_register):
        logging.debug("Using volume register %s", volume_register)
        self.volume_register = volume_register
        # When setting a new Volume register, always update ALSA to
        # state of the DSP
        self.read_dsp_data()
        self.update_alsa(self.dspvol)

    def set_alsa_control(self, alsa_control):
        from alsaaudio import Mixer
        self.mixer = self.get_dsp_mixer(alsa_control)
        if self.mixer != None:
            logging.debug("using existing ALSA control %s", alsa_control)
        else:
            try:
                logging.debug(
                    "ALSA control %s does not exist, creating it", alsa_control)

                self.mixer = self.create_mixer(alsa_control)
            except Exception as e:
                logging.error(
                    "can't create ALSA mixer control %s (%s)",
                    alsa_control, e)
            return False

        if self.mixer == None:
            logging.error("ALSA mixer %s not found", alsa_control)
            return False

        self.mixername = alsa_control
        return True

    def update_alsa(self, value, mixer=None):
        if value is None:
            return

        from alsaaudio import MIXER_CHANNEL_ALL
        vol = round(value)

        if mixer is None:
            mixer = self.mixer

        if mixer is not None:
            mixer.setvolume(vol, MIXER_CHANNEL_ALL)

        self.alsavol = vol

    def update_dsp(self, value):
        if value is None:
            return

        # convert percent to multiplier
        logging.debug("Updating DSP to %s",value)
        volume = percent2amplification(value)

        # write multiplier to DSP
        dspdata = datatools.int_data(self.dsp.decimal_repr(volume),
                                     self.volume_register_length)
        self.spi.write(self.volume_register, dspdata)

        self.dspdata = dspdata
        self.dspvol = value
    

    def read_alsa_data(self):
        from alsaaudio import Mixer
        volumes = self.get_dsp_mixer(self.mixername).getvolume()
        channels = 0
        vol = 0
        for i in range(len(volumes)):
            channels += 1
            vol += volumes[i]

        if channels > 0:
            vol = round(vol / channels)
            
        if vol != self.alsavol:
            logging.debug(
                "ALSA volume changed from {}% to {}%".format(self.alsavol, vol))
            self.alsavol = vol
            return True
        else:
            return False

    def read_dsp_data(self):
        if self.volume_register is None:
            self.dspdata = None
            self.dspvol = None
            return False

        dspdata = self.spi.read(
            self.volume_register, self.volume_register_length)

        if dspdata != self.dspdata:

            # Convert to percent and round to full percent
            vol = round(amplification2percent(self.dsp.decimal_val(dspdata)))

            if vol < 0:
                vol = 0
            elif vol > 100:
                vol = 100

            logging.debug(
                "DSP volume changed from {}% to {}%".format(self.dspvol, vol))
            self.dspvol = vol

            self.dspdata = dspdata
            return True
        else:
            return False

    def get_dsp_mixer(self, mixername):
        import alsaaudio
        find_card = True
        i=0
        while(find_card):
            try:
                mixers = alsaaudio.mixers(cardindex=i)
                if [match for match in mixers if mixername in match]:
                    hw_dev = "hw:{0}".format(str(i))
                    return alsaaudio.Mixer(mixername,device=hw_dev)
            except:
                find_card = False
            i+=1
        return None

    def check_sync(self):
        alsa_changed = self.read_alsa_data()
        dsp_changed = self.read_dsp_data()

        # Check if one of the control has changed and update the other
        # one. If both have changed, ALSA takes precedence
        if alsa_changed:
            logging.debug("Updating DSP volume from ALSA")
            self.update_dsp(self.alsavol)
        elif dsp_changed:
            logging.debug("Updating ALSA volume from DSP")
            self.update_alsa(self.dspvol)

    def run(self):
        reg_set = True
        try:
            while not(self.finished):
                if self.mixer is None:
                    logging.error(
                        "ALSA mixer not available, aborting volume synchronisation")
                    break

                if self.volume_register is None:
                    # Volume control register can change when a new program is
                    # uploaded, just go on and try again later
                    if reg_set:
                        logging.error(
                            "ALSA mixer not available, volume register unknown in profile")
                        reg_set = False
                    time.sleep(1)
                    continue
                else:
                    reg_set = True

                poller = select.poll()
                poller.register(*(self.mixer.polldescriptors()[0]))
                poller.poll(self.pollinterval)
                self.mixer.handleevents()

                self.check_sync()
        except Exception as e:
            logging.error("ALSA sync crashed: %s", e)

    def finish(self):
        self.finished = True

    @staticmethod
    def create_mixer(name):

        with tempfile.NamedTemporaryFile(mode='w', dir="/tmp", delete=False) as asoundstate:
            content = ALSA_STATE_FILE.replace("%VOLUME%", name)
            logging.debug("asoundstate file %s", content)
            asoundstate.write(content)
            asoundstate.close()
            
        

        command = "/usr/sbin/alsactl -f {} restore".format(
            asoundstate.name)
        logging.debug("runnning %s", command)
        os.system(command)
        
        try:
            from alsaaudio import Mixer, mixers
            logging.info("mixers: ", mixers())
            return Mixer(name)
        except:
            from alsaaudio import cards, ALSAAudioError
            raise ALSAAudioError("Mixer {} not found (cards: {})".format(name, cards()))