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