Files
lintunes/lintunes/airplay/stream.py
T
trav d77a9fe7f9 v0.58.0: the library search filters the sidebar's playlists
- Typing in the library search now also narrows the playlist list to names
  containing every word; folders stay when they or something inside match,
  open while filtering, and clearing puts back the folders you had open.
- AirPlay: an unreadable /info reply no longer fails the stream (pyatv died
  on shairport-sync's).
2026-10-16 10:27:51 -07:00

270 lines
9.7 KiB
Python

"""The audio that goes to the speaker: ffmpeg's PCM, as a pyatv AudioSource.
pyatv's `stream_file` takes a path (decoded whole into memory by miniaudio,
which can't read AAC or ALAC) or a pipe (whose duration it reports as 0 and
whose WAV header it skips by assuming 44 bytes). Neither fits, so
`install_shim` teaches pyatv's `open_source` one more input: a `PcmRequest`,
answered with an `FfmpegSource` built at the sample rate, channel count and
sample size the receiver actually negotiated. Every other input still goes to
pyatv's own code.
A `PcmRequest` is also how the GUI thread watches the stream: the source counts
frames into it, and the sink turns that count into a position.
`install_shim` also hooks pyatv's AirPlay 1 for the *compatibility* handshake
(`support.use_compat`), but only for hosts `set_compat` named: auth-setup
even though the receiver isn't an AirPort, no transient pairing (a WiiM drops
the connection when the ANNOUNCE after it arrives unencrypted), and ALAC
instead of L16 — uncompressed frames, what cliraop sends.
"""
import asyncio
import time
from lintunes.airplay.support import alac_verbatim, ffmpeg_command
class PcmRequest:
"""One song from one position, plus what happened to it.
Written from the loop thread, read from the GUI thread; every field is a
plain int/float/bool/str, so a read is never torn.
"""
def __init__(self, path: str, start_ms: int, duration_ms: int):
self.path = path
self.start_ms = max(0, int(start_ms))
self.duration_ms = max(0, int(duration_ms))
self.sample_rate = 44100
self.frames_read = 0
self.created_at = time.monotonic()
self.first_read_at: float | None = None # time.monotonic()
self.exhausted = False # ffmpeg reached the end of the song
self.decode_error = "" # ffmpeg failed before producing any audio
self._process = None
def elapsed_ms(self) -> float | None:
if self.first_read_at is None:
return None
return (time.monotonic() - self.first_read_at) * 1000.0
def kill(self):
process, self._process = self._process, None
if process is not None and process.returncode is None:
try:
process.kill()
except ProcessLookupError:
pass
_source_class = None
def _ffmpeg_source():
"""FfmpegSource subclasses pyatv's AudioSource, so it is defined on first
use rather than at import (see the package docstring)."""
global _source_class
if _source_class is not None:
return _source_class
from pyatv.interface import MediaMetadata
from pyatv.protocols.raop.audio_source import AudioSource
class FfmpegSource(AudioSource):
def __init__(self, request, process, sample_rate, channels,
sample_size):
self._request = request
self._process = process
self._rate = sample_rate
self._channels = channels
self._size = sample_size
self._frame = channels * sample_size
@classmethod
async def open(cls, request, sample_rate, channels, sample_size):
process = await asyncio.create_subprocess_exec(
*ffmpeg_command(request.path, request.start_ms, sample_rate,
channels, sample_size),
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
request._process = process
request.sample_rate = sample_rate
return cls(request, process, sample_rate, channels, sample_size)
async def readframes(self, nframes: int) -> bytes:
request = self._request
if request.exhausted or request.decode_error:
return self.NO_FRAMES
try:
data = await self._process.stdout.readexactly(
nframes * self._frame)
except asyncio.IncompleteReadError as e:
data = e.partial
await self._finish(bool(data))
# A trailing partial frame would shift every sample after it.
data = data[:len(data) - len(data) % self._frame]
if data:
if request.first_read_at is None:
request.first_read_at = time.monotonic()
request.frames_read += len(data) // self._frame
return data
async def _finish(self, got_data: bool):
"""End of ffmpeg's output: the song's end, or a failure if it
never produced a frame (missing file, unreadable codec)."""
code = await self._process.wait()
request = self._request
if code != 0 and request.frames_read == 0 and not got_data:
stderr = await self._process.stderr.read()
lines = stderr.decode(errors="replace").strip().splitlines()
request.decode_error = (lines[-1] if lines
else f"ffmpeg exited with {code}")
else:
request.exhausted = True
async def close(self) -> None:
self._request.kill()
async def get_metadata(self):
return MediaMetadata()
@property
def sample_rate(self) -> int:
return self._rate
@property
def channels(self) -> int:
return self._channels
@property
def sample_size(self) -> int:
return self._size
@property
def duration(self) -> int:
# What's left from the start position: the receiver's progress
# bar runs over this stream, not over the whole song.
remaining = self._request.duration_ms - self._request.start_ms
return max(0, round(remaining / 1000))
_source_class = FfmpegSource
return FfmpegSource
_compat_hosts: set[str] = set()
def set_compat(host: str, on: bool):
"""Stream to `host` with the compatibility handshake, or pyatv's own."""
if on:
_compat_hosts.add(host)
else:
_compat_hosts.discard(host)
def _is_compat(connection) -> bool:
return getattr(connection, "remote_ip", None) in _compat_hosts
class _NoPairing:
"""pair_verify's stand-in for a compat host: verifies nothing."""
def __init__(self, credentials, connection):
pass
async def verify_credentials(self) -> bool:
return False
_COMPAT_ANNOUNCE = (
"v=0\r\n"
"o=iTunes {session_id} 0 IN IP4 {local_ip}\r\n"
"s=iTunes\r\n"
"c=IN IP4 {remote_ip}\r\n"
"t=0 0\r\n"
"m=audio 0 RTP/AVP 96\r\n"
"a=rtpmap:96 AppleLossless\r\n"
"a=fmtp:96 {frames} 0 16 40 10 14 2 255 0 0 {sample_rate}\r\n"
)
def _alac_ok(context) -> bool:
return context.bytes_per_channel == 2 and context.channels == 2
def _install_compat():
from pyatv.protocols.raop import stream_client
from pyatv.protocols.raop.protocols import airplayv1
from pyatv.support import rtsp
real_pair = airplayv1.pair_verify
airplayv1.pair_verify = lambda credentials, connection: (
_NoPairing if _is_compat(connection) else real_pair)(
credentials, connection)
real_auth = stream_client.StreamClient._requires_auth_setup
stream_client.StreamClient._requires_auth_setup = property(
lambda self: _is_compat(self.rtsp.connection)
or real_auth.fget(self))
real_announce = rtsp.RtspSession.announce
async def announce(self, bytes_per_channel, channels, sample_rate,
password):
if (not _is_compat(self.connection) or password is not None
or bytes_per_channel != 2 or channels != 2):
return await real_announce(self, bytes_per_channel, channels,
sample_rate, password)
body = _COMPAT_ANNOUNCE.format(
session_id=self.session_id, local_ip=self.connection.local_ip,
remote_ip=self.connection.remote_ip,
frames=rtsp.FRAMES_PER_PACKET, sample_rate=sample_rate)
return await self.exchange("ANNOUNCE", content_type="application/sdp",
body=body)
rtsp.RtspSession.announce = announce
# GET /info is optional, and pyatv treats an unparseable answer as fatal:
# shairport-sync's classic build answers it with a body that isn't a
# plist, so every stream failed before it began.
real_info = rtsp.RtspSession.info
async def info(self):
try:
return await real_info(self)
except Exception: # noqa: BLE001 — /info is only a hint
return {}
rtsp.RtspSession.info = info
real_send = airplayv1.AirPlayV1.send_audio_packet
async def send_audio_packet(self, transport, rtp_header, audio):
if _is_compat(self.rtsp.connection) and _alac_ok(self.context):
audio = alac_verbatim(audio)
return await real_send(self, transport, rtp_header, audio)
airplayv1.AirPlayV1.send_audio_packet = send_audio_packet
def install_shim():
"""Route a PcmRequest through `stream_file` to an FfmpegSource.
Patches the name the RAOP module looked up at import, which is what
`RaopStream.stream_file` calls. Idempotent.
"""
import pyatv.protocols.raop as raop
if getattr(raop.open_source, "_lintunes", False):
return
original = raop.open_source
async def open_source(source, sample_rate, channels, sample_size):
if isinstance(source, PcmRequest):
return await _ffmpeg_source().open(
source, sample_rate, channels, sample_size)
return await original(source, sample_rate, channels, sample_size)
open_source._lintunes = True
raop.open_source = open_source
_install_compat()