forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpulsehelper.py
More file actions
executable file
·356 lines (280 loc) · 10.1 KB
/
pulsehelper.py
File metadata and controls
executable file
·356 lines (280 loc) · 10.1 KB
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
#!/usr/bin/env python
# A quickie way to switch audio between internal speakers and a USB hub,
# using pulseaudio commandline tools.
# Adjust as needed for your specific audio devices.
# To see your available audio devices: pacmd list-cards
# For each card, look under "profiles:"
# Uses the termcolor module if it's available to highlight fallbacks
# and muted devices.
import sys, os
import subprocess
# The configuration, if any, is global.
config = {}
# If python-termcolor is installed, show muted items in red.
try:
from termcolor import colored
def mutedstring(s):
return colored(s, 'red')
def fallbackstring(s):
return colored(s, 'green', attrs=['bold'])
except:
def mutedstring(s):
return f' ({s})'
def fallbackstring(s):
return '** ' + s
def parse_cards():
"""Get a list of cards"""
cards = []
internal_card = None
usb_card = None
for line in subprocess.check_output(['pactl', 'list',
'short', 'cards']).split(b'\n'):
if line:
card = line.split()[1].decode()
cards.append(card)
if '.usb' in card:
usb_card = card
elif '.pci' in card:
internal_card = card
return cards
def parse_volume(words):
if words[1] == b'front-left:':
return [int(words[2]), int(words[9])]
if words[1] == b'mono:':
return [int(words[2])]
print("Can't parse volume line:", words)
return None
def after_equals(line):
eq = line.index(b'=')
if not eq:
return None
ret =line[eq+1:].strip().decode()
if ret.startswith('"') and ret.endswith('"'):
ret = ret[1:-1]
return ret.strip()
by_index = { 'source': {}, 'sink': {} }
def parse_sources_sinks(whichtype):
"""Get a list of sinks or sources. whichtype should be "source" or "sink".
"""
devs = []
curdict = None
cmd = ['pacmd', f'list-{whichtype}s']
for line in subprocess.check_output(cmd).split(b'\n'):
line = line.strip()
try:
words = line.split()
except:
continue
if not words:
continue
if words[0] == b'*': # default/fallback
fallback = True
words = words[1:]
else:
fallback = False
if words[0] == b'index:': # start a new sink
if curdict:
devs.append(curdict)
curdict = { 'fallback': fallback }
curdict['index'] = words[1].decode()
by_index[whichtype][curdict['index']] = curdict
elif words[0] == b'name:':
# Take the second word and remove enclosing <>
curdict['name'] = words[1][1:-1].decode()
elif words[0] == b'muted:':
curdict['muted'] = (words[1] == b'yes')
elif words[0] == b'volume:':
curdict['volume'] = parse_volume(words)
elif words[0] == b'base' and words[1] == b'volume:':
curdict['base_volume'] = int(words[2])
elif len(words) >= 2 and words[1] == b'=' \
and words[0] in [b'alsa.long_card_name',
b'device.product.name',
b'device.description']:
name = after_equals(line)
curdict[words[0].decode()] = name
if curdict:
devs.append(curdict)
return devs
def parse_sink_inputs():
"""Parse sink inputs: running programs that are producing audio.
"""
cmd = ['pactl', 'list', 'sink-inputs']
sink_inputs = []
sink_input = None
for line in subprocess.check_output(cmd).split(b'\n'):
if line.startswith(b'Sink Input'):
if sink_input:
sink_inputs.append(sink_input)
sink_input = {}
continue
words = line.strip().split()
if not words:
continue
if words[0] == b'Sink:':
sink_input['sink'] = words[1].decode()
if words[0] == b'media.name':
sink_input['medianame'] = after_equals(line)
if words[0] == b'application.name':
sink_input['appname'] = after_equals(line)
if words[0] == b'Mute':
sink_input['mute'] = (words[1] != b'No')
if words[0] == b'Volume':
sink_input['volume'] = parse_volume(words)
if sink_input:
sink_inputs.append(sink_input)
return sink_inputs
def mute_unmute(mute, dev, devtype):
"""Mute (mute=True) or unmute (False) a source (devtype="source")
or sink ("sink") of a given name.
pactl set-source-mute $source 1
"""
print("muting" if mute else "unmuting", sub_str(dev['device.description']))
subprocess.call(["pactl", f"set-{devtype}-mute", dev['name'],
'1' if mute else '0'])
def unmute_one(pattern, devtype, mute_others=True):
"""Make one source or sink the active fallback, unmuting it and
(optionally) muting all others.
pattern is a string (not regexp) to search for in the device description,
e.g. "USB" or "HDMI1", or an integer or a string representing an int.
devtype is "source" or "sink".
If pattern is None or none, mute everything of that type.
"""
devs = parse_sources_sinks(devtype)
muteall = (pattern.lower() == "none")
if type(pattern) is int:
devindex = pattern
elif not muteall:
try:
devindex = int(pattern)
except ValueError:
# Make sure there's a match before muting anything
devindex = -1
for i, dev in enumerate(devs):
if pattern in sub_str(dev['device.description']):
devindex = i
break
if pattern in dev['device.description']:
devindex = i
break
if devindex < 0:
print(f"Didn't find a {devtype} matching", pattern)
return
# Now either muteall or devindex should be set.
# Set the given device as the fallback
if not muteall:
print("Setting", sub_str(devs[devindex]['device.description']),
"as fallback")
print("Calling", ["pactl", f"set-default-{devtype}",
devs[devindex]['index']])
subprocess.call(["pactl", f"set-default-{devtype}",
devs[devindex]['index']])
for i, dev in enumerate(devs):
if not muteall and i == devindex:
mute_unmute(False, dev, devtype)
elif mute_others:
mute_unmute(True, dev, devtype)
print()
def sub_str(s):
"""Substitute any matches found in config['subs'].
"""
if 'subs' not in config:
return s
for pair in config['subs']:
if pair[0] in s:
s = s.replace(pair[0], pair[1])
return s
def sink_or_source_str(devdict):
"""Pretty output for a sink or source.
"""
out = f"{devdict['index']}: {sub_str(devdict['device.description'])}"
if devdict['fallback']:
out += ' (--FALLBACK--)'
if 'volume' in devdict:
try:
multiplier = float(devdict['base_volume']) / 65536.
except:
multiplier = 1.
out += ' (' + ', '.join([ str(int(v / 655.36 * multiplier))
for v in devdict['volume']]) + ')'
else:
out += ' (volume unknown)'
if devdict['muted']:
out += ' (MUTED)'
out = mutedstring(out)
if devdict['fallback']:
out = fallbackstring(out)
return out
def sink_input_str(sidict):
"""Pretty output for a sink input.
"""
# return str(sidict)
out = f"{sidict['appname']} {sidict['medianame']} --> "
sink = by_index['sink'][sidict['sink']]
out += f"{sub_str(sink['device.description'])}"
if sink['muted']:
out = mutedstring(out)
return out
def read_config_file():
"""Read the config file.
Currently, the only configuration is a list of substitutions
to make the output shorter and more readable.
"""
global config
try:
with open(os.path.expanduser("~/.config/pulsehelper/config")) as fp:
for line in fp:
parts = [ p.strip() for p in line.split('=') ]
if len(parts) != 2:
print("Config file parse error, line:", line)
continue
if 'subs' not in config:
config['subs'] = []
config['subs'].append(parts)
except:
pass
return config
def print_status():
cards = parse_cards()
print("Cards:")
for card in cards:
print(card)
print()
sinks = parse_sources_sinks('sink')
print('Sinks:')
for sink in sinks:
print(sink_or_source_str(sink))
print()
sources = parse_sources_sinks('source')
print('Sources:')
for source in sources:
print(sink_or_source_str(source))
print()
sink_inputs = parse_sink_inputs()
print('Currently running (sink inputs):')
for si in sink_inputs:
print(sink_input_str(si))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description="""Control PulseAudio devices.
Provide patterns matching source or sink arguments, e.g.
--sink USB will unmute any sink that has "USB" in its description.
Or specify the number of the source or sink.
Use none to mute every source or every sink.
With no arguments, prints all cards, sources and sinks.
You can create a ~/.config/pulsehelper/config file to provide shorter names.
Lines in that file should look like:
Super Long Hard To Read PulseAudio Name = Nice Short Name
""",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--source', action="store", dest="source",
help='Set current source (microphone)')
parser.add_argument('--sink', action="store", dest="sink",
help='Set current sink (speaker)')
args = parser.parse_args(sys.argv[1:])
config = read_config_file()
if args.source:
unmute_one(args.source, 'source')
if args.sink:
unmute_one(args.sink, 'sink')
print_status()