-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_alsa_config.py
More file actions
executable file
·553 lines (465 loc) · 17.1 KB
/
generate_alsa_config.py
File metadata and controls
executable file
·553 lines (465 loc) · 17.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
#!/usr/bin/env python3
"""
ALSA Configuration Generator for Wondom Speaker Setup
Reads ../speaker_config.json (v2.0 format) and generates ALSA configuration with:
- Base amplifier PCM definitions (amp1, amp2, etc.)
- Stereo PCM devices for each room (room_XXX)
- Combined all_rooms output for testing
- Support for cross-device stereo pairs using ALSA multi plugin
Note: Zones are handled by Snapcast, not ALSA.
"""
import json
import sys
from pathlib import Path
from collections import defaultdict
# ALSA card name suffix pattern: GAB8, GAB8_1, GAB8_2, etc.
def get_alsa_card_name(base_card: str, index: int) -> str:
"""Get ALSA card name for nth device of same type."""
if index == 0:
return base_card
return f"{base_card}_{index}"
CONFIG_FILE = Path(__file__).parent / "speaker_config.json"
# Default max volume coefficient (0.0-1.0)
DEFAULT_MAX_VOLUME = 0.5
def load_config() -> dict:
"""Load speaker configuration from JSON."""
if not CONFIG_FILE.exists():
print(f"Error: {CONFIG_FILE} not found.", file=sys.stderr)
print("Run speaker_identify.py first to create the configuration.", file=sys.stderr)
sys.exit(1)
with open(CONFIG_FILE) as f:
config = json.load(f)
if config.get("version") != "2.0":
print("Error: Config file is not v2.0 format.", file=sys.stderr)
print("Run speaker_identify.py to upgrade the configuration.", file=sys.stderr)
sys.exit(1)
return config
def get_max_volume(config: dict) -> float:
"""Get max volume coefficient from global config."""
return config.get("global", {}).get("max_volume", DEFAULT_MAX_VOLUME)
def generate_amplifier_config(config: dict) -> str:
"""Generate base PCM definitions for all amplifiers."""
amplifiers = config.get("amplifiers", {})
max_vol = get_max_volume(config)
if not amplifiers:
return ""
# Group amps by card type to handle multiple devices of same type
card_counts = defaultdict(int)
amp_cards = {}
for amp_name in sorted(amplifiers.keys()):
amp = amplifiers[amp_name]
base_card = amp.get("card", "GAB8")
alsa_card = get_alsa_card_name(base_card, card_counts[base_card])
card_counts[base_card] += 1
amp_cards[amp_name] = alsa_card
output = """
#########################################
# AMPLIFIER DEFINITIONS
#########################################
"""
for amp_name in sorted(amplifiers.keys()):
amp = amplifiers[amp_name]
alsa_card = amp_cards[amp_name]
channels = amp.get("channels", 8)
output += f"""
# {amp_name} - {alsa_card} ({channels} channels)
pcm.{amp_name} {{
type hw
card {alsa_card}
device 0
}}
pcm.{amp_name}_dmix {{
type dmix
ipc_key 10{amp_name[-1] if amp_name[-1].isdigit() else '0'}
ipc_perm 0666
slave {{
pcm "{amp_name}"
channels {channels}
rate 48000
period_size 2048
buffer_size 16384
}}
}}
"""
# Generate per-channel devices for speaker identification (uses dmix for concurrent access)
for ch in range(1, channels + 1):
ch_idx = ch - 1 # 0-based for ALSA ttable
output += f"""
pcm.{amp_name}_ch{ch}_raw {{
type route
slave.pcm "{amp_name}_dmix"
slave.channels {channels}
ttable.0.{ch_idx} {max_vol}
ttable.1.{ch_idx} {max_vol}
}}
pcm.{amp_name}_ch{ch} {{
type plug
slave.pcm "{amp_name}_ch{ch}_raw"
}}
"""
return output, amp_cards
def get_speaker_info(config: dict, speaker_name: str, max_vol: float) -> dict:
"""Get full speaker info including amplifier details."""
if not speaker_name or speaker_name not in config["speakers"]:
return None
speaker = config["speakers"][speaker_name]
amp_name = speaker["amplifier"]
amp = config["amplifiers"].get(amp_name, {})
# Calculate effective volume: speaker volume (0-100) * global max_volume
speaker_vol = speaker.get("volume", 100) / 100.0
effective_vol = speaker_vol * max_vol
return {
"amplifier": amp_name,
"card": amp.get("card", ""),
"channel": speaker["channel"],
"volume": effective_vol
}
def get_room_speakers(config: dict, max_vol: float) -> dict:
"""Get speaker pairs for each room.
A room is either stereo (left/right speakers, sub optional) OR mono
(single `mono` speaker that receives L+R downmixed). If `mono` is set
it takes precedence and left/right are ignored.
"""
rooms = {}
for room_id, room_info in config["rooms"].items():
mono_info = get_speaker_info(config, room_info.get("mono"), max_vol)
if mono_info:
rooms[room_id] = {
"name": room_info.get("name", room_id),
"mono": mono_info,
"left": None,
"right": None,
"zones": room_info.get("zones", []),
}
continue
left_info = get_speaker_info(config, room_info.get("left"), max_vol)
right_info = get_speaker_info(config, room_info.get("right"), max_vol)
if left_info or right_info:
rooms[room_id] = {
"name": room_info.get("name", room_id),
"left": left_info,
"right": right_info,
"mono": None,
"zones": room_info.get("zones", []),
}
return rooms
def _softvol_path(name: str, route_name: str, card: str) -> str:
"""Render a softvol PCM that wraps a 1.0-coefficient route. Volume is set
at runtime via amixer; this provides live per-speaker gain."""
return f"""
pcm.{name} {{
type softvol
slave.pcm "{route_name}"
control {{
name "{name}"
card {card}
}}
min_dB -60.0
max_dB 0.0
resolution 256
}}
"""
def generate_same_device_config(room_id: str, left: dict, right: dict) -> str:
"""Generate ALSA config for stereo pair on same device — softvol per side."""
device = left["amplifier"]
left_ch = left["channel"] - 1
right_ch = right["channel"] - 1
left_ctrl = f"vol_{room_id}_left"
right_ctrl = f"vol_{room_id}_right"
return f"""
#########
# room_{room_id} - Stereo (same device: {device})
#########
pcm._internal_{room_id}_left_route {{
type route
slave.pcm "{device}_dmix"
slave.channels 8
ttable.0.{left_ch} 1.0
}}
{_softvol_path(left_ctrl, f"_internal_{room_id}_left_route", device)}
pcm._internal_{room_id}_right_route {{
type route
slave.pcm "{device}_dmix"
slave.channels 8
ttable.0.{right_ch} 1.0
}}
{_softvol_path(right_ctrl, f"_internal_{room_id}_right_route", device)}
pcm._internal_{room_id} {{
type multi
slaves.l.pcm "{left_ctrl}"
slaves.l.channels 1
slaves.r.pcm "{right_ctrl}"
slaves.r.channels 1
bindings.0.slave l
bindings.0.channel 0
bindings.1.slave r
bindings.1.channel 0
}}
pcm.room_{room_id} {{
type plug
slave.pcm "_internal_{room_id}"
}}
"""
def generate_cross_device_config(room_id: str, left: dict, right: dict) -> str:
"""Cross-device stereo with per-side softvol on the respective amp's card."""
left_device = left["amplifier"]
right_device = right["amplifier"]
left_ch = left["channel"] - 1
right_ch = right["channel"] - 1
left_ctrl = f"vol_{room_id}_left"
right_ctrl = f"vol_{room_id}_right"
return f"""
#########
# room_{room_id} - Cross-device stereo: {left_device} ch{left_ch+1} + {right_device} ch{right_ch+1}
#########
pcm._internal_{room_id}_left_route {{
type route
slave.pcm "{left_device}_dmix"
slave.channels 8
ttable.0.{left_ch} 1.0
}}
{_softvol_path(left_ctrl, f"_internal_{room_id}_left_route", left_device)}
pcm._internal_{room_id}_right_route {{
type route
slave.pcm "{right_device}_dmix"
slave.channels 8
ttable.0.{right_ch} 1.0
}}
{_softvol_path(right_ctrl, f"_internal_{room_id}_right_route", right_device)}
# Per-speaker stereo aliases (used by speaker test if needed)
pcm.speaker_{room_id}_left {{ type plug; slave.pcm "{left_ctrl}" }}
pcm.speaker_{room_id}_right {{ type plug; slave.pcm "{right_ctrl}" }}
pcm._internal_{room_id} {{
type multi
slaves.l.pcm "{left_ctrl}"
slaves.l.channels 1
slaves.r.pcm "{right_ctrl}"
slaves.r.channels 1
bindings.0.slave l
bindings.0.channel 0
bindings.1.slave r
bindings.1.channel 0
}}
pcm.room_{room_id} {{
type plug
slave.pcm "_internal_{room_id}"
}}
"""
def generate_mono_config(room_id: str, speaker: dict, position: str) -> str:
"""Mono room — single softvol path that sums L+R into one output channel.
ttable coef 0.5 on each source channel keeps the sum at unity (no clipping
when both inputs are at full scale); the per-room softvol still gives live
volume control above that.
"""
device = speaker["amplifier"]
channel = speaker["channel"] - 1
ctrl = f"vol_{room_id}_{position}"
return f"""
#########
# room_{room_id} - Mono ({position} on {device})
#########
pcm._internal_{room_id}_{position}_route {{
type route
slave.pcm "{device}_dmix"
slave.channels 8
ttable.0.{channel} 0.5
ttable.1.{channel} 0.5
}}
{_softvol_path(ctrl, f"_internal_{room_id}_{position}_route", device)}
pcm.room_{room_id} {{
type plug
slave.pcm "{ctrl}"
}}
"""
def generate_inputs_config(config: dict) -> str:
"""Generate capture PCMs for configured audio inputs (USB line-in → lox).
Each input maps a capture card to an `input_<id>` PCM. It's a `type plug`
so the lineinpipe bridge can request lox's canonical 44.1 kHz / stereo
regardless of the card's native rate or channel count — plug resamples and
up/down-mixes as needed, so no lox-side sample-rate config is required.
No softvol here: input gain is regulated by lox per zone.
"""
inputs = config.get("inputs", {})
if not inputs:
return ""
output = """
#########################################
# INPUT DEFINITIONS (USB capture → lox lineIn)
#########################################
"""
for input_id in sorted(inputs.keys()):
inp = inputs[input_id]
card = inp.get("card", input_id)
channels = inp.get("channels", 2)
rate = inp.get("sample_rate", 48000)
output += f"""
# input_{input_id} - capture from {card} ({channels}ch @ {rate}Hz native)
pcm.input_{input_id} {{
type plug
slave.pcm "hw:{card},0"
slave.channels {channels}
slave.rate {rate}
}}
"""
return output
def generate_all_rooms_config(rooms: dict) -> str:
"""Generate a combined stereo device that plays to all rooms."""
if not rooms:
return ""
# Collect all unique devices and their channel mappings
device_channels = defaultdict(list)
for room_id, room in rooms.items():
if room.get("mono"):
# Mono rooms get both source channels into the single output.
device_channels[room["mono"]["amplifier"]].append({
"channel": room["mono"]["channel"] - 1,
"stereo_pos": 0,
})
device_channels[room["mono"]["amplifier"]].append({
"channel": room["mono"]["channel"] - 1,
"stereo_pos": 1,
})
continue
if room.get("left"):
device_channels[room["left"]["amplifier"]].append({
"channel": room["left"]["channel"] - 1,
"stereo_pos": 0
})
if room.get("right"):
device_channels[room["right"]["amplifier"]].append({
"channel": room["right"]["channel"] - 1,
"stereo_pos": 1
})
if len(device_channels) == 1:
# All on one device - use route with dmix
device = list(device_channels.keys())[0]
channels = device_channels[device]
ttable_lines = []
for ch_info in channels:
ttable_lines.append(f" ttable.{ch_info['stereo_pos']}.{ch_info['channel']} 1")
ttable = "\n".join(sorted(set(ttable_lines)))
return f"""
#########
# all_rooms - Play stereo to all configured speakers
#########
pcm.all_rooms_raw {{
type route
slave.pcm "{device}_dmix"
slave.channels 8
{ttable}
}}
pcm.all_rooms {{
type plug
slave.pcm "all_rooms_raw"
}}
"""
else:
# Multi-device setup with dmix for concurrent access
slaves = []
bindings = []
binding_idx = 0
for i, (device, channels) in enumerate(sorted(device_channels.items())):
slave_letter = chr(ord('a') + i)
slaves.append(f' slaves.{slave_letter}.pcm "{device}_dmix"')
slaves.append(f' slaves.{slave_letter}.channels 8')
for ch_info in channels:
bindings.append(f' bindings.{binding_idx}.slave {slave_letter}')
bindings.append(f' bindings.{binding_idx}.channel {ch_info["channel"]}')
binding_idx += 1
slaves_str = "\n".join(slaves)
bindings_str = "\n".join(bindings)
return f"""
#########
# all_rooms - Play stereo to all configured speakers (multi-device)
#########
pcm.all_rooms_multi {{
type multi
{slaves_str}
{bindings_str}
}}
pcm.all_rooms {{
type plug
slave.pcm "all_rooms_multi"
}}
"""
def main():
print("=" * 50, file=sys.stderr)
print("ALSA CONFIGURATION GENERATOR", file=sys.stderr)
print("=" * 50, file=sys.stderr)
config = load_config()
max_vol = get_max_volume(config)
rooms = get_room_speakers(config, max_vol)
if not rooms:
print("No rooms configured!", file=sys.stderr)
sys.exit(1)
amplifiers = config.get("amplifiers", {})
print(f"\nGenerating config for {len(amplifiers)} amplifier(s) and {len(rooms)} room(s)...", file=sys.stderr)
print(f"Global max volume: {max_vol} ({max_vol*100:.0f}%)\n", file=sys.stderr)
# Generate header
output = """
#########################################
# AUTO-GENERATED WONDOM SPEAKER CONFIG
# Generated by generate_alsa_config.py
#########################################
"""
# Generate amplifier definitions
amp_config, amp_cards = generate_amplifier_config(config)
output += amp_config
for amp_name, alsa_card in amp_cards.items():
print(f" {amp_name}: hw:{alsa_card}", file=sys.stderr)
output += """
#########################################
# ROOM DEFINITIONS
#########################################
"""
# Generate config for each room
for room_id in sorted(rooms.keys()):
room = rooms[room_id]
mono = room.get("mono")
left = room.get("left")
right = room.get("right")
if mono:
output += generate_mono_config(room_id, mono, "mono")
print(f" room_{room_id}: mono on {mono['amplifier']}_ch{mono['channel']} vol={mono['volume']:.0%}", file=sys.stderr)
elif left and right:
if left["amplifier"] == right["amplifier"]:
# Same device - use route plugin
output += generate_same_device_config(room_id, left, right)
print(f" room_{room_id}: stereo on {left['amplifier']} (ch{left['channel']}, ch{right['channel']}) vol={left['volume']:.0%}/{right['volume']:.0%}", file=sys.stderr)
else:
# Different devices - use multi plugin
output += generate_cross_device_config(room_id, left, right)
print(f" room_{room_id}: cross-device ({left['amplifier']}_ch{left['channel']} + {right['amplifier']}_ch{right['channel']}) vol={left['volume']:.0%}/{right['volume']:.0%}", file=sys.stderr)
elif left:
output += generate_mono_config(room_id, left, "left")
print(f" room_{room_id}: mono (left only on {left['amplifier']}_ch{left['channel']}) vol={left['volume']:.0%}", file=sys.stderr)
elif right:
output += generate_mono_config(room_id, right, "right")
print(f" room_{room_id}: mono (right only on {right['amplifier']}_ch{right['channel']}) vol={right['volume']:.0%}", file=sys.stderr)
# Generate all_rooms combined output
output += generate_all_rooms_config(rooms)
print(f" all_rooms: combined output to all speakers", file=sys.stderr)
# Generate input (capture) definitions
inputs = config.get("inputs", {})
if inputs:
output += generate_inputs_config(config)
for input_id in sorted(inputs.keys()):
inp = inputs[input_id]
print(f" input_{input_id}: capture from {inp.get('card', input_id)} "
f"→ lox '{inp.get('lox_input_id', input_id)}'", file=sys.stderr)
# Print to stdout
print(output)
print("\n" + "=" * 50, file=sys.stderr)
print("USAGE:", file=sys.stderr)
print(" Save to /etc/asound.conf:", file=sys.stderr)
print(" sudo python3 generate_alsa_config.py > /etc/asound.conf", file=sys.stderr)
print("\n Or save to file:", file=sys.stderr)
print(" python3 generate_alsa_config.py > wondom_rooms.conf", file=sys.stderr)
print("\n Test with:", file=sys.stderr)
for room_id in sorted(rooms.keys()):
print(f" aplay -D room_{room_id} test.wav", file=sys.stderr)
print(f" aplay -D all_rooms test.wav", file=sys.stderr)
print("\n Note: Zones are managed by Snapcast, not ALSA.", file=sys.stderr)
print("=" * 50, file=sys.stderr)
if __name__ == "__main__":
main()