macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
262 lines
9.3 KiB
Python
262 lines
9.3 KiB
Python
"""cliairplay: Music Assistant's AirPlay sender, run as a helper process.
|
|
|
|
pyatv's own stream is accepted by a WiiM (Linkplay) speaker — every request
|
|
answered 200, timing exchanged, volume set — and nothing comes out, in AirPlay
|
|
1 and 2 alike (Round 88). cliairplay, the same speaker, plays. So it streams
|
|
for LinTunes wherever it runs, and pyatv stays for discovery (and as the
|
|
fallback where the helper can't be had).
|
|
|
|
The binary is never committed or pip-installed: it is downloaded once, from
|
|
the release pinned here, and checked against the release's SHA-256 before it
|
|
is ever run (the yt-dlp/fpcalc "runtime tool" rule, minus the package
|
|
manager, since no distribution ships it). GPL-3.0, and run as a separate
|
|
process — LinTunes only talks to it: audio as raw PCM on stdin, commands on a
|
|
named pipe, `[STATUS]` lines back on stderr.
|
|
|
|
Everything here is pure or plain file/network I/O, no Qt.
|
|
"""
|
|
|
|
import contextlib
|
|
import hashlib
|
|
import os
|
|
import platform
|
|
import re
|
|
import secrets
|
|
import tempfile
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
from lintunes import paths
|
|
|
|
VERSION = "0.5.4"
|
|
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
|
|
f"v{VERSION}/")
|
|
# From the release's SHA256SUMS. Linux keys are the bare machine; the Mac
|
|
# builds (same release, same tag) are keyed by their asset suffix.
|
|
_SHA256 = {
|
|
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
|
|
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
|
|
"macos-arm64": "5b99e3bf76d20cb31a2f6946e0c9d8bc12e0845d7d66a0ec22a49b5ebbac14b4",
|
|
"macos-x86_64": "09fd5925787db0cea530d380656b06fa6da89f0da11ef86e1cba1139b3c828fd",
|
|
}
|
|
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
|
|
_MAC_ARCH_ALIASES = {"aarch64": "arm64", "amd64": "x86_64"}
|
|
|
|
DOWNLOAD_TIMEOUT_S = 60
|
|
|
|
|
|
class CliUnavailable(RuntimeError):
|
|
"""The helper can't be had here (platform, network, checksum)."""
|
|
|
|
|
|
def _arch() -> str | None:
|
|
"""The ``_SHA256`` key for this computer, or None."""
|
|
machine = platform.machine().lower()
|
|
if paths.IS_MAC:
|
|
# Under Rosetta this reads x86_64, and the x86_64 build runs there.
|
|
key = "macos-" + _MAC_ARCH_ALIASES.get(machine, machine)
|
|
return key if key in _SHA256 else None
|
|
if platform.system() != "Linux":
|
|
return None
|
|
machine = _ARCH_ALIASES.get(machine, machine)
|
|
return machine if machine in _SHA256 else None
|
|
|
|
|
|
def _asset(arch: str) -> str:
|
|
"""The release asset's file name for an ``_arch`` key."""
|
|
if arch.startswith("macos-"):
|
|
return f"cliairplay-{arch}"
|
|
return f"cliairplay-linux-{arch}"
|
|
|
|
|
|
def binary_dir() -> Path:
|
|
"""Machine-local: a binary for this CPU, never the synced data dir."""
|
|
return paths.data_dir() / "bin"
|
|
|
|
|
|
def binary_path() -> Path | None:
|
|
arch = _arch()
|
|
if arch is None:
|
|
return None
|
|
return binary_dir() / f"cliairplay-{VERSION}-{arch}"
|
|
|
|
|
|
def supported() -> bool:
|
|
return _arch() is not None
|
|
|
|
|
|
def installed() -> Path | None:
|
|
"""The verified binary, if it's already on disk."""
|
|
path = binary_path()
|
|
if path is not None and path.is_file() and os.access(path, os.X_OK):
|
|
return path
|
|
return None
|
|
|
|
|
|
def _sha256(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def download_verified(url: str, sha256: str, path: Path, fetch=None,
|
|
what: str = "the helper", error=CliUnavailable,
|
|
unpack=None) -> Path:
|
|
"""Download ``url`` to ``path`` (mode 755), refusing it unless its
|
|
SHA-256 is ``sha256``. Nothing lands at ``path`` unless it matched.
|
|
``unpack(data) -> bytes`` (after the check) picks the binary out of an
|
|
archive. Raises ``error``. Shared by every pinned runtime download
|
|
(cliairplay here, ``uv`` in ``dj/venv_tool.py``)."""
|
|
fetch = fetch or _fetch
|
|
try:
|
|
data = fetch(url)
|
|
except Exception as e: # noqa: BLE001 — reported, not raised raw
|
|
raise error(f"couldn't download {what} ({e})")
|
|
if _sha256(data) != sha256:
|
|
raise error(f"the downloaded {what} failed its checksum")
|
|
if unpack is not None:
|
|
data = unpack(data)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + "-")
|
|
try:
|
|
with os.fdopen(fd, "wb") as out:
|
|
out.write(data)
|
|
os.chmod(tmp, 0o755)
|
|
os.replace(tmp, path)
|
|
except BaseException:
|
|
with contextlib.suppress(OSError):
|
|
os.unlink(tmp)
|
|
raise
|
|
return path
|
|
|
|
|
|
def ensure_binary(fetch=None) -> Path:
|
|
"""The helper's path, downloading and verifying it first if needed.
|
|
|
|
Blocking (a few MB): callers run it off the GUI thread. `fetch(url)`
|
|
returns the bytes; it's injectable so tests never touch the network.
|
|
"""
|
|
path = installed()
|
|
if path is not None:
|
|
return path
|
|
arch = _arch()
|
|
if arch is None:
|
|
raise CliUnavailable(
|
|
f"no AirPlay helper for {platform.system()} {platform.machine()}")
|
|
return download_verified(_RELEASE + _asset(arch), _SHA256[arch],
|
|
binary_path(), fetch, "AirPlay helper")
|
|
|
|
|
|
def _fetch(url: str) -> bytes:
|
|
with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_S,
|
|
context=https_context()) as response:
|
|
return response.read()
|
|
|
|
|
|
def https_context():
|
|
"""None (urllib's default) on Linux. On a Mac, certifi's roots: the
|
|
Python inside a built LinTunes.app was compiled with an OpenSSL whose
|
|
certificate folder doesn't exist on the user's Mac, so the default
|
|
context trusts nothing and every HTTPS download fails."""
|
|
if not paths.IS_MAC:
|
|
return None
|
|
import ssl
|
|
try:
|
|
import certifi
|
|
return ssl.create_default_context(cafile=certifi.where())
|
|
except Exception: # noqa: BLE001 — fall back to the system's default
|
|
return ssl.create_default_context()
|
|
|
|
|
|
# ---- the command line ----
|
|
|
|
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
|
|
_RAOP_FLAGS = ("et", "md", "am", "pk", "pw", "cn")
|
|
|
|
|
|
def txt_blob(properties: dict) -> str:
|
|
"""The `_airplay._tcp` TXT as cliairplay's --txt: space-separated
|
|
key=value, skipping pairs with whitespace (the binary splits on spaces)."""
|
|
pairs = []
|
|
for key, value in (properties or {}).items():
|
|
if value is None:
|
|
continue
|
|
key, value = str(key), str(value)
|
|
if any(c.isspace() for c in key + value):
|
|
continue
|
|
pairs.append(f"{key}={value}")
|
|
return " ".join(pairs)
|
|
|
|
|
|
def protocol_arg(choice: str) -> str:
|
|
"""config.json's `airplay_protocol` → cliairplay's --protocol. "auto"
|
|
lets the binary pick from the TXT, as Music Assistant does."""
|
|
return {"1": "airplay2-compat", "2": "airplay2"}.get(choice, "auto")
|
|
|
|
|
|
def build_args(binary: str, host: str, port: int, raop: dict, airplay: dict,
|
|
pipe: str, volume: float, choice: str = "auto",
|
|
name: str = "") -> list[str]:
|
|
"""argv for one stream. `raop`/`airplay` are the TXT properties of the
|
|
device's _raop._tcp and _airplay._tcp services ({} when absent)."""
|
|
args = [binary, "--protocol", protocol_arg(choice),
|
|
"--dacp", secrets.token_hex(8).upper(),
|
|
"--activeremote", str(secrets.randbelow(2**32)),
|
|
"--cmdpipe", pipe,
|
|
"--samplerate", "44100", "--bitdepth", "16",
|
|
"--port", str(port),
|
|
"--volume", str(round(max(0.0, min(100.0, volume)))),
|
|
"--debug", "1"]
|
|
for key in _RAOP_FLAGS:
|
|
value = (raop or {}).get(key)
|
|
if value:
|
|
args += [f"--{key}", str(value)]
|
|
# Some receivers (the WiiM) advertise their AirPlay 2 feature bits only on
|
|
# _raop's `ft`; route selection reads them from --txt either way.
|
|
txt = dict(airplay or {})
|
|
if not (txt.get("features") or txt.get("ft")) and (raop or {}).get("ft"):
|
|
txt["ft"] = raop["ft"]
|
|
blob = txt_blob(txt)
|
|
if blob:
|
|
args += ["--txt", blob]
|
|
if name and airplay:
|
|
args += ["--name", name]
|
|
return args + [host]
|
|
|
|
|
|
# ---- what it says ----
|
|
|
|
_STATUS = re.compile(r"^\[STATUS\]\s+(\w+)\s*(.*)$")
|
|
_FIELD = re.compile(r'(\w+)=("([^"]*)"|\S+)')
|
|
|
|
|
|
def parse_status(line: str) -> tuple[str, dict] | None:
|
|
"""`[STATUS] playing elapsed_ms=1203` → ("playing", {"elapsed_ms": "1203"}).
|
|
Anything that isn't a status line is None."""
|
|
match = _STATUS.match(line.strip())
|
|
if match is None:
|
|
return None
|
|
fields = {}
|
|
for key, raw, quoted in _FIELD.findall(match.group(2)):
|
|
fields[key] = quoted if raw.startswith('"') else raw
|
|
return match.group(1), fields
|
|
|
|
|
|
def metadata_command(title: str, artist: str, album: str, duration_s: int,
|
|
artwork_file: str | None = None) -> str:
|
|
"""Now-playing for the receiver. Newlines would end a field early."""
|
|
def clean(value):
|
|
return " ".join(str(value or "").split())
|
|
lines = [f"TITLE={clean(title)}", f"ARTIST={clean(artist)}",
|
|
f"ALBUM={clean(album)}", f"DURATION={max(0, int(duration_s))}"]
|
|
if artwork_file:
|
|
lines.append(f"ARTWORKFILE={artwork_file}")
|
|
lines.append("ACTION=SENDMETA")
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def start_command(at_unix_ms: int) -> str:
|
|
return f"START_UNIX_MS={int(at_unix_ms)}\nACTION=START\n"
|
|
|
|
|
|
def volume_command(percent: float) -> str:
|
|
return f"VOLUME={round(max(0.0, min(100.0, percent)))}\n"
|