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