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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Audient EVO 8 on Linux."""
2
+
3
+ __version__ = "0.1.0"
evo8/about.py ADDED
@@ -0,0 +1,131 @@
1
+ """What the "Acerca de" tab and `evoctl --version` show.
2
+
3
+ Everything here is read from files (package metadata, sysfs, config paths):
4
+ nothing talks to the EVO over USB, so it is safe to call at any time.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import platform
11
+ from pathlib import Path
12
+
13
+ from . import __version__, state
14
+
15
+ NAME = "evo8-linux"
16
+ APP = "Mezclador EVO 8"
17
+ DESCRIPTION = ("Control del Audient EVO 8 en Linux: mezcla de monitoreo interna, "
18
+ "loop-back, preamps y un micrófono virtual para videollamadas.")
19
+ AUTHOR = "wh01s17"
20
+ LICENSE = "MIT"
21
+ REPO = "https://github.com/wh01s17/evo8-linux"
22
+ ISSUES = REPO + "/issues"
23
+ DISCLAIMER = "Proyecto no oficial, sin relación con Audient."
24
+ TESTED_FIRMWARE = "1.4c"
25
+
26
+ VENDOR_ID, PRODUCT_ID = "2708", "0007"
27
+ SYSFS_USB = Path("/sys/bus/usb/devices")
28
+
29
+ _CONFIG_DIRS = (
30
+ ("usuario", Path(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")) / "pipewire"),
31
+ ("sistema", Path("/etc/pipewire")),
32
+ ("paquete", Path("/usr/share/pipewire")),
33
+ )
34
+ _UDEV_RULES = (Path("/etc/udev/rules.d/70-audient-evo8.rules"),
35
+ Path("/usr/lib/udev/rules.d/70-audient-evo8.rules"))
36
+
37
+
38
+ def tilde(path) -> str:
39
+ """The path with the home folder as "~", so reports don't carry the user name."""
40
+ text, home = str(path), os.path.expanduser("~")
41
+ return "~" + text[len(home):] if home not in ("", "/") and (text == home or text.startswith(home + "/")) else text
42
+
43
+
44
+ def version() -> str:
45
+ try:
46
+ from importlib.metadata import PackageNotFoundError, version as dist_version
47
+ return dist_version(NAME)
48
+ except (ImportError, PackageNotFoundError):
49
+ return __version__
50
+
51
+
52
+ def firmware_text(bcd: str) -> str:
53
+ """bcdDevice as sysfs prints it ("014c") → "1.4c"."""
54
+ bcd = bcd.strip().lower()
55
+ if len(bcd) != 4:
56
+ return bcd
57
+ return f"{int(bcd[:2], 16)}.{bcd[2:]}"
58
+
59
+
60
+ def device(root: Path = SYSFS_USB) -> dict:
61
+ """{connected, firmware, tested, speed} from sysfs, without any USB traffic."""
62
+ try:
63
+ entries = sorted(root.iterdir())
64
+ except OSError:
65
+ entries = []
66
+ for d in entries:
67
+ try:
68
+ if (d / "idVendor").read_text().strip() != VENDOR_ID:
69
+ continue
70
+ if (d / "idProduct").read_text().strip() != PRODUCT_ID:
71
+ continue
72
+ fw = firmware_text((d / "bcdDevice").read_text())
73
+ speed = (d / "speed").read_text().strip() if (d / "speed").exists() else ""
74
+ except OSError:
75
+ continue
76
+ return {"connected": True, "firmware": fw, "tested": fw == TESTED_FIRMWARE,
77
+ "speed": f"{speed} Mbit/s" if speed else ""}
78
+ return {"connected": False, "firmware": "", "tested": False, "speed": ""}
79
+
80
+
81
+ def install_kind(module_file: str = __file__) -> str:
82
+ path = Path(module_file).resolve()
83
+ if (path.parents[2] / ".git").exists():
84
+ return f"desarrollo ({tilde(path.parents[2])})"
85
+ if str(path).startswith("/usr/"):
86
+ return "paquete del sistema"
87
+ return "pip"
88
+
89
+
90
+ def pipewire_config() -> str:
91
+ """Where the Mezcla config PipeWire loads comes from (first one wins)."""
92
+ for label, base in _CONFIG_DIRS:
93
+ f = base / "pipewire.conf.d" / "20-mezcla.conf"
94
+ if f.exists():
95
+ return f"{tilde(f)} ({label})"
96
+ return ""
97
+
98
+
99
+ def udev_rule() -> str:
100
+ return next((str(p) for p in _UDEV_RULES if p.exists()), "")
101
+
102
+
103
+ def info(extra_versions: dict | None = None) -> dict:
104
+ return {
105
+ "name": NAME, "app": APP, "version": version(), "description": DESCRIPTION,
106
+ "author": AUTHOR, "license": LICENSE, "repo": REPO, "issues": ISSUES,
107
+ "disclaimer": DISCLAIMER, "testedFirmware": TESTED_FIRMWARE,
108
+ "device": device(),
109
+ "install": install_kind(),
110
+ "pipewireConfig": pipewire_config(),
111
+ "udevRule": udev_rule(),
112
+ "stateFile": tilde(state.STATE),
113
+ "versions": {"Python": platform.python_version(), **(extra_versions or {})},
114
+ "platform": f"{platform.system()} {platform.release()}",
115
+ }
116
+
117
+
118
+ def report(data: dict | None = None) -> str:
119
+ """Plain text to paste into a bug report."""
120
+ d = data or info()
121
+ dev = d["device"]
122
+ lines = [
123
+ f"{d['name']} {d['version']}",
124
+ f"EVO 8: {'conectada, firmware ' + dev['firmware'] if dev['connected'] else 'no conectada'}",
125
+ f"Instalación: {d['install']}",
126
+ f"Config de PipeWire: {d['pipewireConfig'] or 'no encontrada'}",
127
+ f"Regla udev: {d['udevRule'] or 'no instalada'}",
128
+ f"Sistema: {d['platform']}",
129
+ ]
130
+ lines += [f"{k}: {v}" for k, v in d["versions"].items()]
131
+ return "\n".join(lines)
evo8/alsa.py ADDED
@@ -0,0 +1,77 @@
1
+ """Controls the kernel driver (snd-usb-audio) already exposes for the EVO 8.
2
+
3
+ "Mic Playback Volume" is the analog preamp gain per input (the same one the
4
+ interface's knob turns), raw 0..116 = -8..+50 dB in 0.5 dB steps. The EVO does
5
+ not keep these across a power cycle (it comes back at -8 dB), so every change
6
+ is saved and `restore_preamp()` puts them back.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+
14
+ from . import pw, state
15
+
16
+ CARD = os.environ.get("EVO8_ALSA_CARD", "EVO8")
17
+ PREAMP_CONTROL = "Mic Playback Volume"
18
+
19
+
20
+ class AlsaError(RuntimeError):
21
+ pass
22
+
23
+
24
+ def _control(name: str) -> dict:
25
+ info = pw.run("amixer", "-c", CARD, "cget", f"name={name}")
26
+ if not info:
27
+ raise AlsaError(f"control '{name}' not found on card {CARD}")
28
+ rng = re.search(r"min=(-?\d+),max=(-?\d+)", info)
29
+ db = re.search(r"dBminmax-min=(-?[\d.]+)dB,max=(-?[\d.]+)dB", info)
30
+ vals = re.search(r": values=([\d,-]+)", info)
31
+ if not (rng and db and vals):
32
+ raise AlsaError(f"could not parse '{name}' on card {CARD}")
33
+ return {
34
+ "raw_min": int(rng[1]), "raw_max": int(rng[2]),
35
+ "db_min": float(db[1]), "db_max": float(db[2]),
36
+ "values": [int(v) for v in vals[1].split(",")],
37
+ }
38
+
39
+
40
+ def preamp() -> dict:
41
+ """{"min", "max", "step", "gains"} in dB."""
42
+ c = _control(PREAMP_CONTROL)
43
+ step = (c["db_max"] - c["db_min"]) / (c["raw_max"] - c["raw_min"])
44
+ gains = [round(c["db_min"] + (v - c["raw_min"]) * step, 2) for v in c["values"]]
45
+ return {"min": c["db_min"], "max": c["db_max"], "step": round(step, 4), "gains": gains}
46
+
47
+
48
+ def set_preamp(n: int, db: float) -> None:
49
+ c = _control(PREAMP_CONTROL)
50
+ if not 1 <= n <= len(c["values"]):
51
+ raise AlsaError(f"input must be 1-{len(c['values'])}")
52
+ db = min(max(db, c["db_min"]), c["db_max"])
53
+ raw = round(c["raw_min"] + (db - c["db_min"]) / (c["db_max"] - c["db_min"]) * (c["raw_max"] - c["raw_min"]))
54
+ values = list(c["values"])
55
+ values[n - 1] = raw
56
+ pw.run("amixer", "-c", CARD, "cset", f"name={PREAMP_CONTROL}", ",".join(map(str, values)), check=True)
57
+ applied = c["db_min"] + (raw - c["raw_min"]) * (c["db_max"] - c["db_min"]) / (c["raw_max"] - c["raw_min"])
58
+ saved = state.load().get("preamp") or {}
59
+ saved[str(n)] = round(applied, 2)
60
+ state.save("preamp", saved)
61
+
62
+
63
+ def restore_preamp() -> None:
64
+ saved = state.load().get("preamp") or {}
65
+ try:
66
+ c = _control(PREAMP_CONTROL)
67
+ except AlsaError:
68
+ return
69
+ values = list(c["values"])
70
+ for key, db in saved.items():
71
+ n = int(key)
72
+ if 1 <= n <= len(values) and isinstance(db, (int, float)):
73
+ db = min(max(db, c["db_min"]), c["db_max"])
74
+ values[n - 1] = round(c["raw_min"] + (db - c["db_min"]) / (c["db_max"] - c["db_min"])
75
+ * (c["raw_max"] - c["raw_min"]))
76
+ if values != c["values"]:
77
+ pw.run("amixer", "-c", CARD, "cset", f"name={PREAMP_CONTROL}", ",".join(map(str, values)))
evo8/apps.py ADDED
@@ -0,0 +1,76 @@
1
+ """Per-app routing to Compartido, and card profiles.
2
+
3
+ Compartido plays on the selected output and also feeds the Mezcla, so moving
4
+ an app's stream there sends that app along with the mic. WirePlumber
5
+ remembers the choice per application, so its later streams go there too.
6
+ Streams are named by PipeWire node id; pactl numbers sink inputs differently,
7
+ so they are matched through each sink input's object.id.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+
14
+ from . import mix, pw
15
+
16
+
17
+ class AppsError(RuntimeError):
18
+ pass
19
+
20
+
21
+ def shared_streams() -> list[str]:
22
+ """Node ids of the app streams currently on Compartido."""
23
+ shared = pw.sink_index(mix.SHARED_SINK)
24
+ if shared is None:
25
+ return []
26
+ return [s.node_id for s in pw.sink_inputs() if s.sink == shared and s.node_id]
27
+
28
+
29
+ def share(node_id: str, on: bool) -> None:
30
+ match = next((s for s in pw.sink_inputs() if s.node_id == str(node_id)), None)
31
+ if match is None:
32
+ raise AppsError(f"no playback stream for node {node_id}")
33
+ if on:
34
+ if pw.sink_index(mix.SHARED_SINK) is None:
35
+ raise AppsError(f"sink {mix.SHARED_SINK} not found")
36
+ target = mix.SHARED_SINK
37
+ else:
38
+ target = pw.default_sink()
39
+ pw.run("pactl", "move-sink-input", str(match.index), target, check=True)
40
+
41
+
42
+ # ---- card profiles ----
43
+ # Only profiles that are available and not "off" are listed, highest priority
44
+ # first, and cards with nothing to switch between (a phone's audio gateway) are
45
+ # dropped, so every card listed has a real choice.
46
+
47
+ def card_profiles() -> list[dict]:
48
+ out = pw.run("pactl", "-f", "json", "list", "cards", timeout=2)
49
+ try:
50
+ cards = json.loads(out or "[]")
51
+ except json.JSONDecodeError:
52
+ return []
53
+ result = []
54
+ for c in cards:
55
+ profiles = [
56
+ {"name": name, "description": p.get("description") or name,
57
+ "sinks": p.get("sinks", 0), "sources": p.get("sources", 0),
58
+ "_priority": p.get("priority", 0)}
59
+ for name, p in (c.get("profiles") or {}).items()
60
+ if name != "off" and p.get("available") is not False
61
+ ]
62
+ profiles.sort(key=lambda p: -p["_priority"])
63
+ for p in profiles:
64
+ del p["_priority"]
65
+ if len(profiles) > 1:
66
+ result.append({
67
+ "name": c.get("name"),
68
+ "description": (c.get("properties") or {}).get("device.description") or c.get("name"),
69
+ "active": c.get("active_profile") or "",
70
+ "profiles": profiles,
71
+ })
72
+ return result
73
+
74
+
75
+ def set_card_profile(card: str, profile: str) -> None:
76
+ pw.run("pactl", "set-card-profile", card, profile, timeout=3, check=True)
evo8/calibrate.py ADDED
@@ -0,0 +1,159 @@
1
+ """Measure the Mezcla sync delay by playing along to a click.
2
+
3
+ Whoever plays along to music on Compartido hears it after the output latency,
4
+ and their instrument reaches the Mezcla after the input latency, so in the sum
5
+ the instrument trails the music by both. This measures that gap the only way
6
+ that includes the converters, USB and the player: a click track goes out
7
+ through Compartido exactly as the music does, the player hits a short note on
8
+ every click, and the onsets are compared in one 4-channel recording of
9
+ mezcla.suma (inputs 1-2 on FL/FR, Compartido on RL/RR), taken *before* the
10
+ sync delay so it measures the raw gap.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import array
16
+ import math
17
+ import signal
18
+ import statistics
19
+ import subprocess
20
+ import tempfile
21
+ import time
22
+ import wave
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+
26
+ from . import mix, monitor, pw
27
+
28
+ RATE = 48000
29
+ BPM = 100
30
+ BEATS = 20 # the first 4 count in and are not measured
31
+ LEAD_IN = 1.0 # seconds of silence before the first click
32
+ COUNT_IN = 4
33
+ MIN_HITS = 6
34
+
35
+
36
+ class CalibrationError(RuntimeError):
37
+ pass
38
+
39
+
40
+ @dataclass
41
+ class Result:
42
+ clicks: int
43
+ hits: int
44
+ median_ms: int
45
+ spread_ms: float | None
46
+
47
+ @property
48
+ def summary(self) -> str:
49
+ spread = f" · dispersión {self.spread_ms:g} ms" if self.spread_ms is not None else ""
50
+ return f"Golpes medidos: {self.hits} de {self.clicks} · retardo mediano {self.median_ms} ms{spread}"
51
+
52
+
53
+ def click_track(path: Path, bpm: float = BPM, beats: int = BEATS, lead: float = LEAD_IN) -> None:
54
+ period = 60.0 / bpm
55
+ total = int(RATE * (lead + beats * period + 1.0))
56
+ data = array.array("h", [0] * total * 2)
57
+ length = int(RATE * 0.015)
58
+ for b in range(beats):
59
+ start = int(RATE * (lead + b * period))
60
+ freq = 2000.0 if b % 4 == 0 else 1500.0
61
+ for i in range(length):
62
+ v = int(22000 * math.sin(2 * math.pi * freq * i / RATE) * (1 - i / length))
63
+ data[2 * (start + i)] = v
64
+ data[2 * (start + i) + 1] = v
65
+ with wave.open(str(path), "w") as w:
66
+ w.setnchannels(2)
67
+ w.setsampwidth(2)
68
+ w.setframerate(RATE)
69
+ w.writeframes(data.tobytes())
70
+
71
+
72
+ def _envelope(data: array.array, channels: int, picked: list[int], win: int) -> list[int]:
73
+ frames = len(data) // channels
74
+ env = []
75
+ for f in range(0, frames - win, win):
76
+ m = 0
77
+ for c in picked:
78
+ seg = data[f * channels + c:(f + win) * channels + c:channels]
79
+ if seg:
80
+ m = max(m, max(abs(x) for x in seg))
81
+ env.append(m)
82
+ return env
83
+
84
+
85
+ def _onsets(env: list[int], refractory: int) -> list[int]:
86
+ if not env:
87
+ return []
88
+ floor = statistics.median(env)
89
+ top = max(env)
90
+ if top <= floor * 4 or top < 300:
91
+ return []
92
+ thr = floor + 0.3 * (top - floor)
93
+ out, last = [], -10 ** 9
94
+ for i in range(1, len(env)):
95
+ if env[i] >= thr and env[i - 1] < thr and i - last > refractory:
96
+ out.append(i)
97
+ last = i
98
+ return out
99
+
100
+
101
+ def analyse(recording: Path, bpm: float = BPM) -> Result:
102
+ """Onsets on 1 ms envelope frames: clicks on RL/RR, hits on FL/FR."""
103
+ with wave.open(str(recording)) as w:
104
+ rate, ch = w.getframerate(), w.getnchannels()
105
+ data = array.array("h", w.readframes(w.getnframes()))
106
+ win = rate // 1000
107
+ clicks = _onsets(_envelope(data, ch, [2, 3], win), int(60000 / bpm * 0.6))[COUNT_IN:]
108
+ hits = _onsets(_envelope(data, ch, [0, 1], win), 120)
109
+ lags = []
110
+ for c in clicks:
111
+ near = [h - c for h in hits if -60 <= h - c <= 400]
112
+ if near:
113
+ lags.append(min(near, key=abs) if min(near) < 0 else near[0])
114
+ if len(clicks) < MIN_HITS:
115
+ raise CalibrationError("No se detectaron los clicks en Compartido (¿la escucha está en silencio?).")
116
+ if len(lags) < MIN_HITS:
117
+ raise CalibrationError(f"Solo se detectaron {len(lags)} golpes sobre {len(clicks)} clicks. "
118
+ "Toca más fuerte y seco, uno por click, y repite.")
119
+ spread = None
120
+ if len(lags) >= 4:
121
+ q = statistics.quantiles(lags, n=4)
122
+ spread = q[2] - q[0]
123
+ return Result(len(clicks), len(lags), max(0, round(statistics.median(lags))), spread)
124
+
125
+
126
+ def run(apply: bool = False, on_progress=print) -> Result:
127
+ if pw.node_id(mix.SUM_NODE) is None:
128
+ raise CalibrationError("No se encontró la Mezcla (mezcla.suma).")
129
+ if pw.node_id(mix.SHARED_SINK) is None:
130
+ raise CalibrationError("No se encontró Compartido.")
131
+
132
+ # The click must reach the ears the way the music does: through the
133
+ # Compartido listening path, so the full monitor (which mutes that path) is
134
+ # turned off for the measurement and restored afterwards.
135
+ was_on = monitor.status() == "on"
136
+ if was_on:
137
+ monitor.turn_off()
138
+ try:
139
+ with tempfile.TemporaryDirectory() as tmp:
140
+ click, rec = Path(tmp) / "click.wav", Path(tmp) / "rec.wav"
141
+ click_track(click)
142
+ on_progress("Calibrando: toca un golpe corto y seco en cada click (los primeros 4 son de cuenta).")
143
+ recorder = subprocess.Popen(
144
+ ["pw-record", "--target", mix.SUM_NODE, "-P", "stream.capture.sink=true",
145
+ "--channels", "4", "--format", "s16", str(rec)],
146
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
147
+ time.sleep(0.3)
148
+ subprocess.run(["pw-play", "--target", mix.SHARED_SINK, str(click)],
149
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
150
+ time.sleep(0.5)
151
+ recorder.send_signal(signal.SIGINT)
152
+ recorder.wait(timeout=5)
153
+ result = analyse(rec)
154
+ finally:
155
+ if was_on:
156
+ monitor.turn_on()
157
+ if apply:
158
+ mix.set_delay_ms(result.median_ms)
159
+ return result
evo8/cli.py ADDED
@@ -0,0 +1,214 @@
1
+ """evoctl: command-line control of the Audient EVO 8 setup.
2
+
3
+ Output stays machine-friendly (JSON or one bare value per line) so the mixer
4
+ window and shell widgets can read it; messages for people go to stderr.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ from . import about, alsa, apps, calibrate, mix, monitor
14
+
15
+
16
+ def _json(value) -> None:
17
+ print(json.dumps(value, separators=(",", ":"), ensure_ascii=False))
18
+
19
+
20
+ def _on_off(word: str) -> bool | None:
21
+ return {"on": True, "off": False, "toggle": None}[word]
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ p = argparse.ArgumentParser(prog="evoctl", description="Control del Audient EVO 8 y la Mezcla en Linux.")
26
+ p.add_argument("--version", action="version", version=f"evo8-linux {about.version()}")
27
+ sub = p.add_subparsers(dest="cmd", required=True)
28
+
29
+ m = sub.add_parser("mix", help="ganancias de la Mezcla (1-2 entradas, 3-4 Compartido L/R)")
30
+ ms = m.add_subparsers(dest="action", required=True)
31
+ ms.add_parser("get", help="las cuatro ganancias, en JSON")
32
+ s = ms.add_parser("set", help="una ganancia, lineal 0..4")
33
+ s.add_argument("n", type=int, choices=range(1, 5))
34
+ s.add_argument("gain", type=float)
35
+
36
+ d = sub.add_parser("delay", help="compensación de sincronía de Compartido hacia la Mezcla")
37
+ ds = d.add_subparsers(dest="action", required=True)
38
+ ds.add_parser("get", help="retardo actual en ms")
39
+ s = ds.add_parser("set", help="retardo en ms (0..500)")
40
+ s.add_argument("ms", type=float)
41
+
42
+ l = sub.add_parser("listen", help="nivel de escucha de Compartido")
43
+ l.add_subparsers(dest="action", required=True).add_parser("save", help="guardar el nivel actual")
44
+
45
+ sub.add_parser("apply", help="restaurar lo guardado: ganancias, retardo, escucha y preamps")
46
+ sub.add_parser("restore", help="al conectar la EVO: preamps, mezcla interna y loop-back guardados")
47
+
48
+ mo = sub.add_parser("monitor", help="escuchar la Mezcla o entradas sueltas por la salida")
49
+ mos = mo.add_subparsers(dest="action", required=True)
50
+ for name in ("status", "on", "off", "toggle", "follow"):
51
+ mos.add_parser(name)
52
+ mos.add_parser("inputs", help="una marca 0/1 por entrada, en JSON")
53
+ s = mos.add_parser("input", help="monitorear una entrada sola")
54
+ s.add_argument("n", type=int)
55
+ s.add_argument("state", choices=("on", "off", "toggle"))
56
+
57
+ pr = sub.add_parser("preamp", help="ganancia de preamp por entrada (dB)")
58
+ prs = pr.add_subparsers(dest="action", required=True)
59
+ prs.add_parser("get")
60
+ s = prs.add_parser("set")
61
+ s.add_argument("n", type=int)
62
+ s.add_argument("db", type=float)
63
+
64
+ sh = sub.add_parser("share", help="enviar una app a Compartido o devolverla")
65
+ shs = sh.add_subparsers(dest="action", required=True)
66
+ shs.add_parser("list", help="node ids en Compartido, uno por línea")
67
+ for name in ("on", "off"):
68
+ shs.add_parser(name).add_argument("node_id")
69
+
70
+ pf = sub.add_parser("profiles", help="perfiles de las tarjetas de sonido")
71
+ pfs = pf.add_subparsers(dest="action", required=True)
72
+ pfs.add_parser("list")
73
+ s = pfs.add_parser("set")
74
+ s.add_argument("card")
75
+ s.add_argument("profile")
76
+
77
+ hw = sub.add_parser("hw", help="ajustes del hardware por USB (corta el audio ~1 s)")
78
+ hws = hw.add_subparsers(dest="area", required=True)
79
+ lb = hws.add_parser("loopback", help="fuente de los canales 5-6 de captura")
80
+ lbs = lb.add_subparsers(dest="action", required=True)
81
+ lbs.add_parser("get")
82
+ lbs.add_parser("set").add_argument("source", help="loopback | pc12 | pc34 | in12 | in34")
83
+ hi = hws.add_parser("input", help="phantom 48 V y mute por entrada")
84
+ his = hi.add_subparsers(dest="action", required=True)
85
+ his.add_parser("get", help="estado de las 4 entradas, JSON")
86
+ for name in ("phantom", "mute"):
87
+ s = his.add_parser(name, help=f"{name} de una entrada")
88
+ s.add_argument("n", type=int)
89
+ s.add_argument("state", choices=("on", "off"))
90
+ hm = hws.add_parser("mix", help="mezcla de monitoreo interna (10 entradas × 4 salidas)")
91
+ hms = hm.add_subparsers(dest="action", required=True)
92
+ hms.add_parser("get", help="matriz en dB, JSON")
93
+ s = hms.add_parser("set", help="un cruce: entrada (1-10) salida (1-4) dB u off")
94
+ s.add_argument("input", type=int)
95
+ s.add_argument("output", type=int)
96
+ s.add_argument("db")
97
+
98
+ st = sub.add_parser("setup", help="instalar la config de PipeWire, el servicio y el menú en tu usuario (tras pip/pipx)")
99
+ st.add_argument("--remove", action="store_true", help="quitar lo que instaló setup")
100
+ st.add_argument("--dry-run", action="store_true", help="mostrar qué haría sin tocar nada")
101
+
102
+ c = sub.add_parser("calibrate", help="medir la sincronía tocando sobre un click")
103
+ c.add_argument("--apply", action="store_true", help="aplicar el valor medido")
104
+ c.add_argument("--recording", help="analizar una grabación de 4 canales existente")
105
+ return p
106
+
107
+
108
+ def main(argv: list[str] | None = None) -> int:
109
+ args = build_parser().parse_args(argv)
110
+ try:
111
+ return _dispatch(args)
112
+ except (mix.MixError, monitor.MonitorError, alsa.AlsaError, apps.AppsError,
113
+ calibrate.CalibrationError, RuntimeError, ValueError) as e:
114
+ print(str(e), file=sys.stderr)
115
+ return 1
116
+
117
+
118
+ def _dispatch(a) -> int:
119
+ if a.cmd == "setup":
120
+ from . import user_setup
121
+ return user_setup.run(remove_files=a.remove, dry_run=a.dry_run)
122
+ if a.cmd == "mix":
123
+ if a.action == "get":
124
+ _json(mix.gains())
125
+ else:
126
+ mix.set_gain(a.n, a.gain)
127
+ elif a.cmd == "delay":
128
+ if a.action == "get":
129
+ print(mix.delay_ms())
130
+ else:
131
+ mix.set_delay_ms(a.ms)
132
+ elif a.cmd == "listen":
133
+ mix.save_listen_level()
134
+ elif a.cmd == "apply":
135
+ mix.apply()
136
+ alsa.restore_preamp()
137
+ elif a.cmd == "restore":
138
+ import time
139
+ from . import hw, state
140
+ for _ in range(20): # the card's controls appear a moment after plugging
141
+ try:
142
+ alsa.preamp()
143
+ break
144
+ except alsa.AlsaError:
145
+ time.sleep(0.5)
146
+ alsa.restore_preamp()
147
+ hw.restore(state.load().get("hw") or {})
148
+ mix.apply()
149
+ elif a.cmd == "monitor":
150
+ if a.action == "status":
151
+ print(monitor.status())
152
+ elif a.action == "on":
153
+ monitor.turn_on()
154
+ elif a.action == "off":
155
+ monitor.turn_off()
156
+ elif a.action == "toggle":
157
+ monitor.toggle()
158
+ elif a.action == "follow":
159
+ monitor.follow()
160
+ elif a.action == "inputs":
161
+ _json(monitor.inputs())
162
+ else:
163
+ monitor.set_input(a.n, _on_off(a.state))
164
+ elif a.cmd == "preamp":
165
+ if a.action == "get":
166
+ _json(alsa.preamp())
167
+ else:
168
+ alsa.set_preamp(a.n, a.db)
169
+ elif a.cmd == "share":
170
+ if a.action == "list":
171
+ for nid in apps.shared_streams():
172
+ print(nid)
173
+ else:
174
+ apps.share(a.node_id, a.action == "on")
175
+ elif a.cmd == "profiles":
176
+ if a.action == "list":
177
+ _json(apps.card_profiles())
178
+ else:
179
+ apps.set_card_profile(a.card, a.profile)
180
+ elif a.cmd == "hw":
181
+ from . import hw
182
+ if a.area == "input":
183
+ if a.action == "get":
184
+ _json(hw.inputs_get())
185
+ else:
186
+ flags = {a.n - 1: a.state == "on"}
187
+ hw.apply([], None, **{a.action: flags})
188
+ elif a.area == "loopback":
189
+ if a.action == "get":
190
+ _json(hw.loopback_get())
191
+ else:
192
+ hw.loopback_set(a.source)
193
+ elif a.action == "get":
194
+ _json(hw.mixer_get())
195
+ else:
196
+ db = hw.MIXER_OFF_DB if a.db == "off" else float(a.db)
197
+ hw.mixer_set([(a.input - 1, a.output - 1, db)])
198
+ elif a.cmd == "calibrate":
199
+ if a.recording:
200
+ from pathlib import Path
201
+ result = calibrate.analyse(Path(a.recording))
202
+ if a.apply:
203
+ mix.set_delay_ms(result.median_ms)
204
+ else:
205
+ result = calibrate.run(apply=a.apply)
206
+ print(result.summary)
207
+ if a.apply:
208
+ print(f"Compensación aplicada: {result.median_ms} ms.")
209
+ print(f"RESULT {result.median_ms}")
210
+ return 0
211
+
212
+
213
+ if __name__ == "__main__":
214
+ sys.exit(main())
evo8/data/__init__.py ADDED
File without changes
@@ -0,0 +1,8 @@
1
+ [Desktop Entry]
2
+ Type=Application
3
+ Name=Mezclador EVO 8
4
+ Comment=Mezcla, monitor y hardware del Audient EVO 8
5
+ Exec=evo8-mixer
6
+ Icon=evo8-mixer
7
+ Categories=AudioVideo;Audio;Mixer;
8
+ StartupWMClass=evo8-mixer