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 / media-session-and-streaming

Media session and stream delivery

The media session is the boundary between playback and external controls such as Android Auto, Bluetooth devices, and the system notification. MusicService owns this boundary and turns a requested song into a playable stream while keeping controls, queue state, recovery state, and eligible listening history aligned. See Playback system for the wider playback model.

Related pages: Queues and offline playback · Audio controls and automation

Media service boundary

MusicService is the long-lived playback service. It owns the active player and media session, exposes playback state to the app, and keeps audio running when the main activity is not visible. The session also lets external controllers use the same queue and transport controls as the app.

Session ownership

The service creates one media library session around the active player. The session publishes now-playing state and notification controls, while external controllers connect through the service session rather than reaching into the player directly. A controller that connects after the app task is cleared can restore the service's active state.

References: app/…/MusicService.kt• L266-283 app/…/MusicService.kt• L694-736 app/…/MusicService.kt• L4372-4394

Controller commands

The session exposes standard play, pause, seek, and skip actions. It also exposes app actions for like, library membership, shuffle, repeat, radio, and adding a song to a target playlist. These actions use the same service state as the app, so a change from a car or headset is visible to the app and notification.

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

Media library browsing

The media library callback presents the local and online catalog as a browsable tree. A controller starts at root, opens sections such as songs, artists, albums, and playlists, then selects playable media items. The callback reads local data from the music database and can add online search or YouTube playlist results when the request needs them.

Browse tree

The browse tree uses stable media ID paths to describe both containers and songs. Local playlists include liked songs and downloaded songs, while online playlists remain separate from saved local playlists. Results are paged so a controller can browse a large library without loading the full tree at once.

References: app/…/MediaLibrarySessionCallback.kt• L141-175 app/…/MediaLibrarySessionCallback.kt• L177-357 app/…/MediaLibrarySessionCallback.kt• L360-524

Search requests

Search combines local matches with online song matches and removes clear duplicates. A voice request can resolve to a local playlist or to the best matching song. When configured for auto-radio, the selected online song becomes the start of a radio queue instead of a single-item request.

References: app/…/MediaLibrarySessionCallback.kt• L542-637 app/…/MediaLibrarySessionCallback.kt• L761-877

Playback request lifecycle

Playback begins with a media item from the app or a connected controller. The callback expands that item into the correct surrounding list, and the service prepares the player with the selected start position. The stream resolver then supplies the audio URL only when the player needs data.

The main request path is:

flowchart LR
    A[App or external controller] --> B[Media session]
    B --> C[Media library callback]
    C --> D[Queue and start position]
    D --> E[MusicService player]
    E --> F{Cached stream or media data?}
    F -- Yes --> G[Read cached data]
    F -- No --> H[Resolve fresh stream]
    H --> I[Audio transport]
    G --> I
    I --> J[Playback state and controls]

Queue expansion

onSetMediaItems maps a selected ID to its parent context. A song from an album, artist, playlist, search result, or online playlist therefore starts with the related set of songs rather than losing its surrounding queue. Shuffle actions create a shuffled set before playback begins.

References: app/…/MediaLibrarySessionCallback.kt• L640-759

Player state bridge

PlayerConnection is the app-facing bridge to the service player. It observes readiness, playback state, current media metadata, queue windows, and errors through shared state. Its control methods choose local playback or Cast playback when a Cast session is active, while service-level rules can block user queue changes for a synchronized listening guest.

References: app/…/PlayerConnection.kt• L55-170 app/…/PlayerConnection.kt• L207-257 app/…/PlayerConnection.kt• L344-464

YouTube history reporting

The service can report qualifying listening to YouTube without waiting for the song to end. A history reporter follows each player and measures actual play time, so pauses, buffering, and seeks do not create listening time. It sends a report at the configured threshold and gives a failed report one final attempt when playback finishes. Privacy settings, account state, and player release can prevent a report or stop further retries.

References: app/…/MusicService.kt• L1366-1389 app/…/YouTubeHistoryReporter.kt• L36-65 app/…/YouTubeHistoryReporter.kt• L72-93

Stream URL delivery

Stream URLs are short-lived remote addresses. The service resolves them from the selected song and audio-quality policy, then supplies the URL and its request data to the player. The resolver also records stream format information so later playback and audio processing can use the same song facts.

URL cache

The stream cache stores a URL with its request headers, stream client, range rules, and expiry time. It is limited in size and keyed by media ID. A URL is reused only while it is valid; cache generations prevent a stale in-flight result from replacing a newer invalidation.

References: app/…/StreamUrlCache.kt• L12-19 app/…/StreamUrlCache.kt• L37-67 app/…/StreamUrlCache.kt• L72-121

Cache and stream selection

For each data request, the service first gives completed download data and player cache data a chance to satisfy the request. It then uses a valid resolved URL when possible. A quality change or a cache failure bypasses that URL and requests a fresh stream before playback continues.

References: app/…/MusicService.kt• L3781-3834 app/…/MusicService.kt• L3835-3959

Cast delivery

Cast playback needs a stream URL that can be sent to the remote device. MusicService resolves that URL from the same song and quality context, while PlayerConnection routes play, pause, seek, and skip actions to the Cast session when it is active.

References: app/…/MusicService.kt• L4760-4784 app/…/PlayerConnection.kt• L344-464

Transport control flow

Transport controls keep the user's intent separate from the playback target. Local controls act on the service player, while Cast controls act on the remote session. Both paths update the same app-facing state so the notification, app UI, and external controller remain consistent.

Local controls

Play prepares an idle player and sets its play intent. Pause clears that intent. Seek changes the current position. Previous restarts the current song when playback is past the restart threshold; otherwise it selects the previous item. Next selects the next item and resumes playback.

References: app/…/PlayerConnection.kt• L365-464

Audio focus

The service coordinates with Android audio focus so another audio app can pause or lower playback. A full loss pauses playback, a transient loss waits for focus to return, and a duck request lowers volume. If playback was active before a temporary loss, the service can resume it after focus returns.

References: app/…/MusicService.kt• L1369-1469

Playback recovery

Playback recovery distinguishes expired stream addresses, bad cached ranges, network loss, remote errors, and unsupported stream responses. The service clears the affected state, refreshes the stream or waits for connectivity, and retries the same position when recovery is safe.

Error recovery

An expired URL or remote playback error causes a stream refresh. A range or missing-cache-file error causes cached state to be rebuilt. A network error waits for connectivity and then prepares the current item again. Repeated failures are bounded so one broken song cannot create an endless retry loop; the service can stop or skip according to the configured error policy.

References: app/…/MusicService.kt• L2920-3105 app/…/MusicService.kt• L3320-3405

Network resumption

When the network is unavailable, the service marks playback as waiting instead of treating the current song as permanently failed. Backoff retries are limited, and the connectivity observer can trigger a new prepare when the network returns. This preserves the user's play intent after a temporary outage.

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

Change checklist

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

  • Keep media ID path rules aligned between browse results and onSetMediaItems; a valid browse item must still expand to the intended queue.
  • Keep URL expiry, cache invalidation, and retry behavior aligned; a refresh must not allow an older in-flight URL to replace a newer one.
  • Keep local and Cast transport actions aligned so the same user command targets the active playback device.
  • Keep custom session commands aligned with notification layouts and the service callbacks that perform the action.
  • Keep paging offsets aligned with leading shuffle and built-in playlist entries so controllers do not skip or duplicate songs.
  • Keep history thresholds, privacy checks, account checks, and final retry behavior aligned between MusicService and YouTubeHistoryReporter.

Important failure modes

TriggerConsequenceGuard
Expired or forbidden stream URLThe current item cannot continue from the old address.Invalidate the stream state and resolve a fresh URL.
Network loss during playbackThe player can remain paused until connectivity returns.Mark network wait state, retry with backoff, and prepare on reconnect.
Stale cache data or missing cache fileA cached range fails even though the song is known.Clear affected cache state and retry from a fresh stream.
Repeated failures for one songAutomatic retries can loop or delay the queue.Bound retries, then stop or skip by policy.
Browse path and queue expansion mismatchAn external controller starts the wrong list or no list.Treat media ID paths as a shared contract between browsing and selection.
History report starts after privacy or account state changesListening can be sent for the wrong account or against the current privacy choice.Recheck history permission and account identity before the request.
History report fails after live playbackA qualifying listen is missing from remote history.Retry once at the end with the same report request, then stop.

Key files

FileWhy to read it
app/…/MusicService.ktDefines the service boundary, media session, stream request path, transport integration, history reporting, and recovery policy.
app/…/MediaLibrarySessionCallback.ktDefines the browse tree, search behavior, controller commands, and queue expansion.
app/…/PlayerConnection.ktShows how app state and user controls connect to local or Cast playback.
app/…/StreamUrlCache.ktDefines URL expiry, cache invalidation, and protection against stale resolutions.
app/…/YouTubeHistoryReporter.ktDefines when qualifying listening is reported and how release, privacy, and failed requests affect that report.
app/…/YouTubeHistoryReporterTest.ktShows the guarantees for threshold timing, real play-time measurement, repeated listens, and bounded retries.
app/…/InnerTubeXPlayer.ktDescribes the stream data returned to the playback resolver, including URL lifetime and request data.
app/…/MediaLibrarySessionCallbackTest.ktCaptures the browse ID and paging contracts that external media controllers depend on.