"""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