/
/
/
1"""
2Base class/model for a Player within Music Assistant.
3
4All providerspecific players should inherit from this class and implement the required methods.
5
6Note that this is NOT the final state of the player,
7as it may be overridden by (sync)group memberships, configuration options, or other factors.
8This final state will be calculated and snapshotted in the PlayerState dataclass,
9which is what is also what is sent over the API.
10The final active source can be retrieved by using the 'state' property.
11"""
12
13from __future__ import annotations
14
15import asyncio
16import builtins
17import time
18from abc import ABC
19from collections.abc import Callable
20from dataclasses import dataclass
21from typing import TYPE_CHECKING, Any, TypeVar, cast, final, overload
22
23from music_assistant_models.config_entries import MULTI_VALUE_SPLITTER, ConfigValueType
24from music_assistant_models.constants import (
25 EXTRA_ATTRIBUTES_TYPES,
26 PLAYER_CONTROL_FAKE,
27 PLAYER_CONTROL_NATIVE,
28 PLAYER_CONTROL_NONE,
29)
30from music_assistant_models.enums import MediaType, PlaybackState, PlayerFeature, PlayerType
31from music_assistant_models.errors import ActionUnavailable, UnsupportedFeaturedException
32from music_assistant_models.player import (
33 DeviceInfo,
34 OutputProtocol,
35 PlayerMedia,
36 PlayerOption,
37 PlayerOptionValueType,
38 PlayerSoundMode,
39 PlayerSource,
40)
41from music_assistant_models.player import Player as PlayerState
42from music_assistant_models.unique_list import UniqueList
43from propcache import under_cached_property as cached_property
44
45from music_assistant.constants import (
46 ACTIVE_PROTOCOL_FEATURES,
47 ATTR_FAKE_MUTE,
48 ATTR_FAKE_POWER,
49 ATTR_FAKE_VOLUME,
50 CONF_ENTRY_PLAYER_ICON,
51 CONF_EXPOSE_PLAYER_TO_HA,
52 CONF_FLOW_MODE,
53 CONF_HIDE_IN_UI,
54 CONF_LINKED_PROTOCOL_IDS,
55 CONF_MUTE_CONTROL,
56 CONF_PLAYERS,
57 CONF_POWER_CONTROL,
58 CONF_PREFERRED_OUTPUT_PROTOCOL,
59 CONF_SAMPLE_RATES,
60 CONF_UNDERLYING_PLAYER_ID,
61 CONF_VOLUME_CONTROL,
62 EXTERNAL_SOURCES,
63 PLAYER_CONTROL_PROTOCOL,
64 PROTOCOL_FEATURES,
65 PROTOCOL_PRIORITY,
66)
67from music_assistant.helpers.player import get_default_player_icon
68from music_assistant.helpers.util import html_to_markdown
69
70if TYPE_CHECKING:
71 from music_assistant_models.config_entries import (
72 ConfigActionResult,
73 ConfigEntry,
74 PlayerConfig,
75 )
76 from music_assistant_models.media_items import MediaItemPalette
77 from music_assistant_models.player_queue import PlayerQueue
78
79 from .player_provider import PlayerProvider
80 from .setup_flow import SetupSession
81
82# TypeVar for config value type inference
83_ConfigValueT = TypeVar("_ConfigValueT", bound=ConfigValueType)
84
85
86def _clamp_elapsed_time(elapsed_time: float | None) -> float | None:
87 """Return elapsed_time clamped to a non-negative value."""
88 return max(0.0, elapsed_time) if elapsed_time is not None else None
89
90
91def _resolve_position(
92 primary: int | None,
93 primary_last_updated: float | None,
94 fallback: float | None,
95 fallback_last_updated: float | None,
96) -> tuple[int | None, float | None]:
97 """
98 Return the (elapsed_time, elapsed_time_last_updated) pair to report for a media item.
99
100 :param primary: Position reported by the media itself, preferred when set.
101 :param primary_last_updated: Timestamp belonging to the primary position.
102 :param fallback: Position to report when the media has none of its own.
103 :param fallback_last_updated: Timestamp belonging to the fallback position.
104 """
105 # a position is only meaningful together with the timestamp it was taken at,
106 # so both values always come from the same source - never a mix of the two
107 if primary is not None:
108 return primary, primary_last_updated
109 if fallback is not None:
110 return int(fallback), fallback_last_updated
111 return None, None
112
113
114# corrected-position jumps larger than this (in seconds) are treated as a discrete
115# position change (seek/buffer correction) instead of regular playback progression
116POSITION_JUMP_THRESHOLD = 1.0
117
118# Changes to any of these state keys fire the (debounced) on_player_media_updated
119# callback. The palette is included because it resolves asynchronously (shortly
120# after a track change) and players push it to their device from the callback.
121MEDIA_IDENTITY_KEYS = frozenset(
122 {
123 "current_media",
124 "current_media.uri",
125 "current_media.title",
126 "current_media.source_id",
127 "current_media.queue_item_id",
128 "current_media.image_url",
129 "current_media.duration",
130 "current_media.palette",
131 }
132)
133
134# config-derived cached properties (propcache keys in Player._cache); these are
135# only invalidated by set_config, all other cached properties (including those
136# defined by player implementations) are invalidated on every update_state call
137_CONFIG_CACHED_PROPS = frozenset({"hide_in_ui", "expose_to_ha"})
138
139
140@dataclass(frozen=True, slots=True)
141class LinkedOutputProtocol:
142 """
143 A protocol player linked to a parent player.
144
145 Records the link itself (which protocol player, on which domain, how preferred)
146 and nothing about its current state: whether the protocol can actually be reached
147 right now is answered by Player.output_protocols / Player.playback_domains, which
148 resolve it from the live protocol player on every read.
149
150 :param output_protocol_id: player_id of the linked protocol player.
151 :param protocol_domain: Domain of the protocol, e.g. "airplay" or "dlna".
152 :param priority: Selection preference, lower is more preferred.
153 :param derived_from: output_protocol_id of the base output this transport runs on
154 top of ("native" when it rides on the parent player itself), if any.
155 """
156
157 output_protocol_id: str
158 protocol_domain: str
159 priority: int = 100
160 derived_from: str | None = None
161
162
163def _reconcile_position_anchor(
164 prev_position: float | None,
165 prev_timestamp: float | None,
166 new_position: float | None,
167 new_timestamp: float | None,
168 prev_playing: bool,
169 new_playing: bool,
170 force_adopt: bool = False,
171) -> tuple[float | None, float | None, bool]:
172 """
173 Reconcile a playback position anchor (position + timestamp pair) with its predecessor.
174
175 The anchor is a value that only changes on discrete events: regular playback
176 progression extrapolates to (nearly) the same corrected position as the previous
177 anchor and therefore keeps the previous anchor, so steady playback yields no
178 state change at all. The anchor is only adopted when the corrected position
179 jumped more than POSITION_JUMP_THRESHOLD (seek/buffer correction) or when
180 force_adopt is set.
181
182 :param prev_position: Position of the previous anchor.
183 :param prev_timestamp: Timestamp of the previous anchor.
184 :param new_position: Position of the candidate anchor.
185 :param new_timestamp: Timestamp of the candidate anchor.
186 :param prev_playing: Whether the player was playing at the previous anchor.
187 :param new_playing: Whether the player is playing at the candidate anchor.
188 :param force_adopt: Always adopt the candidate anchor (still reports jumps).
189
190 Returns a (position, timestamp, jumped) tuple where jumped indicates a
191 corrected-position discontinuity larger than the threshold.
192 """
193 if (
194 not isinstance(prev_position, int | float)
195 or not isinstance(prev_timestamp, int | float)
196 or not isinstance(new_position, int | float)
197 or not isinstance(new_timestamp, int | float)
198 ):
199 # incomplete (or non-numeric) anchor data: adopt the candidate as-is
200 return new_position, new_timestamp, False
201 now = time.time()
202 # a position anchor only advances (extrapolates) while playing
203 prev_corrected = prev_position + (now - prev_timestamp) if prev_playing else prev_position
204 new_corrected = new_position + (now - new_timestamp) if new_playing else new_position
205 jumped = abs(prev_corrected - new_corrected) > POSITION_JUMP_THRESHOLD
206 if force_adopt or jumped:
207 return new_position, new_timestamp, jumped
208 return prev_position, prev_timestamp, False
209
210
211def _anchor_moved(
212 prev_anchor: tuple[Any, Any] | None,
213 new_anchor: tuple[Any, Any] | None,
214 prev_playing: bool,
215 new_playing: bool,
216) -> bool:
217 """Return whether a position anchor pair moved significantly since its predecessor."""
218 if prev_anchor is None or new_anchor is None:
219 return prev_anchor != new_anchor
220 prev_position, prev_timestamp = prev_anchor
221 new_position, new_timestamp = new_anchor
222 if (
223 not isinstance(prev_position, int | float)
224 or not isinstance(prev_timestamp, int | float)
225 or not isinstance(new_position, int | float)
226 or not isinstance(new_timestamp, int | float)
227 ):
228 # incomplete anchor data can not extrapolate: any change counts as moved
229 return prev_anchor != new_anchor
230 _, _, jumped = _reconcile_position_anchor(
231 prev_position, prev_timestamp, new_position, new_timestamp, prev_playing, new_playing
232 )
233 return jumped
234
235
236def _freeze(value: Any) -> Any:
237 """Return an immutable snapshot of a (serializable) attribute value."""
238 if isinstance(value, dict):
239 return tuple(sorted((key, _freeze(subvalue)) for key, subvalue in value.items()))
240 if isinstance(value, set | frozenset):
241 return frozenset(_freeze(item) for item in value)
242 if isinstance(value, list | tuple):
243 return tuple(_freeze(item) for item in value)
244 return value
245
246
247def _media_fingerprint(fingerprint: dict[str, Any], prefix: str, media: PlayerMedia) -> None:
248 """Add the leaf values of a PlayerMedia to a state fingerprint."""
249 fingerprint[f"{prefix}.uri"] = media.uri
250 fingerprint[f"{prefix}.media_type"] = media.media_type
251 fingerprint[f"{prefix}.title"] = media.title
252 fingerprint[f"{prefix}.artist"] = media.artist
253 fingerprint[f"{prefix}.album"] = media.album
254 fingerprint[f"{prefix}.album_artist"] = media.album_artist
255 fingerprint[f"{prefix}.image_url"] = media.image_url
256 fingerprint[f"{prefix}.duration"] = media.duration
257 fingerprint[f"{prefix}.source_id"] = media.source_id
258 fingerprint[f"{prefix}.queue_item_id"] = media.queue_item_id
259 fingerprint[f"{prefix}.elapsed_time"] = media.elapsed_time
260 fingerprint[f"{prefix}.elapsed_time_last_updated"] = media.elapsed_time_last_updated
261 # the palette object is carried/reused as-is until the image changes,
262 # so object identity suffices to detect a (re)resolved palette
263 fingerprint[f"{prefix}.palette"] = id(media.palette) if media.palette is not None else None
264 fingerprint[f"{prefix}.custom_data"] = (
265 _freeze(media.custom_data) if media.custom_data is not None else None
266 )
267
268
269def _state_fingerprint(state: PlayerState) -> dict[str, Any]:
270 """
271 Collect a flat fingerprint of all event-relevant leaf values of a PlayerState.
272
273 Used to detect changes between state calculations without deepcopying the
274 previous state graph or recursively diffing dataclasses: the fingerprint
275 holds only immutable snapshots, so it stays valid even for values the state
276 references live (extra_attributes, device_info).
277 """
278 fingerprint: dict[str, Any] = {
279 "player_id": state.player_id,
280 "provider": state.provider,
281 "type": state.type,
282 "name": state.name,
283 "available": state.available,
284 "playback_state": state.playback_state,
285 # NOTE: the player's own elapsed_time/elapsed_time_last_updated are
286 # deliberately absent: current_media holds the final calculated position
287 # and is the only position that is event-relevant
288 "powered": state.powered,
289 "volume_level": state.volume_level,
290 "volume_muted": state.volume_muted,
291 "group_members": tuple(state.group_members),
292 "static_group_members": tuple(state.static_group_members),
293 "can_group_with": frozenset(state.can_group_with),
294 "synced_to": state.synced_to,
295 "active_sound_mode": state.active_sound_mode,
296 "active_source": state.active_source,
297 "active_group": state.active_group,
298 "enabled": state.enabled,
299 "hide_in_ui": state.hide_in_ui,
300 "expose_to_ha": state.expose_to_ha,
301 "icon": state.icon,
302 "group_volume": state.group_volume,
303 "group_volume_muted": state.group_volume_muted,
304 "power_control": state.power_control,
305 "volume_control": state.volume_control,
306 "mute_control": state.mute_control,
307 "active_output_protocol": state.active_output_protocol,
308 "needs_setup": state.needs_setup,
309 "setup_reason": state.setup_reason,
310 "has_setup_flow": state.has_setup_flow,
311 "sleep_timer_expires_at": state.sleep_timer_expires_at,
312 "supported_features": frozenset(state.supported_features),
313 "sound_mode_list": tuple((m.id, m.name, m.passive) for m in state.sound_mode_list),
314 "options": tuple((o.key, o.value, o.read_only) for o in state.options),
315 "source_list": tuple(
316 (s.id, s.name, s.passive, s.can_play_pause, s.can_seek, s.can_next_previous)
317 for s in state.source_list
318 ),
319 "output_protocols": tuple(
320 (
321 o.output_protocol_id,
322 o.name,
323 o.protocol_domain,
324 o.is_native,
325 o.priority,
326 o.available,
327 o.derived_from,
328 )
329 for o in state.output_protocols
330 ),
331 "device_info.model": state.device_info.model,
332 "device_info.manufacturer": state.device_info.manufacturer,
333 "device_info.software_version": state.device_info.software_version,
334 "device_info.model_id": state.device_info.model_id,
335 "device_info.manufacturer_id": state.device_info.manufacturer_id,
336 "device_info.identifiers": tuple(sorted(state.device_info.identifiers.items())),
337 "current_media": state.current_media is not None,
338 }
339 for key, value in state.extra_attributes.items():
340 if key in ("seq_no", "last_poll"):
341 # noisy bookkeeping values, not relevant for the state
342 continue
343 fingerprint[f"extra_attributes.{key}"] = _freeze(value)
344 if state.current_media is not None:
345 _media_fingerprint(fingerprint, "current_media", state.current_media)
346 return fingerprint
347
348
349class Player(ABC):
350 """
351 Base representation of a Player within the Music Assistant Server.
352
353 Player Provider implementations should inherit from this base model.
354 """
355
356 _attr_type: PlayerType = PlayerType.PLAYER
357 _attr_supported_features: set[PlayerFeature]
358 _attr_group_members: list[str]
359 _attr_static_group_members: list[str]
360 _attr_device_info: DeviceInfo
361 _attr_can_group_with: set[str]
362 _attr_source_list: list[PlayerSource]
363 _attr_sound_mode_list: list[PlayerSoundMode]
364 _attr_options: list[PlayerOption]
365 _attr_available: bool = True
366 _attr_name: str | None = None
367 _attr_powered: bool | None = None
368 _attr_playback_state: PlaybackState = PlaybackState.IDLE
369 _attr_volume_level: int | None = None
370 _attr_volume_muted: bool | None = None
371 _attr_elapsed_time: float | None = None
372 _attr_elapsed_time_last_updated: float | None = None
373 _attr_active_source: str | None = None
374 _attr_active_sound_mode: str | None = None
375 _attr_current_media: PlayerMedia | None = None
376 # Palette for the image currently shown, resolved asynchronously from the
377 # cache controller and carried here so the (synchronous) state serialization
378 # can read it back without blocking. See set_resolved_palette.
379 _attr_current_palette: MediaItemPalette | None = None
380 _attr_current_palette_url: str | None = None
381 _attr_needs_poll: bool = False
382 _attr_poll_interval: int = 30
383 _attr_hidden_by_default: bool = False
384 _attr_expose_to_ha_by_default: bool = True
385 _attr_enabled_by_default: bool = True
386 _attr_needs_setup: bool = False
387 _attr_setup_reason: str | None = None
388 _attr_supported_sample_rates: list[tuple[int, int]] | None = None
389 _attr_underlying_player_id: str | None = None
390
391 def __init__(self, provider: PlayerProvider, player_id: str) -> None:
392 """Initialize the Player."""
393 # set mass as public variable
394 self.mass = provider.mass
395 self.logger = provider.logger
396 # initialize mutable attributes
397 self._attr_supported_features = set()
398 self._attr_group_members = []
399 self._attr_static_group_members = []
400 self._attr_device_info = DeviceInfo()
401 self._attr_can_group_with = set()
402 self._attr_source_list = []
403 self._attr_sound_mode_list = []
404 self._attr_options = []
405 # do not override/overwrite these private attributes below!
406 self._cache: dict[str, Any] = {} # storage dict for cached properties
407 self.__attr_linked_protocols: list[LinkedOutputProtocol] = []
408 self.__attr_protocol_parent_id: str | None = None
409 self.__attr_active_output_protocol: str | None = None
410 self._player_id = player_id
411 self._provider = provider
412 self.mass.config.create_default_player_config(
413 player_id, self.provider_id, self.type, self.name, self.enabled_by_default
414 )
415 self._config = self.mass.config.get_base_player_config(player_id, self.provider_id)
416 self._extra_data: dict[str, Any] = {}
417 self._extra_attributes: dict[str, Any] = {}
418 self._on_unload_callbacks: list[Callable[[], None]] = []
419 self.__active_mass_source: str | None = None
420 self.__initialized = asyncio.Event()
421 # Change-tracking internals for update_state:
422 # - state_dirty forces a recalculation (state derived from other
423 # sources changed) - starts True so the first update always calculates
424 # - input_snapshot/input_anchor hold the player's own inputs at the last
425 # calculation, so a no-change update_state call can return immediately
426 # - state_fingerprint holds the flat leaf values of the last calculated
427 # PlayerState, used to determine the changed values without deepcopy
428 self.__state_dirty: bool = True
429 self.__input_snapshot: dict[str, Any] | None = None
430 self.__input_anchor: tuple[tuple[Any, Any], tuple[Any, Any] | None, bool] | None = None
431 self.__state_fingerprint: dict[str, Any] | None = None
432 # only probe synced_to when a provider implementation overrides it with its
433 # own (cheap) state; the base implementation derives it by scanning sibling
434 # players, which is cross-player state covered by mark_state_dirty instead
435 self.__probe_synced_to: bool = type(self).synced_to is not Player.synced_to
436 # The PlayerState is the (snapshotted) final state of the player
437 # after applying any config overrides and other transformations,
438 # such as the display name and player controls.
439 # the state is updated when calling 'update_state' and is what is sent over the API.
440 self._state = PlayerState(
441 player_id=self.player_id,
442 provider=self.provider_id,
443 type=self.type,
444 name=self.display_name,
445 available=self.available,
446 device_info=self.device_info,
447 supported_features=self.supported_features,
448 playback_state=self.playback_state,
449 )
450
451 @property
452 def available(self) -> bool:
453 """Return if the player is available."""
454 return self._attr_available
455
456 @property
457 def type(self) -> PlayerType:
458 """Return the type of the player."""
459 return self._attr_type
460
461 @property
462 def name(self) -> str | None:
463 """Return the name of the player."""
464 return self._attr_name
465
466 @property
467 def supported_features(self) -> set[PlayerFeature]:
468 """Return the supported features of the player."""
469 return self._attr_supported_features
470
471 @property
472 def playback_state(self) -> PlaybackState:
473 """Return the current playback state of the player."""
474 return self._attr_playback_state
475
476 @property
477 def requires_flow_mode(self) -> bool:
478 """Return if the player needs flow mode for (queue) playback."""
479 # Default implementation: True if the player does not support PlayerFeature.ENQUEUE
480 return PlayerFeature.ENQUEUE not in self.supported_features
481
482 @property
483 def device_info(self) -> DeviceInfo:
484 """Return the device info of the player."""
485 return self._attr_device_info
486
487 @property
488 def elapsed_time(self) -> float | None:
489 """Return the elapsed time in (fractional) seconds of the current track (if any)."""
490 return _clamp_elapsed_time(self._attr_elapsed_time)
491
492 @property
493 def elapsed_time_last_updated(self) -> float | None:
494 """
495 Return when the elapsed time was last updated.
496
497 return: The (UTC) timestamp when the elapsed time was last updated,
498 or None if it was never updated (or unknown).
499 """
500 return self._attr_elapsed_time_last_updated
501
502 @property
503 def needs_poll(self) -> bool:
504 """Return if the player needs to be polled for state updates."""
505 return self._attr_needs_poll
506
507 @property
508 def poll_interval(self) -> int:
509 """
510 Return the (dynamic) poll interval for the player.
511
512 Only used if 'needs_poll' is set to True.
513 This should return the interval in seconds.
514 """
515 return self._attr_poll_interval
516
517 @property
518 def hidden_by_default(self) -> bool:
519 """Return if the player should be hidden in the UI by default."""
520 return self._attr_hidden_by_default
521
522 @property
523 def expose_to_ha_by_default(self) -> bool:
524 """Return if the player should be exposed to Home Assistant by default."""
525 return self._attr_expose_to_ha_by_default
526
527 @property
528 def enabled_by_default(self) -> bool:
529 """Return if the player should be enabled by default."""
530 return self._attr_enabled_by_default
531
532 @property
533 def static_group_members(self) -> list[str]:
534 """
535 Return the static group members for a player group.
536
537 For PlayerType.GROUP return the player_ids of members that must/can not be removed by
538 the user. For all other player types return an empty list.
539 """
540 return self._attr_static_group_members
541
542 @property
543 def needs_setup(self) -> bool:
544 """
545 Return if the player needs setup.
546
547 If True, the player needs some sort of (initial) setup before it can be used,
548 such as completing an authentication flow or providing additional configuration.
549 """
550 return self._attr_needs_setup
551
552 @property
553 def setup_reason(self) -> str | None:
554 """
555 Return a short (translatable) slug describing why the player needs setup.
556
557 Only meaningful while ``needs_setup`` is True; surfaced next to the "Setup
558 required" indicator so the UI can explain what to do (e.g. "pairing_required"
559 or "password_required"). Returns None when there is no specific reason.
560 """
561 return self._attr_setup_reason
562
563 @property
564 @final
565 def available_for_playback(self) -> bool:
566 """
567 Return if the player can currently be used to play (or control) audio.
568
569 A device that is reachable but still needs setup - an unpaired AirPlay
570 receiver, for example - can not accept a stream, so it must never be
571 picked as an output protocol or command target.
572 """
573 return self.available and not self.needs_setup
574
575 @property
576 @final
577 def implements_setup_flow(self) -> bool:
578 """Return if this player implements its own interactive setup flow."""
579 return type(self).run_setup_flow is not Player.run_setup_flow
580
581 @property
582 @final
583 def has_setup_flow(self) -> bool:
584 """
585 Return if an interactive setup flow can be started for this player.
586
587 True when the player implements its own setup flow, or when it wraps a
588 (non-native) protocol child player that does. Unlike ``needs_setup`` this stays
589 True once setup completed, so the UI can offer to re-run the flow on demand
590 (e.g. to redo a pairing step that was skipped).
591 """
592 if self.implements_setup_flow:
593 return True
594 for output_protocol in self.output_protocols:
595 if output_protocol.is_native:
596 continue
597 child = self.mass.players.get_player(output_protocol.output_protocol_id)
598 if child is not None and child.implements_setup_flow:
599 return True
600 return False
601
602 @property
603 def powered(self) -> bool | None:
604 """
605 Return if the player is powered on.
606
607 If the player does not support PlayerFeature.POWER,
608 or the state is (currently) unknown, this property may return None.
609 """
610 return self._attr_powered
611
612 @property
613 def volume_level(self) -> int | None:
614 """
615 Return the current volume level (0..100) of the player.
616
617 If the player does not support PlayerFeature.VOLUME_SET,
618 or the state is (currently) unknown, this property may return None.
619 """
620 return self._attr_volume_level
621
622 @property
623 def volume_muted(self) -> bool | None:
624 """
625 Return the current mute state of the player.
626
627 If the player does not support PlayerFeature.VOLUME_MUTE,
628 or the state is (currently) unknown, this property may return None.
629 """
630 return self._attr_volume_muted
631
632 @property
633 def active_source(self) -> str | None:
634 """
635 Return the (id of) the active source of the player.
636
637 Only required if the player supports PlayerFeature.SELECT_SOURCE.
638
639 Set to None if the player is not currently playing a source or
640 the player_id if the player is currently playing a MA queue.
641 """
642 return self._attr_active_source
643
644 @property
645 def group_members(self) -> list[str]:
646 """
647 Return the group members of the player.
648
649 If there are other players synced/grouped with this player,
650 this should return the id's of players synced to this player,
651 and this should include the player's own id (as first item in the list).
652
653 If there are currently no group members, this should return an empty list.
654 """
655 return self._attr_group_members
656
657 @property
658 def live_session_members(self) -> list[str]:
659 """
660 Return the id's of the players that take part in this player's live playback session.
661
662 Defaults to :attr:`group_members`, which is the right answer where grouping and
663 the playback session are the same thing. Providers where the two drift apart
664 (a member the session dropped, one that never managed to join it, or no session
665 at all) should override this and answer from the session itself, so callers can
666 tell actual playback partners from tracked group membership.
667 """
668 return self.group_members
669
670 @property
671 def can_group_with(self) -> set[str]:
672 """
673 Return the id's of players this player can group with.
674
675 This should return set of player_id's this player can group/sync with
676 or just the provider's instance_id if all players can group with each other.
677 """
678 return self._attr_can_group_with
679
680 @property
681 def native_grouping_requires_own_stream(self) -> bool:
682 """
683 Return whether native grouping only works while this player renders its own stream.
684
685 Device-side grouping keeps working whatever feeds the leader, so members can
686 stay natively grouped while the leader streams over another protocol.
687 Grouping that attaches members to the leader's own stream has nothing for
688 them to join once the leader moves to a protocol.
689 """
690 return False
691
692 @property
693 def is_active_session(self) -> bool:
694 """
695 Return whether this group player is currently holding (capturing) its members.
696
697 Used by :meth:`__final_active_group` to decide whether children should be
698 considered "owned" by this group at this moment. Non-group players should
699 always return ``False``. Group implementations should return ``True`` while
700 a session is being formed, while it is actively playing/paused, and during
701 any idle grace period; and ``False`` once the group is fully dormant.
702 """
703 return False
704
705 @property
706 def synced_to(self) -> str | None:
707 """Return the id of the player this player is synced to (sync leader)."""
708 # default implementation, feel free to override if your
709 # provider has a more efficient way to determine this
710 if self.type == PlayerType.GROUP:
711 return None
712 for player in self.mass.players.iter_players(
713 return_unavailable=False,
714 provider_filter=self.provider.instance_id,
715 return_protocol_players=True,
716 ):
717 if player.type == PlayerType.GROUP:
718 continue
719 if self.player_id in player.group_members and player.player_id != self.player_id:
720 return player.player_id
721 return None
722
723 @property
724 def current_media(self) -> PlayerMedia | None:
725 """Return the current media being played by the player."""
726 return self._attr_current_media
727
728 @property
729 def source_list(self) -> list[PlayerSource]:
730 """Return list of available (native) sources for this player."""
731 return self._attr_source_list
732
733 @property
734 def active_sound_mode(self) -> str | None:
735 """Return active sound mode of this player."""
736 return self._attr_active_sound_mode
737
738 @cached_property
739 def sound_mode_list(self) -> UniqueList[PlayerSoundMode]:
740 """Return available PlayerSoundModes for Player."""
741 return UniqueList(self._attr_sound_mode_list)
742
743 @cached_property
744 def options(self) -> UniqueList[PlayerOption]:
745 """Return all PlayerOptions for Player."""
746 return UniqueList(self._attr_options)
747
748 @property
749 def supported_sample_rates(self) -> list[tuple[int, int]] | None:
750 """
751 Return the (sample_rate, bit_depth) pairs this player natively supports.
752
753 Example: [(44100, 16), (48000, 24)]
754
755 Players with a known static set should set ``_attr_supported_sample_rates``.
756 Players whose supported rates depend on runtime state (e.g. group players
757 whose members can change) should override this property.
758
759 Returning ``None`` defers to the user's per-player ``CONF_SAMPLE_RATES``
760 selection — callers should use ``get_supported_sample_rates()`` to get a
761 resolved, non-None list.
762 """
763 return self._attr_supported_sample_rates
764
765 async def power(self, powered: bool) -> None:
766 """
767 Handle POWER command on the player.
768
769 Will only be called if the PlayerFeature.POWER is supported.
770
771 :param powered: bool if player should be powered on or off.
772 """
773 raise NotImplementedError("power needs to be implemented when PlayerFeature.POWER is set")
774
775 async def volume_set(self, volume_level: int) -> None:
776 """
777 Handle VOLUME_SET command on the player.
778
779 Will only be called if the PlayerFeature.VOLUME_SET is supported.
780
781 :param volume_level: volume level (0..100) to set on the player.
782 """
783 raise NotImplementedError(
784 "volume_set needs to be implemented when PlayerFeature.VOLUME_SET is set"
785 )
786
787 async def volume_mute(self, muted: bool) -> None:
788 """
789 Handle VOLUME MUTE command on the player.
790
791 Will only be called if the PlayerFeature.VOLUME_MUTE is supported.
792
793 :param muted: bool if player should be muted.
794 """
795 raise NotImplementedError(
796 "volume_mute needs to be implemented when PlayerFeature.VOLUME_MUTE is set"
797 )
798
799 async def play(self) -> None:
800 """Handle PLAY command on the player."""
801 raise NotImplementedError("play needs to be implemented")
802
803 async def stop(self) -> None:
804 """
805 Handle STOP command on the player.
806
807 Will be called to stop the stream/playback if the player has play_media support.
808 """
809 raise NotImplementedError(
810 "stop needs to be implemented when PlayerFeature.PLAY_MEDIA is set"
811 )
812
813 async def pause(self) -> None:
814 """
815 Handle PAUSE command on the player.
816
817 Will only be called if the player reports PlayerFeature.PAUSE is supported.
818 """
819 raise NotImplementedError("pause needs to be implemented when PlayerFeature.PAUSE is set")
820
821 async def next_track(self) -> None:
822 """
823 Handle NEXT_TRACK command on the player.
824
825 Will only be called if the player reports PlayerFeature.NEXT_PREVIOUS
826 is supported and the player's currently selected source supports it.
827 """
828 raise NotImplementedError(
829 "next_track needs to be implemented when PlayerFeature.NEXT_PREVIOUS is set"
830 )
831
832 async def previous_track(self) -> None:
833 """
834 Handle PREVIOUS_TRACK command on the player.
835
836 Will only be called if the player reports PlayerFeature.NEXT_PREVIOUS
837 is supported and the player's currently selected source supports it.
838 """
839 raise NotImplementedError(
840 "previous_track needs to be implemented when PlayerFeature.NEXT_PREVIOUS is set"
841 )
842
843 async def seek(self, position: int) -> None:
844 """
845 Handle SEEK command on the player.
846
847 Seek to a specific position in the current track.
848 Will only be called if the player reports PlayerFeature.SEEK is
849 supported and the player is NOT currently playing a MA queue.
850
851 :param position: The position to seek to, in seconds.
852 """
853 raise NotImplementedError("seek needs to be implemented when PlayerFeature.SEEK is set")
854
855 async def play_media(
856 self,
857 media: PlayerMedia,
858 ) -> None:
859 """
860 Handle PLAY MEDIA command on given player.
861
862 This is called by the Player controller to start playing Media on the player,
863 which can be a MA queue item/stream or a native source.
864 The provider's own implementation should work out how to handle this request.
865
866 :param media: Details of the item that needs to be played on the player.
867 """
868 raise NotImplementedError(
869 "play_media needs to be implemented when PlayerFeature.PLAY_MEDIA is set"
870 )
871
872 async def on_protocol_playback(
873 self,
874 output_protocol: OutputProtocol,
875 ) -> None:
876 """
877 Handle callback when playback starts on a protocol output.
878
879 Called by the Player Controller after play_media is executed on a protocol player.
880 Allows the native player implementation to perform special logic when protocol
881 playback starts.
882
883 Optional - providers can override to implement protocol-specific logic.
884
885 :param output_protocol: The OutputProtocol object containing protocol details.
886 """
887 return # Optional callback - no-op by default
888
889 async def enqueue_next_media(self, media: PlayerMedia) -> None:
890 """
891 Handle enqueuing of the next (queue) item on the player.
892
893 Called when player reports it started buffering a queue item
894 and when the queue items updated.
895
896 A PlayerProvider implementation is in itself responsible for handling this
897 so that the queue items keep playing until its empty or the player stopped.
898
899 Will only be called if the player reports PlayerFeature.ENQUEUE is
900 supported and the player is currently playing a MA queue.
901
902 This will NOT be called if the end of the queue is reached (and repeat disabled).
903 This will NOT be called if the player is using flow mode to playback the queue.
904
905 :param media: Details of the item that needs to be enqueued on the player.
906 """
907 raise NotImplementedError(
908 "enqueue_next_media needs to be implemented when PlayerFeature.ENQUEUE is set"
909 )
910
911 async def play_announcement(
912 self, announcement: PlayerMedia, volume_level: int | None = None
913 ) -> None:
914 """
915 Handle (native) playback of an announcement on the player.
916
917 Will only be called if the PlayerFeature.PLAY_ANNOUNCEMENT is supported.
918
919 :param announcement: Details of the announcement that needs to be played on the player.
920 :param volume_level: The volume level to play the announcement at (0..100).
921 If not set, the player should use the current volume level.
922 """
923 raise NotImplementedError(
924 "play_announcement needs to be implemented when PlayerFeature.PLAY_ANNOUNCEMENT is set"
925 )
926
927 async def select_source(self, source: str) -> None:
928 """
929 Handle SELECT SOURCE command on the player.
930
931 Will only be called if the PlayerFeature.SELECT_SOURCE is supported.
932
933 :param source: The source(id) to select, as defined in the source_list.
934 """
935 raise NotImplementedError(
936 "select_source needs to be implemented when PlayerFeature.SELECT_SOURCE is set"
937 )
938
939 async def select_sound_mode(self, sound_mode: str) -> None:
940 """
941 Handle SELECT SOUND MODE command on the player.
942
943 Will only be called if the PlayerFeature.SELECT_SOUND_MODE is supported.
944
945 :param source: The sound_mode(id) to select, as defined in the sound_mode_list.
946 """
947 raise NotImplementedError(
948 "select_sound_mode needs to be implemented when PlayerFeature.SELECT_SOUND_MODE is set"
949 )
950
951 async def set_option(self, option_key: str, option_value: PlayerOptionValueType) -> None:
952 """
953 Handle SET_OPTION command on the player.
954
955 Will only be called if the PlayerFeature.OPTIONS is supported.
956
957 :param option_key: The option_key of the PlayerOption
958 :param option_value: The new value of the PlayerOption
959 """
960 raise NotImplementedError(
961 "set_option needs to be implemented when PlayerFeature.Option is set"
962 )
963
964 async def set_members(
965 self,
966 player_ids_to_add: list[str] | None = None,
967 player_ids_to_remove: list[str] | None = None,
968 ) -> None:
969 """
970 Handle SET_MEMBERS command on the player.
971
972 Group or ungroup the given child player(s) to/from this player.
973 Will only be called if the PlayerFeature.SET_MEMBERS is supported.
974
975 :param player_ids_to_add: List of player_id's to add to the group.
976 :param player_ids_to_remove: List of player_id's to remove from the group.
977 """
978 raise NotImplementedError(
979 "set_members needs to be implemented when PlayerFeature.SET_MEMBERS is set"
980 )
981
982 async def poll(self) -> None:
983 """
984 Poll player for state updates.
985
986 This is called by the Player Manager;
987 if the 'needs_poll' property is True.
988 """
989 raise NotImplementedError("poll needs to be implemented when needs_poll is True")
990
991 async def get_config_entries(self) -> list[ConfigEntry]:
992 """
993 Return all (provider/player specific) Config Entries for the player.
994
995 Called only for an existing player: read current values via ``self.config``/
996 ``self.get_config_value`` and capabilities via ``self.supported_features``.
997 To override a default config entry, define an entry with the same key.
998 Include ``ConfigEntryType.ACTION`` entries for one-shot buttons and handle their
999 presses in ``handle_config_action``.
1000 """
1001 return []
1002
1003 async def handle_config_action(
1004 self, action: str
1005 ) -> list[ConfigEntry] | ConfigActionResult | None:
1006 """
1007 Run the one-shot side effect for a pressed action button from this player's config.
1008
1009 Override to run the side effect for each ``ConfigEntryType.ACTION`` entry this
1010 player declares. Return a ``ConfigActionResult`` to report the outcome (a message
1011 to show and/or a url to open), or None when there is nothing to report. Raise to
1012 report failure to the caller. Returning entries re-renders the config form from the
1013 owning player's freshly resolved entries; the returned entries themselves are not
1014 shown, so they serve only as the signal that a re-render is needed.
1015
1016 :param action: The action id of the pressed button (an entry's ``action`` key).
1017 """
1018 raise ActionUnavailable(f"Unknown action: {action}")
1019
1020 async def run_setup_flow(self, session: SetupSession) -> None:
1021 """
1022 Run the interactive setup flow for this player (e.g. pairing).
1023
1024 Override in player implementations that require user interaction to become
1025 usable; players without an override report that there is nothing to set up.
1026
1027 :param session: The setup flow session used to interact with the user.
1028 """
1029 raise NotImplementedError
1030
1031 @overload
1032 def get_config_value(
1033 self, key: str, default: _ConfigValueT, *, return_type: builtins.type[_ConfigValueT] = ...
1034 ) -> _ConfigValueT: ...
1035
1036 @overload
1037 def get_config_value(
1038 self, key: str, default: ConfigValueType = ..., *, return_type: builtins.type[_ConfigValueT]
1039 ) -> _ConfigValueT: ...
1040
1041 @overload
1042 def get_config_value(
1043 self, key: str, default: ConfigValueType = ..., *, return_type: None = ...
1044 ) -> ConfigValueType: ...
1045
1046 def get_config_value(
1047 self,
1048 key: str,
1049 default: ConfigValueType = None,
1050 *,
1051 return_type: builtins.type[_ConfigValueT | ConfigValueType] | None = None,
1052 ) -> _ConfigValueT | ConfigValueType:
1053 """
1054 Return a single config value from this player's active configuration.
1055
1056 Entry defaults are already applied to the active configuration, so the
1057 default is only returned when the key itself is not present.
1058
1059 :param key: The config key to retrieve.
1060 :param default: Value to return when the key is not present in the config.
1061 :param return_type: Optional type hint for type inference (e.g., str, int, bool).
1062 Note: This parameter is used purely for static type checking and does not
1063 perform runtime type validation. Callers are responsible for ensuring the
1064 specified type matches the actual config value type.
1065 """
1066 return self.config.get_value(key, default)
1067
1068 def get_setup_value(self, key: str, default: ConfigValueType = None) -> ConfigValueType:
1069 """
1070 Return a value collected by this player's setup flow (from setup_data).
1071
1072 Encrypted (string) values are decrypted transparently. Reads setup_data only
1073 (no fallback to the config values): player-owned credentials/pairing data live
1074 exclusively in setup_data, with a one-time migration moving any legacy values.
1075
1076 :param key: The setup data key to retrieve.
1077 :param default: Value to return when the key is not present.
1078 """
1079 setup_data = self.mass.config.get(f"{CONF_PLAYERS}/{self.player_id}/setup_data") or {}
1080 if key in setup_data:
1081 value = setup_data[key]
1082 return self.mass.config.decrypt_string(value) if isinstance(value, str) else value
1083 return default
1084
1085 @final
1086 def resolve_output_player(self) -> Player:
1087 """
1088 Return the player that actually renders this player's audio output.
1089
1090 For a player playing via one of its linked output protocols this is the
1091 active protocol player; in all other cases (native output, protocol
1092 players themselves, group players serving their own stream) it is the
1093 player itself.
1094 """
1095 active_protocol = self.active_output_protocol
1096 if (
1097 active_protocol
1098 and active_protocol != "native"
1099 and (protocol_player := self.mass.players.get_player(active_protocol))
1100 ):
1101 return protocol_player
1102 return self
1103
1104 @overload
1105 def get_output_config_value(
1106 self, key: str, default: _ConfigValueT, *, return_type: builtins.type[_ConfigValueT] = ...
1107 ) -> _ConfigValueT: ...
1108
1109 @overload
1110 def get_output_config_value(
1111 self, key: str, default: ConfigValueType = ..., *, return_type: builtins.type[_ConfigValueT]
1112 ) -> _ConfigValueT: ...
1113
1114 @overload
1115 def get_output_config_value(
1116 self, key: str, default: ConfigValueType = ..., *, return_type: None = ...
1117 ) -> ConfigValueType: ...
1118
1119 def get_output_config_value(
1120 self,
1121 key: str,
1122 default: ConfigValueType = None,
1123 *,
1124 return_type: builtins.type[_ConfigValueT | ConfigValueType] | None = None,
1125 ) -> _ConfigValueT | ConfigValueType:
1126 """
1127 Return a config value resolved on the player that renders the audio output.
1128
1129 Audio/output related settings (output codec, http profile, output channels,
1130 sample rates) live on the player(protocol) that actually renders the audio:
1131 the active linked protocol player when outputting via a protocol, otherwise
1132 this player itself. The output player's value (or its provider's entry
1133 default) takes precedence; this player's own value is the fallback for keys
1134 the output player has no entry for.
1135
1136 :param key: The config key to retrieve.
1137 :param default: Value to return when the key is not present in any config.
1138 :param return_type: Optional type hint for type inference (e.g., str, int, bool).
1139 Note: This parameter is used purely for static type checking and does not
1140 perform runtime type validation. Callers are responsible for ensuring the
1141 specified type matches the actual config value type.
1142 """
1143 output_player = self.resolve_output_player()
1144 if output_player is not self and key in output_player.config.values:
1145 return output_player.config.get_value(key, default)
1146 return self.get_config_value(key, default)
1147
1148 async def on_config_updated(self) -> None:
1149 """
1150 Handle logic when the player is loaded or updated.
1151
1152 Override this method in your player implementation if you need
1153 to perform any additional setup logic after the player is registered and
1154 the self.config was loaded, and whenever the config changes.
1155 """
1156 return
1157
1158 async def on_unload(self) -> None:
1159 """Handle logic when the player is unloaded from the Player controller."""
1160 for callback in self._on_unload_callbacks:
1161 try:
1162 callback()
1163 except Exception as err:
1164 self.logger.error(
1165 "Error calling on_unload callback for player %s: %s",
1166 self.player_id,
1167 err,
1168 )
1169
1170 async def group_with(self, target_player_id: str) -> None:
1171 """
1172 Handle GROUP_WITH command on the player.
1173
1174 Group this player to the given syncleader/target.
1175 Will only be called if the PlayerFeature.SET_MEMBERS is supported.
1176
1177 :param target_player: player_id of the target player / sync leader.
1178 """
1179 # convenience helper method
1180 # no need to implement unless your player/provider has an optimized way to execute this
1181 # default implementation will simply call set_members
1182 # to add the target player to the group.
1183 target_player = self.mass.players.get_player(target_player_id, raise_unavailable=True)
1184 assert target_player # for type checking
1185 await target_player.set_members(player_ids_to_add=[self.player_id])
1186
1187 async def ungroup(self) -> None:
1188 """
1189 Handle UNGROUP command on the player.
1190
1191 Remove the player from any (sync)groups it currently is grouped to.
1192 If this player is the sync leader (or group player),
1193 all child's will be ungrouped and the group dissolved.
1194
1195 Will only be called if the PlayerFeature.SET_MEMBERS is supported.
1196 """
1197 # convenience helper method
1198 # no need to implement unless your player/provider has an optimized way to execute this
1199 # default implementation will simply call set_members
1200 if self.synced_to:
1201 if parent_player := self.mass.players.get_player(self.synced_to):
1202 # if this player is synced to another player, remove self from that group
1203 await parent_player.set_members(player_ids_to_remove=[self.player_id])
1204 elif self.group_members:
1205 await self.set_members(player_ids_to_remove=self.group_members)
1206
1207 def on_protocol_player_updated(
1208 self, protocol_player: Player, changed_values: dict[str, tuple[Any, Any]]
1209 ) -> None:
1210 """Handle callback when one of the linked protocol players of the player is updated."""
1211 # optional callback
1212 # default implementation will simply trigger an update for the state of the player
1213 self.mass.players.trigger_player_update(self.player_id)
1214
1215 def on_protocol_parent_updated(
1216 self, protocol_parent: Player, changed_values: dict[str, tuple[Any, Any]]
1217 ) -> None:
1218 """Handle callback when the parent protocol player of the player is updated."""
1219 # optional callback
1220 # default implementation will simply trigger an update for the state of the player
1221 self.mass.players.trigger_player_update(self.player_id)
1222
1223 def on_group_member_updated(
1224 self, member_player: Player, changed_values: dict[str, tuple[Any, Any]]
1225 ) -> None:
1226 """Handle callback when a group member of the group player is updated."""
1227 # optional callback
1228 # default implementation will simply trigger an update for the state of the player
1229 self.mass.players.trigger_player_update(self.player_id)
1230
1231 def on_group_updated(
1232 self, group_player: Player, changed_values: dict[str, tuple[Any, Any]]
1233 ) -> None:
1234 """Handle callback when a group player is updated this player is a member of."""
1235 # optional callback
1236 # default implementation will simply trigger an update for the state of the player
1237 self.mass.players.trigger_player_update(self.player_id)
1238
1239 def on_sync_parent_updated(
1240 self, sync_parent: Player, changed_values: dict[str, tuple[Any, Any]]
1241 ) -> None:
1242 """Handle callback when the sync parent of this player is updated."""
1243 # optional callback
1244 # default implementation will simply trigger an update for the state of the player
1245 self.mass.players.trigger_player_update(self.player_id)
1246
1247 @cached_property
1248 @final
1249 def default_icon(self) -> str:
1250 """Return the default player icon."""
1251 return get_default_player_icon(
1252 self.type,
1253 self.provider.domain,
1254 self.device_info.manufacturer,
1255 self.device_info.model,
1256 )
1257
1258 def on_player_media_updated(self) -> None: # noqa: B027
1259 """Handle callback when the current media of the player is updated."""
1260 # optional callback for players that want to be informed when the final
1261 # current media is updated (after applying group/sync membership logic).
1262 # for instance to update any display information on the physical player.
1263
1264 # DO NOT OVERWRITE BELOW !
1265 # These properties and methods are either managed by core logic or they
1266 # are used to perform a very specific function. Overwriting these may
1267 # produce undesirable effects.
1268
1269 @property
1270 @final
1271 def player_id(self) -> str:
1272 """Return the id of the player."""
1273 return self._player_id
1274
1275 @property
1276 @final
1277 def provider(self) -> PlayerProvider:
1278 """Return the provider of the player."""
1279 return self._provider
1280
1281 @property
1282 @final
1283 def provider_id(self) -> str:
1284 """Return the provider (instance) id of the player."""
1285 return self._provider.instance_id
1286
1287 @property
1288 @final
1289 def translation_owner(self) -> str:
1290 """Return the translation owner namespace ("provider.<domain>") of the player's provider."""
1291 return self._provider.translation_owner
1292
1293 @property
1294 @final
1295 def config(self) -> PlayerConfig:
1296 """Return the config of the player."""
1297 return self._config
1298
1299 @property
1300 @final
1301 def extra_attributes(self) -> dict[str, EXTRA_ATTRIBUTES_TYPES]:
1302 """
1303 Return the extra attributes of the player.
1304
1305 This is a dict that can be used to pass any extra (serializable)
1306 attributes over the API, to be consumed by the UI (or another APi client, such as HA).
1307 This is not persisted and not used or validated by the core logic.
1308 """
1309 return self._extra_attributes
1310
1311 @property
1312 @final
1313 def extra_data(self) -> dict[str, Any]:
1314 """
1315 Return the extra data of the player.
1316
1317 This is a dict that can be used to store any extra data
1318 that is not part of the player state or config.
1319 This is not persisted and not exposed on the API.
1320 """
1321 return self._extra_data
1322
1323 @cached_property
1324 @final
1325 def display_name(self) -> str:
1326 """Return the (FINAL) display name of the player."""
1327 if custom_name := self._config.name:
1328 # always prefer the custom name over the default name
1329 return custom_name
1330 return self.name or self._config.default_name or self.player_id
1331
1332 @cached_property
1333 @final
1334 def enabled(self) -> bool:
1335 """Return if the player is enabled."""
1336 return self._config.enabled
1337
1338 @final
1339 def get_supported_sample_rates(self) -> list[tuple[int, int]]:
1340 """
1341 Return the resolved (sample_rate, bit_depth) pairs the player can play.
1342
1343 Honors, in order:
1344 1. The ``supported_sample_rates`` property (declarative or overridden)
1345 2. The user's ``CONF_SAMPLE_RATES`` selection
1346 3. A safe ``[(44100, 16)]`` fallback
1347 """
1348 if (declared := self.supported_sample_rates) is not None:
1349 return declared
1350 config_rates: list[tuple[int, int]] = []
1351 if conf := self.config.get_value(CONF_SAMPLE_RATES):
1352 conf = cast("list[str]", conf)
1353 for item in conf:
1354 # tolerate legacy/malformed entries: anything that does not parse as
1355 # `<rate><splitter><bit_depth>` is skipped and we fall back to defaults
1356 try:
1357 sample_rate_str, bit_depth_str = item.split(MULTI_VALUE_SPLITTER, 1)
1358 config_rates.append((int(sample_rate_str.strip()), int(bit_depth_str.strip())))
1359 except ValueError, TypeError:
1360 self.logger.warning(
1361 "Ignoring malformed CONF_SAMPLE_RATES entry %r for player %s",
1362 item,
1363 self.player_id,
1364 )
1365 return config_rates or [(44100, 16)]
1366
1367 @property
1368 @final
1369 def declares_supported_sample_rates(self) -> bool:
1370 """
1371 Return True when this player exposes its supported rates without user config.
1372
1373 Used by the config controller to decide whether to inject the generic
1374 ``CONF_ENTRY_SAMPLE_RATES`` option in the player config UI.
1375 """
1376 return self.supported_sample_rates is not None
1377
1378 @property
1379 @final
1380 def initialized(self) -> asyncio.Event:
1381 """
1382 Return if the player is initialized.
1383
1384 Used by player controller to indicate initial registration completed.
1385 """
1386 return self.__initialized
1387
1388 @property
1389 def corrected_elapsed_time(self) -> float | None:
1390 """Return the corrected/realtime elapsed time."""
1391 if self.elapsed_time is None or self.elapsed_time_last_updated is None:
1392 return None
1393 if self.playback_state == PlaybackState.PLAYING:
1394 return _clamp_elapsed_time(
1395 self.elapsed_time + (time.time() - self.elapsed_time_last_updated)
1396 )
1397 return _clamp_elapsed_time(self.elapsed_time)
1398
1399 @cached_property
1400 @final
1401 def icon(self) -> str:
1402 """Return the player icon."""
1403 icon = self.mass.config.get_raw_player_config_value(
1404 self.player_id, CONF_ENTRY_PLAYER_ICON.key
1405 )
1406 return icon if isinstance(icon, str) and icon else self.default_icon
1407
1408 @cached_property
1409 @final
1410 def power_control(self) -> str:
1411 """Return the power control type."""
1412 conf = self.mass.config.get_raw_player_config_value(self.player_id, CONF_POWER_CONTROL)
1413 if conf and conf in (PLAYER_CONTROL_NATIVE, PLAYER_CONTROL_FAKE, PLAYER_CONTROL_NONE):
1414 # validate that NATIVE is still backed by an actual POWER feature.
1415 # this handles graceful degradation for players (e.g. group players)
1416 # that previously advertised POWER but no longer do.
1417 if conf == PLAYER_CONTROL_NATIVE and PlayerFeature.POWER not in self.supported_features:
1418 return PLAYER_CONTROL_NONE
1419 return str(conf)
1420 if conf and (_control := self.mass.players.get_player_control(str(conf))):
1421 # the control type is explicitly set to a player control,
1422 return _control.id
1423 # handle auto-select logic if not explicitly set in config
1424 if PlayerFeature.POWER in self.supported_features:
1425 # player supports native power control, always prefer that
1426 return PLAYER_CONTROL_NATIVE
1427 return PLAYER_CONTROL_NONE
1428
1429 @cached_property
1430 @final
1431 def volume_control(self) -> str:
1432 """Return the volume control type."""
1433 conf = self.mass.config.get_raw_player_config_value(self.player_id, CONF_VOLUME_CONTROL)
1434 if conf and conf in (PLAYER_CONTROL_NATIVE, PLAYER_CONTROL_FAKE, PLAYER_CONTROL_NONE):
1435 # the control type is explicitly set in the config, use that
1436 return str(conf)
1437 if conf and conf not in (PLAYER_CONTROL_PROTOCOL, "auto"):
1438 # the control type is explicitly set to a (protocol) player_id or player control,
1439 # check if it exists and is (currently) available
1440 if (_player := self.mass.players.get_player(str(conf))) and _player.available:
1441 return _player.player_id
1442 if _control := self.mass.players.get_player_control(str(conf)):
1443 return _control.id
1444 # handle auto-select logic if not explicitly set in config
1445 if PlayerFeature.VOLUME_SET in self.supported_features:
1446 # player supports native volume control, always prefer that
1447 return PLAYER_CONTROL_NATIVE
1448 # check for protocol player with volume support, and use that if found
1449 if protocol_player := self._get_protocol_player_for_feature(
1450 PlayerFeature.VOLUME_SET, require_active=False
1451 ):
1452 return protocol_player.player_id
1453 return PLAYER_CONTROL_NONE
1454
1455 @cached_property
1456 @final
1457 def mute_control(self) -> str:
1458 """Return the mute control type."""
1459 conf = self.mass.config.get_raw_player_config_value(self.player_id, CONF_MUTE_CONTROL)
1460 if conf == PLAYER_CONTROL_FAKE and self.volume_control == PLAYER_CONTROL_NONE:
1461 # fake mute is simulated by setting the volume to zero, so without a volume
1462 # control to drive there is no way to mute this player at all
1463 return PLAYER_CONTROL_NONE
1464 if conf and conf in (PLAYER_CONTROL_NATIVE, PLAYER_CONTROL_FAKE, PLAYER_CONTROL_NONE):
1465 # the control type is explicitly set in the config, use that
1466 return str(conf)
1467 if conf and conf not in (PLAYER_CONTROL_PROTOCOL, "auto"):
1468 # the control type is explicitly set to a (protocol) player_id or player control,
1469 # check if it exists and is (currently) available
1470 if (_player := self.mass.players.get_player(str(conf))) and _player.available:
1471 return _player.player_id
1472 if _control := self.mass.players.get_player_control(str(conf)):
1473 return _control.id
1474 # handle auto-select logic if not explicitly set in config
1475 if PlayerFeature.VOLUME_MUTE in self.supported_features:
1476 # player supports native mute control, always prefer that
1477 return PLAYER_CONTROL_NATIVE
1478 # check for protocol player with mute support, and use that if found
1479 if protocol_player := self._get_protocol_player_for_feature(
1480 PlayerFeature.VOLUME_MUTE, require_active=False
1481 ):
1482 return protocol_player.player_id
1483 return PLAYER_CONTROL_NONE
1484
1485 @cached_property
1486 @final
1487 def group_volume(self) -> int | None:
1488 """
1489 Return the group volume level.
1490
1491 For group players or syncgroups, returns the maximum volume level of all
1492 powered-on child players, or None if no children support volume control.
1493
1494 For non-group players, returns the player's own volume level.
1495 """
1496 if len(self.state.group_members) == 0:
1497 # player is not a group or syncgroup
1498 if self.state.volume_control == PLAYER_CONTROL_NONE:
1499 return None
1500 return self.state.volume_level
1501 # return the maximum volume of all (turned on) child players
1502 group_volume: int | None = None
1503 for child_player in self.mass.players.iter_group_members(
1504 self, only_powered=True, exclude_self=self.type != PlayerType.PLAYER
1505 ):
1506 if child_player.state.volume_control == PLAYER_CONTROL_NONE:
1507 continue
1508 if (child_volume := child_player.state.volume_level) is None:
1509 continue
1510 if group_volume is None or child_volume > group_volume:
1511 group_volume = child_volume
1512 return group_volume
1513
1514 @cached_property
1515 @final
1516 def group_volume_muted(self) -> bool | None:
1517 """
1518 Return the group mute state.
1519
1520 If this player is a group player or syncgroup, this will return True if all (powered on)
1521 child players in the group are muted, False if at least one is not muted, or None if
1522 none of the players within the group support mute control.
1523
1524 If the player is not a group player or syncgroup, this will return the mute state of the
1525 player itself (if set), or None if not supported.
1526 """
1527 if len(self.state.group_members) == 0:
1528 # player is not a group or syncgroup
1529 if self.state.mute_control == PLAYER_CONTROL_NONE:
1530 return None
1531 return self.state.volume_muted
1532 # calculate group mute state from all (turned on) players
1533 any_unmuted = False
1534 any_muted = False
1535 for child_player in self.mass.players.iter_group_members(
1536 self, only_powered=True, exclude_self=self.type != PlayerType.PLAYER
1537 ):
1538 if child_player.state.mute_control == PLAYER_CONTROL_NONE:
1539 continue
1540 if (child_muted := child_player.state.volume_muted) is None:
1541 continue
1542 if child_muted:
1543 any_muted = True
1544 else:
1545 any_unmuted = True
1546 if any_unmuted and not any_muted:
1547 return False
1548 if any_muted and not any_unmuted:
1549 return True
1550 return None
1551
1552 @cached_property
1553 @final
1554 def hide_in_ui(self) -> bool:
1555 """
1556 Return the hide player in UI options.
1557
1558 This is a convenience property based on the config entry.
1559 """
1560 return bool(self._config.get_value(CONF_HIDE_IN_UI, self.hidden_by_default))
1561
1562 @cached_property
1563 @final
1564 def expose_to_ha(self) -> bool:
1565 """
1566 Return if the player should be exposed to Home Assistant.
1567
1568 This is a convenience property that returns True if the player is set to be exposed
1569 to Home Assistant, based on the config entry.
1570 """
1571 return bool(self._config.get_value(CONF_EXPOSE_PLAYER_TO_HA, self.expose_to_ha_by_default))
1572
1573 @cached_property
1574 @final
1575 def flow_mode(self) -> bool:
1576 """
1577 Return if the player(protocol) needs flow mode.
1578
1579 Will use 'requires_flow_mode' unless overridden by flow_mode config.
1580 """
1581 # Check config override
1582 if bool(self._config.get_value(CONF_FLOW_MODE)) is True:
1583 # flow mode explicitly enabled in config
1584 return True
1585 return self.requires_flow_mode
1586
1587 @property
1588 @final
1589 def supports_enqueue(self) -> bool:
1590 """
1591 Return if the player supports enqueueing tracks.
1592
1593 This considers the active output protocol's capabilities if one is active.
1594 If a protocol player is active, checks that protocol's ENQUEUE feature.
1595 Otherwise checks the native player's ENQUEUE feature.
1596 """
1597 return self._check_feature_with_active_protocol(PlayerFeature.ENQUEUE)
1598
1599 @property
1600 @final
1601 def supports_gapless(self) -> bool:
1602 """
1603 Return if the player supports gapless playback.
1604
1605 This considers the active output protocol's capabilities if one is active.
1606 If a protocol player is active, checks that protocol's GAPLESS_PLAYBACK feature.
1607 Otherwise checks the native player's GAPLESS_PLAYBACK feature.
1608 """
1609 return self._check_feature_with_active_protocol(PlayerFeature.GAPLESS_PLAYBACK)
1610
1611 @property
1612 @final
1613 def state(self) -> PlayerState:
1614 """Return the current (and FINAL) PlayerState of the player."""
1615 return self._state
1616
1617 # Protocol-related properties and helpers
1618
1619 @cached_property
1620 @final
1621 def is_native_player(self) -> bool:
1622 """Return True if this player is a native player."""
1623 is_universal_player = self.provider.domain == "universal_player"
1624 has_play_media = PlayerFeature.PLAY_MEDIA in self.supported_features
1625 return self.type != PlayerType.PROTOCOL and not is_universal_player and has_play_media
1626
1627 @cached_property
1628 @final
1629 def output_protocols(self) -> list[OutputProtocol]:
1630 """
1631 Return all output options for this player.
1632
1633 Includes:
1634 - Native playback (if player supports PLAY_MEDIA and is not a protocol/universal player)
1635 - Active protocol players from linked_output_protocols
1636 - Disabled protocols from cached linked_protocol_ids in config
1637
1638 Each entry has an available flag indicating current availability.
1639 """
1640 result: list[OutputProtocol] = []
1641
1642 # Add native playback option if applicable
1643 if self.is_native_player:
1644 result.append(
1645 OutputProtocol(
1646 output_protocol_id="native",
1647 name=self.provider.name,
1648 protocol_domain=self.provider.domain,
1649 priority=0, # Native is always highest priority
1650 available=self.available_for_playback,
1651 is_native=True,
1652 )
1653 )
1654 elif (
1655 self.provider.domain in PROTOCOL_PRIORITY
1656 and PlayerFeature.SET_MEMBERS in self.supported_features
1657 ):
1658 # Player is itself a native endpoint of a known protocol domain.
1659 result.append(
1660 OutputProtocol(
1661 output_protocol_id=self.player_id,
1662 name=self.provider.name,
1663 protocol_domain=self.provider.domain,
1664 priority=PROTOCOL_PRIORITY[self.provider.domain],
1665 available=self.available_for_playback,
1666 is_native=True,
1667 )
1668 )
1669
1670 # Add active protocol players
1671 active_ids: set[str] = set()
1672 for linked in self.__attr_linked_protocols:
1673 active_ids.add(linked.output_protocol_id)
1674 # Check if the protocol player is actually available
1675 protocol_player = self.mass.players.get_player(linked.output_protocol_id)
1676 is_available = protocol_player.available_for_playback if protocol_player else False
1677 # Use provider name if available, else domain title
1678 if protocol_player:
1679 name = protocol_player.provider.name
1680 else:
1681 name = linked.protocol_domain.title() if linked.protocol_domain else "Unknown"
1682 result.append(
1683 OutputProtocol(
1684 output_protocol_id=linked.output_protocol_id,
1685 name=name,
1686 protocol_domain=linked.protocol_domain,
1687 priority=linked.priority,
1688 available=is_available,
1689 derived_from=linked.derived_from,
1690 )
1691 )
1692
1693 # Add disabled protocols from cache
1694 cached_protocol_ids: list[str] = self.mass.config.get(
1695 f"{CONF_PLAYERS}/{self.player_id}/values/{CONF_LINKED_PROTOCOL_IDS}",
1696 [],
1697 )
1698 for protocol_id in cached_protocol_ids:
1699 if protocol_id in active_ids:
1700 continue # Already included above
1701 # Get stored config to determine protocol domain
1702 if raw_conf := self.mass.config.get(f"{CONF_PLAYERS}/{protocol_id}"):
1703 provider_id = raw_conf.get("provider", "")
1704 protocol_domain = provider_id.split("--")[0] if provider_id else "unknown"
1705 priority = PROTOCOL_PRIORITY.get(protocol_domain, 100)
1706 # resolve the persisted derived-transport edge (if any) so derived
1707 # outputs keep their base reference even while not registered
1708 derived_from = raw_conf.get("values", {}).get(CONF_UNDERLYING_PLAYER_ID)
1709 if derived_from == self.player_id:
1710 derived_from = "native"
1711 result.append(
1712 OutputProtocol(
1713 output_protocol_id=protocol_id,
1714 name=protocol_domain.title(),
1715 protocol_domain=protocol_domain,
1716 priority=priority,
1717 available=False, # Disabled protocols are not available
1718 derived_from=derived_from,
1719 )
1720 )
1721
1722 # Sort by priority (lower = more preferred)
1723 result.sort(key=lambda o: o.priority)
1724 return result
1725
1726 @cached_property
1727 @final
1728 def playback_domains(self) -> set[str]:
1729 """
1730 Return the protocol domains this player can be reached on right now.
1731
1732 Only outputs that are available at this moment are included, so a protocol
1733 whose player went offline is left out. A wrapper player (UniversalPlayer)
1734 contributes its linked protocols but never its own domain.
1735 """
1736 return {output.protocol_domain for output in self.output_protocols if output.available}
1737
1738 @property
1739 @final
1740 def linked_output_protocols(self) -> list[LinkedOutputProtocol]:
1741 """Return the list of actively linked output protocol players."""
1742 return self.__attr_linked_protocols
1743
1744 @property
1745 @final
1746 def protocol_parent_id(self) -> str | None:
1747 """Return the parent player_id if this is a protocol player linked to a native player."""
1748 return self.__attr_protocol_parent_id
1749
1750 @property
1751 @final
1752 def underlying_player_id(self) -> str | None:
1753 """
1754 Return the player_id this (derived) protocol player runs on top of, if any.
1755
1756 Set by bridge implementations (e.g. a Sendspin bridge riding on an AirPlay
1757 player) so the protocol linking layer can resolve the parent deterministically
1758 instead of relying on device identifier matching.
1759 """
1760 return self._attr_underlying_player_id
1761
1762 @property
1763 @final
1764 def active_output_protocol(self) -> str | None:
1765 """Return the currently active output protocol ID."""
1766 return self.__attr_active_output_protocol
1767
1768 @final
1769 def set_active_output_protocol(self, protocol_id: str | None) -> None:
1770 """
1771 Set the currently active output protocol ID.
1772
1773 :param protocol_id: The protocol player_id to set as active, "native" for native playback,
1774 or None to clear the active protocol.
1775 """
1776 # cancel any pending scheduled protocol clear,
1777 # as we're explicitly setting it now
1778 self.mass.cancel_task(f"clear_active_protocol_{self.player_id}")
1779 if self.__attr_active_output_protocol == protocol_id:
1780 return # No change
1781 if protocol_id == self.player_id:
1782 protocol_id = "native" # Normalize to "native" for native player
1783 if protocol_id:
1784 protocol_name = protocol_id
1785 if protocol_id == "native":
1786 protocol_name = "Native"
1787 elif protocol_player := self.mass.players.get_player(protocol_id):
1788 protocol_name = protocol_player.provider.name
1789 self.logger.info(
1790 "Setting active output protocol on %s to %s",
1791 self.display_name,
1792 protocol_name,
1793 )
1794 else:
1795 self.logger.info(
1796 "Clearing active output protocol on %s",
1797 self.display_name,
1798 )
1799 self.__attr_active_output_protocol = protocol_id
1800 self.update_state()
1801
1802 @final
1803 def set_linked_output_protocols(self, protocols: list[LinkedOutputProtocol]) -> None:
1804 """
1805 Set the actively linked output protocol players.
1806
1807 :param protocols: List of links to the active protocol players.
1808 """
1809 self.__attr_linked_protocols = protocols
1810 self.mass.players.trigger_player_update(self.player_id)
1811
1812 @final
1813 def set_protocol_parent_id(self, parent_id: str | None) -> None:
1814 """
1815 Set the parent player_id for protocol players.
1816
1817 :param parent_id: The player_id of the parent player, or None to clear.
1818 """
1819 self.__attr_protocol_parent_id = parent_id
1820 self.mass.players.trigger_player_update(self.player_id)
1821
1822 @final
1823 def get_linked_protocol(self, output_protocol_id: str) -> OutputProtocol | None:
1824 """
1825 Get a linked output protocol by its id, with its name and availability resolved.
1826
1827 :param output_protocol_id: player_id of the linked protocol player.
1828 """
1829 for linked in self.__attr_linked_protocols:
1830 if linked.output_protocol_id == output_protocol_id:
1831 protocol_player = self.mass.players.get_player(output_protocol_id)
1832 return OutputProtocol(
1833 output_protocol_id=linked.output_protocol_id,
1834 name=protocol_player.provider.name
1835 if protocol_player
1836 else linked.protocol_domain.title(),
1837 protocol_domain=linked.protocol_domain,
1838 priority=linked.priority,
1839 available=protocol_player.available_for_playback if protocol_player else False,
1840 derived_from=linked.derived_from,
1841 )
1842 return None
1843
1844 @final
1845 def get_output_protocol_by_domain(self, protocol_domain: str) -> OutputProtocol | None:
1846 """
1847 Get an output protocol by domain, including native protocol.
1848
1849 Unlike get_linked_protocol, this also covers the player's own native output.
1850
1851 :param protocol_domain: The protocol domain to search for (e.g., "airplay", "sonos").
1852 """
1853 for output_protocol in self.output_protocols:
1854 if output_protocol.protocol_domain == protocol_domain:
1855 return output_protocol
1856 return None
1857
1858 @final
1859 def get_protocol_player(self, player_id: str) -> Player | None:
1860 """Get the protocol Player for a given player_id."""
1861 if player_id == "native":
1862 return self if PlayerFeature.PLAY_MEDIA in self.supported_features else None
1863 return self.mass.players.get_player(player_id)
1864
1865 @final
1866 def get_preferred_protocol_player(self) -> Player | None:
1867 """Get the best available protocol player by priority."""
1868 for linked in sorted(self.__attr_linked_protocols, key=lambda x: x.priority):
1869 if protocol_player := self.mass.players.get_player(linked.output_protocol_id):
1870 if protocol_player.available_for_playback:
1871 return protocol_player
1872 return None
1873
1874 @final
1875 def mark_state_dirty(self) -> None:
1876 """
1877 Mark the player's (final) state as dirty.
1878
1879 Forces the next update_state call to recalculate the full PlayerState.
1880 Must be called when state the player derives from changed outside the
1881 player's own attributes (e.g. group topology, linked protocol players,
1882 the active queue) - the player controller does this automatically for
1883 all its notification paths (trigger_player_update and the state fan-out).
1884 """
1885 self.__state_dirty = True
1886
1887 @final
1888 def refresh_state(self, signal_event: bool = True) -> None:
1889 """
1890 Recalculate the player state unconditionally.
1891
1892 Convenience shorthand for mark_state_dirty() + update_state(), for core
1893 code reacting to changes outside the player's own attributes.
1894
1895 :param signal_event: If True, signal the state update event to the PlayerController.
1896 """
1897 self.mark_state_dirty()
1898 self.update_state(signal_event=signal_event)
1899
1900 @final
1901 def update_state(self, force_update: bool = False, signal_event: bool = True) -> None:
1902 """
1903 Update the PlayerState from the current state of the player.
1904
1905 This method should be called to update the player's state
1906 and signal any changes to the PlayerController.
1907
1908 :param force_update: If True, always recalculate the state, even when no
1909 (known) own input changed. An update event still only fires when the
1910 recalculated state actually differs.
1911 :param signal_event: If True, signal the state update event to the PlayerController.
1912 """
1913 self.mass.verify_event_loop_thread("player.update_state")
1914 # Invalidate the cached properties up front so both the input probe and
1915 # a recalculation read fresh values; only the config-derived cached
1916 # properties are retained (set_config invalidates those).
1917 for key in list(self._cache):
1918 if key not in _CONFIG_CACHED_PROPS:
1919 del self._cache[key]
1920 new_snapshot = self.__collect_input_snapshot()
1921 if (
1922 not force_update
1923 and not self.__state_dirty
1924 and self.__input_snapshot is not None
1925 and new_snapshot == self.__input_snapshot
1926 and not self.__own_position_anchor_moved()
1927 ):
1928 # None of the player's own inputs changed since the last calculation:
1929 # nothing to do. Changes the player derives from other sources
1930 # (players/queues/config) always come with a mark_state_dirty call.
1931 return
1932 self.__state_dirty = False
1933 self.__input_snapshot = new_snapshot
1934 current_media = self.current_media
1935 self.__input_anchor = (
1936 (self._attr_elapsed_time, self._attr_elapsed_time_last_updated),
1937 (current_media.elapsed_time, current_media.elapsed_time_last_updated)
1938 if current_media is not None
1939 else None,
1940 self.playback_state == PlaybackState.PLAYING,
1941 )
1942 # calculate the new state
1943 changed_values, position_jumped, media_position_jumped = self.__calculate_player_state()
1944 if not MEDIA_IDENTITY_KEYS.isdisjoint(changed_values.keys()):
1945 # current media changed, call the media updated callback
1946 # debounce the callback to avoid multiple calls when multiple
1947 # state updates happen in a short time
1948 self.mass.call_later(
1949 1, self.on_player_media_updated, task_id=f"player_media_updated_{self.player_id}"
1950 )
1951 # persist the default name if it changed
1952 if self.name and self.config.default_name != self.name:
1953 self.mass.config.set_player_default_name(self.player_id, self.name)
1954 # persist the player type if it changed
1955 if self.type != self._config.player_type:
1956 self.mass.config.set_player_type(self.player_id, self.type)
1957 if position_jumped and signal_event:
1958 # the corrected playback position jumped (seek or buffer correction):
1959 # this is not an event by itself (only current_media is event-relevant)
1960 # but the queue timing must re-base on the fresh position right away
1961 self.mass.players.on_player_position_jumped(self)
1962 # return early if nothing changed (unless force_update is True)
1963 if len(changed_values) == 0 and not force_update:
1964 return
1965
1966 # signal the state update to the PlayerController
1967 if signal_event:
1968 self.mass.players.signal_player_state_update(
1969 self, changed_values, media_position_jumped=media_position_jumped
1970 )
1971
1972 @final
1973 def set_current_media( # noqa: PLR0913
1974 self,
1975 uri: str,
1976 media_type: MediaType = MediaType.UNKNOWN,
1977 title: str | None = None,
1978 artist: str | None = None,
1979 album: str | None = None,
1980 image_url: str | None = None,
1981 duration: int | None = None,
1982 source_id: str | None = None,
1983 queue_item_id: str | None = None,
1984 custom_data: dict[str, Any] | None = None,
1985 clear_all: bool = False,
1986 ) -> None:
1987 """
1988 Set current_media helper.
1989
1990 Assumes use of '_attr_current_media'.
1991 """
1992 if self._attr_current_media is None or clear_all:
1993 self._attr_current_media = PlayerMedia(
1994 uri=uri,
1995 media_type=media_type,
1996 )
1997 self._attr_current_media.uri = uri
1998 if media_type != MediaType.UNKNOWN:
1999 self._attr_current_media.media_type = media_type
2000 if title:
2001 self._attr_current_media.title = title
2002 if artist:
2003 self._attr_current_media.artist = artist
2004 if album:
2005 self._attr_current_media.album = album
2006 if image_url:
2007 self._attr_current_media.image_url = image_url
2008 if duration:
2009 self._attr_current_media.duration = duration
2010 if source_id:
2011 self._attr_current_media.source_id = source_id
2012 if queue_item_id:
2013 self._attr_current_media.queue_item_id = queue_item_id
2014 if custom_data:
2015 self._attr_current_media.custom_data = custom_data
2016
2017 @final
2018 def set_resolved_palette(self, image_url: str, palette: MediaItemPalette) -> None:
2019 """
2020 Store the resolved color palette for the currently shown image.
2021
2022 The palette is resolved asynchronously (from the cache controller) by the
2023 PlayerController; it is carried on the player here so the synchronous state
2024 serialization can attach it without blocking. May only be called by the
2025 PlayerController.
2026
2027 :param image_url: Image URL the palette was extracted from.
2028 :param palette: The extracted color palette.
2029 """
2030 self._attr_current_palette_url = image_url
2031 self._attr_current_palette = palette
2032
2033 @final
2034 def set_config(self, config: PlayerConfig) -> None:
2035 """
2036 Set/update the player config.
2037
2038 May only be called by the PlayerController.
2039 """
2040 # TODO: validate that caller is the PlayerController ?
2041 self._config = config
2042 # config feeds several (cached) state values, so invalidate all cached
2043 # properties (including the config-derived ones) and force a recalculation
2044 self._cache.clear()
2045 self.mark_state_dirty()
2046
2047 @final
2048 def set_initialized(self) -> None:
2049 """Set the player as initialized."""
2050 self.__initialized.set()
2051
2052 @final
2053 def to_dict(self) -> dict[str, Any]:
2054 """Return the (serializable) dict representation of the Player."""
2055 return self.state.to_dict()
2056
2057 @final
2058 def supports_feature(self, feature: PlayerFeature) -> bool:
2059 """Return True if this player supports the given feature."""
2060 return feature in self.supported_features
2061
2062 @final
2063 def check_feature(self, feature: PlayerFeature) -> None:
2064 """Check if this player supports the given feature."""
2065 if not self.supports_feature(feature):
2066 raise UnsupportedFeaturedException(
2067 f"Player {self.display_name} does not support feature {feature.name}"
2068 )
2069
2070 def _update_setup_data(self, key: str, value: ConfigValueType, immediate: bool = True) -> None:
2071 """
2072 Update a single setup_data value for this player (e.g. a rotated pairing credential).
2073
2074 :param key: The setup data key to update.
2075 :param value: The new value; strings are encrypted at rest.
2076 :param immediate: Persist to disk right away (the default) instead of on the
2077 debounced save timer, so a critical value survives a crash.
2078 """
2079 if not self.mass.config.get(f"{CONF_PLAYERS}/{self.player_id}"):
2080 # only allow setting setup data if the main config entry exists
2081 msg = f"Invalid player: {self.player_id}"
2082 raise KeyError(msg)
2083 stored_value = self.mass.config.encrypt_string(value) if isinstance(value, str) else value
2084 self.mass.config.set(
2085 f"{CONF_PLAYERS}/{self.player_id}/setup_data/{key}",
2086 stored_value,
2087 immediate=immediate,
2088 )
2089 # keep the in-memory config copy in sync with storage
2090 self.config.setup_data[key] = stored_value
2091
2092 @final
2093 def _check_feature_with_active_protocol(
2094 self, feature: PlayerFeature, active_only: bool = False
2095 ) -> bool:
2096 """
2097 Check if a feature is supported considering the active output protocol.
2098
2099 If an active output protocol is set (and not native), checks that protocol
2100 player's features. Otherwise checks the native player's features.
2101
2102 :param feature: The PlayerFeature to check.
2103 :return: True if the feature is supported by the active protocol or native player.
2104 """
2105 # If active output protocol is set and not native, check protocol player's features
2106 if (
2107 self.__attr_active_output_protocol
2108 and self.__attr_active_output_protocol != "native"
2109 and (
2110 protocol_player := self.mass.players.get_player(self.__attr_active_output_protocol)
2111 )
2112 ):
2113 return feature in protocol_player.supported_features
2114 # Otherwise check native player's features
2115 return feature in self.supported_features
2116
2117 @final
2118 def _get_protocol_player_for_feature(
2119 self,
2120 feature: PlayerFeature,
2121 require_active: bool = True,
2122 ) -> Player | None:
2123 """Get player(protocol) which has the given PlayerFeature."""
2124 # prefer native player
2125 if feature in self.supported_features:
2126 return self
2127 # prefer active (or preferred) protocol player with the feature
2128 active_protocol = self.active_output_protocol
2129 if active_protocol and active_protocol != "native":
2130 protocol_player = self.mass.players.get_player(active_protocol)
2131 if (
2132 protocol_player
2133 and protocol_player.available_for_playback
2134 and feature in protocol_player.supported_features
2135 ):
2136 return protocol_player
2137 if require_active:
2138 # if we require active and the active protocol
2139 # doesn't support the feature, return None
2140 return None
2141
2142 # fallback to preferred protocol from config
2143 preferred_conf = self.mass.config.get_raw_player_config_value(
2144 self.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2145 )
2146 if preferred_conf and preferred_conf not in ("auto", "native"):
2147 preferred_protocol = str(preferred_conf)
2148 if (
2149 (_player := self.mass.players.get_player(preferred_protocol))
2150 and _player.available_for_playback
2151 and feature in _player.supported_features
2152 ):
2153 return _player
2154
2155 # Otherwise, use the first available linked protocol.
2156 # Prefer protocols that can process commands without active streaming
2157 # (cast/dlna can always handle volume, airplay/sendspin only while streaming).
2158 _control_priority = {"chromecast": 0, "dlna": 1, "airplay": 2, "sendspin": 3}
2159 for linked in sorted(
2160 self.linked_output_protocols,
2161 key=lambda o: _control_priority.get(o.protocol_domain, 10),
2162 ):
2163 if (
2164 (protocol_player := self.mass.players.get_player(linked.output_protocol_id))
2165 and protocol_player.available_for_playback
2166 and feature in protocol_player.supported_features
2167 ):
2168 return protocol_player
2169
2170 return None
2171
2172 @final
2173 def __collect_input_snapshot(self) -> dict[str, Any]:
2174 """
2175 Collect a snapshot of the player's own state-calculation inputs.
2176
2177 Only covers inputs owned by the player itself (its _attr_ values and
2178 provider-overridden properties); state the player derives from other
2179 sources (players/queues/config) is covered by mark_state_dirty instead.
2180 The playback position anchors are deliberately excluded: they are
2181 tracked separately with jump detection (__own_position_anchor_moved).
2182 """
2183 current_media = self.current_media
2184 device_info = self._attr_device_info
2185 return {
2186 "type": self.type,
2187 "available": self.available,
2188 "name": self.name,
2189 "needs_setup": self.needs_setup,
2190 "setup_reason": self.setup_reason,
2191 "playback_state": self.playback_state,
2192 "powered": self.powered,
2193 "volume_level": self.volume_level,
2194 "volume_muted": self.volume_muted,
2195 "active_source": self.active_source,
2196 "active_sound_mode": self.active_sound_mode,
2197 "is_active_session": self.is_active_session,
2198 "synced_to": self.synced_to if self.__probe_synced_to else None,
2199 "supported_features": frozenset(self.supported_features),
2200 "group_members": tuple(self.group_members),
2201 "static_group_members": tuple(self.static_group_members),
2202 "can_group_with": frozenset(self.can_group_with),
2203 "device_info": (
2204 device_info.model,
2205 device_info.manufacturer,
2206 device_info.software_version,
2207 device_info.model_id,
2208 device_info.manufacturer_id,
2209 tuple(sorted(device_info.identifiers.items())),
2210 ),
2211 "source_list": tuple(
2212 (s.id, s.name, s.passive, s.can_play_pause, s.can_seek, s.can_next_previous)
2213 for s in self.source_list
2214 ),
2215 "sound_mode_list": tuple((m.id, m.name, m.passive) for m in self._attr_sound_mode_list),
2216 "options": tuple((o.key, o.value, o.read_only) for o in self._attr_options),
2217 "current_media": (
2218 (
2219 current_media.uri,
2220 current_media.media_type,
2221 current_media.title,
2222 current_media.artist,
2223 current_media.album,
2224 current_media.album_artist,
2225 current_media.image_url,
2226 current_media.duration,
2227 current_media.source_id,
2228 current_media.queue_item_id,
2229 )
2230 if current_media is not None
2231 else None
2232 ),
2233 "extra_attributes": tuple(
2234 sorted(
2235 (key, _freeze(value))
2236 for key, value in self._extra_attributes.items()
2237 if key not in ("seq_no", "last_poll")
2238 )
2239 ),
2240 "fake_controls": (
2241 self._extra_data.get(ATTR_FAKE_POWER),
2242 self._extra_data.get(ATTR_FAKE_VOLUME),
2243 self._extra_data.get(ATTR_FAKE_MUTE),
2244 ),
2245 "linked_protocols": tuple(self.__attr_linked_protocols),
2246 "protocol_parent_id": self.__attr_protocol_parent_id,
2247 "active_output_protocol": self.__attr_active_output_protocol,
2248 "active_mass_source": self.__active_mass_source,
2249 "sleep_timer_expires_at": self.__sleep_timer_expires_at,
2250 }
2251
2252 @final
2253 def __own_position_anchor_moved(self) -> bool:
2254 """Return whether one of the player's own position anchors moved significantly."""
2255 if (prev := self.__input_anchor) is None:
2256 return True
2257 prev_player_anchor, prev_media_anchor, prev_playing = prev
2258 playing = self.playback_state == PlaybackState.PLAYING
2259 media = self.current_media
2260 new_player_anchor = (self._attr_elapsed_time, self._attr_elapsed_time_last_updated)
2261 new_media_anchor = (
2262 (media.elapsed_time, media.elapsed_time_last_updated) if media is not None else None
2263 )
2264 return _anchor_moved(
2265 prev_player_anchor, new_player_anchor, prev_playing, playing
2266 ) or _anchor_moved(prev_media_anchor, new_media_anchor, prev_playing, playing)
2267
2268 @final
2269 def __calculate_player_state(
2270 self,
2271 ) -> tuple[dict[str, tuple[Any, Any]], bool, bool]:
2272 """
2273 Calculate the (current) and FINAL PlayerState.
2274
2275 This method is called when we're updating the player,
2276 and we compare the current state with the previous state to determine
2277 if we need to signal a state change to API consumers.
2278
2279 Returns a tuple of (changed state values, player position jumped,
2280 current_media position jumped). The player's own elapsed_time values
2281 are not part of the changed values: they refresh on every calculation
2282 but only current_media - which holds the final calculated position -
2283 is event-relevant. The jump flags drive the position correction logic.
2284 """
2285 playback_state, elapsed_time, elapsed_time_last_updated = self.__final_playback_state
2286 prev_state = self._state
2287 prev_fingerprint = self.__state_fingerprint or _state_fingerprint(prev_state)
2288 prev_playing = prev_state.playback_state == PlaybackState.PLAYING
2289 new_playing = playback_state == PlaybackState.PLAYING
2290 # detect a discrete jump of the corrected position (seek/buffer correction);
2291 # the fresh anchor is always adopted into the state
2292 _, _, position_jumped = _reconcile_position_anchor(
2293 prev_state.elapsed_time,
2294 prev_state.elapsed_time_last_updated,
2295 elapsed_time,
2296 elapsed_time_last_updated,
2297 prev_playing,
2298 new_playing,
2299 force_adopt=True,
2300 )
2301 self._state = PlayerState(
2302 player_id=self.player_id,
2303 provider=self.provider_id,
2304 type=self.type,
2305 available=self.enabled and self.available and not self.needs_setup,
2306 device_info=self.device_info,
2307 supported_features=self.__final_supported_features,
2308 playback_state=playback_state,
2309 elapsed_time=elapsed_time,
2310 elapsed_time_last_updated=elapsed_time_last_updated,
2311 powered=self.__final_power_state,
2312 volume_level=self.__final_volume_level,
2313 volume_muted=self.__final_volume_muted_state,
2314 group_members=UniqueList(self.__final_group_members),
2315 static_group_members=UniqueList(self.static_group_members),
2316 can_group_with=self.__final_can_group_with,
2317 synced_to=self.__final_synced_to,
2318 active_source=self.__final_active_source,
2319 source_list=self.__final_source_list,
2320 active_group=self.__final_active_group,
2321 current_media=self.__final_current_media,
2322 active_sound_mode=self.active_sound_mode,
2323 sound_mode_list=self.sound_mode_list,
2324 options=self.options,
2325 name=self.display_name,
2326 enabled=self.enabled,
2327 hide_in_ui=self.hide_in_ui,
2328 expose_to_ha=self.expose_to_ha,
2329 icon=self.icon,
2330 group_volume=self.group_volume,
2331 group_volume_muted=self.group_volume_muted,
2332 extra_attributes=self.extra_attributes,
2333 power_control=self.power_control,
2334 volume_control=self.volume_control,
2335 mute_control=self.mute_control,
2336 output_protocols=self.output_protocols,
2337 active_output_protocol=self.__attr_active_output_protocol,
2338 needs_setup=self.needs_setup,
2339 setup_reason=self.setup_reason,
2340 has_setup_flow=self.has_setup_flow,
2341 sleep_timer_expires_at=self.sleep_timer_expires_at,
2342 )
2343 media_position_jumped = self.__reconcile_current_media_anchor(
2344 prev_state, prev_playing, new_playing
2345 )
2346
2347 # track stop called state
2348 if (
2349 prev_state.playback_state == PlaybackState.IDLE
2350 and self._state.playback_state != PlaybackState.IDLE
2351 ):
2352 self.__stop_called = False
2353 elif (
2354 prev_state.playback_state != PlaybackState.IDLE
2355 and self._state.playback_state == PlaybackState.IDLE
2356 ):
2357 self.__stop_called = True
2358 # when we're going to idle,
2359 # we want to reset the active mass source after a short delay
2360 # this is done using a timer which gets reset if the player starts playing again
2361 # before the timer is up, using the task_id
2362 self.mass.call_later(
2363 5, self.set_active_mass_source, None, task_id=f"set_mass_source_{self.player_id}"
2364 )
2365 new_fingerprint = _state_fingerprint(self._state)
2366 self.__state_fingerprint = new_fingerprint
2367 changed_values: dict[str, tuple[Any, Any]] = {}
2368 for key in prev_fingerprint.keys() | new_fingerprint.keys():
2369 old_value = prev_fingerprint.get(key)
2370 new_value = new_fingerprint.get(key)
2371 if old_value != new_value:
2372 changed_values[key] = (old_value, new_value)
2373 if "current_media" in changed_values:
2374 # media appeared/disappeared: collapse the leaf keys into the single
2375 # top-level key carrying the actual (old, new) media objects
2376 for key in [key for key in changed_values if key.startswith("current_media.")]:
2377 del changed_values[key]
2378 changed_values["current_media"] = (prev_state.current_media, self._state.current_media)
2379 if "options" in changed_values:
2380 # the PLAYER_OPTIONS_UPDATED event carries the actual (old, new) options
2381 changed_values["options"] = (prev_state.options, self._state.options)
2382 return changed_values, position_jumped, media_position_jumped
2383
2384 @final
2385 def __reconcile_current_media_anchor(
2386 self, prev_state: PlayerState, prev_playing: bool, new_playing: bool
2387 ) -> bool:
2388 """
2389 Reconcile the position anchor on the freshly calculated current_media.
2390
2391 Keeps the previous anchor while it extrapolates to the same corrected
2392 position (steady playback), so regular ticks don't change the state.
2393
2394 Returns True when the corrected current_media position jumped (seek or
2395 buffer correction reached the current media).
2396 """
2397 prev_media = prev_state.current_media
2398 new_media = self._state.current_media
2399 if new_media is None or prev_media is None:
2400 return False
2401 if (new_media.queue_item_id or new_media.uri) != (
2402 prev_media.queue_item_id or prev_media.uri
2403 ):
2404 # different item loaded - adopt the new anchor as-is
2405 return False
2406 # Players that mirror another player's media (grouped/synced members,
2407 # protocol children) share the owner's PlayerMedia object, which the owner
2408 # already reconciled - only report the jump, never mutate the shared object.
2409 mirrors_parent = bool(
2410 self.__final_active_group
2411 or self.__final_synced_to
2412 or (self.type == PlayerType.PROTOCOL and self.__attr_protocol_parent_id)
2413 )
2414 position, timestamp, jumped = _reconcile_position_anchor(
2415 prev_media.elapsed_time,
2416 prev_media.elapsed_time_last_updated,
2417 new_media.elapsed_time,
2418 new_media.elapsed_time_last_updated,
2419 prev_playing,
2420 new_playing,
2421 force_adopt=mirrors_parent,
2422 )
2423 if not mirrors_parent:
2424 # steady playback resolves to the previous anchor, so nothing changed;
2425 # a jump (or a previous anchor that was still incomplete) adopts the new one
2426 new_media.elapsed_time = int(position) if position is not None else None
2427 new_media.elapsed_time_last_updated = timestamp
2428 return jumped
2429
2430 @cached_property
2431 @final
2432 def __final_playback_state(self) -> tuple[PlaybackState, float | None, float | None]:
2433 """
2434 Return the FINAL playback state based on the playercontrol which may have been set-up.
2435
2436 Returns a tuple of (playback_state, elapsed_time, elapsed_time_last_updated).
2437 """
2438 # Determine base state from protocol player, parent/group, or self.
2439 playback_state: PlaybackState
2440 elapsed_time: float | None
2441 elapsed_time_last_updated: float | None
2442
2443 # If an output protocol is active (and not native),
2444 # use the protocol player's state as the source of truth
2445 if (
2446 self.__attr_active_output_protocol
2447 and self.__attr_active_output_protocol != "native"
2448 and (
2449 protocol_player := self.mass.players.get_player(self.__attr_active_output_protocol)
2450 )
2451 ):
2452 playback_state = protocol_player.state.playback_state
2453 elapsed_time = protocol_player.state.elapsed_time
2454 elapsed_time_last_updated = protocol_player.state.elapsed_time_last_updated
2455 # If we're synced to another player, mirror the leader's state so that
2456 # synced clients report the same playback info as their leader.
2457 elif (parent_id := self.__final_synced_to) and (
2458 parent_player := self.mass.players.get_player(parent_id)
2459 ):
2460 playback_state = parent_player.state.playback_state
2461 elapsed_time = parent_player.state.elapsed_time
2462 elapsed_time_last_updated = parent_player.state.elapsed_time_last_updated
2463 else:
2464 playback_state = self.playback_state
2465 elapsed_time = self.elapsed_time
2466 elapsed_time_last_updated = self.elapsed_time_last_updated
2467
2468 # If the active queue item is an AudioSource with upstream-clock
2469 # metadata (e.g. Spotify Connect / AirPlay / Yandex Ynison reporting
2470 # the source's logical position), prefer that over the protocol /
2471 # self elapsed_time — the latter tracks bytes consumed, which is the
2472 # wrong clock for live plugin sources (loses upstream seeks and
2473 # pause-resume on the queue's corrected_elapsed_time, which the
2474 # player_queues controller and several player providers consume).
2475 # A group player outputs the AudioSource from its own queue, which
2476 # __final_active_source may not resolve to, so the group's own queue
2477 # is also consulted.
2478 candidate_source_ids = [self.__final_active_source]
2479 if self.type == PlayerType.GROUP:
2480 candidate_source_ids.append(self.player_id)
2481 for source_id in candidate_source_ids:
2482 if (
2483 source_id
2484 and (queue := self.mass.player_queues.get(source_id))
2485 and (current_item := queue.current_item) is not None
2486 and (sd := current_item.streamdetails) is not None
2487 and sd.media_type == MediaType.AUDIO_SOURCE
2488 and sd.stream_metadata is not None
2489 and sd.stream_metadata.elapsed_time is not None
2490 ):
2491 elapsed_time = sd.stream_metadata.elapsed_time
2492 elapsed_time_last_updated = (
2493 sd.stream_metadata.elapsed_time_last_updated or time.time()
2494 )
2495 break
2496
2497 return (playback_state, elapsed_time, elapsed_time_last_updated)
2498
2499 @cached_property
2500 @final
2501 def __final_power_state(self) -> bool | None:
2502 """Return the FINAL power state based on the playercontrol which may have been set-up."""
2503 power_control = self.power_control
2504 if power_control == PLAYER_CONTROL_FAKE:
2505 return bool(self.extra_data.get(ATTR_FAKE_POWER, False))
2506 if power_control == PLAYER_CONTROL_NATIVE:
2507 return self.powered
2508 if power_control == PLAYER_CONTROL_NONE:
2509 return None
2510 # handle protocol player as power control
2511 if player_ctrl := self.mass.players.get_player(power_control):
2512 if player_ctrl.powered is not None:
2513 return player_ctrl.powered
2514 # handle player control for power if set
2515 if ext_ctrl := self.mass.players.get_player_control(power_control):
2516 return ext_ctrl.power_state
2517 return None
2518
2519 @cached_property
2520 @final
2521 def __final_volume_level(self) -> int | None:
2522 """Return the FINAL volume level based on the playercontrol which may have been set-up."""
2523 volume_control = self.volume_control
2524 if volume_control == PLAYER_CONTROL_FAKE:
2525 # Fake volume is already stored as logical (0-100)
2526 return int(self.extra_data.get(ATTR_FAKE_VOLUME, 0))
2527 if volume_control == PLAYER_CONTROL_NATIVE:
2528 # Scale device volume back to logical (0-100)
2529 if self.volume_level is None:
2530 return None
2531 return self.mass.players.scale_volume_from_device(self.player_id, self.volume_level)
2532 if volume_control == PLAYER_CONTROL_NONE:
2533 return None
2534 # handle protocol player as volume control
2535 if control := self.mass.players.get_player(volume_control):
2536 control_volume = control.volume_level
2537 if (
2538 control_volume == 0
2539 and control.player_id != self.active_output_protocol
2540 and any(
2541 linked.output_protocol_id == control.player_id
2542 for linked in self.linked_output_protocols
2543 )
2544 ):
2545 # A linked protocol interface that is not actively rendering audio
2546 # may report volume 0 while the device is in standby (e.g. the cast
2547 # side of some devices), which doesn't reflect the real device volume.
2548 # Treat it as unknown so we fall back to other sources instead of
2549 # propagating a spurious hard mute.
2550 control_volume = None
2551 if control_volume is not None:
2552 return self.mass.players.scale_volume_from_device(self.player_id, control_volume)
2553 # handle player control for volume if set
2554 if player_control := self.mass.players.get_player_control(volume_control):
2555 if player_control.volume_level is not None:
2556 return self.mass.players.scale_volume_from_device(
2557 self.player_id, player_control.volume_level
2558 )
2559 # control not (yet) available or has no volume, fall back to native
2560 if self.volume_level is None:
2561 return None
2562 return self.mass.players.scale_volume_from_device(self.player_id, self.volume_level)
2563
2564 @cached_property
2565 @final
2566 def __final_volume_muted_state(self) -> bool | None:
2567 """Return the FINAL mute state based on any playercontrol which may have been set-up."""
2568 mute_control = self.mute_control
2569 if mute_control == PLAYER_CONTROL_FAKE:
2570 return bool(self.extra_data.get(ATTR_FAKE_MUTE, False))
2571 if mute_control == PLAYER_CONTROL_NATIVE:
2572 return self.volume_muted
2573 if mute_control == PLAYER_CONTROL_NONE:
2574 return None
2575 # handle protocol player as mute control
2576 if control := self.mass.players.get_player(mute_control):
2577 if control.volume_muted is not None:
2578 return control.volume_muted
2579 # handle player control for mute if set
2580 if player_control := self.mass.players.get_player_control(mute_control):
2581 if player_control.volume_muted is not None:
2582 return player_control.volume_muted
2583 # control not (yet) available or has no mute state, fall back to native
2584 return self.volume_muted
2585
2586 @cached_property
2587 @final
2588 def __final_active_group(self) -> str | None:
2589 """
2590 Return the player id of any playergroup that is currently active for this player.
2591
2592 This will return the id of the groupplayer if any groups are active.
2593 If no groups are currently active, this will return None.
2594 """
2595 if self.type == PlayerType.PROTOCOL:
2596 # protocol players should not have an active group,
2597 # they follow the group state of their parent player
2598 return None
2599 for group_player in self.mass.players.iter_players(
2600 return_unavailable=False, return_disabled=False
2601 ):
2602 if group_player.type != PlayerType.GROUP:
2603 continue
2604 if group_player.player_id == self.player_id:
2605 continue
2606 # Use the raw `powered` attribute (not `state.powered`) so the
2607 # check reflects what the group player itself believes — for
2608 # native/fake control the group's `power()` method sets
2609 # `_attr_powered` directly. `state.powered` routes through
2610 # `__final_power_state` which may return None for power_control
2611 # == NONE even though the group is actively capturing members.
2612 powered = group_player.powered
2613 if powered is False:
2614 # explicit power-off (fake or native) - never captures members
2615 continue
2616 if powered is not True and not group_player.is_active_session:
2617 # no explicit power-on and no captured session - group is dormant,
2618 # configured members are free to be controlled individually
2619 continue
2620 if self.player_id in group_player.state.group_members:
2621 return group_player.player_id
2622 return None
2623
2624 @cached_property
2625 @final
2626 def __final_current_media(self) -> PlayerMedia | None:
2627 """Return the FINAL current media for the player."""
2628 # if the player is grouped/synced, use the current_media of the group/parent player
2629 if parent_player_id := (self.__final_active_group or self.__final_synced_to):
2630 if parent_player_id != self.player_id and (
2631 parent_player := self.mass.players.get_player(parent_player_id)
2632 ):
2633 return parent_player.state.current_media
2634 return None # if parent player not found, return None for current media
2635 # if this is a protocol player, use the current_media of the parent player
2636 if self.type == PlayerType.PROTOCOL and self.__attr_protocol_parent_id:
2637 if parent_player := self.mass.players.get_player(self.__attr_protocol_parent_id):
2638 return parent_player.state.current_media
2639 # if MA queue is active, return those details
2640 active_source = self.__final_active_source
2641 active_queue: PlayerQueue | None = None
2642 if not active_queue and active_source:
2643 active_queue = self.mass.player_queues.get(active_source)
2644 if not active_queue and self.active_source is None:
2645 active_queue = self.mass.player_queues.get(self.player_id)
2646 if active_queue and (current_item := active_queue.current_item):
2647 item_image_url = (
2648 # the image format needs to be 512x512 jpeg for maximum compatibility with players
2649 self.mass.metadata.get_image_url(current_item.image, size=512)
2650 if current_item.image
2651 else None
2652 )
2653 if current_item.streamdetails and (
2654 stream_metadata := current_item.streamdetails.stream_metadata
2655 ):
2656 # handle stream metadata in streamdetails (e.g. for radio stream)
2657 image_url = stream_metadata.image_url or item_image_url
2658 elapsed_time, elapsed_time_last_updated = _resolve_position(
2659 stream_metadata.elapsed_time,
2660 stream_metadata.elapsed_time_last_updated,
2661 active_queue.elapsed_time,
2662 active_queue.elapsed_time_last_updated,
2663 )
2664 return PlayerMedia(
2665 uri=current_item.uri,
2666 media_type=current_item.media_type,
2667 title=stream_metadata.title or current_item.name,
2668 artist=stream_metadata.artist,
2669 album=stream_metadata.album or stream_metadata.description or current_item.name,
2670 image_url=image_url,
2671 palette=self._resolved_palette(image_url),
2672 duration=stream_metadata.duration or current_item.duration,
2673 source_id=active_queue.queue_id,
2674 queue_item_id=current_item.queue_item_id,
2675 elapsed_time=elapsed_time,
2676 elapsed_time_last_updated=elapsed_time_last_updated,
2677 )
2678 if media_item := current_item.media_item:
2679 # normal media item
2680 # we use getattr here to avoid issues with different media item types
2681 version = getattr(media_item, "version", None)
2682 album = getattr(media_item, "album", None)
2683 podcast = getattr(media_item, "podcast", None)
2684 metadata = getattr(media_item, "metadata", None)
2685 description = getattr(metadata, "description", None) if metadata else None
2686 if description:
2687 # descriptions may contain HTML markup; the OSD shows plain text
2688 description = html_to_markdown(description)
2689 image_url = (
2690 self.mass.metadata.get_image_url(current_item.media_item.image, size=512)
2691 or item_image_url
2692 if current_item.media_item.image
2693 else item_image_url
2694 )
2695 return PlayerMedia(
2696 uri=str(media_item.uri),
2697 media_type=media_item.media_type,
2698 title=f"{media_item.name} ({version})" if version else media_item.name,
2699 artist=getattr(media_item, "artist_str", None),
2700 album=album.name if album else podcast.name if podcast else description,
2701 album_artist=getattr(album, "artist_str", None),
2702 image_url=image_url,
2703 palette=self._resolved_palette(image_url),
2704 duration=media_item.duration,
2705 source_id=active_queue.queue_id,
2706 queue_item_id=current_item.queue_item_id,
2707 elapsed_time=int(active_queue.elapsed_time),
2708 elapsed_time_last_updated=active_queue.elapsed_time_last_updated,
2709 )
2710
2711 # fallback to basic current item details
2712 return PlayerMedia(
2713 uri=current_item.uri,
2714 media_type=current_item.media_type,
2715 title=current_item.name,
2716 image_url=item_image_url,
2717 palette=self._resolved_palette(item_image_url),
2718 duration=current_item.duration,
2719 source_id=active_queue.queue_id,
2720 queue_item_id=current_item.queue_item_id,
2721 elapsed_time=int(active_queue.elapsed_time),
2722 elapsed_time_last_updated=active_queue.elapsed_time_last_updated,
2723 )
2724 if active_queue:
2725 # queue is active but no current item
2726 return None
2727 # return native current media if no group/queue is active
2728 if self.current_media:
2729 image_url = self.current_media.image_url
2730 elapsed_time, elapsed_time_last_updated = _resolve_position(
2731 self.current_media.elapsed_time,
2732 self.current_media.elapsed_time_last_updated,
2733 self.elapsed_time,
2734 self.elapsed_time_last_updated,
2735 )
2736 return PlayerMedia(
2737 uri=self.current_media.uri,
2738 media_type=self.current_media.media_type,
2739 title=self.current_media.title,
2740 artist=self.current_media.artist,
2741 album=self.current_media.album,
2742 image_url=image_url,
2743 palette=self._resolved_palette(image_url),
2744 duration=self.current_media.duration,
2745 source_id=self.current_media.source_id or active_source,
2746 queue_item_id=self.current_media.queue_item_id,
2747 elapsed_time=elapsed_time,
2748 elapsed_time_last_updated=elapsed_time_last_updated,
2749 )
2750 return None
2751
2752 def _resolved_palette(self, image_url: str | None) -> MediaItemPalette | None:
2753 """Return the carried palette if it matches image_url, else None."""
2754 if image_url and image_url == self._attr_current_palette_url:
2755 return self._attr_current_palette
2756 return None
2757
2758 @cached_property
2759 @final
2760 def __final_source_list(self) -> UniqueList[PlayerSource]:
2761 """Return the FINAL source list for the player."""
2762 sources = UniqueList(self.source_list)
2763 if self.type == PlayerType.PROTOCOL:
2764 return sources
2765 # always ensure the Music Assistant Queue is in the source list
2766 mass_source = next((x for x in sources if x.id == self.player_id), None)
2767 if mass_source is None:
2768 # if the MA queue is not in the source list, add it.
2769 # The capability flags reflect what the queue can actually do right now, so clients can
2770 # grey out controls instead of issuing commands that can only fail: an empty queue has
2771 # nothing to play, seek or skip through, and a queue that played to its end can only be
2772 # started over, with nothing left to seek within or skip to.
2773 queue = self.mass.player_queues.get(self.player_id)
2774 queue_has_items = bool(queue and queue.items)
2775 queue_running = queue_has_items and not (queue and queue.ended)
2776 mass_source = PlayerSource(
2777 id=self.player_id,
2778 name="Music Assistant Queue",
2779 passive=False,
2780 can_play_pause=queue_has_items,
2781 can_seek=queue_running,
2782 can_next_previous=queue_running,
2783 )
2784 sources.append(mass_source)
2785 return sources
2786
2787 @cached_property
2788 @final
2789 def __final_group_members(self) -> list[str]:
2790 """Return the FINAL group members of this player."""
2791 if self.__final_synced_to:
2792 # If player is synced to another player, it has no group members itself
2793 return []
2794
2795 # Start by translating native group_members to visible player IDs
2796 # This handles cases where a native player (e.g., native AirPlay) has grouped
2797 # protocol players (e.g., Sonos AirPlay protocol players) that need translation
2798 members: list[str] = []
2799 if self.type == PlayerType.PROTOCOL:
2800 # protocol players use their own group members without translation
2801 members.extend(self.group_members)
2802 else:
2803 translated_members = self._translate_protocol_ids_to_visible(set(self.group_members))
2804 for member in translated_members:
2805 if member.player_id not in members:
2806 members.append(member.player_id)
2807
2808 # If there's an active linked protocol, include its group members (translated)
2809 if self.__attr_active_output_protocol and self.__attr_active_output_protocol != "native":
2810 if protocol_player := self.mass.players.get_player(self.__attr_active_output_protocol):
2811 # Translate protocol player IDs to visible player IDs
2812 protocol_members = self._translate_protocol_ids_to_visible(
2813 set(protocol_player.group_members)
2814 )
2815 for member in protocol_members:
2816 if member.player_id not in members:
2817 members.append(member.player_id)
2818
2819 if self.type != PlayerType.GROUP:
2820 # Ensure the player_id is first in the group_members list
2821 if len(members) > 0 and members[0] != self.player_id:
2822 members = [self.player_id, *[m for m in members if m != self.player_id]]
2823 # If the only member is self, return empty list
2824 if members == [self.player_id]:
2825 return []
2826 return members
2827
2828 @cached_property
2829 @final
2830 def __final_synced_to(self) -> str | None:
2831 """
2832 Return the FINAL synced_to state.
2833
2834 This checks both native sync state and protocol player sync state,
2835 translating protocol player IDs to visible player IDs.
2836 """
2837 # First check the native synced_to from the property
2838 if native_synced_to := self.synced_to:
2839 if sync_parent := self.mass.players.get_player(native_synced_to):
2840 return sync_parent.protocol_parent_id or sync_parent.player_id
2841
2842 return native_synced_to
2843 # check if any of the linked protocol players are synced,
2844 # and if so, return the visible player they are synced to
2845 for linked in self.__attr_linked_protocols:
2846 if not (protocol_player := self.mass.players.get_player(linked.output_protocol_id)):
2847 continue
2848 if protocol_player.synced_to:
2849 # Protocol player is synced, translate to visible player
2850 if proto_sync_parent := self.mass.players.get_player(protocol_player.synced_to):
2851 if proto_sync_parent.type != PlayerType.PROTOCOL:
2852 # Sync parent is already a visible player (e.g., native AirPlay player)
2853 return proto_sync_parent.player_id
2854 if proto_sync_parent.protocol_parent_id and (
2855 parent := self.mass.players.get_player(proto_sync_parent.protocol_parent_id)
2856 ):
2857 # Sync parent is a protocol player, return its visible parent
2858 return parent.player_id
2859
2860 return None
2861
2862 @cached_property
2863 @final
2864 def __final_supported_features(self) -> set[PlayerFeature]:
2865 """Return the FINAL supported features based supported output protocol(s)."""
2866 base_features = self.supported_features.copy()
2867 if self.__attr_active_output_protocol and self.__attr_active_output_protocol != "native":
2868 # Active linked protocol: add from that specific protocol
2869 if protocol_player := self.mass.players.get_player(self.__attr_active_output_protocol):
2870 for feature in protocol_player.supported_features:
2871 if feature in ACTIVE_PROTOCOL_FEATURES:
2872 base_features.add(feature)
2873 # Append (allowed features) from all linked protocols
2874 for linked in self.__attr_linked_protocols:
2875 if protocol_player := self.mass.players.get_player(linked.output_protocol_id):
2876 for feature in protocol_player.supported_features:
2877 if feature in PROTOCOL_FEATURES:
2878 base_features.add(feature)
2879 if self.power_control != PLAYER_CONTROL_NONE:
2880 base_features.add(PlayerFeature.POWER)
2881 else:
2882 base_features.discard(PlayerFeature.POWER)
2883 if self.volume_control != PLAYER_CONTROL_NONE:
2884 base_features.add(PlayerFeature.VOLUME_SET)
2885 else:
2886 base_features.discard(PlayerFeature.VOLUME_SET)
2887 if self.mute_control != PLAYER_CONTROL_NONE:
2888 base_features.add(PlayerFeature.VOLUME_MUTE)
2889 else:
2890 base_features.discard(PlayerFeature.VOLUME_MUTE)
2891 if sum(1 for s in self.__final_source_list if not s.passive) >= 2:
2892 base_features.add(PlayerFeature.SELECT_SOURCE)
2893 return base_features
2894
2895 @cached_property
2896 @final
2897 def __final_can_group_with(self) -> set[str]:
2898 """
2899 Return the FINAL set of player id's this player can group with.
2900
2901 This is a convenience property which calculates the final can_group_with set
2902 based on any linked protocol players and current player/grouped state.
2903
2904 If player is synced to a native parent: return empty set (already grouped).
2905 If player is synced to a protocol: can still group with other players.
2906 If no active linked protocol: return can_group_with from all active output protocols.
2907 If active linked protocol: return native can_group_with + active protocol's.
2908
2909 All protocol player IDs are translated to their visible parent player IDs.
2910 """
2911
2912 def _should_include_player(player: Player) -> bool:
2913 """Check if a player should be included in the can-group-with set."""
2914 if not player.available:
2915 return False
2916 if player.player_id == self.player_id:
2917 return False # Don't include self
2918 # Don't include (playing) players that have group members (they are group leaders)
2919 if ( # noqa: SIM103
2920 player.state.playback_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
2921 and player.group_members
2922 ):
2923 return False
2924 return True
2925
2926 if self.__final_synced_to:
2927 # player is already synced/grouped, cannot group with others
2928 return set()
2929
2930 expanded_can_group_with = self._expand_can_group_with()
2931 # Scenario 1: Player is a protocol player - just return the (expanded) result
2932 if self.type == PlayerType.PROTOCOL:
2933 return {x.player_id for x in expanded_can_group_with}
2934
2935 result: set[str] = set()
2936 # always start with the native can_group_with options (expanded from provider instance IDs)
2937 # NOTE we need to translate protocol player IDs to visible player IDs here as well,
2938 # to cover cases where a native player (e.g., native AirPlay) has grouped protocol players
2939 # (e.g., Sonos AirPlay protocol players)
2940 for player in expanded_can_group_with:
2941 if player.type == PlayerType.PROTOCOL:
2942 if not player.protocol_parent_id:
2943 continue
2944 parent_player = self.mass.players.get_player(player.protocol_parent_id)
2945 if not parent_player or not _should_include_player(parent_player):
2946 continue
2947 result.add(parent_player.player_id)
2948 elif _should_include_player(player):
2949 result.add(player.player_id)
2950
2951 # Scenario 2: External source is active - don't include protocol-based grouping
2952 # When an external source (e.g., Spotify Connect, TV) is active, grouping via
2953 # protocols (AirPlay, Sendspin, etc.) wouldn't work - only native grouping is available.
2954 if self._has_external_source_active():
2955 return result
2956
2957 # Translate can_group_with from active linked protocol(s) and add to result
2958 for linked in self.__attr_linked_protocols:
2959 if protocol_player := self.mass.players.get_player(linked.output_protocol_id):
2960 for player in self._translate_protocol_ids_to_visible(
2961 protocol_player.state.can_group_with
2962 ):
2963 if not _should_include_player(player):
2964 continue
2965 result.add(player.player_id)
2966 return result
2967
2968 @cached_property
2969 @final
2970 def __final_active_source(self) -> str | None:
2971 """
2972 Calculate the final active source based on any group memberships, source plugins etc.
2973
2974 This is rather complicated as we need to account for various scenarios like:
2975 - player is grouped/synced: use the active source of the group/parent player
2976 - protocol player: prefer the active source of the parent player
2977 - plugin source active: return the active plugin source
2978 - linked protocol active: prefer the active source of the linked protocol player
2979 - a protocol player may report an active source that is actually from an
2980 active output protocol (e.g. AirPlay)
2981 - a protocol player that has a 3rd party source active
2982 """
2983 # if the player is grouped/synced, use the active source of the group/parent player
2984 if parent_player_id := (self.__final_synced_to or self.__final_active_group):
2985 if parent_player := self.mass.players.get_player(parent_player_id):
2986 return parent_player.state.active_source
2987 return None # should not happen but just in case
2988
2989 # if this is a protocol player, prefer the active source of the parent player
2990 # a protocol player can not have an active source on its own.
2991 if (
2992 self.type == PlayerType.PROTOCOL
2993 and self.protocol_parent_id
2994 and (parent_player := self.mass.players.get_player(self.protocol_parent_id))
2995 ):
2996 return parent_player.state.active_source
2997
2998 # always prefer active MA source but add a guard to detect if player is really playing
2999 # something different, such as a line-in or TV input, we use an explicit list here
3000 # because many players do not accurately report the active_source
3001 # this way, for the obvious cases, we can detect a source "takeover"
3002 if self.__active_mass_source and (
3003 not self.active_source or self.active_source.lower() not in EXTERNAL_SOURCES
3004 ):
3005 return self.__active_mass_source
3006
3007 # active source as reported by the player itself
3008 if (
3009 self.active_source
3010 and self.active_source != self.player_id
3011 and self.playback_state != PlaybackState.IDLE
3012 # If an output protocol is active, we simply overrule the active source of the player.
3013 # Trying to handle this differently is a hot mess and leads to all kinds of edge cases,
3014 # because many players do not report the active source correctly, especially not when
3015 # an output protocol is active.
3016 and self.active_output_protocol in (None, "native")
3017 ):
3018 return self.active_source
3019
3020 # return the (last) known MA source - fallback to player's own queue source if none
3021 return self.__active_mass_source or self.player_id
3022
3023 @final
3024 def _translate_protocol_ids_to_visible(self, player_ids: set[str]) -> set[Player]:
3025 """
3026 Translate protocol player IDs to their visible parent players.
3027
3028 Protocol players are hidden and users interact with visible players
3029 (native or universal). This method translates protocol player IDs
3030 back to the visible (parent) players.
3031
3032 :param player_ids: Set of player IDs.
3033 :return: Set of visible players.
3034 """
3035 result: set[Player] = set()
3036 if not player_ids:
3037 return result
3038 for player_id in player_ids:
3039 target_player = self.mass.players.get_player(player_id)
3040 if not target_player:
3041 continue
3042 if target_player.type != PlayerType.PROTOCOL:
3043 # Non-protocol player is already visible - include directly
3044 result.add(target_player)
3045 continue
3046 # This is a protocol player - find its visible parent
3047 if not target_player.protocol_parent_id:
3048 continue
3049 parent_player = self.mass.players.get_player(target_player.protocol_parent_id)
3050 if not parent_player:
3051 continue
3052 result.add(parent_player)
3053 return result
3054
3055 @final
3056 def _has_external_source_active(self) -> bool:
3057 """
3058 Check if an external (non-MA-managed) source is currently active.
3059
3060 External sources include things like Spotify Connect, TV input, etc.
3061 When an external source is active, protocol-based grouping is not available.
3062
3063 :return: True if an external source is active, False otherwise.
3064 """
3065 active_source = self.__final_active_source
3066 if active_source is None:
3067 return False
3068
3069 # Player's own ID means MA queue is (or was) active
3070 if active_source == self.player_id:
3071 return False
3072
3073 # If it's a known queue ID it's MA-managed; anything else is external
3074 # (line-in, TV input, etc.)
3075 return self.mass.player_queues.get(active_source) is None
3076
3077 @final
3078 def _expand_can_group_with(self) -> set[Player]:
3079 """
3080 Expand the 'can-group-with' to include all players from provider instance IDs.
3081
3082 This method expands any provider instance IDs (e.g., "airplay", "chromecast")
3083 in the group members to all (available) players of that provider
3084
3085 :return: Set of available players in the can-group-with.
3086 """
3087 result = set()
3088
3089 for member_id in self.can_group_with:
3090 if player := self.mass.players.get_player(member_id):
3091 result.add(player)
3092 continue # already a player ID
3093 # Check if member_id is a provider instance ID
3094 if provider := self.mass.get_provider(member_id):
3095 for player in self.mass.players.iter_players(
3096 return_unavailable=False, # Only include available players
3097 provider_filter=provider.instance_id,
3098 return_protocol_players=True,
3099 ):
3100 result.add(player)
3101 return result
3102
3103 # The id of the (last) active mass source.
3104 # This is to keep track of the last active MA source for the player,
3105 # so we can restore it when needed (e.g. after switching to a plugin source).
3106 __active_mass_source: str | None = None
3107
3108 @final
3109 def set_active_mass_source(self, value: str | None) -> None:
3110 """
3111 Set the id of the (last) active mass source.
3112
3113 This is to keep track of the last active MA source for the player,
3114 so we can restore it when needed (e.g. after switching to a plugin source).
3115 """
3116 self.mass.cancel_timer(f"set_mass_source_{self.player_id}")
3117 self.__active_mass_source = value
3118 self.update_state()
3119
3120 __sleep_timer_expires_at: float | None = None
3121
3122 @final
3123 def set_sleep_timer_expires_at(self, value: float | None) -> None:
3124 """
3125 Set the unix (utc) timestamp at which the active sleep timer stops playback.
3126
3127 :param value: The expiry timestamp, or None to clear the sleep timer.
3128 """
3129 self.__sleep_timer_expires_at = value
3130
3131 @property
3132 @final
3133 def sleep_timer_expires_at(self) -> float | None:
3134 """Return the unix (utc) timestamp at which the active sleep timer stops playback."""
3135 return self.__sleep_timer_expires_at
3136
3137 __stop_called: bool = False
3138
3139 @final
3140 def mark_stop_called(self) -> None:
3141 """Mark that the STOP command was called on the player."""
3142 self.__stop_called = True
3143
3144 @property
3145 @final
3146 def stop_called(self) -> bool:
3147 """
3148 Return True if the STOP command was called on the player.
3149
3150 This is used to differentiate between a user-initiated stop
3151 and a natural end of playback (e.g. end of track/queue).
3152 mainly for debugging/logging purposes by the streams controller.
3153 """
3154 return self.__stop_called
3155
3156 def __hash__(self) -> int:
3157 """Return a hash of the Player."""
3158 return hash(self.player_id)
3159
3160 def __str__(self) -> str:
3161 """Return a string representation of the Player."""
3162 return f"Player {self.name} ({self.player_id})"
3163
3164 def __repr__(self) -> str:
3165 """Return a string representation of the Player."""
3166 return f"<Player name={self.name} id={self.player_id} available={self.available}>"
3167
3168 def __eq__(self, other: object) -> bool:
3169 """Check equality of two Player objects."""
3170 if not isinstance(other, Player):
3171 return False
3172 return self.player_id == other.player_id
3173
3174 def __ne__(self, other: object) -> bool:
3175 """Check inequality of two Player objects."""
3176 return not self.__eq__(other)
3177
3178
3179__all__ = [
3180 # explicitly re-export the models we imported from the models package,
3181 # for convenience reasons
3182 "EXTRA_ATTRIBUTES_TYPES",
3183 "DeviceInfo",
3184 "Player",
3185 "PlayerMedia",
3186 "PlayerSource",
3187 "PlayerState",
3188]
3189