216 lines
6.4 KiB
Python
216 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
||
"""Keep each mover's pan and tilt correction when the knobs turn.
|
||
|
||
Knob 9 (CC 38) and knob 10 (CC 39) are relative encoders, but QLC reads
|
||
the CC as an absolute position. Every slider bound to that CC jumps to
|
||
the same value, so the per-head offsets collapse.
|
||
|
||
This sits between the SMC-PAD and QLC+. It forwards every message, and
|
||
on CC 38/39 it also adds the encoder step to each head and sends that
|
||
head's own position on CC 50–53 (pan) and 54–57 (tilt).
|
||
|
||
pipenv run python scripts/mover_offsets_midi.py
|
||
|
||
Reload shows/twisted.qxw after it is running. Stopping this script puts
|
||
the pad straight back onto QLC+.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import xml.etree.ElementTree as ET
|
||
from pathlib import Path
|
||
|
||
import mido
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
SHOW = ROOT / "shows" / "twisted.qxw"
|
||
|
||
PAN_KNOB = 38
|
||
TILT_KNOB = 39
|
||
# FL, FR, BL, BR. These are the slider input channels in the show.
|
||
PAN_CC = (50, 51, 52, 53)
|
||
TILT_CC = (54, 55, 56, 57)
|
||
HEADS = PAN_CC + TILT_CC
|
||
|
||
NS = {"w": "http://www.qlcplus.org/Workspace"}
|
||
CLIENT_RE = re.compile(r"^client (\d+): '([^']*)'")
|
||
PORT_RE = re.compile(r"^\s+(\d+) '([^']*)'")
|
||
|
||
|
||
def midi_to_dmx(midi: int) -> int:
|
||
"""QLC+ MIDI2DMX: (value * 255) / 127."""
|
||
return (max(0, min(127, midi)) * 255) // 127
|
||
|
||
|
||
_DMX_TO_MIDI = [
|
||
min(range(128), key=lambda midi, dmx=dmx: (abs(midi_to_dmx(midi) - dmx), midi))
|
||
for dmx in range(256)
|
||
]
|
||
|
||
|
||
def dmx_to_midi(dmx: int) -> int:
|
||
return _DMX_TO_MIDI[max(0, min(255, dmx))]
|
||
|
||
|
||
def encoder_delta(value: int) -> int:
|
||
"""1..63 clockwise, 65..127 counter-clockwise."""
|
||
if value <= 0 or value == 64 or value > 127:
|
||
return 0
|
||
if value < 64:
|
||
return value
|
||
return value - 128
|
||
|
||
|
||
def load_positions(path: Path = SHOW) -> dict[int, int]:
|
||
"""DMX value of each offset slider, keyed by its MIDI channel."""
|
||
positions = {cc: 0 for cc in HEADS}
|
||
root = ET.parse(path).getroot()
|
||
for slider in root.findall(".//w:Slider", NS):
|
||
source = slider.find("w:Input", NS)
|
||
level = slider.find("w:Level", NS)
|
||
if source is None or level is None:
|
||
continue
|
||
channel = source.get("Channel")
|
||
if channel is None or int(channel) not in positions:
|
||
continue
|
||
value = level.get("Value")
|
||
if value is not None:
|
||
positions[int(channel)] = int(value)
|
||
return positions
|
||
|
||
|
||
def alsa_ports() -> list[tuple[int, int, str, str]]:
|
||
text = subprocess.check_output(["aconnect", "-l"], text=True)
|
||
client = 0
|
||
client_name = ""
|
||
found: list[tuple[int, int, str, str]] = []
|
||
for line in text.splitlines():
|
||
match = CLIENT_RE.match(line)
|
||
if match:
|
||
client = int(match.group(1))
|
||
client_name = match.group(2)
|
||
continue
|
||
match = PORT_RE.match(line)
|
||
if match:
|
||
found.append((client, int(match.group(1)), client_name, match.group(2).strip()))
|
||
return found
|
||
|
||
|
||
def find_port(ports: list[tuple[int, int, str, str]], name: str) -> tuple[int, int]:
|
||
for client, port, client_name, port_name in ports:
|
||
if name in client_name or name in port_name:
|
||
return client, port
|
||
raise SystemExit(f"ALSA port {name!r} not found")
|
||
|
||
|
||
def connect(src: tuple[int, int], dst: tuple[int, int]) -> None:
|
||
subprocess.check_call(["aconnect", f"{src[0]}:{src[1]}", f"{dst[0]}:{dst[1]}"])
|
||
|
||
|
||
def disconnect(src: tuple[int, int], dst: tuple[int, int]) -> None:
|
||
subprocess.call(["aconnect", "-d", f"{src[0]}:{src[1]}", f"{dst[0]}:{dst[1]}"])
|
||
|
||
|
||
def main() -> None:
|
||
positions = load_positions()
|
||
print(
|
||
"pan "
|
||
+ " ".join(str(positions[cc]) for cc in PAN_CC)
|
||
+ " tilt "
|
||
+ " ".join(str(positions[cc]) for cc in TILT_CC),
|
||
flush=True,
|
||
)
|
||
|
||
pad = find_port(alsa_ports(), "SMC-PAD Bluetooth")
|
||
qlc = find_port(alsa_ports(), "qlcplus")
|
||
|
||
pad_in = mido.open_input("mover-offset-in", virtual=True)
|
||
qlc_out = mido.open_output("mover-offset-out", virtual=True)
|
||
feedback = mido.open_input("mover-offset-fb", virtual=True)
|
||
time.sleep(0.2)
|
||
ports = alsa_ports()
|
||
bridge_in = find_port(ports, "mover-offset-in")
|
||
bridge_out = find_port(ports, "mover-offset-out")
|
||
bridge_fb = find_port(ports, "mover-offset-fb")
|
||
|
||
lock = threading.Lock()
|
||
ignore_until: dict[int, float] = {}
|
||
|
||
def on_feedback(msg: mido.Message) -> None:
|
||
if msg.type != "control_change" or msg.control not in positions:
|
||
return
|
||
if time.monotonic() < ignore_until.get(msg.control, 0):
|
||
return
|
||
with lock:
|
||
positions[msg.control] = midi_to_dmx(msg.value)
|
||
|
||
feedback.callback = on_feedback
|
||
|
||
def fan(ccs: tuple[int, ...], channel: int, delta: int) -> None:
|
||
if delta == 0:
|
||
return
|
||
with lock:
|
||
for cc in ccs:
|
||
nxt = max(0, min(255, positions[cc] + delta))
|
||
midi = dmx_to_midi(nxt)
|
||
positions[cc] = midi_to_dmx(midi)
|
||
ignore_until[cc] = time.monotonic() + 0.05
|
||
qlc_out.send(
|
||
mido.Message(
|
||
"control_change", channel=channel, control=cc, value=midi
|
||
)
|
||
)
|
||
|
||
wired = False
|
||
|
||
def restore(*_args: object) -> None:
|
||
nonlocal wired
|
||
if not wired:
|
||
return
|
||
wired = False
|
||
feedback.callback = None
|
||
disconnect(pad, bridge_in)
|
||
disconnect(bridge_out, qlc)
|
||
disconnect(qlc, bridge_fb)
|
||
connect(pad, qlc)
|
||
print("pad connected straight to QLC+", flush=True)
|
||
|
||
def stop(*_args: object) -> None:
|
||
restore()
|
||
sys.exit(0)
|
||
|
||
signal.signal(signal.SIGINT, stop)
|
||
signal.signal(signal.SIGTERM, stop)
|
||
|
||
disconnect(pad, qlc)
|
||
connect(pad, bridge_in)
|
||
connect(bridge_out, qlc)
|
||
connect(qlc, bridge_fb)
|
||
wired = True
|
||
print(
|
||
f"SMC-PAD {pad[0]}:{pad[1]} → offsets → QLC+ {qlc[0]}:{qlc[1]}",
|
||
flush=True,
|
||
)
|
||
|
||
try:
|
||
for msg in pad_in:
|
||
qlc_out.send(msg)
|
||
if msg.type != "control_change":
|
||
continue
|
||
if msg.control == PAN_KNOB:
|
||
fan(PAN_CC, msg.channel, encoder_delta(msg.value))
|
||
elif msg.control == TILT_KNOB:
|
||
fan(TILT_CC, msg.channel, encoder_delta(msg.value))
|
||
finally:
|
||
restore()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|