/
/
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 self._unlink_from_protocol_parent(player)
1603 return
1604 self._detach_owned_protocols(player)
1605
1606 def _unlink_from_protocol_parent(self, player: Player) -> None:
1607 """Release a protocol player from the parent it is attached to."""
1608 if parent_id := player.protocol_parent_id:
1609 if parent_player := self.get_player(parent_id):
1610 # Use permanent=True to also remove from cached protocol IDs
1611 self._remove_protocol_link(parent_player, player.player_id, permanent=True)
1612 if (
1613 parent_player.provider.domain == "universal_player"
1614 and len(parent_player.linked_output_protocols) == 0
1615 ):
1616 # No protocols left - the universal player has nothing to play
1617 # on. Its config is deliberately kept: the player id is opaque
1618 # and cannot be recreated, so deleting it here would orphan the
1619 # entities API consumers bound to it. Only an explicit removal
1620 # by the user deletes a universal player for good.
1621 self.logger.info(
1622 "Universal player %s has no protocols left",
1623 parent_id,
1624 )
1625 self.mass.create_task(self.mass.players.unregister(parent_id, permanent=False))
1626 else:
1627 parent_player.refresh_state()
1628 else:
1629 # Parent not registered yet — still purge the cached id
1630 self._remove_protocol_id_from_cache(parent_id, player.player_id)
1631
1632 def _detach_owned_protocols(self, player: Player) -> None:
1633 """Detach the protocol players a parent owns so they can find a new parent."""
1634 # collect the ids from both the active links and the cached state, since
1635 # disabled/inactive protocols may only exist in the cached parent data
1636 all_protocol_ids = set(self._get_known_protocol_ids(player))
1637 for protocol_id in all_protocol_ids:
1638 if protocol_player := self.get_player(protocol_id):
1639 # Protocol player is available: clear parent and schedule re-evaluation
1640 # so it can be matched to a new parent or a new universal player
1641 self.logger.debug(
1642 "Player %s no longer owns protocol %s - scheduling evaluation",
1643 player.player_id,
1644 protocol_id,
1645 )
1646 self._detach_protocol_child(protocol_player)
1647 else:
1648 # Clear cached parent ID in config so protocol won't try to
1649 # restore a link to its former parent on next restart
1650 self._clear_protocol_parent_id(protocol_id)
1651 # Protocol player is not registered yet — it may still be
1652 # mid-discovery (e.g., DLNA connecting via SSDP). Don't delete
1653 # its config as that would cause a KeyError when it finishes
1654 # registering. Stale configs are harmless and get cleaned up
1655 # naturally on subsequent restarts.
1656 self.logger.debug(
1657 "Player %s no longer owns protocol %s - not registered, skipping cleanup",
1658 player.player_id,
1659 protocol_id,
1660 )
1661
1662 def _cleanup_player_type_transition(self, existing: Player, *, becomes_protocol: bool) -> None:
1663 """
1664 Release the protocol topology a player owned before its type changed.
1665
1666 :param existing: The registered player instance for the changed player.
1667 :param becomes_protocol: True if the player moves into the protocol role,
1668 False if it leaves it.
1669 """
1670 if not becomes_protocol:
1671 # a provider may announce the new type with the live parent link already
1672 # dropped, so fall back to the persisted one to still reach the parent
1673 parent_id = existing.protocol_parent_id or self._get_cached_protocol_parent_id(
1674 existing.player_id
1675 )
1676 if not parent_id:
1677 return
1678 parent = self.get_player(parent_id)
1679 if parent is not None and parent.provider.domain == "universal_player":
1680 # drop only the active edge and leave the rest to the link evaluation,
1681 # which replaces the wrapper with this player: a leftover edge makes it
1682 # hand the player over to itself, which it refuses, abandoning the swap
1683 self._remove_protocol_link(parent, existing.player_id)
1684 return
1685 existing.set_protocol_parent_id(parent_id)
1686 # unlink at the parent and drop the persisted parent id, which would
1687 # otherwise heal the player's type back to protocol
1688 self._unlink_from_protocol_parent(existing)
1689 # a player leaving the protocol role has no parent, also when that parent
1690 # is not registered (anymore) and only the cached link could be cleaned up
1691 existing.set_protocol_parent_id(None)
1692 return
1693 # the player becomes a child itself: detach the protocol players it owned so they
1694 # can find a new parent, then give up their ownership in its (kept) config - the
1695 # reverse of the removal path, which drops the ownership before the detach
1696 protocol_ids = set(self._get_known_protocol_ids(existing))
1697 self._detach_owned_protocols(existing)
1698 self._remove_protocol_ids_from_parent(existing, protocol_ids)
1699
1700 def _detach_protocol_children(self, parent_id: str) -> None:
1701 """
1702 Detach the registered protocol players of a parent player that is going away.
1703
1704 Covers the removal paths that don't unregister the parent first (e.g. its
1705 provider is unloaded), where the parent is not around anymore to enumerate
1706 its protocol players.
1707
1708 :param parent_id: Player id of the parent that is being removed.
1709 """
1710 for protocol_player in list(self._players.values()):
1711 if protocol_player.state.type != PlayerType.PROTOCOL:
1712 continue
1713 # a protocol player waiting for a parent that never registered only has
1714 # the link in its config, so fall back to the cached parent
1715 linked_parent_id = protocol_player.protocol_parent_id or (
1716 self._get_cached_protocol_parent_id(protocol_player.player_id)
1717 )
1718 if linked_parent_id != parent_id:
1719 continue
1720 self.logger.debug(
1721 "Player %s removed - scheduling evaluation for protocol %s",
1722 parent_id,
1723 protocol_player.player_id,
1724 )
1725 self._detach_protocol_child(protocol_player)
1726
1727 def _detach_protocol_child(self, protocol_player: Player) -> None:
1728 """Clear a protocol player's parent link and schedule a fresh evaluation."""
1729 self._clear_protocol_parent_id(protocol_player.player_id)
1730 protocol_player.set_protocol_parent_id(None)
1731 protocol_player.refresh_state()
1732 self._schedule_protocol_evaluation(protocol_player)
1733
1734 def _identifiers_match(
1735 self, player_a: Player, player_b: Player, protocol_domain: str = ""
1736 ) -> bool:
1737 """
1738 Check if identifiers match between two players.
1739
1740 Matching is done by comparing connection identifiers (MAC, serial, UUID).
1741 As a last resort, IP address is used when at least one player has a
1742 locally-administered MAC, indicating the device uses MAC randomization
1743 and ARP could not resolve the real hardware address.
1744
1745 Invalid identifiers (e.g., 00:00:00:00:00:00 MAC addresses) are filtered out
1746 to prevent false matches between unrelated devices.
1747 """
1748 identifiers_a = player_a.device_info.identifiers
1749 identifiers_b = player_b.device_info.identifiers
1750
1751 # Check identifiers in order of reliability
1752 # MAC_ADDRESS > SERIAL_NUMBER > UUID > CAST_UUID > AIRPLAY_ID
1753 for conn_type in (
1754 IdentifierType.MAC_ADDRESS,
1755 IdentifierType.SERIAL_NUMBER,
1756 IdentifierType.UUID,
1757 IdentifierType.CAST_UUID,
1758 IdentifierType.AIRPLAY_ID,
1759 ):
1760 val_a = identifiers_a.get(conn_type)
1761 val_b = identifiers_b.get(conn_type)
1762
1763 if not val_a or not val_b:
1764 continue
1765
1766 # Filter out invalid MAC addresses (00:00:00:00:00:00, ff:ff:ff:ff:ff:ff)
1767 if conn_type == IdentifierType.MAC_ADDRESS:
1768 if not is_valid_mac_address(val_a) or not is_valid_mac_address(val_b):
1769 self.logger.log(
1770 VERBOSE_LOG_LEVEL,
1771 "Skipping invalid MAC address for matching: %s=%s, %s=%s",
1772 player_a.display_name,
1773 val_a,
1774 player_b.display_name,
1775 val_b,
1776 )
1777 continue
1778
1779 # Normalize values for comparison
1780 if conn_type == IdentifierType.MAC_ADDRESS:
1781 # Use MAC normalization that handles locally-administered bit differences
1782 # Some protocols (like AirPlay) report a locally-administered MAC variant
1783 # where bit 1 of the first octet is set (e.g., 54:78:... vs 56:78:...)
1784 val_a_norm = normalize_mac_for_matching(val_a)
1785 val_b_norm = normalize_mac_for_matching(val_b)
1786
1787 # Direct match on current MAC
1788 if val_a_norm == val_b_norm:
1789 return True
1790
1791 # Multi-MAC matching: also check original reported MACs.
1792 # Devices with multiple interfaces (WiFi + Ethernet) may have ARP
1793 # resolve one MAC while the protocol reports a different one.
1794 macs_a = {val_a_norm}
1795 macs_b = {val_b_norm}
1796 reported_a = player_a.extra_data.get("reported_mac")
1797 reported_b = player_b.extra_data.get("reported_mac")
1798 if reported_a and is_valid_mac_address(reported_a):
1799 macs_a.add(normalize_mac_for_matching(reported_a))
1800 if reported_b and is_valid_mac_address(reported_b):
1801 macs_b.add(normalize_mac_for_matching(reported_b))
1802 if macs_a & macs_b:
1803 return True
1804
1805 # No MAC match - continue to next identifier type
1806 continue
1807
1808 val_a_norm = val_a.lower().replace(":", "").replace("-", "")
1809 val_b_norm = val_b.lower().replace(":", "").replace("-", "")
1810
1811 # Direct match
1812 if val_a_norm == val_b_norm:
1813 return True
1814
1815 # Special case: Sonos UUID matching with DLNA _MR suffix
1816 # Sonos uses RINCON_xxx, DLNA uses RINCON_xxx_MR for Media Renderer
1817 if conn_type == IdentifierType.UUID:
1818 if val_b_norm.endswith("_mr") and val_b_norm[:-3] == val_a_norm:
1819 return True
1820 if val_a_norm.endswith("_mr") and val_a_norm[:-3] == val_b_norm:
1821 return True
1822
1823 # Last resort: IP-based matching.
1824 # Two players on the same IP are very likely the same physical device.
1825 # This handles two cases:
1826 # 1. MAC randomization: at least one player has no real MAC (LA or missing),
1827 # so ARP couldn't resolve a usable address.
1828 # 2. Different MACs per protocol: some devices (e.g., Yamaha MusicCast) report
1829 # different valid globally-unique MACs per protocol (DLNA vs AirPlay differ
1830 # by 1 in the last octet). IP matching is safe here because two different
1831 # devices on a LAN cannot share the same IP simultaneously.
1832 # To avoid false positives between unrelated native players, this path
1833 # requires at least one player to be a protocol or universal player.
1834 ip_a = identifiers_a.get(IdentifierType.IP_ADDRESS)
1835 ip_b = identifiers_b.get(IdentifierType.IP_ADDRESS)
1836 if ip_a and ip_b and ip_a == ip_b:
1837 mac_a = identifiers_a.get(IdentifierType.MAC_ADDRESS)
1838 mac_b = identifiers_b.get(IdentifierType.MAC_ADDRESS)
1839 a_is_real = (
1840 mac_a is not None
1841 and is_valid_mac_address(mac_a)
1842 and not is_locally_administered_mac(mac_a)
1843 )
1844 b_is_real = (
1845 mac_b is not None
1846 and is_valid_mac_address(mac_b)
1847 and not is_locally_administered_mac(mac_b)
1848 )
1849 # Case 1: at least one player has no real hardware MAC
1850 if not (a_is_real and b_is_real):
1851 return True
1852 # Case 2: both have real MACs but at least one is a protocol/universal player
1853 a_is_protocol = (
1854 player_a.type == PlayerType.PROTOCOL
1855 or player_a.provider.domain == "universal_player"
1856 )
1857 b_is_protocol = (
1858 player_b.type == PlayerType.PROTOCOL
1859 or player_b.provider.domain == "universal_player"
1860 )
1861 if a_is_protocol or b_is_protocol:
1862 return True
1863
1864 return False
1865
1866 def _select_best_output_protocol(self, player: Player) -> tuple[Player, OutputProtocol | None]:
1867 """
1868 Select the best available output protocol for a player.
1869
1870 Selection priority:
1871 1. Output protocol that is currently grouped/synced with other players.
1872 2. User's preferred output protocol (from player settings).
1873 3. Native playback (if player supports PLAY_MEDIA).
1874 4. The player's declared default output protocol domain, if available.
1875 5. Best available protocol by priority.
1876
1877 Returns tuple of (target_player, output_protocol).
1878 output_protocol is None when using native playback.
1879 """
1880 self.logger.log(
1881 VERBOSE_LOG_LEVEL,
1882 "Selecting output protocol for %s",
1883 player.state.name,
1884 )
1885
1886 # 1. Check if any output protocol is currently grouped
1887 for linked in player.linked_output_protocols:
1888 if protocol_player := self.get_player(linked.output_protocol_id):
1889 if protocol_player.available_for_playback and self._is_protocol_grouped(
1890 protocol_player
1891 ):
1892 self.logger.log(
1893 VERBOSE_LOG_LEVEL,
1894 "Selected protocol for %s: %s (grouped)",
1895 player.state.name,
1896 protocol_player.state.name,
1897 )
1898 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1899
1900 # 2. Check for user's preferred output protocol.
1901 # The value is only stored while it differs from the entry's default: "native" when a
1902 # native output is available, otherwise "auto". A player without a native output (e.g. a
1903 # LinkPlay shell) therefore has no stored preference by default and gets its default
1904 # output domain applied in step 4.
1905 preferred = self.mass.config.get_raw_player_config_value(
1906 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
1907 )
1908 if preferred and preferred != "auto":
1909 if preferred == "native":
1910 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1911 self.logger.log(
1912 VERBOSE_LOG_LEVEL,
1913 "Selected protocol for %s: native (user preference)",
1914 player.state.name,
1915 )
1916 return player, None
1917 else:
1918 for linked in player.linked_output_protocols:
1919 if linked.output_protocol_id == preferred:
1920 if protocol_player := self.get_player(linked.output_protocol_id):
1921 if protocol_player.available_for_playback:
1922 self.logger.log(
1923 VERBOSE_LOG_LEVEL,
1924 "Selected protocol for %s: %s (user preference)",
1925 player.state.name,
1926 protocol_player.state.name,
1927 )
1928 return protocol_player, player.get_linked_protocol(
1929 linked.output_protocol_id
1930 )
1931 break
1932
1933 # 3. Use native playback if available
1934 if PlayerFeature.PLAY_MEDIA in player.supported_features:
1935 self.logger.log(
1936 VERBOSE_LOG_LEVEL, "Selected protocol for %s: native", player.state.name
1937 )
1938 return player, None
1939
1940 # 4. Use the player's preferred default protocol domain, if it declares one and a
1941 # matching linked protocol is available (e.g. a LinkPlay shell prefers DLNA). This
1942 # never influences grouping; it only steers the default output for playback. "Auto"
1943 # is the entry default here, so it consistently resolves to this domain default.
1944 if default_domain := player.default_output_protocol_domain:
1945 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1946 if linked.protocol_domain != default_domain:
1947 continue
1948 if (protocol_player := self.get_player(linked.output_protocol_id)) and (
1949 protocol_player.available_for_playback
1950 ):
1951 self.logger.log(
1952 VERBOSE_LOG_LEVEL,
1953 "Selected protocol for %s: %s (default domain %s)",
1954 player.state.name,
1955 protocol_player.state.name,
1956 default_domain,
1957 )
1958 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1959
1960 # 5. Fall back to best protocol by priority
1961 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
1962 if protocol_player := self.get_player(linked.output_protocol_id):
1963 if protocol_player.available_for_playback:
1964 self.logger.log(
1965 VERBOSE_LOG_LEVEL,
1966 "Selected protocol for %s: %s (priority-based)",
1967 player.state.name,
1968 protocol_player.state.name,
1969 )
1970 return protocol_player, player.get_linked_protocol(linked.output_protocol_id)
1971
1972 raise PlayerCommandFailed(f"Player {player.state.name} has no available output protocols")
1973
1974 def _get_control_target(
1975 self,
1976 player: Player,
1977 required_feature: PlayerFeature,
1978 require_active: bool = False,
1979 ) -> Player | None:
1980 """
1981 Get the best player(protocol) to send audio-path commands to.
1982
1983 Resolves commands that travel with the audio (enqueue, pause, announcements),
1984 so the output that renders the audio outranks the native player. Volume and
1985 mute are control-plane instead and resolve through
1986 :meth:`Player._get_protocol_player_for_feature`, which orders differently.
1987
1988 :param player: The player the command was issued on.
1989 :param required_feature: The feature the resolved target has to support.
1990 :param require_active: Only accept the output that is already rendering,
1991 instead of falling back to an idle one.
1992 """
1993 # If we have an active protocol, use that
1994 if (
1995 player.active_output_protocol
1996 and player.active_output_protocol != "native"
1997 and (protocol_player := self.mass.players.get_player(player.active_output_protocol))
1998 and required_feature in protocol_player.supported_features
1999 ):
2000 return protocol_player
2001
2002 # if the player natively supports the required feature, use that
2003 if (
2004 player.active_output_protocol == "native"
2005 and required_feature in player.supported_features
2006 ):
2007 return player
2008
2009 # If require_active is set, and no active protocol found, return None
2010 if require_active:
2011 return None
2012
2013 # if the player natively supports the required feature, use that
2014 if required_feature in player.supported_features:
2015 return player
2016
2017 # An output the user explicitly picked owns the audio, so a command that has to
2018 # start playback on an idle player follows it rather than the priority below.
2019 # The stored value survives a relink, so it only counts while it still names one
2020 # of this player's own outputs.
2021 preferred = self.mass.config.get_raw_player_config_value(
2022 player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2023 )
2024 if preferred and preferred not in ("auto", "native"):
2025 for linked in player.linked_output_protocols:
2026 if linked.output_protocol_id != preferred:
2027 continue
2028 if (
2029 (preferred_player := self.mass.players.get_player(str(preferred)))
2030 and preferred_player.available_for_playback
2031 and required_feature in preferred_player.supported_features
2032 ):
2033 return preferred_player
2034 break
2035
2036 # Otherwise, use the best available linked protocol, ordered by the same
2037 # priority that regular playback selection applies.
2038 for linked in sorted(player.linked_output_protocols, key=lambda x: x.priority):
2039 if (
2040 (protocol_player := self.mass.players.get_player(linked.output_protocol_id))
2041 and protocol_player.available_for_playback
2042 and required_feature in protocol_player.supported_features
2043 ):
2044 return protocol_player
2045
2046 return None
2047
2048 def _is_protocol_grouped(self, protocol_player: Player) -> bool:
2049 """
2050 Check if a protocol player is currently grouped/synced with other players.
2051
2052 Used to prefer protocols that are actively participating in a group,
2053 ensuring consistent playback across grouped players.
2054 """
2055 is_grouped = bool(
2056 protocol_player.state.synced_to
2057 or (
2058 protocol_player.state.group_members and len(protocol_player.state.group_members) > 1
2059 )
2060 or protocol_player.state.active_group
2061 )
2062 if is_grouped:
2063 self.logger.log(
2064 VERBOSE_LOG_LEVEL,
2065 "Protocol player %s is grouped",
2066 protocol_player.state.name,
2067 )
2068 return is_grouped
2069
2070 def _translate_members_to_remove_for_protocols(
2071 self,
2072 parent_player: Player,
2073 player_ids: list[str],
2074 parent_protocol_player: Player | None,
2075 parent_protocol_domain: str | None,
2076 ) -> tuple[list[str], list[str]]:
2077 """
2078 Translate member IDs to remove into protocol and native lists.
2079
2080 :param parent_player: The parent player to remove members from.
2081 :param player_ids: List of visible player IDs to remove.
2082 :param parent_protocol_player: The parent's protocol player if available.
2083 :param parent_protocol_domain: The parent's protocol domain if available.
2084 """
2085 self.logger.debug(
2086 "Translating members to remove for %s: player_ids=%s, parent_protocol_domain=%s",
2087 parent_player.state.name,
2088 player_ids,
2089 parent_protocol_domain,
2090 )
2091 protocol_members: list[str] = []
2092 native_members: list[str] = []
2093
2094 for child_player_id in player_ids:
2095 child_player = self.get_player(child_player_id)
2096 if not child_player:
2097 continue
2098
2099 # Check if this member is in the parent's group via protocol
2100 if parent_protocol_domain and parent_protocol_player:
2101 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2102 if child_protocol and child_protocol.available:
2103 # For native protocol players, use the child's player_id directly
2104 child_protocol_id = (
2105 child_player.player_id
2106 if child_protocol.is_native
2107 else child_protocol.output_protocol_id
2108 )
2109 if child_protocol_id in parent_protocol_player.group_members:
2110 self.logger.debug(
2111 "Translating removal: %s -> protocol %s",
2112 child_player_id,
2113 child_protocol_id,
2114 )
2115 protocol_members.append(child_protocol_id)
2116 continue
2117
2118 # Check if child's protocol player is in parent's native group_members
2119 # This handles native protocol players (e.g., native AirPlay player like Apple TV)
2120 # where the parent itself contains protocol player IDs in its group_members
2121 translated = False
2122 for linked in child_player.linked_output_protocols:
2123 if linked.output_protocol_id in parent_player.group_members:
2124 self.logger.debug(
2125 "Translating removal (native parent): %s -> protocol %s",
2126 child_player_id,
2127 linked.output_protocol_id,
2128 )
2129 native_members.append(linked.output_protocol_id)
2130 translated = True
2131 break
2132
2133 if not translated:
2134 native_members.append(child_player_id)
2135
2136 return protocol_members, native_members
2137
2138 def _filter_protocol_members(self, member_ids: list[str], protocol_player: Player) -> list[str]:
2139 """Filter member IDs to only include players from the same protocol domain."""
2140 return [
2141 pid
2142 for pid in member_ids
2143 if (p := self.get_player(pid)) and p.provider.domain == protocol_player.provider.domain
2144 ]
2145
2146 def _filter_native_members(self, member_ids: list[str], parent_player: Player) -> list[str]:
2147 """Filter member IDs to only include players compatible with the parent."""
2148 return [
2149 pid
2150 for pid in member_ids
2151 if (p := self.get_player(pid))
2152 and (
2153 p.provider.instance_id == parent_player.provider.instance_id
2154 or pid in parent_player._attr_can_group_with
2155 or p.provider.instance_id in parent_player._attr_can_group_with
2156 )
2157 ]
2158
2159 def _try_child_preferred_protocol(
2160 self,
2161 child_player: Player,
2162 parent_player: Player,
2163 ) -> tuple[str | None, str | None]:
2164 """
2165 Try to use child's preferred output protocol for grouping.
2166
2167 Returns tuple of (child_protocol_id, protocol_domain) or (None, None).
2168 """
2169 child_preferred = self.mass.config.get_raw_player_config_value(
2170 child_player.player_id, CONF_PREFERRED_OUTPUT_PROTOCOL
2171 )
2172 if not child_preferred or child_preferred in {"auto", "native"}:
2173 return None, None
2174
2175 # Find child's preferred protocol, with its current availability
2176 child_protocol = None
2177 for output_protocol in child_player.output_protocols:
2178 if output_protocol.output_protocol_id == child_preferred:
2179 child_protocol = output_protocol
2180 break
2181
2182 if not child_protocol or not child_protocol.available:
2183 return None, None
2184
2185 # Check if parent supports this protocol (including native protocol)
2186 parent_protocol = parent_player.get_output_protocol_by_domain(
2187 child_protocol.protocol_domain
2188 )
2189 if not parent_protocol or not parent_protocol.available:
2190 return None, None
2191
2192 # Check if this protocol supports set_members
2193 protocol_player = parent_player.get_protocol_player(parent_protocol.output_protocol_id)
2194 if (
2195 not protocol_player
2196 or PlayerFeature.SET_MEMBERS not in protocol_player.state.supported_features
2197 ):
2198 return None, None
2199
2200 return child_protocol.output_protocol_id, child_protocol.protocol_domain
2201
2202 def _can_use_native_grouping(
2203 self,
2204 child_player: Player,
2205 parent_player: Player,
2206 parent_supports_native: bool,
2207 ) -> bool:
2208 """Check if child can be grouped with parent using native grouping."""
2209 if not parent_supports_native:
2210 return False
2211 return (
2212 parent_player.is_native_group_compatible(child_player)
2213 or child_player.player_id in parent_player._attr_can_group_with
2214 or child_player.provider.instance_id in parent_player._attr_can_group_with
2215 )
2216
2217 def _try_find_common_protocol(
2218 self, child_player: Player, parent_player: Player
2219 ) -> tuple[OutputProtocol | None, OutputProtocol | None]:
2220 """
2221 Find common protocol that supports set_members.
2222
2223 Returns tuple of (parent_protocol, child_protocol) or (None, None).
2224 """
2225 for parent_output_protocol in parent_player.output_protocols:
2226 if not parent_output_protocol.available:
2227 continue
2228 child_protocol = child_player.get_output_protocol_by_domain(
2229 parent_output_protocol.protocol_domain
2230 )
2231 if not child_protocol or not child_protocol.available:
2232 continue
2233 protocol_player = parent_player.get_protocol_player(
2234 parent_output_protocol.output_protocol_id
2235 )
2236 if protocol_player and PlayerFeature.SET_MEMBERS in protocol_player.supported_features:
2237 return parent_output_protocol, child_protocol
2238 return None, None
2239
2240 def _parent_has_live_native_session(self, parent_player: Player) -> bool:
2241 """
2242 Return True when the parent currently holds a live native playback session.
2243
2244 The active output protocol lingers for a few seconds after stop, so a non-idle
2245 playback state is required to distinguish a real session from a just-stopped one.
2246 """
2247 return parent_player.active_output_protocol == "native" and (
2248 parent_player.state.playback_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
2249 )
2250
2251 def _order_members_for_native_join(
2252 self,
2253 player_ids: list[str],
2254 parent_player: Player,
2255 parent_supports_native_grouping: bool,
2256 ) -> list[str]:
2257 """
2258 Order members so a live native session can be joined without splitting the group.
2259
2260 When the parent already holds a live native session, children that cannot group
2261 natively are evaluated first: they may force a shared protocol for the whole group,
2262 and processing them before the native-capable children lets those join that same
2263 protocol instead of being stranded in a separate native sub-group. The order is left
2264 untouched when the parent is not playing natively, so fresh-group selection is unchanged.
2265
2266 :param player_ids: The member IDs to be added, in their original order.
2267 :param parent_player: The parent player being joined.
2268 :param parent_supports_native_grouping: Whether the parent can group natively.
2269 """
2270 if not self._parent_has_live_native_session(parent_player):
2271 return player_ids
2272 return sorted(
2273 player_ids,
2274 key=lambda pid: bool(
2275 (child := self.get_player(pid))
2276 and self._can_use_native_grouping(
2277 child, parent_player, parent_supports_native_grouping
2278 )
2279 ),
2280 )
2281
2282 def _try_join_active_native_session(
2283 self,
2284 child_player: Player,
2285 parent_player: Player,
2286 parent_protocol_domain: str | None,
2287 parent_supports_native_grouping: bool,
2288 native_members: list[str],
2289 ) -> bool:
2290 """
2291 Add the child to native_members if it can join the parent's active native session.
2292
2293 A child's preferred output protocol must only steer protocol selection when the child
2294 initiates its own playback; when it joins a parent that is already playing natively it
2295 should adopt native grouping if compatible, rather than forcing the whole group onto
2296 the child's preferred protocol. Skipped once a protocol has been selected for the group,
2297 so mixed batches stay cohesive on a single protocol.
2298
2299 :param child_player: The player being added to the group.
2300 :param parent_player: The parent player being joined.
2301 :param parent_protocol_domain: The protocol domain already selected for the group, if any.
2302 :param parent_supports_native_grouping: Whether the parent can group natively.
2303 :param native_members: The native members list to append to when the child joins.
2304 """
2305 if not (
2306 self._parent_has_live_native_session(parent_player)
2307 and not parent_protocol_domain
2308 and self._can_use_native_grouping(
2309 child_player, parent_player, parent_supports_native_grouping
2310 )
2311 ):
2312 return False
2313 native_members.append(child_player.player_id)
2314 self.logger.log(
2315 VERBOSE_LOG_LEVEL,
2316 "Joining parent's active native session for %s",
2317 child_player.state.name,
2318 )
2319 return True
2320
2321 def _translate_native_members_to_protocol(
2322 self, parent_player: Player, protocol_domain: str, member_ids: list[str]
2323 ) -> list[str]:
2324 """
2325 Translate natively grouped members onto the protocol domain the parent plays through.
2326
2327 Members that do not have that protocol cannot follow the parent at all and are
2328 dropped with a warning instead.
2329
2330 :param parent_player: The parent player the members are grouped with.
2331 :param protocol_domain: The protocol domain selected for the group.
2332 :param member_ids: The member IDs that were selected for native grouping.
2333 """
2334 translated: list[str] = []
2335 for member_id in member_ids:
2336 member_player = self.get_player(member_id)
2337 if not member_player:
2338 continue
2339 # a native group's members may be listed by their protocol player id
2340 if member_player.protocol_parent_id:
2341 member_player = self.get_player(member_player.protocol_parent_id) or member_player
2342 member_protocol = member_player.get_output_protocol_by_domain(protocol_domain)
2343 if not member_protocol or not member_protocol.available:
2344 self.logger.warning(
2345 "Cannot group %s with %s: the group plays through the %s protocol, "
2346 "which %s does not support",
2347 member_player.state.name,
2348 parent_player.state.name,
2349 protocol_domain,
2350 member_player.state.name,
2351 )
2352 continue
2353 # For native protocol players, use the member's player_id directly
2354 translated.append(
2355 member_player.player_id
2356 if member_protocol.is_native
2357 else member_protocol.output_protocol_id
2358 )
2359 self.logger.log(
2360 VERBOSE_LOG_LEVEL,
2361 "Moving %s from native grouping to the %s protocol",
2362 member_player.state.name,
2363 protocol_domain,
2364 )
2365 return translated
2366
2367 def _move_native_members_to_group_protocol(
2368 self,
2369 parent_player: Player,
2370 parent_protocol_player: Player | None,
2371 parent_protocol_domain: str | None,
2372 protocol_members: list[str],
2373 native_members: list[str],
2374 ) -> None:
2375 """
2376 Move the members selected for native grouping onto the protocol the group ended up on.
2377
2378 Does nothing unless the group ends up on one of the parent's protocols while the
2379 parent's native grouping needs the parent's own stream: only then do those members
2380 have no session left to attach to.
2381
2382 :param parent_player: The parent player being joined.
2383 :param parent_protocol_player: The protocol player selected for the group, if any.
2384 :param parent_protocol_domain: The protocol domain selected for the group, if any.
2385 :param protocol_members: The protocol member list the translated IDs are added to.
2386 :param native_members: The native member IDs, emptied when they are moved over.
2387 """
2388 if not (
2389 native_members
2390 and parent_protocol_domain
2391 and parent_protocol_player
2392 and parent_protocol_player.player_id != parent_player.player_id
2393 and parent_player.native_grouping_requires_own_stream
2394 ):
2395 return
2396 protocol_members.extend(
2397 self._translate_native_members_to_protocol(
2398 parent_player, parent_protocol_domain, native_members
2399 )
2400 )
2401 native_members.clear()
2402
2403 def _migrate_stranded_native_members(
2404 self,
2405 parent_player: Player,
2406 parent_protocol_player: Player,
2407 protocol_members: list[str],
2408 ) -> list[str]:
2409 """
2410 Move the native members that a switch to the given protocol strands onto that protocol.
2411
2412 Returns the member IDs that are still attached to the parent's own stream, so the
2413 caller can release them from it. Empty unless the parent renders that stream itself
2414 while its native grouping attaches the members to exactly that stream: only then are
2415 they left without anything to play.
2416
2417 :param parent_player: The parent player that is about to switch protocol.
2418 :param parent_protocol_player: The protocol player the parent will render through.
2419 :param protocol_members: The protocol member list the translated IDs are added to.
2420 """
2421 if parent_protocol_player.player_id == parent_player.player_id:
2422 return []
2423 if not parent_player.native_grouping_requires_own_stream:
2424 return []
2425 if parent_player.active_output_protocol not in (None, "native"):
2426 return []
2427 if parent_player.state.playback_state not in (PlaybackState.PLAYING, PlaybackState.PAUSED):
2428 return []
2429 stranded = [
2430 member_id
2431 for member_id in parent_player.group_members
2432 if member_id != parent_player.player_id
2433 ]
2434 for protocol_id in self._translate_native_members_to_protocol(
2435 parent_player, parent_protocol_player.provider.domain, stranded
2436 ):
2437 if protocol_id not in protocol_members:
2438 protocol_members.append(protocol_id)
2439 return stranded
2440
2441 async def _stop_native_session(
2442 self,
2443 parent_player: Player,
2444 parent_protocol_player: Player,
2445 stranded_native_members: list[str],
2446 ) -> None:
2447 """
2448 Release the given members from the parent's own stream and stop it.
2449
2450 :param parent_player: The parent player whose native session is handed over.
2451 :param parent_protocol_player: The protocol player taking the output over.
2452 :param stranded_native_members: The members to release, already migrated.
2453 """
2454 self.logger.debug(
2455 "Stopping the native session of %s before switching to %s, migrated members: %s",
2456 parent_player.state.name,
2457 parent_protocol_player.state.name,
2458 stranded_native_members,
2459 )
2460 # The members already joined the protocol group, so the native session only has to
2461 # release them and stop. Releasing them first also clears the native group, which
2462 # keeps a later native playback command from resurrecting it. Both calls take the
2463 # provider's own lock, so they must run one after the other.
2464 await parent_player.set_members(player_ids_to_remove=stranded_native_members)
2465 await parent_player.stop()
2466
2467 def _translate_members_for_protocols(
2468 self,
2469 parent_player: Player,
2470 player_ids: list[str],
2471 parent_protocol_player: Player | None,
2472 parent_protocol_domain: str | None,
2473 ) -> tuple[list[str], list[str], Player | None, str | None]:
2474 """
2475 Translate member IDs to protocol or native IDs.
2476
2477 The grouping method is picked per member, see _select_grouping_for_member.
2478
2479 Returns tuple of (protocol_members, native_members, protocol_player, protocol_domain).
2480 """
2481 protocol_members: list[str] = []
2482 native_members: list[str] = []
2483 parent_supports_native_grouping = (
2484 PlayerFeature.SET_MEMBERS in parent_player.supported_features
2485 )
2486 player_ids = self._order_members_for_native_join(
2487 player_ids, parent_player, parent_supports_native_grouping
2488 )
2489
2490 self.logger.log(
2491 VERBOSE_LOG_LEVEL,
2492 "Translating members for %s: parent_supports_native=%s, parent_protocol=%s (%s)",
2493 parent_player.state.name,
2494 parent_supports_native_grouping,
2495 parent_protocol_player.state.name if parent_protocol_player else "none",
2496 parent_protocol_domain or "none",
2497 )
2498
2499 for child_player_id in player_ids:
2500 child_player = self.get_player(child_player_id)
2501 if not child_player:
2502 continue
2503
2504 self.logger.log(
2505 VERBOSE_LOG_LEVEL,
2506 "Processing child %s (type=%s, protocols=%s)",
2507 child_player.state.name,
2508 child_player.state.type,
2509 [p.protocol_domain for p in child_player.output_protocols],
2510 )
2511
2512 parent_protocol_player, parent_protocol_domain = self._select_grouping_for_member(
2513 child_player,
2514 parent_player,
2515 parent_protocol_player,
2516 parent_protocol_domain,
2517 parent_supports_native_grouping,
2518 protocol_members,
2519 native_members,
2520 )
2521
2522 # Post-pass: the protocol selected for the group is only known once every child has
2523 # been processed, so the members picked for native grouping are corrected here.
2524 self._move_native_members_to_group_protocol(
2525 parent_player,
2526 parent_protocol_player,
2527 parent_protocol_domain,
2528 protocol_members,
2529 native_members,
2530 )
2531
2532 return protocol_members, native_members, parent_protocol_player, parent_protocol_domain
2533
2534 def _select_grouping_for_member(
2535 self,
2536 child_player: Player,
2537 parent_player: Player,
2538 parent_protocol_player: Player | None,
2539 parent_protocol_domain: str | None,
2540 parent_supports_native_grouping: bool,
2541 protocol_members: list[str],
2542 native_members: list[str],
2543 ) -> tuple[Player | None, str | None]:
2544 """
2545 Pick the grouping method for a single member and add it to the matching member list.
2546
2547 Selection priority when grouping:
2548 0. If the parent is already playing natively and the child can be grouped
2549 natively, join that native session (a child joining an existing group must
2550 not force the whole group onto its own preferred output protocol)
2551 1. Try child's preferred output protocol (from player settings)
2552 2. Try parent's active output protocol (if any and child supports it)
2553 3. Try native grouping (if parent and child are compatible)
2554 4. Search for common protocol that supports set_members
2555 5. Log warning if no option works
2556
2557 Returns the protocol player/domain the group is on, which the picked method may have
2558 changed.
2559
2560 :param child_player: The player being added to the group.
2561 :param parent_player: The parent player being joined.
2562 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2563 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2564 :param parent_supports_native_grouping: Whether the parent can group natively.
2565 :param protocol_members: The protocol member list to append to.
2566 :param native_members: The native member list to append to.
2567 """
2568 # Priority 0: The parent is already playing natively and the child can join
2569 # that native session directly - adopt it before considering the child's own
2570 # preferred output protocol.
2571 if self._try_join_active_native_session(
2572 child_player,
2573 parent_player,
2574 parent_protocol_domain,
2575 parent_supports_native_grouping,
2576 native_members,
2577 ):
2578 return parent_protocol_player, parent_protocol_domain
2579
2580 # Priority 0.5: a player that runs its own multiroom (e.g. a LinkPlay control shell)
2581 # keeps grouping on its native path rather than routing it through a linked protocol
2582 # that is merely its preferred playback output. Native compatibility still decides
2583 # whether this is possible, so an incompatible/cross-backend pair falls through.
2584 if child_player.prefer_native_grouping and self._can_use_native_grouping(
2585 child_player, parent_player, parent_supports_native_grouping
2586 ):
2587 native_members.append(child_player.player_id)
2588 self.logger.log(
2589 VERBOSE_LOG_LEVEL,
2590 "Using native grouping (preferred) for %s",
2591 child_player.state.name,
2592 )
2593 return parent_protocol_player, parent_protocol_domain
2594
2595 # Priority 1: the child's preferred output protocol
2596 grouped, parent_protocol_player, parent_protocol_domain = (
2597 self._try_group_via_preferred_protocol(
2598 child_player,
2599 parent_player,
2600 parent_protocol_player,
2601 parent_protocol_domain,
2602 protocol_members,
2603 )
2604 )
2605 if grouped:
2606 return parent_protocol_player, parent_protocol_domain
2607
2608 # Priority 2: the protocol the group is already on
2609 grouped, parent_protocol_player, parent_protocol_domain = (
2610 self._try_group_via_active_protocol(
2611 child_player,
2612 parent_protocol_player,
2613 parent_protocol_domain,
2614 protocol_members,
2615 )
2616 )
2617 if grouped:
2618 return parent_protocol_player, parent_protocol_domain
2619
2620 # Priority 3: native grouping
2621 if self._can_use_native_grouping(
2622 child_player, parent_player, parent_supports_native_grouping
2623 ):
2624 native_members.append(child_player.player_id)
2625 self.logger.log(
2626 VERBOSE_LOG_LEVEL,
2627 "Using native grouping for %s",
2628 child_player.state.name,
2629 )
2630 return parent_protocol_player, parent_protocol_domain
2631
2632 # Priority 4: a protocol both players share that supports set_members
2633 grouped, parent_protocol_player, parent_protocol_domain = (
2634 self._try_group_via_common_protocol(
2635 child_player,
2636 parent_player,
2637 parent_protocol_player,
2638 parent_protocol_domain,
2639 protocol_members,
2640 )
2641 )
2642 if grouped:
2643 return parent_protocol_player, parent_protocol_domain
2644
2645 # Priority 5: no option worked
2646 self.logger.warning(
2647 "Cannot group %s with %s: no compatible grouping method found "
2648 "(tried: child preferred protocol, parent active protocol, "
2649 "native grouping, common protocols)",
2650 child_player.state.name,
2651 parent_player.state.name,
2652 )
2653 return parent_protocol_player, parent_protocol_domain
2654
2655 def _try_group_via_preferred_protocol(
2656 self,
2657 child_player: Player,
2658 parent_player: Player,
2659 parent_protocol_player: Player | None,
2660 parent_protocol_domain: str | None,
2661 protocol_members: list[str],
2662 ) -> tuple[bool, Player | None, str | None]:
2663 """
2664 Try to group the child through the output protocol it prefers in its player settings.
2665
2666 Only used when the group is not on a protocol yet or is already on that same protocol.
2667 Returns whether the child was grouped, together with the protocol player/domain the
2668 group is on: the child's preferred protocol may become the group's protocol.
2669
2670 :param child_player: The player being added to the group.
2671 :param parent_player: The parent player being joined.
2672 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2673 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2674 :param protocol_members: The protocol member list to append to.
2675 """
2676 child_protocol_id, protocol_domain = self._try_child_preferred_protocol(
2677 child_player, parent_player
2678 )
2679 if not (
2680 child_protocol_id
2681 and protocol_domain
2682 and (not parent_protocol_domain or protocol_domain == parent_protocol_domain)
2683 ):
2684 return False, parent_protocol_player, parent_protocol_domain
2685
2686 if not parent_protocol_player or parent_protocol_domain != protocol_domain:
2687 parent_protocol = parent_player.get_output_protocol_by_domain(protocol_domain)
2688 if parent_protocol:
2689 parent_protocol_player = parent_player.get_protocol_player(
2690 parent_protocol.output_protocol_id
2691 )
2692 parent_protocol_domain = protocol_domain
2693 protocol_members.append(child_protocol_id)
2694 self.logger.log(
2695 VERBOSE_LOG_LEVEL,
2696 "Using child's preferred protocol %s for %s",
2697 protocol_domain,
2698 child_player.state.name,
2699 )
2700 return True, parent_protocol_player, parent_protocol_domain
2701
2702 def _try_group_via_active_protocol(
2703 self,
2704 child_player: Player,
2705 parent_protocol_player: Player | None,
2706 parent_protocol_domain: str | None,
2707 protocol_members: list[str],
2708 ) -> tuple[bool, Player | None, str | None]:
2709 """
2710 Try to group the child through the protocol the group is already on.
2711
2712 Returns whether the child was grouped, together with the protocol player/domain the
2713 group is on: the selection is dropped when that protocol cannot group members itself,
2714 so a later grouping method can select another one.
2715
2716 :param child_player: The player being added to the group.
2717 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2718 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2719 :param protocol_members: The protocol member list to append to.
2720 """
2721 if not parent_protocol_domain or not parent_protocol_player:
2722 return False, parent_protocol_player, parent_protocol_domain
2723
2724 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2725 self.logger.log(
2726 VERBOSE_LOG_LEVEL,
2727 "Parent's active protocol %s does not support SET_MEMBERS, "
2728 "will search for alternative",
2729 parent_protocol_domain,
2730 )
2731 # Drop the selection so a later grouping method can select a new protocol
2732 return False, None, None
2733
2734 child_protocol = child_player.get_output_protocol_by_domain(parent_protocol_domain)
2735 if not child_protocol or not child_protocol.available:
2736 return False, parent_protocol_player, parent_protocol_domain
2737
2738 # For native protocol players, use the child's player_id directly
2739 # (e.g., a native sendspin web player IS the protocol player)
2740 child_protocol_id = (
2741 child_player.player_id
2742 if child_protocol.is_native
2743 else child_protocol.output_protocol_id
2744 )
2745 protocol_members.append(child_protocol_id)
2746 self.logger.log(
2747 VERBOSE_LOG_LEVEL,
2748 "Using parent's active protocol %s for %s",
2749 parent_protocol_domain,
2750 child_player.state.name,
2751 )
2752 return True, parent_protocol_player, parent_protocol_domain
2753
2754 def _try_group_via_common_protocol(
2755 self,
2756 child_player: Player,
2757 parent_player: Player,
2758 parent_protocol_player: Player | None,
2759 parent_protocol_domain: str | None,
2760 protocol_members: list[str],
2761 ) -> tuple[bool, Player | None, str | None]:
2762 """
2763 Try to group the child through a protocol both players share.
2764
2765 Returns whether the child was grouped, together with the protocol player/domain the
2766 group is on: the shared protocol may become the group's protocol.
2767
2768 :param child_player: The player being added to the group.
2769 :param parent_player: The parent player being joined.
2770 :param parent_protocol_player: The protocol player selected for the group so far, if any.
2771 :param parent_protocol_domain: The protocol domain selected for the group so far, if any.
2772 :param protocol_members: The protocol member list to append to.
2773 """
2774 parent_protocol, child_protocol = self._try_find_common_protocol(
2775 child_player, parent_player
2776 )
2777 if not parent_protocol or not child_protocol:
2778 return False, parent_protocol_player, parent_protocol_domain
2779
2780 if not parent_protocol_player or parent_protocol_domain != parent_protocol.protocol_domain:
2781 parent_protocol_player = parent_player.get_protocol_player(
2782 parent_protocol.output_protocol_id
2783 )
2784 if parent_protocol_player:
2785 parent_protocol_domain = parent_protocol_player.provider.domain
2786 # For native protocol players, use the child's player_id directly
2787 child_protocol_id = (
2788 child_player.player_id
2789 if child_protocol.is_native
2790 else child_protocol.output_protocol_id
2791 )
2792 protocol_members.append(child_protocol_id)
2793 self.logger.log(
2794 VERBOSE_LOG_LEVEL,
2795 "Selected common protocol %s for grouping %s with %s",
2796 parent_protocol.protocol_domain,
2797 child_player.state.name,
2798 parent_player.state.name,
2799 )
2800 return True, parent_protocol_player, parent_protocol_domain
2801
2802 async def _forward_protocol_set_members(
2803 self,
2804 parent_player: Player,
2805 parent_protocol_player: Player,
2806 protocol_members_to_add: list[str],
2807 protocol_members_to_remove: list[str],
2808 ) -> None:
2809 """
2810 Forward protocol members to protocol player's set_members and manage active output protocol.
2811
2812 :param parent_player: The parent player (native/universal).
2813 :param parent_protocol_player: The protocol player to forward commands to.
2814 :param protocol_members_to_add: Protocol player IDs to add.
2815 :param protocol_members_to_remove: Protocol player IDs to remove.
2816 """
2817 filtered_protocol_add = self._filter_protocol_members(
2818 protocol_members_to_add, parent_protocol_player
2819 )
2820 filtered_protocol_remove = self._filter_protocol_members(
2821 protocol_members_to_remove, parent_protocol_player
2822 )
2823 self.logger.debug(
2824 "Protocol grouping on %s: filtered_add=%s, filtered_remove=%s",
2825 parent_protocol_player.state.name,
2826 filtered_protocol_add,
2827 filtered_protocol_remove,
2828 )
2829
2830 if not filtered_protocol_add and not filtered_protocol_remove:
2831 return
2832
2833 # Safety check: verify protocol player supports SET_MEMBERS
2834 if PlayerFeature.SET_MEMBERS not in parent_protocol_player.state.supported_features:
2835 self.logger.error(
2836 "Protocol player %s does not support SET_MEMBERS, cannot perform grouping. "
2837 "This should have been caught earlier in the flow.",
2838 parent_protocol_player.state.name,
2839 )
2840 return
2841
2842 # Members that ride the parent's own stream are stranded by the protocol switch below,
2843 # so they join the protocol group in this very same call and their native session is
2844 # torn down afterwards.
2845 stranded_native_members = (
2846 self._migrate_stranded_native_members(
2847 parent_player, parent_protocol_player, filtered_protocol_add
2848 )
2849 if filtered_protocol_add
2850 else []
2851 )
2852
2853 # This runs before set_members because a member's own stream starts inside that call
2854 # and the provider resolves the member's volume control as it starts: unless its parent
2855 # already points at this protocol, that resolution picks a sibling interface of the same
2856 # device (e.g. its cast side) over the one carrying the audio.
2857 self._activate_protocol_on_added_children(filtered_protocol_add)
2858
2859 self.logger.debug(
2860 "Calling set_members on protocol player %s with add=%s, remove=%s",
2861 parent_protocol_player.state.name,
2862 filtered_protocol_add,
2863 filtered_protocol_remove,
2864 )
2865 await parent_protocol_player.set_members(
2866 player_ids_to_add=filtered_protocol_add or None,
2867 player_ids_to_remove=filtered_protocol_remove or None,
2868 )
2869
2870 if filtered_protocol_add:
2871 await self._activate_group_output_protocol(
2872 parent_player, parent_protocol_player, stranded_native_members
2873 )
2874
2875 self.logger.debug(
2876 "After set_members, protocol player %s state: group_members=%s, synced_to=%s",
2877 parent_protocol_player.state.name,
2878 parent_protocol_player.group_members,
2879 parent_protocol_player.synced_to,
2880 )
2881
2882 def _activate_protocol_on_added_children(self, protocol_member_ids: list[str]) -> None:
2883 """
2884 Point the parent of each given protocol member at the protocol carrying the group audio.
2885
2886 :param protocol_member_ids: The protocol player IDs joining the group.
2887 """
2888 for child_protocol_id in protocol_member_ids:
2889 if not (child_protocol := self.get_player(child_protocol_id)):
2890 continue
2891 if not child_protocol.protocol_parent_id:
2892 continue
2893 if not (child_player := self.get_player(child_protocol.protocol_parent_id)):
2894 continue
2895 if child_player.active_output_protocol == child_protocol_id:
2896 continue
2897 self.logger.debug(
2898 "Setting active output protocol on child %s to %s",
2899 child_player.state.name,
2900 child_protocol_id,
2901 )
2902 child_player.set_active_output_protocol(child_protocol_id)
2903
2904 async def _activate_group_output_protocol(
2905 self,
2906 parent_player: Player,
2907 parent_protocol_player: Player,
2908 stranded_native_members: list[str],
2909 ) -> None:
2910 """
2911 Mark the given protocol as the parent's output and hand the playback over to it.
2912
2913 The handover only runs when the parent is actually switching protocol while it is
2914 rendering; playback is resumed only for a parent that was playing, so adding a member
2915 never starts playback on its own.
2916
2917 :param parent_player: The parent player that just gained protocol members.
2918 :param parent_protocol_player: The protocol player the members joined.
2919 :param stranded_native_members: The members left without a stream by the switch.
2920 """
2921 previous_protocol = parent_player.active_output_protocol
2922 was_playing = parent_player.state.playback_state == PlaybackState.PLAYING
2923 # A paused player still holds its output, so the handover has to run for it too.
2924 was_rendering = was_playing or parent_player.state.playback_state == PlaybackState.PAUSED
2925
2926 # Native protocol: parent_protocol_player is the same as parent_player
2927 is_native_protocol = parent_protocol_player.player_id == parent_player.player_id
2928 already_using_native = previous_protocol in (None, "native")
2929 already_using_this_protocol = previous_protocol == parent_protocol_player.player_id
2930 switching_protocols = not (
2931 (is_native_protocol and already_using_native) or already_using_this_protocol
2932 )
2933
2934 self.logger.debug(
2935 "Protocol grouping: is_native=%s, already_native=%s, already_this=%s, "
2936 "switching=%s, was_rendering=%s",
2937 is_native_protocol,
2938 already_using_native,
2939 already_using_this_protocol,
2940 switching_protocols,
2941 was_rendering,
2942 )
2943
2944 if not (is_native_protocol and already_using_native):
2945 parent_player.set_active_output_protocol(parent_protocol_player.player_id)
2946
2947 if not (was_rendering and switching_protocols):
2948 return
2949
2950 self.logger.info(
2951 "Handing the output of %s over to the %s protocol%s",
2952 parent_player.state.name,
2953 parent_protocol_player.provider.domain,
2954 " and resuming playback" if was_playing else "",
2955 )
2956 if stranded_native_members:
2957 await self._stop_native_session(
2958 parent_player, parent_protocol_player, stranded_native_members
2959 )
2960 old_parent_members = await self._stop_previous_protocol(
2961 parent_player, parent_protocol_player, previous_protocol
2962 )
2963 if was_playing:
2964 await self.mass.players.cmd_resume(parent_player.player_id)
2965 if old_parent_members:
2966 self.logger.debug(
2967 "Re-adding migrated members %s to %s on new protocol",
2968 old_parent_members,
2969 parent_player.state.name,
2970 )
2971 # Use internal handler because we are already inside a
2972 # _handle_set_members call chain that holds the play lock.
2973 await self.mass.players._handle_set_members(
2974 parent_player,
2975 player_ids_to_add=old_parent_members,
2976 )
2977
2978 async def _stop_previous_protocol(
2979 self,
2980 parent_player: Player,
2981 parent_protocol_player: Player,
2982 previous_protocol: str | None,
2983 ) -> list[str]:
2984 """
2985 Stop the protocol player the parent was rendering through and return its members.
2986
2987 The returned IDs are parent player IDs, so the caller can re-add them to the group
2988 once the new protocol carries the audio. Empty if there is nothing to hand over.
2989
2990 :param parent_player: The parent player that is switching protocol.
2991 :param parent_protocol_player: The protocol player taking the output over.
2992 :param previous_protocol: The parent's previous active output protocol, if any.
2993 """
2994 if previous_protocol in (None, "native"):
2995 return []
2996 if not (old_protocol_player := self.get_player(previous_protocol)):
2997 return []
2998 if old_protocol_player.player_id == parent_protocol_player.player_id:
2999 return []
3000 # Translate the old protocol's child members back to parent player IDs
3001 old_parent_members: list[str] = []
3002 for member_id in old_protocol_player.group_members:
3003 if member_id == old_protocol_player.player_id:
3004 continue
3005 if not (member_player := self.get_player(member_id)):
3006 continue
3007 parent_id = member_player.protocol_parent_id or member_id
3008 if parent_id != parent_player.player_id:
3009 old_parent_members.append(parent_id)
3010 self.logger.debug(
3011 "Stopping old protocol player %s before switching to %s, migrating members: %s",
3012 old_protocol_player.state.name,
3013 parent_protocol_player.state.name,
3014 old_parent_members,
3015 )
3016 # Use internal handler to stop the specific protocol player,
3017 # bypassing group/sync redirect and queue redirect logic.
3018 await self.mass.players._handle_cmd_stop(old_protocol_player.player_id)
3019 return old_parent_members
3020