/
/
1"""
2MA-facing provider logic for the Spotify Connect plugin.
3
4The provider owns everything Music Assistant sees: the AudioSource, stream
5details, target-player selection, playback claims and volume policy. It is
6backend-agnostic: all Spotify specifics live behind the
7``SpotifyConnectBackend`` contract and reach the provider as normalized
8``BackendEvent``s.
9"""
10
11from __future__ import annotations
12
13import asyncio
14import time
15from typing import TYPE_CHECKING, Final, cast
16
17from music_assistant_models.config_entries import ConfigEntry, ConfigValueOption
18from music_assistant_models.enums import (
19 ConfigEntryType,
20 MediaType,
21 PlaybackState,
22 ProviderFeature,
23 RepeatMode,
24 SourceControl,
25)
26from music_assistant_models.errors import AudioError, LoginFailed, MediaNotFoundError
27from music_assistant_models.media_items import (
28 AudioSource,
29 ProviderMapping,
30)
31from music_assistant_models.streamdetails import StreamDetails, StreamMetadata
32
33from music_assistant.constants import CONF_CROSSFADE_DURATION, CONF_ENTRY_WARN_PREVIEW
34from music_assistant.models.plugin import PluginProvider, SourceControlValue
35
36from .base import (
37 AUDIO_QUALITY_LOSSLESS,
38 AUDIO_QUALITY_OPTIONS,
39)
40from .go_librespot import GoLibrespotBackend
41from .models import BackendEventType
42from .soloist import VOLUME_MODE_PLAYER_ONLY, VOLUME_MODE_SYNC_SPOTIFY, SoloistBackend
43
44if TYPE_CHECKING:
45 from collections.abc import AsyncGenerator
46
47 from music_assistant_models.config_entries import ProviderConfig
48 from music_assistant_models.provider import ProviderManifest
49
50 from music_assistant.mass import MusicAssistant
51
52 from .base import SpotifyConnectBackend
53 from .models import BackendEvent, BackendPlaybackOptions, BackendTrackMetadata
54
55CONF_MASS_PLAYER_ID = "mass_player_id"
56CONF_PUBLISH_NAME = "publish_name"
57DEFAULT_PUBLISH_NAME = "Music Assistant"
58
59# Backend selection, collected by the setup flow (stored in setup_data).
60CONF_BACKEND = "backend"
61BACKEND_GO_LIBRESPOT = "go_librespot"
62BACKEND_SOLOIST = "soloist"
63
64# Soloist-specific values collected by the setup flow (see CONF_BACKEND).
65CONF_API_KEY = "soloist_api_key"
66CONF_SOLOIST_CONSENT = "soloist_download_consent"
67CONF_VOLUME_MODE = "volume_mode"
68
69# Playback behavior applied by the Spotify engine itself (both backends).
70CONF_LOUDNESS_NORMALIZATION = "loudness_normalization"
71MAX_CROSSFADE_DURATION = 12 # seconds, matching the Spotify apps' slider
72CONF_AUDIO_QUALITY = "audio_quality"
73
74AUDIO_QUALITY_VALUES: Final = {option.value for option in AUDIO_QUALITY_OPTIONS}
75
76# The selectable volume modes (labels resolve from strings.json), shared
77# between the runtime option and the setup flow.
78VOLUME_MODE_OPTIONS: Final = [
79 ConfigValueOption(VOLUME_MODE_PLAYER_ONLY),
80 ConfigValueOption(VOLUME_MODE_SYNC_SPOTIFY),
81]
82
83# Special value for auto player selection
84PLAYER_ID_AUTO = "__auto__"
85
86SUPPORTED_FEATURES = {ProviderFeature.AUDIO_SOURCE}
87
88# stable id for the single AudioSource this provider exposes;
89# combined with the provider instance_id this forms the persistent uri
90AUDIO_SOURCE_ID = "main"
91
92# When playback is paused the backend stops writing PCM. If no PCM arrives for
93# this long while we're not in a 'playing' state, end the stream (clean EOF) so
94# the player leaves the playing state; the next 'playing' event re-streams.
95PAUSE_EOF_TIMEOUT_S = 0.5
96
97# Seconds to wait for the backend to report 'playing' after a resume request.
98PLAYBACK_START_TIMEOUT_S = 3.0
99
100# Debounce before acting on an externally-triggered 'playing' event (see
101# _deferred_play_media_fire for why).
102PLAY_MEDIA_DEBOUNCE_S = 0.5
103
104# Ignore Spotify volume events for this long after a session becomes active, so
105# the player's own volume wins over the backend's initial value on (re)connect.
106INITIAL_VOLUME_GRACE_S = 3.0
107
108# User-facing message for the "not the active Spotify device" failure.
109# {0} is the Spotify Connect device's published name (see _not_active_error).
110NOT_ACTIVE_DEVICE_MESSAGE = (
111 "'{0}' is not the active Spotify playback device. "
112 "Open the Spotify app, select it as the playback device, and try again."
113)
114
115
116class SpotifyConnectProvider(PluginProvider):
117 """Implementation of a Spotify Connect Plugin (backed by a SpotifyConnectBackend)."""
118
119 reload_on_streams_network_change = True
120
121 def __init__(
122 self, mass: MusicAssistant, manifest: ProviderManifest, config: ProviderConfig
123 ) -> None:
124 """Initialize MusicProvider."""
125 super().__init__(mass, manifest, config, SUPPORTED_FEATURES)
126 # Configured default player (PLAYER_ID_AUTO or a specific player id)
127 self._default_player_id: str = (
128 cast("str", self.get_setup_value(CONF_MASS_PLAYER_ID)) or PLAYER_ID_AUTO
129 )
130 self._publish_name = (
131 cast("str", self.get_setup_value(CONF_PUBLISH_NAME)) or DEFAULT_PUBLISH_NAME
132 )
133 # Currently active player (the one currently playing or selected)
134 self._active_player_id: str | None = None
135 self._backend: SpotifyConnectBackend = self._create_backend()
136 self.logger.debug(
137 "Init plugin with name '%s' for player '%s' with instance id '%s'",
138 self.name,
139 self._default_player_id,
140 self.instance_id,
141 )
142 self._stream_metadata = StreamMetadata(title=f"Spotify Connect | {self._publish_name}")
143 self._audio_source = self._build_audio_source()
144 # _in_use_by_player is the queue currently streaming us. Claimed in
145 # on_source_selected (NOT in get_stream_details â that path also runs
146 # from queue preload, where claiming would block a later cross-queue
147 # handoff). Released in on_source_unselected when the session id
148 # matches, or in _clear_active_player on the backend's 'inactive' event.
149 self._in_use_by_player: str | None = None
150 # _active_session_id is the controller-provided token for the current
151 # stream request â used to reject stale on_source_unselected callbacks
152 # after a same-queue reconnect supersedes the previous request.
153 self._active_session_id: str | None = None
154 # tracks the backend's play/pause state from its 'playing' / 'paused' /
155 # 'inactive' events; gates the resume kick in on_source_selected (skip if
156 # already playing) and the play_media trigger in the event handler.
157 self._playing: bool = False
158 # True while MA is the active Spotify Connect device (set on 'active',
159 # cleared on 'inactive'); gates get_stream_details and transport commands.
160 self._spotify_session_active: bool = False
161 # holds the single in-flight deferred play_media task scheduled once the
162 # session is both active and playing; cancelled when a later event makes
163 # that state stale.
164 self._pending_play_media_task: asyncio.Task[None] | None = None
165 # holds the in-flight stop of a paused player (pipe-fed backends
166 # only); the stop dispatches right away, but a 'playing' event cancels
167 # it while it is still in flight (a slow player can hold it for up to
168 # 10s), so a resume is never killed by a stop landing late.
169 self._pending_pause_stop_task: asyncio.Task[None] | None = None
170 self._last_session_active_time: float = 0
171 self._last_volume_sent: int | None = None
172 # Last context/track URIs seen on the event stream. Used to take playback
173 # back (make ourselves the active Spotify device) when the user switched
174 # the active device away in the Spotify app and then presses play in MA.
175 self._last_context_uri: str | None = None
176 self._last_track_uri: str | None = None
177 # Latest playback options reported by the backend. Cached on every
178 # OPTIONS_CHANGED â an externally triggered session reports them before
179 # the queue claim exists â and pushed to the queue once claimed in
180 # on_source_selected. Cleared when the session ends.
181 self._last_playback_options: BackendPlaybackOptions | None = None
182
183 @property
184 def instance_name_postfix(self) -> str | None:
185 """Return the advertised device name as the multi-instance postfix."""
186 return self._publish_name if self._publish_name != DEFAULT_PUBLISH_NAME else None
187
188 async def get_config_entries(self) -> tuple[ConfigEntry, ...]:
189 """Return runtime options for this provider."""
190 # The backend selection and the soloist secrets are managed by the setup
191 # flow (stored in setup_data) and stay hidden; the volume mode is a
192 # visible runtime option for soloist configs.
193 is_soloist = self.get_setup_value(CONF_BACKEND) == BACKEND_SOLOIST
194 return (
195 CONF_ENTRY_WARN_PREVIEW,
196 ConfigEntry(
197 key=CONF_BACKEND,
198 type=ConfigEntryType.STRING,
199 default_value=BACKEND_GO_LIBRESPOT,
200 required=False,
201 hidden=True,
202 ),
203 ConfigEntry(
204 key=CONF_API_KEY,
205 type=ConfigEntryType.SECURE_STRING,
206 required=False,
207 hidden=True,
208 ),
209 ConfigEntry(
210 key=CONF_SOLOIST_CONSENT,
211 type=ConfigEntryType.BOOLEAN,
212 default_value=False,
213 required=False,
214 hidden=True,
215 ),
216 ConfigEntry(
217 key=CONF_VOLUME_MODE,
218 type=ConfigEntryType.STRING,
219 default_value=VOLUME_MODE_PLAYER_ONLY,
220 required=False,
221 options=VOLUME_MODE_OPTIONS,
222 hidden=not is_soloist,
223 ),
224 ConfigEntry(
225 key=CONF_CROSSFADE_DURATION,
226 type=ConfigEntryType.INTEGER,
227 range=(0, MAX_CROSSFADE_DURATION),
228 default_value=0,
229 required=False,
230 ),
231 ConfigEntry(
232 key=CONF_LOUDNESS_NORMALIZATION,
233 type=ConfigEntryType.BOOLEAN,
234 default_value=True,
235 required=False,
236 ),
237 ConfigEntry(
238 key=CONF_AUDIO_QUALITY,
239 type=ConfigEntryType.STRING,
240 default_value=AUDIO_QUALITY_LOSSLESS,
241 required=False,
242 options=AUDIO_QUALITY_OPTIONS,
243 ),
244 )
245
246 async def handle_async_init(self) -> None:
247 """Handle async initialization of the provider."""
248 await self._backend.start()
249
250 async def unload(self, is_removed: bool = False) -> None:
251 """Handle close/cleanup of the provider."""
252 self._cancel_pending_play_media()
253 self._cancel_pending_pause_stop()
254 await self._backend.stop()
255
256 @property
257 def active_player_id(self) -> str | None:
258 """Return the currently active player ID for this plugin."""
259 return self._active_player_id
260
261 async def get_audio_sources(self) -> list[AudioSource]:
262 """Return the AudioSources this plugin currently exposes."""
263 return [self._audio_source]
264
265 async def get_stream_details(self, item_id: str, media_type: MediaType) -> StreamDetails:
266 """
267 Return StreamDetails for streaming the Spotify Connect audio.
268
269 Side-effect-free: ownership is claimed in on_source_selected (which the
270 streams controller fires before this method on the actual stream
271 request). Keeping this idempotent means preload paths can fetch
272 streamdetails without claiming the source and blocking a cross-queue
273 handoff.
274
275 Raises AudioError when MA is not the active Spotify Connect device and
276 no previous playback context is known to resume â the user then has to
277 start playback from the Spotify app once.
278 """
279 if item_id != AUDIO_SOURCE_ID:
280 raise MediaNotFoundError(f"Unknown AudioSource: {item_id}")
281 # Only refuse when we can neither resume nor take playback back. If a last
282 # context is known we let the stream proceed; on_source_selected then takes
283 # playback back (makes us the active device) before audio is pulled.
284 if not self._playing and not self._spotify_session_active and not self._last_context_uri:
285 raise self._not_active_error()
286 # The backend describes how its audio is consumed: CUSTOM (the core pulls
287 # PCM from get_audio_stream) or a named pipe read directly by ffmpeg.
288 # decoded_audio_format tells the core the PCM format while audio_format
289 # keeps the source codec for display; MA resamples to each player's
290 # format as needed.
291 # expiration=0: never reuse a cached streamdetails so the active-device
292 # check above re-runs on every play attempt.
293 stream_source = await self._backend.get_stream_source()
294 return StreamDetails(
295 provider=self.instance_id,
296 item_id=item_id,
297 audio_format=self._backend.audio_format,
298 decoded_audio_format=self._backend.decoded_audio_format,
299 media_type=MediaType.AUDIO_SOURCE,
300 stream_type=stream_source.stream_type,
301 path=stream_source.path,
302 stream_metadata=self._stream_metadata,
303 extra_input_args=stream_source.extra_input_args,
304 expiration=0,
305 )
306
307 async def get_audio_stream(
308 self,
309 streamdetails: StreamDetails,
310 seek_position: int = 0,
311 ) -> AsyncGenerator[bytes]:
312 """
313 Yield raw PCM from the backend's audio pipe for the live AudioSource.
314
315 Only used for backends with a CUSTOM stream source (NAMED_PIPE backends
316 are read directly by the streams controller). When playback pauses the
317 backend stops writing PCM; we then end the stream (clean EOF) so the
318 consuming player leaves the playing state. The next ``playing`` event
319 re-triggers playback.
320
321 :param streamdetails: The StreamDetails of the AudioSource being streamed.
322 :param seek_position: Ignored â seeking is handled upstream by Spotify,
323 not by replaying the bytestream.
324 """
325 if streamdetails.item_id != AUDIO_SOURCE_ID:
326 raise MediaNotFoundError(f"Unknown AudioSource: {streamdetails.item_id}")
327 read_chunk = self._backend.get_audio_reader()
328 if read_chunk is None:
329 raise AudioError("Spotify Connect daemon is not running")
330 # No pacing here: the streams controller's realtime pacer (ffmpeg readrate
331 # with a small initial burst) is the single pacing authority for live
332 # sources. Backpressure through the audio pipe bounds how far the backend
333 # (whose pipe backend is not realtime-paced) runs ahead, while the burst
334 # headroom absorbs scheduling jitter that would otherwise underrun the
335 # player. Pacing a second time here would pin the feed to exactly realtime
336 # and starve that headroom.
337 while True:
338 try:
339 chunk = await asyncio.wait_for(read_chunk(), timeout=PAUSE_EOF_TIMEOUT_S)
340 except TimeoutError:
341 # No PCM for a while. If playback is no longer active (paused /
342 # stopped / session gone) end the stream so the player goes idle;
343 # a brief buffering gap while still playing just keeps waiting.
344 if not self._playing:
345 return
346 continue
347 if not chunk:
348 return # audio pipe closed (backend exited / restarting)
349 yield chunk
350
351 async def on_source_selected(
352 self,
353 source_id: str,
354 player_id: str,
355 owner_player_id: str,
356 stream_session_id: str,
357 ) -> None:
358 """Handle callback when this AudioSource has been selected/started on a player."""
359 if source_id != AUDIO_SOURCE_ID or not player_id:
360 return
361
362 # Cache the owner_player_id (== user-facing MA player) rather than the
363 # protocol-level player_id. Some protocol players are ephemeral bridges
364 # whose ID is invalid for play_media / queue lookups once torn down.
365 active_player_id = owner_player_id
366 prev_player_id = (
367 self._active_player_id if self._active_player_id != active_player_id else None
368 )
369
370 # Claim ownership for this queue BEFORE kicking the previous player: the
371 # awaited stop below can complete the old stream's teardown, and only an
372 # already-replaced session id lets on_source_unselected's stale-guard
373 # reject that teardown â otherwise it releases the Spotify session this
374 # handover is about to use.
375 self._in_use_by_player = owner_player_id
376 self._active_session_id = stream_session_id
377 self._active_player_id = active_player_id
378 self.logger.debug("Active player set to: %s", active_player_id)
379
380 # If a different player was consuming the source, kick it out (the source
381 # is exclusive).
382 if prev_player_id:
383 self.logger.info(
384 "Source selected on player %s, stopping playback on %s",
385 active_player_id,
386 prev_player_id,
387 )
388 try:
389 await self.mass.players.cmd_stop(prev_player_id)
390 except Exception as err:
391 self.logger.debug("Failed to stop previous player %s: %s", prev_player_id, err)
392
393 # Push the options the session reported before this claim existed, so the
394 # queue mirrors the session's shuffle/repeat state from the start.
395 if self._last_playback_options is not None:
396 self.mass.players.update_source_options(
397 owner_player_id,
398 AUDIO_SOURCE_ID,
399 self.instance_id,
400 shuffle_enabled=self._last_playback_options.shuffle,
401 repeat_mode=self._last_playback_options.repeat,
402 )
403
404 # Only persist the selected player as the new default if not in auto mode
405 if self._default_player_id != PLAYER_ID_AUTO:
406 self._save_last_player_id(active_player_id)
407
408 # Externally triggered: the backend is already playing â nothing to do.
409 # Otherwise acquire playback, then confirm it actually started.
410 if not self._playing:
411 try:
412 if self._spotify_session_active:
413 # Still the active Spotify device (just paused) â resume.
414 await self._backend.resume()
415 elif self._last_context_uri:
416 # The user moved the active device away in the Spotify app.
417 # Take playback back by (re)starting the last context on us,
418 # which makes this device the active one again. The track
419 # restarts from its beginning (there is no resume-at-position
420 # play call).
421 self.logger.info("Taking Spotify playback back to Music Assistant")
422 await self._backend.play(
423 self._last_context_uri, skip_to_uri=self._last_track_uri
424 )
425 else:
426 raise self._not_active_error()
427 except AudioError:
428 raise
429 except Exception as err:
430 raise AudioError(f"Failed to acquire Spotify Connect: {err}") from err
431 if not await self._wait_for_playing():
432 raise self._not_active_error()
433
434 # The backend reports 100% volume until told otherwise; push the player's
435 # volume so the Spotify app's absolute volume commands start from the
436 # real level.
437 await self._sync_player_volume_to_spotify(active_player_id)
438
439 async def on_source_unselected(
440 self, source_id: str, owner_player_id: str, stream_session_id: str
441 ) -> None:
442 """Release the queue-scoped exclusive claim when MA tears down the stream."""
443 if source_id != AUDIO_SOURCE_ID:
444 return
445 # Reject stale callbacks: only release if this is still the active
446 # session. A owner_player_id check alone is not sufficient â same-queue
447 # reconnects would otherwise let an old request's late callback clear
448 # the live claim of the new stream.
449 if self._active_session_id != stream_session_id:
450 return
451 self._active_session_id = None
452 if self._in_use_by_player == owner_player_id:
453 self._in_use_by_player = None
454 if self._playing:
455 # MA-side stop/queue-clear: release the Spotify session so the app
456 # drops the device as its playback target â the daemon would
457 # otherwise keep playing into a pipe nobody consumes and the app
458 # would stay tethered to the device. (Teardowns caused by a
459 # Spotify-side pause, deselect or a player handoff never reach
460 # here: those cleared _playing or replaced the session id first.)
461 try:
462 await self._backend.deactivate()
463 except Exception as err:
464 self.logger.debug("Failed to release Spotify session on stream teardown: %s", err)
465
466 async def on_source_released(self, source_id: str, player_id: str) -> None:
467 """Release the Spotify session when a player is done with this source."""
468 if source_id != AUDIO_SOURCE_ID or self._active_player_id != player_id:
469 return
470 if not self._spotify_session_active:
471 return
472 # Released whether or not a stream is still winding down: a paused source
473 # already ended its stream, so its teardown released nothing and the
474 # Spotify app would stay tethered to a player that has moved on.
475 #
476 # Let the player go first. The backend answers a deactivate with the same
477 # 'inactive' event a deselect in the Spotify app produces, and that stops
478 # the player we were on - which by now is playing whatever took our place.
479 self._active_player_id = None
480 try:
481 await self._backend.deactivate()
482 except Exception as err:
483 self.logger.debug("Failed to release Spotify session: %s", err)
484
485 async def on_source_control(
486 self,
487 source_id: str,
488 action: SourceControl,
489 value: SourceControlValue = None,
490 ) -> None:
491 """Proxy playback control commands to the backend."""
492 if source_id != AUDIO_SOURCE_ID:
493 return
494 if not self._playing and not self._spotify_session_active:
495 raise self._not_active_error()
496 try:
497 if action == SourceControl.PLAY:
498 await self._backend.resume()
499 elif action == SourceControl.PAUSE:
500 await self._backend.pause()
501 elif action == SourceControl.NEXT:
502 await self._backend.next()
503 elif action == SourceControl.PREVIOUS:
504 await self._backend.previous()
505 elif (
506 action == SourceControl.SEEK
507 # tolerate float positions from internal callers; bool is an int
508 # subclass, so a misrouted toggle must not become a 1-second seek
509 and isinstance(value, (int, float))
510 and not isinstance(value, bool)
511 ):
512 await self._backend.seek(int(value) * 1000)
513 elif action == SourceControl.SHUFFLE and isinstance(value, bool):
514 # strict bool: None or a misrouted enum (bool(RepeatMode.OFF) is
515 # True) must not silently toggle shuffle
516 await self._backend.set_shuffle(value)
517 elif action == SourceControl.REPEAT and isinstance(value, RepeatMode):
518 await self._backend.set_repeat(value)
519 except Exception as err:
520 self.logger.warning("Failed to send %s command to backend: %s", action, err)
521 raise
522
523 async def on_volume_change(self, source_id: str, volume: int) -> None:
524 """Sync the Spotify app's volume slider with the player's new volume."""
525 if source_id != AUDIO_SOURCE_ID:
526 return
527 if not self._playing and not self._spotify_session_active:
528 raise self._not_active_error()
529 # Prevent ping-pong: only push if the value actually changed from what we
530 # last sent to / received from the backend.
531 if self._last_volume_sent == volume:
532 return
533 try:
534 await self._push_volume_to_backend(volume)
535 except Exception as err:
536 self.logger.warning("Failed to send volume command to backend: %s", err)
537 raise
538
539 def _create_backend(self) -> SpotifyConnectBackend:
540 """Construct the configured Spotify Connect backend implementation."""
541 # The backend choice and soloist secrets are collected by the setup flow
542 # into setup_data; a config migrated from before the backend choice
543 # existed yields None here, which intentionally selects go-librespot
544 # (the equality check must keep treating None as the default).
545 if self.get_setup_value(CONF_BACKEND) == BACKEND_SOLOIST:
546 return SoloistBackend(
547 self.mass,
548 instance_id=self.instance_id,
549 publish_name=self._publish_name,
550 name=self.name,
551 logger=self.logger,
552 event_callback=self._handle_backend_event,
553 api_key=cast("str", self.get_setup_value(CONF_API_KEY) or ""),
554 consent=bool(self.get_setup_value(CONF_SOLOIST_CONSENT)),
555 volume_mode=self._resolve_volume_mode(),
556 crossfade_ms=self._resolve_crossfade_ms(),
557 loudness_normalization=self._resolve_loudness_normalization(),
558 audio_quality=self._resolve_audio_quality(),
559 )
560 return GoLibrespotBackend(
561 self.mass,
562 instance_id=self.instance_id,
563 publish_name=self._publish_name,
564 name=self.name,
565 logger=self.logger,
566 event_callback=self._handle_backend_event,
567 crossfade_ms=self._resolve_crossfade_ms(),
568 loudness_normalization=self._resolve_loudness_normalization(),
569 audio_quality=self._resolve_audio_quality(),
570 )
571
572 def _resolve_volume_mode(self) -> str:
573 """Return the configured volume mode (the provider options page is the only source)."""
574 return cast(
575 "str",
576 self.config.get_value(CONF_VOLUME_MODE) or VOLUME_MODE_PLAYER_ONLY,
577 )
578
579 def _resolve_crossfade_ms(self) -> int:
580 """Return the configured crossfade duration in milliseconds (0 = disabled)."""
581 value = cast("int | None", self.config.get_value(CONF_CROSSFADE_DURATION))
582 return max(0, min(int(value or 0), MAX_CROSSFADE_DURATION)) * 1000
583
584 def _resolve_loudness_normalization(self) -> bool:
585 """Return whether Spotify's loudness normalization should be enabled."""
586 value = self.config.get_value(CONF_LOUDNESS_NORMALIZATION)
587 return True if value is None else bool(value)
588
589 def _resolve_audio_quality(self) -> str:
590 """Return the configured streaming quality tier."""
591 value = self.config.get_value(CONF_AUDIO_QUALITY)
592 if value in AUDIO_QUALITY_VALUES:
593 return cast("str", value)
594 return AUDIO_QUALITY_LOSSLESS
595
596 def _not_active_error(self) -> AudioError:
597 """Build the localized 'not the active Spotify device' error, naming this device."""
598 return AudioError(
599 NOT_ACTIVE_DEVICE_MESSAGE.format(self._publish_name),
600 translation_key="not_active_device",
601 translation_args=[self._publish_name],
602 translation_owner=self.translation_owner,
603 )
604
605 def _build_audio_source(self) -> AudioSource:
606 """
607 Construct the AudioSource MediaItem.
608
609 Backends provide a full control surface, so play / pause / seek /
610 next / previous are always available while a session is active â the
611 capability flags are static (no dependency on the Spotify Web API).
612 Ordering the session is only offered by backends implementing the
613 queue-session verbs.
614 """
615 return AudioSource(
616 item_id=AUDIO_SOURCE_ID,
617 provider=self.instance_id,
618 name=self.name,
619 provider_mappings={
620 ProviderMapping(
621 item_id=AUDIO_SOURCE_ID,
622 provider_domain=self.domain,
623 provider_instance=self.instance_id,
624 audio_format=self._backend.audio_format,
625 )
626 },
627 can_play_pause=True,
628 can_seek=True,
629 can_next_previous=True,
630 can_shuffle=self._backend.supports_queue_control,
631 can_repeat=self._backend.supports_queue_control,
632 exclusive=True,
633 allow_external_trigger=True,
634 # Browsable/startable from MA: playback resumes the last known
635 # Spotify context (claiming active device status). Without any
636 # prior context a localized error points the user to the app.
637 can_initiate=True,
638 )
639
640 def _get_target_player_id(self) -> str | None:
641 """
642 Determine the target player ID for playback.
643
644 Priority: an explicitly selected player; else (auto) a currently playing
645 player then the first available; else the configured default player.
646
647 :return: The player ID to use for playback, or None if none available.
648 """
649 if self._active_player_id:
650 if self.mass.players.get_player(self._active_player_id):
651 return self._active_player_id
652 self._active_player_id = None
653
654 if self._default_player_id == PLAYER_ID_AUTO:
655 all_players = list(self.mass.players.all_players(False, False))
656 for player in all_players:
657 if player.state.playback_state == PlaybackState.PLAYING:
658 self.logger.debug("Auto-selecting playing player: %s", player.display_name)
659 return player.player_id
660 if all_players:
661 first_player = all_players[0]
662 self.logger.debug(
663 "Auto-selecting first available player: %s", first_player.display_name
664 )
665 return first_player.player_id
666 return None
667
668 if self.mass.players.get_player(self._default_player_id):
669 return self._default_player_id
670 self.logger.warning(
671 "Configured default player '%s' no longer exists", self._default_player_id
672 )
673 return None
674
675 async def _wait_for_playing(self, timeout: float = PLAYBACK_START_TIMEOUT_S) -> bool:
676 """
677 Wait up to ``timeout`` seconds for the backend to report it is playing.
678
679 :param timeout: Maximum seconds to wait.
680 :return: True once playback is confirmed, False if the timeout elapses.
681 """
682 deadline = self.mass.loop.time() + timeout
683 while True:
684 if self._playing:
685 return True
686 if self.mass.loop.time() >= deadline:
687 return False
688 await asyncio.sleep(0.1)
689
690 async def _stop_paused_player(self, player_id: str) -> None:
691 """
692 Stop the active player after a pause on a backend without stream EOF.
693
694 :param player_id: The player currently consuming the live source.
695 """
696 self.logger.debug("Stopping player %s after pause", player_id)
697 try:
698 # bounded: an unresponsive player (e.g. a throttled web client) must
699 # not hold this task - and the player's playback lock - indefinitely
700 async with asyncio.timeout(10):
701 await self.mass.players.cmd_stop(player_id)
702 self.logger.debug("Player %s stopped after pause", player_id)
703 except TimeoutError:
704 self.logger.warning("Player %s did not stop within 10s after pause", player_id)
705 except Exception as err:
706 self.logger.debug("Failed to stop player %s on pause: %s", player_id, err)
707
708 def _schedule_play_media(self) -> None:
709 """Schedule playback when Spotify is active and no player owns the source."""
710 if (
711 not self._playing
712 or not self._spotify_session_active
713 or self._in_use_by_player
714 or (
715 self._pending_play_media_task is not None
716 and not self._pending_play_media_task.done()
717 )
718 ):
719 return
720 self._pending_play_media_task = self.mass.create_task(self._deferred_play_media_fire())
721
722 def _cancel_pending_play_media(self) -> None:
723 """Cancel any pending deferred play_media trigger."""
724 task = self._pending_play_media_task
725 if task is not None and not task.done():
726 task.cancel()
727 self._pending_play_media_task = None
728
729 def _schedule_pause_stop(self, player_id: str) -> None:
730 """
731 Dispatch the stop of the paused player, replacing a still-pending one.
732
733 :param player_id: The player currently consuming the live source.
734 """
735 self._cancel_pending_pause_stop()
736 task = self.mass.create_task(self._stop_paused_player(player_id))
737 self._pending_pause_stop_task = task
738 task.add_done_callback(self._on_pause_stop_done)
739
740 def _cancel_pending_pause_stop(self) -> None:
741 """Cancel any pending deferred stop of a paused player."""
742 task = self._pending_pause_stop_task
743 if task is not None and not task.done():
744 task.cancel()
745 self._pending_pause_stop_task = None
746
747 def _on_pause_stop_done(self, task: asyncio.Task[None]) -> None:
748 """Drop the pause-stop handle once its task finished (unless already replaced)."""
749 if self._pending_pause_stop_task is task:
750 self._pending_pause_stop_task = None
751
752 async def _deferred_play_media_fire(self) -> None:
753 """
754 Trigger play_media after a short debounce.
755
756 The backend can emit a stale 'playing' from a dying session just before it
757 reconnects; acting on it immediately would start a stream for a session
758 that is about to be replaced. Debouncing â and cancelling the task on a
759 later 'paused' / 'stopped' / 'active' event â avoids a playâstopâreplay loop.
760 """
761 try:
762 await asyncio.sleep(PLAY_MEDIA_DEBOUNCE_S)
763 except asyncio.CancelledError:
764 return
765 if not self._playing or self._in_use_by_player:
766 return
767 target_player_id = self._get_target_player_id()
768 if not target_player_id:
769 self.logger.warning(
770 "Spotify Connect playback started but no player available. "
771 "Select this source on a player to start playback."
772 )
773 return
774 self.logger.info(
775 "Starting Spotify Connect playback [%s] on player %s",
776 self.instance_id,
777 target_player_id,
778 )
779 self._active_player_id = target_player_id
780 self.mass.create_task(
781 self.mass.player_queues.play_media(target_player_id, str(self._audio_source.uri))
782 )
783
784 def _clear_active_player(self) -> None:
785 """Clear the active player and reset playback state when a session ends."""
786 prev_player_id = self._active_player_id
787 source_session = (
788 self.mass.players.get_audio_source_session(prev_player_id) if prev_player_id else None
789 )
790 self._active_player_id = None
791 self._in_use_by_player = None
792 self._active_session_id = None
793 self._playing = False
794 if prev_player_id:
795 self.logger.debug("Playback ended on player %s, clearing active player", prev_player_id)
796 # the player is not playing us any more, so it should stop saying it is;
797 # the stop itself is scheduled separately by the caller
798 self.mass.create_task(
799 self.mass.players.deselect_source(
800 prev_player_id,
801 stop_playback=False,
802 provider_instance_id=self.instance_id,
803 source_id=AUDIO_SOURCE_ID,
804 playback_session_id=(
805 source_session.playback_session_id if source_session else None
806 ),
807 )
808 )
809
810 def _save_last_player_id(self, player_id: str) -> None:
811 """Persist the selected player ID as the new default."""
812 if self._default_player_id == player_id:
813 return
814 try:
815 self._update_setup_data(CONF_MASS_PLAYER_ID, player_id)
816 self._default_player_id = player_id
817 except Exception as err:
818 self.logger.debug("Failed to persist player ID: %s", err)
819
820 async def _handle_backend_event(self, event: BackendEvent) -> None:
821 """Dispatch a single normalized event received from the backend."""
822 if event.type is BackendEventType.CONNECTION_LOST:
823 # The backend's Spotify session is gone (e.g. daemon exit). Reset
824 # session state so a dead/restarting backend isn't treated as active
825 # and controllable; a fresh 'active' event re-establishes it.
826 self._playing = False
827 self._spotify_session_active = False
828 # stale options must not outlive the session they belong to
829 self._last_playback_options = None
830 return
831 if event.type is BackendEventType.FATAL_ERROR:
832 self.unload_with_error(event.error or "Spotify Connect backend failed")
833 return
834 if event.type is BackendEventType.ERROR:
835 # non-fatal backend error: surface it in the log only
836 self.logger.warning("Spotify Connect backend error: %s", event.error)
837 return
838 if event.type is BackendEventType.AUTH_REQUIRED:
839 self._handle_auth_required()
840 return
841
842 self._remember_context_uris(event)
843
844 if event.type is BackendEventType.QUEUE_CHANGED:
845 # queue snapshots are not consumed yet (full queue-item mirroring comes later)
846 return
847 if event.type is BackendEventType.OPTIONS_CHANGED:
848 # an options report is no reason to re-push the (unchanged) stream metadata below
849 self._handle_options_changed(event)
850 return
851
852 if event.type is BackendEventType.SESSION_ACTIVE:
853 self._spotify_session_active = True
854 self._last_session_active_time = time.time()
855 # A (re)activation supersedes any deferred play_media from a previous
856 # session. Reconcile afterwards because 'playing' may arrive first.
857 self._cancel_pending_play_media()
858 self.logger.info("Spotify Connect session active for %s", self.name)
859 # A new session starts at the backend's 100% volume default; push the
860 # target player's volume so the Spotify app's slider is correct from
861 # device selection, before any playback starts. (In the soloist
862 # player_only mode the backend pins 100% and ignores the pushed
863 # value â the app slider staying at 100 there is by design.)
864 if player_id := self._get_target_player_id():
865 await self._sync_player_volume_to_spotify(player_id)
866 self._schedule_play_media()
867 elif event.type is BackendEventType.SESSION_INACTIVE:
868 self.logger.info("Spotify Connect session inactive for %s", self.name)
869 self._spotify_session_active = False
870 # stale options must not outlive the session they belong to
871 self._last_playback_options = None
872 prev_player_id = self._active_player_id
873 self._clear_active_player()
874 if prev_player_id:
875 # bounded like the pause path: a slow player must not hold the
876 # stop (and its playback lock) indefinitely
877 self._schedule_pause_stop(prev_player_id)
878 return
879 elif event.type is BackendEventType.PLAYING:
880 self._playing = True
881 # A resume can arrive while the pause-stop is still in flight on a
882 # slow player; cancel it so it doesn't kill the restarted stream.
883 # (a stop that already completed is fine: play_media below restarts)
884 self._cancel_pending_pause_stop()
885 # Externally triggered playback: kick a play_media on the target MA
886 # player so the audio reaches a speaker. Deferred so a rapid
887 # playing/active burst from a reconnecting session can cancel it.
888 # Only while the session is active: a daemon playing without being
889 # the active Connect device (e.g. right after a deactivate) must
890 # not grab MA players in a loop.
891 self._schedule_play_media()
892 elif event.type in (BackendEventType.PAUSED, BackendEventType.STOPPED):
893 was_playing = self._playing
894 self._playing = False
895 # A pause/stop is the definitive "don't start": cancel a deferred fire
896 # from a now-stale 'playing'. On a backend whose stream ends on pause the
897 # active get_audio_stream sees the PCM stop and ends the stream (clean
898 # EOF), so the player leaves the playing state and the next 'playing'
899 # event re-fires play_media to resume.
900 self._cancel_pending_play_media()
901 # A backend without a stream end on pause never signals EOF, so
902 # the player must be stopped actively; the claim stays so the next
903 # 'playing' event resumes playback like the EOF path does. Only the
904 # playingâpaused transition fires it: the backend reports a pause
905 # through multiple events (state delta + snapshot).
906 if (
907 was_playing
908 and not self._backend.stream_ends_on_pause
909 and (player_id := self._active_player_id)
910 ):
911 self._schedule_pause_stop(player_id)
912
913 if event.type is BackendEventType.METADATA and event.metadata is not None:
914 self._apply_metadata(event.metadata)
915 elif event.type is BackendEventType.POSITION and event.position is not None:
916 self._stream_metadata.elapsed_time = event.position
917 self._stream_metadata.elapsed_time_last_updated = int(time.time())
918
919 if event.type is BackendEventType.VOLUME and event.volume is not None:
920 await self._handle_volume_event(event.volume)
921
922 # push metadata update to the active queue item's streamdetails
923 if self._in_use_by_player:
924 self.mass.players.update_source_metadata(
925 self._in_use_by_player,
926 AUDIO_SOURCE_ID,
927 self.instance_id,
928 self._stream_metadata,
929 )
930
931 def _remember_context_uris(self, event: BackendEvent) -> None:
932 """
933 Memoize the latest context/track URIs seen on the event stream.
934
935 Used to take playback back (make MA the active Spotify device) when the user
936 switched the active device away in the Spotify app and then presses play in MA
937 (see ``on_source_selected``).
938
939 :param event: The backend event to read the URIs from.
940 """
941 if event.context_uri:
942 self._last_context_uri = event.context_uri
943 if event.track_uri:
944 self._last_track_uri = event.track_uri
945
946 def _handle_auth_required(self) -> None:
947 """Handle a lost Spotify login: reset session state and unload with an auth error."""
948 # the backend lost its Spotify login mid-session: stop treating the
949 # device as active and unload with an auth error so the UI flags
950 # the provider and routes the user through the setup flow
951 self._playing = False
952 self._spotify_session_active = False
953 self._last_playback_options = None
954 self.logger.warning("Spotify Connect backend for %s requires (re)authentication", self.name)
955 self.unload_with_error(
956 LoginFailed(
957 "Spotify authentication required",
958 translation_key="soloist_auth_required",
959 translation_owner=self.translation_owner,
960 )
961 )
962
963 def _handle_options_changed(self, event: BackendEvent) -> None:
964 """
965 Cache the session's playback options and mirror them onto the consuming queue.
966
967 :param event: The OPTIONS_CHANGED event to handle.
968 """
969 if event.options is None:
970 return
971 # cache regardless of claim state: an externally triggered session reports its
972 # options before the queue claim exists; on_source_selected pushes the cached
973 # value once claimed
974 self._last_playback_options = event.options
975 if not self._in_use_by_player:
976 return
977 self.mass.players.update_source_options(
978 self._in_use_by_player,
979 AUDIO_SOURCE_ID,
980 self.instance_id,
981 shuffle_enabled=event.options.shuffle,
982 repeat_mode=event.options.repeat,
983 )
984
985 def _apply_metadata(self, metadata: BackendTrackMetadata) -> None:
986 """Update the live StreamMetadata from a normalized metadata event."""
987 self._stream_metadata.uri = metadata.track_uri
988 if metadata.title:
989 self._stream_metadata.title = metadata.title
990 self._stream_metadata.artist = metadata.artist
991 self._stream_metadata.album = metadata.album
992 self._stream_metadata.image_url = metadata.image_url
993 self._stream_metadata.description = None
994 self._stream_metadata.duration = metadata.duration
995 self._stream_metadata.elapsed_time = metadata.position
996 self._stream_metadata.elapsed_time_last_updated = int(time.time())
997
998 async def _handle_volume_event(self, volume: int) -> None:
999 """
1000 Apply a Spotify-side volume change to the linked MA player.
1001
1002 :param volume: The reported volume as a 0-100 percentage.
1003 """
1004 # Ignore our own echo: the backend emits a 'volume' event for the value we
1005 # just pushed in on_volume_change; re-applying it would ping-pong.
1006 if volume == self._last_volume_sent:
1007 return
1008 # Ignore the volume the backend reports right after a session becomes
1009 # active â the player's own volume should win in that window.
1010 if time.time() - self._last_session_active_time < INITIAL_VOLUME_GRACE_S:
1011 self.logger.debug("Ignoring initial volume_changed event after session active")
1012 return
1013 if not self._in_use_by_player:
1014 return
1015 previous_volume = self._last_volume_sent
1016 self._last_volume_sent = volume
1017 try:
1018 await self.mass.players.cmd_volume_set(self._in_use_by_player, volume)
1019 except Exception as err:
1020 # Volume sync is best-effort: the player may not support volume, or the
1021 # command may fail. Restore the cached value so a retry isn't wrongly
1022 # deduped, and never let it bubble up and drop the events loop.
1023 self._last_volume_sent = previous_volume
1024 self.logger.debug("Could not set volume on %s: %s", self._in_use_by_player, err)
1025
1026 async def _sync_player_volume_to_spotify(self, player_id: str) -> None:
1027 """
1028 Push a player's current volume to the backend (best-effort).
1029
1030 :param player_id: The MA player whose volume to push.
1031 """
1032 player = self.mass.players.get_player(player_id)
1033 if player is None or player.state.volume_level is None:
1034 return
1035 # clamp: the logical volume can be out of range until volume limit
1036 # enforcement runs
1037 volume = max(0, min(100, player.state.volume_level))
1038 # No dedupe against _last_volume_sent here: it holds the last value
1039 # exchanged with the backend, not the backend's current volume, which
1040 # resets to its 100% default on a new session or backend restart.
1041 try:
1042 await self._push_volume_to_backend(volume)
1043 except Exception as err:
1044 self.logger.debug("Failed to sync player volume to Spotify: %s", err)
1045
1046 async def _push_volume_to_backend(self, volume: int) -> None:
1047 """
1048 Send an absolute 0-100 volume to the backend.
1049
1050 :param volume: Volume percentage to send.
1051 :raises Exception: If the request to the backend fails.
1052 """
1053 previous_volume = self._last_volume_sent
1054 # Record BEFORE the call: the backend echoes a 'volume' event back, and
1055 # that echo can arrive over the event stream while we're still awaiting
1056 # set_volume. Recording up front lets _handle_volume_event dedupe it
1057 # instead of bouncing it back as a player volume change.
1058 self._last_volume_sent = volume
1059 try:
1060 await self._backend.set_volume(volume)
1061 except Exception:
1062 # restore on failure so a retry of this value isn't wrongly deduped
1063 self._last_volume_sent = previous_volume
1064 raise
1065