Files
qlcplus/scripts/smooth_smc_pad.py
T

186 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Smooth SMC-PAD knob CCs so RGBW fades feel less stepped.
Reads the physical pad (Bluetooth or USB), passes pad notes through
immediately, and eases Control Change values toward their targets at
~120 Hz before emitting on a virtual port named "SMC-PAD Smooth".
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the smoother is running).
Usage:
.venv/bin/python scripts/smooth_smc_pad.py
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
VIRTUAL_NAME = "SMC-PAD Smooth"
SOURCE_HINTS = (
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
"SMC-PAD",
)
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
for hint in SOURCE_HINTS:
for i, name in enumerate(ports):
if hint in name and VIRTUAL_NAME not in name:
return i
raise SystemExit(
"No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
)
def _alsa_port(client_substr: str, port_substr: str | None = None) -> str | None:
"""Return 'client:port' for an aconnect client/port name match."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return None
client = None
client_name = None
for line in out.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = int(m.group(1)), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if not m or client is None or client_name is None:
continue
port, pname = int(m.group(1)), m.group(2).strip()
if client_substr not in client_name and client_substr not in pname:
continue
if port_substr and port_substr not in pname and port_substr not in client_name:
continue
if VIRTUAL_NAME in pname:
continue
return f"{client}:{port}"
return None
def ensure_alsa_link() -> None:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe."""
src = None
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"):
src = _alsa_port(hint)
if src:
break
dst = _alsa_port("smc-smooth-in")
if not src or not dst:
return
subprocess.run(["aconnect", src, dst], capture_output=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--tau",
type=float,
default=0.055,
help="smoothing time constant in seconds (default 0.055)",
)
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
args = ap.parse_args()
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
midiout.open_virtual_port(VIRTUAL_NAME)
# current/target as floats 0..127, keyed by (channel, cc)
current: dict[tuple[int, int], float] = {}
target: dict[tuple[int, int], float] = {}
last_sent: dict[tuple[int, int], int] = {}
print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
print("Pass notes through; smooth CC. Ctrl+C to stop.", flush=True)
ensure_alsa_link()
dt = 1.0 / args.rate
alpha = 1.0 - math.exp(-dt / max(args.tau, 1e-4))
next_link_check = time.monotonic() + 2.0
try:
while True:
now = time.monotonic()
if now >= next_link_check:
ensure_alsa_link()
next_link_check = now + 2.0
# Drain inbound
while True:
msg = midiin.get_message()
if msg is None:
break
data, _ = msg
if not data:
continue
status = data[0]
cmd = status & 0xF0
ch = status & 0x0F
if cmd == 0xB0 and len(data) >= 3:
# Control Change → smooth
cc, val = data[1], data[2]
key = (ch, cc)
target[key] = float(val)
if key not in current:
current[key] = float(val)
last_sent[key] = -1
else:
# Notes, aftertouch, PC, etc. → immediate
midiout.send_message(data)
# Ease CC toward targets and emit when quantized value moves
for key, tgt in list(target.items()):
cur = current.get(key, tgt)
cur = cur + (tgt - cur) * alpha
# Snap when close so we actually reach the endpoint
if abs(tgt - cur) < 0.15:
cur = tgt
current[key] = cur
q = int(round(cur))
q = 0 if q < 0 else 127 if q > 127 else q
if last_sent.get(key) != q:
ch, cc = key
midiout.send_message([0xB0 | ch, cc, q])
last_sent[key] = q
time.sleep(dt)
except KeyboardInterrupt:
print("\nStopped.", flush=True)
finally:
midiin.close_port()
midiout.close_port()
del midiin
del midiout
if __name__ == "__main__":
main()