File: settings.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 (197 lines) | stat: -rw-r--r-- 6,974 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
'''
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.
'''

from collections.abc import Iterable

import logging

from hifiberrydsp.filtering.volume import percent2amplification, \
    decibel2amplification
from hifiberrydsp.filtering.biquad import Biquad
from hifiberrydsp.parser.xmlprofile import XmlProfile
from hifiberrydsp.hardware.adau145x import Adau145x
from hifiberrydsp.datatools import int_data


class SettingsFile():

    def __init__(self, filename, fs=48000, dsp=Adau145x()):
        self.values = {}
        self.fs = fs
        self.dsp = dsp
        with open(filename) as settingsfile:
            for line in settingsfile:
                if len(line.strip()) == 0 or line.startswith("#"):
                    continue

                try:
                    (attrib, value) = line.split(":", maxsplit=1)
                except:
                    logging.error("can't parse line %s", line)
                    continue

                attrib = attrib.strip()
                if attrib.lower().startswith("iir"):
                    value = self.parse_biquad(value)
                else:
                    value = self.parse_value(value.strip())
                self.values[attrib] = value

    def parse_value(self, value):
        if value.endswith("%"):
            percent = int(value[0:-1])
            return percent2amplification(percent)
        elif value.lower().endswith("db"):
            db = int(value[0:-2])
            return decibel2amplification(db)
        elif "." in value:
            return float(value)
        elif value.startswith("0x"):
            return int(value, 16)
        else:
            return int(value)

    def parse_biquad(self, value):
        filters = value.split(",")
        result = []
        for f in filters:
            try:
                biquad = Biquad.create_filter(f, self.fs)
            except Exception:
                biquad = None

            if biquad == None:
                logging.error("can't parse filter definition %s", f)
            else:
                result.append(biquad)
        return result

    def get_updates(self, xmlprofile):

        replace = {}

        for attribute in self.values:
            (addr, length) = xmlprofile.get_addr_length(attribute)
            
            if addr is None and attribute.startswith("0x"):
                # if it's not a setting form the profile, it might be
                # a memory address
                try:
                    addr = int(attribute,16)
                    length = 1
                except: 
                    logging.error("can't parse address %s", addr)
                    addr = None
                        
            if addr is None:
                continue

            val = self.values[attribute]

            word_length = Adau145x.cell_len(addr)
            memory = self.param_to_bytes(val, length, word_length=word_length)

            if len(memory) <= self.dsp.cell_len(addr):
                replace[addr] = memory
            else:
                # Split long replaced into single words
                assert len(memory) % word_length == 0

                while len(memory) > 0:
                    cellvalue = memory[0:word_length]
                    replace[addr] = cellvalue
                    addr += 1
                    memory = memory[word_length:]
                    
        return replace

    def update_xml_profile(self, xmlprofile):
        replace = self.get_updates(xmlprofile)
        xmlprofile.replace_eeprom_cells(replace)
        xmlprofile.replace_ram_cells(replace)

    def param_to_bytes(self, value, max_length=1, ignore_limit=False, word_length=None):
        biquad = False
        
        if word_length is None:
            word_length = self.dsp.WORD_LENGTH

        if isinstance(value, float):
            value = self.dsp.decimal_repr(value)
            res = int_data(value, word_length )
        elif isinstance(value, int):
            res = int_data(value, word_length)
        elif isinstance(value, Biquad):
            res = []
            bqn = value.normalized()
            vals = []
            vals.append(bqn.b2)
            vals.append(bqn.b1)
            vals.append(bqn.b0)
            vals.append(-bqn.a2)
            vals.append(-bqn.a1)
            for v in vals:
                dec = self.dsp.decimal_repr(v)
                res = res + list(int_data(dec, word_length))

        elif isinstance(value, Iterable):
            res = []
            for part in value:
                if isinstance(part, Biquad):
                    biquad = True
                res = res + self.param_to_bytes(part, 0, ignore_limit=True)
        else:
            raise RuntimeError("parameter type not implemented: %s",
                               type(value).__name__)
            
        while len(res) < max_length * word_length:
            if biquad:
                # Fill biquad filter banks with pass filters
                passfilter = Biquad.pass_filter()
                res = res + \
                    self.param_to_bytes(passfilter, 0, ignore_limit=True)
            else:
                # Fill with zeros
                res.append(0)
        if not(ignore_limit) and len(res) > (max_length * word_length):
            logging.error("parameter set too long (%s bytes), won't fit into %s words",
                          len(res),
                          max_length * self.dsp.WORD_LENGTH)
            res = None

        return res


def demo():
    xml = XmlProfile("sample_files/xml/4way-iir.xml")
    xml.write_xml("/tmp/x.xml")
    fs = xml.samplerate()
    rf = SettingsFile("sample_files/simple-settings.txt", fs)
    print(rf.values)
    rf.update_xml_profile(xml)
    print("writing y.xml")
    xml.write_xml("/tmp/y.xml")
    rf = SettingsFile("sample_files/settings.txt", fs)
    print(rf.values)
    rf.update_xml_profile(xml)
    print("writing z.xml")
    xml.write_xml("/tmp/z.xml")