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.
This commit is contained in:
2026-10-15 18:01:20 -07:00
parent c2a566bf57
commit bdeacd9793
11 changed files with 545 additions and 31 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.56.1"
__version__ = "0.57.0"
+12 -5
View File
@@ -12,7 +12,7 @@ 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.airplay.support import is_available, protocol_choice, use_compat
from lintunes.config import load_config
from lintunes.eventlog import log_control
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
@@ -114,15 +114,22 @@ class AirPlayController(QObject):
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)
model = raop.properties.get("am", "") if raop is not None else ""
compat = use_compat(choice, model)
from lintunes.airplay.stream import install_shim, set_compat
install_shim()
set_compat(str(conf.address), compat)
settings.protocols.raop.protocol_version = (
AirPlayVersion.V1 if compat
else {"2": AirPlayVersion.V2}.get(choice, AirPlayVersion.Auto))
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})")
f"{device.name} ({model}): {used.name}"
f"{' compat' if compat else ''} "
f"(airplay_protocol={choice})")
return await asyncio.wait_for(
pyatv.connect(raop_only(conf), loop, storage=storage),
CONNECT_TIMEOUT_S)
+91 -1
View File
@@ -10,12 +10,18 @@ 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 ffmpeg_command
from lintunes.airplay.support import alac_verbatim, ffmpeg_command
class PcmRequest:
@@ -145,6 +151,89 @@ def _ffmpeg_source():
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
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.
@@ -164,3 +253,4 @@ def install_shim():
open_source._lintunes = True
raop.open_source = open_source
_install_compat()
+45 -3
View File
@@ -111,13 +111,55 @@ def heard_ms(start_ms: int, frames_read: int, elapsed_ms: float | None,
def protocol_choice(value) -> str:
"""config.json's `airplay_protocol`: "auto" (pyatv picks from the
device's features), "1" or "2". Machine-local on purpose — it's about
which speakers this machine meets — and anything unrecognized is auto."""
"""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"}
+39 -1
View File
@@ -2,7 +2,8 @@
so buttons can flash the theme highlight while pressed."""
from PyQt6.QtCore import Qt, QPointF, QRectF
from PyQt6.QtGui import QIcon, QPixmap, QPainter, QPen, QColor, QPolygonF
from PyQt6.QtGui import (QIcon, QPixmap, QPainter, QPainterPath, QPen, QColor,
QPolygonF)
_cache: dict[tuple, QIcon] = {}
@@ -74,6 +75,41 @@ def _shuffle(p, color):
p.drawPolygon(QPolygonF([QPointF(15, 11), QPointF(19, 14), QPointF(15, 17)]))
def _repeat(p, color):
"""iTunes' repeat: a loop of two strands with rounded far corners, the
top one arrowed to the right, the bottom one back to the left."""
pen = QPen(color, 1.8)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
top = QPainterPath(QPointF(3, 11.5))
top.lineTo(3, 9)
top.quadTo(3, 6, 6, 6)
top.lineTo(14, 6)
bottom = QPainterPath(QPointF(17, 8.5))
bottom.lineTo(17, 11)
bottom.quadTo(17, 14, 14, 14)
bottom.lineTo(6, 14)
p.drawPath(top)
p.drawPath(bottom)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(color)
p.drawPolygon(QPolygonF([QPointF(13.5, 2.8), QPointF(18, 6), QPointF(13.5, 9.2)]))
p.drawPolygon(QPolygonF([QPointF(6.5, 10.8), QPointF(2, 14), QPointF(6.5, 17.2)]))
def _repeat_one(p, color):
"""Repeat with a "1" inside the loop."""
_repeat(p, color)
pen = QPen(color, 1.9)
pen.setCapStyle(Qt.PenCapStyle.FlatCap)
pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawPolyline(QPolygonF([QPointF(8.6, 8.9), QPointF(10.6, 7.4),
QPointF(10.6, 12.6)]))
def _cast(p, color):
"""The standard cast glyph: a screen with signal arcs at its lower left.
The screen is lit rather than empty — it is only ever drawn while a device
@@ -127,6 +163,8 @@ _DRAWERS = {
"next": _next,
"previous": _previous,
"shuffle": _shuffle,
"repeat": _repeat,
"repeat_one": _repeat_one,
"cast": _cast,
"airplay": _airplay,
}
+36 -4
View File
@@ -11,6 +11,7 @@ from lintunes.tap_tempo import TapTempo
from lintunes.gui.icons import transport_icon
from lintunes.gui.track_table import format_time
from lintunes.gui.visualizer import VisualizerWidget
from lintunes.player import REPEAT_MODES
from lintunes import theme
@@ -24,7 +25,7 @@ ROW_GAP = 4
# each pair and after the last, always. The now-playing panel (and the seek
# row under it) takes all the width that's left.
GAP = 16
NOW_PLAYING_MIN = 180
NOW_PLAYING_MIN = 150
# Shared height for the boxed side controls (transport, shuffle, bpm) and the
# visualizer, so they line up. ~midway between their old heights: the stretchy
@@ -210,7 +211,7 @@ class BpmButton(QPushButton):
self._manager = manager
self._tempo = TapTempo()
self._target_track_id: int | None = None
self.setFixedWidth(74) # + the box's 3 px margins = its old footprint
self.setFixedWidth(52) # shuffle and repeat's width: "bpm" or 3 digits
self.setFlat(True) # flat text inside its box, like the transport icons
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setEnabled(False)
@@ -415,6 +416,19 @@ class TransportBar(QWidget):
layout.addWidget(shuffle_box, alignment=TOP)
gap()
# Repeat cycles off → all → one, like iTunes': lit while on, with a
# "1" in the loop for one.
self._repeat_btn = FlashButton("repeat")
self._repeat_btn.setMinimumWidth(50)
self._repeat_btn.setCheckable(True)
self._repeat_btn.clicked.connect(self._cycle_repeat)
repeat_box = _box(self._repeat_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(repeat_box)
layout.addWidget(repeat_box, alignment=TOP)
self._show_repeat(player.repeat_mode())
gap()
self._visualizer = VisualizerWidget(player, prefs)
self._visualizer.setFixedHeight(CONTROL_HEIGHT)
layout.addWidget(self._visualizer, alignment=TOP)
@@ -517,7 +531,8 @@ class TransportBar(QWidget):
hug=True, height=CONTROL_HEIGHT, split=True)
self._boxes.append(bpm_box)
layout.addWidget(bpm_box, alignment=TOP)
self._fixed_controls = (transport_box, shuffle_box, self._visualizer,
self._fixed_controls = (transport_box, shuffle_box, repeat_box,
self._visualizer,
self._volume_slider, bpm_box)
# Library button · the current view's header · seek row. MainWindow
@@ -550,6 +565,23 @@ class TransportBar(QWidget):
lambda: (cast.disconnect(),
airplay is not None and airplay.disconnect()))
# ---- repeat ----
_REPEAT_TIPS = {"off": "Repeat: off", "all": "Repeat: all",
"one": "Repeat: this song"}
def _cycle_repeat(self):
modes = REPEAT_MODES
mode = modes[(modes.index(self._player.repeat_mode()) + 1) % len(modes)]
self._player.set_repeat(mode)
self._show_repeat(mode)
def _show_repeat(self, mode: str):
# The click already toggled the check; the mode decides it.
self._repeat_btn.setChecked(mode != "off")
self._repeat_btn.set_kind("repeat_one" if mode == "one" else "repeat")
self._repeat_btn.setToolTip(self._REPEAT_TIPS[mode])
# ---- the header row ----
def set_sidebar_header(self, widget: QWidget):
@@ -634,7 +666,7 @@ class TransportBar(QWidget):
color), the tunable grayscale button boxes, and the now-playing panel
background + text color."""
for button in (self._prev_btn, self._play_btn, self._next_btn,
self._shuffle_btn):
self._shuffle_btn, self._repeat_btn):
button.refresh_icons()
box_bg = theme.gray(theme.gray_value(self._prefs, "color_button"))
for box in self._boxes:
+9 -1
View File
@@ -92,6 +92,7 @@ class VisualizerWidget(QWidget):
# True while audio is coming out of something other than this machine
# (a Chromecast), so there is no decoded PCM to draw.
self._no_pcm = False
self._swallow_release = False
self._device = ""
self._glyph = "cast"
@@ -357,12 +358,19 @@ class VisualizerWidget(QWidget):
def mousePressEvent(self, event):
if self._no_pcm:
# While casting the panel is the cast indicator, not a picture:
# a click stops casting instead.
# a click stops casting instead. Stopping swaps the sink back
# before the release arrives, so that release belongs to this
# press and must not open the big window.
self._swallow_release = True
self.cast_stop_requested.emit()
return
self._swallow_release = False
event.accept() # acted on at release, like a button
def mouseReleaseEvent(self, event):
if self._swallow_release:
self._swallow_release = False
return
if self._no_pcm or event.button() != Qt.MouseButton.LeftButton:
return
if not self.rect().contains(event.position().toPoint()):
+47 -7
View File
@@ -16,6 +16,10 @@ from lintunes.storage import listen_history
# Hitting "previous" more than this far into a song restarts it instead
RESTART_THRESHOLD_MS = 3000
# Repeat modes, in the order the transport button cycles them (iTunes').
REPEAT_OFF, REPEAT_ALL, REPEAT_ONE = "off", "all", "one"
REPEAT_MODES = (REPEAT_OFF, REPEAT_ALL, REPEAT_ONE)
# Resuming after a pause at least this long does a seek-in-place first: when
# the machine sits idle, the OS suspends the audio sink and it can come back
# silently dead — decoding continues (the visualizer moves) but nothing is
@@ -471,6 +475,7 @@ class Player(QObject):
self._current_track: Track | None = None
self._shuffle = False
self._shuffle_order: list[int] = []
self._repeat = REPEAT_OFF
# Custom stop time (ms) for the loaded track: end it early. Enforced
# here rather than in a sink so both playback paths honor it.
self._stop_at_ms = 0
@@ -635,13 +640,29 @@ class Player(QObject):
else:
self._shuffle_order = []
# ---- repeat ----
def repeat_mode(self) -> str:
return self._repeat
def set_repeat(self, mode: str):
"""REPEAT_OFF, REPEAT_ALL (the queue wraps around) or REPEAT_ONE (a
song that *finishes* plays again; Next and Previous still move)."""
self._repeat = mode if mode in REPEAT_MODES else REPEAT_OFF
log_control("player", "repeat", self._repeat)
def _step_index(self, delta: int) -> int | None:
"""Queue index `delta` steps away in the active walking order."""
"""Queue index `delta` steps away in the active walking order. Off
either end is None, unless repeating all: then the walk wraps — and a
shuffled one is reshuffled for its next lap, like iTunes."""
if not self._queue:
return None
wrap = self._repeat == REPEAT_ALL
if not self._shuffle:
candidate = self._index + delta
return candidate if 0 <= candidate < len(self._queue) else None
if 0 <= candidate < len(self._queue):
return candidate
return candidate % len(self._queue) if wrap else None
try:
pos = self._shuffle_order.index(self._index)
except ValueError:
@@ -649,7 +670,15 @@ class Player(QObject):
pos += delta
if 0 <= pos < len(self._shuffle_order):
return self._shuffle_order[pos]
return None
if not wrap:
return None
if pos < 0:
return self._shuffle_order[-1]
# A new lap, never starting with the song that just ended it.
others = [i for i in range(len(self._queue)) if i != self._index]
first = random.choice(others) if others else self._index
self._shuffle_order = make_shuffle_order(len(self._queue), first)
return first
# ---- state ----
@@ -844,6 +873,7 @@ class Player(QObject):
sink can't decode (a Chromecast can't play ALAC, AIFF or protected
AAC). The skip is a loop, not recursion: shuffling into a run of
unsupported tracks must not walk the stack down."""
skipped = 0
while 0 <= self._index < len(self._queue):
key = self._queue[self._index]
track = self._resolve(key)
@@ -871,7 +901,10 @@ class Player(QObject):
self.track_unplayable.emit(
track, self._sink.unplayable_reason(track))
next_index = self._step_index(1)
if next_index is None:
skipped += 1
# Repeat-all wraps, so a queue of nothing playable would
# go round forever.
if next_index is None or skipped >= len(self._queue):
self.stop()
return
self._index = next_index
@@ -913,8 +946,15 @@ class Player(QObject):
def _on_sink_ended(self):
"""The active sink played the track to its natural end."""
self._note_finished(self._current_track)
# Playback has already stopped at the end, so force autoplay.
self._advance(autoplay=True)
self._after_finish()
def _after_finish(self):
"""A song ended by itself: the same one again, or the next. Playback
has already stopped at the end, so autoplay either way."""
if self._repeat == REPEAT_ONE and self._current_track is not None:
self._load_current(autoplay=True)
else:
self._advance(autoplay=True)
def _on_sink_error(self, message: str):
track_name = self._current_track.name if self._current_track else "?"
@@ -936,7 +976,7 @@ class Player(QObject):
self._stop_at_ms = 0 # one-shot: don't re-fire while advancing
track = self._current_track
self._note_finished(track)
self._advance(autoplay=True)
self._after_finish()
def _note_finished(self, track):
"""Record a completed play once, guarding against a double count if