v0.59.0: LinTunes' own AirPlay 1 sender for third-party speakers
pyatv's handshakes play nothing on a WiiM; Music Assistant's cliairplay plays on it through libraop's RAOP client. airplay/raop.py reproduces that client's behaviour on the wire: one RTSP session with auth-setup, an AppleLossless ANNOUNCE and RECORD carrying RTP-Info, OPTIONS keepalives, a 2 s buffer, NTP-locked timestamps, a start that sends the first two seconds at once, the timing responder and resends. Non-Apple speakers stream through it; pyatv only finds them. Verified against shairport-sync (decoded tone, flush on pause/seek, volume, metadata). Round 88's pyatv compat hooks are gone.
This commit is contained in:
+5
-64
@@ -1,10 +1,7 @@
|
||||
"""Round 88: a repeat button, the streaming tile's click, and AirPlay's
|
||||
compatibility handshake for third-party speakers (a WiiM played nothing)."""
|
||||
compatibility mode for third-party speakers (a WiiM played nothing). Round 90
|
||||
replaced its pyatv hooks with raop.py; those tests are in test_round90."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import random
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -169,71 +166,15 @@ class TestAlacVerbatim:
|
||||
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
|
||||
|
||||
class TestShim:
|
||||
def test_install_is_idempotent(self, shim):
|
||||
from pyatv.support import rtsp
|
||||
announce = rtsp.RtspSession.announce
|
||||
info = rtsp.RtspSession.info
|
||||
stream.install_shim()
|
||||
assert rtsp.RtspSession.announce is announce
|
||||
assert rtsp.RtspSession.info is info
|
||||
|
||||
+199
-1
@@ -1,5 +1,11 @@
|
||||
"""Round 90: the track list's headings run over the scrollbar's column."""
|
||||
"""Round 90: the track list's headings run over the scrollbar's column, and
|
||||
LinTunes' own RAOP sender (airplay/raop.py) for third-party speakers."""
|
||||
|
||||
import asyncio
|
||||
import struct
|
||||
|
||||
from lintunes.airplay import raop
|
||||
from lintunes.airplay.support import alac_verbatim, heard_ms
|
||||
from lintunes.gui.track_table import TrackTableView
|
||||
from tests.test_round29 import _local_track
|
||||
|
||||
@@ -17,3 +23,195 @@ def test_headings_span_the_scrollbar_and_dont_scroll_sideways(qapp, tmp_path):
|
||||
assert bar.geometry().top() >= header.height() # starts under them
|
||||
assert view.horizontalScrollBar().maximum() == 0
|
||||
view.close()
|
||||
|
||||
|
||||
# ---- LinTunes' own RAOP sender ----
|
||||
|
||||
|
||||
class TestClocks:
|
||||
def test_ts_and_ntp_round_trip(self):
|
||||
ntp = raop.ntp_now()
|
||||
ts = raop.ntp2ts(ntp)
|
||||
assert abs(raop.ts2ntp(ts) - ntp) < (1 << 32) // 44100 * 2
|
||||
|
||||
def test_volume_matches_pyatv(self):
|
||||
assert raop.percent_to_db(0) == -144.0
|
||||
assert raop.percent_to_db(100) == 0.0
|
||||
assert raop.percent_to_db(50) == -15.0
|
||||
|
||||
def test_two_second_buffer_plus_the_receivers_own(self):
|
||||
client = raop.RaopClient("10.0.0.9", 7000, {})
|
||||
assert client.latency_frames == 88200
|
||||
assert client.latency == 88200 + 11025
|
||||
|
||||
|
||||
class TestPackets:
|
||||
def test_sync_says_frame_ts_minus_latency_plays_at_ntp_ts(self):
|
||||
packet = raop.sync_packet(True, 1_000_000, 88200)
|
||||
first, kind, seq, minus, sec, frac, ts = struct.unpack(">BBHIIII",
|
||||
packet)
|
||||
assert (first, kind, seq) == (0x90, 0xD4, 7)
|
||||
assert minus == 1_000_000 - 88200 and ts == 1_000_000
|
||||
assert (sec << 32 | frac) == raop.ts2ntp(1_000_000)
|
||||
assert raop.sync_packet(False, 5, 1)[0] == 0x80
|
||||
|
||||
def test_audio_packet_marks_only_the_first(self):
|
||||
assert raop.audio_packet(True, 1, 2, 3, b"x")[:2] == b"\x80\xe0"
|
||||
assert raop.audio_packet(False, 1, 2, 3, b"x")[:2] == b"\x80\x60"
|
||||
assert struct.unpack(">HII", raop.audio_packet(
|
||||
False, 0x1_0005, 2**32 + 9, 3, b"")[2:]) == (5, 9, 3)
|
||||
|
||||
def test_timing_reply_echoes_the_send_time(self):
|
||||
request = b"\x80\xd2\x00\x07" + bytes(4) + bytes(16) + b"ABCDEFGH"
|
||||
reply = raop.timing_reply(request, 0x0102030405060708)
|
||||
assert reply[:4] == b"\x80\xd3\x00\x07"
|
||||
assert reply[8:16] == b"ABCDEFGH"
|
||||
assert reply[16:24] == reply[24:32] == bytes(range(1, 9))
|
||||
assert raop.timing_reply(b"short", 1) is None
|
||||
|
||||
def test_resend(self):
|
||||
assert raop.parse_resend(b"\x80\xd5\x00\x01\x00\x0a\x00\x03") == (10, 3)
|
||||
assert raop.parse_resend(b"\x80\xd4\x00\x01\x00\x0a\x00\x03") is None
|
||||
assert raop.resend_packet(b"P") == b"\x80\xd6\x00\x01P"
|
||||
|
||||
def test_daap_item(self):
|
||||
item = raop.daap_item("Song", "", "Album")
|
||||
assert item[:4] == b"mlit"
|
||||
assert struct.unpack(">I", item[4:8])[0] == len(item) - 8
|
||||
assert b"minm\x00\x00\x00\x04Song" in item
|
||||
assert b"asal\x00\x00\x00\x05Album" in item and b"asar" not in item
|
||||
|
||||
def test_sdp_and_transport(self):
|
||||
sdp = raop.announce_sdp("0123456789", "10.0.0.2", "10.0.0.9")
|
||||
assert "a=rtpmap:96 AppleLossless" in sdp
|
||||
assert "a=fmtp:96 352 0 16 40 10 14 2 255 0 0 44100" in sdp
|
||||
assert raop.parse_transport(
|
||||
"RTP/AVP/UDP;unicast;mode=record;server_port=6001;"
|
||||
"control_port=6002;timing_port=6003") == {
|
||||
"server_port": 6001, "control_port": 6002, "timing_port": 6003}
|
||||
|
||||
def test_metadata_caps(self):
|
||||
assert raop.metadata_caps("0,1,2") == {"text", "artwork", "progress"}
|
||||
assert raop.metadata_caps("") == set()
|
||||
|
||||
|
||||
def test_heard_uses_the_senders_own_lag():
|
||||
assert heard_ms(0, 88200, 1000.0, 44100, lag_ms=200) == 800
|
||||
assert heard_ms(0, 88200, 1000.0, 44100) == 0 # pyatv's 1.5 s
|
||||
|
||||
|
||||
class _FakeSpeaker:
|
||||
"""An RTSP + UDP receiver on 127.0.0.1 that records what arrives."""
|
||||
|
||||
def __init__(self):
|
||||
self.requests = []
|
||||
self.audio = []
|
||||
self.control = []
|
||||
|
||||
async def start(self):
|
||||
loop = asyncio.get_running_loop()
|
||||
self.server = await asyncio.start_server(self._client, "127.0.0.1", 0)
|
||||
self.port = self.server.sockets[0].getsockname()[1]
|
||||
speaker = self
|
||||
|
||||
class Sink(asyncio.DatagramProtocol):
|
||||
def __init__(self, into):
|
||||
self.into = into
|
||||
|
||||
def datagram_received(self, data, addr):
|
||||
self.into.append(data)
|
||||
|
||||
self.audio_t, _ = await loop.create_datagram_endpoint(
|
||||
lambda: Sink(speaker.audio), local_addr=("127.0.0.1", 0))
|
||||
self.control_t, _ = await loop.create_datagram_endpoint(
|
||||
lambda: Sink(speaker.control), local_addr=("127.0.0.1", 0))
|
||||
|
||||
async def _client(self, reader, writer):
|
||||
while True:
|
||||
try:
|
||||
head = await reader.readuntil(b"\r\n\r\n")
|
||||
except asyncio.IncompleteReadError:
|
||||
return
|
||||
lines = head.decode().split("\r\n")
|
||||
headers = dict(line.split(": ", 1) for line in lines[1:] if line)
|
||||
body = await reader.readexactly(
|
||||
int(headers.get("Content-Length", 0)))
|
||||
method, url = lines[0].split()[:2]
|
||||
self.requests.append((method, url, headers, body))
|
||||
extra = ""
|
||||
if method == "SETUP":
|
||||
extra = ("Session: 1\r\nTransport: RTP/AVP/UDP;unicast;"
|
||||
f"server_port={self.audio_t.get_extra_info('sockname')[1]};"
|
||||
f"control_port={self.control_t.get_extra_info('sockname')[1]};"
|
||||
"timing_port=1\r\n")
|
||||
writer.write(f"RTSP/1.0 200 OK\r\nCSeq: {headers['CSeq']}\r\n"
|
||||
f"{extra}\r\n".encode())
|
||||
await writer.drain()
|
||||
|
||||
def methods(self):
|
||||
return [(m, u) if m == "POST" else m for m, u, _, _ in self.requests]
|
||||
|
||||
def close(self):
|
||||
self.server.close()
|
||||
self.audio_t.close()
|
||||
self.control_t.close()
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.run(asyncio.wait_for(coro, 20))
|
||||
|
||||
|
||||
def test_the_session_is_libraops():
|
||||
async def go():
|
||||
speaker = _FakeSpeaker()
|
||||
await speaker.start()
|
||||
client = raop.RaopClient("127.0.0.1", speaker.port,
|
||||
{"et": "0,4", "md": "0"})
|
||||
await client.set_volume(-15.0)
|
||||
await client.connect()
|
||||
client.start()
|
||||
pcm = bytes(range(256)) * 5 + bytes(128) # one packet
|
||||
for _ in range(3):
|
||||
client.send(pcm)
|
||||
await client.set_metadata("Song", "Artist", "Album")
|
||||
await asyncio.sleep(0.2)
|
||||
await client.flush()
|
||||
await client.close()
|
||||
speaker.close()
|
||||
return speaker, pcm
|
||||
|
||||
speaker, pcm = _run(go())
|
||||
assert speaker.methods()[:6] == [
|
||||
("POST", "/auth-setup"), "ANNOUNCE", "SETUP", "RECORD",
|
||||
"SET_PARAMETER", "SET_PARAMETER"]
|
||||
by_method = {m: (h, b) for m, _, h, b in speaker.requests}
|
||||
assert len(by_method["POST"][1]) == 33 and by_method["POST"][1][0] == 1
|
||||
assert b"AppleLossless" in by_method["ANNOUNCE"][1]
|
||||
record = by_method["RECORD"][0]
|
||||
assert record["Range"] == "npt=0-" and "rtptime=" in record["RTP-Info"]
|
||||
assert "FLUSH" not in speaker.methods()[:5] # nothing before audio
|
||||
assert all(h["User-Agent"] == raop.USER_AGENT and "DACP-ID" in h
|
||||
for _, _, h, _ in speaker.requests)
|
||||
volume = [b for m, _, h, b in speaker.requests
|
||||
if h.get("Content-Type") == "text/parameters"]
|
||||
assert volume[0] == b"volume: -15.000000\r\n"
|
||||
# The audio: three packets, the first marked, each one ALAC frame.
|
||||
assert [p[1] for p in speaker.audio] == [0xE0, 0x60, 0x60]
|
||||
assert speaker.audio[0][12:] == alac_verbatim(pcm)
|
||||
seqs = [struct.unpack(">H", p[2:4])[0] for p in speaker.audio]
|
||||
assert seqs == [(seqs[0] + i) & 0xFFFF for i in range(3)]
|
||||
stamps = [struct.unpack(">I", p[4:8])[0] for p in speaker.audio]
|
||||
assert [b - a for a, b in zip(stamps, stamps[1:])] == [352, 352]
|
||||
# …and the first sync went out before them, flagged first.
|
||||
assert speaker.control and speaker.control[0][:2] == b"\x90\xd4"
|
||||
|
||||
|
||||
def test_a_late_start_sends_the_first_two_seconds_at_once():
|
||||
client = raop.RaopClient("10.0.0.9", 7000, {})
|
||||
client.state = "flushed"
|
||||
client.start()
|
||||
# The first packet is already ~2 s late: no waiting until the buffer
|
||||
# is full, then real time.
|
||||
assert client.ready_for() < -1.9
|
||||
client.head_ts += raop.ms2ts(2100)
|
||||
assert client.ready_for() > 0
|
||||
|
||||
Reference in New Issue
Block a user