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):
| Type | When to Use | Examples |
|---|---|---|
Provider | Stateless singletons or computed values | dioProvider, routerProvider, isPlayingProvider |
NotifierProvider | Synchronous stateful business logic | playerStateProvider, authStateProvider, baseUrlProvider |
AsyncNotifierProvider | Async stateful + CRUD | serversProvider, playlistListProvider, songsListProvider |
FutureProvider | One-shot async loading | songDetailProvider, configsProvider, appPreferencesProvider |
FutureProvider.family | Parameterized async loading | songDetailProvider(id), playlistDetailProvider(id) |
StreamProvider | Continuous data streams | systemVolumeProvider |
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 eachawaitand exit - Platform interaction: Calls to
SongloftAudioHandler(audio),VolumeController(system volume) - State updates: Drives UI rebuilds
- Playback state persistence:
_saveDebounceTimerdebounces queue saves;_positionSaveTimersaves position every 10s
Network Layer
Multi-Server Management
ServersNotifier (core/network/servers_provider.dart) manages server list CRUD and persistence.
Startup flow (StartupGate):
- Load persisted
RunMode(local / remote) - Local mode (Bundle): request required storage access → start the embedded backend (
EmbeddedBackendService.start()) on a dynamic port → after its health check, setbaseUrlProviderto127.0.0.1:<port>→ read the local backend-generated administrator credentials and sign in automatically; do not use the server's defaultadmin/admin - 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 - Set
probeOutcomeProviderfor the home screen SnackBar - In embedded mode, skip probing and use
Uri.basedirectly 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:
- Request intercept: non-public paths automatically inject
Authorization: Bearer <accessToken>(memory cache preferred, falls back to storage) - Response intercept: on 401, trigger refreshToken → retry original request on success; call
onTokenExpiredcallback on failure to trigger logout - Concurrency protection:
_isRefreshing+Completerensures multiple concurrent 401s trigger only one refresh
Public paths (/auth/login, /auth/refresh, /version, /health) skip token injection.
Storage Layer
| Service | File | Backend | Purpose |
|---|---|---|---|
SecureStorageService | core/storage/secure_storage.dart | SharedPreferences + memory cache | Token storage (access/refresh/expiry) |
AppPreferences | core/storage/app_preferences.dart | SharedPreferences | User preferences (theme, baseUrl, server list, volume, playback mode, last login credentials) |
PlaybackStateStorage | core/storage/playback_state_storage.dart | Native: file (playback_queue.json); Web: SharedPreferences | Playback queue + progress persistence, restored on app restart |
LyricCacheService | core/storage/lyric_cache_service.dart | Native: file (lyric_cache/ directory); Web: in-memory only | Lyric 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
TvThemeConstantsfor larger buttons and font sizes - Routes to
TvHomePage(top Tab navigation) TvFocusablefocus 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 connectplaybackEventStreamdirectly toplaybackState, which is more reliable than manuallisten + add - Notification callbacks (
onSkipToNext/onSkipToPrevious/onSongCompleted) are injected byPlayerNotifier notifySongActivatedhook: notifies the backend to cancel in-progress work (prefetch/transcode) for the old song before switching, resolving an issue whereLockCachingAudioSourcedoes 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 source | Start + fill entry point | Fill 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 paramsmapping for category dimensions goes throughcategorySongsFilter(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) orloadAll()followed byplayPlaylist(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_pageusestate.playlist(the play queue itself), and the pluginsetQueuereceives 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
| Platform | Backend (default) | Notes |
|---|---|---|
| Web | HTML5 Audio + hls.js | Custom SongloftWebJustAudioPlugin (just_audio_web + self-integrated hls.js for HLS radio) |
| Android | libmpv (media_kit) | just_audio_media_kit; unified media_kit(libmpv), supports in-app video |
| iOS | libmpv (media_kit) | Same; unified media_kit(libmpv), supports in-app video |
| macOS | libmpv (media_kit) | Same; unified media_kit(libmpv), supports in-app video |
| Windows / Linux | libmpv (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
VideoControllerfrom the same media_kitPlayerused for audio (core/audio/video_controller_provider.dart) — picture and audio share one engine, naturally in sync, no second player. TheVideoStagewidget 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 throughSongloftWebJustAudioPlugin, and the two are synced by play/pause/position fromplayerStateProvider.
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 sourcemedia_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_kittargets Windows/Linux and has no web implementation. Using media_kit on Web would require abandoning just_audio for the media_kitPlayerAPI across the whole web layer (touching the entireaudio_service/player_providerstate 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.
