/
/
1"""Chromecast Player implementation."""
2
3from __future__ import annotations
4
5import asyncio
6import time
7from collections.abc import Callable
8from typing import TYPE_CHECKING, Any, cast
9from uuid import UUID
10
11if TYPE_CHECKING:
12 from music_assistant_models.config_entries import ConfigEntry
13
14from music_assistant_models.enums import (
15 IdentifierType,
16 MediaType,
17 PlaybackState,
18 PlayerFeature,
19 PlayerType,
20)
21from music_assistant_models.errors import PlayerUnavailableError
22from music_assistant_models.player import PlayerSource
23from pychromecast import IDLE_APP_ID
24from pychromecast.controllers.media import (
25 MEDIA_PLAYER_ERROR_CODES,
26 MEDIA_PLAYER_STATE_BUFFERING,
27 STREAM_TYPE_LIVE,
28)
29from pychromecast.controllers.multizone import MultizoneController
30from pychromecast.socket_client import CONNECTION_STATUS_CONNECTED, CONNECTION_STATUS_DISCONNECTED
31
32from music_assistant.constants import MASS_LOGO_ONLINE, VERBOSE_LOG_LEVEL
33from music_assistant.helpers.util import is_valid_mac_address
34from music_assistant.models.player import DeviceInfo, Player, PlayerMedia
35
36from .constants import (
37 APP_LAUNCH_TIMEOUT,
38 APP_MEDIA_RECEIVER,
39 APP_QUIT_DELAY,
40 CAST_PLAYER_CONFIG_ENTRIES,
41 CONF_ENTRY_SAMPLE_RATES_CAST,
42 CONF_ENTRY_SAMPLE_RATES_CAST_GROUP,
43 CONF_USE_MASS_APP,
44 DASHBOARD_KEEPALIVE_SUFFIXES,
45 MASS_APP_ID,
46 SENDSPIN_CAST_APP_ID,
47)
48from .helpers import CastStatusListener, ChromecastInfo
49
50if TYPE_CHECKING:
51 from pychromecast import Chromecast
52 from pychromecast.controllers.media import MediaStatus
53 from pychromecast.controllers.receiver import CastStatus
54 from pychromecast.socket_client import ConnectionStatus
55
56 from .provider import ChromecastProvider
57
58
59class ChromecastPlayer(Player):
60 """Chromecast Player."""
61
62 active_cast_group: str | None = None
63 # a quit that is already on the wire cannot be recalled, so a receiver that
64 # still reports our app is no longer proof that the session is usable
65 app_quit_sent: bool = False
66
67 def __init__(
68 self,
69 provider: ChromecastProvider,
70 player_id: str,
71 cast_info: ChromecastInfo,
72 chromecast: Chromecast,
73 ) -> None:
74 """Init."""
75 super().__init__(provider, player_id)
76 if cast_info.is_audio_group and cast_info.is_multichannel_group:
77 player_type = PlayerType.STEREO_PAIR
78 elif cast_info.is_audio_group:
79 player_type = PlayerType.GROUP
80 elif self._is_google_device(cast_info):
81 # Google devices (Chromecast, Nest, Google Home) have native Cast support
82 player_type = PlayerType.PLAYER
83 else:
84 # Non-Google devices are generic Chromecast receivers
85 # Will be wrapped in a UniversalPlayer
86 player_type = PlayerType.PROTOCOL
87 self.cc = chromecast
88 self.status_listener: CastStatusListener | None
89 self.cast_info = cast_info
90 self.mz_controller: MultizoneController | None = None
91 self.on_app_status_changed: Callable[[str | None], None] | None = None
92 self.last_poll = 0.0
93 self.last_multichannel_check = 0.0
94 self.flow_meta_checksum: str | None = None
95 self._app_quit_task_id: str = f"cast_quit_app_{player_id}"
96 self._media_error_reported = False
97 # set static variables
98 self._attr_supported_features = {
99 PlayerFeature.PLAY_MEDIA,
100 PlayerFeature.VOLUME_SET,
101 PlayerFeature.VOLUME_MUTE,
102 PlayerFeature.PAUSE,
103 PlayerFeature.NEXT_PREVIOUS,
104 PlayerFeature.ENQUEUE,
105 PlayerFeature.SEEK,
106 }
107 self._attr_name = self.cast_info.friendly_name
108 self._attr_available = False
109 self._attr_needs_poll = True
110 self._attr_type = player_type
111 # Disable TV's by default
112 # (can be enabled manually by the user)
113 enabled_by_default = True
114 for exclude in ("tv", "/12", "PUS", "OLED"):
115 if exclude.lower() in cast_info.friendly_name.lower():
116 enabled_by_default = False
117 self._attr_enabled_by_default = enabled_by_default
118
119 self._attr_device_info = DeviceInfo(
120 model=self.cast_info.model_name,
121 manufacturer=self.cast_info.manufacturer or "",
122 )
123 # add mac/IP identifiers for protocol-matching
124 # (but skip for groups since they don't have a real IP/MAC)
125 if not cast_info.is_audio_group:
126 self._attr_device_info.add_identifier(IdentifierType.IP_ADDRESS, self.cast_info.host)
127 # Only add MAC address if it's valid (not 00:00:00:00:00:00)
128 if is_valid_mac_address(self.cast_info.mac_address):
129 self._attr_device_info.add_identifier(
130 IdentifierType.MAC_ADDRESS, self.cast_info.mac_address
131 )
132 self._attr_device_info.add_identifier(IdentifierType.UUID, str(self.cast_info.uuid))
133 self._attr_device_info.add_identifier(IdentifierType.CAST_UUID, str(self.cast_info.uuid))
134 assert provider.mz_mgr is not None # for type checking
135 status_listener = CastStatusListener(self, provider.mz_mgr)
136 self.status_listener = status_listener
137 if player_type == PlayerType.GROUP:
138 mz_controller = MultizoneController(cast_info.uuid)
139 self.cc.register_handler(mz_controller)
140 self.mz_controller = mz_controller
141
142 async def async_setup(self) -> None:
143 """Start the chromecast socket client (must be called after __init__)."""
144 await asyncio.to_thread(self.cc.start)
145
146 async def get_config_entries(self) -> list[ConfigEntry]:
147 """Return all (provider/player specific) Config Entries for the given player (if any)."""
148 if self.type == PlayerType.GROUP:
149 return [
150 *CAST_PLAYER_CONFIG_ENTRIES,
151 CONF_ENTRY_SAMPLE_RATES_CAST_GROUP,
152 ]
153
154 return [
155 *CAST_PLAYER_CONFIG_ENTRIES,
156 CONF_ENTRY_SAMPLE_RATES_CAST,
157 ]
158
159 async def stop(self) -> None:
160 """Send STOP command to given player."""
161 if self.type == PlayerType.GROUP:
162 await asyncio.to_thread(self.cc.media_controller.stop)
163 return
164 if self.cc.app_id not in (MASS_APP_ID, APP_MEDIA_RECEIVER):
165 # another app is casting to the device, release it right away
166 await self._quit_app()
167 return
168 if self.cc.media_controller.status.media_session_id is not None:
169 # a stop is refused by the cast library when nothing was ever loaded
170 await asyncio.to_thread(self.cc.media_controller.stop)
171 self._schedule_app_release()
172
173 def cancel_pending_app_quit(self) -> None:
174 """Cancel a pending release of the receiver app, to keep the device claimed."""
175 self.mass.cancel_timer(self._app_quit_task_id)
176 # a quit that already fired runs as a task under the same id,
177 # which only cancel_task reaches
178 self.mass.cancel_task(self._app_quit_task_id)
179
180 async def play(self) -> None:
181 """Send PLAY command to given player."""
182 await asyncio.to_thread(self.cc.media_controller.play)
183
184 async def pause(self) -> None:
185 """Send PAUSE command to given player."""
186 await asyncio.to_thread(self.cc.media_controller.pause)
187
188 async def next_track(self) -> None:
189 """Handle NEXT TRACK command for given player."""
190 await asyncio.to_thread(self.cc.media_controller.queue_next)
191
192 async def previous_track(self) -> None:
193 """Handle PREVIOUS TRACK command for given player."""
194 await asyncio.to_thread(self.cc.media_controller.queue_prev)
195
196 async def seek(self, position: int) -> None:
197 """Handle SEEK command on the player."""
198 await asyncio.to_thread(self.cc.media_controller.seek, position)
199
200 async def power(self, powered: bool) -> None:
201 """Send POWER command to given player (only for Cast Groups)."""
202 if powered:
203 await self._launch_app()
204 self._attr_active_source = None
205 else:
206 self._attr_active_source = None
207 await self._quit_app()
208 # optimistically update the state
209 self.update_state()
210
211 async def volume_set(self, volume_level: int) -> None:
212 """Send VOLUME_SET command to given player."""
213 # Round to 2 decimal places to avoid floating-point precision issues
214 await asyncio.to_thread(self.cc.set_volume, round(volume_level / 100, 2))
215
216 async def volume_mute(self, muted: bool) -> None:
217 """Send VOLUME MUTE command to given player."""
218 await asyncio.to_thread(self.cc.set_volume_muted, muted)
219
220 async def play_media(
221 self,
222 media: PlayerMedia,
223 ) -> None:
224 """Handle PLAY MEDIA on given player."""
225 stream_url = await self.provider.mass.streams.resolve_stream_url(self.player_id, media)
226 queuedata = {
227 "type": "LOAD",
228 "media": self._create_cc_media_item(media, stream_url),
229 }
230 # make sure that our media controller app is launched
231 await self._launch_app()
232 # send queue info to the CC
233 media_controller = self.cc.media_controller
234 await asyncio.to_thread(media_controller.send_message, data=queuedata, inc_session_id=True)
235
236 async def enqueue_next_media(self, media: PlayerMedia) -> None:
237 """Handle enqueuing of the next item on the player."""
238 next_item_id = None
239 status = self.cc.media_controller.status
240 stream_url = await self.provider.mass.streams.resolve_stream_url(self.player_id, media)
241 # lookup position of current track in cast queue
242 cast_current_item_id = getattr(status, "current_item_id", 0)
243 cast_queue_items = getattr(status, "items", [])
244 cur_item_found = False
245 for item in cast_queue_items:
246 if item["itemId"] == cast_current_item_id:
247 cur_item_found = True
248 continue
249 if not cur_item_found:
250 continue
251 next_item_id = item["itemId"]
252 # check if the next queue item isn't already queued
253 if item.get("media", {}).get("customData", {}).get("uri") == stream_url:
254 return
255 queuedata = {
256 "type": "QUEUE_INSERT",
257 "insertBefore": next_item_id,
258 "items": [
259 {
260 "autoplay": True,
261 "startTime": 0,
262 "preloadTime": 0,
263 "media": self._create_cc_media_item(media, stream_url),
264 }
265 ],
266 }
267 media_controller = self.cc.media_controller
268 queuedata["mediaSessionId"] = media_controller.status.media_session_id
269 await asyncio.to_thread(media_controller.send_message, data=queuedata, inc_session_id=True)
270
271 async def poll(self) -> None:
272 """Poll player for state updates."""
273 # only update status of media controller if media controller is active
274 if not self.cc.media_controller.is_active:
275 return
276 try:
277 now = time.time()
278 if (now - self.last_poll) >= 60:
279 self.last_poll = now
280 await asyncio.to_thread(self.cc.media_controller.update_status)
281 except ConnectionResetError as err:
282 raise PlayerUnavailableError from err
283
284 async def on_unload(self) -> None:
285 """Handle logic when the player is unloaded from the Player controller."""
286 await super().on_unload()
287 self.cancel_pending_app_quit()
288 self.mz_controller = None
289 if self.status_listener is not None:
290 self.status_listener.invalidate()
291 self.status_listener = None
292 self.logger.debug("Disconnecting from chromecast socket %s", self.display_name)
293 if self.mass.closing:
294 # Non-blocking disconnect: close socket, don't wait for thread.
295 # Socket threads are daemon threads and die on process exit.
296 # Blocking disconnect can stall shutdown if threads are slow to exit.
297 self.cc.disconnect(0)
298 else:
299 await asyncio.to_thread(self.cc.disconnect, 10)
300
301 ### Callbacks from Chromecast Statuslistener
302
303 def on_new_cast_status(self, status: CastStatus) -> None:
304 """Handle updated CastStatus (called from pychromecast socket thread)."""
305 if status is None or self.mass.closing:
306 return
307 # Dispatch to event loop for thread-safe attribute mutation
308 self.mass.loop.call_soon_threadsafe(self._handle_cast_status, status)
309
310 def on_new_media_status(self, status: MediaStatus) -> None:
311 """Handle updated MediaStatus (called from pychromecast socket thread)."""
312 if self.mass.closing:
313 return
314 # Dispatch to event loop for thread-safe attribute mutation
315 self.mass.loop.call_soon_threadsafe(self._handle_media_status, status)
316
317 def on_load_media_failed(self, queue_item_id: int, error_code: int) -> None:
318 """Handle a failed media load (called from pychromecast socket thread)."""
319 if self.mass.closing:
320 return
321 self.mass.loop.call_soon_threadsafe(
322 self._handle_load_media_failed, queue_item_id, error_code
323 )
324
325 def on_new_connection_status(self, status: ConnectionStatus) -> None:
326 """Handle updated ConnectionStatus (called from pychromecast socket thread)."""
327 if self.mass.closing:
328 return
329 # Dispatch to event loop for thread-safe attribute mutation
330 self.mass.loop.call_soon_threadsafe(self._handle_connection_status, status)
331
332 def on_player_media_updated(self) -> None:
333 """Handle callback when the current media of the player is updated."""
334 if self.powered is False:
335 return
336 if not self.cc.media_controller.status.player_is_playing:
337 return
338 if self.active_cast_group:
339 return
340 if self._attr_playback_state != PlaybackState.PLAYING:
341 return
342 if not (current_media := self.state.current_media):
343 return
344 if not (
345 (self._attr_current_media and "/flow/" in self._attr_current_media.uri)
346 or current_media.media_type
347 in (
348 MediaType.RADIO,
349 MediaType.AUDIO_SOURCE,
350 )
351 ):
352 # only update metadata for streams without known duration
353 return
354
355 async def update_flow_metadata() -> None:
356 """Update the metadata of a cast player running the flow (or radio) stream."""
357 media_controller = self.cc.media_controller
358 # update metadata of current item chromecast
359 title = current_media.title or "Music Assistant"
360 artist = current_media.artist or ""
361 album = current_media.album or ""
362 image_url = current_media.image_url or MASS_LOGO_ONLINE
363 flow_meta_checksum = f"{current_media.uri}-{album}-{artist}-{title}-{image_url}"
364 if self.flow_meta_checksum != flow_meta_checksum:
365 # only update if something changed
366 self.flow_meta_checksum = flow_meta_checksum
367 queuedata = {
368 "type": "PLAY",
369 "mediaSessionId": media_controller.status.media_session_id,
370 "customData": {
371 "metadata": {
372 "metadataType": 3,
373 "albumName": album,
374 "songName": title,
375 "artist": artist,
376 "title": title,
377 "images": [{"url": image_url}],
378 }
379 },
380 }
381 await asyncio.to_thread(
382 media_controller.send_message, data=queuedata, inc_session_id=True
383 )
384
385 if len(getattr(media_controller.status, "items", [])) < 2:
386 # In flow mode, all queue tracks are sent to the player as continuous stream.
387 # add a special 'command' item to the queue
388 # this allows for on-player next buttons/commands to still work
389 cmd_next_url = self.mass.streams.get_command_url(self.player_id, "next")
390 msg = {
391 "type": "QUEUE_INSERT",
392 "mediaSessionId": media_controller.status.media_session_id,
393 "items": [
394 {
395 "media": {
396 "contentId": cmd_next_url,
397 "customData": {
398 "uri": cmd_next_url,
399 "queue_item_id": cmd_next_url,
400 },
401 "contentType": "audio/flac",
402 "streamType": STREAM_TYPE_LIVE,
403 "metadata": {},
404 },
405 "autoplay": True,
406 "startTime": 0,
407 "preloadTime": 0,
408 }
409 ],
410 }
411 await asyncio.to_thread(
412 media_controller.send_message, data=msg, inc_session_id=True
413 )
414
415 self.mass.create_task(update_flow_metadata())
416
417 @staticmethod
418 def _is_google_device(cast_info: ChromecastInfo) -> bool:
419 """
420 Check if a device is a Google device with native Cast support.
421
422 Google devices (Chromecast, Nest, Google Home) have native Cast support
423 and should be exposed as PlayerType.PLAYER. Non-Google devices with Cast
424 support should be exposed as PlayerType.PROTOCOL.
425 """
426 if not cast_info.manufacturer:
427 # If no manufacturer, check model name for Google devices
428 model = cast_info.model_name.lower() if cast_info.model_name else ""
429 return any(google in model for google in ("chromecast", "google", "nest", "home"))
430 return cast_info.manufacturer.lower() in ("google", "google inc.")
431
432 async def _launch_app(self) -> None:
433 """Launch the configured Media Receiver App on a Chromecast."""
434 self.cancel_pending_app_quit()
435 if self.config.get_value(CONF_USE_MASS_APP, True):
436 app_id = MASS_APP_ID
437 else:
438 app_id = APP_MEDIA_RECEIVER
439
440 # compare against the configured app, not any compatible one: otherwise the
441 # use_mass_app setting is ignored for as long as the other app is running.
442 # a sent quit clears the reported app id only once the receiver answers, so
443 # skipping the launch then would load into a session that is being torn down
444 if self.cc.app_id == app_id and not self.app_quit_sent:
445 return # the configured receiver app is already active
446
447 event = asyncio.Event()
448 launched = False
449
450 def launched_callback(success: bool, response: dict[str, Any] | None) -> None: # noqa: ARG001
451 nonlocal launched
452 launched = success
453 self.mass.loop.call_soon_threadsafe(event.set)
454
455 def launch() -> None:
456 self.logger.debug("Launching App %s.", app_id)
457 self.cc.socket_client.receiver_controller.launch_app(
458 app_id,
459 force_launch=True,
460 callback_function=launched_callback,
461 )
462
463 await self.mass.loop.run_in_executor(None, launch)
464 try:
465 await asyncio.wait_for(event.wait(), timeout=APP_LAUNCH_TIMEOUT)
466 except TimeoutError:
467 # pychromecast resolves the launch callback only on a reply with a matching
468 # request id, so an ignored LAUNCH never completes on its own.
469 self._log_launch_failure(app_id, "the receiver did not respond")
470 raise PlayerUnavailableError(
471 f"Timed out launching app on {self.display_name}",
472 translation_key="app_launch_timeout",
473 translation_owner=self.translation_owner,
474 translation_args=[self.display_name],
475 ) from None
476
477 if not launched:
478 # not via register_launch_error_listener: a registered listener makes
479 # pychromecast skip its retry of a CANCELLED launch
480 failure = self.cc.socket_client.receiver_controller.launch_failure
481 reason = getattr(failure, "reason", None) or "no reason given"
482 self._log_launch_failure(app_id, reason)
483 raise PlayerUnavailableError(
484 f"Launching app on {self.display_name} was refused: {reason}",
485 translation_key="app_launch_refused",
486 translation_owner=self.translation_owner,
487 translation_args=[self.display_name],
488 )
489
490 if self.cc.app_id != app_id:
491 # a receiver can acknowledge the launch without starting the app;
492 # pychromecast applies the status before the callback, so app_id is current
493 self._log_launch_failure(app_id, "the receiver did not start the app")
494 raise PlayerUnavailableError(
495 f"App did not start on {self.display_name}",
496 translation_key="app_launch_refused",
497 translation_owner=self.translation_owner,
498 translation_args=[self.display_name],
499 )
500
501 self.app_quit_sent = False
502
503 def _log_launch_failure(self, app_id: str, reason: str) -> None:
504 """
505 Log a failed receiver app launch and which config option to try instead.
506
507 :param app_id: Cast application id that failed to launch.
508 :param reason: Why the launch failed, as reported by the receiver.
509 """
510 # Cast emulators in TV boxes and phone apps often implement only one of the two
511 # receiver apps, so the opposite setting is the first thing to try.
512 suggestion = "disabling" if app_id == MASS_APP_ID else "enabling"
513 self.logger.warning(
514 "%s did not launch app %s: %s. If this player keeps failing to start "
515 "playback, try %s the 'Use Music Assistant Cast App' option in its settings.",
516 self.display_name,
517 app_id,
518 reason,
519 suggestion,
520 )
521
522 def _schedule_app_release(self) -> None:
523 """
524 Arm the delayed release of the Cast device.
525
526 The device is released a bit later so a follow-up command (such as an
527 announcement, which stops playback first) can reuse the Cast session.
528 Starting a new session makes the device play its 'cast connected' chime.
529 """
530 self.mass.call_later(
531 APP_QUIT_DELAY, self._quit_app_when_unused, task_id=self._app_quit_task_id
532 )
533
534 async def _quit_app_when_unused(self) -> None:
535 """Release the Cast device, unless the receiver app got used again."""
536 if not self.available:
537 return # the device dropped off in the meantime
538 if self.cc.app_id not in (MASS_APP_ID, APP_MEDIA_RECEIVER):
539 return # another app took over the device
540 status = self.cc.media_controller.status
541 # a device that ran dry at the end of the flow stream keeps reporting buffering,
542 # which counts as playing. no audio is coming for it, so it is not really in use.
543 ran_dry = (
544 status.player_state == MEDIA_PLAYER_STATE_BUFFERING and self._flow_stream_underrun()
545 )
546 if (status.player_is_playing or status.player_is_paused) and not ran_dry:
547 # something is loaded again, e.g. the keepalive media of a dashboard
548 return
549 await self._quit_app()
550
551 async def _quit_app(self) -> None:
552 """Release the Cast device, so a follow-up launch is not skipped as unnecessary."""
553 # a receiver reports our app as running until it answers the quit, and an
554 # unanswered one leaves it reported for the full request timeout
555 self.app_quit_sent = True
556 await asyncio.to_thread(self.cc.quit_app)
557
558 def _handle_cast_status(self, status: CastStatus) -> None:
559 """Process CastStatus on the event loop thread."""
560 if self.mass.closing:
561 return
562 self.logger.log(
563 VERBOSE_LOG_LEVEL,
564 "Received cast status for %s - app_id: %s - volume: %s",
565 self.display_name,
566 status.app_id,
567 status.volume_level,
568 )
569 # handle stereo pairs
570 if self.cast_info.is_multichannel_group:
571 self._attr_type = PlayerType.STEREO_PAIR
572 self._attr_group_members.clear()
573 # handle cast groups
574 if self.cast_info.is_audio_group and not self.cast_info.is_multichannel_group:
575 assert self.mz_controller is not None # for type checking
576 self._attr_type = PlayerType.GROUP
577 self._attr_group_members = [str(UUID(x)) for x in self.mz_controller.members]
578 self._attr_static_group_members = self._attr_group_members.copy()
579 self._attr_supported_features = {
580 PlayerFeature.PLAY_MEDIA,
581 # only cast groups can be powered on/off as a group,
582 # so only add the POWER feature for groups
583 PlayerFeature.POWER,
584 PlayerFeature.VOLUME_SET,
585 PlayerFeature.VOLUME_MUTE,
586 PlayerFeature.PAUSE,
587 PlayerFeature.ENQUEUE,
588 }
589 self._attr_powered = self.cc.app_id is not None and self.cc.app_id != IDLE_APP_ID
590
591 # update player status
592 self._attr_name = self.cast_info.friendly_name
593 # A combo device exposes this cast endpoint next to its own protocol and can
594 # report volume 0 over it while its real volume is set through that other
595 # interface, so keep that unknown instead of reporting a hard mute. A cast
596 # device that is a player in its own right always reports its own volume.
597 volume_level = round(status.volume_level * 100)
598 cast_idle = self.cc.app_id in (None, IDLE_APP_ID)
599 self._attr_volume_level = (
600 None
601 if cast_idle and volume_level == 0 and self.type == PlayerType.PROTOCOL
602 else volume_level
603 )
604 self._attr_volume_muted = status.volume_muted
605 self.update_state()
606 if self.on_app_status_changed is not None:
607 try:
608 self.on_app_status_changed(status.app_id)
609 except Exception:
610 self.logger.exception("Error in app status callback for %s", self.display_name)
611
612 def _handle_media_status(self, status: MediaStatus) -> None:
613 """Process MediaStatus on the event loop thread."""
614 self.logger.log(
615 VERBOSE_LOG_LEVEL,
616 "Received media status for %s update: %s",
617 self.display_name,
618 status.player_state,
619 )
620 # handle player playing from a group
621 group_player: ChromecastPlayer | None = None
622 if self.active_cast_group is not None:
623 player_obj = self.mass.players.get_player(self.active_cast_group)
624 if not isinstance(player_obj, ChromecastPlayer):
625 return
626 group_player = player_obj
627 status = group_player.cc.media_controller.status
628
629 # never surface the receiver's dashboard keepalive as actual playback
630 if status.content_id and status.content_id.endswith(DASHBOARD_KEEPALIVE_SUFFIXES):
631 self._reset_to_idle()
632 return
633
634 self._report_media_error(status, group_player)
635
636 # pychromecast reports BUFFERING as 'playing', so a Cast group that underruns the
637 # LIVE flow stream at EOF never goes idle. Treat that case as idle so the queue
638 # can resume/restart.
639 flow_underrun = (
640 status.player_state == MEDIA_PLAYER_STATE_BUFFERING and self._flow_stream_underrun()
641 )
642 is_playing = status.player_is_playing and not flow_underrun
643 is_idle = status.player_is_idle or flow_underrun
644
645 self._update_playback_state(status, is_playing)
646 self._update_elapsed_time(status, is_playing)
647 self._update_active_source(group_player)
648 self._update_current_media(status, is_idle)
649 self._update_multichannel_group_members()
650 self.update_state()
651
652 def _reset_to_idle(self) -> None:
653 """Drop all playback state and publish the player as idle."""
654 self._attr_playback_state = PlaybackState.IDLE
655 self._attr_current_media = None
656 self._attr_active_source = None
657 self._attr_elapsed_time = 0
658 self._attr_elapsed_time_last_updated = time.time()
659 self.update_state()
660
661 def _report_media_error(
662 self, status: MediaStatus, group_player: ChromecastPlayer | None
663 ) -> None:
664 """
665 Log a media error reported by the receiver, at most once per incident.
666
667 Such an error (e.g. after a failed LOAD) otherwise only shows as a silent
668 return to idle. Any other status ends the incident, so a later error is
669 reported again.
670
671 :param status: Media status as reported by the receiver.
672 :param group_player: Cast group player whose status is being followed, if any.
673 """
674 if not (status.player_is_idle and status.idle_reason == "ERROR"):
675 self._media_error_reported = False
676 return
677 # a group forwards its status to every member, so only the group
678 # player itself reports the error
679 if group_player is not None:
680 return
681 if self._media_error_reported or self._flow_stream_underrun():
682 return
683 self._media_error_reported = True
684 self.logger.warning(
685 "%s reported a media playback error for %s",
686 self.display_name,
687 status.content_id or "the loaded media",
688 )
689
690 def _update_playback_state(self, status: MediaStatus, is_playing: bool) -> None:
691 """
692 Apply the reported playback state, releasing the device once playback ended.
693
694 :param status: Media status as reported by the receiver.
695 :param is_playing: Whether the receiver is really playing audio.
696 """
697 prev_state = self._attr_playback_state
698 if is_playing:
699 self._attr_playback_state = PlaybackState.PLAYING
700 self.set_current_media(uri=status.content_id or "", clear_all=True)
701 elif status.player_is_paused:
702 self._attr_playback_state = PlaybackState.PAUSED
703 # dropped so the metadata update below builds a fresh PlayerMedia instead of
704 # merging the new track into the previous one, which only truthy fields replace
705 self._attr_current_media = None
706 else:
707 self._attr_playback_state = PlaybackState.IDLE
708 self._attr_current_media = None
709 if (
710 prev_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
711 and self.type != PlayerType.GROUP
712 and self.active_cast_group is None
713 ):
714 # Playback that ends on its own never gets a stop command (the queue ran
715 # out, or an announcement finished), so without this the device would stay
716 # claimed forever. A cast group is left alone: quitting its app is what its
717 # power control does, and a group member follows the group's session.
718 self._schedule_app_release()
719
720 def _update_elapsed_time(self, status: MediaStatus, is_playing: bool) -> None:
721 """
722 Apply the playback position reported by the receiver.
723
724 :param status: Media status as reported by the receiver.
725 :param is_playing: Whether the receiver is really playing audio.
726 """
727 self._attr_elapsed_time_last_updated = time.time()
728 self._attr_elapsed_time = (
729 status.adjusted_current_time if is_playing else status.current_time
730 )
731
732 def _update_active_source(self, group_player: ChromecastPlayer | None) -> None:
733 """
734 Apply the active source, exposing a foreign Cast app as a selectable source.
735
736 :param group_player: Cast group player whose status is being followed, if any.
737 """
738 if group_player:
739 self._attr_active_source = group_player.active_source or group_player.player_id
740 elif self.cc.app_id in (MASS_APP_ID, APP_MEDIA_RECEIVER, SENDSPIN_CAST_APP_ID):
741 self._attr_active_source = None
742 elif self.cc.app_id in (None, IDLE_APP_ID):
743 # a released device sits on its backdrop with no app running, which is
744 # not something the user can select as a source
745 self._attr_active_source = None
746 else:
747 app_name = self.cc.app_display_name or "Unknown App"
748 app_id = app_name.lower().replace(" ", "_")
749 self._attr_active_source = app_id
750 has_controls = app_name in ("Spotify", "Qobuz", "YouTube Music", "Deezer", "Tidal")
751 if not any(source.id == app_id for source in self._attr_source_list):
752 self._attr_source_list.append(
753 PlayerSource(
754 id=app_id,
755 name=app_name,
756 passive=True,
757 can_play_pause=has_controls,
758 can_seek=has_controls,
759 can_next_previous=has_controls,
760 )
761 )
762
763 def _update_current_media(self, status: MediaStatus, is_idle: bool) -> None:
764 """
765 Apply the media metadata reported by the receiver.
766
767 :param status: Media status as reported by the receiver.
768 :param is_idle: Whether the receiver has nothing playing.
769 """
770 if status.content_id and not is_idle:
771 self.set_current_media(
772 uri=status.content_id,
773 title=status.title,
774 artist=status.artist,
775 album=status.album_name,
776 image_url=status.images[0].url if status.images else None,
777 duration=int(status.duration) if status.duration is not None else None,
778 media_type=MediaType.TRACK,
779 )
780 else:
781 self._attr_current_media = None
782
783 def _update_multichannel_group_members(self) -> None:
784 """
785 Mirror this group's playback state onto its multichannel members.
786
787 A stereo pair within a cast group receives no updates from the group itself,
788 so its state has to be pushed out manually.
789 """
790 if self.type != PlayerType.GROUP or not self.powered:
791 return
792 for child_id in self.group_members:
793 if child := self.mass.players.get_player(child_id):
794 assert isinstance(child, ChromecastPlayer) # for type checking
795 if not child.cast_info.is_multichannel_group:
796 continue
797 child._attr_playback_state = self._attr_playback_state
798 child._attr_current_media = self._attr_current_media
799 child._attr_elapsed_time = self._attr_elapsed_time
800 child._attr_elapsed_time_last_updated = self._attr_elapsed_time_last_updated
801 child._attr_active_source = self.active_source
802 child.update_state()
803
804 def _handle_load_media_failed(self, queue_item_id: int, error_code: int) -> None:
805 """Process a failed media load on the event loop thread."""
806 self._media_error_reported = True
807 self.logger.warning(
808 "%s failed to load media (queue item %s): error %s (%s)",
809 self.display_name,
810 queue_item_id,
811 error_code,
812 MEDIA_PLAYER_ERROR_CODES.get(error_code, "unknown code"),
813 )
814
815 def _handle_connection_status(self, status: ConnectionStatus) -> None:
816 """Process ConnectionStatus on the event loop thread."""
817 self.logger.log(
818 VERBOSE_LOG_LEVEL,
819 "Received connection status update for %s - status: %s",
820 self.display_name,
821 status.status,
822 )
823
824 if status.status == CONNECTION_STATUS_DISCONNECTED:
825 self._attr_available = False
826 self.update_state()
827 if self.on_app_status_changed is not None:
828 try:
829 self.on_app_status_changed(None)
830 except Exception:
831 self.logger.exception("Error in app status callback for %s", self.display_name)
832 return
833
834 new_available = status.status == CONNECTION_STATUS_CONNECTED
835 if new_available != self.available:
836 self.logger.debug(
837 "[%s] Cast device availability changed: %s",
838 self.cast_info.friendly_name,
839 status.status,
840 )
841 self._attr_available = new_available
842 self._attr_device_info.model = self.cast_info.model_name
843 self._attr_device_info.manufacturer = self.cast_info.manufacturer or ""
844 # Groups share a member device's IP/MAC, skip to avoid false protocol matches
845 if not self.cast_info.is_audio_group:
846 self._attr_device_info.add_identifier(
847 IdentifierType.IP_ADDRESS, self.cast_info.host
848 )
849 if is_valid_mac_address(self.cast_info.mac_address):
850 self._attr_device_info.add_identifier(
851 IdentifierType.MAC_ADDRESS, self.cast_info.mac_address
852 )
853 self._attr_device_info.add_identifier(IdentifierType.UUID, str(self.cast_info.uuid))
854 self._attr_device_info.add_identifier(
855 IdentifierType.CAST_UUID, str(self.cast_info.uuid)
856 )
857 self.update_state()
858
859 if new_available and self.type == PlayerType.PLAYER:
860 # Poll current group status
861 provider = cast("ChromecastProvider", self.provider)
862 mz_mgr = provider.mz_mgr
863 assert mz_mgr is not None # for type checking
864 for group_uuid in mz_mgr.get_multizone_memberships(self.cast_info.uuid):
865 group_media_controller = mz_mgr.get_multizone_mediacontroller(UUID(group_uuid))
866 if not group_media_controller:
867 continue
868
869 def _create_cc_media_item(self, media: PlayerMedia, stream_url: str) -> dict[str, Any]:
870 """Create CC media item from MA PlayerMedia."""
871 # Always use LIVE stream type because MA streams are real-time encoded by FFmpeg,
872 # so they are not seekable and don't have a known content length.
873 stream_type = STREAM_TYPE_LIVE
874 metadata = {
875 "metadataType": 3,
876 "albumName": media.album or "",
877 "songName": media.title or "",
878 "artist": media.artist or "",
879 "title": media.title or "",
880 "images": [{"url": media.image_url}] if media.image_url else None,
881 }
882 file_ext = stream_url.split("?", maxsplit=1)[0].rsplit(".", maxsplit=1)[-1].lower()
883 return {
884 "contentId": stream_url,
885 "customData": {
886 "uri": media.uri,
887 "queue_item_id": media.queue_item_id or stream_url,
888 },
889 "contentType": f"audio/{file_ext}",
890 "streamType": stream_type,
891 "metadata": metadata,
892 "duration": media.stream_duration or media.duration,
893 }
894
895 def _flow_stream_underrun(self) -> bool:
896 """Return whether the active queue's flow stream has been fully consumed."""
897 # Resolve the queue-owning player: a Cast group child mirrors the group's
898 # status, and a Cast exposed as a protocol player is wrapped by a universal
899 # player that owns the queue. Only a native/standalone Cast owns its own queue.
900 queue_id = self.active_cast_group or self.protocol_parent_id or self.player_id
901 return self.mass.player_queues.flow_stream_finished(queue_id)
902