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 / playback-system

Playback system

The playback system turns a selected song or episode into continuous audio. It connects app and external controls to a Media3 session, builds and advances queues, resolves online streams, uses completed downloads when available, and applies audio rules before sound reaches the device.

Playback lifecycle

Playback flow

The playback flow starts with a media selection and ends with audio output and updated playback state. The long-running playback service owns this flow so playback can continue when the app screen is not visible.

This diagram shows how a selection moves through queue creation, session control, stream or download access, and audio output.

flowchart LR
    A[Song or episode selection] --> B[Media metadata]
    B --> C[Queue]
    C --> D[Media3 player]
    D --> E{Available source}
    E -->|Completed download| F[Offline cache]
    E -->|No completed download| G[Resolved online stream]
    F --> H[Audio processing]
    G --> H
    H --> I[Device or cast output]
    D --> J[Media3 session state]
    J --> K[App and external controls]

MusicService is the central owner of the player, session, queue state, audio focus, and recovery work. UI code reads that state through PlayerConnection instead of owning a second player. (MusicService, PlayerConnection)

References: app/…/MusicService.kt• L266-269 app/…/PlayerConnection.kt• L54-66

Media selection

Media identity

MediaMetadata is the shared description of a playable item. Its stable media ID links the item to database records, queue entries, cache data, stream URLs, downloads, artwork, and playback state.

The system converts this description into a Media3 MediaItem. The item keeps the media ID as its identity and carries title, artist, album, artwork, explicit status, and episode or video information for the player and external clients.

References: app/…/MediaMetadata.kt• L19-40 app/…/MediaItemExt.kt• L20-53

Selection sources

Selections can come from local library content, online YouTube content, search, playlists, radio, Android Auto, widgets, or an external media controller. Each source is converted to the same Media3 item shape before it enters playback.

The session callback maps browsable library paths and search results to playable items. A direct selection from a local artist, album, playlist, or downloaded list becomes a queue with the selected item as its start point. (MediaLibrarySessionCallback)

References: app/…/MediaLibrarySessionCallback.kt• L177-187 app/…/MediaLibrarySessionCallback.kt• L542-637 app/…/MediaLibrarySessionCallback.kt• L640-759

Media3 session control

Playback session

The playback session is the control boundary for the app, notification, Android Auto, and other Media3 controllers. MusicService exposes a MediaLibrarySession and keeps a controller connected so system playback controls remain active while the app is in the background.

The service is declared as a media playback foreground service. This gives the session a process that can continue audio playback and show a system media notification outside the main activity. (Android manifest, MusicService)

For the narrower rules for session connection, controller commands, and session delivery, see Media session and streaming.

References: app/…/AndroidManifest.xml• L233-248 app/…/MusicService.kt• L640-736

Library browsing

The session also presents a browsable media library to external clients. Its root can expose liked songs, songs, artists, albums, playlists, and optional online playlists. Child requests then load local database content or online playlist content.

This makes browsing and playback use the same media identity rules. A client can browse to an item and then ask the session to play it without knowing how the app stores or resolves that item. (MediaLibrarySessionCallback, MediaLibrarySessionCallback)

References: app/…/MediaLibrarySessionCallback.kt• L141-161 app/…/MediaLibrarySessionCallback.kt• L177-357

Session commands

The session supports normal player commands plus app actions such as like, start radio, library changes, shuffle, repeat, and adding to a target playlist. These actions let external controls reach product behavior without direct access to the service.

The service refreshes the notification layout when the current song or playback mode changes. The command state therefore follows the same player state that the app reads. (MediaLibrarySessionCallback, MusicService)

References: app/…/MediaLibrarySessionCallback.kt• L94-129 app/…/MusicService.kt• L1576-1634

Streaming

Stream resolution

Online playback resolves a media ID into a current stream URL and request details. The resolver uses the selected audio quality and media hints, then gives Media3 a source that can read the stream by range.

The player first checks known cached data and a cached stream URL. If neither can serve the requested bytes, it asks the playback extractor for a fresh stream. This keeps URL work out of the selection layer and lets playback refresh an expired URL without rebuilding the whole queue. (MusicService)

References: app/…/MusicService.kt• L3781-3859 app/…/StreamUrlCache.kt• L1-120

Cache layers

Playback separates temporary player cache data from completed download data. The player cache can support normal streaming and partial reuse. The download cache represents content that the user can play offline.

A completed download is removed from the player cache so the permanent download source remains authoritative. The download state also updates the database, which allows the library and downloaded queue to reflect whether content is ready. (MusicService, DownloadUtil)

References: app/…/MusicService.kt• L3474-3501 app/…/DownloadUtil.kt• L263-299

Stream recovery

Playback treats a stream failure as a recoverable event when a fresh URL, a cleared cache entry, a different stream client, or a network retry can restore the item. It keeps the current media item and position where possible.

If the network is absent, the service waits for connectivity and prepares the item again when the network returns. If recovery attempts end, the service either advances to the next item or stops according to the auto-skip and autoplay settings. (MusicService, MusicService)

References: app/…/MusicService.kt• L1478-1547 app/…/MusicService.kt• L3016-3104

Queues

Queue sources

A queue is the ordered playback plan plus the rule for obtaining more items. A finite ListQueue serves local or already loaded items. Online queues use continuation data to load more items from a YouTube playlist or radio result.

The service filters queue items before loading them into Media3. Explicit and video-song settings can remove items while preserving the selected start item when possible. Radio can replace the current tail with recommendations without interrupting the current item. (Queue, YouTubeQueue, YouTubePlaylistQueue)

References: app/…/Queue.kt• L12-45 app/…/ListQueue.kt• L11-23 app/…/YouTubeQueue.kt• L26-107 app/…/YouTubePlaylistQueue.kt• L28-69

Queue loading

The service loads the first queue page before normal playback starts. Near the end of an online queue, it requests the next page and appends the result. This keeps initial startup small while allowing long playlists and radio sessions to continue.

When a user adds items next, the service inserts them after the current item. It can remove duplicate entries and rebuild the shuffle order so the new items play in the expected place. (MusicService, MusicService, MusicService)

References: app/…/MusicService.kt• L1761-1834 app/…/MusicService.kt• L2030-2064 app/…/MusicService.kt• L2504-2599

Queue persistence

The system can save the queue, current item, position, shuffle mode, repeat mode, and play intent for later restoration. Restored queue data is converted back into playable Media3 items so playback can resume without repeating the original selection flow.

Persistence preserves the loaded items and their position as the reliable resume point. Source-specific queue state can fall back to that loaded list when the original online source cannot be rebuilt. For queue storage and offline resume rules, see Queues and offline playback. (PersistQueue, Queue extensions, PersistPlayerState)

References: app/…/PersistQueue.kt• L10-45 app/…/QueueExt.kt• L18-116 app/…/PersistPlayerState.kt• L10-18

Offline downloads

Download lifecycle

Downloads turn a media selection into a durable offline item. The download manager prepares the media metadata, resolves the stream through a download-specific source, writes it to the download cache, and reports progress through a foreground service notification.

The system limits concurrent download preparation and does not mark an item as downloaded until Media3 reports completion. Failed, stopped, or removed downloads clear the downloaded status in the database. (DownloadUtil, DownloadUtil, ExoDownloadService)

References: app/…/DownloadUtil.kt• L65-106 app/…/DownloadUtil.kt• L236-317 app/…/ExoDownloadService.kt• L22-80

Offline playback

Playback can read a completed item from the download cache without contacting the online stream service. The downloaded library and downloaded queue use completion state rather than the presence of a partially prepared request.

Normal player cache activity does not make an item an offline download. The system only marks cache-backed playback as downloaded after a natural completion and a full byte-range check. This prevents a short prefetch or an early skip from appearing as a user download. (MusicService, MediaLibrarySessionCallback)

References: app/…/MusicService.kt• L1732-1759 app/…/DownloadUtil.kt• L263-299 app/…/MediaLibrarySessionCallback.kt• L690-729

Audio controls

Output control

The service combines the user volume with mute, sleep-timer, and audio-focus limits to calculate the effective player volume. Android audio focus pauses playback for a full loss, restores it after a recoverable loss when appropriate, and lowers it for ducking.

The player also handles noisy output changes, Bluetooth reconnect behavior, and optional pause on device mute. These rules protect the listening session when another app or audio device changes the output environment. (MusicService, MusicService, MusicService)

Audio processing

The player can apply equalizer settings, loudness normalization, skip-silence processing, crossfade, and playback speed before output. These controls change the audio path without changing the queue or media identity.

Silence processing can either reduce ordinary silent gaps or detect a long silent section and seek forward in short steps when instant skipping is enabled. Loudness and equalizer changes are applied to the active player so the current item reflects new settings. For user-facing audio behavior and automation, see Audio controls and automation. (MusicService, SilenceDetectorAudioProcessor, VolumeNormalizationAudioProcessor)

References: app/…/MusicService.kt• L1289-1367 app/…/SilenceDetectorAudioProcessor.kt• L16-109 app/…/VolumeNormalizationAudioProcessor.kt• L12-60

Playback state

Application state access

PlayerConnection provides a safe read and control surface for app screens. It mirrors readiness, play state, current metadata, queue windows, shuffle, repeat, errors, mute state, and network waiting state from the service.

This boundary also lets the UI observe database-backed song, lyrics, and format data for the current media item. It attaches to a replaced player instance when the service recreates the player, which keeps the UI connected during recovery. (PlayerConnection)

References: app/…/PlayerConnection.kt• L94-239 app/…/PlayerConnection.kt• L242-300

Change checklist

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

  • Keep the media ID contract aligned across MediaMetadata, MediaItem, database rows, stream cache keys, and download request IDs.
  • When changing session library paths or media IDs, update both browsing results and onSetMediaItems mapping so external clients can play what they browse.
  • When changing cache or download completion rules, keep player cache state separate from completed download state.
  • When adding a queue source, define both its initial status and its next-page behavior, then define how its saved items restore after restart.
  • When changing audio focus or volume rules, preserve the relationship between user volume and temporary multipliers from the sleep timer and focus system.

Important failure modes

TriggerConsequenceGuard
A stream URL expires or its cached range is invalidThe current item stops or fails to loadInvalidate the URL and relevant cache, then prepare a fresh stream at the saved position.
The network stays unavailable during retriesPlayback remains paused until connectivity returnsKeep a network-waiting state and trigger a prepare when the connectivity observer reports recovery.
A download stops or is removed before completionThe item must not appear as available offlineUpdate the database only from the download state transition and clear the download status on stop or removal.
A queue source cannot load another pagePlayback can end with no next itemStop further continuation attempts after bounded retries and keep already loaded items playable.
Audio focus is lostTwo apps can compete for output or the user can miss the resume statePause on full or transient loss and restore only when the service still owns the playback intent.

Key files

FileWhy to read it
app/…/MusicService.ktCentral lifecycle for the Media3 player, session, queues, streaming, recovery, and audio behavior.
app/…/MediaLibrarySessionCallback.ktContract for external browsing, search, item selection, and custom session actions.
app/…/PlayerConnection.ktState and control boundary used by the app UI.
app/…/MediaItemExt.ktShared conversion from media metadata to playable Media3 items.
app/…/Queue.ktQueue contract for initial items, continuation, and filtering.
app/…/DownloadUtil.ktDownload preparation, completion state, and download-to-cache flow.
app/…/ExoDownloadService.ktForeground service boundary for download progress and cancellation.
app/…/PersistQueue.ktSaved queue shape used to resume playback after restart.
app/…/AndroidManifest.xmlAndroid service declarations and the external media entry points.