Files
lintunes/lintunes/airplay/stream.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

190 lines
7.0 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.
The compatibility sender (`raop.py`, Round 90) reads its PCM through the
same FfmpegSource; it replaced Round 88's hooks into pyatv's AirPlay 1.
"""
import asyncio
import time
from lintunes.airplay.support import 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
# From the first frame read to its being heard; None = pyatv's.
self.latency_ms: float | None = None
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
def _install_info_fix():
from pyatv.support import rtsp
# 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
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_info_fix()