161 lines
6.2 KiB
Python
161 lines
6.2 KiB
Python
"""Play a show's animations without QLC+.
|
|
|
|
Dry-run returns DMX samples. Pass an IP to send Art-Net. A Python script
|
|
exposes this by defining build() -> Show and calling script_main(build).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import importlib.util
|
|
import json
|
|
import socket
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from patternstudio.artnet import ARTNET_PORT, build_artdmx
|
|
|
|
from .model import Show
|
|
from .spec import SpecError, from_spec
|
|
|
|
|
|
def active_keys(show: Show, keys: list[str] | None = None) -> list[str]:
|
|
if keys is not None:
|
|
return list(keys)
|
|
if show.playback:
|
|
return list(show.playback)
|
|
return [fn.key for fn in show.functions if getattr(fn, "primary", False)]
|
|
|
|
|
|
def frame_at(show: Show, elapsed_ms: float, keys: list[str] | None = None) -> dict[str, dict[int, int]]:
|
|
"""Fixture key → channel → value at `elapsed_ms` for the functions being played."""
|
|
into: dict[int, dict[int, int]] = {}
|
|
for key in active_keys(show, keys):
|
|
show.functions_by_key[key].apply(show, elapsed_ms, into)
|
|
names = {fx.id: fx.key for fx in show.fixtures}
|
|
return {names[fid]: dict(channels) for fid, channels in into.items() if fid in names}
|
|
|
|
|
|
def dmx_frames(show: Show, values: dict[str, dict[int, int]]) -> dict[int, bytearray]:
|
|
"""QLC+ universe → 512-channel frame."""
|
|
frames: dict[int, bytearray] = {}
|
|
for key, channels in values.items():
|
|
fixture = show.fixtures_by_key[key]
|
|
frame = frames.setdefault(fixture.universe, bytearray(512))
|
|
for channel, value in channels.items():
|
|
slot = fixture.address + int(channel)
|
|
if 0 <= slot < 512:
|
|
frame[slot] = max(0, min(255, int(value)))
|
|
return frames
|
|
|
|
|
|
def sample_playback(show: Show, *, seconds: float | None = None, hz: float = 40.0) -> dict[str, Any]:
|
|
keys = active_keys(show)
|
|
if seconds is None:
|
|
duration = max((show.functions_by_key[key].duration_ms(show) for key in keys), default=0)
|
|
times = [0] if duration <= 0 else [int(duration * i / 4) for i in range(4)]
|
|
if duration > 0:
|
|
times.append(max(0, duration - 1))
|
|
else:
|
|
count = max(1, int(float(seconds) * hz))
|
|
times = [int(i * (1000.0 / hz)) for i in range(min(count, 500))]
|
|
duration = int(float(seconds) * 1000)
|
|
return {
|
|
"ok": True,
|
|
"functions": keys,
|
|
"duration_ms": duration,
|
|
"samples": [{"time_ms": t, "values": frame_at(show, t, keys)} for t in times],
|
|
}
|
|
|
|
|
|
def play(
|
|
show: Show,
|
|
*,
|
|
seconds: float | None = None,
|
|
ip: str | None = None,
|
|
universe: int = 0,
|
|
hz: float = 40.0,
|
|
) -> dict[str, Any]:
|
|
"""Sample the running functions, or stream them as Art-Net when `ip` is set."""
|
|
if not ip:
|
|
return sample_playback(show, seconds=seconds, hz=hz)
|
|
return _send(show, ip=ip, universe=universe, seconds=seconds, hz=hz)
|
|
|
|
|
|
def load_show(path: Path | str) -> Show:
|
|
"""Load a show from a build() script or a JSON spec."""
|
|
source = Path(path).resolve()
|
|
if source.suffix == ".json":
|
|
return from_spec(json.loads(source.read_text(encoding="utf-8")))
|
|
spec = importlib.util.spec_from_file_location(f"showfile_script_{source.stem}", source)
|
|
if spec is None or spec.loader is None:
|
|
raise SpecError([{"path": str(source), "message": "could not load the script"}])
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
if not hasattr(module, "build"):
|
|
raise SpecError([{"path": str(source), "message": "script must define build() -> Show"}])
|
|
show = module.build()
|
|
if not isinstance(show, Show):
|
|
raise SpecError([{"path": str(source), "message": "build() must return a Show"}])
|
|
return show
|
|
|
|
|
|
def script_main(build: Any, argv: list[str] | None = None) -> None:
|
|
"""Entry point for `python animation.py`. Prints one JSON object."""
|
|
args = _parser().parse_args(argv)
|
|
_emit(play(build(), seconds=args.seconds, ip=args.ip, universe=args.universe, hz=args.hz))
|
|
|
|
|
|
def _parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(description="Play this animation and print DMX samples, or send Art-Net.")
|
|
parser.add_argument("--ip", help="Art-Net destination. Omit to print samples and exit.")
|
|
parser.add_argument("--seconds", type=float, help="How long to play. Omit with --ip to run until Ctrl+C.")
|
|
parser.add_argument("--hz", type=float, default=40.0)
|
|
parser.add_argument("--universe", type=int, default=0, help="Art-Net universe for QLC+ universe 0.")
|
|
return parser
|
|
|
|
|
|
def _emit(payload: dict[str, Any]) -> None:
|
|
json.dump(payload, sys.stdout, indent=2)
|
|
sys.stdout.write("\n")
|
|
|
|
|
|
def _send(show: Show, *, ip: str, universe: int, seconds: float | None, hz: float) -> dict[str, Any]:
|
|
keys = active_keys(show)
|
|
period = 1.0 / hz if hz > 0 else 0.025
|
|
print(
|
|
f"Art-Net {ip} universe {universe} {', '.join(keys) or '(no functions)'} (Ctrl+C to stop)",
|
|
file=sys.stderr,
|
|
)
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
sequence = 1
|
|
sent = 0
|
|
stopped = False
|
|
started = time.monotonic()
|
|
try:
|
|
while True:
|
|
elapsed_ms = (time.monotonic() - started) * 1000.0
|
|
if seconds is not None and elapsed_ms >= seconds * 1000.0:
|
|
break
|
|
frames = dmx_frames(show, frame_at(show, elapsed_ms, keys))
|
|
if not frames:
|
|
frames = {0: bytearray(512)}
|
|
for qlc_universe, frame in frames.items():
|
|
packet = build_artdmx(bytes(frame), universe + qlc_universe, sequence)
|
|
sock.sendto(packet, (ip, ARTNET_PORT))
|
|
sequence = 1 if sequence >= 255 else sequence + 1
|
|
sent += 1
|
|
time.sleep(period)
|
|
except KeyboardInterrupt:
|
|
stopped = True
|
|
finally:
|
|
for qlc_universe in dmx_frames(show, frame_at(show, 0, keys)) or {0: bytearray()}:
|
|
for _ in range(3):
|
|
sock.sendto(build_artdmx(bytes(512), universe + qlc_universe, sequence), (ip, ARTNET_PORT))
|
|
sequence = 1 if sequence >= 255 else sequence + 1
|
|
sock.close()
|
|
return {"ok": True, "ip": ip, "universe": universe, "functions": keys, "frames": sent, "stopped": stopped}
|