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