/
/
/
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 self._attr_volume_level = round(status.volume_level * 100)
594 self._attr_volume_muted = status.volume_muted
595 self.update_state()
596 if self.on_app_status_changed is not None:
597 try:
598 self.on_app_status_changed(status.app_id)
599 except Exception:
600 self.logger.exception("Error in app status callback for %s", self.display_name)
601
602 def _handle_media_status(self, status: MediaStatus) -> None:
603 """Process MediaStatus on the event loop thread."""
604 self.logger.log(
605 VERBOSE_LOG_LEVEL,
606 "Received media status for %s update: %s",
607 self.display_name,
608 status.player_state,
609 )
610 # handle player playing from a group
611 group_player: ChromecastPlayer | None = None
612 if self.active_cast_group is not None:
613 player_obj = self.mass.players.get_player(self.active_cast_group)
614 if not isinstance(player_obj, ChromecastPlayer):
615 return
616 group_player = player_obj
617 status = group_player.cc.media_controller.status
618
619 # never surface the receiver's dashboard keepalive as actual playback
620 if status.content_id and status.content_id.endswith(DASHBOARD_KEEPALIVE_SUFFIXES):
621 self._reset_to_idle()
622 return
623
624 self._report_media_error(status, group_player)
625
626 # pychromecast reports BUFFERING as 'playing', so a Cast group that underruns the
627 # LIVE flow stream at EOF never goes idle. Treat that case as idle so the queue
628 # can resume/restart.
629 flow_underrun = (
630 status.player_state == MEDIA_PLAYER_STATE_BUFFERING and self._flow_stream_underrun()
631 )
632 is_playing = status.player_is_playing and not flow_underrun
633 is_idle = status.player_is_idle or flow_underrun
634
635 self._update_playback_state(status, is_playing)
636 self._update_elapsed_time(status, is_playing)
637 self._update_active_source(group_player)
638 self._update_current_media(status, is_idle)
639 self._update_multichannel_group_members()
640 self.update_state()
641
642 def _reset_to_idle(self) -> None:
643 """Drop all playback state and publish the player as idle."""
644 self._attr_playback_state = PlaybackState.IDLE
645 self._attr_current_media = None
646 self._attr_active_source = None
647 self._attr_elapsed_time = 0
648 self._attr_elapsed_time_last_updated = time.time()
649 self.update_state()
650
651 def _report_media_error(
652 self, status: MediaStatus, group_player: ChromecastPlayer | None
653 ) -> None:
654 """
655 Log a media error reported by the receiver, at most once per incident.
656
657 Such an error (e.g. after a failed LOAD) otherwise only shows as a silent
658 return to idle. Any other status ends the incident, so a later error is
659 reported again.
660
661 :param status: Media status as reported by the receiver.
662 :param group_player: Cast group player whose status is being followed, if any.
663 """
664 if not (status.player_is_idle and status.idle_reason == "ERROR"):
665 self._media_error_reported = False
666 return
667 # a group forwards its status to every member, so only the group
668 # player itself reports the error
669 if group_player is not None:
670 return
671 if self._media_error_reported or self._flow_stream_underrun():
672 return
673 self._media_error_reported = True
674 self.logger.warning(
675 "%s reported a media playback error for %s",
676 self.display_name,
677 status.content_id or "the loaded media",
678 )
679
680 def _update_playback_state(self, status: MediaStatus, is_playing: bool) -> None:
681 """
682 Apply the reported playback state, releasing the device once playback ended.
683
684 :param status: Media status as reported by the receiver.
685 :param is_playing: Whether the receiver is really playing audio.
686 """
687 prev_state = self._attr_playback_state
688 if is_playing:
689 self._attr_playback_state = PlaybackState.PLAYING
690 self.set_current_media(uri=status.content_id or "", clear_all=True)
691 elif status.player_is_paused:
692 self._attr_playback_state = PlaybackState.PAUSED
693 # dropped so the metadata update below builds a fresh PlayerMedia instead of
694 # merging the new track into the previous one, which only truthy fields replace
695 self._attr_current_media = None
696 else:
697 self._attr_playback_state = PlaybackState.IDLE
698 self._attr_current_media = None
699 if (
700 prev_state in (PlaybackState.PLAYING, PlaybackState.PAUSED)
701 and self.type != PlayerType.GROUP
702 and self.active_cast_group is None
703 ):
704 # Playback that ends on its own never gets a stop command (the queue ran
705 # out, or an announcement finished), so without this the device would stay
706 # claimed forever. A cast group is left alone: quitting its app is what its
707 # power control does, and a group member follows the group's session.
708 self._schedule_app_release()
709
710 def _update_elapsed_time(self, status: MediaStatus, is_playing: bool) -> None:
711 """
712 Apply the playback position reported by the receiver.
713
714 :param status: Media status as reported by the receiver.
715 :param is_playing: Whether the receiver is really playing audio.
716 """
717 self._attr_elapsed_time_last_updated = time.time()
718 self._attr_elapsed_time = (
719 status.adjusted_current_time if is_playing else status.current_time
720 )
721
722 def _update_active_source(self, group_player: ChromecastPlayer | None) -> None:
723 """
724 Apply the active source, exposing a foreign Cast app as a selectable source.
725
726 :param group_player: Cast group player whose status is being followed, if any.
727 """
728 if group_player:
729 self._attr_active_source = group_player.active_source or group_player.player_id
730 elif self.cc.app_id in (MASS_APP_ID, APP_MEDIA_RECEIVER, SENDSPIN_CAST_APP_ID):
731 self._attr_active_source = None
732 elif self.cc.app_id in (None, IDLE_APP_ID):
733 # a released device sits on its backdrop with no app running, which is
734 # not something the user can select as a source
735 self._attr_active_source = None
736 else:
737 app_name = self.cc.app_display_name or "Unknown App"
738 app_id = app_name.lower().replace(" ", "_")
739 self._attr_active_source = app_id
740 has_controls = app_name in ("Spotify", "Qobuz", "YouTube Music", "Deezer", "Tidal")
741 if not any(source.id == app_id for source in self._attr_source_list):
742 self._attr_source_list.append(
743 PlayerSource(
744 id=app_id,
745 name=app_name,
746 passive=True,
747 can_play_pause=has_controls,
748 can_seek=has_controls,
749 can_next_previous=has_controls,
750 )
751 )
752
753 def _update_current_media(self, status: MediaStatus, is_idle: bool) -> None:
754 """
755 Apply the media metadata reported by the receiver.
756
757 :param status: Media status as reported by the receiver.
758 :param is_idle: Whether the receiver has nothing playing.
759 """
760 if status.content_id and not is_idle:
761 self.set_current_media(
762 uri=status.content_id,
763 title=status.title,
764 artist=status.artist,
765 album=status.album_name,
766 image_url=status.images[0].url if status.images else None,
767 duration=int(status.duration) if status.duration is not None else None,
768 media_type=MediaType.TRACK,
769 )
770 else:
771 self._attr_current_media = None
772
773 def _update_multichannel_group_members(self) -> None:
774 """
775 Mirror this group's playback state onto its multichannel members.
776
777 A stereo pair within a cast group receives no updates from the group itself,
778 so its state has to be pushed out manually.
779 """
780 if self.type != PlayerType.GROUP or not self.powered:
781 return
782 for child_id in self.group_members:
783 if child := self.mass.players.get_player(child_id):
784 assert isinstance(child, ChromecastPlayer) # for type checking
785 if not child.cast_info.is_multichannel_group:
786 continue
787 child._attr_playback_state = self._attr_playback_state
788 child._attr_current_media = self._attr_current_media
789 child._attr_elapsed_time = self._attr_elapsed_time
790 child._attr_elapsed_time_last_updated = self._attr_elapsed_time_last_updated
791 child._attr_active_source = self.active_source
792 child.update_state()
793
794 def _handle_load_media_failed(self, queue_item_id: int, error_code: int) -> None:
795 """Process a failed media load on the event loop thread."""
796 self._media_error_reported = True
797 self.logger.warning(
798 "%s failed to load media (queue item %s): error %s (%s)",
799 self.display_name,
800 queue_item_id,
801 error_code,
802 MEDIA_PLAYER_ERROR_CODES.get(error_code, "unknown code"),
803 )
804
805 def _handle_connection_status(self, status: ConnectionStatus) -> None:
806 """Process ConnectionStatus on the event loop thread."""
807 self.logger.log(
808 VERBOSE_LOG_LEVEL,
809 "Received connection status update for %s - status: %s",
810 self.display_name,
811 status.status,
812 )
813
814 if status.status == CONNECTION_STATUS_DISCONNECTED:
815 self._attr_available = False
816 self.update_state()
817 if self.on_app_status_changed is not None:
818 try:
819 self.on_app_status_changed(None)
820 except Exception:
821 self.logger.exception("Error in app status callback for %s", self.display_name)
822 return
823
824 new_available = status.status == CONNECTION_STATUS_CONNECTED
825 if new_available != self.available:
826 self.logger.debug(
827 "[%s] Cast device availability changed: %s",
828 self.cast_info.friendly_name,
829 status.status,
830 )
831 self._attr_available = new_available
832 self._attr_device_info.model = self.cast_info.model_name
833 self._attr_device_info.manufacturer = self.cast_info.manufacturer or ""
834 # Groups share a member device's IP/MAC, skip to avoid false protocol matches
835 if not self.cast_info.is_audio_group:
836 self._attr_device_info.add_identifier(
837 IdentifierType.IP_ADDRESS, self.cast_info.host
838 )
839 if is_valid_mac_address(self.cast_info.mac_address):
840 self._attr_device_info.add_identifier(
841 IdentifierType.MAC_ADDRESS, self.cast_info.mac_address
842 )
843 self._attr_device_info.add_identifier(IdentifierType.UUID, str(self.cast_info.uuid))
844 self._attr_device_info.add_identifier(
845 IdentifierType.CAST_UUID, str(self.cast_info.uuid)
846 )
847 self.update_state()
848
849 if new_available and self.type == PlayerType.PLAYER:
850 # Poll current group status
851 provider = cast("ChromecastProvider", self.provider)
852 mz_mgr = provider.mz_mgr
853 assert mz_mgr is not None # for type checking
854 for group_uuid in mz_mgr.get_multizone_memberships(self.cast_info.uuid):
855 group_media_controller = mz_mgr.get_multizone_mediacontroller(UUID(group_uuid))
856 if not group_media_controller:
857 continue
858
859 def _create_cc_media_item(self, media: PlayerMedia, stream_url: str) -> dict[str, Any]:
860 """Create CC media item from MA PlayerMedia."""
861 # Always use LIVE stream type because MA streams are real-time encoded by FFmpeg,
862 # so they are not seekable and don't have a known content length.
863 stream_type = STREAM_TYPE_LIVE
864 metadata = {
865 "metadataType": 3,
866 "albumName": media.album or "",
867 "songName": media.title or "",
868 "artist": media.artist or "",
869 "title": media.title or "",
870 "images": [{"url": media.image_url}] if media.image_url else None,
871 }
872 file_ext = stream_url.split("?", maxsplit=1)[0].rsplit(".", maxsplit=1)[-1].lower()
873 return {
874 "contentId": stream_url,
875 "customData": {
876 "uri": media.uri,
877 "queue_item_id": media.queue_item_id or stream_url,
878 },
879 "contentType": f"audio/{file_ext}",
880 "streamType": stream_type,
881 "metadata": metadata,
882 "duration": media.stream_duration or media.duration,
883 }
884
885 def _flow_stream_underrun(self) -> bool:
886 """Return whether the active queue's flow stream has been fully consumed."""
887 # Resolve the queue-owning player: a Cast group child mirrors the group's
888 # status, and a Cast exposed as a protocol player is wrapped by a universal
889 # player that owns the queue. Only a native/standalone Cast owns its own queue.
890 queue_id = self.active_cast_group or self.protocol_parent_id or self.player_id
891 return self.mass.player_queues.flow_stream_finished(queue_id)
892