Files
lintunes/lintunes/airplay/sink.py
T
trav efbee5c465 v0.59.0: LinTunes' own AirPlay 1 sender for third-party speakers
pyatv's handshakes play nothing on a WiiM; Music Assistant's cliairplay
plays on it through libraop's RAOP client. airplay/raop.py reproduces that
client's behaviour on the wire: one RTSP session with auth-setup, an
AppleLossless ANNOUNCE and RECORD carrying RTP-Info, OPTIONS keepalives,
a 2 s buffer, NTP-locked timestamps, a start that sends the first two
seconds at once, the timing responder and resends. Non-Apple speakers
stream through it; pyatv only finds them. Verified against shairport-sync
(decoded tone, flush on pause/seek, volume, metadata). Round 88's pyatv
compat hooks are gone.
2026-10-16 23:12:38 -07:00

347 lines
13 KiB
Python

"""The Player sink that plays through an AirPlay speaker.
One `stream_file` per stretch of continuous playback: a song from its start,
or from wherever a resume or a seek put it. Each start bumps a *generation*;
a stream's outcome only counts if it is still the current one, so the stream
a seek just replaced can't report "finished" and advance the queue.
Threading follows cast/sink.py: every pyatv call runs on the AsyncLoop, every
outcome comes back through a private signal (queued onto the GUI thread), and
the position is computed on the GUI thread from the frame count the source
keeps in its PcmRequest.
"""
import asyncio
import logging
from contextlib import suppress
from PyQt6.QtCore import QBuffer, QIODevice, QTimer, Qt, pyqtSignal
from PyQt6.QtGui import QImage
from PyQt6.QtMultimedia import QAudio
from lintunes import tagging
from lintunes.airplay.stream import PcmRequest, install_shim
from lintunes.airplay.support import (
can_stream, heard_ms, level_to_percent, unstreamable_reason)
from lintunes.player import PlaybackSink
# Outcomes a stream reports when it ends.
FINISHED = "finished" # ffmpeg reached the end of the song
DECODE_ERROR = "decode_error" # this song can't be read; Player skips it
DROPPED = "dropped" # the speaker closed on us mid-song
FAILED = "failed" # couldn't reach the speaker at all
ART_MAX_PX = 600
# Each stream's life in the journal: started, first audio, how it ended.
log = logging.getLogger("lintunes.airplay") # receivers show a small square; a 3000 px scan is waste
def jpeg_artwork(data: bytes | None) -> bytes | None:
"""The cover as a JPEG of at most ART_MAX_PX: RAOP sends artwork as
image/jpeg whatever it really is. Best-effort, like every art path."""
if not data:
return None
image = QImage()
if not image.loadFromData(data):
return None
if data[:3] == b"\xff\xd8\xff" and max(image.width(),
image.height()) <= ART_MAX_PX:
return data
if max(image.width(), image.height()) > ART_MAX_PX:
image = image.scaled(ART_MAX_PX, ART_MAX_PX,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
buffer = QBuffer()
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, "JPEG", 90)
return bytes(buffer.data())
def outcome_of(request: PcmRequest, error: Exception | None) -> str:
"""Why a stream ended. A closed connection makes pyatv *return* rather
than raise, so "the song is over" is only ever ffmpeg's end of file."""
if request.decode_error:
return DECODE_ERROR
if error is not None:
return FAILED if request.frames_read == 0 else DROPPED
return FINISHED if request.exhausted else DROPPED
class AirPlaySink(PlaybackSink):
"""Streams decoded PCM to an AirPlay receiver."""
provides_pcm = False
glyph = "airplay"
listen_src = "airplay"
POLL_MS = 250
VOLUME_COALESCE_MS = 120
STOP_TIMEOUT_S = 3.0
_stream_ended = pyqtSignal(int, str, str) # generation, outcome, detail
def __init__(self, atv, loop, name: str, parent=None):
super().__init__(parent)
install_shim()
self._atv = atv
self._loop = loop
self.name = name or "AirPlay"
self._track = None
self._metadata: dict = {}
self._first_logged = False
self._request: PcmRequest | None = None
self._generation = 0
self._playing = False
self._position_ms = 0
self._duration_ms = 0
self._percent = 0.0
self._shutdown_done = False
self._dying = False
# Loop-thread state: the running stream task, and a lock so a new
# stream never starts before the last one has torn down (pyatv
# refuses a second stream while one holds the session).
self._task: asyncio.Task | None = None
self._lock: asyncio.Lock | None = None
self._stream_ended.connect(self._on_stream_ended)
self._poll = QTimer(self)
self._poll.setInterval(self.POLL_MS)
self._poll.timeout.connect(self._on_poll)
self._volume_timer = QTimer(self)
self._volume_timer.setSingleShot(True)
self._volume_timer.setInterval(self.VOLUME_COALESCE_MS)
self._volume_timer.timeout.connect(self._flush_volume)
# ---- PlaybackSink ----
def can_play(self, track) -> bool:
return can_stream(track.location, track.kind)
def unplayable_reason(self, track) -> str:
return unstreamable_reason(track.location, track.kind)
def load(self, track, autoplay: bool, start_ms: int):
self._track = track
self._metadata = {
"title": track.name or "",
"artist": track.artist or "",
"album": track.album or "",
"duration": (track.total_time or 0) / 1000.0,
"artwork": self._artwork(track),
}
self._duration_ms = track.total_time or 0
self.duration_changed.emit(self._duration_ms)
self._set_position(max(0, start_ms))
if autoplay:
self._start_stream(self._position_ms)
else:
self._halt_stream()
self._set_playing(False)
def _artwork(self, track):
try:
return jpeg_artwork(tagging.read_embedded_artwork(track.location))
except Exception: # noqa: BLE001 — art is never worth a failure
return None
def play(self):
if self._track is None or self._playing:
return
self._start_stream(self._position_ms)
def pause(self):
# AirPlay has no pause: stop the stream where the listener is, and
# resume() starts a new one from there.
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def stop(self):
self._freeze_position()
self._halt_stream()
self._set_playing(False)
def seek(self, position_ms: int):
target = max(0, position_ms)
if self._playing:
self._start_stream(target)
else:
self._set_position(target)
def position_ms(self) -> int:
return self._position_ms
def duration_ms(self) -> int:
return self._duration_ms
def is_playing(self) -> bool:
return self._playing
def set_volume(self, level: float):
level = max(0.0, min(1.0, float(level)))
# The same perceptual→linear curve LocalSink uses, then dB on the
# speaker: one slider position, one loudness, either output.
linear = QAudio.convertVolume(
level, QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
self._percent = level_to_percent(linear)
self._volume_timer.start()
def shutdown(self):
"""Stop the speaker and close the session. Waits a moment for the
teardown, so quitting doesn't leave the speaker playing what it had
buffered, and never longer: a vanished speaker can't hold up quit."""
if self._shutdown_done:
return
self._shutdown_done = True
self._poll.stop()
self._volume_timer.stop()
self._generation += 1
with suppress(Exception):
self._loop.run(self._close_all(), self.STOP_TIMEOUT_S)
# ---- streams (GUI side) ----
def _start_stream(self, start_ms: int):
if self._shutdown_done or self._dying or self._track is None:
return
self._generation += 1
request = PcmRequest(self._track.location, start_ms,
self._duration_ms)
self._request = request
self._first_logged = False
log.info("stream %d: %s from %d ms", self._generation,
self._track.name or self._track.location, start_ms)
self._set_position(start_ms)
self._set_playing(True)
self._poll.start()
self._loop.submit(self._restart(self._generation, request,
dict(self._metadata), self._percent))
def _halt_stream(self):
self._generation += 1
self._request = None
self._poll.stop()
if not self._shutdown_done:
self._loop.submit(self._halt())
def _freeze_position(self):
if self._request is not None:
self._set_position(self._heard(self._request))
def _heard(self, request: PcmRequest) -> int:
return heard_ms(request.start_ms, request.frames_read,
request.elapsed_ms(), request.sample_rate,
request.latency_ms)
def _on_poll(self):
request = self._request
if request is not None:
if request.first_read_at is not None and not self._first_logged:
self._first_logged = True
log.info("stream %d: first audio sent %.1f s after play "
"(%d Hz)", self._generation,
request.first_read_at - request.created_at,
request.sample_rate)
self._set_position(self._heard(request))
def _on_stream_ended(self, generation: int, outcome: str, detail: str):
log.info("stream %d ended: %s %s", generation, outcome, detail)
if generation != self._generation or self._shutdown_done:
return
self._request = None
self._poll.stop()
if outcome == FINISHED:
self._set_position(self._duration_ms or self._position_ms)
self._set_playing(False)
self.ended.emit()
elif outcome == DECODE_ERROR:
self._set_playing(False)
self.error.emit(f"it couldn't be decoded ({detail})")
elif outcome == DROPPED:
self._fail(f"{self.name} stopped playing — something else may "
"have taken it over.")
else:
self._fail(f"Lost {self.name} ({detail}).")
def _fail(self, reason: str):
"""Let Player fall back to the local output, still playing — the
cast sink's rule: what lintunes last asked for, not what the dying
session said."""
if self._dying:
return
self._dying = True
self._poll.stop()
self.unavailable.emit(reason)
def _flush_volume(self):
if not self._shutdown_done:
self._loop.submit(self._apply_volume(self._percent))
def _set_playing(self, playing: bool):
if playing != self._playing:
self._playing = playing
self.state_changed.emit(playing)
def _set_position(self, position_ms: int):
self._position_ms = position_ms
self.position_changed.emit(position_ms)
# ---- streams (loop thread) ----
def _loop_lock(self) -> asyncio.Lock:
if self._lock is None:
self._lock = asyncio.Lock()
return self._lock
async def _restart(self, generation, request, metadata, percent):
async with self._loop_lock():
await self._cancel_task()
if generation != self._generation:
return # superseded while the last one tore down
# Before the stream, so its first packet is already at this level:
# with no stream running pyatv only stores it for the next one.
await self._apply_volume(percent)
self._task = asyncio.ensure_future(
self._stream(generation, request, metadata))
async def _halt(self):
async with self._loop_lock():
await self._cancel_task()
async def _cancel_task(self):
task, self._task = self._task, None
if task is not None and not task.done():
task.cancel()
with suppress(asyncio.CancelledError, Exception):
await task
async def _stream(self, generation, request, metadata):
from pyatv.interface import MediaMetadata
error = None
try:
await self._atv.stream.stream_file(
request, metadata=MediaMetadata(**metadata))
except asyncio.CancelledError:
request.kill()
raise
except Exception as e: # noqa: BLE001 — reported, never raised
error = e
finally:
request.kill()
self._stream_ended.emit(generation, outcome_of(request, error),
request.decode_error or str(error or ""))
async def _apply_volume(self, percent: float):
with suppress(Exception): # a volume write is never fatal
await self._atv.audio.set_volume(percent)
async def _close_all(self):
await self._halt()
await asyncio.gather(*self._atv.close(), return_exceptions=True)