Files
lintunes/lintunes/airplay/controller.py
T
trav c2a566bf57 v0.56.1: AirPlay diagnostics — log each stream, choose the protocol
tiat.place connects but stays silent; pyatv streams to it with its AirPlay 2
path, which the fake receiver never exercised. Log every stream's start,
first audio and outcome; config.json airplay_protocol (auto/1/2) forces a
version and airplay_debug turns on pyatv's own debug log.
2026-10-15 16:07:20 -07:00

188 lines
7.0 KiB
Python

"""Owns an AirPlay session on MainWindow's behalf (CastController's shape).
Widget-free: it reports state as signals and MainWindow decides what to show.
"Connected" is mostly a promise here — RAOP holds no connection between
streams, so a speaker that vanishes while paused is only noticed when the
next stream can't reach it, and Player falls back then.
"""
import logging
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes.airplay.discovery import AirPlayDiscovery
from lintunes.airplay.loop import AsyncLoop
from lintunes.airplay.support import is_available, protocol_choice
from lintunes.config import load_config
from lintunes.eventlog import log_control
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
CONNECT_TIMEOUT_S = 10.0
def raop_only(conf):
"""Connect over RAOP alone. The AirPlay service on a speaker is the video/
remote-control side; left enabled, pyatv may route volume through it
when no stream is running."""
from pyatv.const import Protocol
for service in conf.services:
if service.protocol != Protocol.RAOP:
service.enabled = False
return conf
class AirPlayController(QObject):
connecting = pyqtSignal(object) # AirPlayDevice
connected = pyqtSignal(str) # device name
disconnected = pyqtSignal(str) # reason; "" when the user asked
failed = pyqtSignal(str)
_connect_done = pyqtSignal(object, int) # {"atv"|"error"}, attempt
def __init__(self, player, parent=None):
super().__init__(parent)
self._player = player
self._loop = AsyncLoop()
self._sink = None
self._discovery: AirPlayDiscovery | None = None
self._attempt = 0
self._connect_done.connect(self._on_connect_result)
# This machine decodes every packet the speaker plays, so a suspend
# silences the room mid-song.
self._inhibitor = SleepInhibitor(
reason="Playing to an AirPlay speaker",
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
# ---- state ----
def is_available(self) -> tuple[bool, str]:
return is_available()
def is_connected(self) -> bool:
return self._sink is not None
def device_name(self) -> str:
return self._sink.name if self._sink is not None else ""
def discovery(self) -> AirPlayDiscovery:
if self._discovery is None:
self._discovery = AirPlayDiscovery(self._loop, self)
return self._discovery
# ---- connecting ----
def connect_to(self, device):
if self._sink is not None:
self.disconnect()
self._attempt += 1
attempt = self._attempt
self.connecting.emit(device)
log_control("airplay", "connect", f"{device.name} at {device.host}")
conf = self.discovery().config_for(device.uuid)
future = self._loop.submit(self._connect(conf, device))
def done(f):
try:
result = {"atv": f.result(), "name": device.name}
except Exception as e: # noqa: BLE001 — report, never crash
result = {"error": str(e) or type(e).__name__}
self._connect_done.emit(result, attempt)
future.add_done_callback(done)
async def _connect(self, conf, device):
import asyncio
import pyatv
from pyatv.const import Protocol
loop = asyncio.get_running_loop()
if conf is None:
# Not seen by this session's scans (or seen long ago): ask the
# address directly.
found = await pyatv.scan(loop, hosts=[device.host], timeout=5)
conf = next((c for c in found
if str(c.identifier) == device.uuid), None)
if conf is None:
raise ConnectionError(f"{device.name} didn't answer")
from pyatv.protocols.airplay.utils import get_protocol_version
from pyatv.settings import AirPlayVersion
from pyatv.storage.memory_storage import MemoryStorage
config = load_config()
choice = protocol_choice(config.get("airplay_protocol"))
if config.get("airplay_debug"):
# Every RTSP request and a line per second of audio, into the
# journal: what "connected but silent" needs to be diagnosed.
logging.getLogger("pyatv").setLevel(logging.DEBUG)
storage = MemoryStorage()
settings = await storage.get_settings(conf)
settings.protocols.raop.protocol_version = {
"1": AirPlayVersion.V1, "2": AirPlayVersion.V2,
}.get(choice, AirPlayVersion.Auto)
raop = conf.get_service(Protocol.RAOP)
if raop is not None:
used = get_protocol_version(
raop, settings.protocols.raop.protocol_version)
log_control("airplay", "protocol",
f"{device.name}: {used.name} (airplay_protocol={choice})")
return await asyncio.wait_for(
pyatv.connect(raop_only(conf), loop, storage=storage),
CONNECT_TIMEOUT_S)
def _on_connect_result(self, result: dict, attempt: int):
if attempt != self._attempt:
atv = result.get("atv")
if atv is not None:
self._loop.submit(self._close(atv))
return
if "error" in result:
self.failed.emit(f"Couldn't connect: {result['error']}")
return
from lintunes.airplay.sink import AirPlaySink
self._sink = AirPlaySink(result["atv"], self._loop, result["name"],
self)
# Deferred a turn, as in CastController: Player's own fallback slot
# disconnects this signal mid-emission.
self._sink.unavailable.connect(
lambda reason: QTimer.singleShot(
0, lambda: self._on_unavailable(reason)))
self._player.set_sink(self._sink)
self._inhibitor.inhibit()
self.connected.emit(self._sink.name)
@staticmethod
async def _close(atv):
import asyncio
await asyncio.gather(*atv.close(), return_exceptions=True)
# ---- disconnecting ----
def disconnect(self, reason: str = ""):
sink, self._sink = self._sink, None
if sink is None:
return
log_control("airplay", "disconnect",
f"{sink.name} reason={reason or 'user'}")
self._player.set_sink(None)
self._teardown(sink, reason)
def _on_unavailable(self, reason: str):
sink, self._sink = self._sink, None
if sink is None:
return
log_control("airplay", "lost", reason)
self._teardown(sink, reason)
def _teardown(self, sink, reason: str):
sink.shutdown()
self._inhibitor.release()
self.disconnected.emit(reason)
def shutdown(self):
"""Quitting: stop first so the swap back can't burst out of the
laptop's speakers (CastController.shutdown's rule)."""
if self._discovery is not None:
self._discovery.stop()
if self._sink is not None:
self._player.stop()
self.disconnect()
self._inhibitor.release()