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/snapshot.py ADDED
@@ -0,0 +1,98 @@
1
+ """One read of everything the mixer window shows that lives in PulseAudio terms.
2
+
3
+ `take()` runs three `pactl -f json` calls (sinks, sources, sink inputs) and
4
+ `build()` turns them into plain dicts the QML side can bind to. Volumes are
5
+ PulseAudio's 0..1 scale (raw / 65536), the same one pavucontrol and wpctl show.
6
+ `build()` is pure so it can be tested with recorded JSON.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+
13
+ from .. import mix, pw
14
+
15
+ NORM = 65536
16
+ # Our own plumbing and helpers never show up as "apps".
17
+ HIDDEN_PREFIXES = ("mezcla.", "evo8.", "wh01s17_speaker_tuning")
18
+
19
+
20
+ def _json(*args: str) -> list[dict]:
21
+ try:
22
+ data = json.loads(pw.run("pactl", "-f", "json", *args) or "[]")
23
+ except json.JSONDecodeError:
24
+ return []
25
+ return data if isinstance(data, list) else []
26
+
27
+
28
+ def take() -> dict:
29
+ return build(
30
+ sinks=_json("list", "sinks"),
31
+ sources=_json("list", "sources"),
32
+ inputs=_json("list", "sink-inputs"),
33
+ default_sink=pw.default_sink(),
34
+ )
35
+
36
+
37
+ def _volumes(entry: dict) -> list[float]:
38
+ vol = entry.get("volume") or {}
39
+ return [round(ch.get("value", 0) / NORM, 4) for ch in vol.values() if isinstance(ch, dict)]
40
+
41
+
42
+ def _avg(values: list[float]) -> float:
43
+ return round(sum(values) / len(values), 4) if values else 0.0
44
+
45
+
46
+ def _label(props: dict) -> str:
47
+ return str(props.get("application.name") or props.get("media.name")
48
+ or props.get("node.description") or props.get("node.name") or "App")
49
+
50
+
51
+ def build(sinks: list[dict], sources: list[dict], inputs: list[dict], default_sink: str) -> dict:
52
+ sink = next((s for s in sinks if s.get("name") == default_sink), None)
53
+ shared = next((s for s in sinks if s.get("name") == mix.SHARED_SINK), None)
54
+ mezcla = next((s for s in sources if s.get("name") == mix.MIX_SOURCE), None)
55
+
56
+ out = {
57
+ "sink": None,
58
+ "mezcla": None,
59
+ "escucha": None,
60
+ "streams": [],
61
+ }
62
+ if sink:
63
+ props = sink.get("properties") or {}
64
+ vols = _volumes(sink)
65
+ out["sink"] = {
66
+ "name": sink["name"],
67
+ "label": str(props.get("device.nick") or props.get("device.description")
68
+ or sink.get("description") or sink["name"]),
69
+ "isPro": "pro-output" in sink["name"],
70
+ "volumes": vols,
71
+ "mute": bool(sink.get("mute")),
72
+ }
73
+ if mezcla:
74
+ out["mezcla"] = {"volume": _avg(_volumes(mezcla)), "mute": bool(mezcla.get("mute"))}
75
+
76
+ for si in inputs:
77
+ props = si.get("properties") or {}
78
+ name = str(props.get("node.name") or "")
79
+ vols = _volumes(si)
80
+ if name == mix.LISTEN_NODE:
81
+ out["escucha"] = {"index": si["index"], "volume": _avg(vols), "mute": bool(si.get("mute"))}
82
+ continue
83
+ if name.startswith(HIDDEN_PREFIXES):
84
+ continue
85
+ out["streams"].append({
86
+ "index": si["index"],
87
+ "nodeId": str(props.get("object.id", "")),
88
+ "label": _label(props),
89
+ "volume": _avg(vols),
90
+ "channels": len(vols) or 2,
91
+ "mute": bool(si.get("mute")),
92
+ "shared": bool(shared) and si.get("sink") == shared.get("index"),
93
+ })
94
+ return out
95
+
96
+
97
+ def raw(volume: float) -> str:
98
+ return str(max(0, round(volume * NORM)))
evo8/hw.py ADDED
@@ -0,0 +1,147 @@
1
+ """EVO 8 hardware settings over USB (see docs/protocolo-usb.md).
2
+
3
+ Confirmed on the device:
4
+ * Routing matrix = unit 51, selector 6: one byte per capture channel (0-5)
5
+ naming its source. Sources 0-5 are the analog inputs, 6-11 the computer's
6
+ playback channels 1-6. Factory routing: inputs 1-4 on capture 1-4 and
7
+ playback 5-6 ("loop-back") on capture 5-6.
8
+ * Mixer unit 60, selector 1 (the hardware monitor mix): control number
9
+ input * 4 + output, s16 in 1/256 dB, -128 dB = off. Readable and writable.
10
+ * Input control unit 58 (4-byte values, channel = input - 1): selector 0 =
11
+ phantom 48 V (verified against the front-panel button), 1 = preamp gain in
12
+ 1/256 dB (same as ALSA), 2 = mute (as EVO Control uses it).
13
+
14
+ Only selectors EVO Control itself uses may be touched: a GET to one it does
15
+ not use (unit 59, selector 3) went unanswered and hung the firmware until the
16
+ EVO was unplugged.
17
+
18
+ Each call is one usb.session(), which drops the audio card for a moment.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from . import usb
24
+
25
+ ROUTE_UNIT = 51
26
+ ROUTE_SELECTOR = 6
27
+ LOOPBACK_CHANNELS = (4, 5) # capture channels 5-6
28
+
29
+ MIXER_UNIT = 60
30
+ MIXER_SELECTOR = 1
31
+ MIXER_INPUTS = 10 # inputs 1-4, then playback 1-6
32
+ MIXER_OUTPUTS = 4 # outputs 1-4
33
+ MIXER_OFF_DB = -128.0
34
+
35
+ # Loop-back sources by name: (left, right) routing-matrix source indices.
36
+ LOOPBACK_SOURCES = {
37
+ "loopback": (10, 11), # playback 5-6, the factory setting
38
+ "pc12": (6, 7), # whatever plays on outputs 1-2
39
+ "pc34": (8, 9),
40
+ "in12": (0, 1),
41
+ "in34": (2, 3),
42
+ }
43
+
44
+
45
+ INPUT_UNIT = 58
46
+ INPUT_PHANTOM = 0
47
+ INPUT_MUTE = 2
48
+ INPUTS = 4
49
+
50
+
51
+ class HwError(RuntimeError):
52
+ pass
53
+
54
+
55
+ def loopback_get() -> dict:
56
+ with usb.session() as s:
57
+ pair = tuple(s.get(ROUTE_UNIT, ROUTE_SELECTOR, c, 1)[0] for c in LOOPBACK_CHANNELS)
58
+ name = next((n for n, p in LOOPBACK_SOURCES.items() if p == pair), None)
59
+ return {"source": name, "raw": list(pair)}
60
+
61
+
62
+ def loopback_set(source: str) -> None:
63
+ if source not in LOOPBACK_SOURCES:
64
+ raise HwError(f"fuente desconocida: {source} (opciones: {', '.join(LOOPBACK_SOURCES)})")
65
+ apply([], source)
66
+
67
+
68
+ def _mcn(inp: int, out: int) -> int:
69
+ if not (0 <= inp < MIXER_INPUTS and 0 <= out < MIXER_OUTPUTS):
70
+ raise HwError(f"entrada 1-{MIXER_INPUTS} y salida 1-{MIXER_OUTPUTS}")
71
+ return inp * MIXER_OUTPUTS + out
72
+
73
+
74
+ def mixer_get() -> list[list[float]]:
75
+ """Gain in dB of every input (rows) into every output (columns)."""
76
+ with usb.session() as s:
77
+ return [[s.get_s16(MIXER_UNIT, MIXER_SELECTOR, _mcn(i, o)) / 256 for o in range(MIXER_OUTPUTS)]
78
+ for i in range(MIXER_INPUTS)]
79
+
80
+
81
+ def mixer_set(changes: list[tuple[int, int, float]]) -> None:
82
+ """Apply (input, output, dB) changes, 0-based, in one session."""
83
+ apply(changes, None)
84
+
85
+
86
+ def _flag(s, selector: int, inp: int) -> bool:
87
+ return int.from_bytes(s.get(INPUT_UNIT, selector, inp, 4), "little", signed=True) != 0
88
+
89
+
90
+ def _set_flag(s, selector: int, inp: int, on: bool) -> None:
91
+ s.set(INPUT_UNIT, selector, inp, (1 if on else 0).to_bytes(4, "little"))
92
+
93
+
94
+ def read_all() -> dict:
95
+ """Everything in one session: {mix, loopback, loopbackRaw, phantom, mute}."""
96
+ with usb.session() as s:
97
+ matrix = [[s.get_s16(MIXER_UNIT, MIXER_SELECTOR, _mcn(i, o)) / 256 for o in range(MIXER_OUTPUTS)]
98
+ for i in range(MIXER_INPUTS)]
99
+ pair = tuple(s.get(ROUTE_UNIT, ROUTE_SELECTOR, c, 1)[0] for c in LOOPBACK_CHANNELS)
100
+ phantom = [_flag(s, INPUT_PHANTOM, i) for i in range(INPUTS)]
101
+ mute = [_flag(s, INPUT_MUTE, i) for i in range(INPUTS)]
102
+ name = next((n for n, p in LOOPBACK_SOURCES.items() if p == pair), None)
103
+ return {"mix": matrix, "loopback": name, "loopbackRaw": list(pair), "phantom": phantom, "mute": mute}
104
+
105
+
106
+ def inputs_get() -> dict:
107
+ with usb.session() as s:
108
+ return {"phantom": [_flag(s, INPUT_PHANTOM, i) for i in range(INPUTS)],
109
+ "mute": [_flag(s, INPUT_MUTE, i) for i in range(INPUTS)]}
110
+
111
+
112
+ def apply(changes: list[tuple[int, int, float]], loopback: str | None,
113
+ phantom: dict[int, bool] | None = None, mute: dict[int, bool] | None = None) -> None:
114
+ """Mixer changes (input, output, dB; 0-based), an optional loop-back
115
+ source and per-input phantom/mute flags (0-based input -> on), all in one
116
+ session so the audio drops only once."""
117
+ if loopback is not None and loopback not in LOOPBACK_SOURCES:
118
+ raise HwError(f"fuente desconocida: {loopback}")
119
+ for flags in (phantom or {}, mute or {}):
120
+ if any(not 0 <= i < INPUTS for i in flags):
121
+ raise HwError(f"entrada 1-{INPUTS}")
122
+ with usb.session() as s:
123
+ for inp, on in (phantom or {}).items():
124
+ _set_flag(s, INPUT_PHANTOM, inp, on)
125
+ for inp, on in (mute or {}).items():
126
+ _set_flag(s, INPUT_MUTE, inp, on)
127
+ for inp, out, db in changes:
128
+ db = max(MIXER_OFF_DB, min(0.0, db))
129
+ s.set_s16(MIXER_UNIT, MIXER_SELECTOR, _mcn(inp, out), round(db * 256))
130
+ if loopback is not None:
131
+ for ch, src in zip(LOOPBACK_CHANNELS, LOOPBACK_SOURCES[loopback]):
132
+ s.set(ROUTE_UNIT, ROUTE_SELECTOR, ch, bytes([src]))
133
+
134
+
135
+ def restore(saved: dict) -> bool:
136
+ """Put back a saved {mix, loopback} (from state.json "hw") in one session.
137
+ Phantom power is never restored: sending 48 V to whatever is plugged in
138
+ now is not safe to assume. Returns whether anything was sent."""
139
+ matrix = saved.get("mix")
140
+ changes = []
141
+ if isinstance(matrix, list) and len(matrix) == MIXER_INPUTS:
142
+ changes = [(i, o, float(matrix[i][o])) for i in range(MIXER_INPUTS) for o in range(MIXER_OUTPUTS)]
143
+ loopback = saved.get("loopback") if saved.get("loopback") in LOOPBACK_SOURCES else None
144
+ if not changes and loopback is None:
145
+ return False
146
+ apply(changes, loopback)
147
+ return True
evo8/mix.py ADDED
@@ -0,0 +1,109 @@
1
+ """The Mezcla virtual microphone (evo8/data/pipewire/pipewire.conf.d/20-mezcla.conf).
2
+
3
+ mezcla.suma is a filter-chain summing four channels into Mezcla:
4
+ mix:Gain 1 = interface input 1, mix:Gain 2 = input 2,
5
+ mix:Gain 3/4 = Compartido L/R, after compL/compR, which delay Compartido so
6
+ it lines up with an instrument played along to it.
7
+ These are live Props params, but PipeWire resets them to the config's values
8
+ whenever it restarts, so every change is also saved and `apply` puts the saved
9
+ values back. The Compartido listening level (mezcla.compartido.escucha) is
10
+ saved too: that stream opts out of WirePlumber's own restore so a mute the
11
+ monitor left behind never comes back.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from . import pw, state
17
+
18
+ SUM_NODE = "mezcla.suma"
19
+ LISTEN_NODE = "mezcla.compartido.escucha"
20
+ SHARED_SINK = "Compartido"
21
+ MIX_SOURCE = "Mezcla"
22
+ DEFAULT_GAINS = [1.0, 1.0, 0.5, 0.5]
23
+ MAX_GAIN = 4.0
24
+ MAX_DELAY_MS = 500
25
+
26
+
27
+ class MixError(RuntimeError):
28
+ pass
29
+
30
+
31
+ def _sum_id() -> int:
32
+ nid = pw.node_id(SUM_NODE)
33
+ if nid is None:
34
+ raise MixError(f"node {SUM_NODE} not found")
35
+ return nid
36
+
37
+
38
+ def _graph_params(nid: int) -> dict[str, float]:
39
+ """The filter-graph's own Props entry (the one carrying "mix:Gain 1")."""
40
+ for entry in pw.props_params(nid):
41
+ params = entry.get("params")
42
+ if isinstance(params, list) and "mix:Gain 1" in params:
43
+ return {params[i]: params[i + 1] for i in range(0, len(params) - 1, 2)}
44
+ return {}
45
+
46
+
47
+ def gains() -> list[float]:
48
+ p = _graph_params(_sum_id())
49
+ return [float(p.get(f"mix:Gain {n}", DEFAULT_GAINS[n - 1])) for n in range(1, 5)]
50
+
51
+
52
+ def set_gain(n: int, gain: float) -> None:
53
+ if n not in (1, 2, 3, 4):
54
+ raise MixError("gain number must be 1-4")
55
+ if not 0 <= gain <= MAX_GAIN:
56
+ raise MixError(f"gain must be between 0 and {MAX_GAIN:g}")
57
+ pw.set_graph_param(_sum_id(), f"mix:Gain {n}", gain)
58
+ state.save(str(n), gain)
59
+
60
+
61
+ def delay_ms() -> int:
62
+ p = _graph_params(_sum_id())
63
+ if "compL:Delay (s)" not in p:
64
+ raise MixError(f"no sync delay in {SUM_NODE} (20-mezcla.conf without compL/compR?)")
65
+ return round(float(p["compL:Delay (s)"]) * 1000)
66
+
67
+
68
+ def _set_delay_live(nid: int, ms: float) -> None:
69
+ s = ms / 1000
70
+ pw.set_graph_param(nid, "compL:Delay (s)", s)
71
+ pw.set_graph_param(nid, "compR:Delay (s)", s)
72
+
73
+
74
+ def set_delay_ms(ms: float) -> None:
75
+ if not 0 <= ms <= MAX_DELAY_MS:
76
+ raise MixError(f"delay must be between 0 and {MAX_DELAY_MS} ms")
77
+ _set_delay_live(_sum_id(), ms)
78
+ state.save("delay_ms", ms)
79
+
80
+
81
+ def save_listen_level() -> None:
82
+ nid = pw.node_id(LISTEN_NODE)
83
+ if nid is None:
84
+ raise MixError(f"node {LISTEN_NODE} not found")
85
+ for entry in pw.props_params(nid):
86
+ vols = entry.get("channelVolumes")
87
+ if isinstance(vols, list) and vols:
88
+ state.save("escucha", vols)
89
+ return
90
+
91
+
92
+ def apply() -> None:
93
+ """Restore everything saved."""
94
+ saved = state.load()
95
+ if not saved:
96
+ return
97
+ nid = pw.node_id(SUM_NODE)
98
+ if nid is not None:
99
+ for n in range(1, 5):
100
+ g = saved.get(str(n))
101
+ if isinstance(g, (int, float)) and 0 <= g <= MAX_GAIN:
102
+ pw.set_graph_param(nid, f"mix:Gain {n}", float(g))
103
+ ms = saved.get("delay_ms")
104
+ if isinstance(ms, (int, float)) and 0 <= ms <= MAX_DELAY_MS:
105
+ _set_delay_live(nid, float(ms))
106
+ lid = pw.node_id(LISTEN_NODE)
107
+ vols = saved.get("escucha")
108
+ if lid is not None and isinstance(vols, list) and vols:
109
+ pw.set_props(lid, "{ channelVolumes = [ " + " ".join(f"{float(v):.6g}" for v in vols) + " ] }")
evo8/monitor.py ADDED
@@ -0,0 +1,229 @@
1
+ """Hear the Mezcla, or single interface inputs, on the selected output.
2
+
3
+ The full monitor links the Mezcla source straight onto the selected output's
4
+ first two channels (FL/FR, or AUX0/AUX1 on a Pro Audio interface): a direct
5
+ port link adds no buffering of its own, so the delay is the graph quantum,
6
+ which is lowered while monitoring. The Compartido listening loopback is muted
7
+ meanwhile, because the mix already carries it and it would be heard twice.
8
+
9
+ Each interface input can also be heard on its own: its capture port is linked
10
+ onto the same two output channels, without the Compartido music, which keeps
11
+ playing through its listening loopback. The inputs wanted on are kept in a
12
+ runtime file and the links are kept in step with it by every call (`status`
13
+ included), so they come back after PipeWire restarts and follow the selected
14
+ output. While the full monitor is on they are lifted, as the Mezcla already
15
+ carries inputs 1-2.
16
+
17
+ Links are made with pw-link, so they live in PipeWire rather than in this
18
+ process; they last until turned off or PipeWire restarts.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+
25
+ from . import mix, pw, state
26
+
27
+ SOURCE_PORT = f"{mix.MIX_SOURCE}:capture_MONO"
28
+ QUANTUM = int(os.environ.get("EVO8_MONITOR_QUANTUM", "128"))
29
+ INPUT_SOURCE = os.environ.get("EVO8_INPUT_SOURCE", "alsa_input.usb-Audient_EVO8-00.pro-input-0")
30
+
31
+ # Present while the full monitor is on. If its links vanish without `off`
32
+ # (PipeWire restarted, the output was recreated), `status` finds the mark and
33
+ # undoes the rest: the muted listening stream and the forced quantum.
34
+ MARKER = state.runtime_dir() / "evo8-monitor"
35
+ INPUTS_FILE = state.runtime_dir() / "evo8-monitor-inputs"
36
+
37
+ # The wh01s17 shell scripts kept the same state under other names; adopt it.
38
+ _LEGACY_MARKER = state.runtime_dir() / "wh01s17-mix-monitor"
39
+ _LEGACY_INPUTS = state.runtime_dir() / "wh01s17-mix-monitor-inputs"
40
+ for _old, _new in ((_LEGACY_MARKER, MARKER), (_LEGACY_INPUTS, INPUTS_FILE)):
41
+ if _old.exists() and not _new.exists():
42
+ try:
43
+ _old.replace(_new)
44
+ except OSError:
45
+ pass
46
+
47
+
48
+ class MonitorError(RuntimeError):
49
+ pass
50
+
51
+
52
+ # ---- full monitor ----
53
+
54
+ def available() -> bool:
55
+ return SOURCE_PORT in pw.output_ports()
56
+
57
+
58
+ def _playback_links(port: str) -> list[str]:
59
+ # Real sinks have playback_* inputs; Meet's own capture stream has input_*
60
+ # ports and is left alone.
61
+ return [t for t in pw.links_from(port) if ":playback_" in t]
62
+
63
+
64
+ def is_on() -> bool:
65
+ return bool(_playback_links(SOURCE_PORT))
66
+
67
+
68
+ def _listen_inputs() -> list[pw.SinkInput]:
69
+ return [s for s in pw.sink_inputs() if s.node_name == mix.LISTEN_NODE]
70
+
71
+
72
+ def _listen_muted() -> bool:
73
+ return any(s.mute for s in _listen_inputs())
74
+
75
+
76
+ def _set_listen_mute(muted: bool) -> None:
77
+ for s in _listen_inputs():
78
+ pw.run("pactl", "set-sink-input-mute", str(s.index), "1" if muted else "0")
79
+
80
+
81
+ def status() -> str:
82
+ """"on", "off" or "unavailable" (no Mezcla); heals stale state on the way."""
83
+ if not available():
84
+ result = "unavailable"
85
+ elif is_on():
86
+ result = "on"
87
+ else:
88
+ # Off, but left in a monitoring state by links that vanished on their own.
89
+ if MARKER.exists() or _listen_muted():
90
+ _undo_side_effects()
91
+ result = "off"
92
+ if INPUTS_FILE.exists():
93
+ sync_inputs()
94
+ update_quantum()
95
+ return result
96
+
97
+
98
+ def _sync_port(port: str, want: set[str]) -> None:
99
+ """Make `port`'s playback links exactly `want`, touching only what differs.
100
+
101
+ Re-linking what is already linked is not harmless: every link change makes
102
+ the selected output's node change, and a client that re-targets the monitor
103
+ on such changes (follow) would loop, glitching the audio each time."""
104
+ have = set(_playback_links(port))
105
+ for t in have - want:
106
+ pw.unlink(port, t)
107
+ for t in want - have:
108
+ pw.link(port, t)
109
+
110
+
111
+ def turn_on() -> None:
112
+ if not available():
113
+ raise MonitorError("unavailable")
114
+ ports = pw.sink_ports()
115
+ if not ports:
116
+ raise MonitorError("the selected output has no playback ports")
117
+ _sync_port(SOURCE_PORT, set(ports))
118
+ if not all(s.mute for s in _listen_inputs()):
119
+ _set_listen_mute(True)
120
+ MARKER.touch()
121
+ sync_inputs()
122
+ update_quantum()
123
+
124
+
125
+ def _undo_side_effects() -> None:
126
+ if _listen_muted():
127
+ _set_listen_mute(False)
128
+ MARKER.unlink(missing_ok=True)
129
+ sync_inputs()
130
+ update_quantum()
131
+
132
+
133
+ def turn_off() -> None:
134
+ _sync_port(SOURCE_PORT, set())
135
+ _undo_side_effects()
136
+
137
+
138
+ def toggle() -> None:
139
+ turn_off() if is_on() else turn_on()
140
+
141
+
142
+ def follow() -> None:
143
+ """Re-target whatever is monitored onto the selected output."""
144
+ if is_on():
145
+ turn_on()
146
+ elif MARKER.exists() or _listen_muted():
147
+ _undo_side_effects()
148
+ else:
149
+ sync_inputs()
150
+ update_quantum()
151
+
152
+
153
+ # ---- single inputs ----
154
+
155
+ def interface_ports() -> list[str]:
156
+ """Capture ports of the interface, in input order (AUX0 = input 1)."""
157
+ prefix = f"{INPUT_SOURCE}:capture_"
158
+ ports = [p for p in pw.output_ports() if p.startswith(prefix)]
159
+
160
+ def order(p: str):
161
+ tail = p[len(prefix):]
162
+ digits = "".join(c for c in tail if c.isdigit())
163
+ return (tail.rstrip("0123456789"), int(digits) if digits else 0)
164
+
165
+ return sorted(ports, key=order)
166
+
167
+
168
+ def wanted_inputs() -> set[int]:
169
+ try:
170
+ text = INPUTS_FILE.read_text()
171
+ except OSError:
172
+ return set()
173
+ return {int(l) for l in text.split() if l.isdigit()}
174
+
175
+
176
+ def _write_wanted(wanted: set[int]) -> None:
177
+ if not wanted:
178
+ INPUTS_FILE.unlink(missing_ok=True)
179
+ return
180
+ tmp = INPUTS_FILE.with_suffix(".tmp")
181
+ tmp.write_text("".join(f"{n}\n" for n in sorted(wanted)))
182
+ tmp.replace(INPUTS_FILE)
183
+
184
+
185
+ def sync_inputs() -> None:
186
+ """Bring the input links in line with the wanted set: only missing links are
187
+ made and stale ones removed, so a call that changes nothing makes no sound."""
188
+ ports = interface_ports()
189
+ if not ports:
190
+ return
191
+ targets = [] if is_on() else pw.sink_ports()
192
+ wanted = wanted_inputs()
193
+ for i, port in enumerate(ports, start=1):
194
+ _sync_port(port, set(targets) if i in wanted else set())
195
+
196
+
197
+ def _any_input_linked() -> bool:
198
+ return any(_playback_links(p) for p in interface_ports())
199
+
200
+
201
+ def update_quantum() -> None:
202
+ """Hold the low quantum while anything is monitored. Only our own value is
203
+ ever undone, never one something else forced."""
204
+ current = pw.force_quantum()
205
+ if is_on() or _any_input_linked():
206
+ if current == 0:
207
+ pw.set_force_quantum(QUANTUM)
208
+ elif current == QUANTUM:
209
+ pw.set_force_quantum(0)
210
+
211
+
212
+ def inputs() -> list[int]:
213
+ """One 0/1 per interface input: whether it is monitored."""
214
+ wanted = wanted_inputs()
215
+ return [1 if i in wanted else 0 for i in range(1, len(interface_ports()) + 1)]
216
+
217
+
218
+ def set_input(n: int, on: bool | None) -> None:
219
+ """Turn input n on, off, or toggle it (on=None)."""
220
+ count = len(interface_ports())
221
+ if not 1 <= n <= count:
222
+ raise MonitorError(f"no input {n} on {INPUT_SOURCE}")
223
+ wanted = wanted_inputs()
224
+ if on is None:
225
+ on = n not in wanted
226
+ (wanted.add if on else wanted.discard)(n)
227
+ _write_wanted(wanted)
228
+ sync_inputs()
229
+ update_quantum()
evo8/profiles.py ADDED
@@ -0,0 +1,112 @@
1
+ """Card profiles a person would actually pick.
2
+
3
+ ALSA offers every channel layout it can probe (the EVO 8 lists 25), almost all
4
+ of them useless. Each card keeps:
5
+ Pro Audio -- every input and output as its own channel
6
+ Estándar -- the best regular profile (input + output if one exists)
7
+ Solo salida -- the best output-only one, when Estándar has inputs too
8
+ plus whatever is active now, so the current state is always visible.
9
+ Each one carries a short hint saying what picking it does.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from . import apps
17
+
18
+ # Profiles a card must be on for the Mezcla to work: its config reads the EVO 8
19
+ # inputs one by one, which only Pro Audio exposes.
20
+ REQUIRED = {"alsa_card.usb-Audient_EVO8-00": "pro-audio"}
21
+
22
+
23
+ def _profile_name(name: str) -> str:
24
+ return "Pro Audio" if name == "pro-audio" else name
25
+
26
+
27
+ def friendly_label(text: str) -> str:
28
+ label = str(text or "").strip()
29
+ for pattern in (r"^sof-soundwire\s+", r"^built-?in audio\s+", r"\s+Output$", r"\s+Input$"):
30
+ label = re.sub(pattern, "", label, flags=re.I)
31
+ return label.replace("Microphones", "Microphone")
32
+
33
+
34
+ def card_label(name: str, description: str, profiles: list[dict]) -> str:
35
+ desc = str(description or name or "")
36
+ if re.search(r"built-?in", desc, re.I):
37
+ return "Integrado"
38
+ if profiles and all(p["name"] == "pro-audio" or re.search("hdmi", p["name"], re.I) for p in profiles):
39
+ return "HDMI"
40
+ return friendly_label(desc)
41
+
42
+
43
+ def hint(profile: dict, bluetooth: bool = False, required: bool = False) -> str:
44
+ """What picking this profile does, in a few words."""
45
+ if profile["name"] == "pro-audio":
46
+ return "cada canal aparte" + (" · lo usa la Mezcla" if required else "")
47
+ if profile["sinks"] and profile["sources"]:
48
+ return "con micrófono, sonido de llamada" if bluetooth else "entrada y salida comunes"
49
+ if profile["sinks"]:
50
+ if bluetooth:
51
+ return "solo sonido, alta calidad"
52
+ return "solo sonido, sin entrada"
53
+ if profile["sources"]:
54
+ return "solo entrada"
55
+ return ""
56
+
57
+
58
+ def curate(profiles: list[dict], active: str, bluetooth: bool = False,
59
+ required: str = "") -> list[dict]:
60
+ """Profiles come sorted by priority (apps.card_profiles)."""
61
+ picked: list[dict] = []
62
+ seen: set[str] = set()
63
+
64
+ def add(p, label):
65
+ if p and p["name"] not in seen:
66
+ seen.add(p["name"])
67
+ picked.append({"name": p["name"], "label": label,
68
+ "hint": hint(p, bluetooth, p["name"] == required)})
69
+
70
+ pro = next((p for p in profiles if p["name"] == "pro-audio"), None)
71
+ rest = [p for p in profiles if p["name"] != "pro-audio"]
72
+ duplex = next((p for p in rest if p["sinks"] > 0 and p["sources"] > 0), None)
73
+ output = next((p for p in rest if p["sinks"] > 0 and p["sources"] == 0), None)
74
+ add(pro, "Pro Audio")
75
+ if duplex:
76
+ add(duplex, "Estándar")
77
+ add(output, "Solo salida")
78
+ else:
79
+ add(output, "Estándar")
80
+ for p in profiles:
81
+ if p["name"] == active:
82
+ add(p, p["description"])
83
+ return picked
84
+
85
+
86
+ def warning(card: dict) -> str:
87
+ """Non-empty when the card is off the profile the Mezcla needs."""
88
+ required = card.get("required")
89
+ if not required or card.get("active") == required:
90
+ return ""
91
+ return "Requiere " + _profile_name(required)
92
+
93
+
94
+ def cards(raw: list[dict] | None = None) -> list[dict]:
95
+ """[{name, label, active, required, warning, profiles: [{name, label, hint}]}]"""
96
+ result = []
97
+ for c in apps.card_profiles() if raw is None else raw:
98
+ required = REQUIRED.get(c["name"], "")
99
+ curated = curate(c["profiles"], c["active"],
100
+ bluetooth=str(c["name"]).startswith("bluez_card."), required=required)
101
+ if len(curated) < 2:
102
+ continue
103
+ card = {
104
+ "name": c["name"],
105
+ "label": card_label(c["name"], c["description"], c["profiles"]),
106
+ "active": c["active"],
107
+ "required": required,
108
+ "profiles": curated,
109
+ }
110
+ card["warning"] = warning(card)
111
+ result.append(card)
112
+ return result