/
/
1"""
2Protocol Linking Mixin for the Player Controller.
3
4Handles all logic for linking protocol players (AirPlay, Chromecast, DLNA) to
5native players or wrapping them in Universal Players.
6
7This module provides the ProtocolLinkingMixin class which is inherited by
8PlayerController to add protocol linking capabilities.
9"""
10
11from __future__ import annotations
12
13import asyncio
14import logging
15from contextlib import suppress
16from copy import deepcopy
17from typing import TYPE_CHECKING, cast
18
19from music_assistant_models.enums import (
20 EventType,
21 IdentifierType,
22 PlaybackState,
23 PlayerFeature,
24 PlayerType,
25 ProviderType,
26)
27from music_assistant_models.errors import PlayerCommandFailed, PlayerUnavailableError
28
29from music_assistant.constants import (
30 CONF_CACHED_ARP_MAC,
31 CONF_GROUP_MEMBERS,
32 CONF_LINKED_PROTOCOL_IDS,
33 CONF_PLAYER_DSP,
34 CONF_PLAYER_QUEUES,
35 CONF_PLAYERS,
36 CONF_PREFERRED_OUTPUT_PROTOCOL,
37 CONF_PROTOCOL_KEY_SPLITTER,
38 CONF_PROTOCOL_PARENT_ID,
39 CONF_REPORTED_MAC,
40 CONF_UNDERLYING_PLAYER_ID,
41 PROTOCOL_PRIORITY,
42 VERBOSE_LOG_LEVEL,
43)
44from music_assistant.helpers.util import (
45 is_locally_administered_mac,
46 is_valid_mac_address,
47 normalize_mac_for_matching,
48)
49from music_assistant.models.player import LinkedOutputProtocol, Player
50from music_assistant.providers.sync_group.constants import CONF_ALLOWED_MEMBERS
51from music_assistant.providers.universal_player import UniversalPlayer, UniversalPlayerProvider
52from music_assistant.providers.universal_player.constants import (
53 CONF_CREATED_AT,
54 CONF_DEVICE_IDENTIFIERS,
55 CONF_DEVICE_INFO,
56)
57
58if TYPE_CHECKING:
59 from collections.abc import Coroutine
60 from typing import Any
61
62 from music_assistant_models.player import OutputProtocol
63
64 from music_assistant import MusicAssistant
65
66# Config value keys that are bookkeeping of the universal player wrapper itself
67# (protocol links, device-identity caches and its creation moment) and must never
68# be carried over when a native player replaces a universal player, or when one
69# universal player absorbs another.
70UNIVERSAL_PLAYER_INTERNAL_CONF_KEYS = (
71 CONF_LINKED_PROTOCOL_IDS,
72 CONF_PROTOCOL_PARENT_ID,
73 CONF_UNDERLYING_PLAYER_ID,
74 CONF_DEVICE_IDENTIFIERS,
75 CONF_DEVICE_INFO,
76 CONF_CACHED_ARP_MAC,
77 CONF_REPORTED_MAC,
78 CONF_CREATED_AT,
79)
80
81
82class ProtocolLinkingMixin:
83 """
84 Mixin class providing protocol linking functionality for PlayerController.
85
86 Handles the complex logic of:
87 - Matching protocol players to native players via device identifiers
88 - Creating Universal Players for devices without native support
89 - Managing protocol links and their lifecycle
90 - Selecting the best output protocol for playback
91
92 This mixin expects to be mixed with a class that provides:
93 - mass: MusicAssistant instance
94 - _players: dict of registered players
95 - _pending_protocol_evaluations: dict of pending protocol evaluations
96 - logger: logging.Logger instance
97 - all(): method to get all players
98 - get(): method to get a player by ID
99 - unregister(): method to unregister a player
100 """
101
102 # Type hints for attributes provided by the class this mixin is used with
103 if TYPE_CHECKING:
104 mass: MusicAssistant
105 _players: dict[str, Player]
106 _pending_protocol_evaluations: dict[str, asyncio.TimerHandle]
107 _delayed_evaluation_lock: asyncio.Lock
108 logger: logging.Logger
109
110 def all_players( # noqa: D102
111 self,
112 return_unavailable: bool = True,
113 return_disabled: bool = False,
114 provider_filter: str | None = None,
115 return_protocol_players: bool = False,
116 ) -> list[Player]: ...
117
118 def get_player(self, player_id: str) -> Player | None: ... # noqa: D102
119
120 def unregister( # noqa: D102
121 self,
122 player_id: str,
123 permanent: bool = False,
124 replacement_player_id: str | None = None,
125 ) -> Coroutine[Any, Any, None]: ...
126
127 def _is_protocol_player(self, player: Player) -> bool:
128 """
129 Check if a player is a generic protocol player without native support.
130
131 Protocol players have PlayerType.PROTOCOL set by their provider, indicating
132 they are generic streaming endpoints (e.g., AirPlay receiver, Chromecast device)
133 without vendor-specific native support in Music Assistant.
134 """
135 return player.state.type == PlayerType.PROTOCOL
136
137 def _evaluate_protocol_links(self, player: Player) -> None:
138 """
139 Evaluate and establish protocol links for a player.
140
141 Called when a player is registered to:
142 1. If it's from a protocol provider - try to link to a native player.
143 2. If it's a native player - try to link any existing protocol players.
144 """
145 if player.state.type == PlayerType.PROTOCOL:
146 # Protocol player: try to find a native parent
147 self._try_link_protocol_to_native(player)
148 elif player.state.type == PlayerType.GROUP:
149 return
150 else:
151 # A player that registers with a non-protocol type can no longer be a
152 # protocol child: drop a leftover persisted parent link (e.g. from a
153 # bridge client that turned web player) so the startup repair pass
154 # doesn't heal its player type back to protocol.
155 if self._get_cached_protocol_parent_id(player.player_id):
156 self._clear_protocol_parent_id(player.player_id)
157 # Native player (including STEREO_PAIR): try to find protocol players to link
158 self._try_link_protocols_to_native(player)
159
160 def _try_link_protocol_to_native(self, protocol_player: Player) -> None:
161 """Try to link a protocol player to a native player."""
162 protocol_domain = protocol_player.provider.domain
163
164 # Derived protocol players (e.g. Sendspin bridges riding on another
165 # protocol) resolve strictly via their underlying player - no identifier
166 # matching or delayed evaluation. If the underlying player has no parent
167 # yet, the link is established by _link_derived_protocols_of as soon as
168 # the underlying player gets linked.
169 if protocol_player.underlying_player_id:
170 self._try_link_derived_protocol(protocol_player)
171 return
172
173 # Check for cached parent_id from previous session and restore link immediately
174 cached_parent_id = self._get_cached_protocol_parent_id(protocol_player.player_id)
175 if cached_parent_id:
176 result = self._try_restore_cached_parent(
177 protocol_player, cached_parent_id, protocol_domain
178 )
179 if result:
180 return
181 # Link was refused or parent has active domain - fall through to search
182
183 # Look for a matching native player
184 if self._try_link_to_existing_player(protocol_player, protocol_domain):
185 return
186
187 # No native player found - schedule delayed evaluation to allow other protocols to register
188 if not protocol_player.protocol_parent_id:
189 self._schedule_protocol_evaluation(protocol_player)
190
191 def _try_restore_cached_parent(
192 self, protocol_player: Player, cached_parent_id: str, protocol_domain: str
193 ) -> bool:
194 """
195 Try to restore a cached parent link from a previous session.
196
197 :param protocol_player: The protocol player to link.
198 :param cached_parent_id: The cached parent player ID.
199 :param protocol_domain: The protocol domain (e.g., "airplay").
200 :return: True if handled (linked or waiting), False if should fall through.
201 """
202 if parent_player := self.get_player(cached_parent_id):
203 if parent_player.state.type == PlayerType.GROUP:
204 self._clear_protocol_parent_id(protocol_player.player_id)
205 return False
206 already_linked = any(
207 link.output_protocol_id == protocol_player.player_id
208 for link in parent_player.linked_output_protocols
209 )
210 if already_linked:
211 # Already linked from a previous call - just restore parent and identifiers
212 protocol_player.set_protocol_parent_id(cached_parent_id)
213 else:
214 # Try to add the link (may be refused if domain already has active link)
215 self._add_protocol_link(parent_player, protocol_player, protocol_domain)
216 if protocol_player.protocol_parent_id:
217 protocol_player.refresh_state()
218 parent_player.refresh_state()
219 # Merge the protocol player's identifiers into the universal player
220 # so identifiers discovered since the last persist (e.g. an
221 # ARP-resolved MAC) are included and new protocol players
222 # (like Sendspin bridges) can match via identifiers.
223 if parent_player.provider.domain == "universal_player" and isinstance(
224 parent_player, UniversalPlayer
225 ):
226 for conn_type, value in protocol_player.device_info.identifiers.items():
227 parent_player.device_info.add_identifier(conn_type, value)
228 self._update_universal_device_info(parent_player, protocol_player)
229 # Check if this universal player should now be merged with another
230 # (e.g., DLNA brought a MAC via ARP that matches an AirPlay universal)
231 self._check_merge_universal_players(parent_player)
232 return True
233 # Link was refused (domain already active on parent) - fall through
234 return False
235
236 # Parent is not registered yet. Leave the protocol player unparented
237 # so the caller schedules delayed evaluation, which can wait for the
238 # cached parent without stranding the protocol player on a dangling id.
239 return False
240
241 def _try_link_to_existing_player(self, protocol_player: Player, protocol_domain: str) -> bool:
242 """
243 Try to link a protocol player to an existing native or universal player.
244
245 :param protocol_player: The protocol player to link.
246 :param protocol_domain: The protocol domain (e.g., "airplay").
247 :return: True if linked successfully, False if no match found.
248 """
249 # Protocol players should only link to:
250 # 1. True native players (Sonos, etc.)
251 # 2. Universal players
252 # NOT to other protocol players (they get merged via universal_player)
253 for native_player in self.all_players(return_protocol_players=False):
254 if native_player.player_id == protocol_player.player_id:
255 continue
256 if native_player.state.type in (PlayerType.PROTOCOL, PlayerType.GROUP):
257 continue
258
259 # For universal players, check if this protocol player is in its stored list
260 # or if identifiers match (for new protocol players like Sendspin bridges
261 # that weren't previously known to the Universal Player)
262 if native_player.provider.domain == "universal_player":
263 if isinstance(native_player, UniversalPlayer):
264 is_known = protocol_player.player_id in native_player._protocol_player_ids
265 is_match = not is_known and self._identifiers_match(
266 native_player, protocol_player, protocol_domain
267 )
268 if is_known or is_match:
269 self._add_protocol_link(native_player, protocol_player, protocol_domain)
270 # Check if linking actually succeeded (may be refused for
271 # duplicate domain)
272 if not protocol_player.protocol_parent_id:
273 continue
274 # Merge the protocol player's identifiers into the universal
275 # player so newly discovered identifiers are included as well
276 for conn_type, value in protocol_player.device_info.identifiers.items():
277 native_player.device_info.add_identifier(conn_type, value)
278 # Update model/manufacturer if universal player has generic values
279 self._update_universal_device_info(native_player, protocol_player)
280 # Register newly matched protocol player with the universal player
281 if is_match:
282 native_player.add_protocol_player(protocol_player.player_id)
283 # Persist updated data to config (async via task)
284 self._save_universal_player_data(native_player)
285 # Check if this universal player should now be merged with another
286 self._check_merge_universal_players(native_player)
287 protocol_player.refresh_state()
288 native_player.refresh_state()
289 return True
290 continue
291
292 # Check cached protocol IDs first for fast matching on restart
293 cached_ids = self._get_cached_protocol_ids(native_player.player_id)
294 if protocol_player.player_id in cached_ids:
295 self._add_protocol_link(native_player, protocol_player, protocol_domain)
296 if protocol_player.protocol_parent_id:
297 protocol_player.refresh_state()
298 native_player.refresh_state()
299 return True
300 # Link refused (domain duplicate) - try next native player
301 continue
302
303 # Fallback to identifier matching
304 if self._identifiers_match(native_player, protocol_player, protocol_domain):
305 self._add_protocol_link(native_player, protocol_player, protocol_domain)
306 if protocol_player.protocol_parent_id:
307 protocol_player.refresh_state()
308 native_player.refresh_state()
309 return True
310 # Link refused (domain duplicate) - try next native player
311 continue
312
313 # Final fallback: check if any already-linked protocol player on this native
314 # player shares identifiers with the new protocol player ("sibling matching").
315 # This handles native players (e.g., HEOS) that don't have their own MAC/serial
316 # identifiers but have protocol players (e.g., AirPlay) from the same device
317 # that do share identifiers with the new protocol player (e.g., Sendspin bridge).
318 if self._match_via_linked_protocols(native_player, protocol_player, protocol_domain):
319 return True
320
321 return False
322
323 def _match_via_linked_protocols(
324 self,
325 native_player: Player,
326 protocol_player: Player,
327 protocol_domain: str,
328 ) -> bool:
329 """
330 Try to match a protocol player to a native player via sibling protocol identifiers.
331
332 Check if any of the native player's already-linked protocol players share
333 identifiers with the new protocol player. This handles native players that lack
334 their own device identifiers but have sibling protocols from the same physical device.
335
336 :param native_player: The native player to potentially link to.
337 :param protocol_player: The new protocol player to link.
338 :param protocol_domain: The protocol domain of the new player.
339 :return: True if linked successfully, False if no match found.
340 """
341 for linked in native_player.linked_output_protocols:
342 linked_player = self.get_player(linked.output_protocol_id)
343 if not linked_player:
344 continue
345 if self._identifiers_match(linked_player, protocol_player, protocol_domain):
346 self._add_protocol_link(native_player, protocol_player, protocol_domain)
347 if protocol_player.protocol_parent_id:
348 protocol_player.refresh_state()
349 native_player.refresh_state()
350 return True
351 # Link refused (domain duplicate) - stop checking siblings
352 break
353 return False
354
355 def _try_link_derived_protocol(self, protocol_player: Player) -> bool:
356 """
357 Link a derived protocol player to the parent of its underlying player.
358
359 Derived protocol players carry an underlying_player_id declared by their
360 bridge, which makes the parent resolution deterministic: they always join
361 the parent of the player they ride on (or that player itself when it is
362 not a protocol player). Callers must ensure the player is not linked yet.
363
364 :param protocol_player: The derived protocol player to link.
365 :return: True if the player got linked, False if the underlying player
366 (or its parent) is not available yet or the link was refused.
367 """
368 underlying = self.get_player(protocol_player.underlying_player_id or "")
369 if underlying is None:
370 return False
371 if underlying.state.type == PlayerType.PROTOCOL:
372 parent = (
373 self.get_player(underlying.protocol_parent_id)
374 if underlying.protocol_parent_id
375 else None
376 )
377 else:
378 parent = underlying
379 if parent is None or parent.state.type == PlayerType.GROUP:
380 return False
381
382 self._add_protocol_link(parent, protocol_player, protocol_player.provider.domain)
383 if not protocol_player.protocol_parent_id:
384 # Link refused (e.g. parent already has an active link from this domain)
385 return False
386
387 if parent.provider.domain == "universal_player" and isinstance(parent, UniversalPlayer):
388 # Track membership and identifiers on the universal player so the
389 # derived protocol restores quickly on the next start.
390 parent.add_protocol_player(protocol_player.player_id)
391 for conn_type, value in protocol_player.device_info.identifiers.items():
392 parent.device_info.add_identifier(conn_type, value)
393 self._save_universal_player_data(parent)
394
395 protocol_player.refresh_state()
396 parent.refresh_state()
397 self.logger.debug(
398 "Linked derived protocol %s to %s (via underlying %s)",
399 protocol_player.player_id,
400 parent.player_id,
401 underlying.player_id,
402 )
403 return True
404
405 def _link_derived_protocols_of(self, underlying_player: Player) -> None:
406 """
407 Link any waiting derived protocol players that ride on the given player.
408
409 Called after a player is linked to a parent (or registered as a native
410 player), so derived protocol players that registered earlier can join
411 the same parent.
412 """
413 for candidate in self.all_players(return_protocol_players=True):
414 if candidate.underlying_player_id != underlying_player.player_id:
415 continue
416 if candidate.protocol_parent_id:
417 continue
418 self._try_link_derived_protocol(candidate)
419
420 def _schedule_protocol_evaluation(self, protocol_player: Player) -> None:
421 """
422 Schedule a delayed protocol evaluation.
423
424 Delays evaluation to allow other protocol players and native players to register.
425 Uses a longer delay (30s) if this protocol player was previously linked to a native
426 player that hasn't registered yet, giving native providers time to start up.
427 """
428 player_id = protocol_player.player_id
429
430 # Cancel any existing pending evaluation for this player
431 if player_id in self._pending_protocol_evaluations:
432 self._pending_protocol_evaluations[player_id].cancel()
433
434 # Check if this protocol player has a cached parent (was previously linked)
435 cached_parent_id = self._get_cached_protocol_parent_id(player_id)
436 if cached_parent_id and not self.get_player(cached_parent_id):
437 # Previously linked to a native player that hasn't registered yet
438 # Use longer delay to give native providers time to start up
439 delay = 45.0
440 self.logger.debug(
441 "Protocol player %s waiting for cached parent %s (45s delay)",
442 player_id,
443 cached_parent_id,
444 )
445 else:
446 # Standard delay for protocol player discovery
447 # Allows time for other protocols and native players to register
448 delay = 15.0
449
450 # Schedule evaluation after the delay
451 handle = self.mass.loop.call_later(
452 delay,
453 lambda: self.mass.create_task(self._delayed_protocol_evaluation(player_id)),
454 )
455 self._pending_protocol_evaluations[player_id] = handle
456
457 async def _delayed_protocol_evaluation(self, player_id: str) -> None:
458 """
459 Perform delayed protocol evaluation.
460
461 Called after a delay to allow all protocol players for a device to register.
462 Decides whether to create a universal player, join an existing one, or
463 promote a single protocol player directly.
464
465 Uses a shared lock to serialize evaluations - multiple protocol players from the
466 same device may trigger concurrent evaluations that would otherwise race each other.
467 """
468 self._pending_protocol_evaluations.pop(player_id, None)
469
470 async with self._delayed_evaluation_lock:
471 protocol_player = self.get_player(player_id)
472 if not protocol_player or protocol_player.protocol_parent_id:
473 return
474 if protocol_player.state.type != PlayerType.PROTOCOL:
475 # The player changed type while the evaluation was pending
476 # (e.g. re-registered as a regular player); it must never be
477 # linked as a protocol or wrapped in a universal player.
478 return
479
480 # Derived protocol players resolve strictly via their underlying
481 # player and never match by identifiers or wrap into universal
482 # players; they wait for _link_derived_protocols_of otherwise.
483 if protocol_player.underlying_player_id:
484 self._try_link_derived_protocol(protocol_player)
485 return
486
487 protocol_domain = protocol_player.provider.domain
488
489 # Re-try linking to an existing native/universal player
490 if self._try_link_to_existing_player(protocol_player, protocol_domain):
491 return
492
493 # Check if there's an existing universal player we should join
494 if existing_universal := self._find_matching_universal_player(protocol_player):
495 await self._add_protocol_to_existing_universal(
496 existing_universal, protocol_player, protocol_domain
497 )
498 if protocol_player.protocol_parent_id is not None:
499 return
500 # Link refused (domain duplicate) - fall through to create separate UP
501
502 # Refuse to create a universal player wrapper when the cached parent
503 # config exists but is disabled. The user explicitly turned the
504 # parent device off; surfacing its protocols as a separate player
505 # would defeat that intent.
506 cached_parent_id = self._get_cached_protocol_parent_id(player_id)
507 if cached_parent_id:
508 parent_raw = self.mass.config.get(f"{CONF_PLAYERS}/{cached_parent_id}")
509 if parent_raw and not parent_raw.get("enabled", True):
510 self.logger.debug(
511 "Skipping universal player creation for %s: cached parent %s is disabled",
512 player_id,
513 cached_parent_id,
514 )
515 return
516
517 # Find all protocol players that match this device's identifiers
518 matching_protocols = self._find_matching_protocol_players(protocol_player)
519
520 # Create or update UniversalPlayer for all protocol players
521 await self._create_or_update_universal_player(matching_protocols)
522
523 def _find_matching_protocol_players(self, protocol_player: Player) -> list[Player]:
524 """
525 Find all protocol players that match the same device as the given player.
526
527 Searches through all registered protocol players to find ones that share
528 identifiers (MAC, IP, UUID) with the given player, indicating they represent
529 the same physical device.
530 """
531 matching = [protocol_player]
532 protocol_domain = protocol_player.provider.domain
533
534 for other_player in self.all_players(return_protocol_players=True):
535 if other_player.player_id == protocol_player.player_id:
536 continue
537 if other_player.state.type != PlayerType.PROTOCOL:
538 continue
539 if other_player.protocol_parent_id:
540 continue
541 if other_player.underlying_player_id:
542 # Derived protocol players follow their underlying player
543 # once it is linked; they never seed a universal player.
544 continue
545 # Skip players from the same protocol domain
546 # Multiple instances of the same protocol on one host are separate players
547 if other_player.provider.domain == protocol_domain:
548 continue
549 if self._identifiers_match(protocol_player, other_player):
550 matching.append(other_player)
551
552 return matching
553
554 def _find_matching_universal_player(self, protocol_player: Player) -> Player | None:
555 """Find an existing universal player that matches this protocol player."""
556 for player in self._players.values():
557 if not isinstance(player, UniversalPlayer):
558 continue
559 if self._identifiers_match(protocol_player, player, ""):
560 return player
561 return None
562
563 async def _add_protocol_to_existing_universal(
564 self, universal_player: Player, protocol_player: Player, protocol_domain: str
565 ) -> None:
566 """Add a protocol player to an existing universal player."""
567 # Refuse if the universal player already has a registered player from this domain.
568 # This prevents a second instance (e.g., two snapcast players on the same host)
569 # from replacing the first. The caller falls through to create a separate UP.
570 for link in universal_player.linked_output_protocols:
571 if link.protocol_domain == protocol_domain and self.get_player(link.output_protocol_id):
572 return
573
574 self._add_protocol_link(universal_player, protocol_player, protocol_domain)
575
576 # Check if linking actually succeeded (may be refused for duplicate domain)
577 if not protocol_player.protocol_parent_id:
578 return
579
580 if isinstance(universal_player, UniversalPlayer):
581 universal_player.add_protocol_player(protocol_player.player_id)
582 for conn_type, value in protocol_player.device_info.identifiers.items():
583 universal_player.device_info.add_identifier(conn_type, value)
584 # Update model/manufacturer if universal player has generic values
585 self._update_universal_device_info(universal_player, protocol_player)
586
587 # Persist all player data (protocol IDs, identifiers, device info) to config
588 for provider in self.mass.get_providers(ProviderType.PLAYER):
589 if provider.domain == "universal_player":
590 await cast("UniversalPlayerProvider", provider)._save_player_data(
591 universal_player.player_id, universal_player
592 )
593 break
594
595 # Check if this universal player should now be merged with another
596 self._check_merge_universal_players(universal_player)
597
598 protocol_player.refresh_state()
599 universal_player.refresh_state()
600
601 def _update_universal_device_info(
602 self, universal_player: UniversalPlayer, protocol_player: Player
603 ) -> None:
604 """
605 Update universal player's device info from protocol player if needed.
606
607 A universal player carries generic placeholder device info
608 (model="Universal Player", manufacturer="Music Assistant") when no real
609 values are known for it (yet). This method updates those values from a
610 protocol player that has real device info.
611 """
612 # Check if universal player has generic placeholder device info
613 device_info = universal_player.device_info
614 protocol_info = protocol_player.device_info
615
616 # Update model if universal player has generic value
617 if device_info.model in (None, "Universal Player") and protocol_info.model:
618 device_info.model = protocol_info.model
619
620 # Update manufacturer if universal player has generic value
621 if device_info.manufacturer in (None, "Music Assistant") and protocol_info.manufacturer:
622 device_info.manufacturer = protocol_info.manufacturer
623
624 def _save_universal_player_data(self, universal_player: UniversalPlayer) -> None:
625 """
626 Save universal player data to config via background task.
627
628 This is a helper to persist player data from synchronous code.
629 """
630
631 async def _do_save() -> None:
632 for provider in self.mass.get_providers(ProviderType.PLAYER):
633 if provider.domain == "universal_player":
634 await cast("UniversalPlayerProvider", provider)._save_player_data(
635 universal_player.player_id, universal_player
636 )
637 break
638
639 self.mass.create_task(_do_save())
640
641 def _get_known_protocol_ids(self, parent: Player) -> list[str]:
642 """
643 Get all protocol IDs tracked for a parent player.
644
645 Includes both active links and cached/inactive protocol IDs so callers can
646 safely migrate or clean up the full parent/protocol relationship.
647 """
648 result: list[str] = []
649 seen: set[str] = set()
650
651 for linked in parent.linked_output_protocols:
652 if linked.output_protocol_id not in seen:
653 result.append(linked.output_protocol_id)
654 seen.add(linked.output_protocol_id)
655
656 if parent.provider.domain == "universal_player" and isinstance(parent, UniversalPlayer):
657 cached_ids = parent._protocol_player_ids
658 else:
659 cached_ids = self._get_cached_protocol_ids(parent.player_id)
660
661 for protocol_id in cached_ids:
662 if protocol_id not in seen:
663 result.append(protocol_id)
664 seen.add(protocol_id)
665
666 return result
667
668 def _migrate_protocol_ids_to_parent(self, parent: Player, protocol_ids: set[str]) -> None:
669 """
670 Persist protocol ownership on a new parent without requiring active links.
671
672 This is used when protocol ownership moves from one parent to another during
673 promotion/merge flows. Active protocols are already linked in memory, but
674 disabled or temporarily unavailable protocols still need their cached parent
675 relationship moved as well.
676 """
677 if not protocol_ids:
678 return
679
680 if parent.provider.domain == "universal_player" and isinstance(parent, UniversalPlayer):
681 for protocol_id in protocol_ids:
682 parent.add_protocol_player(protocol_id)
683 self._save_universal_player_data(parent)
684 else:
685 conf_key = f"{CONF_PLAYERS}/{parent.player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
686 cached_ids = self._get_cached_protocol_ids(parent.player_id)
687 changed = False
688 for protocol_id in protocol_ids:
689 if protocol_id not in cached_ids:
690 cached_ids.append(protocol_id)
691 changed = True
692 if changed:
693 self.mass.config.set(conf_key, cached_ids)
694
695 for protocol_id in protocol_ids:
696 if self.mass.config.get(f"{CONF_PLAYERS}/{protocol_id}"):
697 self._save_protocol_parent_id(protocol_id, parent.player_id)
698
699 def _remove_protocol_ids_from_parent(self, parent: Player, protocol_ids: set[str]) -> None:
700 """
701 Remove protocol ownership from a parent before it is permanently cleaned up.
702
703 This prevents `_cleanup_protocol_links` from treating already-migrated
704 protocols as orphaned when the obsolete parent is unregistered.
705 """
706 if not protocol_ids:
707 return
708
709 remaining_links = [
710 link
711 for link in parent.linked_output_protocols
712 if link.output_protocol_id not in protocol_ids
713 ]
714 if len(remaining_links) != len(parent.linked_output_protocols):
715 parent.set_linked_output_protocols(remaining_links)
716
717 if parent.provider.domain == "universal_player" and isinstance(parent, UniversalPlayer):
718 for protocol_id in protocol_ids:
719 parent.remove_protocol_player(protocol_id)
720 if self.mass.config.get(f"{CONF_PLAYERS}/{parent.player_id}"):
721 self.mass.config.set(
722 f"{CONF_PLAYERS}/{parent.player_id}/values/{CONF_LINKED_PROTOCOL_IDS}",
723 parent._protocol_player_ids,
724 )
725 else:
726 for protocol_id in protocol_ids:
727 self._remove_protocol_id_from_cache(parent.player_id, protocol_id)
728
729 def _check_merge_universal_players(self, universal_player: UniversalPlayer) -> None:
730 """
731 Check if another universal player should be merged into this one.
732
733 Called after identifiers are copied from a protocol player to a universal player.
734 When a protocol player brings new identifiers (e.g., MAC from ARP enrichment),
735 the universal player may now match another universal player that was created
736 from a different protocol (e.g., DLNA-based universal player now matches
737 AirPlay-based universal player because they share the same MAC address).
738
739 The oldest universal player absorbs the other one. Only one merge is performed
740 per call; re-evaluation will catch cascading merges.
741 """
742 if not (match := self._find_mergeable_universal_player(universal_player)):
743 return
744 keep, remove = self._select_merge_winner(universal_player, match)
745 self.logger.info(
746 "Merging universal player %s into %s (shared identifiers)",
747 remove.player_id,
748 keep.player_id,
749 )
750 self._merge_universal_players(keep, remove)
751
752 def _find_mergeable_universal_player(
753 self, universal_player: UniversalPlayer
754 ) -> UniversalPlayer | None:
755 """
756 Return the first other universal player that represents the same device, if any.
757
758 Players that share a protocol domain are not returned: they are separate devices
759 that merely share an identifier, so merging them would orphan a protocol.
760
761 :param universal_player: The universal player to find a merge candidate for.
762 """
763 for player in list(self._players.values()):
764 if player.provider.domain != "universal_player":
765 continue
766 if player.player_id == universal_player.player_id:
767 continue
768 if not isinstance(player, UniversalPlayer):
769 continue
770
771 if not self._identifiers_match(universal_player, player, ""):
772 continue
773
774 # Do not merge if both UPs have protocols from the same domain.
775 # Multiple instances of the same protocol on one host (e.g., several
776 # squeezelite players on the same VM) are separate devices that happen
777 # to share an IP. Merging them would orphan one instance's protocol.
778 domains_a = {
779 link.protocol_domain
780 for link in universal_player.linked_output_protocols
781 if link.protocol_domain
782 }
783 domains_b = {
784 link.protocol_domain
785 for link in player.linked_output_protocols
786 if link.protocol_domain
787 }
788 if domains_a & domains_b:
789 self.logger.debug(
790 "Skipping merge of %s and %s: shared protocol domain(s) %s",
791 universal_player.player_id,
792 player.player_id,
793 domains_a & domains_b,
794 )
795 continue
796
797 return player
798
799 return None
800
801 def _select_merge_winner(
802 self, universal_player: UniversalPlayer, other_player: UniversalPlayer
803 ) -> tuple[UniversalPlayer, UniversalPlayer]:
804 """
805 Return which of the two universal players absorbs the other, as (keeper, absorbed).
806
807 The oldest player wins, on a tie the one with the most protocol links.
808
809 :param universal_player: The universal player the merge was triggered for.
810 :param other_player: The universal player it matched with.
811 """
812 # The outcome must be stable across server restarts. Without that, which
813 # UniversalPlayer "wins" depends on iteration order of self._players.values(),
814 # which can shift between runs and causes downstream player_id reshuffling
815 # (and broken entity bindings in consumers like the Home Assistant MA integration).
816 if self._merge_rank(universal_player) <= self._merge_rank(other_player):
817 return universal_player, other_player
818 return other_player, universal_player
819
820 def _merge_rank(self, universal_player: Player) -> tuple[int, int, str]:
821 """
822 Return the sort key of a universal player in a merge, lowest wins.
823
824 Age comes first because the keeper's player id is the one that survives, and the
825 oldest player is the one API consumers have been bound to the longest. The links
826 of the absorbed player move over either way, so nothing is lost by keeping the
827 smaller one. A player from before player ids were minted has no stored moment and
828 counts as the oldest, which is exactly what it is.
829 """
830 created_at = self.mass.config.get(
831 f"{CONF_PLAYERS}/{universal_player.player_id}/values/{CONF_CREATED_AT}", 0
832 )
833 return (
834 created_at if isinstance(created_at, int) else 0,
835 -len(universal_player.linked_output_protocols),
836 universal_player.player_id,
837 )
838
839 def _merge_universal_players(self, keep: UniversalPlayer, remove: UniversalPlayer) -> None:
840 """
841 Absorb one universal player into another and schedule the absorbed one's removal.
842
843 :param keep: The universal player that stays.
844 :param remove: The universal player that is absorbed.
845 """
846 known_protocol_ids = set(self._get_known_protocol_ids(remove))
847 active_protocol_ids = {link.output_protocol_id for link in remove.linked_output_protocols}
848 moved_protocol_ids: set[str] = set()
849
850 # Transfer protocol links from the removed player to the keeper
851 for linked in list(remove.linked_output_protocols):
852 if protocol_player := self.get_player(linked.output_protocol_id):
853 protocol_player.set_protocol_parent_id(None)
854 domain = linked.protocol_domain or protocol_player.provider.domain
855
856 # Check if keeper already has an active link from this domain
857 if self._parent_has_active_protocol_from_domain(keep, domain):
858 self.logger.debug(
859 "Skipping duplicate %s link during merge: %s",
860 domain,
861 linked.output_protocol_id,
862 )
863 continue
864
865 self._add_protocol_link(keep, protocol_player, domain)
866 if protocol_player.protocol_parent_id == keep.player_id:
867 moved_protocol_ids.add(protocol_player.player_id)
868 protocol_player.refresh_state()
869
870 # Move cached-only protocol ownership as well so old-parent cleanup
871 # does not wipe protocols that were intentionally preserved.
872 cached_only_ids = known_protocol_ids - active_protocol_ids
873 preserved_protocol_ids = moved_protocol_ids | cached_only_ids
874 self._migrate_protocol_ids_to_parent(keep, preserved_protocol_ids)
875 self._remove_protocol_ids_from_parent(remove, preserved_protocol_ids)
876
877 # Merge identifiers
878 for conn_type, value in remove.device_info.identifiers.items():
879 keep.device_info.add_identifier(conn_type, value)
880 keep.refresh_state()
881
882 # Persist updated data before the obsolete player is removed
883 self._save_universal_player_data(keep)
884
885 # Carry over the user's configuration and re-point group memberships
886 # before the permanent removal below deletes the losing wrapper's config
887 self._migrate_universal_player_config(remove.player_id, keep.player_id)
888 self._repoint_group_memberships(remove.player_id, keep.player_id)
889
890 # Stop playback and remove the obsolete player
891 self.mass.create_task(self._stop_and_unregister(remove, keep.player_id))
892
893 def _link_protocols_to_universal(
894 self, universal_player: Player, protocol_players: list[Player]
895 ) -> None:
896 """Link protocol players to a universal player, cleaning up existing links."""
897 for player in protocol_players:
898 # Clean up if linked to another player
899 if player.protocol_parent_id:
900 if parent := self.get_player(player.protocol_parent_id):
901 self._remove_protocol_link(parent, player.player_id)
902 player.set_protocol_parent_id(None)
903 # Link to universal player
904 self._add_protocol_link(universal_player, player, player.provider.domain)
905 player.refresh_state()
906
907 # Update availability from protocol players
908 universal_player.refresh_state()
909
910 async def _create_or_update_universal_player(self, protocol_players: list[Player]) -> None:
911 """
912 Create or update a UniversalPlayer for a set of protocol players.
913
914 Delegates to the universal player provider which handles orchestration,
915 locking, and player creation. The controller then links the protocols
916 to the universal player.
917 """
918 # Filter out players that got linked during the async delay
919 protocol_players = [p for p in protocol_players if not p.protocol_parent_id]
920 if not protocol_players:
921 return
922
923 # Get the universal_player provider
924 universal_provider: UniversalPlayerProvider | None = None
925 for provider in self.mass.get_providers(ProviderType.PLAYER):
926 if provider.domain == "universal_player":
927 universal_provider = cast("UniversalPlayerProvider", provider)
928 break
929
930 if not universal_provider:
931 return
932
933 # Delegate to provider - it handles locking, create/update decision, etc.
934 # It reports which universal player each protocol player belongs to, as a
935 # device with several instances of one protocol domain gets more than one.
936 assignments = await universal_provider.ensure_universal_players_for_protocols(
937 protocol_players
938 )
939
940 # Link the protocols to their universal player (the controller manages
941 # cross-provider state), skipping players that were linked in the meantime.
942 by_universal_player: dict[str, list[Player]] = {}
943 for player in protocol_players:
944 if player.protocol_parent_id:
945 continue
946 if universal_player := assignments.get(player.player_id):
947 by_universal_player.setdefault(universal_player.player_id, []).append(player)
948
949 for universal_player_id, players in by_universal_player.items():
950 if universal_player := self.get_player(universal_player_id):
951 self._link_protocols_to_universal(universal_player, players)
952
953 def _try_link_protocols_to_native(self, native_player: Player) -> None:
954 """Try to link protocol players to a native player."""
955 # First, check if there's a universal player for this device that should be replaced
956 self._check_replace_universal_player(native_player)
957
958 # Look for protocol players that should be linked
959 for protocol_player in self.all_players(return_protocol_players=True):
960 if protocol_player.state.type != PlayerType.PROTOCOL:
961 continue
962 if protocol_player.protocol_parent_id:
963 # Already linked to a parent (could be this native player after replacement)
964 continue
965 if protocol_player.underlying_player_id:
966 # Derived protocol players link via their underlying player instead
967 continue
968
969 protocol_domain = protocol_player.provider.domain
970
971 # Skip if this native player already has an active link from this domain
972 # (prevents a second instance of the same protocol from trying to link)
973 if self._parent_has_active_protocol_from_domain(native_player, protocol_domain):
974 continue
975
976 if self._identifiers_match(native_player, protocol_player, protocol_domain):
977 self._add_protocol_link(native_player, protocol_player, protocol_domain)
978 # Check if linking succeeded (may be refused for duplicate domain)
979 if protocol_player.protocol_parent_id is not None:
980 protocol_player.refresh_state()
981 native_player.refresh_state()
982
983 # Proactively recover disabled/missing protocols from config
984 # This ensures disabled protocols show up in the UI so they can be re-enabled
985 self._recover_cached_protocol_links(native_player)
986
987 # Second pass: match remaining unlinked protocol players via sibling identifiers.
988 # After cache recovery, the native player has linked protocols (e.g., AirPlay)
989 # whose identifiers can be used to match new protocol players (e.g., Sendspin bridge)
990 # that share the same device identifiers but couldn't match the native player directly.
991 for protocol_player in self.all_players(return_protocol_players=True):
992 if protocol_player.state.type != PlayerType.PROTOCOL:
993 continue
994 if protocol_player.protocol_parent_id:
995 continue
996 if protocol_player.underlying_player_id:
997 continue
998 protocol_domain = protocol_player.provider.domain
999 if self._parent_has_active_protocol_from_domain(native_player, protocol_domain):
1000 continue
1001 if self._match_via_linked_protocols(native_player, protocol_player, protocol_domain):
1002 self.logger.debug(
1003 "Linked %s to %s via sibling protocol identifiers",
1004 protocol_player.player_id,
1005 native_player.player_id,
1006 )
1007
1008 # Finally, link derived protocol players that ride directly on this
1009 # native player (derived players riding on the protocol players linked
1010 # above are handled by _add_protocol_link itself).
1011 self._link_derived_protocols_of(native_player)
1012
1013 def _check_replace_universal_player(self, native_player: Player) -> None:
1014 """Check if a universal player should be replaced by this native player."""
1015 # Skip if native_player is itself a universal player (prevent self-replacement)
1016 if native_player.provider.domain == "universal_player":
1017 return
1018
1019 # Look for universal players that match this native player
1020 for player in list(self._players.values()):
1021 if player.provider.domain != "universal_player":
1022 continue
1023
1024 # Check by identifiers first
1025 identifiers_match = self._identifiers_match(native_player, player, "")
1026
1027 # Also check if native player's ID is in the universal player's stored protocol list
1028 # This handles players that changed type (e.g., sendspin web players changed from
1029 # PROTOCOL to PLAYER type) and have no identifiers to match against
1030 player_id_in_protocols = (
1031 isinstance(player, UniversalPlayer)
1032 and native_player.player_id in player._protocol_player_ids
1033 )
1034
1035 if not identifiers_match and not player_id_in_protocols:
1036 continue
1037
1038 known_protocol_ids = set(self._get_known_protocol_ids(player))
1039 refused_protocol_ids: set[str] = set()
1040 moved_protocol_ids: set[str] = set()
1041
1042 # Transfer all protocol links from universal player to native player
1043 for linked in list(player.linked_output_protocols):
1044 if protocol_player := self.get_player(linked.output_protocol_id):
1045 protocol_player.set_protocol_parent_id(None)
1046 domain = linked.protocol_domain or protocol_player.provider.domain
1047 self._add_protocol_link(native_player, protocol_player, domain)
1048 if protocol_player.protocol_parent_id != native_player.player_id:
1049 # Link refused, keep the protocol owned by the universal player.
1050 protocol_player.set_protocol_parent_id(player.player_id)
1051 refused_protocol_ids.add(protocol_player.player_id)
1052 continue
1053 protocol_player.refresh_state()
1054 moved_protocol_ids.add(protocol_player.player_id)
1055
1056 # A refused link leaves the universal player in charge, so only hand over what
1057 # actually moved: ownership that exists in config alone stays with it, which
1058 # keeps a protocol derived from a refused one with the parent it will link to.
1059 migrated_protocol_ids = (
1060 moved_protocol_ids if refused_protocol_ids else known_protocol_ids
1061 )
1062 # A device that kept its id across a type change lists itself here.
1063 # It must never become its own protocol, and it must also be dropped
1064 # from the obsolete universal player so the permanent cleanup below
1065 # doesn't treat it as an orphaned protocol (which would re-wrap the
1066 # native player in a fresh universal player).
1067 migrated_protocol_ids.discard(native_player.player_id)
1068 self._migrate_protocol_ids_to_parent(native_player, migrated_protocol_ids)
1069 self._remove_protocol_ids_from_parent(
1070 player, migrated_protocol_ids | {native_player.player_id}
1071 )
1072 native_player.refresh_state()
1073
1074 if refused_protocol_ids:
1075 # Registered protocols that the native player refused remain on the wrapper.
1076 continue
1077
1078 # Carry over the user's configuration and re-point group memberships
1079 # before the permanent removal below deletes the universal player's config
1080 self._migrate_universal_player_config(player.player_id, native_player.player_id)
1081 self._repoint_group_memberships(player.player_id, native_player.player_id)
1082
1083 # Stop playback and remove the now-obsolete universal player
1084 self.mass.create_task(self._stop_and_unregister(player, native_player.player_id))
1085
1086 def _migrate_universal_player_config(self, universal_id: str, native_id: str) -> None:
1087 """
1088 Carry over user-set configuration from a replaced universal player.
1089
1090 Copies the custom display name, player config values, DSP settings and
1091 per-queue settings of the (obsolete) universal player onto the native
1092 player that replaces it, without overwriting values explicitly set on
1093 the native player itself. Must be called while the universal player's
1094 config still exists, as the permanent removal deletes it.
1095
1096 :param universal_id: Player id of the obsolete universal player being replaced.
1097 :param native_id: Player id of the native player that replaces it.
1098 """
1099 source_raw = self.mass.config.get(f"{CONF_PLAYERS}/{universal_id}")
1100 source_raw = source_raw if isinstance(source_raw, dict) else {}
1101 target_key = f"{CONF_PLAYERS}/{native_id}"
1102 target_raw = self.mass.config.get(target_key)
1103 target_raw = target_raw if isinstance(target_raw, dict) else {}
1104 player_config_changed = False
1105
1106 # only carry an actual user rename, not the auto-generated default name;
1107 # likewise a name on the native player only counts as a user override when
1108 # it differs from the default name
1109 custom_name = source_raw.get("name")
1110 target_name = target_raw.get("name")
1111 target_has_custom_name = bool(target_name) and target_name != target_raw.get("default_name")
1112 if (
1113 custom_name
1114 and custom_name != source_raw.get("default_name")
1115 and not target_has_custom_name
1116 ):
1117 self.mass.config.set(f"{target_key}/name", custom_name)
1118 player_config_changed = True
1119
1120 source_values = source_raw.get("values")
1121 source_values = source_values if isinstance(source_values, dict) else {}
1122 target_values = target_raw.get("values")
1123 target_values = target_values if isinstance(target_values, dict) else {}
1124 for key, value in source_values.items():
1125 if key in UNIVERSAL_PLAYER_INTERNAL_CONF_KEYS:
1126 continue
1127 if CONF_PROTOCOL_KEY_SPLITTER in key:
1128 # stale virtual mirror of a protocol player's own config
1129 continue
1130 if key in target_values:
1131 continue
1132 self.mass.config.set(f"{target_key}/values/{key}", deepcopy(value))
1133 player_config_changed = True
1134
1135 # DSP settings follow wholesale, unless the native player has its own
1136 dsp_changed = False
1137 source_dsp = self.mass.config.get(f"{CONF_PLAYER_DSP}/{universal_id}")
1138 if source_dsp and not self.mass.config.get(f"{CONF_PLAYER_DSP}/{native_id}"):
1139 self.mass.config.set(f"{CONF_PLAYER_DSP}/{native_id}", deepcopy(source_dsp))
1140 dsp_changed = True
1141
1142 queue_changed = self._migrate_universal_queue_config(universal_id, native_id)
1143
1144 if not (player_config_changed or dsp_changed or queue_changed):
1145 return
1146 self.logger.info(
1147 "Carried over configuration of universal player %s to %s", universal_id, native_id
1148 )
1149 if player_config_changed:
1150 # the native player's in-place config was loaded before the carry-over,
1151 # so reload it to make the migrated values (e.g. custom name) effective
1152 self.mass.create_task(self._reapply_player_config(native_id))
1153
1154 def _migrate_universal_queue_config(self, universal_id: str, native_id: str) -> bool:
1155 """
1156 Move the per-queue settings of a replaced universal player to its replacement.
1157
1158 Queue ids equal player ids, so the source entry is removed once it is carried over.
1159
1160 :param universal_id: Player id of the obsolete universal player.
1161 :param native_id: Player id of the native player that replaces it.
1162 :return: True if any queue setting was carried over.
1163 """
1164 queue_changed = False
1165 source_queue_raw = self.mass.config.get(f"{CONF_PLAYER_QUEUES}/{universal_id}")
1166 source_queue_raw = source_queue_raw if isinstance(source_queue_raw, dict) else None
1167 if source_queue_values := (source_queue_raw or {}).get("values"):
1168 target_queue_key = f"{CONF_PLAYER_QUEUES}/{native_id}"
1169 target_queue_raw = self.mass.config.get(target_queue_key)
1170 target_queue_raw = (
1171 deepcopy(target_queue_raw) if isinstance(target_queue_raw, dict) else {}
1172 )
1173 target_queue_values = target_queue_raw.setdefault("values", {})
1174 for key, value in source_queue_values.items():
1175 if key in target_queue_values:
1176 continue
1177 target_queue_values[key] = deepcopy(value)
1178 queue_changed = True
1179 if queue_changed:
1180 target_queue_raw["queue_id"] = native_id
1181 self.mass.config.set(target_queue_key, target_queue_raw)
1182 if source_queue_raw is not None:
1183 self.mass.config.remove(f"{CONF_PLAYER_QUEUES}/{universal_id}")
1184 return queue_changed
1185
1186 async def _reapply_player_config(self, player_id: str) -> None:
1187 """Reload the stored config onto a registered player and refresh its state."""
1188 if not (player := self.get_player(player_id)):
1189 return
1190 config = await self.mass.config.get_player_config(player_id)
1191 player.set_config(config)
1192 player.update_state()
1193 self.mass.signal_event(EventType.PLAYER_CONFIG_UPDATED, object_id=player_id, data=config)
1194
1195 def _repoint_group_memberships(self, old_player_id: str, new_player_id: str) -> None:
1196 """
1197 Re-point group memberships from a removed player to its successor.
1198
1199 When a universal player is replaced by a native player or merged into
1200 another universal player, other players that list the removed player as
1201 a group member (or allowed member) must follow its successor so those
1202 memberships are not silently lost. Updates the persisted config and keeps
1203 any registered player whose membership changed in sync.
1204
1205 :param old_player_id: Player id that is being removed.
1206 :param new_player_id: Player id that replaces it.
1207 """
1208 all_player_configs = self.mass.config.get(CONF_PLAYERS, {})
1209 if not isinstance(all_player_configs, dict):
1210 return
1211 for other_id, other_cfg in all_player_configs.items():
1212 if not isinstance(other_cfg, dict):
1213 continue
1214 other_values = other_cfg.get("values")
1215 if not isinstance(other_values, dict):
1216 continue
1217 for key in (CONF_GROUP_MEMBERS, CONF_ALLOWED_MEMBERS):
1218 members = other_values.get(key)
1219 if not isinstance(members, list) or old_player_id not in members:
1220 continue
1221 new_members: list[str] = []
1222 for member_id in members:
1223 resolved = new_player_id if member_id == old_player_id else member_id
1224 if resolved not in new_members:
1225 new_members.append(resolved)
1226 self.mass.config.set(f"{CONF_PLAYERS}/{other_id}/values/{key}", new_members)
1227 # keep a registered player's in-place config copy and state in sync
1228 if other_player := self.get_player(other_id):
1229 if entry := other_player.config.values.get(key):
1230 entry.value = new_members
1231 other_player.refresh_state()
1232
1233 async def _stop_and_unregister(self, player: Player, replacement_player_id: str) -> None:
1234 """
1235 Stop active playback on a player and then permanently unregister it.
1236
1237 Used when an obsolete universal player is replaced or merged away: while
1238 it is not idle its protocol child keeps playing the dead queue's stream
1239 until the buffer drains, so playback is stopped first. Queue ownership is
1240 intentionally not transferred.
1241
1242 :param player: The obsolete player to stop and permanently remove.
1243 :param replacement_player_id: Player ID that takes the obsolete player's place.
1244 """
1245 if player.playback_state != PlaybackState.IDLE:
1246 with suppress(PlayerCommandFailed, PlayerUnavailableError):
1247 await self.mass.player_queues.stop(player.player_id)
1248 await self.unregister(
1249 player.player_id, permanent=True, replacement_player_id=replacement_player_id
1250 )
1251
1252 def _parent_has_active_protocol_from_domain(
1253 self, parent: Player, domain: str, exclude_player_id: str | None = None
1254 ) -> bool:
1255 """
1256 Check if a parent already has an active (registered) protocol player from a given domain.
1257
1258 This prevents a second protocol player of the same domain (e.g., a second AirPlay
1259 instance on the same host) from replacing the first one's link on the same parent.
1260
1261 :param parent: The parent player to check.
1262 :param domain: The protocol domain to check for (e.g., "airplay", "dlna").
1263 :param exclude_player_id: Optional player ID to exclude from the check
1264 (used when checking if a player's own domain is already linked).
1265 """
1266 for link in parent.linked_output_protocols:
1267 if link.protocol_domain != domain:
1268 continue
1269 if exclude_player_id and link.output_protocol_id == exclude_player_id:
1270 continue
1271 # A registered player from this domain blocks the link, even if unavailable.
1272 # Being offline doesn't make it a different device — it's still occupying
1273 # this domain slot. The provider should remove stale players explicitly.
1274 if self.get_player(link.output_protocol_id):
1275 return True
1276 return False
1277
1278 def _add_protocol_link(
1279 self, native_player: Player, protocol_player: Player, protocol_domain: str
1280 ) -> None:
1281 """Add a protocol link from native player to protocol player."""
1282 # Never link a player to itself (hides it as its own protocol child).
1283 if native_player.player_id == protocol_player.player_id:
1284 return
1285 # Guard: refuse to replace an existing active link from the same domain.
1286 # This prevents a second instance of the same protocol (e.g., two AirPlay
1287 # instances on the same host) from silently replacing the first one.
1288 if self._parent_has_active_protocol_from_domain(
1289 native_player, protocol_domain, exclude_player_id=protocol_player.player_id
1290 ):
1291 self.logger.debug(
1292 "Refusing to link %s to %s: parent already has an active %s link",
1293 protocol_player.player_id,
1294 native_player.player_id,
1295 protocol_domain,
1296 )
1297 return
1298
1299 # Remove any existing link for the same protocol domain
1300 updated_protocols = [
1301 link
1302 for link in native_player.linked_output_protocols
1303 if link.protocol_domain != protocol_domain
1304 ]
1305
1306 # Get priority for this protocol
1307 priority = PROTOCOL_PRIORITY.get(protocol_domain, 100)
1308
1309 # Derived transports (e.g. a Sendspin bridge riding on an AirPlay player)
1310 # reference the base output they run on top of; "native" when they ride
1311 # on the parent player itself
1312 derived_from = protocol_player.underlying_player_id
1313 if derived_from == native_player.player_id:
1314 derived_from = "native"
1315
1316 # Add the new link
1317 updated_protocols.append(
1318 LinkedOutputProtocol(
1319 output_protocol_id=protocol_player.player_id,
1320 protocol_domain=protocol_domain,
1321 priority=priority,
1322 derived_from=derived_from,
1323 )
1324 )
1325 native_player.set_linked_output_protocols(updated_protocols)
1326
1327 # Set protocol player's parent
1328 protocol_player.set_protocol_parent_id(native_player.player_id)
1329
1330 # Persist linked protocol IDs to config for fast restart
1331 # (only for non-universal players, as universal players handle this themselves)
1332 if native_player.provider.domain != "universal_player":
1333 self._save_linked_protocol_ids(native_player)
1334 # Always save the parent ID on the protocol player for reverse lookup on restart
1335 # (needed for both native and universal parents to enable fast restore)
1336 self._save_protocol_parent_id(protocol_player.player_id, native_player.player_id)
1337
1338 # The freshly linked player may have derived protocol players (e.g. a
1339 # Sendspin bridge riding on it) waiting to join the same parent.
1340 self._link_derived_protocols_of(protocol_player)
1341
1342 def _remove_protocol_link(
1343 self, native_player: Player, protocol_player_id: str, permanent: bool = False
1344 ) -> None:
1345 """
1346 Remove a protocol link.
1347
1348 :param native_player: The parent player to remove the link from.
1349 :param protocol_player_id: The protocol player ID to unlink.
1350 :param permanent: If True, also removes the protocol ID from the cached list.
1351 Use this when the protocol player config is being deleted. If False,
1352 the protocol ID remains in the cache so it can be shown as disabled
1353 and re-enabled later.
1354 """
1355 updated_protocols = [
1356 link
1357 for link in native_player.linked_output_protocols
1358 if link.output_protocol_id != protocol_player_id
1359 ]
1360 native_player.set_linked_output_protocols(updated_protocols)
1361
1362 # Clear parent reference on protocol player if it still exists
1363 if protocol_player := self.get_player(protocol_player_id):
1364 if protocol_player.protocol_parent_id == native_player.player_id:
1365 protocol_player.set_protocol_parent_id(None)
1366
1367 # Update persisted linked protocol IDs
1368 if native_player.provider.domain != "universal_player":
1369 if permanent:
1370 # Permanently remove from cache (player config is being deleted)
1371 self._remove_protocol_id_from_cache(native_player.player_id, protocol_player_id)
1372 # Note: we don't call _save_linked_protocol_ids here anymore for non-permanent
1373 # removals because the merge approach will preserve the ID in the cache
1374 # Always clear the cached parent ID (for both native and universal parents)
1375 self._clear_protocol_parent_id(protocol_player_id)
1376
1377 def _save_linked_protocol_ids(self, native_player: Player) -> None:
1378 """
1379 Save linked protocol IDs to config for persistence across restarts.
1380
1381 This method merges active protocol IDs with existing cached IDs to preserve
1382 disabled protocol players in the cache. This allows disabled protocols to be
1383 shown in the UI so they can be re-enabled.
1384 """
1385 conf_key = f"{CONF_PLAYERS}/{native_player.player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1386 # Get existing cached IDs to preserve disabled protocols
1387 existing_ids: list[str] = self.mass.config.get(conf_key, [])
1388 # Get currently active protocol IDs
1389 active_ids = {link.output_protocol_id for link in native_player.linked_output_protocols}
1390 # Merge: keep existing IDs and add any new active ones
1391 merged_ids = list(existing_ids)
1392 for protocol_id in active_ids:
1393 if protocol_id not in merged_ids:
1394 merged_ids.append(protocol_id)
1395 self.mass.config.set(conf_key, merged_ids)
1396
1397 def _get_cached_protocol_ids(self, player_id: str) -> list[str]:
1398 """Get cached linked protocol IDs from config."""
1399 conf_key = f"{CONF_PLAYERS}/{player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1400 result = self.mass.config.get(conf_key, [])
1401 return list(result) if result else []
1402
1403 def _remove_protocol_id_from_cache(
1404 self, parent_player_id: str, protocol_player_id: str
1405 ) -> None:
1406 """
1407 Permanently remove a protocol player ID from the cached linked protocol IDs.
1408
1409 Use this when a protocol player config is being deleted, not just disabled.
1410 """
1411 conf_key = f"{CONF_PLAYERS}/{parent_player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1412 cached_ids: list[str] = self.mass.config.get(conf_key, [])
1413 if protocol_player_id in cached_ids:
1414 cached_ids.remove(protocol_player_id)
1415 self.mass.config.set(conf_key, cached_ids)
1416
1417 def _save_protocol_parent_id(self, protocol_player_id: str, parent_id: str) -> None:
1418 """Save the parent ID for a protocol player for persistence across restarts."""
1419 # Only save if the player config still exists to avoid creating partial entries
1420 if not self.mass.config.get(f"{CONF_PLAYERS}/{protocol_player_id}"):
1421 return
1422 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1423 self.mass.config.set(conf_key, parent_id)
1424
1425 def _save_underlying_player_id(self, player: Player) -> None:
1426 """
1427 Persist the derived-transport edge of a player to config.
1428
1429 Allows the edge to be resolved (e.g. by the config UI) even while the
1430 player is not registered. Clears a previously persisted edge when the
1431 player is no longer derived (e.g. a bridge client turned web player).
1432 """
1433 # Only save if the player config still exists to avoid creating partial entries
1434 if not self.mass.config.get(f"{CONF_PLAYERS}/{player.player_id}"):
1435 return
1436 conf_key = f"{CONF_PLAYERS}/{player.player_id}/values/{CONF_UNDERLYING_PLAYER_ID}"
1437 if player.underlying_player_id:
1438 self.mass.config.set(conf_key, player.underlying_player_id)
1439 elif self.mass.config.get(conf_key) is not None:
1440 self.mass.config.set(conf_key, None)
1441
1442 def _get_cached_protocol_parent_id(self, protocol_player_id: str) -> str | None:
1443 """Get cached parent ID for a protocol player from config."""
1444 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1445 result = self.mass.config.get(conf_key, None)
1446 return str(result) if result else None
1447
1448 def _clear_protocol_parent_id(self, protocol_player_id: str) -> None:
1449 """Clear the cached parent ID for a protocol player."""
1450 # Only clear if the player config still exists to avoid creating partial entries
1451 if not self.mass.config.get(f"{CONF_PLAYERS}/{protocol_player_id}"):
1452 return
1453 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1454 self.mass.config.set(conf_key, None)
1455
1456 def _recover_cached_protocol_links(self, native_player: Player) -> None:
1457 """
1458 Recover protocol links from config for disabled/missing protocols.
1459
1460 This ensures that disabled protocols show up in the output_protocols list
1461 so they can be re-enabled by the user. It also handles the case where
1462 protocol players haven't registered yet during startup.
1463 """
1464 # Get currently linked protocol IDs
1465 linked_protocol_ids = {
1466 link.output_protocol_id for link in native_player.linked_output_protocols
1467 }
1468
1469 # Get cached protocol IDs from config (includes protocols that were explicitly linked)
1470 cached_protocol_ids = self._get_cached_protocol_ids(native_player.player_id)
1471
1472 # Also check all protocol players that have protocol_parent_id pointing to this player
1473 # (this handles disabled protocols that may not be in linked_protocol_ids)
1474 all_player_configs = self.mass.config.get(CONF_PLAYERS, {})
1475 for protocol_id, protocol_config in all_player_configs.items():
1476 # Skip if not a protocol player
1477 if protocol_config.get("player_type") != "protocol":
1478 continue
1479 # Check if this protocol has a parent_id pointing to this native player
1480 protocol_values = protocol_config.get("values", {})
1481 protocol_parent_id = protocol_values.get(CONF_PROTOCOL_PARENT_ID)
1482 if protocol_parent_id == native_player.player_id:
1483 if protocol_id not in cached_protocol_ids:
1484 cached_protocol_ids.append(protocol_id)
1485
1486 if not cached_protocol_ids:
1487 return
1488
1489 # Add link entries for any cached protocols that aren't currently linked
1490 updated_protocols = list(native_player.linked_output_protocols)
1491 for protocol_id in cached_protocol_ids:
1492 if protocol_id in linked_protocol_ids:
1493 continue # Already linked
1494
1495 # Get protocol player config to determine the protocol domain
1496 protocol_config = self.mass.config.get(f"{CONF_PLAYERS}/{protocol_id}")
1497 if not protocol_config:
1498 continue
1499
1500 # Determine protocol domain from provider
1501 protocol_provider: str = protocol_config.get("provider")
1502 if not protocol_provider:
1503 continue
1504
1505 # Extract domain from provider instance_id (e.g., "airplay--uuid" -> "airplay")
1506 protocol_domain = protocol_provider.split("--", maxsplit=1)[0]
1507
1508 # Skip if parent already has a link from this domain
1509 existing_domains = {link.protocol_domain for link in updated_protocols}
1510 if protocol_domain in existing_domains:
1511 continue
1512
1513 # Get priority for this protocol
1514 priority = PROTOCOL_PRIORITY.get(protocol_domain, 100)
1515
1516 # Resolve the derived-transport edge from the live player when
1517 # registered, else from the persisted edge in config
1518 protocol_player = self.get_player(protocol_id)
1519 derived_from = (
1520 protocol_player.underlying_player_id
1521 if protocol_player
1522 else protocol_config.get("values", {}).get(CONF_UNDERLYING_PLAYER_ID)
1523 )
1524 if derived_from == native_player.player_id:
1525 derived_from = "native"
1526
1527 updated_protocols.append(
1528 LinkedOutputProtocol(
1529 output_protocol_id=protocol_id,
1530 protocol_domain=protocol_domain,
1531 priority=priority,
1532 derived_from=derived_from,
1533 )
1534 )
1535 self.logger.debug(
1536 "Recovered cached protocol link %s -> %s",
1537 native_player.player_id,
1538 protocol_id,
1539 )
1540
1541 if len(updated_protocols) != len(native_player.linked_output_protocols):
1542 native_player.set_linked_output_protocols(updated_protocols)
1543
1544 def _cleanup_protocol_links(self, player: Player) -> None:
1545 """Clean up protocol links when a player is permanently removed."""
1546 if player.state.type == PlayerType.PROTOCOL:
1547 # Protocol player being removed: remove link from parent
1548 if parent_id := player.protocol_parent_id:
1549 if parent_player := self.get_player(parent_id):
1550 # Use permanent=True to also remove from cached protocol IDs
1551 self._remove_protocol_link(parent_player, player.player_id, permanent=True)
1552 if (
1553 parent_player.provider.domain == "universal_player"
1554 and len(parent_player.linked_output_protocols) == 0
1555 ):
1556 # No protocols left - the universal player has nothing to play
1557 # on. Its config is deliberately kept: the player id is opaque
1558 # and cannot be recreated, so deleting it here would orphan the
1559 # entities API consumers bound to it. Only an explicit removal
1560 # by the user deletes a universal player for good.
1561 self.logger.info(
1562 "Universal player %s has no protocols left",
1563 parent_id,
1564 )
1565 self.mass.create_task(
1566 self.mass.players.unregister(parent_id, permanent=False)
1567 )
1568 else:
1569 parent_player.refresh_state()
1570 else:
1571 # Parent not registered yet — still purge the cached id
1572 self._remove_protocol_id_from_cache(parent_id, player.player_id)
1573 else:
1574 # Native/universal player being removed: handle all linked protocol players.
1575 # Collect all known protocol IDs from both active links and cached state,
1576 # since disabled/inactive protocols may only exist in the cached parent data.
1577 all_protocol_ids = set(self._get_known_protocol_ids(player))
1578 for protocol_id in all_protocol_ids:
1579 if protocol_player := self.get_player(protocol_id):
1580 # Protocol player is available: clear parent and schedule re-evaluation
1581 # so it can be matched to a new parent or a new universal player
1582 self.logger.debug(
1583 "Player %s removed - scheduling evaluation for protocol %s",
1584 player.player_id,
1585 protocol_id,
1586 )
1587 self._detach_protocol_child(protocol_player)
1588 else:
1589 # Clear cached parent ID in config so protocol won't try to
1590 # restore a link to the deleted player on next restart
1591 self._clear_protocol_parent_id(protocol_id)
1592 # Protocol player is not registered yet — it may still be
1593 # mid-discovery (e.g., DLNA connecting via SSDP). Don't delete
1594 # its config as that would cause a KeyError when it finishes
1595 # registering. Stale configs are harmless and get cleaned up
1596 # naturally on subsequent restarts.
1597 self.logger.debug(
1598 "Player %s removed - protocol %s not registered, skipping cleanup",
1599 player.player_id,
1600 protocol_id,
1601 )
1602
1603 def _cleanup_player_type_transition(self, existing: Player) -> None:
1604 """
1605 Release the protocol topology a player owned before its type changed.
1606
1607 :param existing: The registered player instance, still reporting its previous type.
1608 """
1609 if existing.state.type == PlayerType.PROTOCOL:
1610 # a provider may announce the new type with the live parent link already
1611 # dropped, so fall back to the persisted one to still reach the parent
1612 parent_id = existing.protocol_parent_id or self._get_cached_protocol_parent_id(
1613 existing.player_id
1614 )
1615 if not parent_id:
1616 return
1617 parent = self.get_player(parent_id)
1618 if parent is not None and parent.provider.domain == "universal_player":
1619 # drop only the active edge and leave the rest to the link evaluation,
1620 # which replaces the wrapper with this player: a leftover edge makes it
1621 # hand the player over to itself, which it refuses, abandoning the swap
1622 self._remove_protocol_link(parent, existing.player_id)
1623 return
1624 existing.set_protocol_parent_id(parent_id)
1625 # unlink at the parent and drop the persisted parent id, which would
1626 # otherwise heal the player's type back to protocol
1627 self._cleanup_protocol_links(existing)
1628 # a player leaving the protocol role has no parent, also when that parent
1629 # is not registered (anymore) and only the cached link could be cleaned up
1630 existing.set_protocol_parent_id(None)
1631 return
1632 # the player becomes a child itself: detach the protocol players it owned so they
1633 # can find a new parent, then give up their ownership in its (kept) config - the
1634 # reverse of the removal path, which drops the ownership before the detach
1635 protocol_ids = set(self._get_known_protocol_ids(existing))
1636 self._cleanup_protocol_links(existing)
1637 self._remove_protocol_ids_from_parent(existing, protocol_ids)
1638
1639 def _detach_protocol_children(self, parent_id: str) -> None:
1640 """
1641 Detach the registered protocol players of a parent player that is going away.
1642
1643 Covers the removal paths that don't unregister the parent first (e.g. its
1644 provider is unloaded), where the parent is not around anymore to enumerate
1645 its protocol players.
1646
1647 :param parent_id: Player id of the parent that is being removed.
1648 """
1649 for protocol_player in list(self._players.values()):
1650 if protocol_player.state.type != PlayerType.PROTOCOL:
1651 continue
1652 # a protocol player waiting for a parent that never registered only has
1653 # the link in its config, so fall back to the cached parent
1654 linked_parent_id = protocol_player.protocol_parent_id or (
1655 self._get_cached_protocol_parent_id(protocol_player.player_id)
1656 )
1657 if linked_parent_id != parent_id:
1658 continue
1659 self.logger.debug(
1660 "Player %s removed - scheduling evaluation for protocol %s",
1661 parent_id,
1662 protocol_player.player_id,
1663 )
1664 self._detach_protocol_child(protocol_player)
1665
1666 def _detach_protocol_child(self, protocol_player: Player) -> None:
1667 """Clear a protocol player's parent link and schedule a fresh evaluation."""
1668 self._clear_protocol_parent_id(protocol_player.player_id)
1669 protocol_player.set_protocol_parent_id(None)
1670 protocol_player.refresh_state()
1671 self._schedule_protocol_evaluation(protocol_player)
1672
1673 def _identifiers_match(
1674 self, player_a: Player, player_b: Player, protocol_domain: str = ""
1675 ) -> bool:
1676 """
1677 Check if identifiers match between two players.
1678
1679 Matching is done by comparing connection identifiers (MAC, serial, UUID).
1680 As a last resort, IP address is used when at least one player has a
1681 locally-administered MAC, indicating the device uses MAC randomization
1682 and ARP could not resolve the real hardware address.
1683
1684 Invalid identifiers (e.g., 00:00:00:00:00:00 MAC addresses) are filtered out
1685 to prevent false matches between unrelated devices.
1686 """
1687 identifiers_a = player_a.device_info.identifiers
1688 identifiers_b = player_b.device_info.identifiers
1689
1690 # Check identifiers in order of reliability
1691 # MAC_ADDRESS > SERIAL_NUMBER > UUID > CAST_UUID > AIRPLAY_ID
1692 for conn_type in (
1693 IdentifierType.MAC_ADDRESS,
1694 IdentifierType.SERIAL_NUMBER,
1695 IdentifierType.UUID,
1696 IdentifierType.CAST_UUID,
1697 IdentifierType.AIRPLAY_ID,
1698 ):
1699 val_a = identifiers_a.get(conn_type)
1700 val_b = identifiers_b.get(conn_type)
1701
1702 if not val_a or not val_b:
1703 continue
1704
1705 # Filter out invalid MAC addresses (00:00:00:00:00:00, ff:ff:ff:ff:ff:ff)
1706 if conn_type == IdentifierType.MAC_ADDRESS:
1707 if not is_valid_mac_address(val_a) or not is_valid_mac_address(val_b):
1708 self.logger.log(
1709 VERBOSE_LOG_LEVEL,
1710 "Skipping invalid MAC address for matching: %s=%s, %s=%s",
1711 player_a.display_name,
1712 val_a,
1713 player_b.display_name,
1714 val_b,
1715 )
1716 continue
1717
1718 # Normalize values for comparison
1719 if conn_type == IdentifierType.MAC_ADDRESS:
1720 # Use MAC normalization that handles locally-administered bit differences
1721 # Some protocols (like AirPlay) report a locally-administered MAC variant
1722 # where bit 1 of the first octet is set (e.g., 54:78:... vs 56:78:...)
1723 val_a_norm = normalize_mac_for_matching(val_a)
1724 val_b_norm = normalize_mac_for_matching(val_b)
1725
1726 # Direct match on current MAC
1727 if val_a_norm == val_b_norm:
1728 return True
1729
1730 # Multi-MAC matching: also check original reported MACs.
1731 # Devices with multiple interfaces (WiFi + Ethernet) may have ARP
1732 # resolve one MAC while the protocol reports a different one.
1733 macs_a = {val_a_norm}
1734 macs_b = {val_b_norm}
1735 reported_a = player_a.extra_data.get("reported_mac")
1736 reported_b = player_b.extra_data.get("reported_mac")
1737 if reported_a and is_valid_mac_address(reported_a):
1738 macs_a.add(normalize_mac_for_matching(reported_a))
1739 if reported_b and is_valid_mac_address(reported_b):
1740 macs_b.add(normalize_mac_for_matching(reported_b))
1741 if macs_a & macs_b:
1742 return True
1743
1744 # No MAC match - continue to next identifier type
1745 continue
1746
1747 val_a_norm = val_a.lower().replace(":", "").replace("-", "")
1748 val_b_norm = val_b.lower().replace(":", "").replace("-", "")
1749
1750 # Direct match
1751 if val_a_norm == val_b_norm:
1752 return True
1753
1754 # Special case: Sonos UUID matching with DLNA _MR suffix
1755 # Sonos uses RINCON_xxx, DLNA uses RINCON_xxx_MR for Media Renderer
1756 if conn_type == IdentifierType.UUID:
1757 if val_b_norm.endswith("_mr") and val_b_norm[:-3] == val_a_norm:
1758 return True
1759 if val_a_norm.endswith("_mr") and val_a_norm[:-3] == val_b_norm:
1760 return True
1761
1762 # Last resort: IP-based matching.
1763 # Two players on the same IP are very likely the same physical device.
1764 # This handles two cases:
1765 # 1. MAC randomization: at least one player has no real MAC (LA or missing),
1766 # so ARP couldn't resolve a usable address.
1767 # 2. Different MACs per protocol: some devices (e.g., Yamaha MusicCast) report
1768 # different valid globally-unique MACs per protocol (DLNA vs AirPlay differ
1769 # by 1 in the last octet). IP matching is safe here because two different
1770 # devices on a LAN cannot share the same IP simultaneously.
1771 # To avoid false positives between unrelated native players, this path
1772 # requires at least one player to be a protocol or universal player.
1773 ip_a = identifiers_a.get(IdentifierType.IP_ADDRESS)
1774 ip_b = identifiers_b.get(IdentifierType.IP_ADDRESS)
1775 if ip_a and ip_b and ip_a == ip_b:
1776 mac_a = identifiers_a.get(IdentifierType.MAC_ADDRESS)
1777 mac_b = identifiers_b.get(IdentifierType.MAC_ADDRESS)
1778 a_is_real = (
1779 mac_a is not None
1780 and is_valid_mac_address(mac_a)
1781 and not is_locally_administered_mac(mac_a)
1782 )
1783 b_is_real = (
1784 mac_b is not None
1785 and is_valid_mac_address(mac_b)
1786 and not is_locally_administered_mac(mac_b)
1787 )
1788 # Case 1: at least one player has no real hardware MAC
1789 if not (a_is_real and b_is_real):
1790 return True
1791 # Case 2: both have real MACs but at least one is a protocol/universal player
1792 a_is_protocol = (
1793 player_a.type == PlayerType.PROTOCOL
1794 or player_a.provider.domain == "universal_player"
1795 )
1796 b_is_protocol = (
1797 player_b.type == PlayerType.PROTOCOL
1798 or player_b.provider.domain == "universal_player"
1799 )
1800 if a_is_protocol or b_is_protocol:
1801 return True
1802
1803 return False
1804
1805 def _select_best_output_protocol(self, player: Player) -> tuple[Player, OutputProtocol | None]:
1806 """
1807 Select the best available output protocol for a player.
1808
1809 Selection priority:
1810 1. Output protocol that is currently grouped/synced with other players.
1811 2. User's preferred output protocol (from player settings).
1812 3. Native playback (if player supports PLAY_MEDIA).
1813 4. The player's declared default output protocol domain, if available.
1814 5. Best available protocol by priority.
1815
1816 Returns tuple of (target_player, output_protocol).
1817 output_protocol is None when using native playback.
1818 """
1819 self.logger.log(
1820 VERBOSE_LOG_LEVEL,
1821 "Selecting output protocol for %s",
1822 player.state.name,
1823 )
1824
1825 # 1. Check if any output protocol is currently grouped
1826 for linked in player.linked_output_protocols:
1827 if protocol_player := self.get_player(linked.output_protocol_id):
1828 if protocol_player.available_for_playback and self._is_protocol_grouped(
1829 protocol_player
1830 ):
1831 self.logger.log(
1832 VERBOSE_LOG_LEVEL,
1833 "Selected protocol for %s: %s (grouped)",
1834 player.state.name,
1835 protocol_player.state.name,
1836 )
1837 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1838
1839 # 2. Check for user's preferred output protocol.
1840 # The value is only stored while it differs from the entry's default: "native" when a
1841 # native output is available, otherwise "auto". A player without a native output (e.g. a
1842 # LinkPlay shell) therefore has no stored preference by default and gets its default
1843 # output domain applied in step 4.
1844 preferred = self.mass.config.get_raw_player_config_value(
1845 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
1846 )
1847 if preferred and preferred != "auto":
1848 if preferred == "native":
1849 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1850 self.logger.log(
1851 VERBOSE_LOG_LEVEL,
1852 "Selected protocol for %s: native (user preference)",
1853 player.state.name,
1854 )
1855 return player, None
1856 else:
1857 for linked in player.linked_output_protocols:
1858 if linked.output_protocol_id == preferred:
1859 if protocol_player := self.get_player(linked.output_protocol_id):
1860 if protocol_player.available_for_playback:
1861 self.logger.log(
1862 VERBOSE_LOG_LEVEL,
1863 "Selected protocol for %s: %s (user preference)",
1864 player.state.name,
1865 protocol_player.state.name,
1866 )
1867 return protocol_player, player.get_linked_protocol(
1868 linked.output_protocol_id
1869 )
1870 break
1871
1872 # 3. Use native playback if available
1873 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1874 self.logger.log(
1875 VERBOSE_LOG_LEVEL, "Selected protocol for %s: native", player.state.name
1876 )
1877 return player, None
1878
1879 # 4. Use the player's preferred default protocol domain, if it declares one and a
1880 # matching linked protocol is available (e.g. a LinkPlay shell prefers DLNA). This
1881 # never influences grouping; it only steers the default output for playback. "Auto"
1882 # is the entry default here, so it consistently resolves to this domain default.
1883 if default_domain := player.default_output_protocol_domain:
1884 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1885 if linked.protocol_domain != default_domain:
1886 continue
1887 if (protocol_player := self.get_player(linked.output_protocol_id)) and (
1888 protocol_player.available_for_playback
1889 ):
1890 self.logger.log(
1891 VERBOSE_LOG_LEVEL,
1892 "Selected protocol for %s: %s (default domain %s)",
1893 player.state.name,
1894 protocol_player.state.name,
1895 default_domain,
1896 )
1897 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1898
1899 # 5. Fall back to best protocol by priority
1900 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1901 if protocol_player := self.get_player(linked.output_protocol_id):
1902 if protocol_player.available_for_playback:
1903 self.logger.log(
1904 VERBOSE_LOG_LEVEL,
1905 "Selected protocol for %s: %s (priority-based)",
1906 player.state.name,
1907 protocol_player.state.name,
1908 )
1909 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1910
1911 raise PlayerCommandFailed(f"Player {player.state.name} has no available output protocols")
1912
1913 def _get_control_target(
1914 self,
1915 player: Player,
1916 required_feature: PlayerFeature,
1917 require_active: bool = False,
1918 ) -> Player | None:
1919 """
1920 Get the best player(protocol) to send audio-path commands to.
1921
1922 Resolves commands that travel with the audio (enqueue, pause, announcements),
1923 so the output that renders the audio outranks the native player. Volume and
1924 mute are control-plane instead and resolve through
1925 :meth:`Player._get_protocol_player_for_feature`, which orders differently.
1926
1927 :param player: The player the command was issued on.
1928 :param required_feature: The feature the resolved target has to support.
1929 :param require_active: Only accept the output that is already rendering,
1930 instead of falling back to an idle one.
1931 """
1932 # If we have an active protocol, use that
1933 if (
1934 player.active_output_protocol
1935 and player.active_output_protocol != "native"
1936 and (protocol_player := self.mass.players.get_player(player.active_output_protocol))
1937 and required_feature in protocol_player.supported_features
1938 ):
1939 return protocol_player
1940
1941 # if the player natively supports the required feature, use that
1942 if (
1943 player.active_output_protocol == "native"
1944 and required_feature in player.supported_features
1945 ):
1946 return player
1947
1948 # If require_active is set, and no active protocol found, return None
1949 if require_active:
1950 return None
1951
1952 # if the player natively supports the required feature, use that
1953 if required_feature in player.supported_features:
1954 return player
1955
1956 # An output the user explicitly picked owns the audio, so a command that has to
1957 # start playback on an idle player follows it rather than the priority below.
1958 # The stored value survives a relink, so it only counts while it still names one
1959 # of this player's own outputs.
1960 preferred = self.mass.config.get_raw_player_config_value(
1961 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
1962 )
1963 if preferred and preferred not in ("auto", "native"):
1964 for linked in player.linked_output_protocols:
1965 if linked.output_protocol_id != preferred:
1966 continue
1967 if (
1968 (preferred_player := self.mass.players.get_player(str(preferred)))
1969 and preferred_player.available_for_playback
1970 and required_feature in preferred_player.supported_features
1971 ):
1972 return preferred_player
1973 break
1974
1975 # Otherwise, use the best available linked protocol, ordered by the same
1976 # priority that regular playback selection applies.
1977 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1978 if (
1979 (protocol_player := self.mass.players.get_player(linked.output_protocol_id))
1980 and protocol_player.available_for_playback
1981 and required_feature in protocol_player.supported_features
1982 ):
1983 return protocol_player
1984
1985 return None
1986
1987 def _is_protocol_grouped(self, protocol_player: Player) -> bool:
1988 """
1989 Check if a protocol player is currently grouped/synced with other players.
1990
1991 Used to prefer protocols that are actively participating in a group,
1992 ensuring consistent playback across grouped players.
1993 """
1994 is_grouped = bool(
1995 protocol_player.state.synced_to
1996 or (
1997 protocol_player.state.group_members and len(protocol_player.state.group_members) > 1
1998 )
1999 or protocol_player.state.active_group
2000 )
2001 if is_grouped:
2002 self.logger.log(
2003 VERBOSE_LOG_LEVEL,
2004 "Protocol player %s is grouped",
2005 protocol_player.state.name,
2006 )
2007 return is_grouped
2008
2009 def _translate_members_to_remove_for_protocols(
2010 self,
2011 parent_player: Player,
2012 player_ids: list[str],
2013 parent_protocol_player: Player | None,
2014 parent_protocol_domain: str | None,
2015 ) -> tuple[list[str], list[str]]:
2016 """
2017 Translate member IDs to remove into protocol and native lists.
2018
2019 :param parent_player: The parent player to remove members from.
2020 :param player_ids: List of visible player IDs to remove.
2021 :param parent_protocol_player: The parent's protocol player if available.
2022 :param parent_protocol_domain: The parent's protocol domain if available.
2023 """
2024 self.logger.debug(
2025 "Translating members to remove for %s: player_ids=%s, parent_protocol_domain=%s",
2026 parent_player.state.name,
2027 player_ids,
2028 parent_protocol_domain,
2029 )
2030 protocol_members: list[str] = []
2031 native_members: list[str] = []
2032
2033 for child_player_id in player_ids:
2034 child_player = self.get_player(child_player_id)
2035 if not child_player:
2036 continue
2037
2038 # Check if this member is in the parent's group via protocol
2039 if parent_protocol_domain and parent_protocol_player:
2040 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2041 if child_protocol and child_protocol.available:
2042 # For native protocol players, use the child's player_id directly
2043 child_protocol_id = (
2044 child_player.player_id
2045 if child_protocol.is_native
2046 else child_protocol.output_protocol_id
2047 )
2048 if child_protocol_id in parent_protocol_player.group_members:
2049 self.logger.debug(
2050 "Translating removal: %s -> protocol %s",
2051 child_player_id,
2052 child_protocol_id,
2053 )
2054 protocol_members.append(child_protocol_id)
2055 continue
2056
2057 # Check if child's protocol player is in parent's native group_members
2058 # This handles native protocol players (e.g., native AirPlay player like Apple TV)
2059 # where the parent itself contains protocol player IDs in its group_members
2060 translated = False
2061 for linked in child_player.linked_output_protocols:
2062 if linked.output_protocol_id in parent_player.group_members:
2063 self.logger.debug(
2064 "Translating removal (native parent): %s -> protocol %s",
2065 child_player_id,
2066 linked.output_protocol_id,
2067 )
2068 native_members.append(linked.output_protocol_id)
2069 translated = True
2070 break
2071
2072 if not translated:
2073 native_members.append(child_player_id)
2074
2075 return protocol_members, native_members
2076
2077 def _filter_protocol_members(self, member_ids: list[str], protocol_player: Player) -> list[str]:
2078 """Filter member IDs to only include players from the same protocol domain."""
2079 return [
2080 pid
2081 for pid in member_ids
2082 if (p := self.get_player(pid)) and p.provider.domain == protocol_player.provider.domain
2083 ]
2084
2085 def _filter_native_members(self, member_ids: list[str], parent_player: Player) -> list[str]:
2086 """Filter member IDs to only include players compatible with the parent."""
2087 return [
2088 pid
2089 for pid in member_ids
2090 if (p := self.get_player(pid))
2091 and (
2092 p.provider.instance_id == parent_player.provider.instance_id
2093 or pid in parent_player._attr_can_group_with
2094 or p.provider.instance_id in parent_player._attr_can_group_with
2095 )
2096 ]
2097
2098 def _try_child_preferred_protocol(
2099 self,
2100 child_player: Player,
2101 parent_player: Player,
2102 ) -> tuple[str | None, str | None]:
2103 """
2104 Try to use child's preferred output protocol for grouping.
2105
2106 Returns tuple of (child_protocol_id, protocol_domain) or (None, None).
2107 """
2108 child_preferred = self.mass.config.get_raw_player_config_value(
2109 child_player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2110 )
2111 if not child_preferred or child_preferred in {"auto", "native"}:
2112 return None, None
2113
2114 # Find child's preferred protocol, with its current availability
2115 child_protocol = None
2116 for output_protocol in child_player.output_protocols:
2117 if output_protocol.output_protocol_id == child_preferred:
2118 child_protocol = output_protocol
2119 break
2120
2121 if not child_protocol or not child_protocol.available:
2122 return None, None
2123
2124 # Check if parent supports this protocol (including native protocol)
2125 parent_protocol = parent_player.get_output_protocol_by_domain(
2126 child_protocol.protocol_domain
2127 )
2128 if not parent_protocol or not parent_protocol.available:
2129 return None, None
2130
2131 # Check if this protocol supports set_members
2132 protocol_player = parent_player.get_protocol_player(parent_protocol.output_protocol_id)
2133 if (
2134 not protocol_player
2135 or PlayerFeature.SET_MEMBERS not in protocol_player.state.supported_features
2136 ):
2137 return None, None
2138
2139 return child_protocol.output_protocol_id, child_protocol.protocol_domain
2140
2141 def _can_use_native_grouping(
2142 self,
2143 child_player: Player,
2144 parent_player: Player,
2145 parent_supports_native: bool,
2146 ) -> bool:
2147 """Check if child can be grouped with parent using native grouping."""
2148 if not parent_supports_native:
2149 return False
2150 return (
2151 parent_player.is_native_group_compatible(child_player)
2152 or child_player.player_id in parent_player._attr_can_group_with
2153 or child_player.provider.instance_id in parent_player._attr_can_group_with
2154 )
2155
2156 def _try_find_common_protocol(
2157 self, child_player: Player, parent_player: Player
2158 ) -> tuple[OutputProtocol | None, OutputProtocol | None]:
2159 """
2160 Find common protocol that supports set_members.
2161
2162 Returns tuple of (parent_protocol, child_protocol) or (None, None).
2163 """
2164 for parent_output_protocol in parent_player.output_protocols:
2165 if not parent_output_protocol.available:
2166 continue
2167 child_protocol = child_player.get_output_protocol_by_domain(
2168 parent_output_protocol.protocol_domain
2169 )
2170 if not child_protocol or not child_protocol.available:
2171 continue
2172 protocol_player = parent_player.get_protocol_player(
2173 parent_output_protocol.output_protocol_id
2174 )
2175 if protocol_player and PlayerFeature.SET_MEMBERS in protocol_player.supported_features:
2176 return parent_output_protocol, child_protocol
2177 return None, None
2178
2179 def _parent_has_live_native_session(self, parent_player: Player) -> bool:
2180 """
2181 Return True when the parent currently holds a live native playback session.
2182
2183 The active output protocol lingers for a few seconds after stop, so a non-idle
2184 playback state is required to distinguish a real session from a just-stopped one.
2185 """
2186 return parent_player.active_output_protocol == "native" and (
2187 parent_player.state.playback_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
2188 )
2189
2190 def _order_members_for_native_join(
2191 self,
2192 player_ids: list[str],
2193 parent_player: Player,
2194 parent_supports_native_grouping: bool,
2195 ) -> list[str]:
2196 """
2197 Order members so a live native session can be joined without splitting the group.
2198
2199 When the parent already holds a live native session, children that cannot group
2200 natively are evaluated first: they may force a shared protocol for the whole group,
2201 and processing them before the native-capable children lets those join that same
2202 protocol instead of being stranded in a separate native sub-group. The order is left
2203 untouched when the parent is not playing natively, so fresh-group selection is unchanged.
2204
2205 :param player_ids: The member IDs to be added, in their original order.
2206 :param parent_player: The parent player being joined.
2207 :param parent_supports_native_grouping: Whether the parent can group natively.
2208 """
2209 if not self._parent_has_live_native_session(parent_player):
2210 return player_ids
2211 return sorted(
2212 player_ids,
2213 key=lambda pid: bool(
2214 (child := self.get_player(pid))
2215 and self._can_use_native_grouping(
2216 child, parent_player, parent_supports_native_grouping
2217 )
2218 ),
2219 )
2220
2221 def _try_join_active_native_session(
2222 self,
2223 child_player: Player,
2224 parent_player: Player,
2225 parent_protocol_domain: str | None,
2226 parent_supports_native_grouping: bool,
2227 native_members: list[str],
2228 ) -> bool:
2229 """
2230 Add the child to native_members if it can join the parent's active native session.
2231
2232 A child's preferred output protocol must only steer protocol selection when the child
2233 initiates its own playback; when it joins a parent that is already playing natively it
2234 should adopt native grouping if compatible, rather than forcing the whole group onto
2235 the child's preferred protocol. Skipped once a protocol has been selected for the group,
2236 so mixed batches stay cohesive on a single protocol.
2237
2238 :param child_player: The player being added to the group.
2239 :param parent_player: The parent player being joined.
2240 :param parent_protocol_domain: The protocol domain already selected for the group, if any.
2241 :param parent_supports_native_grouping: Whether the parent can group natively.
2242 :param native_members: The native members list to append to when the child joins.
2243 """
2244 if not (
2245 self._parent_has_live_native_session(parent_player)
2246 and not parent_protocol_domain
2247 and self._can_use_native_grouping(
2248 child_player, parent_player, parent_supports_native_grouping
2249 )
2250 ):
2251 return False
2252 native_members.append(child_player.player_id)
2253 self.logger.log(
2254 VERBOSE_LOG_LEVEL,
2255 "Joining parent's active native session for %s",
2256 child_player.state.name,
2257 )
2258 return True
2259
2260 def _translate_native_members_to_protocol(
2261 self, parent_player: Player, protocol_domain: str, member_ids: list[str]
2262 ) -> list[str]:
2263 """
2264 Translate natively grouped members onto the protocol domain the parent plays through.
2265
2266 Members that do not have that protocol cannot follow the parent at all and are
2267 dropped with a warning instead.
2268
2269 :param parent_player: The parent player the members are grouped with.
2270 :param protocol_domain: The protocol domain selected for the group.
2271 :param member_ids: The member IDs that were selected for native grouping.
2272 """
2273 translated: list[str] = []
2274 for member_id in member_ids:
2275 member_player = self.get_player(member_id)
2276 if not member_player:
2277 continue
2278 # a native group's members may be listed by their protocol player id
2279 if member_player.protocol_parent_id:
2280 member_player = self.get_player(member_player.protocol_parent_id) or member_player
2281 member_protocol = member_player.get_output_protocol_by_domain(protocol_domain)
2282 if not member_protocol or not member_protocol.available:
2283 self.logger.warning(
2284 "Cannot group %s with %s: the group plays through the %s protocol, "
2285 "which %s does not support",
2286 member_player.state.name,
2287 parent_player.state.name,
2288 protocol_domain,
2289 member_player.state.name,
2290 )
2291 continue
2292 # For native protocol players, use the member's player_id directly
2293 translated.append(
2294 member_player.player_id
2295 if member_protocol.is_native
2296 else member_protocol.output_protocol_id
2297 )
2298 self.logger.log(
2299 VERBOSE_LOG_LEVEL,
2300 "Moving %s from native grouping to the %s protocol",
2301 member_player.state.name,
2302 protocol_domain,
2303 )
2304 return translated
2305
2306 def _move_native_members_to_group_protocol(
2307 self,
2308 parent_player: Player,
2309 parent_protocol_player: Player | None,
2310 parent_protocol_domain: str | None,
2311 protocol_members: list[str],
2312 native_members: list[str],
2313 ) -> None:
2314 """
2315 Move the members selected for native grouping onto the protocol the group ended up on.
2316
2317 Does nothing unless the group ends up on one of the parent's protocols while the
2318 parent's native grouping needs the parent's own stream: only then do those members
2319 have no session left to attach to.
2320
2321 :param parent_player: The parent player being joined.
2322 :param parent_protocol_player: The protocol player selected for the group, if any.
2323 :param parent_protocol_domain: The protocol domain selected for the group, if any.
2324 :param protocol_members: The protocol member list the translated IDs are added to.
2325 :param native_members: The native member IDs, emptied when they are moved over.
2326 """
2327 if not (
2328 native_members
2329 and parent_protocol_domain
2330 and parent_protocol_player
2331 and parent_protocol_player.player_id != parent_player.player_id
2332 and parent_player.native_grouping_requires_own_stream
2333 ):
2334 return
2335 protocol_members.extend(
2336 self._translate_native_members_to_protocol(
2337 parent_player, parent_protocol_domain, native_members
2338 )
2339 )
2340 native_members.clear()
2341
2342 def _migrate_stranded_native_members(
2343 self,
2344 parent_player: Player,
2345 parent_protocol_player: Player,
2346 protocol_members: list[str],
2347 ) -> list[str]:
2348 """
2349 Move the native members that a switch to the given protocol strands onto that protocol.
2350
2351 Returns the member IDs that are still attached to the parent's own stream, so the
2352 caller can release them from it. Empty unless the parent renders that stream itself
2353 while its native grouping attaches the members to exactly that stream: only then are
2354 they left without anything to play.
2355
2356 :param parent_player: The parent player that is about to switch protocol.
2357 :param parent_protocol_player: The protocol player the parent will render through.
2358 :param protocol_members: The protocol member list the translated IDs are added to.
2359 """
2360 if parent_protocol_player.player_id == parent_player.player_id:
2361 return []
2362 if not parent_player.native_grouping_requires_own_stream:
2363 return []
2364 if parent_player.active_output_protocol not in (None, "native"):
2365 return []
2366 if parent_player.state.playback_state not in (PlaybackState.PLAYING, PlaybackState.PAUSED):
2367 return []
2368 stranded = [
2369 member_id
2370 for member_id in parent_player.group_members
2371 if member_id != parent_player.player_id
2372 ]
2373 for protocol_id in self._translate_native_members_to_protocol(
2374 parent_player, parent_protocol_player.provider.domain, stranded
2375 ):
2376 if protocol_id not in protocol_members:
2377 protocol_members.append(protocol_id)
2378 return stranded
2379
2380 async def _stop_native_session(
2381 self,
2382 parent_player: Player,
2383 parent_protocol_player: Player,
2384 stranded_native_members: list[str],
2385 ) -> None:
2386 """
2387 Release the given members from the parent's own stream and stop it.
2388
2389 :param parent_player: The parent player whose native session is handed over.
2390 :param parent_protocol_player: The protocol player taking the output over.
2391 :param stranded_native_members: The members to release, already migrated.
2392 """
2393 self.logger.debug(
2394 "Stopping the native session of %s before switching to %s, migrated members: %s",
2395 parent_player.state.name,
2396 parent_protocol_player.state.name,
2397 stranded_native_members,
2398 )
2399 # The members already joined the protocol group, so the native session only has to
2400 # release them and stop. Releasing them first also clears the native group, which
2401 # keeps a later native playback command from resurrecting it. Both calls take the
2402 # provider's own lock, so they must run one after the other.
2403 await parent_player.set_members(player_ids_to_remove=stranded_native_members)
2404 await parent_player.stop()
2405
2406 def _translate_members_for_protocols(
2407 self,
2408 parent_player: Player,
2409 player_ids: list[str],
2410 parent_protocol_player: Player | None,
2411 parent_protocol_domain: str | None,
2412 ) -> tuple[list[str], list[str], Player | None, str | None]:
2413 """
2414 Translate member IDs to protocol or native IDs.
2415
2416 The grouping method is picked per member, see _select_grouping_for_member.
2417
2418 Returns tuple of (protocol_members, native_members, protocol_player, protocol_domain).
2419 """
2420 protocol_members: list[str] = []
2421 native_members: list[str] = []
2422 parent_supports_native_grouping = (
2423 PlayerFeature.SET_MEMBERS in parent_player.supported_features
2424 )
2425 player_ids = self._order_members_for_native_join(
2426 player_ids, parent_player, parent_supports_native_grouping
2427 )
2428
2429 self.logger.log(
2430 VERBOSE_LOG_LEVEL,
2431 "Translating members for %s: parent_supports_native=%s, parent_protocol=%s (%s)",
2432 parent_player.state.name,
2433 parent_supports_native_grouping,
2434 parent_protocol_player.state.name if parent_protocol_player else "none",
2435 parent_protocol_domain or "none",
2436 )
2437
2438 for child_player_id in player_ids:
2439 child_player = self.get_player(child_player_id)
2440 if not child_player:
2441 continue
2442
2443 self.logger.log(
2444 VERBOSE_LOG_LEVEL,
2445 "Processing child %s (type=%s, protocols=%s)",
2446 child_player.state.name,
2447 child_player.state.type,
2448 [p.protocol_domain for p in child_player.output_protocols],
2449 )
2450
2451 parent_protocol_player, parent_protocol_domain = self._select_grouping_for_member(
2452 child_player,
2453 parent_player,
2454 parent_protocol_player,
2455 parent_protocol_domain,
2456 parent_supports_native_grouping,
2457 protocol_members,
2458 native_members,
2459 )
2460
2461 # Post-pass: the protocol selected for the group is only known once every child has
2462 # been processed, so the members picked for native grouping are corrected here.
2463 self._move_native_members_to_group_protocol(
2464 parent_player,
2465 parent_protocol_player,
2466 parent_protocol_domain,
2467 protocol_members,
2468 native_members,
2469 )
2470
2471 return protocol_members, native_members, parent_protocol_player, parent_protocol_domain
2472
2473 def _select_grouping_for_member(
2474 self,
2475 child_player: Player,
2476 parent_player: Player,
2477 parent_protocol_player: Player | None,
2478 parent_protocol_domain: str | None,
2479 parent_supports_native_grouping: bool,
2480 protocol_members: list[str],
2481 native_members: list[str],
2482 ) -> tuple[Player | None, str | None]:
2483 """
2484 Pick the grouping method for a single member and add it to the matching member list.
2485
2486 Selection priority when grouping:
2487 0. If the parent is already playing natively and the child can be grouped
2488 natively, join that native session (a child joining an existing group must
2489 not force the whole group onto its own preferred output protocol)
2490 1. Try child's preferred output protocol (from player settings)
2491 2. Try parent's active output protocol (if any and child supports it)
2492 3. Try native grouping (if parent and child are compatible)
2493 4. Search for common protocol that supports set_members
2494 5. Log warning if no option works
2495
2496 Returns the protocol player/domain the group is on, which the picked method may have
2497 changed.
2498
2499 :param child_player: The player being added to the group.
2500 :param parent_player: The parent player being joined.
2501 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2502 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2503 :param parent_supports_native_grouping: Whether the parent can group natively.
2504 :param protocol_members: The protocol member list to append to.
2505 :param native_members: The native member list to append to.
2506 """
2507 # Priority 0: The parent is already playing natively and the child can join
2508 # that native session directly - adopt it before considering the child's own
2509 # preferred output protocol.
2510 if self._try_join_active_native_session(
2511 child_player,
2512 parent_player,
2513 parent_protocol_domain,
2514 parent_supports_native_grouping,
2515 native_members,
2516 ):
2517 return parent_protocol_player, parent_protocol_domain
2518
2519 # Priority 0.5: a player that runs its own multiroom (e.g. a LinkPlay control shell)
2520 # keeps grouping on its native path rather than routing it through a linked protocol
2521 # that is merely its preferred playback output. Native compatibility still decides
2522 # whether this is possible, so an incompatible/cross-backend pair falls through.
2523 if child_player.prefer_native_grouping and self._can_use_native_grouping(
2524 child_player, parent_player, parent_supports_native_grouping
2525 ):
2526 native_members.append(child_player.player_id)
2527 self.logger.log(
2528 VERBOSE_LOG_LEVEL,
2529 "Using native grouping (preferred) for %s",
2530 child_player.state.name,
2531 )
2532 return parent_protocol_player, parent_protocol_domain
2533
2534 # Priority 1: the child's preferred output protocol
2535 grouped, parent_protocol_player, parent_protocol_domain = (
2536 self._try_group_via_preferred_protocol(
2537 child_player,
2538 parent_player,
2539 parent_protocol_player,
2540 parent_protocol_domain,
2541 protocol_members,
2542 )
2543 )
2544 if grouped:
2545 return parent_protocol_player, parent_protocol_domain
2546
2547 # Priority 2: the protocol the group is already on
2548 grouped, parent_protocol_player, parent_protocol_domain = (
2549 self._try_group_via_active_protocol(
2550 child_player,
2551 parent_protocol_player,
2552 parent_protocol_domain,
2553 protocol_members,
2554 )
2555 )
2556 if grouped:
2557 return parent_protocol_player, parent_protocol_domain
2558
2559 # Priority 3: native grouping
2560 if self._can_use_native_grouping(
2561 child_player, parent_player, parent_supports_native_grouping
2562 ):
2563 native_members.append(child_player.player_id)
2564 self.logger.log(
2565 VERBOSE_LOG_LEVEL,
2566 "Using native grouping for %s",
2567 child_player.state.name,
2568 )
2569 return parent_protocol_player, parent_protocol_domain
2570
2571 # Priority 4: a protocol both players share that supports set_members
2572 grouped, parent_protocol_player, parent_protocol_domain = (
2573 self._try_group_via_common_protocol(
2574 child_player,
2575 parent_player,
2576 parent_protocol_player,
2577 parent_protocol_domain,
2578 protocol_members,
2579 )
2580 )
2581 if grouped:
2582 return parent_protocol_player, parent_protocol_domain
2583
2584 # Priority 5: no option worked
2585 self.logger.warning(
2586 "Cannot group %s with %s: no compatible grouping method found "
2587 "(tried: child preferred protocol, parent active protocol, "
2588 "native grouping, common protocols)",
2589 child_player.state.name,
2590 parent_player.state.name,
2591 )
2592 return parent_protocol_player, parent_protocol_domain
2593
2594 def _try_group_via_preferred_protocol(
2595 self,
2596 child_player: Player,
2597 parent_player: Player,
2598 parent_protocol_player: Player | None,
2599 parent_protocol_domain: str | None,
2600 protocol_members: list[str],
2601 ) -> tuple[bool, Player | None, str | None]:
2602 """
2603 Try to group the child through the output protocol it prefers in its player settings.
2604
2605 Only used when the group is not on a protocol yet or is already on that same protocol.
2606 Returns whether the child was grouped, together with the protocol player/domain the
2607 group is on: the child's preferred protocol may become the group's protocol.
2608
2609 :param child_player: The player being added to the group.
2610 :param parent_player: The parent player being joined.
2611 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2612 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2613 :param protocol_members: The protocol member list to append to.
2614 """
2615 child_protocol_id, protocol_domain = self._try_child_preferred_protocol(
2616 child_player, parent_player
2617 )
2618 if not (
2619 child_protocol_id
2620 and protocol_domain
2621 and (not parent_protocol_domain or protocol_domain == parent_protocol_domain)
2622 ):
2623 return False, parent_protocol_player, parent_protocol_domain
2624
2625 if not parent_protocol_player or parent_protocol_domain != protocol_domain:
2626 parent_protocol = parent_player.get_output_protocol_by_domain(protocol_domain)
2627 if parent_protocol:
2628 parent_protocol_player = parent_player.get_protocol_player(
2629 parent_protocol.output_protocol_id
2630 )
2631 parent_protocol_domain = protocol_domain
2632 protocol_members.append(child_protocol_id)
2633 self.logger.log(
2634 VERBOSE_LOG_LEVEL,
2635 "Using child's preferred protocol %s for %s",
2636 protocol_domain,
2637 child_player.state.name,
2638 )
2639 return True, parent_protocol_player, parent_protocol_domain
2640
2641 def _try_group_via_active_protocol(
2642 self,
2643 child_player: Player,
2644 parent_protocol_player: Player | None,
2645 parent_protocol_domain: str | None,
2646 protocol_members: list[str],
2647 ) -> tuple[bool, Player | None, str | None]:
2648 """
2649 Try to group the child through the protocol the group is already on.
2650
2651 Returns whether the child was grouped, together with the protocol player/domain the
2652 group is on: the selection is dropped when that protocol cannot group members itself,
2653 so a later grouping method can select another one.
2654
2655 :param child_player: The player being added to the group.
2656 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2657 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2658 :param protocol_members: The protocol member list to append to.
2659 """
2660 if not parent_protocol_domain or not parent_protocol_player:
2661 return False, parent_protocol_player, parent_protocol_domain
2662
2663 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2664 self.logger.log(
2665 VERBOSE_LOG_LEVEL,
2666 "Parent's active protocol %s does not support SET_MEMBERS, "
2667 "will search for alternative",
2668 parent_protocol_domain,
2669 )
2670 # Drop the selection so a later grouping method can select a new protocol
2671 return False, None, None
2672
2673 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2674 if not child_protocol or not child_protocol.available:
2675 return False, parent_protocol_player, parent_protocol_domain
2676
2677 # For native protocol players, use the child's player_id directly
2678 # (e.g., a native sendspin web player IS the protocol player)
2679 child_protocol_id = (
2680 child_player.player_id
2681 if child_protocol.is_native
2682 else child_protocol.output_protocol_id
2683 )
2684 protocol_members.append(child_protocol_id)
2685 self.logger.log(
2686 VERBOSE_LOG_LEVEL,
2687 "Using parent's active protocol %s for %s",
2688 parent_protocol_domain,
2689 child_player.state.name,
2690 )
2691 return True, parent_protocol_player, parent_protocol_domain
2692
2693 def _try_group_via_common_protocol(
2694 self,
2695 child_player: Player,
2696 parent_player: Player,
2697 parent_protocol_player: Player | None,
2698 parent_protocol_domain: str | None,
2699 protocol_members: list[str],
2700 ) -> tuple[bool, Player | None, str | None]:
2701 """
2702 Try to group the child through a protocol both players share.
2703
2704 Returns whether the child was grouped, together with the protocol player/domain the
2705 group is on: the shared protocol may become the group's protocol.
2706
2707 :param child_player: The player being added to the group.
2708 :param parent_player: The parent player being joined.
2709 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2710 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2711 :param protocol_members: The protocol member list to append to.
2712 """
2713 parent_protocol, child_protocol = self._try_find_common_protocol(
2714 child_player, parent_player
2715 )
2716 if not parent_protocol or not child_protocol:
2717 return False, parent_protocol_player, parent_protocol_domain
2718
2719 if not parent_protocol_player or parent_protocol_domain != parent_protocol.protocol_domain:
2720 parent_protocol_player = parent_player.get_protocol_player(
2721 parent_protocol.output_protocol_id
2722 )
2723 if parent_protocol_player:
2724 parent_protocol_domain = parent_protocol_player.provider.domain
2725 # For native protocol players, use the child's player_id directly
2726 child_protocol_id = (
2727 child_player.player_id
2728 if child_protocol.is_native
2729 else child_protocol.output_protocol_id
2730 )
2731 protocol_members.append(child_protocol_id)
2732 self.logger.log(
2733 VERBOSE_LOG_LEVEL,
2734 "Selected common protocol %s for grouping %s with %s",
2735 parent_protocol.protocol_domain,
2736 child_player.state.name,
2737 parent_player.state.name,
2738 )
2739 return True, parent_protocol_player, parent_protocol_domain
2740
2741 async def _forward_protocol_set_members(
2742 self,
2743 parent_player: Player,
2744 parent_protocol_player: Player,
2745 protocol_members_to_add: list[str],
2746 protocol_members_to_remove: list[str],
2747 ) -> None:
2748 """
2749 Forward protocol members to protocol player's set_members and manage active output protocol.
2750
2751 :param parent_player: The parent player (native/universal).
2752 :param parent_protocol_player: The protocol player to forward commands to.
2753 :param protocol_members_to_add: Protocol player IDs to add.
2754 :param protocol_members_to_remove: Protocol player IDs to remove.
2755 """
2756 filtered_protocol_add = self._filter_protocol_members(
2757 protocol_members_to_add, parent_protocol_player
2758 )
2759 filtered_protocol_remove = self._filter_protocol_members(
2760 protocol_members_to_remove, parent_protocol_player
2761 )
2762 self.logger.debug(
2763 "Protocol grouping on %s: filtered_add=%s, filtered_remove=%s",
2764 parent_protocol_player.state.name,
2765 filtered_protocol_add,
2766 filtered_protocol_remove,
2767 )
2768
2769 if not filtered_protocol_add and not filtered_protocol_remove:
2770 return
2771
2772 # Safety check: verify protocol player supports SET_MEMBERS
2773 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2774 self.logger.error(
2775 "Protocol player %s does not support SET_MEMBERS, cannot perform grouping. "
2776 "This should have been caught earlier in the flow.",
2777 parent_protocol_player.state.name,
2778 )
2779 return
2780
2781 # Members that ride the parent's own stream are stranded by the protocol switch below,
2782 # so they join the protocol group in this very same call and their native session is
2783 # torn down afterwards.
2784 stranded_native_members = (
2785 self._migrate_stranded_native_members(
2786 parent_player, parent_protocol_player, filtered_protocol_add
2787 )
2788 if filtered_protocol_add
2789 else []
2790 )
2791
2792 # This runs before set_members because a member's own stream starts inside that call
2793 # and the provider resolves the member's volume control as it starts: unless its parent
2794 # already points at this protocol, that resolution picks a sibling interface of the same
2795 # device (e.g. its cast side) over the one carrying the audio.
2796 self._activate_protocol_on_added_children(filtered_protocol_add)
2797
2798 self.logger.debug(
2799 "Calling set_members on protocol player %s with add=%s, remove=%s",
2800 parent_protocol_player.state.name,
2801 filtered_protocol_add,
2802 filtered_protocol_remove,
2803 )
2804 await parent_protocol_player.set_members(
2805 player_ids_to_add=filtered_protocol_add or None,
2806 player_ids_to_remove=filtered_protocol_remove or None,
2807 )
2808
2809 if filtered_protocol_add:
2810 await self._activate_group_output_protocol(
2811 parent_player, parent_protocol_player, stranded_native_members
2812 )
2813
2814 self.logger.debug(
2815 "After set_members, protocol player %s state: group_members=%s, synced_to=%s",
2816 parent_protocol_player.state.name,
2817 parent_protocol_player.group_members,
2818 parent_protocol_player.synced_to,
2819 )
2820
2821 def _activate_protocol_on_added_children(self, protocol_member_ids: list[str]) -> None:
2822 """
2823 Point the parent of each given protocol member at the protocol carrying the group audio.
2824
2825 :param protocol_member_ids: The protocol player IDs joining the group.
2826 """
2827 for child_protocol_id in protocol_member_ids:
2828 if not (child_protocol := self.get_player(child_protocol_id)):
2829 continue
2830 if not child_protocol.protocol_parent_id:
2831 continue
2832 if not (child_player := self.get_player(child_protocol.protocol_parent_id)):
2833 continue
2834 if child_player.active_output_protocol == child_protocol_id:
2835 continue
2836 self.logger.debug(
2837 "Setting active output protocol on child %s to %s",
2838 child_player.state.name,
2839 child_protocol_id,
2840 )
2841 child_player.set_active_output_protocol(child_protocol_id)
2842
2843 async def _activate_group_output_protocol(
2844 self,
2845 parent_player: Player,
2846 parent_protocol_player: Player,
2847 stranded_native_members: list[str],
2848 ) -> None:
2849 """
2850 Mark the given protocol as the parent's output and hand the playback over to it.
2851
2852 The handover only runs when the parent is actually switching protocol while it is
2853 rendering; playback is resumed only for a parent that was playing, so adding a member
2854 never starts playback on its own.
2855
2856 :param parent_player: The parent player that just gained protocol members.
2857 :param parent_protocol_player: The protocol player the members joined.
2858 :param stranded_native_members: The members left without a stream by the switch.
2859 """
2860 previous_protocol = parent_player.active_output_protocol
2861 was_playing = parent_player.state.playback_state == PlaybackState.PLAYING
2862 # A paused player still holds its output, so the handover has to run for it too.
2863 was_rendering = was_playing or parent_player.state.playback_state == PlaybackState.PAUSED
2864
2865 # Native protocol: parent_protocol_player is the same as parent_player
2866 is_native_protocol = parent_protocol_player.player_id == parent_player.player_id
2867 already_using_native = previous_protocol in (None, "native")
2868 already_using_this_protocol = previous_protocol == parent_protocol_player.player_id
2869 switching_protocols = not (
2870 (is_native_protocol and already_using_native) or already_using_this_protocol
2871 )
2872
2873 self.logger.debug(
2874 "Protocol grouping: is_native=%s, already_native=%s, already_this=%s, "
2875 "switching=%s, was_rendering=%s",
2876 is_native_protocol,
2877 already_using_native,
2878 already_using_this_protocol,
2879 switching_protocols,
2880 was_rendering,
2881 )
2882
2883 if not (is_native_protocol and already_using_native):
2884 parent_player.set_active_output_protocol(parent_protocol_player.player_id)
2885
2886 if not (was_rendering and switching_protocols):
2887 return
2888
2889 self.logger.info(
2890 "Handing the output of %s over to the %s protocol%s",
2891 parent_player.state.name,
2892 parent_protocol_player.provider.domain,
2893 " and resuming playback" if was_playing else "",
2894 )
2895 if stranded_native_members:
2896 await self._stop_native_session(
2897 parent_player, parent_protocol_player, stranded_native_members
2898 )
2899 old_parent_members = await self._stop_previous_protocol(
2900 parent_player, parent_protocol_player, previous_protocol
2901 )
2902 if was_playing:
2903 await self.mass.players.cmd_resume(parent_player.player_id)
2904 if old_parent_members:
2905 self.logger.debug(
2906 "Re-adding migrated members %s to %s on new protocol",
2907 old_parent_members,
2908 parent_player.state.name,
2909 )
2910 # Use internal handler because we are already inside a
2911 # _handle_set_members call chain that holds the play lock.
2912 await self.mass.players._handle_set_members(
2913 parent_player,
2914 player_ids_to_add=old_parent_members,
2915 )
2916
2917 async def _stop_previous_protocol(
2918 self,
2919 parent_player: Player,
2920 parent_protocol_player: Player,
2921 previous_protocol: str | None,
2922 ) -> list[str]:
2923 """
2924 Stop the protocol player the parent was rendering through and return its members.
2925
2926 The returned IDs are parent player IDs, so the caller can re-add them to the group
2927 once the new protocol carries the audio. Empty if there is nothing to hand over.
2928
2929 :param parent_player: The parent player that is switching protocol.
2930 :param parent_protocol_player: The protocol player taking the output over.
2931 :param previous_protocol: The parent's previous active output protocol, if any.
2932 """
2933 if previous_protocol in (None, "native"):
2934 return []
2935 if not (old_protocol_player := self.get_player(previous_protocol)):
2936 return []
2937 if old_protocol_player.player_id == parent_protocol_player.player_id:
2938 return []
2939 # Translate the old protocol's child members back to parent player IDs
2940 old_parent_members: list[str] = []
2941 for member_id in old_protocol_player.group_members:
2942 if member_id == old_protocol_player.player_id:
2943 continue
2944 if not (member_player := self.get_player(member_id)):
2945 continue
2946 parent_id = member_player.protocol_parent_id or member_id
2947 if parent_id != parent_player.player_id:
2948 old_parent_members.append(parent_id)
2949 self.logger.debug(
2950 "Stopping old protocol player %s before switching to %s, migrating members: %s",
2951 old_protocol_player.state.name,
2952 parent_protocol_player.state.name,
2953 old_parent_members,
2954 )
2955 # Use internal handler to stop the specific protocol player,
2956 # bypassing group/sync redirect and queue redirect logic.
2957 await self.mass.players._handle_cmd_stop(old_protocol_player.player_id)
2958 return old_parent_members
2959