/
/
1"""Model/base for a Plugin Provider implementation."""
2
3from __future__ import annotations
4
5from dataclasses import dataclass
6from typing import TYPE_CHECKING, Any
7
8from music_assistant_models.enums import ProviderFeature
9from music_assistant_models.media_items import SearchResults, UniqueList
10
11from .provider import Provider
12
13if TYPE_CHECKING:
14 from collections.abc import AsyncGenerator, Sequence
15
16 from music_assistant_models.enums import MediaType, RepeatMode, SourceControl
17 from music_assistant_models.media_items import (
18 AudioSource,
19 BrowseFolder,
20 ItemMapping,
21 MediaItemType,
22 Playlist,
23 RecommendationFolder,
24 Track,
25 )
26 from music_assistant_models.streamdetails import StreamDetails
27
28
29# separator between the owning provider's instance_id and the provider-scoped engine id;
30# occurs in neither MA instance_ids nor Home Assistant entity_ids
31ENGINE_UID_SEPARATOR = "/"
32
33# payload accepted by ``on_source_control``: seek position (seconds) or volume level
34# for SEEK/VOLUME, the enabled state for SHUFFLE, the RepeatMode for REPEAT,
35# None for plain transport actions
36type SourceControlValue = int | bool | RepeatMode | None
37
38
39@dataclass(kw_only=True)
40class PluginEngine:
41 """
42 A single selectable backend exposed by a plugin provider.
43
44 One plugin can expose several engines (for example one per Home Assistant entity),
45 so consumers offer them as options in a config picker rather than treating the
46 plugin itself as the unit of choice. The chosen engine is stored in config by its
47 ``uid`` and handed back to the owning provider as the provider-scoped ``id``.
48
49 Server-side only: never serialized to clients.
50 """
51
52 id: str
53 name: str
54 provider: PluginProvider
55
56 @property
57 def uid(self) -> str:
58 """Return the globally unique id for this engine, as stored in config."""
59 return f"{self.provider.instance_id}{ENGINE_UID_SEPARATOR}{self.id}"
60
61
62@dataclass(kw_only=True)
63class AIEngine(PluginEngine):
64 """An engine that answers AI queries, invoked through ``PluginProvider.ai_query``."""
65
66
67@dataclass(kw_only=True)
68class TTSEngine(PluginEngine):
69 """An engine that renders speech, invoked through ``PluginProvider.get_tts_message``."""
70
71
72class PluginProvider(Provider):
73 """
74 Base representation of a Plugin for Music Assistant.
75
76 Plugin Provider implementations should inherit from this base model.
77 """
78
79 async def get_audio_sources(self) -> list[AudioSource]:
80 """
81 Return all AudioSources this plugin currently exposes.
82
83 Will only be called if ProviderFeature.AUDIO_SOURCE is declared.
84
85 May change over time (e.g. when a paired hardware device adds/removes
86 favorites). Each AudioSource is a regular MediaItem and will be browsable
87 under the global "Live Inputs" node and playable via the standard play_media flow.
88
89 :return: A list of AudioSource items. Return an empty list if the plugin
90 currently has no sources to expose (e.g. hardware is offline).
91 """
92 if ProviderFeature.AUDIO_SOURCE in self.supported_features:
93 raise NotImplementedError
94 return []
95
96 async def get_stream_details(self, item_id: str, media_type: MediaType) -> StreamDetails:
97 """
98 Return StreamDetails for a streamable item owned by this plugin.
99
100 Called for a playable item this plugin exposes; ``media_type`` says which kind.
101 AudioSource items require ProviderFeature.AUDIO_SOURCE to be declared.
102
103 MUST be side-effect-free. MA calls this from both the streaming path
104 and from queue preload (``_load_item``); claiming ownership here would
105 let a preload accidentally reserve an exclusive source and block a
106 subsequent cross-queue handoff at the actual stream request. Ownership
107 is claimed in ``on_source_selected`` (which fires only on the real
108 stream request, paired with ``on_source_unselected`` in the finally).
109
110 The returned StreamDetails uses the standard fields:
111 ``stream_type`` selects between a custom async generator and a path
112 (e.g. NAMED_PIPE); ``audio_format`` describes the source for display and
113 ``decoded_audio_format`` the PCM actually delivered, which a plugin that
114 decoded the source itself has to set; ``stream_metadata`` carries the initial
115 live metadata (and can be updated at runtime via
116 ``mass.players.update_source_metadata(player_id, ...)``).
117
118 Silence-during-pause contract:
119 the player consuming the stream needs a continuous byte flow or it will
120 disconnect after a few seconds. The server keeps the connection alive
121 differently depending on ``stream_type``:
122
123 - ``StreamType.CUSTOM`` â the server wraps ``get_audio_stream`` with a
124 silence-keepalive so a paused upstream device (no bytes yielded) does
125 NOT cause the player to drop out. The plugin can just stop yielding
126 while paused; the wrapper inserts silence frames at the declared PCM
127 format.
128 - ``StreamType.NAMED_PIPE`` â the underlying process MUST keep writing
129 silence to the pipe during pause states (shairport-sync and librespot
130 in pipe/passthrough mode both do this by default). If the producer
131 binary actually stops writing, the consuming ffmpeg will block and
132 the player will eventually disconnect.
133
134 :param item_id: The provider-scoped id of the item requested for playback:
135 an ``AudioSource.item_id`` or the id of another item this plugin owns.
136 :param media_type: The media type of the requested item.
137 """
138 raise NotImplementedError
139
140 async def get_audio_stream(
141 self, streamdetails: StreamDetails, seek_position: int = 0
142 ) -> AsyncGenerator[bytes]:
143 """
144 Return the (custom) audio stream for an AudioSource.
145
146 Will only be called when the StreamDetails returned by get_stream_details
147 has ``stream_type=StreamType.CUSTOM``. The yielded bytes must be in the PCM
148 format declared by ``streamdetails.decoded_audio_format``, falling back to
149 ``audio_format`` when the plugin delivers its source untouched.
150
151 Pausing is fine: when the upstream device is paused the plugin can stop
152 yielding bytes. The server wraps this generator with a silence-keepalive
153 that keeps the player connected by inserting silence at the declared PCM
154 format during quiet periods. The plugin should release any per-session
155 state in a ``try/finally`` â the consumer closes the generator when
156 playback ends or another queue takes over.
157
158 :param streamdetails: The StreamDetails previously returned by get_stream_details.
159 :param seek_position: Ignored for live AudioSources (no seek through the bytestream).
160 """
161 raise NotImplementedError
162 # unreachable, but the yield keeps this method an async generator
163 # so an unimplemented provider fails deterministically without emitting
164 # a stray empty chunk to the downstream consumer first.
165 yield b"" # type: ignore[unreachable]
166
167 async def on_source_control(
168 self,
169 source_id: str,
170 action: SourceControl,
171 value: SourceControlValue = None,
172 ) -> None:
173 """
174 Handle a playback control command for an active AudioSource.
175
176 Called when the user (or an automation) issues a control command while
177 this AudioSource is the live source on a player. The player controller
178 gates the transport actions on the flag the source declares for each:
179 ``can_play_pause`` for PLAY/PAUSE, ``can_seek`` for SEEK and
180 ``can_next_previous`` for NEXT/PREVIOUS. SHUFFLE/REPEAT are forwarded
181 whatever ``can_shuffle`` / ``can_repeat`` say, because only the session
182 knows whether its current content can be reordered â those flags tell
183 clients what to offer, and a source declaring them is expected to report
184 the resulting state back via ``mass.players.update_source_options``.
185
186 :param source_id: The AudioSource.item_id the command applies to.
187 :param action: The control action to perform.
188 :param value: Optional payload for the action: seek position in seconds
189 for SEEK, volume level 0-100 for VOLUME, the enabled state (bool)
190 for SHUFFLE, the RepeatMode for REPEAT; None for other actions.
191 """
192 raise NotImplementedError
193
194 async def on_source_selected(
195 self,
196 source_id: str,
197 player_id: str,
198 owner_player_id: str,
199 stream_session_id: str,
200 ) -> None:
201 """
202 React to an AudioSource being selected for playback.
203
204 Plugins exposing an exclusive AudioSource MUST claim ownership in this
205 hook (rather than in ``get_stream_details``). This hook fires only on
206 the actual stream request â not on queue preload â so claiming here
207 keeps the preload path side-effect-free and lets cross-queue handoffs
208 succeed (the streams controller fires this **before**
209 ``get_stream_details`` so the plugin can stop the previous player and
210 replace its claim before the upcoming stream-details fetch).
211
212 ``stream_session_id`` is a fresh per-request token paired with the
213 matching ``on_source_unselected`` call. Plugins should store it (and
214 replace any previously stored value) so the unselect callback can be
215 rejected as stale when a same-queue reconnect interleaves with the
216 prior request's teardown â see ``on_source_unselected`` for details.
217
218 :param source_id: The AudioSource.item_id that was selected.
219 :param player_id: The player the audio is served to. For a source playing on
220 a player this is the owner itself; only direct-PCM consumers and the
221 legacy queue-item path pass a different (protocol or group member) player.
222 :param owner_player_id: The player that owns this playback session. Prefer this
223 for anything you store: it is the user-facing player and stays valid for
224 play_media and cmd_stop, where ``player_id`` can be an ephemeral protocol
225 bridge whose id is gone by the time you use it.
226 :param stream_session_id: Opaque controller-generated token identifying
227 this specific stream request. The matching ``on_source_unselected``
228 receives the same value.
229 """
230
231 async def on_source_unselected(
232 self,
233 source_id: str,
234 owner_player_id: str,
235 stream_session_id: str,
236 ) -> None:
237 """
238 React to MA tearing down an AudioSource stream from this queue.
239
240 Fired in the ``finally`` block of the queue-item streaming handler â so
241 it runs whether the stream ended normally, the player disconnected, the
242 queue moved on, or an exception interrupted streaming. Override to
243 release any per-queue state set in ``get_stream_details`` (notably the
244 exclusive lock used to reject cross-queue claims) so the source becomes
245 available to other queues without depending on an external session
246 event.
247
248 Implementations MUST guard on ``stream_session_id`` matching the value
249 last set in ``on_source_selected``. A owner_player_id-only check is not
250 sufficient: same-queue reconnects (player drops + reopens the same
251 stream URL before the original request's finally fires) would
252 otherwise let the old request's late callback clear the live claim of
253 the new stream, silently dropping metadata and volume sync.
254
255 :param source_id: The AudioSource.item_id whose stream ended.
256 :param owner_player_id: The player that owns the stream being torn down.
257 :param stream_session_id: The token paired with ``on_source_selected``
258 for this specific stream request. Ignore the callback if it does
259 not match the currently stored active session id.
260 """
261
262 async def on_source_released(self, source_id: str, player_id: str) -> None:
263 """
264 React to a player letting go of this AudioSource.
265
266 Fired when the player stops playing the source for good: another source was
267 selected on it, it was deselected, or the player went away. Not fired when a
268 stream merely ends â a paused source keeps the player, and its stream is torn
269 down without the player being done with it. Override to release state that
270 must not outlive the player's use of the source, such as an upstream session
271 still pointing at Music Assistant.
272
273 Guard on the player still being the one you hold: a source moving to another
274 player claims the new one before releasing the old, so this can arrive after
275 the source is already playing elsewhere.
276
277 :param source_id: The AudioSource.item_id that was released.
278 :param player_id: The player that let it go.
279 """
280
281 async def on_volume_change(self, source_id: str, volume: int) -> None:
282 """
283 React to a volume change on the player streaming this AudioSource.
284
285 Optional hook. Override when the plugin wants to sync the upstream
286 device's volume slider with MA (e.g. Spotify Connect updating the
287 Spotify app's volume display, Yandex Ynison forwarding the new
288 level back to the Yandex device). Fired only on the direct queue
289 owner â group volume changes fire once at the group level, not
290 per child.
291
292 :param source_id: The AudioSource.item_id currently streaming.
293 :param volume: The new volume level (0-100).
294 """
295
296 async def get_tts_engines(self) -> list[TTSEngine]:
297 """
298 Return the TTS engines this plugin exposes.
299
300 Will only be called if ProviderFeature.TTS is declared.
301
302 May change over time (e.g. when the backend adds or removes voices/entities).
303 The user picks one of these in the config of a consuming provider.
304
305 :return: A list of TTSEngine items. Return an empty list if the plugin
306 currently has no engines to expose (e.g. the backend is offline).
307 """
308 if ProviderFeature.TTS in self.supported_features:
309 raise NotImplementedError
310 return []
311
312 async def get_tts_message(
313 self,
314 message: str,
315 language: str | None = None,
316 engine_id: str | None = None,
317 options: dict[str, Any] | None = None,
318 ) -> StreamDetails:
319 """
320 Convert text to speech audio.
321
322 Will only be called if ProviderFeature.TTS is declared.
323
324 :param message: The text to convert to speech.
325 :param language: Optional language code.
326 :param engine_id: The provider-scoped id of the engine to use (``TTSEngine.id``,
327 not its ``uid``). Omit or pass None to use the plugin's own default engine.
328 :param options: Optional integration-specific options (for example a voice
329 tuning parameter), passed through to the engine as-is. Ignored by plugins
330 that have none.
331 :return: StreamDetails for the generated audio. ``path`` must be either a
332 fetchable http(s)/rtsp/rtmp URL or the absolute path of an existing local
333 file, and must stay resolvable for as long as consumers may play the clip.
334 """
335 raise NotImplementedError
336
337 async def get_ai_engines(self) -> list[AIEngine]:
338 """
339 Return the AI engines this plugin exposes.
340
341 Will only be called if ProviderFeature.AI_QUERY is declared.
342
343 May change over time (e.g. when the backend adds or removes entities).
344 The user picks one of these in the config of a consuming provider.
345
346 :return: A list of AIEngine items. Return an empty list if the plugin
347 currently has no engines to expose (e.g. the backend is offline).
348 """
349 if ProviderFeature.AI_QUERY in self.supported_features:
350 raise NotImplementedError
351 return []
352
353 async def ai_query(self, query: str, engine_id: str | None = None) -> str:
354 """
355 Handle an AI query.
356
357 Will only be called if ProviderFeature.AI_QUERY is declared.
358
359 :param query: The query/prompt to send.
360 :param engine_id: The provider-scoped id of the engine to use (``AIEngine.id``,
361 not its ``uid``). Omit or pass None to use the plugin's own default engine.
362 :return: The AI response as a string.
363 """
364 raise NotImplementedError
365
366 async def search(
367 self,
368 search_query: str,
369 media_types: list[MediaType],
370 limit: int = 5,
371 ) -> SearchResults:
372 """
373 Perform a search on this plugin.
374
375 Will only be called if ProviderFeature.SEARCH is declared.
376
377 :param search_query: Search query.
378 :param media_types: A list of media_types to include.
379 :param limit: Number of items to return in the search (per type).
380 """
381 if ProviderFeature.SEARCH in self.supported_features:
382 raise NotImplementedError
383 return SearchResults()
384
385 async def get_similar_tracks(self, track: Track, limit: int = 25) -> list[Track]:
386 """
387 Retrieve a list of similar tracks for the given track.
388
389 Will only be called if ProviderFeature.SIMILAR_TRACKS is declared.
390
391 :param track: The reference track.
392 :param limit: Maximum number of similar tracks to return.
393 """
394 if ProviderFeature.SIMILAR_TRACKS in self.supported_features:
395 raise NotImplementedError
396 return []
397
398 async def get_recommendations(self) -> list[RecommendationFolder]:
399 """
400 Get this plugin's available recommendation rows, without items.
401
402 Must be fast: return static or cached row descriptors only, without
403 live backend calls. The items for a row are fetched separately
404 through get_recommendation_items.
405
406 Will only be called if ProviderFeature.RECOMMENDATIONS is declared.
407 """
408 if ProviderFeature.RECOMMENDATIONS in self.supported_features:
409 raise NotImplementedError
410 return []
411
412 async def get_recommendation_items(
413 self, item_id: str
414 ) -> UniqueList[MediaItemType | ItemMapping | BrowseFolder]:
415 """
416 Get the items for a single recommendation row.
417
418 Live backend fetches belong here. Will only be called if
419 ProviderFeature.RECOMMENDATIONS is declared.
420
421 :param item_id: The item_id of the row, as returned by get_recommendations.
422 """
423 if ProviderFeature.RECOMMENDATIONS in self.supported_features:
424 raise NotImplementedError
425 return UniqueList()
426
427 async def browse(self, path: str) -> Sequence[MediaItemType | ItemMapping | BrowseFolder]:
428 """
429 Browse this plugin's contents.
430
431 Will only be called if ProviderFeature.BROWSE is declared.
432
433 :param path: The path to browse, in the form ``<instance_id>://<sub_path>``.
434 """
435 if ProviderFeature.BROWSE in self.supported_features:
436 raise NotImplementedError
437 return []
438
439 async def get_playlist(self, prov_playlist_id: str) -> Playlist:
440 """
441 Return details of a single playlist owned by this plugin.
442
443 :param prov_playlist_id: Provider-scoped playlist id.
444 """
445 raise NotImplementedError
446
447 async def get_playlist_tracks(self, prov_playlist_id: str, page: int = 0) -> list[Track]:
448 """
449 Return a page of tracks for a playlist owned by this plugin.
450
451 :param prov_playlist_id: Provider-scoped playlist id.
452 :param page: Zero-based page index for paginated results.
453 """
454 raise NotImplementedError
455
456 async def resolve_image(self, path: str) -> str | bytes:
457 """
458 Resolve an image from an image path.
459
460 This either returns (a generator to get) raw bytes of the image or
461 a string with an http(s) URL or local path that is accessible from the server.
462 """
463 return path
464