Introducing a new way to review your PRs.

Read the announcement

metrolistgroup / metrolist

Material Design YouTube Music client for Android, iOS and desktop

View on GitHub

19 documents · Updated Nov 4, 2026

docs / queues-and-offline-playback

Queues, downloads, and offline playback

Metrolist turns song selections into a player queue, keeps the queue and player position across service restarts, and stores selected media for use without a network. The playback service joins queue data, local song records, download state, and player state so the item shown to the user matches the item that can play.

Queue construction

A queue is the source that supplies media items to the player. It can contain a fixed list, a remote playlist, a remote radio stream, or a local album with more related items loaded later. app/…/Queue.kt defines the common status returned to the playback service: title, items, start index, and position.

The main queue types serve different product flows:

Queue typePurposeMore items
ListQueuePlays a known set such as liked or downloaded songsNo
YouTubePlaylistQueuePlays a remote playlistLoads continuation pages
YouTubeQueueStarts radio or watch-based playbackLoads remote continuation pages
YouTubeAlbumRadioStarts with an album, then adds radio resultsLoads after the album
LocalAlbumRadioStarts with a saved album, then adds remote resultsLoads after the local songs

The playback service applies content rules before it gives a queue to the player. These rules can remove explicit songs or video songs while keeping the current song index stable when possible. Near the end of a queue, the service asks the queue for another page when auto-load is enabled; this lets a remote queue grow without loading all of its content at once. References: app/…/Queue.kt• L12-61, app/…/ListQueue.kt• L11-24, app/…/YouTubePlaylistQueue.kt• L16-70, app/…/YouTubeQueue.kt• L16-123, app/…/MusicService.kt• L1761-1834, app/…/MusicService.kt• L2578-2603

Queue persistence

Queue persistence preserves the current listening context when the playback service stops or the app restarts. The service writes the queue title, media metadata, current item index, and position to its private files. It also writes player state such as play intent, volume, repeat mode, shuffle mode, and playback position.

The persistence path works as follows:

  1. Queue changes and player state changes trigger a save. Periodic saves provide protection against a crash or force kill.
  2. Startup reads the saved queue and rebuilds media items from the stored metadata.
  3. Startup restores the saved index and position after the queue is ready.
  4. Invalid or unreadable files are cleared instead of blocking player startup.

The saved queue records its original queue kind, but remote and album-radio kinds currently restore as a fixed ListQueue made from the items already saved. A restored queue therefore keeps the visible listening order and position, but it does not resume the old remote continuation source. The persistent queue preference controls both restore and later saves. References: app/…/PersistQueue.kt• L10-45, app/…/PersistPlayerState.kt• L10-18, app/…/QueueExt.kt• L18-116, app/…/MusicService.kt• L1184-1261, app/…/MusicService.kt• L2601-2603, app/…/MusicService.kt• L4088-4165

Download service

The download service turns a song selection into a durable Media3 download. DownloadUtil first makes sure that the song and its album metadata exist locally. It then submits a request keyed by the song ID to ExoDownloadService, which owns the foreground download work and its progress notification.

Download preparation resolves a current audio stream and records its format and length. Up to three preparations or downloads can run in parallel. Artwork is also placed in the image cache so downloaded songs remain useful in local lists and player views.

Download state has two layers:

LayerMeaning
Media3 download index and DownloadUtil.downloadsCurrent queued, active, stopped, failed, or completed work
Song database fieldsProduct state used by local screens: isDownloaded and dateDownload

The database marks a song as downloaded only after Media3 reports completion. Failed, stopped, or removed work clears that mark. This separation prevents a song from appearing as a completed download when stream setup has started but no full file exists. References: app/…/DownloadUtil.kt• L65-74, app/…/DownloadUtil.kt• L233-317, app/…/DownloadUtil.kt• L321-387, app/…/ExoDownloadService.kt• L22-80, app/…/SongEntity.kt• L28-66, app/…/DatabaseDao.kt• L1249-1261

Offline media handling

Playback checks local media before it asks the network for a stream. The download cache is checked first because it represents durable offline media. The player cache is checked next when song caching is enabled. Only when neither cache has the needed byte range does the player resolve a fresh stream URL.

The playback path is therefore:

flowchart TD
    A[Player requests song bytes] --> B{Full range in download cache?}
    B -- Yes --> C[Play local download]
    B -- No --> D{Needed range in player cache?}
    D -- Yes --> E[Play cached stream data]
    D -- No --> F[Resolve a fresh remote stream]
    F --> G[Play and fill player cache]

The download resolver and the normal player resolver both use the song ID as the cache key. A completed download is removed from the temporary player cache so the durable download remains the clear source for offline playback. A partial player cache is not the same as an offline download; it may still need the network for missing ranges. References: app/…/MusicService.kt• L3474-3501, app/…/MusicService.kt• L3781-3847, app/…/DownloadUtil.kt• L96-130, app/…/DownloadUtil.kt• L263-276

Player state reconciliation

MusicService is the owner of the live queue and ExoPlayer state. PlayerConnection is the read and command boundary used by the rest of the app. It observes the active player instance, refreshes queue windows and indexes, and exposes current media metadata, playback state, and network wait state to the UI.

When a player instance changes, PlayerConnection detaches from the old instance and copies the new instance's current state. When a media item changes or the timeline grows, it updates the current index, queue windows, and skip controls. This keeps controls and screens aligned with the player after queue loads, restores, and player replacement.

The relationship between queue, caches, and state is:

sequenceDiagram
    participant User
    participant Connection as PlayerConnection
    participant Service as MusicService
    participant Queue
    participant Store as Queue and song stores
    participant Player

    User->>Connection: Start or change playback
    Connection->>Service: Submit queue action
    Service->>Queue: Get initial status
    Queue-->>Service: Items, index, position
    Service->>Player: Set media items and prepare
    Player->>Service: Transition or timeline event
    Service->>Queue: Load next page near queue end
    Service->>Store: Save queue and player position
    Service-->>Connection: Updated state flows
    Connection-->>User: Current item and controls

Network errors can pause playback while the service waits for connectivity, while a completed local download can continue without stream resolution. If recovery fails and auto-skip is allowed, the service advances to the next item; otherwise it stops. These choices change player state, which then flows back through PlayerConnection and the saved state path. References: app/…/PlayerConnection.kt• L122-239, app/…/PlayerConnection.kt• L242-317, app/…/PlayerConnection.kt• L595-668, app/…/MusicService.kt• L1761-1834, app/…/MusicService.kt• L2606-2668, app/…/MusicService.kt• L3439-3449

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to MediaItem IDs or custom cache keys must stay aligned with download request IDs and both cache layers.
  • Changes to queue metadata or queue types must remain readable by PersistQueue and must preserve the saved index and position contract.
  • Changes to download completion states must keep DownloadUtil.downloads, SongEntity.isDownloaded, and SongEntity.dateDownload consistent.
  • Changes to player replacement or timeline events must keep PlayerConnection attached to the active player and refresh queue indexes.
  • Changes to auto-load or filtering rules must preserve the relation between the current item index and the filtered queue.

Important failure modes

TriggerConsequenceGuard
A saved queue file cannot be read or rebuiltThe old queue and related saved state are clearedStartup wraps restore in failure handling and removes invalid files
A remote stream URL expires during a downloadThe download fails and its URL is invalidated for a later retryDownloadUtil detects expired HTTP errors and clears the download mark on failure
A song is marked downloaded before the download completesOffline lists can show media that is not fully availableDatabase completion state changes only from STATE_COMPLETED
A queue reaches its end while the network is unavailableNo new page is added and playback can stop or wait for recoveryAuto-load checks queue continuation and the service tracks network wait state
A cache entry is evicted or corruptedPlayback can report a file-not-found error instead of using the missing cache bytesCache errors are handled as playback failures and can fall back to stream resolution

Key files

FileWhy to read it
app/…/Queue.ktDefines the queue contract and index-safe filtering
app/…/YouTubePlaylistQueue.ktShows remote playlist paging
app/…/YouTubeQueue.ktShows radio queue creation and continuation behavior
app/…/MusicService.ktCoordinates queue loading, player state, cache lookup, restore, and save
app/…/DownloadUtil.ktDefines download requests, cache resolution, and completion state
app/…/ExoDownloadService.ktConnects the download manager to Android foreground work and notifications
app/…/PlayerConnection.ktExposes live player and queue state to app clients
app/…/QueueExt.ktMaps live queues to persisted queues and back
app/…/PersistQueue.ktDefines the saved queue shape and queue variants
app/…/DatabaseDao.ktDefines downloaded-song queries and download-state updates

Related pages: Playback system, Media session and streaming, Audio controls and automation