evo8-linux 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. evo8/__init__.py +3 -0
  2. evo8/about.py +131 -0
  3. evo8/alsa.py +77 -0
  4. evo8/apps.py +76 -0
  5. evo8/calibrate.py +159 -0
  6. evo8/cli.py +214 -0
  7. evo8/data/__init__.py +0 -0
  8. evo8/data/applications/evo8-mixer.desktop +8 -0
  9. evo8/data/evo8-mixer.svg +38 -0
  10. evo8/data/pipewire/pipewire-pulse.conf.d/20-bloquear-volumen-micro.conf +16 -0
  11. evo8/data/pipewire/pipewire.conf.d/20-mezcla.conf +158 -0
  12. evo8/data/systemd/evo8-restore.service +8 -0
  13. evo8/data/udev/70-audient-evo8.rules +7 -0
  14. evo8/gui/__init__.py +1 -0
  15. evo8/gui/app.py +92 -0
  16. evo8/gui/backend.py +485 -0
  17. evo8/gui/meters.py +86 -0
  18. evo8/gui/qml/AboutPage.qml +257 -0
  19. evo8/gui/qml/CardProfiles.qml +118 -0
  20. evo8/gui/qml/ConsolePage.qml +255 -0
  21. evo8/gui/qml/Divider.qml +8 -0
  22. evo8/gui/qml/GlyphButton.qml +30 -0
  23. evo8/gui/qml/HardwarePage.qml +603 -0
  24. evo8/gui/qml/HwMixStrip.qml +178 -0
  25. evo8/gui/qml/Main.qml +139 -0
  26. evo8/gui/qml/PixelSlider.qml +80 -0
  27. evo8/gui/qml/Strip.qml +396 -0
  28. evo8/gui/qml/StripGroup.qml +23 -0
  29. evo8/gui/qml/Theme.qml +22 -0
  30. evo8/gui/qml/Tip.qml +20 -0
  31. evo8/gui/qml/Toggle.qml +41 -0
  32. evo8/gui/qml/VMeter.qml +28 -0
  33. evo8/gui/qml/format.js +88 -0
  34. evo8/gui/qml/qmldir +14 -0
  35. evo8/gui/snapshot.py +98 -0
  36. evo8/hw.py +147 -0
  37. evo8/mix.py +109 -0
  38. evo8/monitor.py +229 -0
  39. evo8/profiles.py +112 -0
  40. evo8/pw.py +164 -0
  41. evo8/state.py +45 -0
  42. evo8/usb.py +122 -0
  43. evo8/user_setup.py +224 -0
  44. evo8_linux-0.1.0.dist-info/METADATA +198 -0
  45. evo8_linux-0.1.0.dist-info/RECORD +49 -0
  46. evo8_linux-0.1.0.dist-info/WHEEL +5 -0
  47. evo8_linux-0.1.0.dist-info/entry_points.txt +5 -0
  48. evo8_linux-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. evo8_linux-0.1.0.dist-info/top_level.txt +1 -0
evo8/gui/backend.py ADDED
@@ -0,0 +1,485 @@
1
+ """The object QML talks to (`mixer` in the QML context).
2
+
3
+ Everything slow (pactl, pw-cli, amixer, USB) runs on one worker thread, in
4
+ order, so the window never blocks and writes never overtake each other.
5
+
6
+ * Reads: a 1 s poll for PulseAudio state (devices, streams, volumes) and a 3 s
7
+ poll for the rest (Mezcla gains, sync delay, preamps, monitor, profiles).
8
+ * Writes: sliders change the model at once (so the control does not jump) and
9
+ queue a write; writes with the same key coalesce for 60 ms, so a drag costs a
10
+ few commands, not one per pixel. Polled values for a key are ignored for a
11
+ moment after writing it, until the system has caught up.
12
+ * Hardware (USB) settings drop the audio for a moment, so they are staged and
13
+ applied together with one button.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import queue
19
+ import threading
20
+ import time
21
+ import traceback
22
+
23
+ from PySide6.QtCore import Property, QObject, QTimer, Signal, Slot
24
+
25
+ from .. import about, alsa, calibrate, hw, mix, monitor, profiles, pw, state
26
+ from . import snapshot
27
+ from .meters import Meters
28
+
29
+ HOLD_S = 1.5
30
+ FAST_MS = 1000
31
+ SLOW_EVERY = 3
32
+ FLUSH_MS = 60
33
+ METER_MS = 50
34
+ METER_DECAY = 0.82
35
+
36
+
37
+ class Worker:
38
+ """One thread running jobs in order; results come back through `done`."""
39
+
40
+ def __init__(self, done: Signal):
41
+ self._q: queue.Queue = queue.Queue()
42
+ self._done = done
43
+ threading.Thread(target=self._run, daemon=True).start()
44
+
45
+ def submit(self, key: str, fn, *args) -> None:
46
+ self._q.put((key, fn, args))
47
+
48
+ def _run(self) -> None:
49
+ while True:
50
+ key, fn, args = self._q.get()
51
+ try:
52
+ result, error = fn(*args), None
53
+ except Exception as e: # reported to the window, never fatal
54
+ result, error = None, str(e) or e.__class__.__name__
55
+ traceback.print_exc()
56
+ self._done.emit(key, result, error)
57
+
58
+
59
+ def _safe(fn, default=None):
60
+ try:
61
+ return fn()
62
+ except Exception:
63
+ return default
64
+
65
+
66
+ def _slow_read() -> dict:
67
+ return {
68
+ "gains": _safe(mix.gains),
69
+ "delayMs": _safe(mix.delay_ms),
70
+ "preamp": _safe(alsa.preamp),
71
+ "monitor": _safe(monitor.status, "unavailable"),
72
+ "inputMonitors": _safe(monitor.inputs, []),
73
+ "cards": _safe(profiles.cards, []),
74
+ }
75
+
76
+
77
+ class Backend(QObject):
78
+ modelChanged = Signal()
79
+ metersChanged = Signal()
80
+ hwChanged = Signal()
81
+ aboutChanged = Signal()
82
+ _done = Signal(str, "QVariant", "QVariant")
83
+
84
+ def __init__(self, parent=None):
85
+ super().__init__(parent)
86
+ self._model: dict = {
87
+ "gains": None, "delayMs": None, "preamp": None, "monitor": "",
88
+ "inputMonitors": [], "cards": [], "sink": None, "mezcla": None,
89
+ "escucha": None, "streams": [], "message": "",
90
+ "calibrating": False, "notice": "",
91
+ }
92
+ saved = state.load().get("hw") or {}
93
+ self._hw: dict = {
94
+ "mix": saved.get("mix"), "loopback": saved.get("loopback"),
95
+ "readAt": saved.get("readAt"), "pending": {}, "pendingLoopback": None,
96
+ "phantom": saved.get("phantom"), "mute": saved.get("mute"),
97
+ "pendingPhantom": {}, "pendingMute": {},
98
+ "busy": False, "message": "",
99
+ }
100
+ self._meters_view: dict = {}
101
+ self._about: dict = {}
102
+ self.refreshAbout()
103
+ self._hold: dict[str, float] = {}
104
+ self._before_mute: dict[int, float] = {}
105
+ self._writes: dict[str, tuple] = {}
106
+ self._inflight: set[str] = set()
107
+ self._tick = 0
108
+
109
+ self._done.connect(self._on_done)
110
+ self._worker = Worker(self._done)
111
+
112
+ self._flush_timer = QTimer(self, singleShot=True, interval=FLUSH_MS, timeout=self._flush)
113
+ self._listen_save = QTimer(self, singleShot=True, interval=400,
114
+ timeout=lambda: self._worker.submit("listen-save", mix.save_listen_level))
115
+ self._poll_timer = QTimer(self, interval=FAST_MS, timeout=self._poll)
116
+ self._poll_timer.start()
117
+ self._poll()
118
+
119
+ self._meters = Meters([
120
+ ("suma", mix.SUM_NODE, 4, True), # FL/FR inputs 1-2, RL/RR Compartido
121
+ ("mezcla", mix.MIX_SOURCE, 1, False),
122
+ ])
123
+ self._meters.start()
124
+ self._meter_timer = QTimer(self, interval=METER_MS, timeout=self._update_meters)
125
+ self._meter_timer.start()
126
+
127
+ # ---- properties ----
128
+ def _get_model(self):
129
+ return self._model
130
+
131
+ def _get_meters(self):
132
+ return self._meters_view
133
+
134
+ def _get_hw(self):
135
+ return self._hw
136
+
137
+ model = Property("QVariant", _get_model, notify=modelChanged)
138
+ meters = Property("QVariant", _get_meters, notify=metersChanged)
139
+ hardware = Property("QVariant", _get_hw, notify=hwChanged)
140
+
141
+ def _get_about(self):
142
+ return self._about
143
+
144
+ about = Property("QVariant", _get_about, notify=aboutChanged)
145
+
146
+ # Files only (metadata, sysfs, config paths): cheap, no USB traffic.
147
+ @Slot()
148
+ def refreshAbout(self) -> None:
149
+ import PySide6
150
+ from PySide6.QtCore import qVersion
151
+ self._about = about.info({"PySide6": PySide6.__version__, "Qt": qVersion()})
152
+ self.aboutChanged.emit()
153
+
154
+ @Slot()
155
+ def copyAbout(self) -> None:
156
+ from PySide6.QtGui import QGuiApplication
157
+ QGuiApplication.clipboard().setText(about.report(self._about))
158
+
159
+ def shutdown(self) -> None:
160
+ self._meters.stop()
161
+
162
+ # ---- polling ----
163
+ def _poll(self) -> None:
164
+ if "fast" not in self._inflight:
165
+ self._inflight.add("fast")
166
+ self._worker.submit("fast", snapshot.take)
167
+ if self._tick % SLOW_EVERY == 0 and "slow" not in self._inflight:
168
+ self._inflight.add("slow")
169
+ self._worker.submit("slow", _slow_read)
170
+ self._tick += 1
171
+
172
+ def _held(self, key: str) -> bool:
173
+ return self._hold.get(key, 0) > time.monotonic()
174
+
175
+ def _hold_key(self, key: str) -> None:
176
+ self._hold[key] = time.monotonic() + HOLD_S
177
+
178
+ def _update(self, values: dict) -> None:
179
+ changed = False
180
+ for k, v in values.items():
181
+ if self._held(k):
182
+ continue
183
+ if self._model.get(k) != v:
184
+ self._model[k] = v
185
+ changed = True
186
+ if changed:
187
+ self._model = dict(self._model)
188
+ self.modelChanged.emit()
189
+
190
+ def _on_done(self, key: str, result, error) -> None:
191
+ self._inflight.discard(key)
192
+ if key == "fast" and result:
193
+ self._update(result)
194
+ elif key == "slow" and result:
195
+ self._update(result)
196
+ elif key == "calibrated":
197
+ if error:
198
+ self._model = dict(self._model, calibrating=False, notice="", message="SINC · " + error)
199
+ else:
200
+ self._hold.pop("delayMs", None)
201
+ self._model = dict(self._model, calibrating=False, delayMs=result["ms"],
202
+ notice=f"SINC · {result['summary']} · aplicado {result['ms']} ms")
203
+ self.modelChanged.emit()
204
+ elif key == "hw-read":
205
+ self._hw_done(result, error, "Leído de la EVO.")
206
+ elif key == "hw-apply":
207
+ self._hw_done(result, error, "Aplicado a la EVO.")
208
+ elif error:
209
+ self._set_message(error)
210
+
211
+ def _set_message(self, text: str) -> None:
212
+ self._model = dict(self._model, message=text)
213
+ self.modelChanged.emit()
214
+
215
+ # ---- writes ----
216
+ def _queue(self, key: str, fn, *args) -> None:
217
+ self._writes[key] = (fn, args)
218
+ self._flush_timer.start()
219
+
220
+ def _flush(self) -> None:
221
+ writes, self._writes = self._writes, {}
222
+ for key, (fn, args) in writes.items():
223
+ self._worker.submit("write:" + key, fn, *args)
224
+
225
+ def _local(self, key: str, value) -> None:
226
+ self._hold_key(key)
227
+ self._model = dict(self._model, **{key: value})
228
+ self.modelChanged.emit()
229
+
230
+ @Slot(int, float)
231
+ def setGain(self, index: int, value: float) -> None:
232
+ gains = list(self._model["gains"] or mix.DEFAULT_GAINS)
233
+ gains[index] = round(max(0.0, min(mix.MAX_GAIN, value)), 4)
234
+ self._local("gains", gains)
235
+ self._queue(f"gain{index}", mix.set_gain, index + 1, gains[index])
236
+
237
+ @Slot(int)
238
+ def toggleGainMute(self, index: int) -> None:
239
+ """Mute a Mezcla gain (0..3; 2 and 3 move together) and bring back the
240
+ level it had."""
241
+ gains = list(self._model["gains"] or mix.DEFAULT_GAINS)
242
+ indices = [2, 3] if index in (2, 3) else [index]
243
+ if gains[indices[0]] > 0:
244
+ self._before_mute[index] = gains[indices[0]]
245
+ value = 0.0
246
+ else:
247
+ value = self._before_mute.pop(index, mix.DEFAULT_GAINS[indices[0]])
248
+ if len(indices) == 2:
249
+ self.setSharedGain(value)
250
+ else:
251
+ self.setGain(index, value)
252
+
253
+ @Slot(float)
254
+ def setSharedGain(self, value: float) -> None:
255
+ """Compartido L and R together."""
256
+ gains = list(self._model["gains"] or mix.DEFAULT_GAINS)
257
+ gains[2] = gains[3] = round(max(0.0, min(mix.MAX_GAIN, value)), 4)
258
+ self._local("gains", gains)
259
+ self._queue("gain2", mix.set_gain, 3, gains[2])
260
+ self._queue("gain3", mix.set_gain, 4, gains[3])
261
+
262
+ @Slot(int, float)
263
+ def setPreamp(self, index: int, db: float) -> None:
264
+ pre = self._model["preamp"]
265
+ if not pre:
266
+ return
267
+ gains = list(pre["gains"])
268
+ gains[index] = db
269
+ self._local("preamp", dict(pre, gains=gains))
270
+ self._queue(f"preamp{index}", alsa.set_preamp, index + 1, db)
271
+
272
+ @Slot(float)
273
+ def setDelay(self, ms: float) -> None:
274
+ ms = round(max(0, min(mix.MAX_DELAY_MS, ms)))
275
+ self._local("delayMs", ms)
276
+ self._queue("delay", mix.set_delay_ms, ms)
277
+
278
+ @Slot(float)
279
+ def setListenVolume(self, value: float) -> None:
280
+ esc = self._model["escucha"]
281
+ if not esc:
282
+ return
283
+ self._local("escucha", dict(esc, volume=value))
284
+ raw = snapshot.raw(value)
285
+ self._queue("escucha", pw.run, "pactl", "set-sink-input-volume", str(esc["index"]), raw, raw)
286
+ self._listen_save.start()
287
+
288
+ @Slot(float)
289
+ def setMezclaVolume(self, value: float) -> None:
290
+ m = self._model["mezcla"]
291
+ if not m:
292
+ return
293
+ self._local("mezcla", dict(m, volume=value))
294
+ self._queue("mezcla", pw.run, "pactl", "set-source-volume", mix.MIX_SOURCE, snapshot.raw(value))
295
+
296
+ @Slot()
297
+ def toggleMezclaMute(self) -> None:
298
+ m = self._model["mezcla"]
299
+ if m:
300
+ self._local("mezcla", dict(m, mute=not m["mute"]))
301
+ self._queue("mezcla-mute", pw.run, "pactl", "set-source-mute", mix.MIX_SOURCE, "toggle")
302
+
303
+ @Slot("QVariantList", float)
304
+ def setSinkChannels(self, channels, value: float) -> None:
305
+ sink = self._model["sink"]
306
+ if not sink:
307
+ return
308
+ vols = list(sink["volumes"])
309
+ for c in channels:
310
+ if 0 <= int(c) < len(vols):
311
+ vols[int(c)] = value
312
+ self._local("sink", dict(sink, volumes=vols))
313
+ self._queue("sink", pw.run, "pactl", "set-sink-volume", sink["name"], *map(snapshot.raw, vols))
314
+
315
+ @Slot()
316
+ def toggleSinkMute(self) -> None:
317
+ sink = self._model["sink"]
318
+ if sink:
319
+ self._local("sink", dict(sink, mute=not sink["mute"]))
320
+ self._queue("sink-mute", pw.run, "pactl", "set-sink-mute", sink["name"], "toggle")
321
+
322
+ def _stream(self, index: int):
323
+ return next((s for s in self._model["streams"] if s["index"] == index), None)
324
+
325
+ def _local_stream(self, index: int, **changes) -> None:
326
+ streams = [dict(s, **changes) if s["index"] == index else s for s in self._model["streams"]]
327
+ self._local("streams", streams)
328
+
329
+ @Slot(int, float)
330
+ def setStreamVolume(self, index: int, value: float) -> None:
331
+ s = self._stream(index)
332
+ if not s:
333
+ return
334
+ self._local_stream(index, volume=value)
335
+ raw = snapshot.raw(value)
336
+ self._queue(f"stream{index}", pw.run, "pactl", "set-sink-input-volume", str(index),
337
+ *[raw] * s["channels"])
338
+
339
+ @Slot(int)
340
+ def toggleStreamMute(self, index: int) -> None:
341
+ s = self._stream(index)
342
+ if s:
343
+ self._local_stream(index, mute=not s["mute"])
344
+ self._queue(f"stream-mute{index}", pw.run, "pactl", "set-sink-input-mute", str(index), "toggle")
345
+
346
+ @Slot(int)
347
+ def toggleStreamShared(self, index: int) -> None:
348
+ from .. import apps
349
+ s = self._stream(index)
350
+ if s and s["nodeId"]:
351
+ self._local_stream(index, shared=not s["shared"])
352
+ self._queue(f"share{index}", apps.share, s["nodeId"], not s["shared"])
353
+
354
+ @Slot()
355
+ def toggleMonitor(self) -> None:
356
+ if self._model["monitor"] not in ("on", "off"):
357
+ return
358
+ on = self._model["monitor"] != "on"
359
+ self._local("monitor", "on" if on else "off")
360
+ self._queue("monitor", monitor.turn_on if on else monitor.turn_off)
361
+
362
+ @Slot(int)
363
+ def toggleInputMonitor(self, index: int) -> None:
364
+ cur = list(self._model["inputMonitors"] or [])
365
+ if index >= len(cur):
366
+ return
367
+ cur[index] = 0 if cur[index] else 1
368
+ self._local("inputMonitors", cur)
369
+ self._queue(f"input-monitor{index}", monitor.set_input, index + 1, bool(cur[index]))
370
+
371
+ @Slot(str, str)
372
+ def setCardProfile(self, card: str, profile: str) -> None:
373
+ cards = [dict(c, active=profile, warning=profiles.warning(dict(c, active=profile)))
374
+ if c["name"] == card else c for c in self._model["cards"]]
375
+ self._local("cards", cards)
376
+ self._queue(f"profile:{card}", pw.run, "pactl", "set-card-profile", card, profile)
377
+
378
+ # ---- sync calibration ----
379
+ # Runs on its own thread: it takes ~15 s of playing, and the polls and
380
+ # writes must keep going meanwhile.
381
+ @Slot()
382
+ def calibrate(self) -> None:
383
+ if self._model["calibrating"]:
384
+ return
385
+ self._model = dict(self._model, calibrating=True,
386
+ notice="SINC · toca un golpe corto y seco en cada click (los primeros 4 son de cuenta)…")
387
+ self.modelChanged.emit()
388
+
389
+ def job():
390
+ try:
391
+ r = calibrate.run(apply=True, on_progress=lambda _m: None)
392
+ self._done.emit("calibrated", {"ms": r.median_ms, "summary": r.summary}, None)
393
+ except Exception as e:
394
+ self._done.emit("calibrated", None, str(e))
395
+
396
+ threading.Thread(target=job, daemon=True).start()
397
+
398
+ # ---- hardware (USB) ----
399
+ def _hw_set(self, **changes) -> None:
400
+ self._hw = dict(self._hw, **changes)
401
+ self.hwChanged.emit()
402
+
403
+ @Slot()
404
+ def hwRead(self) -> None:
405
+ if self._hw["busy"]:
406
+ return
407
+ self._hw_set(busy=True, message="Leyendo de la EVO…")
408
+ self._worker.submit("hw-read", hw.read_all)
409
+
410
+ @Slot(int, int, float)
411
+ def hwSetCell(self, inp: int, out: int, db: float) -> None:
412
+ pending = dict(self._hw["pending"])
413
+ key = f"{inp},{out}"
414
+ current = (self._hw["mix"] or [[None] * 4] * 10)[inp][out]
415
+ if current is not None and abs(current - db) < 0.5:
416
+ pending.pop(key, None)
417
+ else:
418
+ pending[key] = round(db)
419
+ self._hw_set(pending=pending)
420
+
421
+ @Slot(str)
422
+ def hwSetLoopback(self, name: str) -> None:
423
+ self._hw_set(pendingLoopback=None if name == self._hw["loopback"] else name)
424
+
425
+ def _hw_flag(self, kind: str, inp: int, on: bool) -> None:
426
+ current = (self._hw.get(kind) or [None] * 4)[inp]
427
+ pending = dict(self._hw["pending" + kind.capitalize()])
428
+ if current is not None and bool(current) == on:
429
+ pending.pop(str(inp), None)
430
+ else:
431
+ pending[str(inp)] = on
432
+ self._hw_set(**{"pending" + kind.capitalize(): pending})
433
+
434
+ @Slot(int, bool)
435
+ def hwSetPhantom(self, inp: int, on: bool) -> None:
436
+ self._hw_flag("phantom", inp, on)
437
+
438
+ @Slot(int, bool)
439
+ def hwSetMute(self, inp: int, on: bool) -> None:
440
+ self._hw_flag("mute", inp, on)
441
+
442
+ @Slot()
443
+ def hwDiscard(self) -> None:
444
+ self._hw_set(pending={}, pendingLoopback=None, pendingPhantom={}, pendingMute={}, message="")
445
+
446
+ @Slot()
447
+ def hwApply(self) -> None:
448
+ if self._hw["busy"]:
449
+ return
450
+ changes = [(int(k.split(",")[0]), int(k.split(",")[1]), float(v)) for k, v in self._hw["pending"].items()]
451
+ loop = self._hw["pendingLoopback"]
452
+ phantom = {int(k): v for k, v in self._hw["pendingPhantom"].items()}
453
+ mute = {int(k): v for k, v in self._hw["pendingMute"].items()}
454
+ if not changes and loop is None and not phantom and not mute:
455
+ return
456
+ self._hw_set(busy=True, message="Aplicando a la EVO…")
457
+
458
+ def job():
459
+ hw.apply(changes, loop, phantom, mute)
460
+ return hw.read_all()
461
+
462
+ self._worker.submit("hw-apply", job)
463
+
464
+ def _hw_done(self, result, error, ok_text: str) -> None:
465
+ if error:
466
+ self._hw_set(busy=False, message="Error: " + error)
467
+ return
468
+ read_at = time.strftime("%H:%M:%S")
469
+ state.save("hw", {"mix": result["mix"], "loopback": result["loopback"], "readAt": read_at,
470
+ "phantom": result["phantom"], "mute": result["mute"]})
471
+ self._hw_set(busy=False, mix=result["mix"], loopback=result["loopback"], readAt=read_at,
472
+ phantom=result["phantom"], mute=result["mute"],
473
+ pending={}, pendingLoopback=None, pendingPhantom={}, pendingMute={},
474
+ message=ok_text)
475
+
476
+ # ---- meters ----
477
+ def _update_meters(self) -> None:
478
+ levels = self._meters.levels()
479
+ view = dict(self._meters_view)
480
+ for name, peaks in levels.items():
481
+ prev = view.get(name) or [0.0] * len(peaks)
482
+ view[name] = [round(max(p, q * METER_DECAY), 4) for p, q in zip(peaks, prev)]
483
+ if view != self._meters_view:
484
+ self._meters_view = view
485
+ self.metersChanged.emit()
evo8/gui/meters.py ADDED
@@ -0,0 +1,86 @@
1
+ """Peak meters: each reader is one `pw-record --raw` of float samples on stdout.
2
+
3
+ Readers run in threads and keep only the latest peak per channel; the window
4
+ polls `levels()` on a timer, so audio never waits for the UI and vice versa.
5
+ The capture streams are passive (they never keep a device awake) and carry an
6
+ `evo8.` node name so the app list hides them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import array
12
+ import subprocess
13
+ import threading
14
+
15
+ RATE = 48000
16
+ CHUNK_FRAMES = 480 # 10 ms
17
+
18
+
19
+ class Reader:
20
+ def __init__(self, name: str, target: str, channels: int, capture_sink: bool):
21
+ self.name, self.target, self.channels = name, target, channels
22
+ self.capture_sink = capture_sink
23
+ self.peaks = [0.0] * channels
24
+ self._proc: subprocess.Popen | None = None
25
+ self._stop = threading.Event()
26
+ self._thread = threading.Thread(target=self._run, daemon=True)
27
+
28
+ def start(self) -> None:
29
+ self._thread.start()
30
+
31
+ def stop(self) -> None:
32
+ self._stop.set()
33
+ if self._proc and self._proc.poll() is None:
34
+ self._proc.terminate()
35
+
36
+ def take(self) -> list[float]:
37
+ """Peaks since the last call."""
38
+ p, self.peaks = self.peaks, [0.0] * self.channels
39
+ return p
40
+
41
+ def _cmd(self) -> list[str]:
42
+ props = (f"{{ node.name = evo8.meter.{self.name} node.passive = true "
43
+ f"stream.capture.sink = {'true' if self.capture_sink else 'false'} }}")
44
+ return ["pw-record", "--raw", "--target", self.target, "--channels", str(self.channels),
45
+ "--rate", str(RATE), "--format", "f32", "--latency", "20ms", "-P", props, "-"]
46
+
47
+ def _run(self) -> None:
48
+ size = CHUNK_FRAMES * self.channels * 4
49
+ while not self._stop.is_set():
50
+ try:
51
+ self._proc = subprocess.Popen(self._cmd(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
52
+ except OSError:
53
+ return
54
+ stream = self._proc.stdout
55
+ while not self._stop.is_set():
56
+ data = stream.read(size)
57
+ if not data:
58
+ break
59
+ samples = array.array("f")
60
+ samples.frombytes(data[: len(data) - len(data) % (4 * self.channels)])
61
+ peaks = self.peaks[:]
62
+ for c in range(self.channels):
63
+ m = max((abs(x) for x in samples[c::self.channels]), default=0.0)
64
+ if m > peaks[c]:
65
+ peaks[c] = m
66
+ self.peaks = peaks
67
+ if self._proc.poll() is None:
68
+ self._proc.terminate()
69
+ # The target can vanish (PipeWire restart, card reprobe): retry.
70
+ self._stop.wait(1.0)
71
+
72
+
73
+ class Meters:
74
+ def __init__(self, specs: list[tuple[str, str, int, bool]]):
75
+ self.readers = {name: Reader(name, target, ch, cap) for name, target, ch, cap in specs}
76
+
77
+ def start(self) -> None:
78
+ for r in self.readers.values():
79
+ r.start()
80
+
81
+ def stop(self) -> None:
82
+ for r in self.readers.values():
83
+ r.stop()
84
+
85
+ def levels(self) -> dict[str, list[float]]:
86
+ return {name: r.take() for name, r in self.readers.items()}