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