/
/
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._update_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 the protocol links from the universal player to the native player.
1043 # A derived protocol rides on another output, so a base and everything riding
1044 # on it can only move together: refusing one of them holds back the group.
1045 for group in self._group_protocol_links(player):
1046 domains = {
1047 protocol_player.player_id: linked.protocol_domain
1048 or protocol_player.provider.domain
1049 for linked, protocol_player in group
1050 }
1051 if any(
1052 self._parent_has_active_protocol_from_domain(
1053 native_player, domain, exclude_player_id=protocol_id
1054 )
1055 for protocol_id, domain in domains.items()
1056 ):
1057 refused_protocol_ids.update(domains.keys())
1058 continue
1059 for _, protocol_player in group:
1060 protocol_player.set_protocol_parent_id(None)
1061 self._add_protocol_link(
1062 native_player, protocol_player, domains[protocol_player.player_id]
1063 )
1064 if protocol_player.protocol_parent_id != native_player.player_id:
1065 # Link refused, keep the protocol owned by the universal player.
1066 protocol_player.set_protocol_parent_id(player.player_id)
1067 refused_protocol_ids.add(protocol_player.player_id)
1068 continue
1069 protocol_player.refresh_state()
1070 moved_protocol_ids.add(protocol_player.player_id)
1071
1072 # A refused link leaves the universal player in charge, so only hand over what
1073 # actually moved: ownership that exists in config alone stays with it, which
1074 # keeps a protocol derived from a refused one with the parent it will link to.
1075 migrated_protocol_ids = (
1076 moved_protocol_ids if refused_protocol_ids else known_protocol_ids
1077 )
1078 # A device that kept its id across a type change lists itself here.
1079 # It must never become its own protocol, and it must also be dropped
1080 # from the obsolete universal player so the permanent cleanup below
1081 # doesn't treat it as an orphaned protocol (which would re-wrap the
1082 # native player in a fresh universal player).
1083 migrated_protocol_ids.discard(native_player.player_id)
1084 self._migrate_protocol_ids_to_parent(native_player, migrated_protocol_ids)
1085 self._remove_protocol_ids_from_parent(
1086 player, migrated_protocol_ids | {native_player.player_id}
1087 )
1088 native_player.refresh_state()
1089
1090 if refused_protocol_ids:
1091 # Registered protocols that the native player refused remain on the wrapper.
1092 continue
1093
1094 # Carry over the user's configuration and re-point group memberships
1095 # before the permanent removal below deletes the universal player's config
1096 self._migrate_universal_player_config(player.player_id, native_player.player_id)
1097 self._update_group_memberships(player.player_id, native_player.player_id)
1098
1099 # Stop playback and remove the now-obsolete universal player
1100 self.mass.create_task(self._stop_and_unregister(player, native_player.player_id))
1101
1102 def _group_protocol_links(
1103 self, parent: Player
1104 ) -> list[list[tuple[LinkedOutputProtocol, Player]]]:
1105 """
1106 Group a parent's registered protocol links with the protocols riding on them.
1107
1108 Each group holds one base protocol followed by the derived protocols that ride
1109 on it. A protocol whose underlying player is not one of the parent's own links
1110 forms a group of its own.
1111
1112 :param parent: The parent player whose protocol links should be grouped.
1113 """
1114 registered = [
1115 (linked, protocol_player)
1116 for linked in parent.linked_output_protocols
1117 if (protocol_player := self.get_player(linked.output_protocol_id))
1118 ]
1119 link_ids = {protocol_player.player_id for _, protocol_player in registered}
1120 riders: dict[str, list[tuple[LinkedOutputProtocol, Player]]] = {}
1121 bases: list[tuple[LinkedOutputProtocol, Player]] = []
1122 for linked, protocol_player in registered:
1123 underlying_id = protocol_player.underlying_player_id
1124 if underlying_id and underlying_id in link_ids:
1125 riders.setdefault(underlying_id, []).append((linked, protocol_player))
1126 else:
1127 bases.append((linked, protocol_player))
1128
1129 groups = [
1130 [(linked, protocol_player), *riders.get(protocol_player.player_id, [])]
1131 for linked, protocol_player in bases
1132 ]
1133 # A derived protocol riding on another derived protocol has no base group here,
1134 # so it moves on its own rather than being dropped from the transfer.
1135 grouped_ids = {
1136 protocol_player.player_id for group in groups for _, protocol_player in group
1137 }
1138 groups.extend([entry] for entry in registered if entry[1].player_id not in grouped_ids)
1139 return groups
1140
1141 def _migrate_universal_player_config(self, universal_id: str, native_id: str) -> None:
1142 """
1143 Carry over user-set configuration from a replaced universal player.
1144
1145 Copies the custom display name, player config values, DSP settings and
1146 per-queue settings of the (obsolete) universal player onto the native
1147 player that replaces it, without overwriting values explicitly set on
1148 the native player itself. Must be called while the universal player's
1149 config still exists, as the permanent removal deletes it.
1150
1151 :param universal_id: Player id of the obsolete universal player being replaced.
1152 :param native_id: Player id of the native player that replaces it.
1153 """
1154 source_raw = self.mass.config.get(f"{CONF_PLAYERS}/{universal_id}")
1155 source_raw = source_raw if isinstance(source_raw, dict) else {}
1156 target_key = f"{CONF_PLAYERS}/{native_id}"
1157 target_raw = self.mass.config.get(target_key)
1158 target_raw = target_raw if isinstance(target_raw, dict) else {}
1159 player_config_changed = False
1160
1161 # only carry an actual user rename, not the auto-generated default name;
1162 # likewise a name on the native player only counts as a user override when
1163 # it differs from the default name
1164 custom_name = source_raw.get("name")
1165 target_name = target_raw.get("name")
1166 target_has_custom_name = bool(target_name) and target_name != target_raw.get("default_name")
1167 if (
1168 custom_name
1169 and custom_name != source_raw.get("default_name")
1170 and not target_has_custom_name
1171 ):
1172 self.mass.config.set(f"{target_key}/name", custom_name)
1173 player_config_changed = True
1174
1175 source_values = source_raw.get("values")
1176 source_values = source_values if isinstance(source_values, dict) else {}
1177 target_values = target_raw.get("values")
1178 target_values = target_values if isinstance(target_values, dict) else {}
1179 for key, value in source_values.items():
1180 if key in UNIVERSAL_PLAYER_INTERNAL_CONF_KEYS:
1181 continue
1182 if CONF_PROTOCOL_KEY_SPLITTER in key:
1183 # stale virtual mirror of a protocol player's own config
1184 continue
1185 if key in target_values:
1186 continue
1187 self.mass.config.set(f"{target_key}/values/{key}", deepcopy(value))
1188 player_config_changed = True
1189
1190 # DSP settings follow wholesale, unless the native player has its own
1191 dsp_changed = False
1192 source_dsp = self.mass.config.get(f"{CONF_PLAYER_DSP}/{universal_id}")
1193 if source_dsp and not self.mass.config.get(f"{CONF_PLAYER_DSP}/{native_id}"):
1194 self.mass.config.set(f"{CONF_PLAYER_DSP}/{native_id}", deepcopy(source_dsp))
1195 dsp_changed = True
1196
1197 queue_changed = self._migrate_universal_queue_config(universal_id, native_id)
1198
1199 if not (player_config_changed or dsp_changed or queue_changed):
1200 return
1201 self.logger.info(
1202 "Carried over configuration of universal player %s to %s", universal_id, native_id
1203 )
1204 if player_config_changed:
1205 # the native player's in-place config was loaded before the carry-over,
1206 # so reload it to make the migrated values (e.g. custom name) effective
1207 self.mass.create_task(self._reapply_player_config(native_id))
1208
1209 def _migrate_universal_queue_config(self, universal_id: str, native_id: str) -> bool:
1210 """
1211 Move the per-queue settings of a replaced universal player to its replacement.
1212
1213 Queue ids equal player ids, so the source entry is removed once it is carried over.
1214
1215 :param universal_id: Player id of the obsolete universal player.
1216 :param native_id: Player id of the native player that replaces it.
1217 :return: True if any queue setting was carried over.
1218 """
1219 queue_changed = False
1220 source_queue_raw = self.mass.config.get(f"{CONF_PLAYER_QUEUES}/{universal_id}")
1221 source_queue_raw = source_queue_raw if isinstance(source_queue_raw, dict) else None
1222 if source_queue_values := (source_queue_raw or {}).get("values"):
1223 target_queue_key = f"{CONF_PLAYER_QUEUES}/{native_id}"
1224 target_queue_raw = self.mass.config.get(target_queue_key)
1225 target_queue_raw = (
1226 deepcopy(target_queue_raw) if isinstance(target_queue_raw, dict) else {}
1227 )
1228 target_queue_values = target_queue_raw.setdefault("values", {})
1229 for key, value in source_queue_values.items():
1230 if key in target_queue_values:
1231 continue
1232 target_queue_values[key] = deepcopy(value)
1233 queue_changed = True
1234 if queue_changed:
1235 target_queue_raw["queue_id"] = native_id
1236 self.mass.config.set(target_queue_key, target_queue_raw)
1237 if source_queue_raw is not None:
1238 self.mass.config.remove(f"{CONF_PLAYER_QUEUES}/{universal_id}")
1239 return queue_changed
1240
1241 async def _reapply_player_config(self, player_id: str) -> None:
1242 """Reload the stored config onto a registered player and refresh its state."""
1243 if not (player := self.get_player(player_id)):
1244 return
1245 config = await self.mass.config.get_player_config(player_id)
1246 player.set_config(config)
1247 player.update_state()
1248 self.mass.signal_event(EventType.PLAYER_CONFIG_UPDATED, object_id=player_id, data=config)
1249
1250 def _update_group_memberships(self, old_player_id: str, new_player_id: str | None) -> None:
1251 """
1252 Hand a removed player's group memberships over to its successor, or drop them.
1253
1254 Other players that list the removed player as a group member (or allowed
1255 member) must follow its successor so those memberships are not silently
1256 lost. Without a successor the player is gone for good and its id is dropped
1257 from the group members instead, so it can not linger in a group and pull a
1258 device that returns under the same id back in. Its allow-list entry is left
1259 alone there, since an allow-list that runs empty stops restricting at all.
1260 Updates the persisted config and keeps any registered player whose
1261 membership changed in sync.
1262
1263 :param old_player_id: Player id that is being removed.
1264 :param new_player_id: Player id that replaces it, or None if there is none.
1265 """
1266 all_player_configs = self.mass.config.get(CONF_PLAYERS, {})
1267 if not isinstance(all_player_configs, dict):
1268 return
1269 for other_id, other_cfg in all_player_configs.items():
1270 if not isinstance(other_cfg, dict):
1271 continue
1272 other_values = other_cfg.get("values")
1273 if not isinstance(other_values, dict):
1274 continue
1275 other_player = self.get_player(other_id)
1276 changed = False
1277 for key in (CONF_GROUP_MEMBERS, CONF_ALLOWED_MEMBERS):
1278 members = other_values.get(key)
1279 if not isinstance(members, list) or old_player_id not in members:
1280 continue
1281 if new_player_id is None and key == CONF_ALLOWED_MEMBERS:
1282 # an allow-list that runs empty reads as "everyone may join", so the
1283 # entry of a removed player stays: it can never join again anyway
1284 continue
1285 new_members: list[str] = []
1286 for member_id in members:
1287 resolved = new_player_id if member_id == old_player_id else member_id
1288 if resolved is not None and resolved not in new_members:
1289 new_members.append(resolved)
1290 self.mass.config.set(f"{CONF_PLAYERS}/{other_id}/values/{key}", new_members)
1291 changed = True
1292 # keep a registered player's in-place config copy in sync
1293 if other_player and (entry := other_player.config.values.get(key)):
1294 entry.value = new_members
1295 if changed and other_player:
1296 self.mass.create_task(self._reload_group_members(other_player))
1297
1298 async def _reload_group_members(self, player: Player) -> None:
1299 """
1300 Let a group re-read its member config so its live member list follows along.
1301
1302 :param player: The group player whose stored member list changed.
1303 """
1304 await player.on_config_updated()
1305 player.refresh_state()
1306
1307 async def _stop_and_unregister(self, player: Player, replacement_player_id: str) -> None:
1308 """
1309 Stop active playback on a player and then permanently unregister it.
1310
1311 Used when an obsolete universal player is replaced or merged away: while
1312 it is not idle its protocol child keeps playing the dead queue's stream
1313 until the buffer drains, so playback is stopped first. Queue ownership is
1314 intentionally not transferred.
1315
1316 :param player: The obsolete player to stop and permanently remove.
1317 :param replacement_player_id: Player ID that takes the obsolete player's place.
1318 """
1319 if player.playback_state != PlaybackState.IDLE:
1320 with suppress(PlayerCommandFailed, PlayerUnavailableError):
1321 await self.mass.player_queues.stop(player.player_id)
1322 await self.unregister(
1323 player.player_id, permanent=True, replacement_player_id=replacement_player_id
1324 )
1325
1326 def _parent_has_active_protocol_from_domain(
1327 self, parent: Player, domain: str, exclude_player_id: str | None = None
1328 ) -> bool:
1329 """
1330 Check if a parent already has an active (registered) protocol player from a given domain.
1331
1332 This prevents a second protocol player of the same domain (e.g., a second AirPlay
1333 instance on the same host) from replacing the first one's link on the same parent.
1334
1335 :param parent: The parent player to check.
1336 :param domain: The protocol domain to check for (e.g., "airplay", "dlna").
1337 :param exclude_player_id: Optional player ID to exclude from the check
1338 (used when checking if a player's own domain is already linked).
1339 """
1340 for link in parent.linked_output_protocols:
1341 if link.protocol_domain != domain:
1342 continue
1343 if exclude_player_id and link.output_protocol_id == exclude_player_id:
1344 continue
1345 # A registered player from this domain blocks the link, even if unavailable.
1346 # Being offline doesn't make it a different device — it's still occupying
1347 # this domain slot. The provider should remove stale players explicitly.
1348 if self.get_player(link.output_protocol_id):
1349 return True
1350 return False
1351
1352 def _add_protocol_link(
1353 self, native_player: Player, protocol_player: Player, protocol_domain: str
1354 ) -> None:
1355 """Add a protocol link from native player to protocol player."""
1356 # Never link a player to itself (hides it as its own protocol child).
1357 if native_player.player_id == protocol_player.player_id:
1358 return
1359 # Guard: refuse to replace an existing active link from the same domain.
1360 # This prevents a second instance of the same protocol (e.g., two AirPlay
1361 # instances on the same host) from silently replacing the first one.
1362 if self._parent_has_active_protocol_from_domain(
1363 native_player, protocol_domain, exclude_player_id=protocol_player.player_id
1364 ):
1365 self.logger.debug(
1366 "Refusing to link %s to %s: parent already has an active %s link",
1367 protocol_player.player_id,
1368 native_player.player_id,
1369 protocol_domain,
1370 )
1371 return
1372
1373 # Remove any existing link for the same protocol domain
1374 updated_protocols = [
1375 link
1376 for link in native_player.linked_output_protocols
1377 if link.protocol_domain != protocol_domain
1378 ]
1379
1380 # Get priority for this protocol
1381 priority = PROTOCOL_PRIORITY.get(protocol_domain, 100)
1382
1383 # Derived transports (e.g. a Sendspin bridge riding on an AirPlay player)
1384 # reference the base output they run on top of; "native" when they ride
1385 # on the parent player itself
1386 derived_from = protocol_player.underlying_player_id
1387 if derived_from == native_player.player_id:
1388 derived_from = "native"
1389
1390 # Add the new link
1391 updated_protocols.append(
1392 LinkedOutputProtocol(
1393 output_protocol_id=protocol_player.player_id,
1394 protocol_domain=protocol_domain,
1395 priority=priority,
1396 derived_from=derived_from,
1397 )
1398 )
1399 native_player.set_linked_output_protocols(updated_protocols)
1400
1401 # Set protocol player's parent
1402 protocol_player.set_protocol_parent_id(native_player.player_id)
1403
1404 # Persist linked protocol IDs to config for fast restart
1405 # (only for non-universal players, as universal players handle this themselves)
1406 if native_player.provider.domain != "universal_player":
1407 self._save_linked_protocol_ids(native_player)
1408 # Always save the parent ID on the protocol player for reverse lookup on restart
1409 # (needed for both native and universal parents to enable fast restore)
1410 self._save_protocol_parent_id(protocol_player.player_id, native_player.player_id)
1411
1412 # The freshly linked player may have derived protocol players (e.g. a
1413 # Sendspin bridge riding on it) waiting to join the same parent.
1414 self._link_derived_protocols_of(protocol_player)
1415
1416 def _remove_protocol_link(
1417 self, native_player: Player, protocol_player_id: str, permanent: bool = False
1418 ) -> None:
1419 """
1420 Remove a protocol link.
1421
1422 :param native_player: The parent player to remove the link from.
1423 :param protocol_player_id: The protocol player ID to unlink.
1424 :param permanent: If True, also removes the protocol ID from the cached list.
1425 Use this when the protocol player config is being deleted. If False,
1426 the protocol ID remains in the cache so it can be shown as disabled
1427 and re-enabled later.
1428 """
1429 updated_protocols = [
1430 link
1431 for link in native_player.linked_output_protocols
1432 if link.output_protocol_id != protocol_player_id
1433 ]
1434 native_player.set_linked_output_protocols(updated_protocols)
1435
1436 # Clear parent reference on protocol player if it still exists
1437 if protocol_player := self.get_player(protocol_player_id):
1438 if protocol_player.protocol_parent_id == native_player.player_id:
1439 protocol_player.set_protocol_parent_id(None)
1440
1441 # Update persisted linked protocol IDs
1442 if native_player.provider.domain != "universal_player":
1443 if permanent:
1444 # Permanently remove from cache (player config is being deleted)
1445 self._remove_protocol_id_from_cache(native_player.player_id, protocol_player_id)
1446 # Note: we don't call _save_linked_protocol_ids here anymore for non-permanent
1447 # removals because the merge approach will preserve the ID in the cache
1448 # Always clear the cached parent ID (for both native and universal parents)
1449 self._clear_protocol_parent_id(protocol_player_id)
1450
1451 def _save_linked_protocol_ids(self, native_player: Player) -> None:
1452 """
1453 Save linked protocol IDs to config for persistence across restarts.
1454
1455 This method merges active protocol IDs with existing cached IDs to preserve
1456 disabled protocol players in the cache. This allows disabled protocols to be
1457 shown in the UI so they can be re-enabled.
1458 """
1459 conf_key = f"{CONF_PLAYERS}/{native_player.player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1460 # Get existing cached IDs to preserve disabled protocols
1461 existing_ids: list[str] = self.mass.config.get(conf_key, [])
1462 # Get currently active protocol IDs
1463 active_ids = {link.output_protocol_id for link in native_player.linked_output_protocols}
1464 # Merge: keep existing IDs and add any new active ones
1465 merged_ids = list(existing_ids)
1466 for protocol_id in active_ids:
1467 if protocol_id not in merged_ids:
1468 merged_ids.append(protocol_id)
1469 self.mass.config.set(conf_key, merged_ids)
1470
1471 def _get_cached_protocol_ids(self, player_id: str) -> list[str]:
1472 """Get cached linked protocol IDs from config."""
1473 conf_key = f"{CONF_PLAYERS}/{player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1474 result = self.mass.config.get(conf_key, [])
1475 return list(result) if result else []
1476
1477 def _remove_protocol_id_from_cache(
1478 self, parent_player_id: str, protocol_player_id: str
1479 ) -> None:
1480 """
1481 Permanently remove a protocol player ID from the cached linked protocol IDs.
1482
1483 Use this when a protocol player config is being deleted, not just disabled.
1484 """
1485 conf_key = f"{CONF_PLAYERS}/{parent_player_id}/values/{CONF_LINKED_PROTOCOL_IDS}"
1486 cached_ids: list[str] = self.mass.config.get(conf_key, [])
1487 if protocol_player_id in cached_ids:
1488 cached_ids.remove(protocol_player_id)
1489 self.mass.config.set(conf_key, cached_ids)
1490
1491 def _save_protocol_parent_id(self, protocol_player_id: str, parent_id: str) -> None:
1492 """Save the parent ID for a protocol player for persistence across restarts."""
1493 # Only save if the player config still exists to avoid creating partial entries
1494 if not self.mass.config.get(f"{CONF_PLAYERS}/{protocol_player_id}"):
1495 return
1496 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1497 self.mass.config.set(conf_key, parent_id)
1498
1499 def _save_underlying_player_id(self, player: Player) -> None:
1500 """
1501 Persist the derived-transport edge of a player to config.
1502
1503 Allows the edge to be resolved (e.g. by the config UI) even while the
1504 player is not registered. Clears a previously persisted edge when the
1505 player is no longer derived (e.g. a bridge client turned web player).
1506 """
1507 # Only save if the player config still exists to avoid creating partial entries
1508 if not self.mass.config.get(f"{CONF_PLAYERS}/{player.player_id}"):
1509 return
1510 conf_key = f"{CONF_PLAYERS}/{player.player_id}/values/{CONF_UNDERLYING_PLAYER_ID}"
1511 if player.underlying_player_id:
1512 self.mass.config.set(conf_key, player.underlying_player_id)
1513 elif self.mass.config.get(conf_key) is not None:
1514 self.mass.config.set(conf_key, None)
1515
1516 def _get_cached_protocol_parent_id(self, protocol_player_id: str) -> str | None:
1517 """Get cached parent ID for a protocol player from config."""
1518 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1519 result = self.mass.config.get(conf_key, None)
1520 return str(result) if result else None
1521
1522 def _clear_protocol_parent_id(self, protocol_player_id: str) -> None:
1523 """Clear the cached parent ID for a protocol player."""
1524 # Only clear if the player config still exists to avoid creating partial entries
1525 if not self.mass.config.get(f"{CONF_PLAYERS}/{protocol_player_id}"):
1526 return
1527 conf_key = f"{CONF_PLAYERS}/{protocol_player_id}/values/{CONF_PROTOCOL_PARENT_ID}"
1528 self.mass.config.set(conf_key, None)
1529
1530 def _recover_cached_protocol_links(self, native_player: Player) -> None:
1531 """
1532 Recover protocol links from config for disabled/missing protocols.
1533
1534 This ensures that disabled protocols show up in the output_protocols list
1535 so they can be re-enabled by the user. It also handles the case where
1536 protocol players haven't registered yet during startup.
1537 """
1538 # Get currently linked protocol IDs
1539 linked_protocol_ids = {
1540 link.output_protocol_id for link in native_player.linked_output_protocols
1541 }
1542
1543 # Get cached protocol IDs from config (includes protocols that were explicitly linked)
1544 cached_protocol_ids = self._get_cached_protocol_ids(native_player.player_id)
1545
1546 # Also check all protocol players that have protocol_parent_id pointing to this player
1547 # (this handles disabled protocols that may not be in linked_protocol_ids)
1548 all_player_configs = self.mass.config.get(CONF_PLAYERS, {})
1549 for protocol_id, protocol_config in all_player_configs.items():
1550 # Skip if not a protocol player
1551 if protocol_config.get("player_type") != "protocol":
1552 continue
1553 # Check if this protocol has a parent_id pointing to this native player
1554 protocol_values = protocol_config.get("values", {})
1555 protocol_parent_id = protocol_values.get(CONF_PROTOCOL_PARENT_ID)
1556 if protocol_parent_id == native_player.player_id:
1557 if protocol_id not in cached_protocol_ids:
1558 cached_protocol_ids.append(protocol_id)
1559
1560 if not cached_protocol_ids:
1561 return
1562
1563 # Add link entries for any cached protocols that aren't currently linked
1564 updated_protocols = list(native_player.linked_output_protocols)
1565 for protocol_id in cached_protocol_ids:
1566 if protocol_id in linked_protocol_ids:
1567 continue # Already linked
1568
1569 # Get protocol player config to determine the protocol domain
1570 protocol_config = self.mass.config.get(f"{CONF_PLAYERS}/{protocol_id}")
1571 if not protocol_config:
1572 continue
1573
1574 # Determine protocol domain from provider
1575 protocol_provider: str = protocol_config.get("provider")
1576 if not protocol_provider:
1577 continue
1578
1579 # Extract domain from provider instance_id (e.g., "airplay--uuid" -> "airplay")
1580 protocol_domain = protocol_provider.split("--", maxsplit=1)[0]
1581
1582 # Skip if parent already has a link from this domain
1583 existing_domains = {link.protocol_domain for link in updated_protocols}
1584 if protocol_domain in existing_domains:
1585 continue
1586
1587 # Get priority for this protocol
1588 priority = PROTOCOL_PRIORITY.get(protocol_domain, 100)
1589
1590 # Resolve the derived-transport edge from the live player when
1591 # registered, else from the persisted edge in config
1592 protocol_player = self.get_player(protocol_id)
1593 derived_from = (
1594 protocol_player.underlying_player_id
1595 if protocol_player
1596 else protocol_config.get("values", {}).get(CONF_UNDERLYING_PLAYER_ID)
1597 )
1598 if derived_from == native_player.player_id:
1599 derived_from = "native"
1600
1601 updated_protocols.append(
1602 LinkedOutputProtocol(
1603 output_protocol_id=protocol_id,
1604 protocol_domain=protocol_domain,
1605 priority=priority,
1606 derived_from=derived_from,
1607 )
1608 )
1609 self.logger.debug(
1610 "Recovered cached protocol link %s -> %s",
1611 native_player.player_id,
1612 protocol_id,
1613 )
1614
1615 if len(updated_protocols) != len(native_player.linked_output_protocols):
1616 native_player.set_linked_output_protocols(updated_protocols)
1617
1618 def _cleanup_protocol_links(self, player: Player) -> None:
1619 """Clean up protocol links when a player is permanently removed."""
1620 if player.state.type == PlayerType.PROTOCOL:
1621 self._unlink_from_protocol_parent(player)
1622 return
1623 self._detach_owned_protocols(player)
1624
1625 def _unlink_from_protocol_parent(self, player: Player) -> None:
1626 """Release a protocol player from the parent it is attached to."""
1627 if parent_id := player.protocol_parent_id:
1628 if parent_player := self.get_player(parent_id):
1629 # Use permanent=True to also remove from cached protocol IDs
1630 self._remove_protocol_link(parent_player, player.player_id, permanent=True)
1631 if (
1632 parent_player.provider.domain == "universal_player"
1633 and len(parent_player.linked_output_protocols) == 0
1634 ):
1635 # No protocols left - the universal player has nothing to play
1636 # on. Its config is deliberately kept: the player id is opaque
1637 # and cannot be recreated, so deleting it here would orphan the
1638 # entities API consumers bound to it. Only an explicit removal
1639 # by the user deletes a universal player for good.
1640 self.logger.info(
1641 "Universal player %s has no protocols left",
1642 parent_id,
1643 )
1644 self.mass.create_task(self.mass.players.unregister(parent_id, permanent=False))
1645 else:
1646 parent_player.refresh_state()
1647 else:
1648 # Parent not registered yet — still purge the cached id
1649 self._remove_protocol_id_from_cache(parent_id, player.player_id)
1650
1651 def _detach_owned_protocols(self, player: Player) -> None:
1652 """Detach the protocol players a parent owns so they can find a new parent."""
1653 # collect the ids from both the active links and the cached state, since
1654 # disabled/inactive protocols may only exist in the cached parent data
1655 all_protocol_ids = set(self._get_known_protocol_ids(player))
1656 for protocol_id in all_protocol_ids:
1657 if protocol_player := self.get_player(protocol_id):
1658 # Protocol player is available: clear parent and schedule re-evaluation
1659 # so it can be matched to a new parent or a new universal player
1660 self.logger.debug(
1661 "Player %s no longer owns protocol %s - scheduling evaluation",
1662 player.player_id,
1663 protocol_id,
1664 )
1665 self._detach_protocol_child(protocol_player)
1666 else:
1667 # Clear cached parent ID in config so protocol won't try to
1668 # restore a link to its former parent on next restart
1669 self._clear_protocol_parent_id(protocol_id)
1670 # Protocol player is not registered yet — it may still be
1671 # mid-discovery (e.g., DLNA connecting via SSDP). Don't delete
1672 # its config as that would cause a KeyError when it finishes
1673 # registering. Stale configs are harmless and get cleaned up
1674 # naturally on subsequent restarts.
1675 self.logger.debug(
1676 "Player %s no longer owns protocol %s - not registered, skipping cleanup",
1677 player.player_id,
1678 protocol_id,
1679 )
1680
1681 def _cleanup_player_type_transition(self, existing: Player, *, becomes_protocol: bool) -> None:
1682 """
1683 Release the protocol topology a player owned before its type changed.
1684
1685 :param existing: The registered player instance for the changed player.
1686 :param becomes_protocol: True if the player moves into the protocol role,
1687 False if it leaves it.
1688 """
1689 if not becomes_protocol:
1690 # a provider may announce the new type with the live parent link already
1691 # dropped, so fall back to the persisted one to still reach the parent
1692 parent_id = existing.protocol_parent_id or self._get_cached_protocol_parent_id(
1693 existing.player_id
1694 )
1695 if not parent_id:
1696 return
1697 parent = self.get_player(parent_id)
1698 if parent is not None and parent.provider.domain == "universal_player":
1699 # drop only the active edge and leave the rest to the link evaluation,
1700 # which replaces the wrapper with this player: a leftover edge makes it
1701 # hand the player over to itself, which it refuses, abandoning the swap
1702 self._remove_protocol_link(parent, existing.player_id)
1703 return
1704 existing.set_protocol_parent_id(parent_id)
1705 # unlink at the parent and drop the persisted parent id, which would
1706 # otherwise heal the player's type back to protocol
1707 self._unlink_from_protocol_parent(existing)
1708 # a player leaving the protocol role has no parent, also when that parent
1709 # is not registered (anymore) and only the cached link could be cleaned up
1710 existing.set_protocol_parent_id(None)
1711 return
1712 # the player becomes a child itself: detach the protocol players it owned so they
1713 # can find a new parent, then give up their ownership in its (kept) config - the
1714 # reverse of the removal path, which drops the ownership before the detach
1715 protocol_ids = set(self._get_known_protocol_ids(existing))
1716 self._detach_owned_protocols(existing)
1717 self._remove_protocol_ids_from_parent(existing, protocol_ids)
1718
1719 def _detach_protocol_children(self, parent_id: str) -> None:
1720 """
1721 Detach the registered protocol players of a parent player that is going away.
1722
1723 Covers the removal paths that don't unregister the parent first (e.g. its
1724 provider is unloaded), where the parent is not around anymore to enumerate
1725 its protocol players.
1726
1727 :param parent_id: Player id of the parent that is being removed.
1728 """
1729 for protocol_player in list(self._players.values()):
1730 if protocol_player.state.type != PlayerType.PROTOCOL:
1731 continue
1732 # a protocol player waiting for a parent that never registered only has
1733 # the link in its config, so fall back to the cached parent
1734 linked_parent_id = protocol_player.protocol_parent_id or (
1735 self._get_cached_protocol_parent_id(protocol_player.player_id)
1736 )
1737 if linked_parent_id != parent_id:
1738 continue
1739 self.logger.debug(
1740 "Player %s removed - scheduling evaluation for protocol %s",
1741 parent_id,
1742 protocol_player.player_id,
1743 )
1744 self._detach_protocol_child(protocol_player)
1745
1746 def _detach_protocol_child(self, protocol_player: Player) -> None:
1747 """Clear a protocol player's parent link and schedule a fresh evaluation."""
1748 self._clear_protocol_parent_id(protocol_player.player_id)
1749 protocol_player.set_protocol_parent_id(None)
1750 protocol_player.refresh_state()
1751 self._schedule_protocol_evaluation(protocol_player)
1752
1753 def _identifiers_match(
1754 self, player_a: Player, player_b: Player, protocol_domain: str = ""
1755 ) -> bool:
1756 """
1757 Check if identifiers match between two players.
1758
1759 Matching is done by comparing connection identifiers (MAC, serial, UUID).
1760 As a last resort, IP address is used when at least one player has a
1761 locally-administered MAC, indicating the device uses MAC randomization
1762 and ARP could not resolve the real hardware address.
1763
1764 Invalid identifiers (e.g., 00:00:00:00:00:00 MAC addresses) are filtered out
1765 to prevent false matches between unrelated devices.
1766 """
1767 identifiers_a = player_a.device_info.identifiers
1768 identifiers_b = player_b.device_info.identifiers
1769
1770 # Check identifiers in order of reliability
1771 # MAC_ADDRESS > SERIAL_NUMBER > UUID > CAST_UUID > AIRPLAY_ID
1772 for conn_type in (
1773 IdentifierType.MAC_ADDRESS,
1774 IdentifierType.SERIAL_NUMBER,
1775 IdentifierType.UUID,
1776 IdentifierType.CAST_UUID,
1777 IdentifierType.AIRPLAY_ID,
1778 ):
1779 val_a = identifiers_a.get(conn_type)
1780 val_b = identifiers_b.get(conn_type)
1781
1782 if not val_a or not val_b:
1783 continue
1784
1785 # Filter out invalid MAC addresses (00:00:00:00:00:00, ff:ff:ff:ff:ff:ff)
1786 if conn_type == IdentifierType.MAC_ADDRESS:
1787 if not is_valid_mac_address(val_a) or not is_valid_mac_address(val_b):
1788 self.logger.log(
1789 VERBOSE_LOG_LEVEL,
1790 "Skipping invalid MAC address for matching: %s=%s, %s=%s",
1791 player_a.display_name,
1792 val_a,
1793 player_b.display_name,
1794 val_b,
1795 )
1796 continue
1797
1798 # Normalize values for comparison
1799 if conn_type == IdentifierType.MAC_ADDRESS:
1800 # Use MAC normalization that handles locally-administered bit differences
1801 # Some protocols (like AirPlay) report a locally-administered MAC variant
1802 # where bit 1 of the first octet is set (e.g., 54:78:... vs 56:78:...)
1803 val_a_norm = normalize_mac_for_matching(val_a)
1804 val_b_norm = normalize_mac_for_matching(val_b)
1805
1806 # Direct match on current MAC
1807 if val_a_norm == val_b_norm:
1808 return True
1809
1810 # Multi-MAC matching: also check original reported MACs.
1811 # Devices with multiple interfaces (WiFi + Ethernet) may have ARP
1812 # resolve one MAC while the protocol reports a different one.
1813 macs_a = {val_a_norm}
1814 macs_b = {val_b_norm}
1815 reported_a = player_a.extra_data.get("reported_mac")
1816 reported_b = player_b.extra_data.get("reported_mac")
1817 if reported_a and is_valid_mac_address(reported_a):
1818 macs_a.add(normalize_mac_for_matching(reported_a))
1819 if reported_b and is_valid_mac_address(reported_b):
1820 macs_b.add(normalize_mac_for_matching(reported_b))
1821 if macs_a & macs_b:
1822 return True
1823
1824 # No MAC match - continue to next identifier type
1825 continue
1826
1827 val_a_norm = val_a.lower().replace(":", "").replace("-", "")
1828 val_b_norm = val_b.lower().replace(":", "").replace("-", "")
1829
1830 # Direct match
1831 if val_a_norm == val_b_norm:
1832 return True
1833
1834 # Special case: Sonos UUID matching with DLNA _MR suffix
1835 # Sonos uses RINCON_xxx, DLNA uses RINCON_xxx_MR for Media Renderer
1836 if conn_type == IdentifierType.UUID:
1837 if val_b_norm.endswith("_mr") and val_b_norm[:-3] == val_a_norm:
1838 return True
1839 if val_a_norm.endswith("_mr") and val_a_norm[:-3] == val_b_norm:
1840 return True
1841
1842 # Last resort: IP-based matching.
1843 # Two players on the same IP are very likely the same physical device.
1844 # This handles two cases:
1845 # 1. MAC randomization: at least one player has no real MAC (LA or missing),
1846 # so ARP couldn't resolve a usable address.
1847 # 2. Different MACs per protocol: some devices (e.g., Yamaha MusicCast) report
1848 # different valid globally-unique MACs per protocol (DLNA vs AirPlay differ
1849 # by 1 in the last octet). IP matching is safe here because two different
1850 # devices on a LAN cannot share the same IP simultaneously.
1851 # To avoid false positives between unrelated native players, this path
1852 # requires at least one player to be a protocol or universal player.
1853 ip_a = identifiers_a.get(IdentifierType.IP_ADDRESS)
1854 ip_b = identifiers_b.get(IdentifierType.IP_ADDRESS)
1855 if ip_a and ip_b and ip_a == ip_b:
1856 mac_a = identifiers_a.get(IdentifierType.MAC_ADDRESS)
1857 mac_b = identifiers_b.get(IdentifierType.MAC_ADDRESS)
1858 a_is_real = (
1859 mac_a is not None
1860 and is_valid_mac_address(mac_a)
1861 and not is_locally_administered_mac(mac_a)
1862 )
1863 b_is_real = (
1864 mac_b is not None
1865 and is_valid_mac_address(mac_b)
1866 and not is_locally_administered_mac(mac_b)
1867 )
1868 # Case 1: at least one player has no real hardware MAC
1869 if not (a_is_real and b_is_real):
1870 return True
1871 # Case 2: both have real MACs but at least one is a protocol/universal player
1872 a_is_protocol = (
1873 player_a.type == PlayerType.PROTOCOL
1874 or player_a.provider.domain == "universal_player"
1875 )
1876 b_is_protocol = (
1877 player_b.type == PlayerType.PROTOCOL
1878 or player_b.provider.domain == "universal_player"
1879 )
1880 if a_is_protocol or b_is_protocol:
1881 return True
1882
1883 return False
1884
1885 def _select_best_output_protocol(self, player: Player) -> tuple[Player, OutputProtocol | None]:
1886 """
1887 Select the best available output protocol for a player.
1888
1889 Selection priority:
1890 1. Output protocol that is currently grouped/synced with other players.
1891 2. User's preferred output protocol (from player settings).
1892 3. Native playback (if player supports PLAY_MEDIA).
1893 4. The player's declared default output protocol domain, if available.
1894 5. Best available protocol by priority.
1895
1896 Returns tuple of (target_player, output_protocol).
1897 output_protocol is None when using native playback.
1898 """
1899 self.logger.log(
1900 VERBOSE_LOG_LEVEL,
1901 "Selecting output protocol for %s",
1902 player.state.name,
1903 )
1904
1905 # 1. Check if any output protocol is currently grouped
1906 for linked in player.linked_output_protocols:
1907 if protocol_player := self.get_player(linked.output_protocol_id):
1908 if protocol_player.available_for_playback and self._is_protocol_grouped(
1909 protocol_player
1910 ):
1911 self.logger.log(
1912 VERBOSE_LOG_LEVEL,
1913 "Selected protocol for %s: %s (grouped)",
1914 player.state.name,
1915 protocol_player.state.name,
1916 )
1917 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1918
1919 # 2. Check for user's preferred output protocol.
1920 # The value is only stored while it differs from the entry's default: "native" when a
1921 # native output is available, otherwise "auto". A player without a native output (e.g. a
1922 # LinkPlay shell) therefore has no stored preference by default and gets its default
1923 # output domain applied in step 4.
1924 preferred = self.mass.config.get_raw_player_config_value(
1925 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
1926 )
1927 if preferred and preferred != "auto":
1928 if preferred == "native":
1929 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1930 self.logger.log(
1931 VERBOSE_LOG_LEVEL,
1932 "Selected protocol for %s: native (user preference)",
1933 player.state.name,
1934 )
1935 return player, None
1936 else:
1937 for linked in player.linked_output_protocols:
1938 if linked.output_protocol_id == preferred:
1939 if protocol_player := self.get_player(linked.output_protocol_id):
1940 if protocol_player.available_for_playback:
1941 self.logger.log(
1942 VERBOSE_LOG_LEVEL,
1943 "Selected protocol for %s: %s (user preference)",
1944 player.state.name,
1945 protocol_player.state.name,
1946 )
1947 return protocol_player, player.get_linked_protocol(
1948 linked.output_protocol_id
1949 )
1950 break
1951
1952 # 3. Use native playback if available
1953 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1954 self.logger.log(
1955 VERBOSE_LOG_LEVEL, "Selected protocol for %s: native", player.state.name
1956 )
1957 return player, None
1958
1959 # 4. Use the player's preferred default protocol domain, if it declares one and a
1960 # matching linked protocol is available (e.g. a LinkPlay shell prefers DLNA). This
1961 # never influences grouping; it only steers the default output for playback. "Auto"
1962 # is the entry default here, so it consistently resolves to this domain default.
1963 if default_domain := player.default_output_protocol_domain:
1964 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1965 if linked.protocol_domain != default_domain:
1966 continue
1967 if (protocol_player := self.get_player(linked.output_protocol_id)) and (
1968 protocol_player.available_for_playback
1969 ):
1970 self.logger.log(
1971 VERBOSE_LOG_LEVEL,
1972 "Selected protocol for %s: %s (default domain %s)",
1973 player.state.name,
1974 protocol_player.state.name,
1975 default_domain,
1976 )
1977 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1978
1979 # 5. Fall back to best protocol by priority
1980 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1981 if protocol_player := self.get_player(linked.output_protocol_id):
1982 if protocol_player.available_for_playback:
1983 self.logger.log(
1984 VERBOSE_LOG_LEVEL,
1985 "Selected protocol for %s: %s (priority-based)",
1986 player.state.name,
1987 protocol_player.state.name,
1988 )
1989 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1990
1991 raise PlayerCommandFailed(f"Player {player.state.name} has no available output protocols")
1992
1993 def _get_control_target(
1994 self,
1995 player: Player,
1996 required_feature: PlayerFeature,
1997 require_active: bool = False,
1998 ) -> Player | None:
1999 """
2000 Get the best player(protocol) to send audio-path commands to.
2001
2002 Resolves commands that travel with the audio (enqueue, pause, announcements),
2003 so the output that renders the audio outranks the native player. Volume and
2004 mute are control-plane instead and resolve through
2005 :meth:`Player._get_protocol_player_for_feature`, which orders differently.
2006
2007 :param player: The player the command was issued on.
2008 :param required_feature: The feature the resolved target has to support.
2009 :param require_active: Only accept the output that is already rendering,
2010 instead of falling back to an idle one.
2011 """
2012 # If we have an active protocol, use that
2013 if (
2014 player.active_output_protocol
2015 and player.active_output_protocol != "native"
2016 and (protocol_player := self.mass.players.get_player(player.active_output_protocol))
2017 and required_feature in protocol_player.supported_features
2018 ):
2019 return protocol_player
2020
2021 # if the player natively supports the required feature, use that
2022 if (
2023 player.active_output_protocol == "native"
2024 and required_feature in player.supported_features
2025 ):
2026 return player
2027
2028 # If require_active is set, and no active protocol found, return None
2029 if require_active:
2030 return None
2031
2032 # if the player natively supports the required feature, use that
2033 if required_feature in player.supported_features:
2034 return player
2035
2036 # An output the user explicitly picked owns the audio, so a command that has to
2037 # start playback on an idle player follows it rather than the priority below.
2038 # The stored value survives a relink, so it only counts while it still names one
2039 # of this player's own outputs.
2040 preferred = self.mass.config.get_raw_player_config_value(
2041 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2042 )
2043 if preferred and preferred not in ("auto", "native"):
2044 for linked in player.linked_output_protocols:
2045 if linked.output_protocol_id != preferred:
2046 continue
2047 if (
2048 (preferred_player := self.mass.players.get_player(str(preferred)))
2049 and preferred_player.available_for_playback
2050 and required_feature in preferred_player.supported_features
2051 ):
2052 return preferred_player
2053 break
2054
2055 # Otherwise, use the best available linked protocol, ordered by the same
2056 # priority that regular playback selection applies.
2057 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
2058 if (
2059 (protocol_player := self.mass.players.get_player(linked.output_protocol_id))
2060 and protocol_player.available_for_playback
2061 and required_feature in protocol_player.supported_features
2062 ):
2063 return protocol_player
2064
2065 return None
2066
2067 def _is_protocol_grouped(self, protocol_player: Player) -> bool:
2068 """
2069 Check if a protocol player is currently grouped/synced with other players.
2070
2071 Used to prefer protocols that are actively participating in a group,
2072 ensuring consistent playback across grouped players.
2073 """
2074 is_grouped = bool(
2075 protocol_player.state.synced_to
2076 or (
2077 protocol_player.state.group_members and len(protocol_player.state.group_members) > 1
2078 )
2079 or protocol_player.state.active_group
2080 )
2081 if is_grouped:
2082 self.logger.log(
2083 VERBOSE_LOG_LEVEL,
2084 "Protocol player %s is grouped",
2085 protocol_player.state.name,
2086 )
2087 return is_grouped
2088
2089 def _translate_members_to_remove_for_protocols(
2090 self,
2091 parent_player: Player,
2092 player_ids: list[str],
2093 parent_protocol_player: Player | None,
2094 parent_protocol_domain: str | None,
2095 ) -> tuple[list[str], list[str]]:
2096 """
2097 Translate member IDs to remove into protocol and native lists.
2098
2099 :param parent_player: The parent player to remove members from.
2100 :param player_ids: List of visible player IDs to remove.
2101 :param parent_protocol_player: The parent's protocol player if available.
2102 :param parent_protocol_domain: The parent's protocol domain if available.
2103 """
2104 self.logger.debug(
2105 "Translating members to remove for %s: player_ids=%s, parent_protocol_domain=%s",
2106 parent_player.state.name,
2107 player_ids,
2108 parent_protocol_domain,
2109 )
2110 protocol_members: list[str] = []
2111 native_members: list[str] = []
2112
2113 for child_player_id in player_ids:
2114 child_player = self.get_player(child_player_id)
2115 if not child_player:
2116 continue
2117
2118 # Check if this member is in the parent's group via protocol
2119 if parent_protocol_domain and parent_protocol_player:
2120 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2121 if child_protocol and child_protocol.available:
2122 # For native protocol players, use the child's player_id directly
2123 child_protocol_id = (
2124 child_player.player_id
2125 if child_protocol.is_native
2126 else child_protocol.output_protocol_id
2127 )
2128 if child_protocol_id in parent_protocol_player.group_members:
2129 self.logger.debug(
2130 "Translating removal: %s -> protocol %s",
2131 child_player_id,
2132 child_protocol_id,
2133 )
2134 protocol_members.append(child_protocol_id)
2135 continue
2136
2137 # Check if child's protocol player is in parent's native group_members
2138 # This handles native protocol players (e.g., native AirPlay player like Apple TV)
2139 # where the parent itself contains protocol player IDs in its group_members
2140 translated = False
2141 for linked in child_player.linked_output_protocols:
2142 if linked.output_protocol_id in parent_player.group_members:
2143 self.logger.debug(
2144 "Translating removal (native parent): %s -> protocol %s",
2145 child_player_id,
2146 linked.output_protocol_id,
2147 )
2148 native_members.append(linked.output_protocol_id)
2149 translated = True
2150 break
2151
2152 if not translated:
2153 native_members.append(child_player_id)
2154
2155 return protocol_members, native_members
2156
2157 def _filter_protocol_members(self, member_ids: list[str], protocol_player: Player) -> list[str]:
2158 """Filter member IDs to only include players from the same protocol domain."""
2159 return [
2160 pid
2161 for pid in member_ids
2162 if (p := self.get_player(pid)) and p.provider.domain == protocol_player.provider.domain
2163 ]
2164
2165 def _filter_native_members(self, member_ids: list[str], parent_player: Player) -> list[str]:
2166 """Filter member IDs to only include players compatible with the parent."""
2167 return [
2168 pid
2169 for pid in member_ids
2170 if (p := self.get_player(pid))
2171 and (
2172 p.provider.instance_id == parent_player.provider.instance_id
2173 or pid in parent_player._attr_can_group_with
2174 or p.provider.instance_id in parent_player._attr_can_group_with
2175 )
2176 ]
2177
2178 def _try_child_preferred_protocol(
2179 self,
2180 child_player: Player,
2181 parent_player: Player,
2182 ) -> tuple[str | None, str | None]:
2183 """
2184 Try to use child's preferred output protocol for grouping.
2185
2186 Returns tuple of (child_protocol_id, protocol_domain) or (None, None).
2187 """
2188 child_preferred = self.mass.config.get_raw_player_config_value(
2189 child_player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2190 )
2191 if not child_preferred or child_preferred in {"auto", "native"}:
2192 return None, None
2193
2194 # Find child's preferred protocol, with its current availability
2195 child_protocol = None
2196 for output_protocol in child_player.output_protocols:
2197 if output_protocol.output_protocol_id == child_preferred:
2198 child_protocol = output_protocol
2199 break
2200
2201 if not child_protocol or not child_protocol.available:
2202 return None, None
2203
2204 # Check if parent supports this protocol (including native protocol)
2205 parent_protocol = parent_player.get_output_protocol_by_domain(
2206 child_protocol.protocol_domain
2207 )
2208 if not parent_protocol or not parent_protocol.available:
2209 return None, None
2210
2211 # Check if this protocol supports set_members
2212 protocol_player = parent_player.get_protocol_player(parent_protocol.output_protocol_id)
2213 if (
2214 not protocol_player
2215 or PlayerFeature.SET_MEMBERS not in protocol_player.state.supported_features
2216 ):
2217 return None, None
2218
2219 return child_protocol.output_protocol_id, child_protocol.protocol_domain
2220
2221 def _can_use_native_grouping(
2222 self,
2223 child_player: Player,
2224 parent_player: Player,
2225 parent_supports_native: bool,
2226 ) -> bool:
2227 """Check if child can be grouped with parent using native grouping."""
2228 if not parent_supports_native:
2229 return False
2230 return (
2231 parent_player.is_native_group_compatible(child_player)
2232 or child_player.player_id in parent_player._attr_can_group_with
2233 or child_player.provider.instance_id in parent_player._attr_can_group_with
2234 )
2235
2236 def _try_find_common_protocol(
2237 self, child_player: Player, parent_player: Player
2238 ) -> tuple[OutputProtocol | None, OutputProtocol | None]:
2239 """
2240 Find common protocol that supports set_members.
2241
2242 Returns tuple of (parent_protocol, child_protocol) or (None, None).
2243 """
2244 for parent_output_protocol in parent_player.output_protocols:
2245 if not parent_output_protocol.available:
2246 continue
2247 child_protocol = child_player.get_output_protocol_by_domain(
2248 parent_output_protocol.protocol_domain
2249 )
2250 if not child_protocol or not child_protocol.available:
2251 continue
2252 protocol_player = parent_player.get_protocol_player(
2253 parent_output_protocol.output_protocol_id
2254 )
2255 if protocol_player and PlayerFeature.SET_MEMBERS in protocol_player.supported_features:
2256 return parent_output_protocol, child_protocol
2257 return None, None
2258
2259 def _parent_has_live_native_session(self, parent_player: Player) -> bool:
2260 """
2261 Return True when the parent currently holds a live native playback session.
2262
2263 The active output protocol lingers for a few seconds after stop, so a non-idle
2264 playback state is required to distinguish a real session from a just-stopped one.
2265 """
2266 return parent_player.active_output_protocol == "native" and (
2267 parent_player.state.playback_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
2268 )
2269
2270 def _order_members_for_native_join(
2271 self,
2272 player_ids: list[str],
2273 parent_player: Player,
2274 parent_supports_native_grouping: bool,
2275 ) -> list[str]:
2276 """
2277 Order members so a live native session can be joined without splitting the group.
2278
2279 When the parent already holds a live native session, children that cannot group
2280 natively are evaluated first: they may force a shared protocol for the whole group,
2281 and processing them before the native-capable children lets those join that same
2282 protocol instead of being stranded in a separate native sub-group. The order is left
2283 untouched when the parent is not playing natively, so fresh-group selection is unchanged.
2284
2285 :param player_ids: The member IDs to be added, in their original order.
2286 :param parent_player: The parent player being joined.
2287 :param parent_supports_native_grouping: Whether the parent can group natively.
2288 """
2289 if not self._parent_has_live_native_session(parent_player):
2290 return player_ids
2291 return sorted(
2292 player_ids,
2293 key=lambda pid: bool(
2294 (child := self.get_player(pid))
2295 and self._can_use_native_grouping(
2296 child, parent_player, parent_supports_native_grouping
2297 )
2298 ),
2299 )
2300
2301 def _try_join_active_native_session(
2302 self,
2303 child_player: Player,
2304 parent_player: Player,
2305 parent_protocol_domain: str | None,
2306 parent_supports_native_grouping: bool,
2307 native_members: list[str],
2308 ) -> bool:
2309 """
2310 Add the child to native_members if it can join the parent's active native session.
2311
2312 A child's preferred output protocol must only steer protocol selection when the child
2313 initiates its own playback; when it joins a parent that is already playing natively it
2314 should adopt native grouping if compatible, rather than forcing the whole group onto
2315 the child's preferred protocol. Skipped once a protocol has been selected for the group,
2316 so mixed batches stay cohesive on a single protocol.
2317
2318 :param child_player: The player being added to the group.
2319 :param parent_player: The parent player being joined.
2320 :param parent_protocol_domain: The protocol domain already selected for the group, if any.
2321 :param parent_supports_native_grouping: Whether the parent can group natively.
2322 :param native_members: The native members list to append to when the child joins.
2323 """
2324 if not (
2325 self._parent_has_live_native_session(parent_player)
2326 and not parent_protocol_domain
2327 and self._can_use_native_grouping(
2328 child_player, parent_player, parent_supports_native_grouping
2329 )
2330 ):
2331 return False
2332 native_members.append(child_player.player_id)
2333 self.logger.log(
2334 VERBOSE_LOG_LEVEL,
2335 "Joining parent's active native session for %s",
2336 child_player.state.name,
2337 )
2338 return True
2339
2340 def _translate_native_members_to_protocol(
2341 self, parent_player: Player, protocol_domain: str, member_ids: list[str]
2342 ) -> list[str]:
2343 """
2344 Translate natively grouped members onto the protocol domain the parent plays through.
2345
2346 Members that do not have that protocol cannot follow the parent at all and are
2347 dropped with a warning instead.
2348
2349 :param parent_player: The parent player the members are grouped with.
2350 :param protocol_domain: The protocol domain selected for the group.
2351 :param member_ids: The member IDs that were selected for native grouping.
2352 """
2353 translated: list[str] = []
2354 for member_id in member_ids:
2355 member_player = self.get_player(member_id)
2356 if not member_player:
2357 continue
2358 # a native group's members may be listed by their protocol player id
2359 if member_player.protocol_parent_id:
2360 member_player = self.get_player(member_player.protocol_parent_id) or member_player
2361 member_protocol = member_player.get_output_protocol_by_domain(protocol_domain)
2362 if not member_protocol or not member_protocol.available:
2363 self.logger.warning(
2364 "Cannot group %s with %s: the group plays through the %s protocol, "
2365 "which %s does not support",
2366 member_player.state.name,
2367 parent_player.state.name,
2368 protocol_domain,
2369 member_player.state.name,
2370 )
2371 continue
2372 # For native protocol players, use the member's player_id directly
2373 translated.append(
2374 member_player.player_id
2375 if member_protocol.is_native
2376 else member_protocol.output_protocol_id
2377 )
2378 self.logger.log(
2379 VERBOSE_LOG_LEVEL,
2380 "Moving %s from native grouping to the %s protocol",
2381 member_player.state.name,
2382 protocol_domain,
2383 )
2384 return translated
2385
2386 def _move_native_members_to_group_protocol(
2387 self,
2388 parent_player: Player,
2389 parent_protocol_player: Player | None,
2390 parent_protocol_domain: str | None,
2391 protocol_members: list[str],
2392 native_members: list[str],
2393 ) -> None:
2394 """
2395 Move the members selected for native grouping onto the protocol the group ended up on.
2396
2397 Does nothing unless the group ends up on one of the parent's protocols while the
2398 parent's native grouping needs the parent's own stream: only then do those members
2399 have no session left to attach to.
2400
2401 :param parent_player: The parent player being joined.
2402 :param parent_protocol_player: The protocol player selected for the group, if any.
2403 :param parent_protocol_domain: The protocol domain selected for the group, if any.
2404 :param protocol_members: The protocol member list the translated IDs are added to.
2405 :param native_members: The native member IDs, emptied when they are moved over.
2406 """
2407 if not (
2408 native_members
2409 and parent_protocol_domain
2410 and parent_protocol_player
2411 and parent_protocol_player.player_id != parent_player.player_id
2412 and parent_player.native_grouping_requires_own_stream
2413 ):
2414 return
2415 protocol_members.extend(
2416 self._translate_native_members_to_protocol(
2417 parent_player, parent_protocol_domain, native_members
2418 )
2419 )
2420 native_members.clear()
2421
2422 def _migrate_stranded_native_members(
2423 self,
2424 parent_player: Player,
2425 parent_protocol_player: Player,
2426 protocol_members: list[str],
2427 ) -> list[str]:
2428 """
2429 Move the native members that a switch to the given protocol strands onto that protocol.
2430
2431 Returns the member IDs that are still attached to the parent's own stream, so the
2432 caller can release them from it. Empty unless the parent renders that stream itself
2433 while its native grouping attaches the members to exactly that stream: only then are
2434 they left without anything to play.
2435
2436 :param parent_player: The parent player that is about to switch protocol.
2437 :param parent_protocol_player: The protocol player the parent will render through.
2438 :param protocol_members: The protocol member list the translated IDs are added to.
2439 """
2440 if parent_protocol_player.player_id == parent_player.player_id:
2441 return []
2442 if not parent_player.native_grouping_requires_own_stream:
2443 return []
2444 if parent_player.active_output_protocol not in (None, "native"):
2445 return []
2446 if parent_player.state.playback_state not in (PlaybackState.PLAYING, PlaybackState.PAUSED):
2447 return []
2448 stranded = [
2449 member_id
2450 for member_id in parent_player.group_members
2451 if member_id != parent_player.player_id
2452 ]
2453 for protocol_id in self._translate_native_members_to_protocol(
2454 parent_player, parent_protocol_player.provider.domain, stranded
2455 ):
2456 if protocol_id not in protocol_members:
2457 protocol_members.append(protocol_id)
2458 return stranded
2459
2460 async def _stop_native_session(
2461 self,
2462 parent_player: Player,
2463 parent_protocol_player: Player,
2464 stranded_native_members: list[str],
2465 ) -> None:
2466 """
2467 Release the given members from the parent's own stream and stop it.
2468
2469 :param parent_player: The parent player whose native session is handed over.
2470 :param parent_protocol_player: The protocol player taking the output over.
2471 :param stranded_native_members: The members to release, already migrated.
2472 """
2473 self.logger.debug(
2474 "Stopping the native session of %s before switching to %s, migrated members: %s",
2475 parent_player.state.name,
2476 parent_protocol_player.state.name,
2477 stranded_native_members,
2478 )
2479 # The members already joined the protocol group, so the native session only has to
2480 # release them and stop. Releasing them first also clears the native group, which
2481 # keeps a later native playback command from resurrecting it. Both calls take the
2482 # provider's own lock, so they must run one after the other.
2483 await parent_player.set_members(player_ids_to_remove=stranded_native_members)
2484 await parent_player.stop()
2485
2486 def _translate_members_for_protocols(
2487 self,
2488 parent_player: Player,
2489 player_ids: list[str],
2490 parent_protocol_player: Player | None,
2491 parent_protocol_domain: str | None,
2492 ) -> tuple[list[str], list[str], Player | None, str | None]:
2493 """
2494 Translate member IDs to protocol or native IDs.
2495
2496 The grouping method is picked per member, see _select_grouping_for_member.
2497
2498 Returns tuple of (protocol_members, native_members, protocol_player, protocol_domain).
2499 """
2500 protocol_members: list[str] = []
2501 native_members: list[str] = []
2502 parent_supports_native_grouping = (
2503 PlayerFeature.SET_MEMBERS in parent_player.supported_features
2504 )
2505 player_ids = self._order_members_for_native_join(
2506 player_ids, parent_player, parent_supports_native_grouping
2507 )
2508
2509 self.logger.log(
2510 VERBOSE_LOG_LEVEL,
2511 "Translating members for %s: parent_supports_native=%s, parent_protocol=%s (%s)",
2512 parent_player.state.name,
2513 parent_supports_native_grouping,
2514 parent_protocol_player.state.name if parent_protocol_player else "none",
2515 parent_protocol_domain or "none",
2516 )
2517
2518 for child_player_id in player_ids:
2519 child_player = self.get_player(child_player_id)
2520 if not child_player:
2521 continue
2522
2523 self.logger.log(
2524 VERBOSE_LOG_LEVEL,
2525 "Processing child %s (type=%s, protocols=%s)",
2526 child_player.state.name,
2527 child_player.state.type,
2528 [p.protocol_domain for p in child_player.output_protocols],
2529 )
2530
2531 parent_protocol_player, parent_protocol_domain = self._select_grouping_for_member(
2532 child_player,
2533 parent_player,
2534 parent_protocol_player,
2535 parent_protocol_domain,
2536 parent_supports_native_grouping,
2537 protocol_members,
2538 native_members,
2539 )
2540
2541 # Post-pass: the protocol selected for the group is only known once every child has
2542 # been processed, so the members picked for native grouping are corrected here.
2543 self._move_native_members_to_group_protocol(
2544 parent_player,
2545 parent_protocol_player,
2546 parent_protocol_domain,
2547 protocol_members,
2548 native_members,
2549 )
2550
2551 return protocol_members, native_members, parent_protocol_player, parent_protocol_domain
2552
2553 def _select_grouping_for_member(
2554 self,
2555 child_player: Player,
2556 parent_player: Player,
2557 parent_protocol_player: Player | None,
2558 parent_protocol_domain: str | None,
2559 parent_supports_native_grouping: bool,
2560 protocol_members: list[str],
2561 native_members: list[str],
2562 ) -> tuple[Player | None, str | None]:
2563 """
2564 Pick the grouping method for a single member and add it to the matching member list.
2565
2566 Selection priority when grouping:
2567 0. If the parent is already playing natively and the child can be grouped
2568 natively, join that native session (a child joining an existing group must
2569 not force the whole group onto its own preferred output protocol)
2570 1. Try child's preferred output protocol (from player settings)
2571 2. Try parent's active output protocol (if any and child supports it)
2572 3. Try native grouping (if parent and child are compatible)
2573 4. Search for common protocol that supports set_members
2574 5. Log warning if no option works
2575
2576 Returns the protocol player/domain the group is on, which the picked method may have
2577 changed.
2578
2579 :param child_player: The player being added to the group.
2580 :param parent_player: The parent player being joined.
2581 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2582 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2583 :param parent_supports_native_grouping: Whether the parent can group natively.
2584 :param protocol_members: The protocol member list to append to.
2585 :param native_members: The native member list to append to.
2586 """
2587 # Priority 0: The parent is already playing natively and the child can join
2588 # that native session directly - adopt it before considering the child's own
2589 # preferred output protocol.
2590 if self._try_join_active_native_session(
2591 child_player,
2592 parent_player,
2593 parent_protocol_domain,
2594 parent_supports_native_grouping,
2595 native_members,
2596 ):
2597 return parent_protocol_player, parent_protocol_domain
2598
2599 # Priority 0.5: a player that runs its own multiroom (e.g. a LinkPlay control shell)
2600 # keeps grouping on its native path rather than routing it through a linked protocol
2601 # that is merely its preferred playback output. Native compatibility still decides
2602 # whether this is possible, so an incompatible/cross-backend pair falls through.
2603 if child_player.prefer_native_grouping and self._can_use_native_grouping(
2604 child_player, parent_player, parent_supports_native_grouping
2605 ):
2606 native_members.append(child_player.player_id)
2607 self.logger.log(
2608 VERBOSE_LOG_LEVEL,
2609 "Using native grouping (preferred) for %s",
2610 child_player.state.name,
2611 )
2612 return parent_protocol_player, parent_protocol_domain
2613
2614 # Priority 1: the child's preferred output protocol
2615 grouped, parent_protocol_player, parent_protocol_domain = (
2616 self._try_group_via_preferred_protocol(
2617 child_player,
2618 parent_player,
2619 parent_protocol_player,
2620 parent_protocol_domain,
2621 protocol_members,
2622 )
2623 )
2624 if grouped:
2625 return parent_protocol_player, parent_protocol_domain
2626
2627 # Priority 2: the protocol the group is already on
2628 grouped, parent_protocol_player, parent_protocol_domain = (
2629 self._try_group_via_active_protocol(
2630 child_player,
2631 parent_protocol_player,
2632 parent_protocol_domain,
2633 protocol_members,
2634 )
2635 )
2636 if grouped:
2637 return parent_protocol_player, parent_protocol_domain
2638
2639 # Priority 3: native grouping
2640 if self._can_use_native_grouping(
2641 child_player, parent_player, parent_supports_native_grouping
2642 ):
2643 native_members.append(child_player.player_id)
2644 self.logger.log(
2645 VERBOSE_LOG_LEVEL,
2646 "Using native grouping for %s",
2647 child_player.state.name,
2648 )
2649 return parent_protocol_player, parent_protocol_domain
2650
2651 # Priority 4: a protocol both players share that supports set_members
2652 grouped, parent_protocol_player, parent_protocol_domain = (
2653 self._try_group_via_common_protocol(
2654 child_player,
2655 parent_player,
2656 parent_protocol_player,
2657 parent_protocol_domain,
2658 protocol_members,
2659 )
2660 )
2661 if grouped:
2662 return parent_protocol_player, parent_protocol_domain
2663
2664 # Priority 5: no option worked
2665 self.logger.warning(
2666 "Cannot group %s with %s: no compatible grouping method found "
2667 "(tried: child preferred protocol, parent active protocol, "
2668 "native grouping, common protocols)",
2669 child_player.state.name,
2670 parent_player.state.name,
2671 )
2672 return parent_protocol_player, parent_protocol_domain
2673
2674 def _try_group_via_preferred_protocol(
2675 self,
2676 child_player: Player,
2677 parent_player: Player,
2678 parent_protocol_player: Player | None,
2679 parent_protocol_domain: str | None,
2680 protocol_members: list[str],
2681 ) -> tuple[bool, Player | None, str | None]:
2682 """
2683 Try to group the child through the output protocol it prefers in its player settings.
2684
2685 Only used when the group is not on a protocol yet or is already on that same protocol.
2686 Returns whether the child was grouped, together with the protocol player/domain the
2687 group is on: the child's preferred protocol may become the group's protocol.
2688
2689 :param child_player: The player being added to the group.
2690 :param parent_player: The parent player being joined.
2691 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2692 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2693 :param protocol_members: The protocol member list to append to.
2694 """
2695 child_protocol_id, protocol_domain = self._try_child_preferred_protocol(
2696 child_player, parent_player
2697 )
2698 if not (
2699 child_protocol_id
2700 and protocol_domain
2701 and (not parent_protocol_domain or protocol_domain == parent_protocol_domain)
2702 ):
2703 return False, parent_protocol_player, parent_protocol_domain
2704
2705 if not parent_protocol_player or parent_protocol_domain != protocol_domain:
2706 parent_protocol = parent_player.get_output_protocol_by_domain(protocol_domain)
2707 if parent_protocol:
2708 parent_protocol_player = parent_player.get_protocol_player(
2709 parent_protocol.output_protocol_id
2710 )
2711 parent_protocol_domain = protocol_domain
2712 protocol_members.append(child_protocol_id)
2713 self.logger.log(
2714 VERBOSE_LOG_LEVEL,
2715 "Using child's preferred protocol %s for %s",
2716 protocol_domain,
2717 child_player.state.name,
2718 )
2719 return True, parent_protocol_player, parent_protocol_domain
2720
2721 def _try_group_via_active_protocol(
2722 self,
2723 child_player: Player,
2724 parent_protocol_player: Player | None,
2725 parent_protocol_domain: str | None,
2726 protocol_members: list[str],
2727 ) -> tuple[bool, Player | None, str | None]:
2728 """
2729 Try to group the child through the protocol the group is already on.
2730
2731 Returns whether the child was grouped, together with the protocol player/domain the
2732 group is on: the selection is dropped when that protocol cannot group members itself,
2733 so a later grouping method can select another one.
2734
2735 :param child_player: The player being added to the group.
2736 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2737 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2738 :param protocol_members: The protocol member list to append to.
2739 """
2740 if not parent_protocol_domain or not parent_protocol_player:
2741 return False, parent_protocol_player, parent_protocol_domain
2742
2743 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2744 self.logger.log(
2745 VERBOSE_LOG_LEVEL,
2746 "Parent's active protocol %s does not support SET_MEMBERS, "
2747 "will search for alternative",
2748 parent_protocol_domain,
2749 )
2750 # Drop the selection so a later grouping method can select a new protocol
2751 return False, None, None
2752
2753 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2754 if not child_protocol or not child_protocol.available:
2755 return False, parent_protocol_player, parent_protocol_domain
2756
2757 # For native protocol players, use the child's player_id directly
2758 # (e.g., a native sendspin web player IS the protocol player)
2759 child_protocol_id = (
2760 child_player.player_id
2761 if child_protocol.is_native
2762 else child_protocol.output_protocol_id
2763 )
2764 protocol_members.append(child_protocol_id)
2765 self.logger.log(
2766 VERBOSE_LOG_LEVEL,
2767 "Using parent's active protocol %s for %s",
2768 parent_protocol_domain,
2769 child_player.state.name,
2770 )
2771 return True, parent_protocol_player, parent_protocol_domain
2772
2773 def _try_group_via_common_protocol(
2774 self,
2775 child_player: Player,
2776 parent_player: Player,
2777 parent_protocol_player: Player | None,
2778 parent_protocol_domain: str | None,
2779 protocol_members: list[str],
2780 ) -> tuple[bool, Player | None, str | None]:
2781 """
2782 Try to group the child through a protocol both players share.
2783
2784 Returns whether the child was grouped, together with the protocol player/domain the
2785 group is on: the shared protocol may become the group's protocol.
2786
2787 :param child_player: The player being added to the group.
2788 :param parent_player: The parent player being joined.
2789 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2790 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2791 :param protocol_members: The protocol member list to append to.
2792 """
2793 parent_protocol, child_protocol = self._try_find_common_protocol(
2794 child_player, parent_player
2795 )
2796 if not parent_protocol or not child_protocol:
2797 return False, parent_protocol_player, parent_protocol_domain
2798
2799 if not parent_protocol_player or parent_protocol_domain != parent_protocol.protocol_domain:
2800 parent_protocol_player = parent_player.get_protocol_player(
2801 parent_protocol.output_protocol_id
2802 )
2803 if parent_protocol_player:
2804 parent_protocol_domain = parent_protocol_player.provider.domain
2805 # For native protocol players, use the child's player_id directly
2806 child_protocol_id = (
2807 child_player.player_id
2808 if child_protocol.is_native
2809 else child_protocol.output_protocol_id
2810 )
2811 protocol_members.append(child_protocol_id)
2812 self.logger.log(
2813 VERBOSE_LOG_LEVEL,
2814 "Selected common protocol %s for grouping %s with %s",
2815 parent_protocol.protocol_domain,
2816 child_player.state.name,
2817 parent_player.state.name,
2818 )
2819 return True, parent_protocol_player, parent_protocol_domain
2820
2821 async def _forward_protocol_set_members(
2822 self,
2823 parent_player: Player,
2824 parent_protocol_player: Player,
2825 protocol_members_to_add: list[str],
2826 protocol_members_to_remove: list[str],
2827 ) -> None:
2828 """
2829 Forward protocol members to protocol player's set_members and manage active output protocol.
2830
2831 :param parent_player: The parent player (native/universal).
2832 :param parent_protocol_player: The protocol player to forward commands to.
2833 :param protocol_members_to_add: Protocol player IDs to add.
2834 :param protocol_members_to_remove: Protocol player IDs to remove.
2835 """
2836 filtered_protocol_add = self._filter_protocol_members(
2837 protocol_members_to_add, parent_protocol_player
2838 )
2839 filtered_protocol_remove = self._filter_protocol_members(
2840 protocol_members_to_remove, parent_protocol_player
2841 )
2842 self.logger.debug(
2843 "Protocol grouping on %s: filtered_add=%s, filtered_remove=%s",
2844 parent_protocol_player.state.name,
2845 filtered_protocol_add,
2846 filtered_protocol_remove,
2847 )
2848
2849 if not filtered_protocol_add and not filtered_protocol_remove:
2850 return
2851
2852 # Safety check: verify protocol player supports SET_MEMBERS
2853 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2854 self.logger.error(
2855 "Protocol player %s does not support SET_MEMBERS, cannot perform grouping. "
2856 "This should have been caught earlier in the flow.",
2857 parent_protocol_player.state.name,
2858 )
2859 return
2860
2861 # Members that ride the parent's own stream are stranded by the protocol switch below,
2862 # so they join the protocol group in this very same call and their native session is
2863 # torn down afterwards.
2864 stranded_native_members = (
2865 self._migrate_stranded_native_members(
2866 parent_player, parent_protocol_player, filtered_protocol_add
2867 )
2868 if filtered_protocol_add
2869 else []
2870 )
2871
2872 # This runs before set_members because a member's own stream starts inside that call
2873 # and the provider resolves the member's volume control as it starts: unless its parent
2874 # already points at this protocol, that resolution picks a sibling interface of the same
2875 # device (e.g. its cast side) over the one carrying the audio.
2876 self._activate_protocol_on_added_children(filtered_protocol_add)
2877
2878 self.logger.debug(
2879 "Calling set_members on protocol player %s with add=%s, remove=%s",
2880 parent_protocol_player.state.name,
2881 filtered_protocol_add,
2882 filtered_protocol_remove,
2883 )
2884 await parent_protocol_player.set_members(
2885 player_ids_to_add=filtered_protocol_add or None,
2886 player_ids_to_remove=filtered_protocol_remove or None,
2887 )
2888
2889 if filtered_protocol_add:
2890 await self._activate_group_output_protocol(
2891 parent_player, parent_protocol_player, stranded_native_members
2892 )
2893
2894 self.logger.debug(
2895 "After set_members, protocol player %s state: group_members=%s, synced_to=%s",
2896 parent_protocol_player.state.name,
2897 parent_protocol_player.group_members,
2898 parent_protocol_player.synced_to,
2899 )
2900
2901 def _activate_protocol_on_added_children(self, protocol_member_ids: list[str]) -> None:
2902 """
2903 Point the parent of each given protocol member at the protocol carrying the group audio.
2904
2905 :param protocol_member_ids: The protocol player IDs joining the group.
2906 """
2907 for child_protocol_id in protocol_member_ids:
2908 if not (child_protocol := self.get_player(child_protocol_id)):
2909 continue
2910 if not child_protocol.protocol_parent_id:
2911 continue
2912 if not (child_player := self.get_player(child_protocol.protocol_parent_id)):
2913 continue
2914 if child_player.active_output_protocol == child_protocol_id:
2915 continue
2916 self.logger.debug(
2917 "Setting active output protocol on child %s to %s",
2918 child_player.state.name,
2919 child_protocol_id,
2920 )
2921 child_player.set_active_output_protocol(child_protocol_id)
2922
2923 async def _activate_group_output_protocol(
2924 self,
2925 parent_player: Player,
2926 parent_protocol_player: Player,
2927 stranded_native_members: list[str],
2928 ) -> None:
2929 """
2930 Mark the given protocol as the parent's output and hand the playback over to it.
2931
2932 The handover only runs when the parent is actually switching protocol while it is
2933 rendering; playback is resumed only for a parent that was playing, so adding a member
2934 never starts playback on its own.
2935
2936 :param parent_player: The parent player that just gained protocol members.
2937 :param parent_protocol_player: The protocol player the members joined.
2938 :param stranded_native_members: The members left without a stream by the switch.
2939 """
2940 previous_protocol = parent_player.active_output_protocol
2941 was_playing = parent_player.state.playback_state == PlaybackState.PLAYING
2942 # A paused player still holds its output, so the handover has to run for it too.
2943 was_rendering = was_playing or parent_player.state.playback_state == PlaybackState.PAUSED
2944
2945 # Native protocol: parent_protocol_player is the same as parent_player
2946 is_native_protocol = parent_protocol_player.player_id == parent_player.player_id
2947 already_using_native = previous_protocol in (None, "native")
2948 already_using_this_protocol = previous_protocol == parent_protocol_player.player_id
2949 switching_protocols = not (
2950 (is_native_protocol and already_using_native) or already_using_this_protocol
2951 )
2952
2953 self.logger.debug(
2954 "Protocol grouping: is_native=%s, already_native=%s, already_this=%s, "
2955 "switching=%s, was_rendering=%s",
2956 is_native_protocol,
2957 already_using_native,
2958 already_using_this_protocol,
2959 switching_protocols,
2960 was_rendering,
2961 )
2962
2963 if not (is_native_protocol and already_using_native):
2964 parent_player.set_active_output_protocol(parent_protocol_player.player_id)
2965
2966 if not (was_rendering and switching_protocols):
2967 return
2968
2969 self.logger.info(
2970 "Handing the output of %s over to the %s protocol%s",
2971 parent_player.state.name,
2972 parent_protocol_player.provider.domain,
2973 " and resuming playback" if was_playing else "",
2974 )
2975 if stranded_native_members:
2976 await self._stop_native_session(
2977 parent_player, parent_protocol_player, stranded_native_members
2978 )
2979 old_parent_members = await self._stop_previous_protocol(
2980 parent_player, parent_protocol_player, previous_protocol
2981 )
2982 if was_playing:
2983 await self.mass.players.cmd_resume(parent_player.player_id)
2984 if old_parent_members:
2985 self.logger.debug(
2986 "Re-adding migrated members %s to %s on new protocol",
2987 old_parent_members,
2988 parent_player.state.name,
2989 )
2990 # Use internal handler because we are already inside a
2991 # _handle_set_members call chain that holds the play lock.
2992 await self.mass.players._handle_set_members(
2993 parent_player,
2994 player_ids_to_add=old_parent_members,
2995 )
2996
2997 async def _stop_previous_protocol(
2998 self,
2999 parent_player: Player,
3000 parent_protocol_player: Player,
3001 previous_protocol: str | None,
3002 ) -> list[str]:
3003 """
3004 Stop the protocol player the parent was rendering through and return its members.
3005
3006 The returned IDs are parent player IDs, so the caller can re-add them to the group
3007 once the new protocol carries the audio. Empty if there is nothing to hand over.
3008
3009 :param parent_player: The parent player that is switching protocol.
3010 :param parent_protocol_player: The protocol player taking the output over.
3011 :param previous_protocol: The parent's previous active output protocol, if any.
3012 """
3013 if previous_protocol in (None, "native"):
3014 return []
3015 if not (old_protocol_player := self.get_player(previous_protocol)):
3016 return []
3017 if old_protocol_player.player_id == parent_protocol_player.player_id:
3018 return []
3019 # Translate the old protocol's child members back to parent player IDs
3020 old_parent_members: list[str] = []
3021 for member_id in old_protocol_player.group_members:
3022 if member_id == old_protocol_player.player_id:
3023 continue
3024 if not (member_player := self.get_player(member_id)):
3025 continue
3026 parent_id = member_player.protocol_parent_id or member_id
3027 if parent_id != parent_player.player_id:
3028 old_parent_members.append(parent_id)
3029 self.logger.debug(
3030 "Stopping old protocol player %s before switching to %s, migrating members: %s",
3031 old_protocol_player.state.name,
3032 parent_protocol_player.state.name,
3033 old_parent_members,
3034 )
3035 # Use internal handler to stop the specific protocol player,
3036 # bypassing group/sync redirect and queue redirect logic.
3037 await self.mass.players._handle_cmd_stop(old_protocol_player.player_id)
3038 return old_parent_members
3039