aboutsummaryrefslogtreecommitdiff
path: root/elusive-events.py
blob: ea8a7b5c69f40b1b386ae531268ae1ca7087b087 (plain)
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
#!/usr/bin/env python3

import re, sys, time
import pacmd, pa


DEFAULT_PRINT = ["properties/media.name"]

config = {
    "delay": 0.1,       # type: float
    "print": [],        # type: List[str]
    "printall": False,  # type: bool
    "filter": [],       # type: List[Tuple[str, str]]
    "filterregex": [],  # type: List[Tuple[str, str]]
    "do": [],           # type: List[Tuple[str, Any]]
}


def usage():
    print(\
"""Usage: {argv0} [OPTIONS]

Program for watching and modifying elusive sound events.

By default, this program will regularly poll PulseAudio (using pacmd) for
sink-inputs, and print their details on standard output. You can change the
information printed, filter events, and perform certain actions on matching
events.

Options are as follows:

  -config option=value
    Configuration options are as follows:
      delay: Seconds to sleep between polling for sink-inputs. Default: {config[delay]}

  -print key
    Prints the given key in the log. If this option is not used at all, by
    default the following keys are printed:
      {default_print}
    The available keys can be scouted by running 'pacmd list-sink-inputs'
    while a sound is playing, or by using -printall.

  -printall
    Print all keys in the log. This is pretty verbose.

  -filter key=value
    Process only events for which 'key' exists and matches 'value'; if the
    key does not exists in an event, it is assumed not to match.

  -filter key~=regex
    Same as 'filter key=value', except that 'regex' is a Python regex.

  -do volume=float
    Sets the volume of the event to the given value between 0.0 and 1.0. The
    maximum volume is heuristically determined.

  -do raw_volume=int
    Sets the volume of the event to the given value; this is typically 0 to
    65536, but may be different."""
        .format(argv0=sys.argv[0], config=config, default_print=DEFAULT_PRINT),
        file=sys.stderr)

def parse_args(args):
    global config

    i = 0

    def report_error(fmtstr):
        nonlocal i, args
        print(fmtstr.format(arg=args[i], prev=args[i-1]), file=sys.stderr)
        sys.exit(1)

    def next_arg():
        nonlocal i, args
        if i + 1 < len(args):
            i += 1
            return args[i]
        else:
            report_error("Expected argument after '{arg}'")

    def parse_kv(arg):
        nonlocal i, args
        m = re.fullmatch(r"([^=]*)=(.*)", arg)
        if m:
            return m[1], m[2]
        else:
            report_error("Expected 'key=value' argument after '{prev}'")

    def parse_int(value):
        try:
            return int(value, 10)
        except e:
            report_error("Expected integer value in '{arg}'")

    def parse_float(value):
        try:
            return float(value)
        except e:
            report_error("Expected float value in '{arg}'")

    while i < len(args):
        if args[i] in ["-h", "--help", "-help"]:
            usage()
            sys.exit(0)

        elif args[i] == "-config":
            key, value = parse_kv(next_arg())
            if key == "delay":
                config["delay"] = parse_float(value)
            else:
                report_error("Unknown config key in '{arg}'")

        elif args[i] == "-print":
            config["print"].append(next_arg())

        elif args[i] == "-printall":
            config["printall"] = True

        elif args[i] == "-filter":
            key, value = parse_kv(next_arg())
            if key[-1] == "~":
                config["filterregex"].append((key[:-1], value))
            else:
                config["filter"].append((key, value))

        elif args[i] == "-do":
            key, value = parse_kv(next_arg())
            if key == "volume":
                value = parse_float(value)
                if value < 0 or value > 1:
                    report_error("Volume out of range [0.0, 1.0]: {arg}")
                config["do"].append(("volume", parse_float(value)))
            elif key == "raw_volume":
                config["do"].append(("raw_volume", parse_int(value)))
            else:
                report_error("Unknown action key in '{arg}'")

        else:
            report_error("Unrecognised argument '{arg}'")

        i += 1

    if len(config["print"]) == 0:
        config["print"] = DEFAULT_PRINT

def get_key(inp, key):
    key = key.split("/")
    node = inp.properties()
    for item in key:
        if item not in node.ch: return None
        node = node.ch[item]
    return " ".join(node.value) if type(node.value) == list else node.value

def all_keys(inp):
    def all_keys_of_node(node, prefix):
        res = []
        if type(node) == pacmd.Node and node.value is not None:
            res.append(prefix[1:])
        for k, n in node.ch.items(): res += all_keys_of_node(n, prefix + "/" + k)
        return res
    return all_keys_of_node(inp.properties(), "")

def filters_allow(inp):
    for (key, wanted) in config["filter"]:
        value = get_key(inp, key)
        if value is None or value != wanted:
            return False
    for (key, regex) in config["filterregex"]:
        value = get_key(inp, key)
        if value is None or not re.fullmatch(regex, value):
            return False
    return True

def format_event(inp):
    to_print = config["print"] if not config["printall"] else all_keys(inp)
    line = str(inp.index()) + ":"
    for key in to_print:
        value = get_key(inp, key)
        line += " {}={}".format(key, "<none>" if value is None else repr(value))
    return line

def perform_event_actions(inp):
    for action, arg in config["do"]:
        if action == "volume":
            assert type(arg) == float and 0 <= arg <= 1
            inp.set_volume(arg)
            print("  Set volume to {} on {}".format(arg, inp.index()))
        elif action == "raw_volume":
            assert type(arg) == int
            inp.set_raw_volume(arg)
            print("  Set raw volume to {} on {}".format(arg, inp.index()))
        else:
            assert False

class State:
    def __init__(self):
        self.ongoing = set()

    def poll(self):
        newev = {inp.index(): inp for inp in pa.list_sink_inputs()}

        # Remove events that are not ongoing anymore
        self.ongoing &= newev.keys()

        # Ignore ongoing events
        for k in self.ongoing:
            if k in newev:
                newev.pop(k)

        # New events are now also ongoing
        self.ongoing |= newev.keys()

        # Ignore any filtered-out events
        filtered_out = [index for index, inp in newev.items()
                        if not filters_allow(inp)]
        for k in filtered_out:
            newev.pop(k)

        for inp in newev.values():
            print(format_event(inp))

        for inp in newev.values():
            perform_event_actions(inp)

def main():
    parse_args(sys.argv[1:])
    #  print(config)

    state = State()
    try:
        while True:
            state.poll()
            time.sleep(config["delay"])
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()