-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamplerate.py
More file actions
1505 lines (1305 loc) · 60.1 KB
/
samplerate.py
File metadata and controls
1505 lines (1305 loc) · 60.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Helpers for PipeWire samplerate status and conservative settings inventory."""
from __future__ import annotations
import json
import os
import re
import subprocess
from pathlib import Path
from typing import Any
NON_SELECTABLE_OUTPUT_KEYS = {"easyeffects_sink"}
NON_SELECTABLE_INPUT_KEYS = {"easyeffects_source"}
SOURCE_MODE_APP_PLAYBACK = "app-playback"
SOURCE_MODE_EXTERNAL_INPUT = "external-input"
SOURCE_MODE_BLUETOOTH_INPUT = "bluetooth-input"
def _run_command(args: list[str]) -> str:
result = subprocess.run(args, capture_output=True, text=True, check=False)
if result.returncode != 0:
stderr = (result.stderr or "").strip()
raise RuntimeError(stderr or f"Command failed: {' '.join(args)}")
return result.stdout
def _command_available(command: str) -> bool:
return any(
Path(path, command).exists() and os.access(Path(path, command), os.X_OK)
for path in os.environ.get("PATH", "").split(os.pathsep)
if path
)
def _pipewire_bluez_plugin_available() -> bool:
candidates = [
"/usr/lib64/spa-0.2/bluez5/libspa-bluez5.so",
"/usr/lib/spa-0.2/bluez5/libspa-bluez5.so",
"/usr/lib/*/spa-0.2/bluez5/libspa-bluez5.so",
]
for candidate in candidates:
if any(Path("/").glob(candidate.lstrip("/"))):
return True
return False
def _is_bluetooth_sink_name(name: str | None) -> bool:
normalized = (name or "").strip()
return normalized.startswith("bluez_output.")
def _is_bluetooth_source_name(name: str | None) -> bool:
normalized = (name or "").strip()
return normalized.startswith("bluez_input.") or normalized.startswith("bluez_source.")
def _extract_bluetooth_address(value: str | None) -> str | None:
normalized = (value or "").strip()
match = re.search(r"([0-9A-F]{2}(?:[:_][0-9A-F]{2}){5})", normalized, re.IGNORECASE)
if not match:
return None
return match.group(1).replace("_", ":").upper()
def _bluetooth_device_id(address: str | None) -> str | None:
normalized = _extract_bluetooth_address(address)
if not normalized:
return None
return f"bluez-dev-{normalized.replace(':', '_')}"
def _parse_bluetoothctl_show(output: str) -> dict[str, Any]:
result: dict[str, Any] = {
"address": None,
"name": None,
"alias": None,
"powered": None,
"discoverable": None,
"pairable": None,
"discovering": None,
"roles": [],
"uuids": [],
}
for index, raw_line in enumerate(output.splitlines()):
line = raw_line.strip()
if index == 0:
match = re.match(r"Controller\s+([0-9A-F:]{17})", line, re.IGNORECASE)
if match:
result["address"] = match.group(1).upper()
elif line.startswith("Name:"):
result["name"] = line.split(":", 1)[1].strip() or None
elif line.startswith("Alias:"):
result["alias"] = line.split(":", 1)[1].strip() or None
elif line.startswith("Powered:"):
result["powered"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Discoverable:"):
result["discoverable"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Pairable:"):
result["pairable"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Discovering:"):
result["discovering"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("UUID:"):
uuid_label = line.split(":", 1)[1].strip()
if uuid_label:
result.setdefault("uuids", []).append(uuid_label)
elif line.startswith("Roles:"):
role = line.split(":", 1)[1].strip()
if role:
result.setdefault("roles", []).append(role)
return result
def _parse_bluetoothctl_devices(output: str) -> list[dict[str, str]]:
devices: list[dict[str, str]] = []
for raw_line in output.splitlines():
line = raw_line.strip()
match = re.match(r"Device\s+([0-9A-F:]{17})\s+(.+)$", line, re.IGNORECASE)
if not match:
continue
address, name = match.groups()
devices.append({
"address": address.upper(),
"name": name.strip(),
})
return devices
def _parse_bluetoothctl_info(output: str) -> dict[str, Any]:
info: dict[str, Any] = {
"address": None,
"name": None,
"alias": None,
"paired": False,
"trusted": False,
"connected": False,
"blocked": False,
"rssi": None,
"battery_percent": None,
"uuids": [],
"modalias": None,
}
for index, raw_line in enumerate(output.splitlines()):
line = raw_line.strip()
if index == 0:
match = re.match(r"Device\s+([0-9A-F:]{17})\s+(.+)$", line, re.IGNORECASE)
if match:
info["address"] = match.group(1).upper()
info["name"] = match.group(2).strip() or None
continue
if line.startswith("Name:"):
info["name"] = line.split(":", 1)[1].strip() or None
elif line.startswith("Alias:"):
info["alias"] = line.split(":", 1)[1].strip() or None
elif line.startswith("Paired:"):
info["paired"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Trusted:"):
info["trusted"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Connected:"):
info["connected"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("Blocked:"):
info["blocked"] = line.split(":", 1)[1].strip().lower() == "yes"
elif line.startswith("RSSI:"):
info["rssi"] = _safe_int(line.split(":", 1)[1].strip())
elif line.startswith("Battery Percentage:"):
battery_value = line.split(":", 1)[1].strip().replace("%", "")
info["battery_percent"] = _safe_int(battery_value)
elif line.startswith("UUID:"):
uuid_label = line.split(":", 1)[1].strip()
if uuid_label:
info.setdefault("uuids", []).append(uuid_label)
elif line.startswith("Modalias:"):
info["modalias"] = line.split(":", 1)[1].strip() or None
return info
def _bluetooth_profile_from_node_name(name: str | None) -> str | None:
normalized = (name or "").strip()
if not normalized or "." not in normalized:
return None
suffix = normalized.rsplit(".", 1)[-1]
return suffix or None
def _infer_bluetooth_codec(profile: str | None) -> str | None:
normalized = (profile or "").strip().lower()
if "ldac" in normalized:
return "ldac"
if "aac" in normalized:
return "aac"
if "aptx" in normalized:
return "aptx"
if normalized.startswith("a2dp"):
return "a2dp"
return None
def _parse_wpctl_status_bluetooth_streams(output: str) -> list[dict[str, Any]]:
streams: list[dict[str, Any]] = []
in_audio_streams = False
current_stream: dict[str, Any] | None = None
for raw_line in output.splitlines():
stripped = raw_line.strip()
if stripped == "Audio":
in_audio_streams = False
current_stream = None
continue
if "Streams:" in stripped and ("└" in raw_line or "├" in raw_line or stripped == "Streams:"):
in_audio_streams = True
current_stream = None
continue
if in_audio_streams and stripped in {"Video", "Settings"}:
break
if not in_audio_streams:
continue
stream_match = re.match(r"^[\s│├└─]*(\d+)\.\s+(bluez_(?:input|source|output)\.[^\s]+)", raw_line)
if stream_match:
current_stream = {
"id": int(stream_match.group(1)),
"name": stream_match.group(2),
"active": False,
}
streams.append(current_stream)
continue
if current_stream and "[active]" in raw_line:
current_stream["active"] = True
return streams
def _parse_wpctl_inspect(output: str) -> dict[str, str]:
result: dict[str, str] = {}
for raw_line in output.splitlines():
match = re.match(r'^\s*(?:\*\s+)?([A-Za-z0-9._-]+)\s*=\s*(.+?)\s*$', raw_line)
if not match:
continue
key, value = match.groups()
cleaned = value.strip()
if cleaned.startswith('"') and cleaned.endswith('"') and len(cleaned) >= 2:
cleaned = cleaned[1:-1]
result[key] = cleaned
return result
def _parse_fraction_rate(value: str | None) -> int | None:
normalized = (value or "").strip()
if not normalized:
return None
slash_match = re.search(r"/(\d+)$", normalized)
if slash_match:
return _safe_int(slash_match.group(1))
hz_match = re.search(r"(\d+)\s*Hz$", normalized, re.IGNORECASE)
if hz_match:
return _safe_int(hz_match.group(1))
return _safe_int(normalized)
def _parse_pw_metadata_settings(output: str) -> dict[str, Any]:
settings: dict[str, Any] = {
"clock_rate": None,
"force_rate": None,
"allowed_rates": [],
}
for line in output.splitlines():
match = re.search(r"key:'([^']+)' value:'([^']*)'", line)
if not match:
continue
key, value = match.groups()
if key == "clock.rate":
settings["clock_rate"] = _safe_int(value)
elif key == "clock.force-rate":
settings["force_rate"] = _safe_int(value)
elif key == "clock.allowed-rates":
settings["allowed_rates"] = [int(item) for item in re.findall(r"\d+", value)]
return settings
def _parse_default_sink(output: str) -> dict[str, Any]:
sink: dict[str, Any] = {"id": None, "name": None, "description": None}
first_line = output.splitlines()[0] if output.splitlines() else ""
id_match = re.search(r"id\s+(\d+),", first_line)
if id_match:
sink["id"] = int(id_match.group(1))
for line in output.splitlines():
line = line.strip()
if line.startswith("* node.name = "):
sink["name"] = _strip_quoted_value(line)
elif line.startswith("* node.description = "):
sink["description"] = _strip_quoted_value(line)
return sink
def _parse_active_rate(output: str) -> int | None:
match = re.search(r"Audio:rate.*?\n\s+Int\s+(\d+)", output, re.DOTALL)
if match:
return int(match.group(1))
return None
def _parse_pactl_sinks_short(output: str) -> list[dict[str, Any]]:
sinks: list[dict[str, Any]] = []
for line in output.splitlines():
parts = line.split("\t")
if len(parts) < 5:
continue
sample_spec = parts[3].strip()
rate_match = re.search(r"(\d+)Hz", sample_spec)
sinks.append({
"id": _safe_int(parts[0].strip()),
"name": parts[1].strip(),
"driver": parts[2].strip(),
"sample_spec": sample_spec,
"active_rate": int(rate_match.group(1)) if rate_match else None,
"state": parts[4].strip().upper(),
})
return sinks
def _parse_pactl_sources_short(output: str) -> list[dict[str, Any]]:
sources: list[dict[str, Any]] = []
for line in output.splitlines():
parts = line.split("\t")
if len(parts) < 5:
continue
sample_spec = parts[3].strip()
rate_match = re.search(r"(\d+)Hz", sample_spec)
sources.append({
"id": _safe_int(parts[0].strip()),
"name": parts[1].strip(),
"driver": parts[2].strip(),
"sample_spec": sample_spec,
"active_rate": int(rate_match.group(1)) if rate_match else None,
"state": parts[4].strip().upper(),
})
return sources
def _parse_pactl_sinks_detailed(output: str) -> dict[str, dict[str, Any]]:
sinks: dict[str, dict[str, Any]] = {}
current: dict[str, Any] | None = None
in_ports = False
for raw_line in output.splitlines():
line = raw_line.rstrip()
stripped = line.strip()
if stripped.startswith('Sink #'):
if current and current.get('name'):
sinks[current['name']] = current
current = {
'description': None,
'device_description': None,
'sample_spec': None,
'state': None,
'ports': [],
'active_port': None,
}
in_ports = False
continue
if current is None:
continue
if stripped.startswith('Name:'):
current['name'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('Description:'):
current['description'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('State:'):
current['state'] = stripped.split(':', 1)[1].strip().upper()
in_ports = False
elif stripped.startswith('Sample Specification:'):
current['sample_spec'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('device.description = '):
current['device_description'] = _strip_quoted_value(stripped)
elif stripped == 'Ports:':
in_ports = True
elif stripped.startswith('Active Port:'):
current['active_port'] = stripped.split(':', 1)[1].strip() or None
in_ports = False
elif stripped == 'Formats:':
in_ports = False
elif in_ports and line.startswith('\t\t'):
port_match = re.match(r'([^:]+):\s+(.+?)\s+\((.*)\)$', stripped)
if port_match:
port_key, port_label, port_meta = port_match.groups()
unavailable = 'not available' in port_meta.lower()
current['ports'].append({
'key': port_key.strip(),
'label': port_label.strip(),
'available': not unavailable,
})
if current and current.get('name'):
sinks[current['name']] = current
return sinks
def _parse_pactl_cards_detailed(output: str) -> list[dict[str, Any]]:
cards: list[dict[str, Any]] = []
current: dict[str, Any] | None = None
current_port: dict[str, Any] | None = None
in_ports = False
for raw_line in output.splitlines():
line = raw_line.rstrip()
stripped = line.strip()
if stripped.startswith('Card #'):
if current_port and current is not None:
current.setdefault('ports', []).append(current_port)
current_port = None
if current:
cards.append(current)
current = {
'name': None,
'device_description': None,
'ports': [],
}
in_ports = False
continue
if current is None:
continue
if stripped.startswith('Name:'):
current['name'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('device.description = '):
current['device_description'] = _strip_quoted_value(stripped)
elif stripped == 'Ports:':
in_ports = True
if current_port:
current['ports'].append(current_port)
current_port = None
elif stripped.startswith('Active Profile:') or stripped == 'Profiles:' or stripped == 'Properties:' or stripped == 'Formats:':
in_ports = False
if current_port:
current['ports'].append(current_port)
current_port = None
elif in_ports and line.startswith('\t\t') and not line.startswith('\t\t\t'):
if current_port:
current['ports'].append(current_port)
port_match = re.match(r'([^:]+):\s+(.+?)\s+\((.*)\)$', stripped)
if port_match:
port_key, port_label, port_meta = port_match.groups()
meta_lower = port_meta.lower()
current_port = {
'key': port_key.strip(),
'label': port_label.strip(),
'available': 'not available' not in meta_lower,
'profiles': [],
}
else:
current_port = None
elif in_ports and current_port and line.startswith('\t\t\tPart of profile(s):'):
profiles_value = stripped.split(':', 1)[1].strip()
current_port['profiles'] = [item.strip() for item in profiles_value.split(',') if item.strip()]
if current_port and current is not None:
current.setdefault('ports', []).append(current_port)
if current:
cards.append(current)
return cards
def _parse_pactl_sources_detailed(output: str) -> dict[str, dict[str, Any]]:
sources: dict[str, dict[str, Any]] = {}
current: dict[str, Any] | None = None
in_ports = False
for raw_line in output.splitlines():
line = raw_line.rstrip()
stripped = line.strip()
if stripped.startswith('Source #'):
if current and current.get('name'):
sources[current['name']] = current
current = {
'description': None,
'device_description': None,
'sample_spec': None,
'state': None,
'ports': [],
'active_port': None,
}
in_ports = False
continue
if current is None:
continue
if stripped.startswith('Name:'):
current['name'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('Description:'):
current['description'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('State:'):
current['state'] = stripped.split(':', 1)[1].strip().upper()
in_ports = False
elif stripped.startswith('Sample Specification:'):
current['sample_spec'] = stripped.split(':', 1)[1].strip()
in_ports = False
elif stripped.startswith('device.description = '):
current['device_description'] = _strip_quoted_value(stripped)
elif stripped == 'Ports:':
in_ports = True
elif stripped.startswith('Active Port:'):
current['active_port'] = stripped.split(':', 1)[1].strip() or None
in_ports = False
elif stripped == 'Formats:':
in_ports = False
elif in_ports and line.startswith('\t\t'):
port_match = re.match(r'([^:]+):\s+(.+?)\s+\((.*)\)$', stripped)
if port_match:
port_key, port_label, port_meta = port_match.groups()
unavailable = 'not available' in port_meta.lower()
current['ports'].append({
'key': port_key.strip(),
'label': port_label.strip(),
'available': not unavailable,
})
if current and current.get('name'):
sources[current['name']] = current
return sources
def _humanize_sink_name(name: str | None) -> str:
cleaned = (name or "").strip()
if not cleaned:
return "Unknown output"
cleaned = cleaned.replace("alsa_output.", "")
cleaned = cleaned.replace("bluez_output.", "")
cleaned = cleaned.replace(".analog-stereo", "")
cleaned = cleaned.replace(".digital-stereo", "")
cleaned = cleaned.replace(".iec958-stereo", "")
cleaned = cleaned.replace(".hdmi-stereo", "")
cleaned = cleaned.replace("_", " ")
cleaned = re.sub(r"\.(pro|output|sink)$", "", cleaned)
cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
return cleaned or (name or "Unknown output")
def _normalize_output_label(label: str | None) -> str:
cleaned = (label or '').lower()
cleaned = cleaned.replace('displayport', 'display port')
cleaned = re.sub(r'\boutput\b', ' ', cleaned)
cleaned = re.sub(r'\bdevice\b', ' ', cleaned)
cleaned = re.sub(r'[^a-z0-9]+', ' ', cleaned)
return re.sub(r'\s+', ' ', cleaned).strip()
def _prefer_output_port_label(port_label: str | None, fallback_label: str | None) -> str | None:
cleaned_port = (port_label or '').strip()
if not cleaned_port:
return fallback_label
lowered = cleaned_port.lower()
if 'headphone' in lowered:
return 'Headphones'
if 'hdmi' in lowered or 'displayport' in lowered or 'display port' in lowered:
return 'HDMI'
if cleaned_port.lower() in {'analog output', 'line out', 'speaker'}:
return fallback_label or cleaned_port
return cleaned_port
def _build_sink_output_label(name: str | None, details: dict[str, Any], default_label: str | None = None) -> str:
fallback_label = (
details.get('description')
or details.get('device_description')
or default_label
or _humanize_sink_name(name)
)
active_port = details.get('active_port')
port_label = None
for port in details.get('ports') or []:
if port.get('key') == active_port:
port_label = port.get('label')
break
return _prefer_output_port_label(port_label, fallback_label) or fallback_label
def _build_card_port_output_entries(cards: list[dict[str, Any]], existing_outputs: list[dict[str, Any]]) -> list[dict[str, Any]]:
existing_labels = {
_normalize_output_label(item.get('label') or item.get('name'))
for item in existing_outputs
if item.get('label') or item.get('name')
}
inferred_outputs: list[dict[str, Any]] = []
for card in cards:
card_name = card.get('name')
card_device_label = card.get('device_description') or 'Audio device'
for port in card.get('ports') or []:
port_key = port.get('key') or ''
profiles = port.get('profiles') or []
if 'output' not in port_key and not any(profile.startswith('output:') for profile in profiles):
continue
label = _prefer_output_port_label(port.get('label'), card_device_label) or card_device_label
normalized_label = _normalize_output_label(label)
if not normalized_label or normalized_label in existing_labels:
continue
existing_labels.add(normalized_label)
inferred_outputs.append({
'id': None,
'key': f"card-port::{card_name or 'unknown'}::{port_key}",
'name': None,
'label': label,
'sample_spec': None,
'active_rate': None,
'state': 'AVAILABLE' if port.get('available', True) else 'UNAVAILABLE',
'is_default': False,
'is_current': False,
'is_selected': False,
'selectable': False,
'inventory_source': 'card-port',
})
return inferred_outputs
def _humanize_source_name(name: str | None) -> str:
cleaned = (name or "").strip()
if not cleaned:
return "Unknown input"
cleaned = cleaned.replace("alsa_input.", "")
cleaned = cleaned.replace("bluez_input.", "")
cleaned = cleaned.replace("source.", "")
cleaned = cleaned.replace(".analog-stereo", "")
cleaned = cleaned.replace(".digital-stereo", "")
cleaned = cleaned.replace(".iec958-stereo", "")
cleaned = cleaned.replace(".mono-fallback", "")
cleaned = cleaned.replace("_", " ")
cleaned = re.sub(r"\.input$", "", cleaned)
cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
return cleaned or (name or "Unknown input")
def _audio_output_selection_path() -> Path:
config_root = Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config"))
return config_root / "fxroute" / "audio-output-selection.json"
def _audio_source_selection_path() -> Path:
config_root = Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config"))
return config_root / "fxroute" / "audio-source-selection.json"
def _load_audio_output_selection() -> dict[str, Any]:
path = _audio_output_selection_path()
if not path.exists():
return {"selected_key": None}
try:
payload = json.loads(path.read_text())
except Exception:
return {"selected_key": None}
selected_key = payload.get("selected_key")
return {
"selected_key": selected_key if isinstance(selected_key, str) and selected_key else None,
}
def _load_audio_source_selection() -> dict[str, Any]:
path = _audio_source_selection_path()
if not path.exists():
return {"mode": SOURCE_MODE_APP_PLAYBACK, "selected_input_key": None}
try:
payload = json.loads(path.read_text())
except Exception:
return {"mode": SOURCE_MODE_APP_PLAYBACK, "selected_input_key": None}
mode = payload.get("mode")
selected_input_key = payload.get("selected_input_key")
return {
"mode": mode if mode in {SOURCE_MODE_APP_PLAYBACK, SOURCE_MODE_EXTERNAL_INPUT, SOURCE_MODE_BLUETOOTH_INPUT} else SOURCE_MODE_APP_PLAYBACK,
"selected_input_key": selected_input_key if isinstance(selected_input_key, str) and selected_input_key else None,
}
def _save_audio_output_selection(selected_key: str) -> None:
path = _audio_output_selection_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({
"selected_key": selected_key,
}, indent=2) + "\n")
def _save_audio_source_selection(mode: str, selected_input_key: str | None) -> None:
path = _audio_source_selection_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({
"mode": mode,
"selected_input_key": selected_input_key,
}, indent=2) + "\n")
def set_bluetooth_receiver_enabled(enabled: bool) -> dict[str, Any]:
if not _command_available("bluetoothctl"):
raise RuntimeError("bluetoothctl is not installed or not available in PATH")
commands = [["bluetoothctl", "power", "on"]] if enabled else []
commands.extend([
["bluetoothctl", "pairable", "on" if enabled else "off"],
["bluetoothctl", "discoverable", "on" if enabled else "off"],
])
failures: list[str] = []
for command in commands:
try:
_run_command(command)
except Exception as exc:
failures.append(f"{' '.join(command[1:])}: {exc}")
if failures:
raise RuntimeError("; ".join(failures))
return get_bluetooth_audio_overview()
def disconnect_connected_bluetooth_audio_sources() -> list[str]:
if not _command_available("bluetoothctl"):
raise RuntimeError("bluetoothctl is not installed or not available in PATH")
disconnected: list[str] = []
failures: list[str] = []
for item in _parse_bluetoothctl_devices(_run_command(["bluetoothctl", "devices"])):
address = item.get("address")
if not address:
continue
try:
info = _parse_bluetoothctl_info(_run_command(["bluetoothctl", "info", address]))
except Exception as exc:
failures.append(f"info {address}: {exc}")
continue
uuids = list(info.get("uuids") or [])
is_audio_source = any("Audio Source" in uuid for uuid in uuids)
if not info.get("connected") or not is_audio_source:
continue
try:
_run_command(["bluetoothctl", "disconnect", address])
disconnected.append(address)
except Exception as exc:
failures.append(f"disconnect {address}: {exc}")
if failures and not disconnected:
raise RuntimeError("; ".join(failures))
return disconnected
def _set_default_sink(name: str) -> None:
_run_command(["pactl", "set-default-sink", name])
def _parse_default_source_name(output: str) -> str | None:
for line in output.splitlines():
stripped = line.strip()
if stripped.startswith("Default Source:"):
value = stripped.split(":", 1)[1].strip()
return value or None
return None
def _build_source_selection_key(source_name: str, port_key: str | None = None) -> str:
return f"{source_name}::{port_key}" if port_key else source_name
def _split_source_selection_key(selection_key: str | None) -> tuple[str | None, str | None]:
normalized = (selection_key or '').strip()
if not normalized:
return None, None
if '::' in normalized:
source_name, port_key = normalized.split('::', 1)
return source_name or None, port_key or None
return normalized, None
def _set_source_port(source_name: str, port_key: str) -> None:
_run_command(["pactl", "set-source-port", source_name, port_key])
def _build_selected_output_payload(selected_key: str | None, current_name: str | None, explicit_outputs: list[dict[str, Any]]) -> dict[str, Any] | None:
lookup_key = selected_key or current_name
selected_output = next((item for item in explicit_outputs if item.get("key") == lookup_key), None)
if selected_output:
return {
"key": selected_output.get("key"),
"label": selected_output.get("label") or selected_output.get("name") or "Unknown output",
"target_name": selected_output.get("name"),
"target_label": selected_output.get("label") or selected_output.get("name") or "Unknown output",
"is_default": selected_output.get("is_default", False),
}
return None
def get_bluetooth_audio_overview() -> dict[str, Any]:
notes: list[str] = []
selection_state = _load_audio_source_selection()
receiver_enabled_intent = selection_state.get("mode") == SOURCE_MODE_BLUETOOTH_INPUT
bluetoothctl_available = _command_available("bluetoothctl")
pactl_available = _command_available("pactl")
pw_cli_available = _command_available("pw-cli")
wpctl_available = _command_available("wpctl")
controller: dict[str, Any] | None = None
adapter_present = False
if bluetoothctl_available:
try:
controller = _parse_bluetoothctl_show(_run_command(["bluetoothctl", "show"]))
adapter_present = bool(controller.get("address"))
except Exception as exc:
notes.append(f"Bluetooth adapter status unavailable: {exc}")
else:
notes.append("bluetoothctl is not installed or not available in PATH.")
sources: list[dict[str, Any]] = []
sinks: list[dict[str, Any]] = []
source_details: dict[str, dict[str, Any]] = {}
sink_details: dict[str, dict[str, Any]] = {}
if pactl_available:
try:
sources = _parse_pactl_sources_short(_run_command(["pactl", "list", "sources", "short"]))
except Exception as exc:
notes.append(f"Bluetooth source inventory unavailable: {exc}")
try:
sinks = _parse_pactl_sinks_short(_run_command(["pactl", "list", "sinks", "short"]))
except Exception as exc:
notes.append(f"Bluetooth sink inventory unavailable: {exc}")
try:
source_details = _parse_pactl_sources_detailed(_run_command(["pactl", "list", "sources"]))
except Exception as exc:
notes.append(f"Bluetooth source details unavailable: {exc}")
try:
sink_details = _parse_pactl_sinks_detailed(_run_command(["pactl", "list", "sinks"]))
except Exception as exc:
notes.append(f"Bluetooth sink details unavailable: {exc}")
else:
notes.append("pactl is not installed or not available in PATH.")
wpctl_bluetooth_streams: list[dict[str, Any]] = []
if wpctl_available:
try:
wpctl_bluetooth_streams = _parse_wpctl_status_bluetooth_streams(_run_command(["wpctl", "status"]))
except Exception as exc:
notes.append(f"Bluetooth PipeWire stream inventory unavailable: {exc}")
source_names = {str(source.get("name") or "") for source in sources}
sink_names = {str(sink.get("name") or "") for sink in sinks}
for stream in wpctl_bluetooth_streams:
stream_name = str(stream.get("name") or "").strip()
if not stream_name:
continue
try:
inspect = _parse_wpctl_inspect(_run_command(["wpctl", "inspect", str(stream.get("id"))]))
except Exception:
inspect = {}
detail_payload = {
"description": inspect.get("node.description") or inspect.get("media.name") or _humanize_source_name(stream_name),
"device_description": inspect.get("node.description") or inspect.get("media.name") or _humanize_source_name(stream_name),
"active_codec": inspect.get("api.bluez5.codec"),
"profile": inspect.get("api.bluez5.profile"),
"address": inspect.get("api.bluez5.address"),
"active_rate": _parse_fraction_rate(inspect.get("node.rate")) or _parse_fraction_rate(inspect.get("node.latency")),
}
if _is_bluetooth_source_name(stream_name) and stream_name not in source_names:
sources.append({
"id": stream.get("id"),
"name": stream_name,
"state": "RUNNING" if stream.get("active") else "IDLE",
})
source_details[stream_name] = detail_payload
source_names.add(stream_name)
elif _is_bluetooth_sink_name(stream_name) and stream_name not in sink_names:
sinks.append({
"id": stream.get("id"),
"name": stream_name,
"state": "RUNNING" if stream.get("active") else "IDLE",
})
sink_details[stream_name] = detail_payload
sink_names.add(stream_name)
elif _is_bluetooth_source_name(stream_name):
source_details.setdefault(stream_name, detail_payload)
elif _is_bluetooth_sink_name(stream_name):
sink_details.setdefault(stream_name, detail_payload)
bluez_device_available = False
if pw_cli_available:
try:
bluez_device_available = "api.bluez5" in _run_command(["pw-cli", "ls", "Device"])
except Exception:
bluez_device_available = False
bt_sources = [source for source in sources if _is_bluetooth_source_name(source.get("name"))]
bt_sinks = [sink for sink in sinks if _is_bluetooth_sink_name(sink.get("name"))]
controller_uuids = [str(uuid) for uuid in (controller or {}).get("uuids") or []]
can_receive_audio = any("Audio Sink" in uuid for uuid in controller_uuids)
can_send_audio = any("Audio Source" in uuid for uuid in controller_uuids)
pipewire_bluetooth_available = bool(
bluez_device_available
or bt_sources
or bt_sinks
or _pipewire_bluez_plugin_available()
)
device_seed_output = ""
if bluetoothctl_available:
try:
paired_output = _run_command(["bluetoothctl", "devices", "Paired"])
all_output = _run_command(["bluetoothctl", "devices"])
device_seed_output = "\n".join(filter(None, [paired_output, all_output]))
except Exception as exc:
notes.append(f"Bluetooth device list unavailable: {exc}")
devices_by_address: dict[str, dict[str, Any]] = {}
for item in _parse_bluetoothctl_devices(device_seed_output):
devices_by_address[item["address"]] = {
"id": _bluetooth_device_id(item.get("address")),
"address": item.get("address"),
"name": item.get("name"),
"alias": item.get("name"),
"transport": "bluetooth",
"paired": False,
"trusted": False,
"connected": False,
"connection_state": "disconnected",
"rssi": None,
"battery_percent": None,
"roles": {
"can_stream_to_fxroute": False,
"can_receive_from_fxroute": False,
"can_remote_control": False,
"metadata_capable": False,
},
"profiles": [],
"active_profile": None,
"supported_codecs": [],
"active_codec": None,
"session": None,
"output_binding": None,
"notes": [],
}
for address, device in list(devices_by_address.items()):
try:
info = _parse_bluetoothctl_info(_run_command(["bluetoothctl", "info", address]))
except Exception:
continue
device.update({
"name": info.get("name") or device.get("name"),
"alias": info.get("alias") or device.get("alias") or info.get("name") or device.get("name"),
"paired": bool(info.get("paired")),
"trusted": bool(info.get("trusted")),
"connected": bool(info.get("connected")),
"connection_state": "connected" if info.get("connected") else "disconnected",
"rssi": info.get("rssi"),
"battery_percent": info.get("battery_percent"),
"profiles": list(info.get("uuids") or []),
})
device["roles"] = {
"can_stream_to_fxroute": any("Audio Source" in uuid for uuid in device.get("profiles") or []),
"can_receive_from_fxroute": any("Audio Sink" in uuid for uuid in device.get("profiles") or []),
"can_remote_control": any("A/V Remote Control" in uuid for uuid in device.get("profiles") or []),
"metadata_capable": any("A/V Remote Control" in uuid for uuid in device.get("profiles") or []),
}
receiver_session = None
for source in bt_sources:
source_name = source.get("name")
details = source_details.get(source_name or "", {})
address = _extract_bluetooth_address(details.get("address") or source_name)
device_id = _bluetooth_device_id(address)
profile = details.get("profile") or _bluetooth_profile_from_node_name(source_name)
device = devices_by_address.get(address or "")
label = details.get("description") or details.get("device_description") or _humanize_source_name(source_name)
active_codec = details.get("active_codec") or _infer_bluetooth_codec(profile)
session_payload = {
"active": True,
"source_name": source_name,
"device_id": device_id,
"device_name": (device or {}).get("alias") or label,
"mode": SOURCE_MODE_BLUETOOTH_INPUT,
"streaming": str(source.get("state") or "").upper() == "RUNNING",