Skip to content

Architecture Notes ​

For a complete architecture overview, see the parent repository's docs/architecture_frontend.md (directory structure, page routing, responsive layout, theme system, and deployment modes). This document focuses on supplementary implementation details.


State Management ​

Choosing Provider Types ​

The project uses flutter_riverpod with hand-written Providers (no code generation):

TypeWhen to UseExamples
ProviderStateless singletons or computed valuesdioProvider, routerProvider, isPlayingProvider
NotifierProviderSynchronous stateful business logicplayerStateProvider, authStateProvider, baseUrlProvider
AsyncNotifierProviderAsync stateful + CRUDserversProvider, playlistListProvider, songsListProvider
FutureProviderOne-shot async loadingsongDetailProvider, configsProvider, appPreferencesProvider
FutureProvider.familyParameterized async loadingsongDetailProvider(id), playlistDetailProvider(id)
StreamProviderContinuous data streamssystemVolumeProvider

Provider Dependency Chain ​

appPreferencesProvider (SharedPreferences)
    ↓
secureStorageProvider → dioProvider → [feature xxxApiProvider]
    ↓                       ↓
authStateProvider      baseUrlProvider ← serversProvider
    ↓
routerProvider (redirect guard)

Core principle: dioProvider watches baseUrlProvider via ref.watch. When baseUrl changes, the Dio instance is automatically rebuilt, and all downstream API providers update accordingly.

PlayerNotifier Lifecycle ​

PlayerNotifier's core business logic has been extracted into domain/use_cases/ pure Dart layer (see Domain Layer Architecture):

  • PlayQueue: Queue add/insert/remove/move with correct currentIndex tracking
  • PlayModeResolver: next/prev index calculation for 5 play modes, shuffle deduplication
  • PlaybackRetryPolicy: Local/network song retry strategy (exponential backoff), consecutive failure threshold
  • SongCompletionRouter: Song completed → action routing
  • SleepTimerLogic: Sleep timer (by duration / by song count)
  • QueueLoader: Background batch loading + generation-based race cancellation + ring assembly
  • PrefetchStrategy: Prefetch decision logic

The Notifier itself retains:

  • Play generation _playGeneration: Old coroutines detect generation change after each await and exit
  • Platform interaction: Calls to SongloftAudioHandler (audio), VolumeController (system volume)
  • State updates: Drives UI rebuilds
  • Playback state persistence: _saveDebounceTimer debounces queue saves; _positionSaveTimer saves position every 10s

Network Layer ​

Multi-Server Management ​

ServersNotifier (core/network/servers_provider.dart) manages server list CRUD and persistence.

Startup flow (StartupGate):

  1. Load persisted RunMode (local / remote)
  2. Local mode (Bundle): request required storage access → start the embedded backend (EmbeddedBackendService.start()) on a dynamic port → after its health check, set baseUrlProvider to 127.0.0.1:<port> → read the local backend-generated administrator credentials and sign in automatically; do not use the server's default admin/admin
  3. Remote mode: load persisted server list → single server: use directly; multiple servers: probe reachability in parallel (max 2.5s) → write the highest-priority successful result to baseUrlProvider; fall back to the first item if all fail
  4. Set probeOutcomeProvider for the home screen SnackBar
  5. In embedded mode, skip probing and use Uri.base directly
  6. BackendLifecycle (WidgetsBindingObserver) monitors app lifecycle — auto-restarts backend on resume, stops on detached

Dynamic baseUrl Switching ​

BaseUrlNotifier (core/network/base_url_provider.dart) is the single source of truth for baseUrl. Writes are mirrored synchronously to AppConfig.baseUrl for non-Riverpod contexts (e.g. UrlHelper string concatenation).

Token Refresh Flow ​

AuthInterceptor handles JWT dual-token:

  1. Request intercept: non-public paths automatically inject Authorization: Bearer <accessToken> (memory cache preferred, falls back to storage)
  2. Response intercept: on 401, trigger refreshToken → retry original request on success; call onTokenExpired callback on failure to trigger logout
  3. Concurrency protection: _isRefreshing + Completer ensures multiple concurrent 401s trigger only one refresh

Public paths (/auth/login, /auth/refresh, /version, /health) skip token injection.


Storage Layer ​

ServiceFileBackendPurpose
SecureStorageServicecore/storage/secure_storage.dartSharedPreferences + memory cacheToken storage (access/refresh/expiry)
AppPreferencescore/storage/app_preferences.dartSharedPreferencesUser preferences (theme, baseUrl, server list, volume, playback mode, last login credentials)
PlaybackStateStoragecore/storage/playback_state_storage.dartNative: file (playback_queue.json); Web: SharedPreferencesPlayback queue + progress persistence, restored on app restart
LyricCacheServicecore/storage/lyric_cache_service.dartNative: file (lyric_cache/ directory); Web: in-memory onlyLyric cache to avoid repeated network requests

Token Storage Strategy ​

SharedPreferences is used exclusively (not FlutterSecureStorage). For self-hosted local music servers, simplified storage is acceptable. cachedAccessToken / cachedRefreshToken static variables provide synchronous reads, working around unstable storage reads on Windows.


Platform Specialization ​

TV Mode Detection ​

TvDetector (core/env/tv_detector.dart) detects whether the app is running on a TV system at startup and writes the result to AppConfig.isTvMode (late final, set only once).

In TV mode:

  • Uses TvThemeConstants for larger buttons and font sizes
  • Routes to TvHomePage (top Tab navigation)
  • TvFocusable focus component supports D-Pad directional navigation

Live Activity ​

LiveActivityService (core/platform/live_activity_service.dart) provides a Lock Screen Live Activity on iOS to display the currently playing song.

Window and Tray ​

WindowTrayManager (core/utils/window_tray_manager.dart) manages window size and position memory, system tray icon, and menu on desktop platforms (macOS/Windows/Linux).


Audio Playback ​

SongloftAudioHandler ​

Integrates audio_service for system notification bar controls. Core design:

  • Uses the official pipe() pattern to connect playbackEventStream directly to playbackState, which is more reliable than manual listen + add
  • Notification callbacks (onSkipToNext / onSkipToPrevious / onSongCompleted) are injected by PlayerNotifier
  • notifySongActivated hook: notifies the backend to cancel in-progress work (prefetch/transcode) for the old song before switching, resolving an issue where LockCachingAudioSource does not abort upstream HTTP connections

Building the Play Queue When Tapping a Song in a Paginated List (hard rule, songloft-org/songloft#299) ​

Long lists such as playlists, the song library, and category browsing are all loaded via scroll pagination (first page 100 items, loadMore fetches the next page on hitting the bottom). When a song is tapped in such a list to start playback, the "currently loaded page slice" must never be treated as the complete play queue — otherwise the queue is truncated to the loaded page (e.g. capped at 100), looping within that page; it only grows to 200/300 passively after the user scrolls and triggers loadMore. This is exactly the behavior reported in #299.

Unified convention: tapping a song in a paginated list = start playing immediately from the loaded slice + startIndex PLUS if total > loaded count, background-fill the entire queue from the loaded offset onward, using the exact same filter/sort as the list. The fill goes through PlayerNotifier's background loader and is guarded by _loadGeneration: an in-flight fill is automatically invalidated when the user switches playlists / changes filters / clears the queue.

List sourceStart + fill entry pointFill criteria
Playlist detail (normal / TV)playPlaylistFromLoaded(loadedSongs, startIndex, playlistId, total, sort, order, keyword)Same sort/order/keyword, paged by playlistId
Library "All Songs" (normal / TV)playPlaylist(...) + loadRemainingSongsForCurrentPlaylist(keyword, type, ...)Same keyword/type filter
Category pages (album / artist / genre / decade…, normal / TV)playPlaylist(...) + loadRemainingSongsForCurrentPlaylist(..., genre/artist/album/language/style/year/decade)Same category-dimension filter, mapping via categorySongsFilter(key)

Key points:

  • Filter/sort must match the list: if the fill uses default criteria instead of the list's current sort/order/keyword/category dimension, the filled-in songs will be misaligned with the order/scope the user sees. The (field,value) → getSongs params mapping for category dimensions goes through categorySongsFilter(key) (category_provider.dart) as the single source of truth — do not re-implement it in the UI layer.
  • "Play All" is a separate path: it uses playPlaylistById (playlists) or loadAll() followed by playPlaylist (category/facet), which already covers the full set and is unaffected by this convention.
  • No fill needed when the list is already complete: the queue drawer / queue_page use state.playlist (the play queue itself), and the plugin setQueue receives the plugin's already-resolved full song list — neither is a paginated slice.
  • Any new "tap-to-play in a paginated list" page must wire up both "start + background fill", otherwise it reintroduces the same truncation.

Audio Backend per Platform ​

PlatformBackend (default)Notes
WebHTML5 Audio + hls.jsCustom SongloftWebJustAudioPlugin (just_audio_web + self-integrated hls.js for HLS radio)
Androidlibmpv (media_kit)just_audio_media_kit; unified media_kit(libmpv), supports in-app video
iOSlibmpv (media_kit)Same; unified media_kit(libmpv), supports in-app video
macOSlibmpv (media_kit)Same; unified media_kit(libmpv), supports in-app video
Windows / Linuxlibmpv (media_kit)just_audio_media_kit, LGPL-2.1+

All native platforms (Win/Linux/macOS/Android/iOS) uniformly use media_kit(libmpv) — no fallback, no kill-switch. Backend selection is centralized in AudioBackend.usesMediaKit (core/audio/audio_backend.dart, simplified to !kIsWeb), unifying the backend and enabling in-app video (songloft-org/songloft#76).

Video Rendering & the Web Backend Decision (songloft-org/songloft#76) ​

Video containers (mp4/mov/mkv/webm/avi/ts) are probed by the backend's ffprobe for is_video. In-app picture rendering takes two paths:

  • Native platforms (Win/Linux/macOS/Android/iOS): derive a VideoController from the same media_kit Player used for audio (core/audio/video_controller_provider.dart) — picture and audio share one engine, naturally in sync, no second player. The VideoStage widget renders the picture for video songs, otherwise falls back to the cover.
  • Web: a muted native <video> (features/player/.../web_video_view_web.dart) shows only the picture; audio still plays through SongloftWebJustAudioPlugin, and the two are synced by play/pause/position from playerStateProvider.

Why not migrate Web to media_kit for a unified backend? (investigated — don't relitigate)

  • media_kit does not use libmpv on Web; its web backend is just the browser <video> element, and HLS is enabled by dynamically injecting hls.js (media_kit source media_kit/lib/src/player/web/utils/hls.dart). So switching to media_kit cannot drop hls.js — it just replaces "we integrate hls.js" with "media_kit integrates it for you"; HLS capability doesn't improve (official docs call web format support "extremely limited").
  • The bridge package just_audio_media_kit targets Windows/Linux and has no web implementation. Using media_kit on Web would require abandoning just_audio for the media_kit Player API across the whole web layer (touching the entire audio_service/player_provider state machine) — a cost far exceeding the benefit of "maintaining one less hls.js hookup".
  • Conclusion: Web keeps just_audio_web + custom hls.js (radio) + muted <video> (picture). Revisit a full-layer migration only if unified Web video maintenance becomes a hard requirement.