tiat.place connects but stays silent; pyatv streams to it with its AirPlay 2 path, which the fake receiver never exercised. Log every stream's start, first audio and outcome; config.json airplay_protocol (auto/1/2) forces a version and airplay_debug turns on pyatv's own debug log.
500 lines
18 KiB
Python
500 lines
18 KiB
Python
"""Round 87: Connect to AirPlay.
|
|
|
|
The sink is driven against a fake pyatv session on the real AsyncLoop thread;
|
|
the ffmpeg source decodes real files. Nothing here touches the network —
|
|
pyatv's scan and connect are never called.
|
|
"""
|
|
|
|
import asyncio
|
|
import time
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from PyQt6.QtCore import QObject, pyqtSignal
|
|
from PyQt6.QtGui import QColor, QImage
|
|
|
|
from lintunes import player as player_module
|
|
from lintunes.airplay import support
|
|
from lintunes.airplay.discovery import AirPlayDevice
|
|
from lintunes.airplay.loop import AsyncLoop
|
|
from lintunes.gui.cast_dialog import AirPlayDialog, ChromecastDialog
|
|
from lintunes.models.library import Library
|
|
from lintunes.player import Player
|
|
|
|
|
|
def _until(qapp, condition, timeout=3.0):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
qapp.processEvents()
|
|
if condition():
|
|
return True
|
|
time.sleep(0.005)
|
|
qapp.processEvents()
|
|
return condition()
|
|
|
|
|
|
# ---- pure helpers ----
|
|
|
|
class TestSupport:
|
|
def test_only_receivers_that_take_anyone_are_connectable(self):
|
|
assert support.classify(True, "NotNeeded", False) == (True, "")
|
|
assert support.classify(True, "Optional", False) == (True, "")
|
|
assert support.classify(True, "Mandatory", False) == (False,
|
|
"needs pairing")
|
|
assert support.classify(True, "NotNeeded", True)[0] is False
|
|
assert support.classify(True, "Unsupported", False)[0] is False
|
|
# AirPlay without RAOP is a screen to mirror to, not a speaker.
|
|
assert support.classify(False, "", False) == (False, "video only")
|
|
|
|
def test_volume_is_the_same_db_as_the_local_output(self):
|
|
assert support.level_to_percent(0.0) == 0.0
|
|
assert support.level_to_percent(1.0) == 100.0
|
|
# Half amplitude is -6 dB: 24/30 of the way up pyatv's -30..0 scale.
|
|
assert support.level_to_percent(0.5) == pytest.approx(79.93, abs=0.01)
|
|
# Below pyatv's floor is silence, never a negative percent.
|
|
assert support.level_to_percent(0.01) == 0.0
|
|
|
|
def test_position_is_what_was_heard_not_what_was_sent(self):
|
|
rate = 44100
|
|
latency = support.latency_ms(rate)
|
|
assert latency == pytest.approx(1500, abs=1)
|
|
# Nothing read yet: still at the start position.
|
|
assert support.heard_ms(5000, 0, None, rate) == 5000
|
|
# Inside the receiver's latency nothing has come out yet.
|
|
assert support.heard_ms(5000, rate, 1000, rate) == 5000
|
|
assert support.heard_ms(0, 10 * rate, 3500, rate) == 2000
|
|
# Capped at what was read: pyatv sends trailing silence after the
|
|
# song, and the position must not run past it.
|
|
assert support.heard_ms(0, 4 * rate, 9000, rate) == 4000
|
|
|
|
def test_ffmpeg_seeks_only_when_asked_and_sends_big_endian(self):
|
|
cmd = support.ffmpeg_command("/m/a.m4a", 0, 44100, 2, 2)
|
|
assert "-ss" not in cmd
|
|
assert cmd[cmd.index("-f") + 1] == "s16be"
|
|
assert cmd[-1] == "pipe:1"
|
|
cmd = support.ffmpeg_command("/m/a.m4a", 61_500, 44100, 2, 2)
|
|
# Before -i: an input seek, instant however deep into the file.
|
|
assert cmd.index("-ss") < cmd.index("-i")
|
|
assert cmd[cmd.index("-ss") + 1] == "61.500"
|
|
|
|
def test_everything_but_fairplay_streams(self):
|
|
assert support.can_stream("/m/a.m4a", "Apple Lossless audio file")
|
|
assert support.can_stream("/m/a.aiff", "AIFF audio file")
|
|
assert not support.can_stream("/m/a.m4p", "")
|
|
assert not support.can_stream("/m/a.m4a", "Protected AAC audio file")
|
|
assert not support.can_stream("", "")
|
|
assert "copy-protected" in support.unstreamable_reason(
|
|
"/m/a.m4a", "Protected AAC audio file")
|
|
|
|
|
|
# ---- the ffmpeg source ----
|
|
|
|
def _drain(request, rate=44100):
|
|
from lintunes.airplay.stream import _ffmpeg_source
|
|
|
|
async def run():
|
|
source = await _ffmpeg_source().open(request, rate, 2, 2)
|
|
total = b""
|
|
while True:
|
|
chunk = await source.readframes(352)
|
|
if not chunk:
|
|
break
|
|
total += chunk
|
|
await source.close()
|
|
return total
|
|
return asyncio.run(run())
|
|
|
|
|
|
class TestFfmpegSource:
|
|
@pytest.fixture(autouse=True)
|
|
def _needs_pyatv(self):
|
|
pytest.importorskip("pyatv")
|
|
|
|
def test_decodes_a_whole_song(self, m4a_file):
|
|
from lintunes.airplay.stream import PcmRequest
|
|
request = PcmRequest(str(m4a_file), 0, 1000)
|
|
data = _drain(request)
|
|
assert request.exhausted and not request.decode_error
|
|
assert request.frames_read == len(data) // 4
|
|
# A 1 s AAC fixture, give or take the encoder's priming frames.
|
|
assert request.frames_read == pytest.approx(44100, abs=2048)
|
|
assert request.first_read_at is not None
|
|
|
|
def test_starts_from_an_offset(self, flac_file):
|
|
from lintunes.airplay.stream import PcmRequest
|
|
request = PcmRequest(str(flac_file), 500, 1000)
|
|
_drain(request)
|
|
assert request.frames_read == pytest.approx(22050, abs=64)
|
|
|
|
def test_an_unreadable_file_is_a_decode_error(self, tmp_path):
|
|
from lintunes.airplay.stream import PcmRequest
|
|
request = PcmRequest(str(tmp_path / "gone.mp3"), 0, 1000)
|
|
assert _drain(request) == b""
|
|
assert request.decode_error
|
|
assert not request.exhausted
|
|
|
|
def test_shim_routes_only_our_requests(self):
|
|
import pyatv.protocols.raop as raop
|
|
from lintunes.airplay.stream import install_shim
|
|
install_shim()
|
|
patched = raop.open_source
|
|
install_shim()
|
|
assert raop.open_source is patched # idempotent
|
|
assert patched._lintunes
|
|
|
|
|
|
# ---- the sink, against a fake pyatv session ----
|
|
|
|
class _FakeAtv:
|
|
def __init__(self):
|
|
self.log = []
|
|
self.behavior = "finish"
|
|
self.closed = 0
|
|
outer = self
|
|
|
|
class Stream:
|
|
async def stream_file(self, request, metadata=None):
|
|
outer.log.append(("stream", request.start_ms, metadata.title))
|
|
behavior = outer.behavior
|
|
if behavior == "finish":
|
|
request.frames_read = 4410
|
|
request.exhausted = True
|
|
elif behavior == "hang":
|
|
try:
|
|
await asyncio.sleep(3600)
|
|
except asyncio.CancelledError:
|
|
outer.log.append(("cancelled", request.start_ms))
|
|
raise
|
|
elif behavior == "decode":
|
|
request.decode_error = "Invalid data found"
|
|
elif behavior == "drop":
|
|
request.frames_read = 1000
|
|
elif behavior == "unreachable":
|
|
raise ConnectionRefusedError("refused")
|
|
|
|
class Audio:
|
|
async def set_volume(self, percent):
|
|
outer.log.append(("volume", round(percent, 1)))
|
|
|
|
self.stream = Stream()
|
|
self.audio = Audio()
|
|
|
|
def close(self):
|
|
self.closed += 1
|
|
return set()
|
|
|
|
def kinds(self):
|
|
return [entry[0] for entry in self.log]
|
|
|
|
|
|
def _track(location="/m/song.mp3", total_time=4000):
|
|
return SimpleNamespace(location=location, kind="MPEG audio file",
|
|
name="Song", artist="Artist", album="Album",
|
|
total_time=total_time)
|
|
|
|
|
|
@pytest.fixture
|
|
def loop():
|
|
return AsyncLoop()
|
|
|
|
|
|
@pytest.fixture
|
|
def sink_and_atv(qapp, loop):
|
|
pytest.importorskip("pyatv")
|
|
from lintunes.airplay.sink import AirPlaySink
|
|
atv = _FakeAtv()
|
|
with patch("lintunes.airplay.sink.tagging.read_embedded_artwork",
|
|
return_value=None):
|
|
sink = AirPlaySink(atv, loop, "tiat.place")
|
|
events = []
|
|
sink.ended.connect(lambda: events.append("ended"))
|
|
sink.error.connect(lambda m: events.append(("error", m)))
|
|
sink.unavailable.connect(lambda m: events.append(("unavailable", m)))
|
|
yield sink, atv, events
|
|
sink.shutdown()
|
|
|
|
|
|
class TestAirPlaySink:
|
|
def test_a_finished_song_ends_once(self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
sink.load(_track(), autoplay=True, start_ms=0)
|
|
assert sink.is_playing()
|
|
assert _until(qapp, lambda: events)
|
|
assert events == ["ended"]
|
|
assert not sink.is_playing()
|
|
assert sink.position_ms() == 4000
|
|
assert ("stream", 0, "Song") in atv.log
|
|
|
|
def test_volume_reaches_the_speaker_before_the_stream(
|
|
self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
sink.set_volume(1.0)
|
|
sink.load(_track(), autoplay=True, start_ms=0)
|
|
assert _until(qapp, lambda: "stream" in atv.kinds())
|
|
assert atv.log[0] == ("volume", 100.0)
|
|
assert atv.kinds().index("volume") < atv.kinds().index("stream")
|
|
|
|
def test_loading_paused_streams_nothing(self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
sink.load(_track(), autoplay=False, start_ms=1200)
|
|
_until(qapp, lambda: False, timeout=0.2)
|
|
assert "stream" not in atv.kinds()
|
|
assert sink.position_ms() == 1200 and not sink.is_playing()
|
|
|
|
def test_a_seek_replaces_the_stream_and_the_old_one_cannot_end_it(
|
|
self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
atv.behavior = "hang"
|
|
sink.load(_track(), autoplay=True, start_ms=0)
|
|
assert _until(qapp, lambda: ("stream", 0, "Song") in atv.log)
|
|
sink.seek(3000)
|
|
assert sink.position_ms() == 3000
|
|
assert _until(qapp, lambda: ("stream", 3000, "Song") in atv.log)
|
|
assert ("cancelled", 0) in atv.log
|
|
# The old stream was cancelled, never finished: no queue advance.
|
|
assert events == []
|
|
assert sink.is_playing()
|
|
|
|
def test_pause_stops_the_stream_and_resume_starts_where_it_was(
|
|
self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
atv.behavior = "hang"
|
|
sink.load(_track(), autoplay=True, start_ms=2000)
|
|
assert _until(qapp, lambda: ("stream", 2000, "Song") in atv.log)
|
|
sink.pause()
|
|
assert not sink.is_playing()
|
|
assert _until(qapp, lambda: ("cancelled", 2000) in atv.log)
|
|
paused_at = sink.position_ms()
|
|
sink.play()
|
|
assert _until(qapp, lambda: atv.kinds().count("stream") == 2)
|
|
assert atv.log[-1] == ("stream", paused_at, "Song")
|
|
assert events == []
|
|
|
|
def test_an_undecodable_song_is_skipped_not_a_lost_speaker(
|
|
self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
atv.behavior = "decode"
|
|
sink.load(_track(), autoplay=True, start_ms=0)
|
|
assert _until(qapp, lambda: events)
|
|
assert events[0][0] == "error"
|
|
assert "Invalid data" in events[0][1]
|
|
|
|
@pytest.mark.parametrize("behavior, says", [
|
|
("drop", "something else"), # pyatv returned before ffmpeg's end
|
|
("unreachable", "Lost"),
|
|
])
|
|
def test_a_lost_speaker_hands_back_to_this_machine(
|
|
self, qapp, sink_and_atv, behavior, says):
|
|
sink, atv, events = sink_and_atv
|
|
atv.behavior = behavior
|
|
sink.load(_track(), autoplay=True, start_ms=0)
|
|
assert _until(qapp, lambda: events)
|
|
kind, reason = events[0]
|
|
assert kind == "unavailable" and says in reason
|
|
# Still "playing": Player falls back to the local output carrying on.
|
|
assert sink.is_playing()
|
|
|
|
def test_shutdown_closes_the_session(self, qapp, sink_and_atv):
|
|
sink, atv, events = sink_and_atv
|
|
sink.shutdown()
|
|
sink.shutdown()
|
|
assert atv.closed == 1
|
|
|
|
def test_artwork_is_sent_as_a_small_jpeg(self, qapp):
|
|
from lintunes.airplay.sink import ART_MAX_PX, jpeg_artwork
|
|
from PyQt6.QtCore import QBuffer, QIODevice
|
|
image = QImage(1200, 800, QImage.Format.Format_RGB32)
|
|
image.fill(QColor("red"))
|
|
buffer = QBuffer()
|
|
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
|
image.save(buffer, "PNG")
|
|
out = jpeg_artwork(bytes(buffer.data()))
|
|
assert out[:3] == b"\xff\xd8\xff"
|
|
decoded = QImage()
|
|
decoded.loadFromData(out)
|
|
assert max(decoded.width(), decoded.height()) == ART_MAX_PX
|
|
assert jpeg_artwork(None) is None
|
|
assert jpeg_artwork(b"not an image") is None
|
|
|
|
|
|
# ---- the controller ----
|
|
|
|
def _player(qapp):
|
|
with patch.multiple(player_module, QMediaPlayer=MagicMock(),
|
|
QAudioOutput=MagicMock(),
|
|
QAudioBufferOutput=MagicMock(),
|
|
QMediaDevices=MagicMock()):
|
|
return Player(MagicMock(library=Library()))
|
|
|
|
|
|
class TestController:
|
|
def test_connect_hands_player_the_sink_and_disconnect_takes_it_back(
|
|
self, qapp):
|
|
pytest.importorskip("pyatv")
|
|
from lintunes.airplay.controller import AirPlayController
|
|
player = _player(qapp)
|
|
controller = AirPlayController(player)
|
|
controller._inhibitor = MagicMock()
|
|
seen = []
|
|
controller.connected.connect(seen.append)
|
|
atv = _FakeAtv()
|
|
|
|
controller._attempt = 1
|
|
controller._on_connect_result({"atv": atv, "name": "tiat.place"}, 1)
|
|
assert controller.is_connected()
|
|
assert player.active_sink().name == "tiat.place"
|
|
assert player.active_sink().listen_src == "airplay"
|
|
assert seen == ["tiat.place"]
|
|
|
|
controller.disconnect()
|
|
assert player.is_local
|
|
assert not controller.is_connected()
|
|
assert atv.closed == 1
|
|
|
|
def test_a_superseded_connect_is_closed_not_installed(self, qapp):
|
|
pytest.importorskip("pyatv")
|
|
from lintunes.airplay.controller import AirPlayController
|
|
player = _player(qapp)
|
|
controller = AirPlayController(player)
|
|
atv = _FakeAtv()
|
|
controller._attempt = 2
|
|
controller._on_connect_result({"atv": atv, "name": "old pick"}, 1)
|
|
assert not controller.is_connected()
|
|
assert _until(qapp, lambda: atv.closed == 1)
|
|
|
|
def test_raop_only_turns_the_other_services_off(self):
|
|
pytest.importorskip("pyatv")
|
|
from pyatv.const import Protocol
|
|
from lintunes.airplay.controller import raop_only
|
|
services = [SimpleNamespace(protocol=Protocol.AirPlay, enabled=True),
|
|
SimpleNamespace(protocol=Protocol.RAOP, enabled=True)]
|
|
raop_only(SimpleNamespace(services=services))
|
|
assert [s.enabled for s in services] == [False, True]
|
|
|
|
|
|
# ---- discovery and the picker ----
|
|
|
|
class TestDiscovery:
|
|
def test_a_scan_result_becomes_a_device(self):
|
|
pytest.importorskip("pyatv")
|
|
from pyatv.const import Protocol
|
|
from lintunes.airplay.discovery import to_device
|
|
|
|
def conf(raop, name, model):
|
|
return SimpleNamespace(
|
|
identifier="42:D9", name=name, address="192.0.2.7",
|
|
device_info=SimpleNamespace(raw_model=model),
|
|
get_service=lambda p: raop if p == Protocol.RAOP else None)
|
|
|
|
speaker = to_device(conf(SimpleNamespace(
|
|
pairing=SimpleNamespace(name="NotNeeded"), requires_password=False,
|
|
properties={"am": "WiiM Mini Receiver"}), "Gallery", None))
|
|
assert speaker == AirPlayDevice(
|
|
uuid="42:D9", name="Gallery", model="WiiM Mini Receiver",
|
|
host="192.0.2.7", connectable=True, note="")
|
|
|
|
tv = to_device(conf(None, "Lobby TV", "7415X"))
|
|
assert not tv.connectable and tv.note == "video only"
|
|
assert tv.model == "7415X"
|
|
|
|
|
|
class _FakeDiscovery(QObject):
|
|
device_found = pyqtSignal(object)
|
|
device_lost = pyqtSignal(object)
|
|
failed = pyqtSignal(str)
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.stopped = 0
|
|
|
|
def devices(self):
|
|
return []
|
|
|
|
def start(self):
|
|
pass
|
|
|
|
def stop(self):
|
|
self.stopped += 1
|
|
|
|
|
|
def _ap(uuid, name, connectable=True, note=""):
|
|
return AirPlayDevice(uuid=uuid, name=name, model="", host="192.0.2.9",
|
|
connectable=connectable, note=note)
|
|
|
|
|
|
class TestPicker:
|
|
def test_unusable_devices_are_listed_greyed_with_the_reason(self, qapp):
|
|
discovery = _FakeDiscovery()
|
|
dialog = AirPlayDialog(discovery)
|
|
assert dialog.windowTitle() == "Connect to AirPlay"
|
|
assert "AirPlay speaker" in dialog._status.text()
|
|
|
|
discovery.device_found.emit(_ap("tv", "Lobby TV", False,
|
|
"needs pairing"))
|
|
assert dialog._list.count() == 1
|
|
assert "needs pairing" in dialog._list.item(0).text()
|
|
assert not dialog._connect_button.isEnabled()
|
|
dialog._on_connect()
|
|
assert dialog.selected_device is None
|
|
|
|
dialog._on_empty_timeout()
|
|
assert "can play to" in dialog._status.text()
|
|
|
|
discovery.device_found.emit(_ap("wiim", "tiat.place"))
|
|
assert dialog._connect_button.isEnabled()
|
|
dialog._on_connect()
|
|
assert dialog.selected_device.name == "tiat.place"
|
|
assert discovery.stopped == 1
|
|
|
|
def test_chromecast_picker_reads_as_before(self, qapp):
|
|
dialog = ChromecastDialog(_FakeDiscovery())
|
|
assert dialog.windowTitle() == "Connect to Chromecast"
|
|
assert dialog._status.text() == "Searching for Chromecasts…"
|
|
dialog.reject()
|
|
|
|
|
|
# ---- the transport-bar indicator ----
|
|
|
|
class TestIndicator:
|
|
def test_the_visualizer_shows_airplay_and_a_click_disconnects_it(
|
|
self, qapp, tmp_path):
|
|
from lintunes.gui.transport import TransportBar
|
|
from lintunes.player import PlaybackSink
|
|
from lintunes.preferences import Preferences
|
|
|
|
class Sink(PlaybackSink):
|
|
name = "tiat.place"
|
|
glyph = "airplay"
|
|
|
|
def stop(self):
|
|
pass
|
|
|
|
def set_volume(self, level):
|
|
pass
|
|
|
|
def position_ms(self):
|
|
return 0
|
|
|
|
def is_playing(self):
|
|
return False
|
|
|
|
player = _player(qapp)
|
|
cast, airplay = MagicMock(), MagicMock()
|
|
bar = TransportBar(player, MagicMock(), Preferences(tmp_path),
|
|
cast=cast, airplay=airplay)
|
|
player.set_sink(Sink())
|
|
vis = bar._visualizer
|
|
assert vis._glyph == "airplay"
|
|
assert vis.toolTip() == "Playing on tiat.place — click to stop"
|
|
vis.mousePressEvent(None)
|
|
airplay.disconnect.assert_called_once()
|
|
|
|
|
|
def test_protocol_choice_defaults_to_auto():
|
|
assert support.protocol_choice(None) == "auto"
|
|
assert support.protocol_choice("1") == "1"
|
|
assert support.protocol_choice("v1") == "1"
|
|
assert support.protocol_choice(2) == "2"
|
|
assert support.protocol_choice("three") == "auto"
|