From bdeacd979316c5cdfa88329007628ecf5454e4e7 Mon Sep 17 00:00:00 2001 From: trav Date: Thu, 15 Oct 2026 18:01:20 -0700 Subject: [PATCH] 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. --- CLAUDE.md | 26 +++- lintunes/__init__.py | 2 +- lintunes/airplay/controller.py | 17 ++- lintunes/airplay/stream.py | 92 ++++++++++++- lintunes/airplay/support.py | 48 ++++++- lintunes/gui/icons.py | 40 +++++- lintunes/gui/transport.py | 40 +++++- lintunes/gui/visualizer.py | 10 +- lintunes/player.py | 54 +++++++- tests/test_round69.py | 8 +- tests/test_round88.py | 239 +++++++++++++++++++++++++++++++++ 11 files changed, 545 insertions(+), 31 deletions(-) create mode 100644 tests/test_round88.py diff --git a/CLAUDE.md b/CLAUDE.md index ef4f8f4..50c9df5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,6 +169,12 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal implementation. `set_sink()` carries the current track, position and playing-state across a swap and deliberately does *not* re-emit `track_changed` (that would double-scrobble the same song). + **Repeat** (Round 88, the transport's button, off → all → one) lives in + `Player`: repeat-all wraps `_step_index` both ways (a shuffled walk is + reshuffled for each lap, never starting with the song that ended the last), + repeat-one replays only a song that *finished* (`_after_finish`) — Next and + Previous still move — and `_load_current`'s unplayable-skip loop gives up + after one lap, since a wrapping walk would otherwise never end. Player is also deliberately **context-agnostic**: playback *context* ("library" / "playlist:") is tracked in `MainWindow`, not the player. @@ -839,11 +845,21 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal tile shows the sink's `glyph`. Testing streams against **pyatv's own fake receiver** (`tests/fake_device/raop.py` in its sdist, bound to 127.0.0.1) — never a real speaker unless trav says so. - pyatv picks AirPlay **2** for any receiver advertising its features (the - WiiM does) and the fake only exercises v1, so `config.json` takes - `airplay_protocol` ("auto"/"1"/"2") and `airplay_debug` (pyatv's logger - at DEBUG); every stream's start, first audio and outcome are logged at - INFO under `lintunes.airplay`, and the chosen protocol in the control log. + **pyatv's own handshakes play nothing on a WiiM** (Round 88): its AirPlay 2 + session (picked for any receiver advertising AirPlay 2 features) gets 200 + OK for everything, timing included, and stays silent; its AirPlay 1 runs a + transient pairing and then sends the ANNOUNCE unencrypted, and the WiiM + hangs up. Third-party speakers take what cliraop/owntones send, so + `stream.install_shim` also hooks pyatv for hosts marked by `set_compat`: + auth-setup whatever the model, no pairing, and ALAC — `AppleLossless` in + the SDP, each packet an uncompressed ALAC frame (`support.alac_verbatim`, + byte-identical to ffmpeg's encoder on incompressible input). The handshake + was verified silently (all-zero audio) against tiat.place. `use_compat`: + config.json's `airplay_protocol` "auto" = compat for everything but + Apple's own hardware (a HomePod is AirPlay 2 only), "1" = compat + everywhere, "2" = pyatv's AirPlay 2. `airplay_debug` puts pyatv's logger at + DEBUG; every stream's start, first audio and outcome are logged at INFO + under `lintunes.airplay`, and the chosen protocol in the control log. ## Conventions & gotchas diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 8c137bf..1ba3550 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.56.1" +__version__ = "0.57.0" diff --git a/lintunes/airplay/controller.py b/lintunes/airplay/controller.py index 0587fdb..fefc2df 100644 --- a/lintunes/airplay/controller.py +++ b/lintunes/airplay/controller.py @@ -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) diff --git a/lintunes/airplay/stream.py b/lintunes/airplay/stream.py index ad5d554..a3d1456 100644 --- a/lintunes/airplay/stream.py +++ b/lintunes/airplay/stream.py @@ -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() diff --git a/lintunes/airplay/support.py b/lintunes/airplay/support.py index f776f0b..72aa64c 100644 --- a/lintunes/airplay/support.py +++ b/lintunes/airplay/support.py @@ -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"} diff --git a/lintunes/gui/icons.py b/lintunes/gui/icons.py index 86fda6b..fc4154f 100644 --- a/lintunes/gui/icons.py +++ b/lintunes/gui/icons.py @@ -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, } diff --git a/lintunes/gui/transport.py b/lintunes/gui/transport.py index d126264..926face 100644 --- a/lintunes/gui/transport.py +++ b/lintunes/gui/transport.py @@ -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: diff --git a/lintunes/gui/visualizer.py b/lintunes/gui/visualizer.py index 09e192d..2160189 100644 --- a/lintunes/gui/visualizer.py +++ b/lintunes/gui/visualizer.py @@ -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()): diff --git a/lintunes/player.py b/lintunes/player.py index aefe42b..a36bb17 100644 --- a/lintunes/player.py +++ b/lintunes/player.py @@ -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 diff --git a/tests/test_round69.py b/tests/test_round69.py index 96bf641..7614bbd 100644 --- a/tests/test_round69.py +++ b/tests/test_round69.py @@ -120,7 +120,9 @@ def test_panel_fills_what_the_gaps_leave(qapp, tmp_path): window.resize(1280, 500) qapp.processEvents() assert wide - bar._now_playing.width() == 640 - window.resize(800, 500) + # Just above the narrowest the row of boxes can be (it grows with each + # control: 784 px before the repeat button, 858 after). + window.resize(bar.minimumSizeHint().width() + 16, 500) qapp.processEvents() assert bar._now_playing.width() >= NOW_PLAYING_MIN bpm = bar._bpm_button.parentWidget() @@ -163,13 +165,13 @@ def test_row_is_knolled_with_equal_gaps_and_ends(qapp, tmp_path): window.resize(width, 500) qapp.processEvents() row = [bar._prev_btn.parentWidget(), bar._shuffle_btn.parentWidget(), - bar._visualizer, bar._volume_slider, bar._now_playing, + bar._repeat_btn.parentWidget(), bar._visualizer, bar._volume_slider, bar._now_playing, bar._bpm_button.parentWidget()] edges = [(w.geometry().left(), w.geometry().right()) for w in row] gaps = [b[0] - a[1] - 1 for a, b in zip(edges, edges[1:])] # The same GAP everywhere, ends included, at every width. left_end, right_end = edges[0][0], bar.width() - 1 - edges[-1][1] - assert gaps + [left_end, right_end] == [GAP] * 7 + assert gaps + [left_end, right_end] == [GAP] * 8 def test_gap_between_playlists_and_songs_matches_left_inset(qapp, tmp_path): diff --git a/tests/test_round88.py b/tests/test_round88.py new file mode 100644 index 0000000..fa960b3 --- /dev/null +++ b/tests/test_round88.py @@ -0,0 +1,239 @@ +"""Round 88: a repeat button, the streaming tile's click, and AirPlay's +compatibility handshake for third-party speakers (a WiiM played nothing).""" + +import asyncio +import os +import random +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from PyQt6.QtCore import QPointF, Qt +from PyQt6.QtGui import QMouseEvent + +from lintunes.airplay import stream +from lintunes.airplay.support import alac_verbatim, use_compat +from lintunes.player import REPEAT_ALL, REPEAT_OFF, REPEAT_ONE +from tests.test_round29 import _FakeSink, _local_track, _player + + +# ---- repeat ---- + +def _queue(qapp, tmp_path, n=3, sink=None): + tracks = [_local_track(tmp_path, i) for i in range(1, n + 1)] + player = _player(qapp, tracks) + sink = sink or _FakeSink() + player.set_sink(sink) + player.play_queue([t.track_id for t in tracks], 0) + return player, sink + + +class TestRepeat: + def test_off_stops_at_the_end(self, qapp, tmp_path): + player, sink = _queue(qapp, tmp_path) + player._index = 2 + assert player._step_index(1) is None + assert player._step_index(-3) is None + + def test_all_wraps_both_ways(self, qapp, tmp_path): + player, sink = _queue(qapp, tmp_path) + player.set_repeat(REPEAT_ALL) + player._index = 2 + assert player._step_index(1) == 0 + player._index = 0 + assert player._step_index(-1) == 2 + + def test_all_reshuffles_a_new_lap_without_repeating_the_last_song( + self, qapp, tmp_path): + player, sink = _queue(qapp, tmp_path, n=5) + player.set_shuffle(True) + player.set_repeat(REPEAT_ALL) + for _ in range(20): + player._index = player._shuffle_order[-1] + first = player._step_index(1) + assert first is not None and first != player._index + assert player._shuffle_order[0] == first + assert sorted(player._shuffle_order) == list(range(5)) + + def test_a_finished_song_plays_again_on_repeat_one(self, qapp, tmp_path): + player, sink = _queue(qapp, tmp_path) + player.set_repeat(REPEAT_ONE) + sink.ended.emit() + assert sink.loads[-1] == (1, True, 0) + assert player.current_track.track_id == 1 + player._manager.record_play.assert_called_once_with(1) + + def test_next_still_moves_on_repeat_one(self, qapp, tmp_path): + player, sink = _queue(qapp, tmp_path) + player.set_repeat(REPEAT_ONE) + player.next() + assert player.current_track.track_id == 2 + + def test_nothing_playable_doesnt_loop_forever_on_repeat_all( + self, qapp, tmp_path): + tracks = [_local_track(tmp_path, i) for i in range(1, 4)] + player = _player(qapp, tracks) + player.set_repeat(REPEAT_ALL) + player.set_sink(_FakeSink(playable=False)) + player.play_queue([1, 2, 3], 0) + assert player.current_track is None + + def test_unknown_mode_is_off(self, qapp, tmp_path): + player, _ = _queue(qapp, tmp_path) + player.set_repeat("sideways") + assert player.repeat_mode() == REPEAT_OFF + + +class TestRepeatButton: + def test_cycles_off_all_one(self, qapp, tmp_path): + from lintunes.gui.transport import TransportBar + from lintunes.preferences import Preferences + player, _ = _queue(qapp, tmp_path) + bar = TransportBar(player, MagicMock(), Preferences(tmp_path / "p")) + button = bar._repeat_btn + assert not button.isChecked() and button._kind == "repeat" + seen = [] + for _ in range(3): + button.click() + seen.append((player.repeat_mode(), button.isChecked(), + button._kind)) + assert seen == [(REPEAT_ALL, True, "repeat"), + (REPEAT_ONE, True, "repeat_one"), + (REPEAT_OFF, False, "repeat")] + + +# ---- the streaming tile ---- + +class TestStreamingTileClick: + def test_stopping_a_stream_doesnt_open_the_big_window(self, qapp): + from lintunes.gui.visualizer import VisualizerWidget + player = MagicMock() + widget = VisualizerWidget(player, MagicMock(get=lambda k, d=None: d)) + widget.resize(140, 60) + widget._no_pcm = True + opened = [] + widget.open_big = lambda: opened.append(1) + + def stop(): # the swap back happens before the release + widget._no_pcm = False + widget.cast_stop_requested.connect(stop) + + at = QPointF(70, 30) + for kind in (QMouseEvent.Type.MouseButtonPress, + QMouseEvent.Type.MouseButtonRelease): + widget.event(QMouseEvent(kind, at, at, Qt.MouseButton.LeftButton, + Qt.MouseButton.LeftButton, + Qt.KeyboardModifier.NoModifier)) + assert opened == [] + # …and the next click is an ordinary one again. + for kind in (QMouseEvent.Type.MouseButtonPress, + QMouseEvent.Type.MouseButtonRelease): + widget.event(QMouseEvent(kind, at, at, Qt.MouseButton.LeftButton, + Qt.MouseButton.LeftButton, + Qt.KeyboardModifier.NoModifier)) + assert opened == [1] + + +# ---- AirPlay compatibility ---- + +class TestUseCompat: + def test_auto_is_compat_except_for_apple(self): + assert use_compat("auto", "WiiM Mini Receiver") + assert use_compat("auto", "") + assert not use_compat("auto", "AudioAccessory5,1") # HomePod mini + assert not use_compat("auto", "AppleTV6,2") + + def test_explicit_choices_win(self): + assert use_compat("1", "AudioAccessory5,1") + assert not use_compat("2", "WiiM Mini Receiver") + + +class TestAlacVerbatim: + def test_frame_layout(self): + pcm = bytes(range(256)) * 5 + bytes(128) # 352 stereo frames + frame = alac_verbatim(pcm) + assert len(frame) == 1412 # 23 + 11264 + 3 bits, padded + assert frame[:2] == b"\x20\x00" + bits = int.from_bytes(frame, "big") + total = len(frame) * 8 + # the samples sit right after the 23-bit header… + body = (bits >> (total - 23 - len(pcm) * 8)) & ((1 << len(pcm) * 8) - 1) + assert body.to_bytes(len(pcm), "big") == pcm + # …then the end tag 0b111, then zero padding. + tail = bits & ((1 << (total - 23 - len(pcm) * 8)) - 1) + assert tail == 0b111 << 6 + + def test_header_bits(self): + frame = alac_verbatim(bytes(1408)) + # channel pair, tag 0, no size, no shift, not compressed + assert frame[2] >> 1 == 0b0000001 + + +class _Conn: + def __init__(self, ip): + self.remote_ip = ip + self.local_ip = "10.0.0.2" + + +@pytest.fixture +def shim(): + stream.install_shim() + yield + stream._compat_hosts.clear() + + +class TestCompatHooks: + def test_announce_says_apple_lossless_only_for_compat_hosts(self, shim): + from pyatv.support import rtsp + sent = [] + + async def exchange(self, method, **kw): + sent.append(kw["body"]) + return SimpleNamespace(code=200, headers={}) + + session = rtsp.RtspSession(_Conn("10.0.0.9")) + session.exchange = exchange.__get__(session) + stream.set_compat("10.0.0.9", True) + asyncio.run(session.announce(2, 2, 44100, None)) + stream.set_compat("10.0.0.9", False) + asyncio.run(session.announce(2, 2, 44100, None)) + assert "a=rtpmap:96 AppleLossless" in sent[0] + assert "a=fmtp:96 352 0 16 40 10 14 2 255 0 0 44100" in sent[0] + assert "L16/44100/2" in sent[1] + + def test_no_pairing_and_auth_setup_for_compat_hosts(self, shim): + from pyatv.protocols.raop import stream_client + from pyatv.protocols.raop.protocols import airplayv1 + from pyatv.protocols.raop.parsers import EncryptionType + stream.set_compat("10.0.0.9", True) + assert isinstance(airplayv1.pair_verify(None, _Conn("10.0.0.9")), + stream._NoPairing) + client = SimpleNamespace(rtsp=SimpleNamespace( + connection=_Conn("10.0.0.9")), _properties={"am": "WiiM"}, + _encryption_types=EncryptionType.Unencrypted) + assert stream_client.StreamClient._requires_auth_setup.fget(client) + client.rtsp.connection = _Conn("10.0.0.10") + assert not stream_client.StreamClient._requires_auth_setup.fget(client) + + def test_audio_is_wrapped_as_alac_for_compat_hosts(self, shim): + from pyatv.protocols.raop.protocols import airplayv1 + sent = [] + proto = SimpleNamespace( + rtsp=SimpleNamespace(connection=_Conn("10.0.0.9")), + context=SimpleNamespace(bytes_per_channel=2, channels=2, rtpseq=7)) + transport = SimpleNamespace(sendto=sent.append) + pcm = os.urandom(1408) + stream.set_compat("10.0.0.9", True) + asyncio.run(airplayv1.AirPlayV1.send_audio_packet( + proto, transport, b"H" * 12, pcm)) + stream.set_compat("10.0.0.9", False) + asyncio.run(airplayv1.AirPlayV1.send_audio_packet( + proto, transport, b"H" * 12, pcm)) + assert sent[0] == b"H" * 12 + alac_verbatim(pcm) + assert sent[1] == b"H" * 12 + pcm + + def test_install_is_idempotent(self, shim): + from pyatv.support import rtsp + announce = rtsp.RtspSession.announce + stream.install_shim() + assert rtsp.RtspSession.announce is announce