/
/
1"""Sendspin Player implementation."""
2
3from __future__ import annotations
4
5import asyncio
6import time
7from collections.abc import Callable
8from contextlib import suppress
9from io import BytesIO
10from typing import TYPE_CHECKING, ClassVar, cast
11
12from aiosendspin.models import AudioCodec, MediaCommand
13from aiosendspin.models.management import (
14 ManagementSetPairingConfigPayload,
15 SetDynamicPinConfig,
16 SetStaticPinConfig,
17 SetUnpairedAccessConfig,
18)
19from aiosendspin.models.types import PairMethod, PlaybackStateType, PlayerCommand, role_family
20from aiosendspin.models.types import RepeatMode as SendspinRepeatMode
21from aiosendspin.models.visualizer import BeatAvailability, BeatTiming
22from aiosendspin.noise.driver import HandshakeAbortedError
23from aiosendspin.noise.pairing import (
24 SERVER_FIRST_MESSAGE_TIMEOUT_S,
25 SERVER_GESTURE_TIMEOUT_S,
26 PairingError,
27)
28from aiosendspin.noise.trust_store import PskCategory
29from aiosendspin.server import ClientEvent, GroupEvent, SendspinGroup, VolumeChangedEvent
30from aiosendspin.server.audio import AudioFormat as SendspinAudioFormat
31from aiosendspin.server.client import DisconnectBehaviour
32from aiosendspin.server.events import (
33 ClientGroupChangedEvent,
34 GroupDeletedEvent,
35 GroupMemberAddedEvent,
36 GroupMemberRemovedEvent,
37 GroupStateChangedEvent,
38)
39from aiosendspin.server.roles import (
40 ArtworkGroupRole,
41 ColorGroupRole,
42 ControllerEvent,
43 ControllerGroupRole,
44 ControllerNextEvent,
45 ControllerPauseEvent,
46 ControllerPlayEvent,
47 ControllerPreviousEvent,
48 ControllerRepeatEvent,
49 ControllerSeekEvent,
50 ControllerSeekRelativeEvent,
51 ControllerShuffleEvent,
52 ControllerStopEvent,
53 MetadataGroupRole,
54 VisualizerGroupRole,
55)
56from aiosendspin.server.roles.color.state import Color
57from aiosendspin.server.roles.metadata.state import Metadata
58from aiosendspin.server.roles.player.events import StaticDelayChangedEvent
59from aiosendspin.server.roles.player.types import PlayerRoleProtocol
60from music_assistant_models.config_entries import ConfigEntry, ConfigValueOption
61from music_assistant_models.constants import PLAYER_CONTROL_NONE
62from music_assistant_models.enums import (
63 ConfigEntryType,
64 IdentifierType,
65 MediaType,
66 PlaybackState,
67 PlayerFeature,
68 PlayerType,
69 ProviderType,
70 RepeatMode,
71)
72from music_assistant_models.errors import MediaNotFoundError, PlayerCommandFailed
73from music_assistant_models.media_items import Album, Artist, is_track
74from music_assistant_models.player import DeviceInfo
75from PIL import Image
76
77from music_assistant.constants import HIDDEN_ANNOUNCE_VOLUME_CONFIG_ENTRIES
78from music_assistant.controllers.streams.audio_analysis import SMART_FADES_ANALYSIS_DOMAIN
79from music_assistant.helpers.util import is_valid_mac_address, join_task
80from music_assistant.models.player import Player, PlayerMedia
81from music_assistant.models.setup_flow import AbortFlow, StepExpiredError
82
83from .constants import (
84 BRIDGE_PREFIX,
85 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_DISABLE,
86 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_ENABLE,
87 CONF_ACTION_MANAGEMENT_ENTER,
88 CONF_ACTION_MANAGEMENT_EXIT,
89 CONF_ACTION_MANAGEMENT_STATIC_PIN_DISABLE,
90 CONF_ACTION_MANAGEMENT_STATIC_PIN_ENABLE,
91 CONF_ACTION_MANAGEMENT_UNPAIRED_DISABLE,
92 CONF_ACTION_MANAGEMENT_UNPAIRED_ENABLE,
93 CONF_ACTION_REVOKE_UNPAIRED,
94 CONF_ACTION_UNPAIR,
95 CONF_CAST_AUDIO_UNSUPPORTED,
96 CONF_PAIRING_METHOD,
97 CONF_PAIRING_PIN,
98 CONF_PAIRING_TOKEN,
99 CONF_SENDSPIN_STATIC_DELAY,
100 CONF_SOURCE_AUTOSTART_TARGET,
101 DEFAULT_SENDSPIN_STATIC_DELAY,
102 PAIR_METHOD_DYNAMIC_PIN,
103 PAIR_METHOD_PIN,
104 PAIR_METHOD_STATIC_PIN,
105 PAIR_METHOD_TOKEN,
106 PAIR_METHOD_UNPAIRED,
107 SOURCE_AUTOSTART_OFF,
108)
109from .helpers import (
110 AlertText,
111 SecurityActionError,
112 action_entry,
113 alert_entry,
114 effective_pair_methods,
115 effective_unpaired_access,
116 error_alert,
117 mac_from_bridge_client_id,
118 pair_method_descriptor,
119)
120from .playback import SendspinPlaybackSession
121
122# Supported group commands for Sendspin players
123SUPPORTED_GROUP_COMMANDS = [
124 MediaCommand.PLAY,
125 MediaCommand.PAUSE,
126 MediaCommand.STOP,
127 MediaCommand.NEXT,
128 MediaCommand.PREVIOUS,
129 MediaCommand.REPEAT_OFF,
130 MediaCommand.REPEAT_ONE,
131 MediaCommand.REPEAT_ALL,
132 MediaCommand.SHUFFLE,
133 MediaCommand.UNSHUFFLE,
134 MediaCommand.SEEK,
135 MediaCommand.SEEK_RELATIVE,
136]
137
138# Config constants for Sendspin audio format
139CONF_PREFERRED_SENDSPIN_FORMAT = "preferred_sendspin_format"
140SENDSPIN_FORMAT_AUTOMATIC = "automatic"
141
142# Player types that can render a line-in, so groups and pairs stay selectable.
143SOURCE_AUTOSTART_TARGET_TYPES = {
144 PlayerType.PLAYER,
145 PlayerType.STEREO_PAIR,
146 PlayerType.GROUP,
147}
148
149
150def format_to_option_value(fmt: SupportedAudioFormat) -> str:
151 """Convert SupportedAudioFormat to "codec:sample_rate:bit_depth:channels"."""
152 return f"{fmt.codec.value}:{fmt.sample_rate}:{fmt.bit_depth}:{fmt.channels}"
153
154
155def option_value_to_format(value: str) -> tuple[AudioCodec, SendspinAudioFormat] | None:
156 """
157 Parse option value back to (AudioCodec, SendspinAudioFormat).
158
159 :param value: Option value in format "codec:sample_rate:bit_depth:channels".
160 :return: Tuple of (AudioCodec, SendspinAudioFormat) or None if parsing fails.
161 """
162 try:
163 codec_str, sample_rate_str, bit_depth_str, channels_str = value.split(":")
164 codec = AudioCodec(codec_str)
165 audio_format = SendspinAudioFormat(
166 sample_rate=int(sample_rate_str),
167 bit_depth=int(bit_depth_str),
168 channels=int(channels_str),
169 )
170 return (codec, audio_format)
171 except ValueError, KeyError:
172 return None
173
174
175def format_to_display_string(fmt: SupportedAudioFormat) -> str:
176 """Convert to display string like "FLAC 48kHz/24bit stereo"."""
177 codec_name = fmt.codec.name
178 sample_rate_khz = fmt.sample_rate / 1000
179 # Format sample rate: show as integer if whole number, otherwise one decimal
180 if sample_rate_khz == int(sample_rate_khz):
181 sample_rate_str = f"{int(sample_rate_khz)}kHz"
182 else:
183 sample_rate_str = f"{sample_rate_khz:.1f}kHz"
184 if fmt.channels == 2:
185 channels_str = "stereo"
186 elif fmt.channels == 1:
187 channels_str = "mono"
188 else:
189 channels_str = f"{fmt.channels}ch"
190 return f"{codec_name} {sample_rate_str}/{fmt.bit_depth}bit {channels_str}"
191
192
193_MANAGEMENT_ACTIONS = {
194 CONF_ACTION_MANAGEMENT_UNPAIRED_ENABLE: ManagementSetPairingConfigPayload(
195 unpaired_access=SetUnpairedAccessConfig(enabled=True)
196 ),
197 CONF_ACTION_MANAGEMENT_UNPAIRED_DISABLE: ManagementSetPairingConfigPayload(
198 unpaired_access=SetUnpairedAccessConfig(enabled=False)
199 ),
200 CONF_ACTION_MANAGEMENT_STATIC_PIN_ENABLE: ManagementSetPairingConfigPayload(
201 static_pin=SetStaticPinConfig(enabled=True)
202 ),
203 CONF_ACTION_MANAGEMENT_STATIC_PIN_DISABLE: ManagementSetPairingConfigPayload(
204 static_pin=SetStaticPinConfig(enabled=False)
205 ),
206 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_ENABLE: ManagementSetPairingConfigPayload(
207 dynamic_pin=SetDynamicPinConfig(enabled=True)
208 ),
209 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_DISABLE: ManagementSetPairingConfigPayload(
210 dynamic_pin=SetDynamicPinConfig(enabled=False)
211 ),
212}
213
214# Seconds the setup flow gives the operator to enter the PIN. Advisory: the authoritative end
215# is the device's own attempt timeout (spec-recommended 2 minutes), which aborts the attempt.
216PAIR_PIN_ENTRY_TIMEOUT = 120.0
217# Seconds the setup flow waits for pairing to complete after the PIN is submitted.
218PAIR_CONFIRM_TIMEOUT = 30.0
219# Seconds a Cast-bridged member gets to report its Sendspin app ready.
220CAST_APP_READY_TIMEOUT = 30.0
221
222# Terminal pairing-error slugs that map to a dedicated setup_flow.abort reason;
223# anything else falls back to the generic "pairing_failed" abort.
224_PAIRING_ABORT_REASONS = {
225 "pairing_error_concurrent": "pairing_error_concurrent",
226 "pairing_error_no_pin_method": "no_pair_methods",
227 "pairing_error_not_connected": "pairing_error_not_connected",
228}
229
230# How the operator gets a method's secret, per the device's own descriptor hints: where a
231# configured secret is found, or which channel conveys a per-session PIN. Values outside these
232# maps render nothing.
233_SECRET_HINT_LABELS = {
234 PairMethod.STATIC_PIN: {
235 "device": "static_pin_location_device",
236 "leaflet": "static_pin_location_leaflet",
237 "operator": "static_pin_location_operator",
238 },
239 PairMethod.PAIRING_PSK: {
240 "device": "pairing_psk_location_device",
241 "leaflet": "pairing_psk_location_leaflet",
242 "operator": "pairing_psk_location_operator",
243 },
244 PairMethod.DYNAMIC_PIN: {
245 "display": "dynamic_pin_channel_display",
246 "speaker": "dynamic_pin_channel_speaker",
247 },
248}
249
250
251def _pin_error_slug(error: Exception | None) -> str:
252 """Return the strings.json errors slug for a retryable PIN failure (re-rendered form)."""
253 if error is None:
254 return "pairing_error_generic"
255 return error_alert(error).key
256
257
258def _pairing_abort_reason(error: Exception | None) -> str:
259 """Return the setup_flow.abort reason slug for a terminal pairing failure."""
260 if error is None:
261 return "pairing_failed"
262 key = error.alert_key if isinstance(error, SecurityActionError) else error_alert(error).key
263 return _PAIRING_ABORT_REASONS.get(key, "pairing_failed")
264
265
266if TYPE_CHECKING:
267 from aiosendspin.models.core import ClientHelloPayload
268 from aiosendspin.models.management import ManagementResultData, PairingMethodConfig
269 from aiosendspin.models.player import SupportedAudioFormat
270 from aiosendspin.noise.trust_store import ServerPairingRecord
271 from aiosendspin.server.client import SendspinClient
272 from music_assistant_models.media_items import MediaItemPalette
273 from music_assistant_models.player_queue import PlayerQueue
274 from music_assistant_models.queue_item import QueueItem
275
276 from music_assistant.controllers.player_queues.state import PlayerQueueData
277 from music_assistant.models.setup_flow import SetupSession
278 from music_assistant.providers.chromecast.sendspin_bridge import SendspinBridgeManager
279 from music_assistant.providers.hass import HomeAssistantProvider
280
281 from .provider import PinPairingSession, SendspinProvider
282
283
284class SendspinBasePlayer(Player):
285 """
286 Base class for Sendspin players in Music Assistant.
287
288 Provides shared device-info, group membership, and event handling logic
289 that is common to both audio and non-audio (visualizer) player types.
290 """
291
292 api: SendspinClient
293 unsub_event_cb: Callable[[], None] | None
294 unsub_group_event_cb: Callable[[], None] | None
295 is_web_player: bool = False
296 # transient alert produced by the most recent security action, surfaced on the next
297 # config-entries render (the settings page re-renders after invoking an action)
298 _pending_security_alert: AlertText | None = None
299
300 def __init__(
301 self,
302 provider: SendspinProvider,
303 player_id: str,
304 initial_hello: ClientHelloPayload | None = None,
305 ) -> None:
306 """
307 Initialize the base Sendspin player.
308
309 :param provider: The Sendspin provider instance.
310 :param player_id: The unique player identifier.
311 :param initial_hello: Optional hello payload from the client.
312 """
313 super().__init__(provider, player_id)
314 sendspin_client = provider.server_api.get_client(player_id)
315 assert sendspin_client is not None
316 self.api = sendspin_client
317 self.unsub_event_cb = None
318 self.unsub_group_event_cb = None
319 self.logger = self.provider.logger.getChild(player_id)
320 self._attr_can_group_with = {provider.instance_id}
321 self._attr_power_control = PLAYER_CONTROL_NONE
322 self._refresh_client_info(sendspin_client, hello_payload=initial_hello)
323 self._subscribe_client_callbacks()
324
325 def event_cb(self, client: SendspinClient, event: ClientEvent) -> None:
326 """Event callback registered to the sendspin client."""
327 match event:
328 case ClientGroupChangedEvent(new_group=new_group):
329 if self.unsub_group_event_cb is not None:
330 self.unsub_group_event_cb()
331 self.unsub_group_event_cb = new_group.add_event_listener(self.group_event_cb)
332 self._on_group_changed(new_group)
333 self.update_state()
334
335 def group_event_cb(self, group: SendspinGroup, event: GroupEvent) -> None:
336 """Event callback registered to the sendspin group this player belongs to."""
337 if self.synced_to is not None:
338 # Only handle group events as the leader, except for:
339 # - GroupMemberRemovedEvent: to handle being removed from a group
340 # - GroupStateChangedEvent: to update playback state when leader stops/disconnects
341 if not isinstance(event, (GroupMemberRemovedEvent, GroupStateChangedEvent)):
342 return
343 match event:
344 case GroupStateChangedEvent(state=state):
345 match state:
346 case PlaybackStateType.PLAYING:
347 self._attr_playback_state = PlaybackState.PLAYING
348 case PlaybackStateType.PAUSED:
349 self._attr_playback_state = PlaybackState.PAUSED
350 case PlaybackStateType.STOPPED:
351 self._attr_playback_state = PlaybackState.IDLE
352 self._attr_elapsed_time = 0
353 self._attr_elapsed_time_last_updated = time.time()
354 self._on_group_stopped()
355 self.update_state()
356 case GroupMemberAddedEvent(client_id=client_id):
357 is_group_leader = (
358 bool(group.clients) and group.clients[0].client_id == self.player_id
359 )
360 if is_group_leader and (
361 not self._attr_group_members or self._attr_group_members[0] != self.player_id
362 ):
363 self._attr_group_members = [self.player_id, *self._attr_group_members]
364 if client_id not in self._attr_group_members:
365 self._attr_group_members.append(client_id)
366 self.update_state()
367 self._schedule_membership_sync(group)
368 case GroupMemberRemovedEvent(client_id=client_id):
369 self.mass.create_task(self._handle_group_member_removed(group, client_id))
370 self._schedule_membership_sync(group)
371 case GroupDeletedEvent():
372 pass
373
374 async def on_unload(self) -> None:
375 """Handle logic when the player is unloaded from the Player controller."""
376 await super().on_unload()
377 self._unsubscribe_client_callbacks()
378
379 @property
380 def needs_setup(self) -> bool:
381 """
382 Whether the device is connected and encrypted but not yet usable for playback.
383
384 An unpaired device that has not been paired or allowed unpaired playback still
385 connects, but the server activates no roles for it. Reporting needs_setup keeps it
386 out of the ready-to-play targets while its settings (and the pairing actions) stay
387 reachable. Legacy unencrypted devices and the built-in web player can play as-is.
388 """
389 if self._is_bridge_or_web_player:
390 return False
391
392 # Deliberately no is_connected gate: between a (re)connect's hello and its first
393 # client/state, security and active roles are already valid while is_connected is not.
394
395 if self.api.connection_security is None:
396 return False
397 return not self.api.active_roles
398
399 @property
400 def setup_reason(self) -> str | None:
401 """Return the reason this device needs setup (pairing), or None when it does not."""
402 return "pairing_required" if self.needs_setup else None
403
404 async def get_config_entries(self) -> list[ConfigEntry]:
405 """Return all (provider/player specific) Config Entries for the player."""
406 entries = await super().get_config_entries()
407 entries.extend(await self._get_security_config_entries())
408 entries.extend(self._get_source_autostart_config_entries())
409 return entries
410
411 async def handle_config_action(self, action: str) -> list[ConfigEntry]:
412 """Run an unpair/management action, then re-render the entries."""
413 if self.api.connection is not None:
414 provider = cast("SendspinProvider", self.provider)
415 alert = await self._handle_security_action(provider, action)
416 if alert is not None:
417 self._pending_security_alert = alert
418 return await self.get_config_entries()
419
420 async def run_setup_flow(self, session: SetupSession) -> None:
421 """
422 Drive pairing (or an unpaired-access grant) for this encrypted Sendspin device.
423
424 An unpaired device picks between the offered pair methods and - when the device
425 permits it - playback without pairing; re-running the flow on a paired device
426 verifies its presence via a dynamic PIN. Pairing succeeds as a side effect of
427 the provider pairing calls; the flow finishes with no persisted values. Bridge/
428 web players and unencrypted (legacy) connections have nothing to pair.
429
430 :param session: The setup flow session used to interact with the user.
431 """
432 security = self.api.connection_security
433 if self._is_bridge_or_web_player or security is None:
434 raise AbortFlow("nothing_to_configure")
435 provider = cast("SendspinProvider", self.provider)
436 record = await provider.server_api.pairing_store.record_by_client_id(self.player_id)
437 if security.psk_category is PskCategory.LONG_TERM and record is not None:
438 await self._run_verify_presence_flow(session, provider, record)
439 await session.finish({})
440 return
441 trusted_unpaired = (
442 await provider.server_api.pairing_store.trusted_unpaired(self.player_id) is not None
443 )
444 options = self._pairing_method_options(provider, offer_unpaired=not trusted_unpaired)
445 if not options:
446 raise AbortFlow("no_pair_methods")
447 if len(options) == 1 and options[0] != PAIR_METHOD_UNPAIRED:
448 method = options[0]
449 else:
450 # a lone unpaired-access option still renders the form: granting
451 # unauthenticated playback needs an explicit user choice
452 values = await session.form(
453 [
454 ConfigEntry(
455 key=CONF_PAIRING_METHOD,
456 type=ConfigEntryType.STRING,
457 required=True,
458 options=[ConfigValueOption(value=option) for option in options],
459 expanded_options=True,
460 )
461 ],
462 step_id="select_method",
463 )
464 method = str(values[CONF_PAIRING_METHOD])
465 if method == PAIR_METHOD_UNPAIRED:
466 await provider.set_trusted_unpaired(self.player_id, enabled=True)
467 elif method == PAIR_METHOD_TOKEN:
468 await self._run_token_pairing_flow(session, provider)
469 else:
470 await self._run_pin_pairing_flow(
471 session, provider, static=method == PAIR_METHOD_STATIC_PIN
472 )
473 await session.finish({})
474
475 def _get_source_autostart_config_entries(self) -> list[ConfigEntry]:
476 """Return the line-in autostart entries, for source clients that can sense a signal."""
477 if not self._supports_line_sense():
478 return []
479 # A source that is also a player defaults to playing on itself, which for a
480 # protocol player means the visible player it belongs to.
481 own_target = self.protocol_parent_id or self.player_id
482 options = [
483 ConfigValueOption(SOURCE_AUTOSTART_OFF),
484 *(
485 ConfigValueOption(
486 player.player_id,
487 title=None if player.player_id == own_target else player.display_name,
488 translation_key="this_device" if player.player_id == own_target else None,
489 )
490 for player in sorted(
491 self.mass.players.all_players(False, False),
492 # Lead with the device's own player, so the default sits at the top
493 # of the list rather than alphabetically among every other player.
494 key=lambda player: (
495 player.player_id != own_target,
496 player.display_name.lower(),
497 ),
498 )
499 # Only players that render audio, so lights, displays and other
500 # capture-only clients are not offered as somewhere to play a line-in.
501 if player.type in SOURCE_AUTOSTART_TARGET_TYPES
502 ),
503 ]
504 valid = {option.value for option in options}
505 default = (
506 own_target if "player" in self._negotiated_families() and own_target in valid else None
507 )
508 return [
509 ConfigEntry(
510 key=CONF_SOURCE_AUTOSTART_TARGET,
511 type=ConfigEntryType.STRING,
512 options=options,
513 default_value=default or SOURCE_AUTOSTART_OFF,
514 ),
515 ]
516
517 def _negotiated_families(self) -> set[str]:
518 """Role families the client negotiated, which survive an inactive/unpaired state."""
519 return {role_family(role_id) for role_id in self.api.negotiated_role_ids}
520
521 def _supports_line_sense(self) -> bool:
522 """Whether this client has a source role that reports line-in signal presence."""
523 if "source" not in self._negotiated_families():
524 return False
525 info = self.api.info_or_none
526 support = info.source_support if info else None
527 features = support.features if support else None
528 return bool(features and features.line_sense)
529
530 @property
531 def _is_bridge_or_web_player(self) -> bool:
532 """Whether this is a protocol bridge or built-in web/app player (skips pairing setup)."""
533 return self.player_id.startswith(BRIDGE_PREFIX) or self.is_web_player
534
535 def _subscribe_client_callbacks(self) -> None:
536 """Subscribe to client and group events for the currently bound client."""
537 self.api.disconnect_behaviour = DisconnectBehaviour.UNGROUP
538 self.unsub_event_cb = self.api.add_event_listener(self.event_cb)
539 self.unsub_group_event_cb = self.api.group.add_event_listener(self.group_event_cb)
540
541 def _unsubscribe_client_callbacks(self) -> None:
542 """Unsubscribe any active client and group listeners."""
543 if self.unsub_event_cb is not None:
544 with suppress(Exception):
545 self.unsub_event_cb()
546 self.unsub_event_cb = None
547 if self.unsub_group_event_cb is not None:
548 with suppress(Exception):
549 self.unsub_group_event_cb()
550 self.unsub_group_event_cb = None
551
552 def _refresh_client_info(
553 self,
554 sendspin_client: SendspinClient,
555 hello_payload: ClientHelloPayload | None = None,
556 ) -> None:
557 """
558 Refresh shared player attributes from a Sendspin client hello/info payload.
559
560 :param sendspin_client: The Sendspin client instance.
561 :param hello_payload: Optional hello payload to use instead of client info.
562 """
563 client_info = hello_payload or sendspin_client.info
564 preserved_identifiers = dict(self._attr_device_info.identifiers)
565 self._attr_name = client_info.name
566 if device_info := client_info.device_info:
567 self._attr_device_info = DeviceInfo(
568 model=device_info.product_name or "Unknown model",
569 manufacturer=device_info.manufacturer or "Unknown Manufacturer",
570 software_version=device_info.software_version,
571 )
572 else:
573 self._attr_device_info = DeviceInfo()
574 for id_type, id_value in preserved_identifiers.items():
575 self._attr_device_info.add_identifier(id_type, id_value)
576 # Add player_id as MAC identifier for protocol linking (if it's a valid MAC)
577 # This enables linking with bridged players (e.g., AirPlay via Sendspin bridge)
578 if IdentifierType.MAC_ADDRESS not in self._attr_device_info.identifiers:
579 if _mac := mac_from_bridge_client_id(self.player_id):
580 self._attr_device_info.add_identifier(IdentifierType.MAC_ADDRESS, _mac)
581 elif is_valid_mac_address(self.player_id):
582 self._attr_device_info.add_identifier(IdentifierType.MAC_ADDRESS, self.player_id)
583 self._attr_available = True
584
585 @property
586 def _artwork_role(self) -> ArtworkGroupRole | None:
587 """Get the ArtworkGroupRole for this player's group."""
588 role = self.api.group.group_role("artwork")
589 if isinstance(role, ArtworkGroupRole):
590 return role
591 return None
592
593 @property
594 def _metadata_role(self) -> MetadataGroupRole | None:
595 """Get the MetadataGroupRole for this player's group."""
596 role = self.api.group.group_role("metadata")
597 if isinstance(role, MetadataGroupRole):
598 return role
599 return None
600
601 @property
602 def _color_role(self) -> ColorGroupRole | None:
603 """Get the ColorGroupRole for this player's group."""
604 role = self.api.group.group_role("color")
605 if isinstance(role, ColorGroupRole):
606 return role
607 return None
608
609 @property
610 def _visualizer_role(self) -> VisualizerGroupRole | None:
611 """Get the VisualizerGroupRole for this player's group."""
612 role = self.api.group.group_role("visualizer")
613 if isinstance(role, VisualizerGroupRole):
614 return role
615 return None
616
617 @property
618 def _controller_role(self) -> ControllerGroupRole | None:
619 """Get the ControllerGroupRole for this player's group."""
620 role = self.api.group.group_role("controller")
621 if isinstance(role, ControllerGroupRole):
622 return role
623 return None
624
625 @property
626 def _player_role(self) -> PlayerRoleProtocol | None:
627 """Get the player role for this client (not group role)."""
628 for role in self.api.roles_by_family("player"):
629 if isinstance(role, PlayerRoleProtocol):
630 return role
631 return None
632
633 def _on_group_changed(self, new_group: SendspinGroup) -> None:
634 """
635 Handle group change logic.
636
637 Syncs playback state from the new group and schedules membership sync.
638 Override in subclasses for additional behaviour.
639
640 :param new_group: The new group this player has been assigned to.
641 """
642 # Sync playback state from the new group
643 match new_group.state:
644 case PlaybackStateType.PLAYING:
645 self._attr_playback_state = PlaybackState.PLAYING
646 case PlaybackStateType.PAUSED:
647 self._attr_playback_state = PlaybackState.PAUSED
648 case PlaybackStateType.STOPPED:
649 self._attr_playback_state = PlaybackState.IDLE
650 self._attr_elapsed_time = 0
651 self._attr_elapsed_time_last_updated = time.time()
652 # Update in case this is a newly created group
653 # GroupMemberAddedEvent or GroupMemberRemovedEvent will be fired before this
654 # so group members are already up to date at this point
655 self._schedule_membership_sync(new_group)
656
657 def _on_group_stopped(self) -> None:
658 """Handle the group transitioning to STOPPED state."""
659
660 async def _sync_membership_from_group(self, group: SendspinGroup) -> None:
661 """
662 Sync MA player group membership from authoritative group state.
663
664 :param group: The Sendspin group to sync from.
665 """
666 # Ignore stale events from a group we no longer belong to.
667 if group is not self.api.group:
668 return
669 group_client_ids = [client.client_id for client in group.clients]
670 is_leader = bool(group_client_ids) and group_client_ids[0] == self.player_id
671 desired_group_members = group_client_ids if is_leader else []
672 if self._attr_group_members != desired_group_members:
673 self._attr_group_members = desired_group_members
674 self.update_state()
675
676 def _schedule_membership_sync(self, group: SendspinGroup) -> None:
677 """Schedule a coalesced membership reconciliation task for this player."""
678 self.mass.create_task(
679 self._sync_membership_from_group(group),
680 task_id=f"sendspin_membership_sync_{self.player_id}",
681 abort_existing=True,
682 )
683
684 async def _handle_group_member_removed(self, group: SendspinGroup, client_id: str) -> None:
685 """Handle a group member being removed asynchronously."""
686 if client_id == self.player_id:
687 was_leader = (
688 bool(self._attr_group_members) and self._attr_group_members[0] == self.player_id
689 )
690 if was_leader and len(group.clients) > 0:
691 # We were removed as the group leader but other clients remain.
692 # Don't stop the group -- the PushStream keeps running for
693 # remaining members (playback session was transferred in set_members).
694 self.logger.debug(
695 "Player %s removed as group leader; group continues for remaining members",
696 self.player_id,
697 )
698 elif not was_leader:
699 self.logger.debug(
700 "Player %s removed from group as non-leader; keeping old group playing",
701 self.player_id,
702 )
703 # Clear members for our detached/solo state.
704 self._attr_group_members = []
705 self.update_state()
706 elif client_id in self._attr_group_members:
707 # Someone else left our group
708 self._attr_group_members.remove(client_id)
709 self.update_state()
710
711 async def _get_security_config_entries(self) -> list[ConfigEntry]:
712 """Build the pairing/security section entries."""
713 if self._is_bridge_or_web_player:
714 return []
715 provider = cast("SendspinProvider", self.provider)
716 # surface (and clear) any alert produced by the most recent action
717 alert: AlertText | None = self._pending_security_alert
718 self._pending_security_alert = None
719 status, actions = await self._security_state_entries(provider)
720 entries = [status] if status is not None else []
721 if alert is not None:
722 entries.append(alert_entry(alert))
723 return entries + actions
724
725 async def _security_state_entries(
726 self, provider: SendspinProvider
727 ) -> tuple[ConfigEntry | None, list[ConfigEntry]]:
728 """Return the current security-status entry and the available action entries."""
729 if not self.api.is_connected:
730 # The action dropped the connection (e.g. unpair); the client will reconnect
731 return ConfigEntry(key="security_status_disconnected", type=ConfigEntryType.LABEL), []
732
733 security = self.api.connection_security
734 if security is None:
735 return ConfigEntry(key="security_status_unencrypted", type=ConfigEntryType.ALERT), []
736
737 record = await provider.server_api.pairing_store.record_by_client_id(self.player_id)
738
739 # psk_category is fixed at handshake time: right after an unpair the live connection
740 # still reports LONG_TERM while the record is already gone. The settings view refetches
741 # in exactly that window and will not observe the later reconnect until reopened, so
742 # require the record too or else render the unpaired end state immediately.
743 if security.psk_category is PskCategory.LONG_TERM and record is not None:
744 return (
745 ConfigEntry(key="security_status_paired", type=ConfigEntryType.LABEL),
746 await self._paired_entries(
747 provider, provider.pairing_config_snapshot(self.player_id)
748 ),
749 )
750
751 trusted_unpaired = (
752 await provider.server_api.pairing_store.trusted_unpaired(self.player_id) is not None
753 )
754 if not trusted_unpaired:
755 return None, []
756 return (
757 ConfigEntry(key="security_status_unpaired", type=ConfigEntryType.ALERT),
758 [action_entry(CONF_ACTION_REVOKE_UNPAIRED)],
759 )
760
761 async def _paired_entries(
762 self,
763 provider: SendspinProvider,
764 pairing_config: ManagementResultData | None,
765 ) -> list[ConfigEntry]:
766 """Return the action entries for the paired view (management, unpair)."""
767 entries: list[ConfigEntry] = []
768 if provider.get_management_session(self.player_id) is not None:
769 # Render from the snapshot the enter/patch actions keep fresh; only fetch if it is
770 # unexpectedly empty (e.g. a session opened without a fetch).
771 management_config = pairing_config
772 if management_config is None:
773 try:
774 management_config = await provider.management_get_pairing_config(self.player_id)
775 except SecurityActionError as err:
776 provider.exit_management(self.player_id)
777 entries.append(alert_entry(error_alert(err)))
778 if management_config is not None:
779 entries.extend(self._management_section_entries(management_config))
780 return entries
781 entries.append(action_entry(CONF_ACTION_MANAGEMENT_ENTER))
782 entries.append(action_entry(CONF_ACTION_UNPAIR, advanced=True))
783 return entries
784
785 @staticmethod
786 def _management_section_entries(config: ManagementResultData) -> list[ConfigEntry]:
787 """Return the entries for the open device-management section."""
788 entries: list[ConfigEntry] = [
789 ConfigEntry(key="management_status", type=ConfigEntryType.LABEL)
790 ]
791 if config.unpaired_access is not None:
792 action = (
793 CONF_ACTION_MANAGEMENT_UNPAIRED_DISABLE
794 if config.unpaired_access.enabled
795 else CONF_ACTION_MANAGEMENT_UNPAIRED_ENABLE
796 )
797 entries.append(action_entry(action))
798 entries.extend(
799 SendspinBasePlayer._management_pin_method_entries(
800 config.static_pin,
801 CONF_ACTION_MANAGEMENT_STATIC_PIN_ENABLE,
802 CONF_ACTION_MANAGEMENT_STATIC_PIN_DISABLE,
803 )
804 )
805 entries.extend(
806 SendspinBasePlayer._management_pin_method_entries(
807 config.dynamic_pin,
808 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_ENABLE,
809 CONF_ACTION_MANAGEMENT_DYNAMIC_PIN_DISABLE,
810 )
811 )
812 entries.append(action_entry(CONF_ACTION_MANAGEMENT_EXIT))
813 return entries
814
815 @staticmethod
816 def _management_pin_method_entries(
817 method: PairingMethodConfig | None,
818 enable_action: str,
819 disable_action: str,
820 ) -> list[ConfigEntry]:
821 """Return the toggle for one PIN pairing method, empty if the device lacks it."""
822 if method is None:
823 return []
824 action = disable_action if method.enabled else enable_action
825 return [action_entry(action, advanced=True)]
826
827 async def _handle_security_action(
828 self, provider: SendspinProvider, action: str
829 ) -> AlertText | None:
830 """Execute an unpair/management action, returning a localized alert on failure."""
831 try:
832 if action == CONF_ACTION_UNPAIR:
833 await provider.unpair_client(self.player_id)
834 elif action == CONF_ACTION_REVOKE_UNPAIRED:
835 await provider.set_trusted_unpaired(self.player_id, enabled=False)
836 elif action == CONF_ACTION_MANAGEMENT_ENTER:
837 provider.enter_management(self.player_id)
838 try:
839 await provider.management_get_pairing_config(self.player_id)
840 except SecurityActionError:
841 provider.exit_management(self.player_id)
842 raise
843 elif action == CONF_ACTION_MANAGEMENT_EXIT:
844 provider.exit_management(self.player_id)
845 elif action in _MANAGEMENT_ACTIONS:
846 await provider.management_set_pairing_config(
847 self.player_id, _MANAGEMENT_ACTIONS[action]
848 )
849 except (
850 HandshakeAbortedError,
851 PairingError,
852 TimeoutError,
853 OSError,
854 SecurityActionError,
855 ValueError,
856 ) as err:
857 return error_alert(err)
858 return None
859
860 def _pairing_method_options(
861 self, provider: SendspinProvider, *, offer_unpaired: bool
862 ) -> list[str]:
863 """
864 Return the pairing-method option values the device currently offers for setup.
865
866 :param offer_unpaired: Include the unpaired-playback grant when the device permits it.
867 """
868 info = self.api.info_or_none
869 pairing_config = provider.pairing_config_snapshot(self.player_id)
870 pair_methods = effective_pair_methods(info, pairing_config)
871 usable_pin_methods = {
872 descriptor.method
873 for descriptor in pair_methods
874 if descriptor.method in (PairMethod.DYNAMIC_PIN, PairMethod.STATIC_PIN)
875 }
876 options: list[str] = []
877 if usable_pin_methods:
878 # Static PIN is only a distinct, meaningful choice when both PIN methods are usable;
879 # opposite it the other option names the dynamic PIN rather than PINs in general.
880 both_pin_methods = usable_pin_methods >= {PairMethod.DYNAMIC_PIN, PairMethod.STATIC_PIN}
881 options.append(PAIR_METHOD_DYNAMIC_PIN if both_pin_methods else PAIR_METHOD_PIN)
882 if both_pin_methods:
883 options.append(PAIR_METHOD_STATIC_PIN)
884 if any(descriptor.method is PairMethod.PAIRING_PSK for descriptor in pair_methods):
885 options.append(PAIR_METHOD_TOKEN)
886 if offer_unpaired and effective_unpaired_access(info, pairing_config):
887 options.append(PAIR_METHOD_UNPAIRED)
888 return options
889
890 async def _pairing_succeeded(
891 self, provider: SendspinProvider, pin_session: PinPairingSession
892 ) -> bool:
893 """Whether the attempt finished cleanly (or a long-term pairing record now exists)."""
894 if pin_session.finished and pin_session.error is None:
895 return True
896 if pin_session.verify:
897 return False
898 # a confirm wait that outlived its deadline: the record is the proof of success
899 return (
900 await provider.server_api.pairing_store.record_by_client_id(self.player_id) is not None
901 )
902
903 async def _run_verify_presence_flow(
904 self, session: SetupSession, provider: SendspinProvider, record: ServerPairingRecord
905 ) -> None:
906 """Confirm a paired device's physical presence via its dynamic PIN."""
907 info = self.api.info_or_none
908 pairing_config = provider.pairing_config_snapshot(self.player_id)
909 offers_dynamic_pin = any(
910 descriptor.method is PairMethod.DYNAMIC_PIN
911 for descriptor in effective_pair_methods(info, pairing_config)
912 )
913 # presence proven by a dynamic-PIN pairing itself needs no re-verification
914 if not offers_dynamic_pin or PairMethod.DYNAMIC_PIN in record.pair_methods:
915 raise AbortFlow("already_paired")
916 await self._run_pin_pairing_flow(session, provider, static=False, verify=True)
917
918 async def _run_pin_pairing_flow(
919 self,
920 session: SetupSession,
921 provider: SendspinProvider,
922 *,
923 static: bool,
924 verify: bool = False,
925 ) -> None:
926 """
927 Pair via PIN: the device wait, PIN entry and the retry-in-place loop.
928
929 A retryable failure re-renders the PIN form (start_pin_pairing resumes the session in
930 place); a terminal failure aborts the flow and an expired device wait propagates as a
931 timed_out abort. On any non-success exit the finally tears down a device-side session
932 still in flight - including when the flow is cancelled.
933
934 :param static: Pair with the device's static PIN instead of a dynamic one.
935 :param verify: Verify an already-paired device's presence (dynamic PIN only).
936 """
937 succeeded = False
938 errors: dict[str, str] | None = None
939 try:
940 while True:
941 try:
942 pin_session = await provider.start_pin_pairing(
943 self.player_id, static=static, verify=verify
944 )
945 except SecurityActionError as err:
946 raise AbortFlow(_pairing_abort_reason(err)) from err
947 await self._await_pin_request(session, pin_session)
948 if not pin_session.awaiting_pin:
949 # The attempt ended before a PIN could be entered.
950 if await self._pairing_succeeded(provider, pin_session):
951 succeeded = True
952 return
953 if pin_session.can_retry:
954 errors = {"base": _pin_error_slug(pin_session.error)}
955 continue
956 raise AbortFlow(_pairing_abort_reason(pin_session.error))
957 try:
958 pin_values = await session.form(
959 self._pin_form_entries(provider, pin_session),
960 step_id="verify_pin" if verify else "enter_pin",
961 errors=errors,
962 expires_in=PAIR_PIN_ENTRY_TIMEOUT,
963 )
964 except StepExpiredError:
965 # The countdown mirrors the device's attempt timeout, which aborts the
966 # attempt around now; retry in place rather than dropping the flow.
967 errors = {"base": "pairing_error_timeout"}
968 continue
969 errors = None
970 try:
971 provider.submit_pin(self.player_id, str(pin_values[CONF_PAIRING_PIN]).strip())
972 except SecurityActionError as err:
973 # the session ended underneath us (cancelled/timed out); start afresh
974 errors = {"base": err.alert_key}
975 continue
976 task = pin_session.task
977 if task is not None and not task.done():
978 # Join the pairing task: the step deadline must not cancel it.
979 with suppress(StepExpiredError):
980 await session.progress_until(
981 join_task(task),
982 step_id="confirming",
983 text="confirming",
984 expires_in=PAIR_CONFIRM_TIMEOUT,
985 )
986 if await self._pairing_succeeded(provider, pin_session):
987 succeeded = True
988 return
989 if pin_session.can_retry:
990 errors = {"base": _pin_error_slug(pin_session.error)}
991 continue
992 raise AbortFlow(_pairing_abort_reason(pin_session.error))
993 finally:
994 if succeeded:
995 provider.clear_pin_session(self.player_id)
996 elif provider.get_pin_session(self.player_id) is not None:
997 await provider.cancel_pin_pairing(self.player_id)
998
999 async def _await_pin_request(
1000 self,
1001 session: SetupSession,
1002 pin_session: PinPairingSession,
1003 ) -> None:
1004 """Wait until the device asks for its PIN, showing what it is waiting on."""
1005 if pin_session.awaiting_first_message:
1006 await session.progress_until(
1007 pin_session.wait_first_message(),
1008 step_id="awaiting_device",
1009 text="awaiting_device",
1010 expires_in=SERVER_FIRST_MESSAGE_TIMEOUT_S,
1011 )
1012 if pin_session.awaiting_gesture:
1013 await session.progress_until(
1014 pin_session.wait_pin_request(),
1015 step_id="awaiting_gesture",
1016 text="awaiting_gesture",
1017 expires_in=SERVER_GESTURE_TIMEOUT_S,
1018 )
1019
1020 def _pin_form_entries(
1021 self, provider: SendspinProvider, pin_session: PinPairingSession
1022 ) -> list[ConfigEntry]:
1023 """Return the PIN form fields, hinting how the operator gets the PIN and how long it is."""
1024 entries = self._secret_hint_entries(provider, pin_session.method)
1025 if pin_session.pin_length is not None:
1026 entries.append(
1027 ConfigEntry(
1028 key="dynamic_pin_digits",
1029 type=ConfigEntryType.LABEL,
1030 translation_params=[str(pin_session.pin_length)],
1031 )
1032 )
1033 entries.append(
1034 ConfigEntry(key=CONF_PAIRING_PIN, type=ConfigEntryType.STRING, required=True)
1035 )
1036 return entries
1037
1038 def _secret_hint_entries(
1039 self, provider: SendspinProvider, method: PairMethod
1040 ) -> list[ConfigEntry]:
1041 """Return LABEL entries for the device's hints on obtaining a method's pairing secret."""
1042 descriptor = pair_method_descriptor(
1043 effective_pair_methods(
1044 self.api.info_or_none, provider.pairing_config_snapshot(self.player_id)
1045 ),
1046 method,
1047 )
1048 if descriptor is None:
1049 return []
1050 hints = (
1051 descriptor.out_channels if method is PairMethod.DYNAMIC_PIN else descriptor.locations
1052 )
1053 labels = _SECRET_HINT_LABELS[method]
1054 return [
1055 ConfigEntry(key=key, type=ConfigEntryType.LABEL)
1056 for hint in hints or []
1057 if (key := labels.get(hint)) is not None
1058 ]
1059
1060 async def _run_token_pairing_flow(
1061 self, session: SetupSession, provider: SendspinProvider
1062 ) -> None:
1063 """Pair via a pasted pairing token, re-rendering the form on a recoverable failure."""
1064 errors: dict[str, str] | None = None
1065 while True:
1066 token_values = await session.form(
1067 [
1068 *self._secret_hint_entries(provider, PairMethod.PAIRING_PSK),
1069 ConfigEntry(key=CONF_PAIRING_TOKEN, type=ConfigEntryType.STRING, required=True),
1070 ],
1071 step_id="enter_token",
1072 errors=errors,
1073 )
1074 try:
1075 await provider.pair_with_token(
1076 self.player_id, str(token_values[CONF_PAIRING_TOKEN]).strip()
1077 )
1078 except (
1079 SecurityActionError,
1080 PairingError,
1081 HandshakeAbortedError,
1082 TimeoutError,
1083 OSError,
1084 ) as err:
1085 errors = {"base": error_alert(err).key}
1086 continue
1087 return
1088
1089
1090class SendspinPlayer(SendspinBasePlayer):
1091 """A sendspin audio player in Music Assistant."""
1092
1093 _attr_type = PlayerType.PROTOCOL
1094
1095 last_sent_artwork_url: str | None = None
1096 last_sent_artist_artwork_url: str | None = None
1097 _last_beat_queue_item_id: str | None = None
1098 _last_beat_anchor_us: int | None = None
1099 # Background poller that retries _send_beat_schedule when analysis is
1100 # not yet available. Cancelled on track change / stop / successful push.
1101 _beat_retry_task: asyncio.Task[None] | None = None
1102 # Queue item the current poller is targeting (so a track switch cancels it).
1103 _beat_retry_queue_item_id: str | None = None
1104 playback_session: SendspinPlaybackSession
1105 static_delay_default_ms: int = DEFAULT_SENDSPIN_STATIC_DELAY
1106 # HA media_player entity announcements are relayed to (ESPHome-backed devices)
1107 _hass_announce_entity_id: str | None = None
1108
1109 @property
1110 def requires_flow_mode(self) -> bool:
1111 """Return if the player requires flow mode."""
1112 return True
1113
1114 def __init__(
1115 self,
1116 provider: SendspinProvider,
1117 player_id: str,
1118 initial_hello: ClientHelloPayload | None = None,
1119 ) -> None:
1120 """Initialize the Player."""
1121 super().__init__(provider, player_id, initial_hello)
1122 hello_payload = initial_hello or self.api.info
1123 self.playback_session = SendspinPlaybackSession(self)
1124 self._attr_supported_features = {
1125 PlayerFeature.PLAY_MEDIA,
1126 PlayerFeature.SET_MEMBERS,
1127 PlayerFeature.MULTI_DEVICE_DSP,
1128 }
1129 # Keep volume/mute features of the first registration as a workaround for Cast.
1130 if hello_payload.player_support:
1131 _supported_commands = hello_payload.player_support.supported_commands
1132 if PlayerCommand.VOLUME in _supported_commands:
1133 self._attr_supported_features.add(PlayerFeature.VOLUME_SET)
1134 if PlayerCommand.MUTE in _supported_commands:
1135 self._attr_supported_features.add(PlayerFeature.VOLUME_MUTE)
1136
1137 @property
1138 def supported_sample_rates(self) -> list[tuple[int, int]] | None:
1139 """Return supported (sample_rate, bit_depth) tuples derived from the player role."""
1140 # not cached: the player role / reported formats can change after the
1141 # client (re)registers, so we always re-resolve from the live role state
1142 if (player_role := self._player_role) is not None:
1143 formats = player_role.get_supported_formats() or []
1144 rates = sorted({(fmt.sample_rate, fmt.bit_depth) for fmt in formats})
1145 if rates:
1146 return rates
1147 return [(44100, 16)]
1148
1149 def preserve_control_features_from(self, other: SendspinPlayer) -> None:
1150 """Keep the first registration's volume/mute features as a workaround for Cast."""
1151 for feature in (PlayerFeature.VOLUME_SET, PlayerFeature.VOLUME_MUTE):
1152 if feature in other.supported_features:
1153 self._attr_supported_features.add(feature)
1154 else:
1155 self._attr_supported_features.discard(feature)
1156
1157 def set_hass_announce_entity(self, entity_id: str | None) -> None:
1158 """
1159 Set or clear the Home Assistant entity used to relay announcements.
1160
1161 ESPHome devices support announcements natively (ducking any running
1162 playback), but that capability is only reachable through their Home
1163 Assistant media_player entity; the PLAY_ANNOUNCEMENT feature follows it.
1164
1165 :param entity_id: The HA media_player entity id, or None to clear.
1166 """
1167 self._hass_announce_entity_id = entity_id
1168 if entity_id is not None:
1169 self._attr_supported_features.add(PlayerFeature.PLAY_ANNOUNCEMENT)
1170 else:
1171 self._attr_supported_features.discard(PlayerFeature.PLAY_ANNOUNCEMENT)
1172
1173 async def play_announcement(
1174 self, announcement: PlayerMedia, volume_level: int | None = None
1175 ) -> None:
1176 """Handle (provider native) playback of an announcement on given player."""
1177 entity_id = self._hass_announce_entity_id
1178 hass = cast("HomeAssistantProvider | None", self.mass.get_provider("hass"))
1179 if entity_id is None or hass is None or not hass.available:
1180 raise PlayerCommandFailed(
1181 f"Announcement relay via Home Assistant is not available for {self.display_name}"
1182 )
1183 self.logger.info(
1184 "Playing announcement %s on %s (via Home Assistant)",
1185 announcement.uri,
1186 self.display_name,
1187 )
1188 if volume_level is not None:
1189 # the device's announcement pipeline plays at its own volume;
1190 # the announce volume config entries are hidden for this player
1191 self.logger.debug("Ignoring announcement volume level for player %s", self.display_name)
1192 await hass.play_announcement_on_entity(entity_id, announcement)
1193 self.logger.debug("Playing announcement on %s completed", self.display_name)
1194
1195 def restore_bridge_identity(
1196 self, previous_device_info: DeviceInfo, previous_type: PlayerType
1197 ) -> None:
1198 """Keep bridge players exposed as protocol bridges after client attach updates."""
1199 if previous_type != PlayerType.PROTOCOL:
1200 return
1201 if not (
1202 IdentifierType.CAST_UUID in previous_device_info.identifiers
1203 or IdentifierType.AIRPLAY_ID in previous_device_info.identifiers
1204 ):
1205 return
1206 refreshed_identifiers = dict(self._attr_device_info.identifiers)
1207 self._attr_device_info = DeviceInfo(
1208 model=previous_device_info.model,
1209 manufacturer=previous_device_info.manufacturer,
1210 software_version=self._attr_device_info.software_version,
1211 )
1212 for id_type, id_value in refreshed_identifiers.items():
1213 self._attr_device_info.add_identifier(id_type, id_value)
1214 self.is_web_player = False
1215 self._attr_hidden_by_default = False
1216 self._attr_private = False
1217 self._attr_expose_to_ha_by_default = True
1218 self._attr_type = PlayerType.PROTOCOL
1219
1220 def event_cb(self, client: SendspinClient, event: ClientEvent) -> None:
1221 """Event callback registered to the sendspin client."""
1222 match event:
1223 case VolumeChangedEvent(volume=volume, muted=muted):
1224 self._attr_volume_level = volume
1225 self._attr_volume_muted = muted
1226 self.update_state()
1227 case StaticDelayChangedEvent(static_delay_ms=delay_ms):
1228 self.logger.debug("Static delay changed to %d ms", delay_ms)
1229 current = self.config.get_value(
1230 CONF_SENDSPIN_STATIC_DELAY, self.static_delay_default_ms
1231 )
1232 if current != delay_ms:
1233 self.mass.config.set_raw_player_config_value(
1234 self.player_id, CONF_SENDSPIN_STATIC_DELAY, delay_ms
1235 )
1236 case _:
1237 super().event_cb(client, event)
1238
1239 def group_event_cb(self, group: SendspinGroup, event: GroupEvent) -> None:
1240 """Event callback registered to the sendspin group this player belongs to."""
1241 # Leader only: a synced follower's self.state.current_media is a reference to
1242 # the leader's PlayerMedia object, so the refresh below would mutate the leader's
1243 # anchor from every follower. The metadata push (also leader-only) is what these
1244 # refreshes exist to serve, so followers have nothing to do here.
1245 is_resume = (
1246 isinstance(event, GroupStateChangedEvent)
1247 and event.state == PlaybackStateType.PLAYING
1248 and self._attr_playback_state == PlaybackState.PAUSED
1249 and self.synced_to is None
1250 )
1251 if is_resume:
1252 # _attr_elapsed_time_last_updated is only advanced by playback.py's commit
1253 # loop, which stops while paused - so it's still anchored to the moment
1254 # playback paused. Fast-forward it now, before update_state() below flips
1255 # playback_state to PLAYING, so corrected_elapsed_time doesn't extrapolate
1256 # across the paused span.
1257 self._attr_elapsed_time_last_updated = time.time()
1258 super().group_event_cb(group, event)
1259 if is_resume and self.state.current_media is not None:
1260 # send_current_media_metadata() (scheduled below) reads self.state.current_media,
1261 # which the queue controller rebuilds from its own cached elapsed-time anchor -
1262 # only refreshed via a 500ms-debounced callback, so it's still stale here even
1263 # after the fix above. Patch this update's snapshot directly so the imminent
1264 # metadata push doesn't race ahead of that debounce with a stale value.
1265 self.state.current_media.elapsed_time_last_updated = time.time()
1266 match event:
1267 case GroupStateChangedEvent(state=state) if self.synced_to is None and state in (
1268 PlaybackStateType.PLAYING,
1269 PlaybackStateType.PAUSED,
1270 ):
1271 # Push progress explicitly: current_media's identity is unchanged across
1272 # pause/resume so update_state() above won't debounce a metadata push
1273 # through the normal media-changed callback.
1274 self.mass.create_task(
1275 self.send_current_media_metadata(),
1276 task_id=f"sendspin_metadata_{self.player_id}",
1277 abort_existing=True,
1278 )
1279 case ControllerEvent() as controller_event:
1280 if self.synced_to is None:
1281 self.mass.create_task(self._handle_controller_event(controller_event))
1282
1283 async def volume_set(self, volume_level: int) -> None:
1284 """Handle VOLUME_SET command on the player."""
1285 roles = self.api.roles_by_family("player")
1286 for role in roles:
1287 role.set_player_volume(volume_level)
1288
1289 async def volume_mute(self, muted: bool) -> None:
1290 """Handle VOLUME MUTE command on the player."""
1291 roles = self.api.roles_by_family("player")
1292 for role in roles:
1293 role.set_player_mute(muted)
1294 # Native clients don't always emit a VolumeChangedEvent in response to a
1295 # mute command, so update our state directly to keep MA in sync.
1296 self._attr_volume_muted = muted
1297 self.update_state()
1298
1299 async def stop(self) -> None:
1300 """Stop command."""
1301 self.logger.debug("Received STOP command on player %s", self.display_name)
1302 self.mark_stop_called()
1303 self._attr_current_media = None
1304 self._attr_playback_state = PlaybackState.IDLE
1305 self._attr_elapsed_time = 0
1306 self._attr_elapsed_time_last_updated = time.time()
1307 self.update_state()
1308 # group.stop() snapshots the live position, which it can only do while the push
1309 # stream is up - cancelling first leaves it re-emitting a stale anchor. Teardown
1310 # goes in finally so a failing group stop can't strand the session, and nothing
1311 # may await between the two: the STOPPED event cancels this session inline, and a
1312 # suspension in between would let that cancel cut pipeline teardown short.
1313 try:
1314 await self.api.group.stop()
1315 finally:
1316 await self.playback_session.cancel("stop command")
1317
1318 async def play_media(self, media: PlayerMedia) -> None:
1319 """Play media command."""
1320 self.logger.debug(
1321 "Received PLAY_MEDIA command on player %s with uri %s", self.display_name, media.uri
1322 )
1323
1324 self._attr_current_media = media
1325 self._attr_elapsed_time = None
1326 self._attr_elapsed_time_last_updated = None
1327
1328 # The spec reserves stream/end for queue-empty, not track changes.
1329 await self.playback_session.cancel("new media requested", keep_stream=True)
1330
1331 # Cast-only: reset future before start() to avoid racing _on_stream_start
1332 # and to cancel any stale pending future from a previous timed-out attempt.
1333 cast_app_ready: asyncio.Future[None] | None = None
1334 if (mgr := self._get_cast_bridge_manager()) and (
1335 bridge := mgr.get_bridge_by_client_id(self.player_id)
1336 ):
1337 cast_app_ready = bridge.reset_cast_app_ready()
1338
1339 await self.playback_session.start(media)
1340 self.update_state()
1341
1342 if cast_app_ready is None:
1343 return
1344 try:
1345 await asyncio.wait_for(asyncio.shield(cast_app_ready), timeout=CAST_APP_READY_TIMEOUT)
1346 except BaseException as exc:
1347 if not cast_app_ready.done():
1348 cast_app_ready.cancel()
1349 # Cancel the playback session so we don't keep streaming to a
1350 # device that never reported ready.
1351 with suppress(Exception):
1352 await self.playback_session.cancel("cast app readiness failed")
1353 if isinstance(exc, TimeoutError):
1354 raise PlayerCommandFailed(
1355 f"Cast app on {self.display_name} did not report ready within 30s",
1356 translation_key="cast_app_not_ready",
1357 translation_owner=self.translation_owner,
1358 translation_args=[self.display_name],
1359 ) from None
1360 raise
1361
1362 async def on_config_updated(self) -> None:
1363 """Handle logic when the PlayerConfig is first loaded or updated."""
1364 await self._apply_preferred_format()
1365 await self._apply_static_delay()
1366
1367 async def set_members(
1368 self,
1369 player_ids_to_add: list[str] | None = None,
1370 player_ids_to_remove: list[str] | None = None,
1371 ) -> None:
1372 """Handle SET_MEMBERS command on the player."""
1373 for player_id in player_ids_to_remove or []:
1374 member_player = self.mass.players.get_player(player_id, True)
1375 member_player = cast("SendspinPlayer", member_player)
1376
1377 # Dynamic leader switch: transfer the active playback session to the
1378 # next remaining group member before removing ourselves from the group.
1379 # This keeps the PushStream alive for the remaining members.
1380 if (
1381 player_id == self.player_id
1382 and self.playback_session.playback_task is not None
1383 and not self.playback_session.playback_task.done()
1384 ):
1385 remaining = [c for c in self.api.group.clients if c.client_id != self.player_id]
1386 if remaining:
1387 new_owner_id = remaining[0].client_id
1388 new_owner = self.mass.players.get_player(new_owner_id)
1389 if isinstance(new_owner, SendspinPlayer):
1390 self.logger.info(
1391 "Transferring playback session to %s for dynamic leader switch",
1392 new_owner.display_name,
1393 )
1394 await self.playback_session.transfer_to(new_owner)
1395 new_owner.playback_session = self.playback_session
1396 self.playback_session = SendspinPlaybackSession(self)
1397
1398 await self.api.group.remove_client(member_player.api)
1399 # Cast-only: reset futures before add so a fatal error on a Cast-bridged
1400 # member (e.g. AudioContext unsupported) raises PlayerCommandFailed.
1401 # Only track readiness while streaming, only then add_client launches the app.
1402 bridge_manager = self._get_cast_bridge_manager()
1403 pending_cast: list[tuple[SendspinPlayer, asyncio.Future[None]]] = []
1404 try:
1405 for player_id in player_ids_to_add or []:
1406 member_player = cast(
1407 "SendspinPlayer", self.mass.players.get_player(player_id, True)
1408 )
1409 if (
1410 self.api.group.has_active_stream
1411 and bridge_manager
1412 and (bridge := bridge_manager.get_bridge_by_client_id(player_id))
1413 ):
1414 pending_cast.append((member_player, bridge.reset_cast_app_ready()))
1415 await self.api.group.add_client(member_player.api)
1416
1417 if pending_cast:
1418 # asyncio.wait leaves the futures untouched: the stuck list below needs
1419 # them intact, and a waiter that adopts them makes asyncio report a member
1420 # failing afterwards to the loop exception handler as well
1421 await asyncio.wait(
1422 [f for _, f in pending_cast],
1423 timeout=CAST_APP_READY_TIMEOUT,
1424 return_when=asyncio.FIRST_EXCEPTION,
1425 )
1426 for _, ready in pending_cast:
1427 if ready.done():
1428 # a member's own failure outranks the readiness timeout
1429 ready.result()
1430 if stuck := [m.display_name for m, f in pending_cast if not f.done()]:
1431 raise PlayerCommandFailed(
1432 f"Cast app on {', '.join(stuck)} did not report ready within 30s",
1433 translation_key="cast_app_members_not_ready",
1434 translation_owner=self.translation_owner,
1435 translation_args=[", ".join(stuck)],
1436 )
1437 except BaseException:
1438 # Roll back Cast members we just added so a failed group operation
1439 # doesn't leave dead members in the Sendspin group.
1440 for member, _ in pending_cast:
1441 with suppress(Exception):
1442 await self.api.group.remove_client(member.api)
1443 raise
1444 finally:
1445 for _, f in pending_cast:
1446 if not f.done():
1447 f.cancel()
1448 # self.group_members will be updated by the group event callback
1449
1450 def on_player_media_updated(self) -> None:
1451 """Handle callback when the current media of the player is updated."""
1452 if self.synced_to is not None:
1453 # Only leader sends metadata
1454 return
1455 self.mass.create_task(
1456 self.send_current_media_metadata(),
1457 task_id=f"sendspin_metadata_{self.player_id}",
1458 abort_existing=True,
1459 )
1460
1461 async def send_current_media_metadata(self) -> None:
1462 """Send the current media metadata to the sendspin group."""
1463 if not self.available:
1464 return
1465 current_media = self.state.current_media
1466 if current_media is None:
1467 await self._clear_current_media_metadata()
1468 return
1469 # check if we are playing a MA queue item
1470 queue_item: QueueItem | None = None
1471 queue: PlayerQueue | None = None
1472 if current_media.source_id and current_media.queue_item_id:
1473 queue = self.mass.player_queues.get(current_media.source_id)
1474 queue_item = self.mass.player_queues.get_item(
1475 current_media.source_id, current_media.queue_item_id
1476 )
1477
1478 # Runs even without a queue item so radio / Spotify Connect streams still get art.
1479 await self._send_album_artwork(current_media)
1480 if queue_item:
1481 await self._send_artist_artwork(queue_item)
1482
1483 track_number: int | None = None
1484 year: int | None = None
1485 album_artist: str | None = None
1486 if queue_item and queue_item.media_item and is_track(queue_item.media_item):
1487 track = queue_item.media_item
1488 track_number = track.track_number or None
1489 album_mapping = track.album
1490 if album_mapping is not None:
1491 year = album_mapping.year
1492 if not isinstance(album_mapping, Album):
1493 # Cheap DB-only lookup, no external API call; None if not in library
1494 result = await self.mass.music.get_library_item_by_prov_id(
1495 MediaType.ALBUM, album_mapping.item_id, album_mapping.provider
1496 )
1497 full_album: Album | None = result if isinstance(result, Album) else None
1498 else:
1499 full_album = album_mapping
1500 if full_album and full_album.artists:
1501 album_artist = full_album.artist_str
1502
1503 track_duration = current_media.duration or 0
1504 if controller_role := self._controller_role:
1505 controller_role.set_seek_max_ms(int(track_duration * 1000) if track_duration else None)
1506 repeat = SendspinRepeatMode.OFF
1507 if queue and queue.repeat_mode == RepeatMode.ALL:
1508 repeat = SendspinRepeatMode.ALL
1509 elif queue and queue.repeat_mode == RepeatMode.ONE:
1510 repeat = SendspinRepeatMode.ONE
1511
1512 shuffle = queue.shuffle_enabled if queue else False
1513 is_playing = self.state.playback_state == PlaybackState.PLAYING
1514 track_progress = self._compute_track_progress_ms(current_media, is_playing=is_playing)
1515
1516 metadata = Metadata(
1517 title=current_media.title,
1518 artist=current_media.artist,
1519 album_artist=album_artist,
1520 album=current_media.album,
1521 artwork_url=current_media.image_url,
1522 year=year,
1523 track=track_number,
1524 track_duration=track_duration * 1000 if track_duration is not None else None,
1525 track_progress=track_progress,
1526 playback_speed=1000 if is_playing else 0,
1527 repeat=repeat,
1528 shuffle=shuffle,
1529 )
1530
1531 # Send metadata to the group
1532 if (metadata_role := self._metadata_role) is not None:
1533 metadata_role.set_metadata(metadata)
1534
1535 self._publish_repeat_shuffle(repeat, shuffle=shuffle)
1536
1537 # Send color palette derived from the cover art (already computed by
1538 # the players controller with the Sendspin defined minimum contrast values).
1539 if (color_role := self._color_role) is not None:
1540 self._send_color_palette(color_role, current_media.palette)
1541
1542 await self._send_beat_schedule(queue, queue_item, track_progress, is_playing)
1543
1544 async def get_config_entries(self) -> list[ConfigEntry]:
1545 """Return all (provider/player specific) Config Entries for the player."""
1546 entries: list[ConfigEntry] = []
1547 # Show alert if this Cast device is known to lack AudioContext support
1548 if self.mass.config.get_raw_player_config_value(
1549 self.player_id, CONF_CAST_AUDIO_UNSUPPORTED
1550 ):
1551 entries.append(
1552 ConfigEntry(
1553 key="cast_audio_unsupported",
1554 type=ConfigEntryType.ALERT,
1555 required=False,
1556 )
1557 )
1558 entries.extend(await super().get_config_entries())
1559 # Build dynamic format options from player's supported formats
1560 player_role = self._player_role
1561 if player_role is not None:
1562 supported_formats = player_role.get_supported_formats()
1563 if supported_formats:
1564 format_options = [
1565 ConfigValueOption(SENDSPIN_FORMAT_AUTOMATIC),
1566 ]
1567 for fmt in supported_formats:
1568 format_options.append(
1569 ConfigValueOption(
1570 format_to_option_value(fmt), title=format_to_display_string(fmt)
1571 )
1572 )
1573 entries.append(
1574 ConfigEntry(
1575 key=CONF_PREFERRED_SENDSPIN_FORMAT,
1576 type=ConfigEntryType.STRING,
1577 category="protocol_generic",
1578 default_value=SENDSPIN_FORMAT_AUTOMATIC,
1579 options=format_options,
1580 advanced=True,
1581 )
1582 )
1583
1584 if (
1585 player_role is not None
1586 and PlayerCommand.SET_STATIC_DELAY in player_role.state_supported_commands
1587 ):
1588 entries.append(
1589 ConfigEntry(
1590 key=CONF_SENDSPIN_STATIC_DELAY,
1591 type=ConfigEntryType.INTEGER,
1592 required=False,
1593 default_value=self.static_delay_default_ms,
1594 range=(0, 5000),
1595 immediate_apply=True,
1596 # Not a advanced option since this will only show up for players where it is likely
1597 # necessary to adjust the delay.
1598 advanced=False,
1599 )
1600 )
1601
1602 if self._hass_announce_entity_id is not None:
1603 # announcements are relayed to the device via Home Assistant,
1604 # which has no volume control for announcements
1605 entries.extend(HIDDEN_ANNOUNCE_VOLUME_CONFIG_ENTRIES)
1606
1607 return entries
1608
1609 async def on_unload(self) -> None:
1610 """Handle logic when the player is unloaded from the Player controller."""
1611 await self.playback_session.close()
1612 await super().on_unload()
1613
1614 def _subscribe_client_callbacks(self) -> None:
1615 """Subscribe to client and group events for the currently bound client."""
1616 super()._subscribe_client_callbacks()
1617 self.api.disconnect_behaviour = DisconnectBehaviour.STOP
1618 if controller_role := self._controller_role:
1619 controller_role.set_supported_commands(SUPPORTED_GROUP_COMMANDS)
1620
1621 def _refresh_client_info(
1622 self,
1623 sendspin_client: SendspinClient,
1624 hello_payload: ClientHelloPayload | None = None,
1625 ) -> None:
1626 """Refresh player attributes from a Sendspin client hello/info payload."""
1627 super()._refresh_client_info(sendspin_client, hello_payload=hello_payload)
1628 client_info = hello_payload or sendspin_client.info
1629 if device_info := client_info.device_info:
1630 # determine if this is a web/app player based on product name or manufacturer
1631 # TODO: make this part of the spec and let clients explicitly report if they
1632 # are a web/app player instead of relying on heuristics
1633 self.is_web_player = (
1634 device_info.product_name
1635 in (
1636 "Web Browser",
1637 "Web Player",
1638 "Mobile Application",
1639 "PWA",
1640 )
1641 or device_info.manufacturer == "Music Assistant"
1642 )
1643 else:
1644 self.is_web_player = False
1645 if client_info.player_support:
1646 for role in sendspin_client.roles_by_family("player"):
1647 volume = role.get_player_volume()
1648 muted = role.get_player_muted()
1649 if volume is not None:
1650 self._attr_volume_level = volume
1651 if muted is not None:
1652 self._attr_volume_muted = muted
1653 if volume is not None or muted is not None:
1654 break
1655 # virtual players are server-owned anchors that follow the same
1656 # hidden/standalone semantics as web players, without relying on the
1657 # device-info heuristics above
1658 is_standalone = self.is_web_player or cast(
1659 "SendspinProvider", self.provider
1660 ).is_virtual_player(self.player_id)
1661 self._attr_expose_to_ha_by_default = not is_standalone
1662 self._attr_hidden_by_default = is_standalone
1663 self._attr_private = is_standalone
1664 # register web/app player as native player type because it doesn't need to be linked
1665 # every web/app player is just a standalone player.
1666 self._attr_type = PlayerType.PLAYER if is_standalone else PlayerType.PROTOCOL
1667
1668 def _on_group_changed(self, new_group: SendspinGroup) -> None:
1669 """Handle group change with controller commands and playback session cancellation."""
1670 if controller_role := self._controller_role:
1671 controller_role.set_supported_commands(SUPPORTED_GROUP_COMMANDS)
1672 # Cancel active playback - push stream belongs to the old group
1673 self.mass.create_task(self.playback_session.cancel("group changed"))
1674 super()._on_group_changed(new_group)
1675
1676 def _on_group_stopped(self) -> None:
1677 """Cancel playback session when group stops and we are the leader."""
1678 if self.synced_to is not None:
1679 return
1680 # Bind the cancel to the session task that is live right now: by the time
1681 # the deferred task below runs, play_media may already have started a fresh
1682 # session, which must not be torn down by this stale group-stopped event.
1683 stale_task = self.playback_session.playback_task
1684 if stale_task is None or stale_task.done():
1685 return
1686 self.mass.create_task(self._cancel_stale_playback_session(stale_task))
1687
1688 async def _cancel_stale_playback_session(self, task: asyncio.Task[None]) -> None:
1689 """Cancel the playback session only if the given task is still the active one."""
1690 if self.playback_session.playback_task is not task:
1691 return
1692 await self.playback_session.cancel("group stopped")
1693
1694 async def _handle_controller_event(self, event: ControllerEvent) -> None:
1695 """Handle a controller event from the ControllerGroupRole."""
1696 queue = self.mass.player_queues.get_active_queue(self.player_id)
1697 match event:
1698 case ControllerPlayEvent():
1699 await self.mass.players.cmd_play(self.player_id)
1700 case ControllerPauseEvent():
1701 await self.mass.players.cmd_pause(self.player_id)
1702 case ControllerStopEvent():
1703 await self.mass.players.cmd_stop(self.player_id)
1704 case ControllerNextEvent():
1705 await self.mass.players.cmd_next_track(self.player_id)
1706 case ControllerPreviousEvent():
1707 await self.mass.players.cmd_previous_track(self.player_id)
1708 case ControllerRepeatEvent(mode=mode) if queue:
1709 match mode:
1710 case SendspinRepeatMode.OFF:
1711 self.mass.player_queues.set_repeat(queue.queue_id, RepeatMode.OFF)
1712 case SendspinRepeatMode.ONE:
1713 self.mass.player_queues.set_repeat(queue.queue_id, RepeatMode.ONE)
1714 case SendspinRepeatMode.ALL:
1715 self.mass.player_queues.set_repeat(queue.queue_id, RepeatMode.ALL)
1716 case ControllerShuffleEvent(shuffle=shuffle) if queue:
1717 await self.mass.player_queues.set_shuffle(queue.queue_id, shuffle_enabled=shuffle)
1718 case ControllerSeekEvent(position_ms=position_ms) if (
1719 queue and queue.current_item and queue.current_item.duration
1720 ):
1721 # Clamp in case track duration changed after we advertised the seek range.
1722 duration_ms = int(queue.current_item.duration * 1000)
1723 await self.mass.player_queues.seek(
1724 queue.queue_id, max(0, min(position_ms, duration_ms)) // 1000
1725 )
1726 case ControllerSeekRelativeEvent(offset_ms=offset_ms) if (
1727 queue and queue.current_item and queue.current_item.duration
1728 ):
1729 # Clamp current position + offset to the 0..duration range.
1730 target_ms = int(queue.corrected_elapsed_time * 1000) + offset_ms
1731 duration_ms = int(queue.current_item.duration * 1000)
1732 await self.mass.player_queues.seek(
1733 queue.queue_id, max(0, min(target_ms, duration_ms)) // 1000
1734 )
1735
1736 async def _sync_membership_from_group(self, group: SendspinGroup) -> None:
1737 """Sync MA/player + playback session membership from authoritative group state."""
1738 # Ignore stale events from a group we no longer belong to.
1739 if group is not self.api.group:
1740 return
1741 group_client_ids = [client.client_id for client in group.clients]
1742 is_leader = bool(group_client_ids) and group_client_ids[0] == self.player_id
1743 desired_group_members = group_client_ids if is_leader else []
1744 desired_session_members = group_client_ids[1:] if is_leader else []
1745 if self._attr_group_members != desired_group_members:
1746 self._attr_group_members = desired_group_members
1747 self.update_state()
1748 # Only use STOP when we actually lead other members.
1749 self.api.disconnect_behaviour = (
1750 DisconnectBehaviour.STOP
1751 if is_leader and len(desired_session_members) > 0
1752 else DisconnectBehaviour.UNGROUP
1753 )
1754 await self.playback_session.sync_members(set(desired_session_members))
1755
1756 def _get_cast_bridge_manager(self) -> SendspinBridgeManager | None:
1757 """Return the Chromecast provider's Sendspin bridge manager, if loaded."""
1758 chromecast_provider = self.mass.get_provider("chromecast")
1759 if chromecast_provider is None:
1760 return None
1761 manager = getattr(chromecast_provider, "bridge_manager", None)
1762 if manager is None:
1763 return None
1764 return cast("SendspinBridgeManager", manager)
1765
1766 async def _apply_preferred_format(self) -> None:
1767 """Read config and set/clear the players preferred format."""
1768 player_role = self._player_role
1769 if player_role is None:
1770 return
1771
1772 config_value = cast(
1773 "str",
1774 self.config.get_value(CONF_PREFERRED_SENDSPIN_FORMAT, SENDSPIN_FORMAT_AUTOMATIC),
1775 )
1776 if config_value == SENDSPIN_FORMAT_AUTOMATIC:
1777 # Automatic mode: clear override and let client decide.
1778 player_role.set_preferred_format(None, None)
1779 return
1780
1781 parsed = option_value_to_format(config_value)
1782 if parsed is None:
1783 self.logger.warning(
1784 "Invalid audio format config value '%s' for player %s",
1785 config_value,
1786 self.display_name,
1787 )
1788 return
1789
1790 codec, audio_format = parsed
1791 if not player_role.set_preferred_format(audio_format, codec):
1792 self.logger.warning(
1793 "Failed to set preferred audio format %s %s for player %s",
1794 codec.name,
1795 audio_format,
1796 self.display_name,
1797 )
1798
1799 async def _apply_static_delay(self) -> None:
1800 """Read config and send set_static_delay command if supported."""
1801 player_role = self._player_role
1802 if player_role is None:
1803 return
1804
1805 config_value = cast(
1806 "int",
1807 self.config.get_value(CONF_SENDSPIN_STATIC_DELAY, self.static_delay_default_ms),
1808 )
1809 player_role.set_static_delay(config_value)
1810
1811 async def _send_album_artwork(self, current_media: PlayerMedia) -> str | None:
1812 """
1813 Send album artwork to the sendspin group.
1814
1815 Args:
1816 current_media: The current player media.
1817 """
1818 # image_url is resolved per-source upstream (radio / Spotify Connect / queue items).
1819 artwork_url = current_media.image_url
1820 if artwork_url != self.last_sent_artwork_url:
1821 self.last_sent_artwork_url = artwork_url
1822 if artwork_url is not None:
1823 # Fetch from the resolved URL so the bytes match artwork_url, even when
1824 # radio now-playing art differs from the queue item's own image.
1825 try:
1826 image_data = await self.mass.metadata.get_thumbnail(
1827 artwork_url, provider="builtin"
1828 )
1829 except MediaNotFoundError:
1830 # artwork file was removed from disk; skip rather than crash the send
1831 image_data = None
1832 if isinstance(image_data, bytes):
1833 # decode through the guard so undecodable art (e.g. SVG) is skipped, not crashed
1834 image = await self._decode_artwork(image_data)
1835 if image is not None and (artwork_role := self._artwork_role) is not None:
1836 await artwork_role.set_album_artwork(image)
1837 elif (artwork_role := self._artwork_role) is not None:
1838 await artwork_role.set_album_artwork(None)
1839
1840 return artwork_url
1841
1842 async def _send_artist_artwork(self, current_item: QueueItem) -> None:
1843 """Send artist artwork to the sendspin group."""
1844 artist_artwork_url: str | None = None
1845
1846 if current_item.media_item is not None and is_track(current_item.media_item):
1847 artists = current_item.media_item.artists
1848 if artists:
1849 primary_artist = artists[0]
1850 # Prefer a full library artist (has reliable up-to-date artwork) over
1851 # the ItemMapping in the queue item, which often has image=None.
1852 result = await self.mass.music.get_library_item_by_prov_id(
1853 MediaType.ARTIST, primary_artist.item_id, primary_artist.provider
1854 )
1855 artist_item = result if isinstance(result, Artist) else None
1856 image = artist_item.image if artist_item is not None else primary_artist.image
1857 if image is not None:
1858 artist_artwork_url = self.mass.metadata.get_image_url(image)
1859
1860 if artist_artwork_url != self.last_sent_artist_artwork_url:
1861 self.last_sent_artist_artwork_url = artist_artwork_url
1862 if artist_artwork_url is not None:
1863 # Fetch bytes from the already-resolved URL to avoid the secondary
1864 # provider lookup that get_image_data_for_item triggers for ItemMappings.
1865 try:
1866 artist_image_data = await self.mass.metadata.get_thumbnail(
1867 artist_artwork_url, provider="builtin"
1868 )
1869 except MediaNotFoundError:
1870 # artwork file was removed from disk; skip rather than crash the send
1871 artist_image_data = None
1872 if isinstance(artist_image_data, bytes):
1873 artist_image = await self._decode_artwork(artist_image_data)
1874 if (
1875 artist_image is not None
1876 and (artwork_role := self._artwork_role) is not None
1877 ):
1878 await artwork_role.set_artist_artwork(artist_image)
1879 elif (artwork_role := self._artwork_role) is not None:
1880 await artwork_role.set_artist_artwork(None)
1881
1882 async def _decode_artwork(self, image_data: bytes) -> Image.Image | None:
1883 """
1884 Decode artwork bytes into a Pillow image, returning None if undecodable.
1885
1886 :param image_data: Raw image bytes to decode.
1887 """
1888
1889 def _open() -> Image.Image:
1890 img = Image.open(BytesIO(image_data))
1891 img.load()
1892 return img
1893
1894 try:
1895 return await asyncio.to_thread(_open)
1896 except OSError as err:
1897 self.logger.debug("Skipping undecodable artwork: %s", err)
1898 return None
1899
1900 async def _clear_current_media_metadata(self) -> None:
1901 """Clear all metadata and artwork from the sendspin group."""
1902 # Stop any in-flight beat-analysis polling task
1903 self._cancel_beat_retry()
1904 if (metadata_role := self._metadata_role) is not None:
1905 metadata_role.set_metadata(Metadata())
1906 if (visualizer_role := self._visualizer_role) is not None:
1907 visualizer_role.clear_beat_schedule()
1908 # Reset to PENDING so beats are re-deferred until the next track's analysis lands.
1909 visualizer_role.set_beat_availability(BeatAvailability.PENDING)
1910 if (artwork_role := self._artwork_role) is not None:
1911 await artwork_role.set_album_artwork(None)
1912 await artwork_role.set_artist_artwork(None)
1913 if (color_role := self._color_role) is not None:
1914 color_role.clear()
1915 if (controller_role := self._controller_role) is not None:
1916 controller_role.set_seek_max_ms(None)
1917 self.last_sent_artwork_url = None
1918 self.last_sent_artist_artwork_url = None
1919 self._last_beat_queue_item_id = None
1920 self._last_beat_anchor_us = None
1921
1922 def _publish_repeat_shuffle(self, repeat: SendspinRepeatMode, *, shuffle: bool) -> None:
1923 """
1924 Push repeat/shuffle to controller state for current-spec clients.
1925
1926 Clients implementing the older spec version still read the copy mirrored
1927 onto metadata state, for now.
1928 """
1929 if (controller_role := self._controller_role) is not None:
1930 controller_role.set_repeat(repeat)
1931 controller_role.set_shuffle(shuffle=shuffle)
1932
1933 def _send_color_palette(
1934 self, color_role: ColorGroupRole, palette: MediaItemPalette | None
1935 ) -> None:
1936 """Push the palette already attached to current_media to the sendspin group."""
1937 if palette is None:
1938 color_role.clear()
1939 return
1940 color_role.set_color(
1941 Color(
1942 background_dark=palette.background_dark,
1943 background_light=palette.background_light,
1944 primary=palette.primary,
1945 accent=palette.accent,
1946 on_dark=palette.on_dark,
1947 on_light=palette.on_light,
1948 )
1949 )
1950
1951 def _compute_track_progress_ms(self, current_media: PlayerMedia, *, is_playing: bool) -> int:
1952 """
1953 Resolve current track position in ms from queue/media elapsed time.
1954
1955 Prefer queue/media elapsed as source of truth. Only interpolate while
1956 actively playing; for paused/idle states keep the last fixed position.
1957 """
1958 elapsed_time: float | None = (
1959 float(current_media.elapsed_time) if current_media.elapsed_time is not None else None
1960 )
1961 if is_playing and current_media.corrected_elapsed_time is not None:
1962 elapsed_time = current_media.corrected_elapsed_time
1963 if elapsed_time is None:
1964 elapsed_time = self.corrected_elapsed_time if is_playing else self.elapsed_time
1965 return max(0, int(elapsed_time * 1000)) if elapsed_time is not None else 0
1966
1967 async def _refresh_beat_schedule(self) -> None:
1968 """
1969 Re-attempt beat hydration only, without re-pushing metadata/artwork.
1970
1971 Lighter than `send_current_media_metadata`: the retry poller uses this so
1972 late-arriving analysis lands without re-running the full pipeline.
1973 """
1974 current_media = self.state.current_media
1975 if current_media is None:
1976 return
1977 queue_item: QueueItem | None = None
1978 queue: PlayerQueue | None = None
1979 if current_media.source_id and current_media.queue_item_id:
1980 queue = self.mass.player_queues.get(current_media.source_id)
1981 queue_item = self.mass.player_queues.get_item(
1982 current_media.source_id, current_media.queue_item_id
1983 )
1984 is_playing = self.state.playback_state == PlaybackState.PLAYING
1985 track_progress = self._compute_track_progress_ms(current_media, is_playing=is_playing)
1986 await self._send_beat_schedule(queue, queue_item, track_progress, is_playing)
1987
1988 @staticmethod
1989 def _flow_track_offset_us(pq_data: PlayerQueueData | None, queue_item: QueueItem) -> int | None:
1990 """
1991 Return the current track's flow-stream start offset (minus file seek), in µs.
1992
1993 Sums the streamed duration of every track committed before the current
1994 one in the queue-flow stream, so beats anchor to this track's start
1995 rather than the first track's. Returns None when the flow log hasn't
1996 recorded this track yet, so the caller falls back to the progress anchor.
1997
1998 A track whose intro was crossfade-trimmed loses its raw seek position
1999 (only the elapsed-inflated value survives), so its anchor can be off by
2000 up to the crossfade duration. Exact handling needs a raw-seek field on
2001 the flow log entry.
2002 """
2003 if pq_data is None or queue_item.streamdetails is None:
2004 return None
2005 log = pq_data.flow_mode_stream_log
2006 if not log or log[-1].queue_item_id != queue_item.queue_item_id:
2007 return None
2008 track_flow_start_s = sum(entry.seconds_streamed or 0.0 for entry in log[:-1])
2009 file_seek_s = float(queue_item.streamdetails.seek_position or 0)
2010 return int((track_flow_start_s - file_seek_s) * 1_000_000)
2011
2012 async def _send_beat_schedule(
2013 self,
2014 queue: PlayerQueue | None,
2015 queue_item: QueueItem | None,
2016 track_progress_ms: int,
2017 is_playing: bool,
2018 ) -> None:
2019 """Hydrate per-track beat timings from audio analysis and push to visualizer."""
2020 visualizer_role = self._visualizer_role
2021 if visualizer_role is None:
2022 return
2023 if not is_playing or queue_item is None or queue_item.streamdetails is None:
2024 visualizer_role.clear_beat_schedule()
2025 self._last_beat_queue_item_id = None
2026 self._last_beat_anchor_us = None
2027 self._cancel_beat_retry()
2028 return
2029 # smart_fades is the only AA provider that emits beats. Without it, no
2030 # beats will ever arrive for this source.
2031 if not any(
2032 p.available and p.domain == "smart_fades"
2033 for p in self.mass.get_providers(ProviderType.AUDIO_ANALYSIS)
2034 ):
2035 visualizer_role.clear_beat_schedule()
2036 visualizer_role.set_beat_availability(BeatAvailability.UNAVAILABLE)
2037 self._last_beat_queue_item_id = None
2038 self._last_beat_anchor_us = None
2039 self._cancel_beat_retry()
2040 return
2041 provider = cast("SendspinProvider", self.provider)
2042 now_us = provider.server_api.clock.now_us()
2043 # Anchor beats to the current track's spot in the flow stream's audio
2044 # timeline. Falls back to the progress-derived anchor until the first
2045 # chunk commits or while the flow log hasn't recorded this track yet.
2046 anchor_us: int | None = None
2047 pq_data = self.mass.player_queues.queue_data_or_none(queue.queue_id) if queue else None
2048 offset_us = self._flow_track_offset_us(pq_data, queue_item)
2049 if offset_us is not None:
2050 anchor_us = self.playback_session.flow_track_anchor_us(offset_us)
2051 if anchor_us is None:
2052 anchor_us = now_us - track_progress_ms * 1000
2053 # Re-push only on track change or seek (anchor jumps beyond natural drift).
2054 if (
2055 queue_item.queue_item_id == self._last_beat_queue_item_id
2056 and self._last_beat_anchor_us is not None
2057 and abs(anchor_us - self._last_beat_anchor_us) < 500_000
2058 ):
2059 return
2060 sd = queue_item.streamdetails
2061 analysis = await self.mass.streams.audio_analysis.get_audio_analysis(
2062 sd.item_id,
2063 sd.provider,
2064 media_type=sd.media_type,
2065 priority=(SMART_FADES_ANALYSIS_DOMAIN,),
2066 )
2067 if analysis is None or analysis.beats is None or len(analysis.beats) == 0:
2068 visualizer_role.clear_beat_schedule()
2069 # Analysis may still be running (offline NN takes ~5-10 s). Kick a
2070 # poller so beats land once available, without waiting for the
2071 # next player media update.
2072 # This could be solved more elegantly with an event instead of this
2073 # poller, but that means changes outside the sendspin provider, which
2074 # is riskier.
2075 self._schedule_beat_retry(queue_item.queue_item_id)
2076 return # don't poison the cache; retry asynchronously
2077 # Analysis is in â no more retries needed.
2078 self._cancel_beat_retry()
2079 downbeats = (
2080 {float(d) for d in analysis.downbeats} if analysis.downbeats is not None else set()
2081 )
2082 beats: list[BeatTiming] = []
2083 for b in analysis.beats:
2084 beat_us = int(anchor_us + float(b) * 1_000_000)
2085 if beat_us < now_us:
2086 continue
2087 beats.append(BeatTiming(timestamp_us=beat_us, is_downbeat=float(b) in downbeats))
2088 visualizer_role.clear_beat_schedule()
2089 if beats:
2090 visualizer_role.append_beat_schedule(beats)
2091 self._last_beat_queue_item_id = queue_item.queue_item_id
2092 self._last_beat_anchor_us = anchor_us
2093
2094 # Initial backoff for the beat-analysis poller. The neural beat tracker
2095 # in smart_fades takes ~5-10 s; retry every 3 s until it lands. Capped so
2096 # tracks that won't ever have analysis don't poll forever.
2097 _BEAT_RETRY_INTERVAL_S: ClassVar[float] = 3.0
2098 _BEAT_RETRY_MAX_ATTEMPTS: ClassVar[int] = 30 # ~90 s of wait
2099
2100 def _schedule_beat_retry(self, queue_item_id: str) -> None:
2101 """
2102 Start the background poller for late-arriving beat analysis.
2103
2104 If a poller is already running for this queue item, no-op.
2105 """
2106 if (
2107 self._beat_retry_task is not None
2108 and not self._beat_retry_task.done()
2109 and self._beat_retry_queue_item_id == queue_item_id
2110 ):
2111 return
2112 self._cancel_beat_retry()
2113 self._beat_retry_queue_item_id = queue_item_id
2114 self._beat_retry_task = asyncio.create_task(self._beat_retry_loop(queue_item_id))
2115
2116 def _cancel_beat_retry(self) -> None:
2117 """Cancel the beat-analysis poller if running."""
2118 if self._beat_retry_task is not None and not self._beat_retry_task.done():
2119 self._beat_retry_task.cancel()
2120 self._beat_retry_task = None
2121 self._beat_retry_queue_item_id = None
2122
2123 async def _beat_retry_loop(self, queue_item_id: str) -> None:
2124 """Retry beat-schedule hydration until beats land or the track changes."""
2125 try:
2126 for _ in range(self._BEAT_RETRY_MAX_ATTEMPTS):
2127 await asyncio.sleep(self._BEAT_RETRY_INTERVAL_S)
2128 if self._beat_retry_queue_item_id != queue_item_id:
2129 return # superseded by another poller
2130 current = self.current_media
2131 if current is None or current.queue_item_id != queue_item_id:
2132 return # track changed
2133 if self._last_beat_queue_item_id == queue_item_id:
2134 return # beats were pushed via some other path
2135 # Re-attempt beat hydration only; _send_beat_schedule will push
2136 # beats now or schedule another retry.
2137 try:
2138 await self._refresh_beat_schedule()
2139 except Exception:
2140 self.logger.exception("Beat-schedule retry failed for %s", queue_item_id)
2141 continue
2142 if self._last_beat_queue_item_id == queue_item_id:
2143 return
2144 # Cap exhausted without beats landing. Flip the visualizer to
2145 # UNAVAILABLE so clients (Hue, web) stop waiting and the peak
2146 # walker / static palette path takes over for this track.
2147 if (
2148 self._beat_retry_queue_item_id == queue_item_id
2149 and (current := self.current_media) is not None
2150 and current.queue_item_id == queue_item_id
2151 and (visualizer_role := self._visualizer_role) is not None
2152 ):
2153 visualizer_role.set_beat_availability(BeatAvailability.UNAVAILABLE)
2154 except asyncio.CancelledError:
2155 return
2156 finally:
2157 if self._beat_retry_queue_item_id == queue_item_id:
2158 self._beat_retry_queue_item_id = None
2159
2160
2161class SendspinVisualizerPlayer(SendspinBasePlayer):
2162 """A non-audio Sendspin player for visualizer/lighting devices."""
2163
2164 _attr_type = PlayerType.VISUALIZER
2165 _attr_hidden_by_default = True
2166 _attr_expose_to_ha_by_default = False
2167
2168 def __init__(
2169 self,
2170 provider: SendspinProvider,
2171 player_id: str,
2172 initial_hello: ClientHelloPayload | None = None,
2173 ) -> None:
2174 """
2175 Initialize the visualizer player.
2176
2177 :param provider: The Sendspin provider instance.
2178 :param player_id: The unique player identifier.
2179 :param initial_hello: Optional hello payload from the client.
2180 """
2181 super().__init__(provider, player_id, initial_hello)
2182 self._attr_supported_features = {PlayerFeature.SET_MEMBERS}
2183
2184 async def set_members(
2185 self,
2186 player_ids_to_add: list[str] | None = None,
2187 player_ids_to_remove: list[str] | None = None,
2188 ) -> None:
2189 """Handle SET_MEMBERS command for the visualizer player."""
2190 for player_id in player_ids_to_remove or []:
2191 member = self.mass.players.get_player(player_id, True)
2192 if isinstance(member, SendspinBasePlayer):
2193 await self.api.group.remove_client(member.api)
2194 for player_id in player_ids_to_add or []:
2195 member = self.mass.players.get_player(player_id, True)
2196 if isinstance(member, SendspinBasePlayer):
2197 await self.api.group.add_client(member.api)
2198
2199
2200class SendspinSourcePlayer(SendspinBasePlayer):
2201 """
2202 A capture-only Sendspin player for clients that just feed audio in.
2203
2204 Renders nothing and is never a playback or grouping target. It exists so a
2205 source-only device still has a settings page for pairing, enabling and the
2206 line-in autostart target. The sendspin_source plugin exposes the audio itself.
2207 """
2208
2209 _attr_type = PlayerType.UNKNOWN
2210 _attr_hidden_by_default = True
2211 _attr_private = True
2212 _attr_expose_to_ha_by_default = False
2213