Files
lintunes/lintunes/airplay/support.py
T
trav bdeacd9793 v0.57.0: repeat button; AirPlay compatibility handshake for third-party speakers
- Transport: a repeat button (off / all / one) between shuffle and the
  visualizer. Repeat-all wraps the walk (a shuffled one is reshuffled per
  lap); repeat-one replays a song that finishes, Next/Previous still move.
  BPM button and the now-playing minimum shrink to make room.
- Clicking the streaming tile to stop casting/AirPlay no longer also opens
  the big visualizer (the release after the stop counted as a click).
- AirPlay: pyatv's AirPlay 2 session is silent on a WiiM, and its AirPlay 1
  pairs then talks plaintext, which the WiiM hangs up on. Non-Apple
  speakers now get cliraop's handshake: auth-setup, no pairing, ALAC
  (uncompressed frames). airplay_protocol "2" keeps pyatv's AirPlay 2.
2026-10-15 18:01:20 -07:00

186 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Pure helpers for AirPlay: availability, formats, volume, position.
Free of pyatv and the network, so the fiddly arithmetic is unit-tested
offline (the cast/support.py pattern).
"""
import math
import shutil
from pathlib import Path
# pyatv's own buffering: RAOP receivers are told to play each packet
# ``22050 + sample_rate`` frames after it is sent (stream_client's
# StreamContext.latency), so what is heard trails what was sent by ~1.5 s.
def latency_ms(sample_rate: int) -> float:
return (22050 + sample_rate) / sample_rate * 1000.0
# ffmpeg decodes everything the desktop plays; only FairPlay is out of reach.
_REFUSED_KINDS = {"Protected AAC audio file": "copy-protected AAC"}
_REFUSED_SUFFIXES = {".m4p": "copy-protected AAC"}
# AirPlay's volume is dB: 0 is full, -30 is pyatv's floor (its 0–100 % maps
# linearly onto -30..0 dB), -144 is mute.
DBFS_FLOOR = -30.0
def is_available() -> tuple[bool, str]:
"""(True, "") when pyatv is importable and ffmpeg is on PATH.
find_spec, not an import: the menu asks on every open, and pyatv pulls in
aiohttp, cryptography and protobuf.
"""
import importlib.util
try:
if importlib.util.find_spec("pyatv") is None:
return False, "pyatv isn't installed"
except (ImportError, ValueError):
return False, "pyatv isn't installed"
if shutil.which("ffmpeg") is None:
return False, "ffmpeg isn't installed (AirPlay decodes with it)"
return True, ""
def can_stream(location: str, kind: str = "") -> bool:
if not location:
return False
if kind in _REFUSED_KINDS:
return False
return Path(location).suffix.lower() not in _REFUSED_SUFFIXES
def unstreamable_reason(location: str, kind: str = "") -> str:
if not location:
return "it has no file"
if kind in _REFUSED_KINDS:
return f"AirPlay can't play {_REFUSED_KINDS[kind]}"
suffix = Path(location).suffix.lower()
return f"AirPlay can't play {_REFUSED_SUFFIXES.get(suffix, 'this file')}"
def classify(has_raop: bool, pairing: str, requires_password: bool
) -> tuple[bool, str]:
"""Can lintunes stream to this device? (yes, "") or (no, why not).
`pairing` is the name of pyatv's PairingRequirement for the RAOP service.
Only receivers that take a stream from anyone are offered: pairing (a PIN
on a TV) and passwords aren't built yet. A device with AirPlay but no RAOP
is a video/screen-mirroring target with no audio-only endpoint.
"""
if not has_raop:
return False, "video only"
if requires_password:
return False, "needs a password"
if pairing == "Mandatory":
return False, "needs pairing"
if pairing in ("Unsupported", "Disabled"):
return False, "doesn't accept LinTunes"
return True, ""
def level_to_percent(linear: float) -> float:
"""pyatv's volume percent for a *linear* amplitude 0..1.
Player hands sinks a perceptual slider level; the sink converts that to
linear the way LocalSink does (Qt's log→linear curve), and this turns the
linear gain into the same dB on the speaker, so the slider means one
loudness whichever output is playing. Anything under pyatv's -30 dB floor
is 0 % (silent) — the bottom of Qt's curve is that quiet locally too.
"""
if linear <= 0:
return 0.0
db = 20.0 * math.log10(min(1.0, linear))
return max(0.0, min(100.0, (db - DBFS_FLOOR) / -DBFS_FLOOR * 100.0))
def heard_ms(start_ms: int, frames_read: int, elapsed_ms: float | None,
sample_rate: int) -> int:
"""Where the listener is in the song.
`elapsed_ms` runs from the first frame handed to pyatv (None before
that). pyatv paces packets to real time, so elapsed minus the receiver's
latency is what has come out of the speaker — never more than what was
actually read, which is what holds the position at the end while pyatv
sends its trailing silence.
"""
if elapsed_ms is None or sample_rate <= 0:
return start_ms
read_ms = frames_read / sample_rate * 1000.0
played = max(0.0, min(read_ms, elapsed_ms - latency_ms(sample_rate)))
return start_ms + int(played)
def protocol_choice(value) -> str:
"""config.json's `airplay_protocol`: "auto", "1" or "2". Machine-local on
purpose — it's about which speakers this machine meets — and anything
unrecognized is auto."""
value = str(value or "auto").strip().lower().lstrip("v")
return value if value in ("1", "2") else "auto"
# RAOP `am` (model) prefixes of Apple's own receivers. A HomePod takes only
# AirPlay 2, so Apple hardware keeps pyatv's own choice.
_APPLE_MODELS = ("AudioAccessory", "AppleTV", "AirPort", "Mac", "iMac")
def use_compat(choice: str, model: str) -> bool:
"""Stream with the AirPlay 1 compatibility handshake (stream.py)?
pyatv picks AirPlay 2 for any receiver advertising its features, and a
WiiM (Linkplay) takes that whole session — RECORD, volume, timing — and
plays nothing; its own AirPlay 1 refuses pyatv's transient pairing. What
third-party speakers accept is the handshake cliraop/owntones send:
auth-setup, no pairing, ALAC. So "auto" means that for everything that
isn't Apple's, "1" means it everywhere, and "2" is pyatv's AirPlay 2.
"""
if choice == "1":
return True
if choice == "2":
return False
return not (model or "").startswith(_APPLE_MODELS)
_ALAC_HEAD = None
def alac_verbatim(pcm: bytes) -> bytes:
"""16-bit stereo big-endian PCM as one uncompressed ALAC frame.
ALAC's escape: a channel-pair element flagged "not compressed" carries
the samples as-is, so there's nothing to encode — a 23-bit header
(0x20 0x00 0x02 less its last bit), the samples, the 3-bit end tag, zero
padding. Byte-identical to ffmpeg's encoder on incompressible input.
"""
import numpy as np
global _ALAC_HEAD
if _ALAC_HEAD is None:
_ALAC_HEAD = np.unpackbits(np.frombuffer(b"\x20\x00\x02", np.uint8))[:23]
bits = np.unpackbits(np.frombuffer(pcm, np.uint8))
return np.packbits(np.concatenate(
[_ALAC_HEAD, bits, np.ones(3, np.uint8)])).tobytes()
_SAMPLE_FORMATS = {2: "s16be", 4: "s32be"}
def ffmpeg_command(path: str, start_ms: int, sample_rate: int, channels: int,
sample_size: int) -> list[str]:
"""Decode `path` from `start_ms` to raw PCM on stdout, in the shape the
receiver asked for.
*Big*-endian: pyatv's own sources byteswap little-endian samples before
sending (audio_source._to_audio_samples), so asking ffmpeg for BE is the
same bytes on the wire. `-ss` before `-i` is an input seek, which is
sample-accurate for audio and instant even deep into a long file.
"""
fmt = _SAMPLE_FORMATS.get(sample_size)
if fmt is None:
raise ValueError(f"unsupported sample size {sample_size}")
command = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error"]
if start_ms > 0:
command += ["-ss", f"{start_ms / 1000.0:.3f}"]
command += ["-i", path, "-map", "0:a:0", "-vn",
"-f", fmt, "-ac", str(channels), "-ar", str(sample_rate),
"pipe:1"]
return command