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