# Offline

Download a video, an episode or a whole HLS stream with MediaDownloads, follow its progress, and play it from the device without network.

`MediaDownloads` keeps media on the device. Once a URI is stored, a player opening that same URI
plays the stored copy, network or not; nothing changes in your player code. Downloads survive
the app's restart.

## Download

```kotlin
MediaDownloads.download("https://example.com/hls/master.m3u8")
MediaDownloads.download(url, headers = mapOf("Authorization" to "Bearer $token"))
```

`download` returns at once. A file is stored whole; an HLS stream with every variant, audio
rendition, init segment, key and segment its playlists reference. Calling it again for a URI
already stored or in progress does nothing; a failed download starts over.

## Follow the progress

`downloads` is a `StateFlow` of every download:

```kotlin
val downloads by MediaDownloads.downloads.collectAsState()
downloads.forEach { d ->
    // d.uri, d.state (QUEUED, DOWNLOADING, COMPLETED, FAILED),
    // d.bytesDownloaded, d.totalBytes (-1 while unknown), d.error
}
```

A stream's total is unknown until it completes. A download the app quit during comes back
`FAILED`; download it again to resume.

## Play and remove

```kotlin
player.openUri("https://example.com/hls/master.m3u8")   // the stored copy, if COMPLETED
MediaDownloads.remove(url)                               // stops it and deletes the files
```

## Where it is stored

| Platform | Storage |
| -------- | ------- |
| Android | Media3's `DownloadManager`, in a cache of its own under the app's files; the player reads through it |
| Desktop | The app's data directory: `%LOCALAPPDATA%\<appId>\media-downloads` on Windows, `~/Library/Application Support/<appId>/media-downloads` on macOS. The system property `nucleus.media.downloadsDir` overrides it |
| iOS | The app's Application Support directory; a stored stream is served on loopback, since AVPlayer opens no playlist from a file |
| Web | The browser's Cache Storage, the list in `localStorage` |

Android downloads DASH and Smooth Streaming too, through their modules. On the desktop, iOS and
the web, a DASH or Smooth Streaming download fails rather than storing the manifest alone.

## What's next

- [Streaming](/docs/media/streaming): the formats a download can hold.
- [Platform support](/docs/media/platform-support): every difference between platforms.
