DEV Community

Cover image for Offline downloads on Android: one state machine, a foreground service and HLS
Yonto Player
Yonto Player

Posted on

Offline downloads on Android: one state machine, a foreground service and HLS

A download sounds like the easy part of a media app: fetch a file, play it later. The transfer has to survive the screen turning off, a dropped connection and the process being reclaimed. The player has to prefer the local file over the stream, and the title page has to work with no connection.

This post is about how that is built in Yonto Player on Android phones and tablets, and about the few decisions that keep it small.

One record, one state machine

Every download is a DownloadRecord, keyed by the same play key that a title's resume point uses. That choice matters later: the file a download becomes is found by the identity History already uses, so the downloaded copy of a title in your own library is found the way its resume point is.

The record has five states, and the rules for moving between them live in one function in the shared core:

// Simplified sketch of the download state machine, not the exact source.
enum class State { QUEUED, RUNNING, PAUSED, FAILED, DONE }

sealed interface Event {
    object Started : Event
    data class Progress(val done: Long, val total: Long?) : Event
    object Pause : Event
    object Resume : Event
    data class Fail(val message: String) : Event
    object Complete : Event
    object Interrupted : Event
}

// Returns the next record, or null when the event is not legal in this state.
fun Record.on(event: Event): Record? = when (state) {
    State.QUEUED  -> when (event) {
        Event.Started -> copy(state = State.RUNNING)
        Event.Pause   -> copy(state = State.PAUSED)
        is Event.Fail -> copy(state = State.FAILED, error = event.message)
        else -> null
    }
    State.RUNNING -> when (event) {
        is Event.Progress -> copy(bytesDone = event.done)
        Event.Pause       -> copy(state = State.PAUSED)
        is Event.Fail     -> copy(state = State.FAILED, error = event.message)
        Event.Complete    -> copy(state = State.DONE)
        Event.Interrupted -> copy(state = State.QUEUED)
        else -> null
    }
    State.PAUSED, State.FAILED -> if (event == Event.Resume) copy(state = State.QUEUED) else null
    State.DONE -> null
}
Enter fullscreen mode Exit fullscreen mode

Two details carry most of the weight. First, an illegal event returns null and changes nothing, so a late "progress" that arrives after a pause is simply refused rather than corrupting the record. Second, Interrupted sends a running download back to QUEUED. If the process dies mid-transfer, the next start finds a record that says "running", marks it interrupted, and queues it again to continue from the bytes already on disk.

A paused or failed download can be resumed, which queues it again. Cancelling and removing are not transitions. They delete the record, which keeps the machine small. The repository exposes one apply(playKey, event) call, and an engine never writes a state itself, so the legal moves live in one place. A unit test tries each state against each event and checks that only the legal ones take effect.

The engine is a seam

How the bytes are fetched is the engine's business, so the shared code only knows an interface. A simplified sketch of it:

// Simplified sketch of the engine seam, not the exact source.
interface DownloadEngine {
    suspend fun start(request: DownloadRequest)   // queue it; start when the engine can
    suspend fun pause(playKey: String)
    suspend fun resume(playKey: String)
    suspend fun cancel(playKey: String)           // not done yet: stop, delete the partial file and the record
    suspend fun remove(playKey: String)           // any state: delete the file and the record
}
Enter fullscreen mode Exit fullscreen mode

The Android implementation reports every change through the repository's apply, runs at most two transfers at a time, and waits when the network is not one the viewer allows. Downloads use Wi-Fi only by default, and turning that off lets a download use mobile data.

A foreground service for long transfers

A transfer that lasts minutes cannot rely on the app being on screen. A foreground service of the data-sync type keeps a transfer running while the screen is off, and shows one ongoing notification with Pause and Cancel for the download that has run longest. When a download finishes or fails, a quiet notification says so.

The service is thin. It keeps the process running and the notification current by watching the same records the screens watch, and its buttons call the same pause, resume and cancel as the in-app ones. A paused download keeps a plain notification of its own, with Resume and Cancel, that does not hold the service open.

Android 15 ends a data-sync service after a time limit, so the service handles the timeout callback, and the next fetch asks for a service again.

What can be downloaded

The app plays your own library, and a download is a copy of a title from it for when you have no connection. Whether a title can be downloaded is decided in two steps when you touch Download. First comes the kind of source: titles that come over the network from your own Jellyfin, Emby or Plex server, a WebDAV folder or a cloud drive of your own can be downloaded, and a folder on the device cannot, because the file is already there. Then the stream the source gives for that title is checked:

  • A video that is one file downloads as it is served, with a ranged request so a resume asks for the same file from where it stopped.
  • A video that comes in pieces (an HLS playlist) is fetched piece by piece into one file.
  • A live stream is refused with a sentence: "A live stream can't be downloaded." A live channel has no end to save, and a playlist with no end marker counts as live.
  • Pieces that cannot be put into one file, such as DASH or protected pieces, are refused with their own sentence rather than saved as something that will not play.

The refusal happens before anything starts, and a download that turns out to be pieces after it began stops with the same sentence in the Downloads list. Saying why is cheaper than leaving a ring that never fills.

A note on use: downloads are for titles you have the right to keep, such as your own media. Please respect copyright and the terms of the services you use, and do not use downloads to copy or share content you have no right to. Yonto Player does not provide content and is not meant for piracy.

HLS as one file

The HLS fetch reads the playlist, follows a master playlist to its highest-bandwidth variant, and appends each piece in order to the download's .part file. Transport-stream pieces make a .ts file, and fragmented-MP4 pieces make an .mp4. AES-128 encrypted pieces are decrypted as they are written.

Two things make it resumable. A small progress file beside the .part records how many pieces are whole and how long the file was then, so a pause or a dropped connection continues from the last whole piece. And when the last piece lands, a transport stream is rewritten as an MP4 where the stream can be carried in one, because a transport stream has no index and a player has to search it to seek. The H.264 pictures and AAC frames are copied, not decoded, so it is a repackaging and not a re-encode. When the stream cannot be carried in an MP4, the transport stream is kept as it is.

Choosing what to download

A film that comes in several versions asks which one first. For a series, the Download button under Play opens a sheet of episodes with a box each. It starts with the next three unwatched episodes ticked, counted from the episode Resume would play, and two chips, Next 3 unwatched and All unwatched, tick episodes again. Select all and Select none work on a season. An episode that already has a download cannot be ticked, so a sheet never counts, sizes or starts the same file twice.

Sizes are asked from the source when the sheet opens, and the total says "at least" until they arrive, because the sheet does not guess.

A finished download plays under the same key

When a download is done, playable(playKey) hands back a local file target for it. When the player redeems what to play, it asks for that key first and falls back to the source's stream only when there is no download. The record also keeps what a title page needs, such as the label, the poster and the picture format, so the page can be drawn with the source out of reach.

With no connection, a title's page is built from its finished downloads. Each download becomes a playback option that saves its progress under the play key it was downloaded for, so the resume point, History and the next episode work as they do for a stream. Before a downloaded file is handed to the player, its size is checked against the record, and a file that is missing or the wrong size removes its download rather than offering something that will not play.

What to take from it

  • Put the legal transitions in one pure function and make every engine go through it. The engine decides how to fetch, not what a download is allowed to do.
  • Key the download by the identity playback already uses. Offline playback then needs no new concept.
  • Decide what is downloadable from the kind of source and then the stream, and say why when it is not.
  • For HLS, write to one file and record where you are, so a resume is a seek to the last whole piece.

Read more

Top comments (1)

Collapse
 
prikshit profile image
Prikshit •

Returning null for an illegal event is a neat way to stop a late progress update from undoing a pause. The case I'd look at in that transition test is Interrupted going back to QUEUED and resuming from the bytes on disk, because for HLS those bytes are a set of segments, so resuming means knowing which segments finished and whether the playlist changed. Does the engine refetch the playlist on resume or trust the copy it saved?