Android Video with Media3, Caching and Transformer
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. Jetpack Media3 is the supported way to play video on
Android. The standalone ExoPlayer repository (google/ExoPlayer) is archived, and its code lives on in the
androidx.media3 artifacts. Media3 artifacts are published on Google’s Maven repository, so check the current version
on the Media3 release page. The packaging that produces
what the player consumes is in video streaming: HLS, DASH and CMAF.
Dependencies
val media3 = "<version>" // use the current stable version from the release page
dependencies {
implementation("androidx.media3:media3-exoplayer:$media3")
implementation("androidx.media3:media3-exoplayer-hls:$media3")
implementation("androidx.media3:media3-exoplayer-dash:$media3")
implementation("androidx.media3:media3-ui:$media3")
implementation("androidx.media3:media3-datasource:$media3") // CacheDataSource and SimpleCache
implementation("androidx.media3:media3-database:$media3")
implementation("androidx.media3:media3-transformer:$media3") // on-device transcoding
implementation("androidx.media3:media3-effect:$media3")
}
Playing HLS and DASH
ExoPlayer chooses the media source from the URL’s type, so adding the exoplayer-hls and exoplayer-dash modules is
enough to play .m3u8 and .mpd. The player implements adaptive bitrate selection and switches rendition by segment.
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
class PlayerHolder(context: Context) {
val player: ExoPlayer = ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri("https://cdn.example.com/videos/42/master.m3u8"))
prepare()
playWhenReady = false
}
fun release() = player.release()
}
Release the player in onStop or when the composable leaves the composition, and create one player per screen, not per
list item. In a list, show the poster image (see
Coil and Glide) and create the player when the user taps play.
For private video, add the signed-cookie or token header with a custom DataSource.Factory, see
video streaming. Reference:
ExoPlayer hello world and
HLS support.
Caching segments with SimpleCache
SimpleCache stores downloaded media on disk, so replays and short seeks do not hit the network again.
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
object MediaCache {
private var cache: SimpleCache? = null
fun get(context: Context): SimpleCache = cache ?: SimpleCache(
File(context.cacheDir, "media"),
LeastRecentlyUsedCacheEvictor(200L * 1024 * 1024), // 200 MB
StandaloneDatabaseProvider(context),
).also { cache = it }
}
fun buildPlayer(context: Context): ExoPlayer {
val dataSourceFactory = CacheDataSource.Factory()
.setCache(MediaCache.get(context))
.setUpstreamDataSourceFactory(DefaultHttpDataSource.Factory())
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
return ExoPlayer.Builder(context)
.setMediaSourceFactory(DefaultMediaSourceFactory(context).setDataSourceFactory(dataSourceFactory))
.build()
}
Use a single SimpleCache instance per cache directory for the whole process: a second instance on the same folder throws.
Reference: downloading and caching media.
Compressing before upload with Transformer
Media3 Transformer re-encodes a video on the device with the hardware codecs, so the upload is smaller and faster, see device-side compression and uploads for when this is worth doing.
import androidx.media3.common.MimeTypes
import androidx.media3.effect.Presentation
import androidx.media3.transformer.*
fun compress(context: Context, input: Uri, outputPath: String, onDone: (Boolean) -> Unit) {
val edited = EditedMediaItem.Builder(MediaItem.fromUri(input))
.setEffects(Effects(emptyList(), listOf(Presentation.createForHeight(720)))) // scale to 720p
.build()
val transformer = Transformer.Builder(context)
.setVideoMimeType(MimeTypes.VIDEO_H264)
.setAudioMimeType(MimeTypes.AUDIO_AAC)
.addListener(object : Transformer.Listener {
override fun onCompleted(composition: Composition, result: ExportResult) = onDone(true)
override fun onError(composition: Composition, result: ExportResult, exception: ExportException) = onDone(false)
})
.build()
transformer.start(edited, outputPath) // call from the main thread, runs in the background
}
Transformer can trim, rotate and change frame rate and mime type. It uses the device’s encoders, so output size and quality vary between phones. Keep the server-side transcode as the authority, see video encoding fundamentals. Reference: Media3 Transformer.
Cover frames with MediaMetadataRetriever
fun coverFrame(context: Context, uri: Uri, timeMs: Long): Bitmap? {
// MediaMetadataRetriever is AutoCloseable (so .use {} works) only from API 29; release() works on every level.
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(context, uri)
return retriever.getFrameAtTime(timeMs * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
} finally {
retriever.release()
}
}
OPTION_CLOSEST_SYNC returns the nearest keyframe, which is fast. Scale the bitmap, compress it to JPEG or WebP, and upload
it as the poster, or leave the cover to the backend, see
video covers and thumbnails. Reference:
MediaMetadataRetriever.
What the pieces do at run time
ExoPlayer is a composition of small components, and every setting of this page belongs to exactly one of them. Knowing which one tells you where to look when a video stutters or a cache does not hit.
The media source parses the multivariant playlist and exposes the renditions as tracks. The track selector chooses one, the load control decides how far ahead to fetch, and the data source fetches the bytes, from the disk cache when it can. When the URL has no recognisable extension, tell the player what the stream is instead of letting it guess:
val item = MediaItem.Builder()
.setUri("https://cdn.example.com/videos/42/master.m3u8")
.setMimeType(MimeTypes.APPLICATION_M3U8) // MimeTypes.APPLICATION_MPD for DASH
.build()
Many classes used below (the cache classes, AnalyticsListener, parts of Transformer) carry the @UnstableApi annotation, so
the code that uses them needs @OptIn(UnstableApi::class) from androidx.media3.common.util, or a file-level opt-in.
Choosing a rendition on a phone
On the web, a player chooses a rendition from the bandwidth estimate and the size of the video element (see video playback and streaming). On a phone the same decision has two more inputs: whether the network is metered, and how much of the screen the player really covers. ExoPlayer exposes them as track selection parameters, which survive across media items:
fun ExoPlayer.limitQuality(context: Context, maxHeight: Int) {
val connectivity = context.getSystemService(ConnectivityManager::class.java)
val metered = connectivity.isActiveNetworkMetered
trackSelectionParameters = trackSelectionParameters.buildUpon()
.setMaxVideoSize(maxHeight * 16 / 9, maxHeight) // largest width and height to choose
.setMaxVideoBitrate(if (metered) 2_000_000 else Int.MAX_VALUE)
.build()
}
The limit compares the width of a rendition with the maximum width and its height with the maximum height, without looking
at the orientation, so a feed of portrait video passes the two numbers swapped (setMaxVideoSize(maxHeight, maxHeight * 16 / 9)).
The ladder of the backend pages has four rungs (360p at 0.8, 540p at 1.8, 720p at 3 and 1080p at 6 Mbit/s). The choice below applies the same rule as the web page, with a safety factor of 0.8 on the bandwidth estimate, and the extra caps. It was evaluated for the ladder with a small script that models the decision (the player’s real algorithm also uses buffer levels and switching hysteresis):
| Situation | Rung chosen |
|---|---|
Wi-Fi at 20 Mbit/s, full-screen player on a 1080p display |
1080p |
Cellular at 20 Mbit/s, |
540p |
Feed tile with |
540p |
The second row is the reason to set a bitrate ceiling on metered networks instead of trusting the estimate: the link is
fast, and the cap is a product decision about the user’s data plan. The third row is the equivalent of capLevelToPlayerSize
on the web. For a feed that shows many players in tiles, set the size cap to the tile, not the screen.
DefaultLoadControl decides how much to buffer ahead. The defaults suit long-form video. For short clips in a feed, a
smaller buffer wastes less data when the user scrolls past:
val loadControl = DefaultLoadControl.Builder()
.setBufferDurationsMs(
/* minBufferMs = */ 5_000,
/* maxBufferMs = */ 15_000,
/* bufferForPlaybackMs = */ 1_000,
/* bufferForPlaybackAfterRebufferMs = */ 2_000,
)
.build()
val player = ExoPlayer.Builder(context).setLoadControl(loadControl).build()
A player that follows the lifecycle
A Compose screen owns the player with remember, hands it to a PlayerView, and releases it when it leaves the
composition. Pausing on ON_STOP stops audio when the app goes to the background:
@OptIn(UnstableApi::class)
@Composable
fun VideoScreen(url: String, modifier: Modifier = Modifier) {
val context = LocalContext.current
val player = remember(url) {
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri(url))
limitQuality(context, maxHeight = 720)
prepare()
}
}
DisposableEffect(player) { onDispose { player.release() } }
LifecycleEventEffect(Lifecycle.Event.ON_STOP) { player.pause() }
AndroidView(
factory = { PlayerView(it).apply { this.player = player } },
modifier = modifier.fillMaxWidth().aspectRatio(16f / 9f),
)
}
LifecycleEventEffect comes from androidx.lifecycle:lifecycle-runtime-compose. For private video, the headers set on the
HTTP data source apply to the playlists and to every segment request, so one setting covers the whole stream:
val http = DefaultHttpDataSource.Factory()
.setDefaultRequestProperties(mapOf("Authorization" to "Bearer $accessToken"))
Pass http as the upstream factory of the CacheDataSource.Factory above. A token that expires mid-stream needs a
fresh player or a data source factory that reads the current token on each request.
How big should the cache be
LeastRecentlyUsedCacheEvictor removes the least recently read spans once the limit is exceeded, so the question is how
many minutes of video the limit holds. A six second segment is the bitrate divided by 8, times 6, which gives the size of
a segment for each rung of the ladder:
| Rung | Segment | Segments in 200 MiB | Minutes of video |
|---|---|---|---|
360p |
0.57 MiB |
349 |
34.9 |
540p |
1.29 MiB |
155 |
15.5 |
720p |
2.15 MiB |
93 |
9.3 |
1080p |
4.29 MiB |
46 |
4.6 |
A model of an LRU cache of that size, with 2 minute videos at 720p, behaves as follows. Watching video 42 twice gives 20 cache hits and 20 misses, and the cache then holds 42.9 MiB. After ten other videos of 2 minutes each have been watched, the cache is full at 199.6 MiB, and a third view of video 42 misses all 20 segments, because the ten other videos pushed it out. A cache that should serve replays of the last hour of viewing needs to be sized from the rung that the users actually watch, not from the top of the ladder, and it should be smaller than the free space that the app can count on (the cache directory is cleared by the system when storage is low).
Compressing with a bitrate target
The Transformer example above lets the encoder choose the bit rate. A target makes the output size predictable, which
matters for the upload: bytes are bit rate divided by 8, times the duration. A one minute clip at 2.5 Mbit/s is about
18.75 MB (17.9 MiB), plus about 128 kbit/s of AAC audio, while a one minute 4K recording at 50 Mbit/s is 375 MB. The
encoder settings go on the factory, and progress is polled with a ProgressHolder:
val encoderFactory = DefaultEncoderFactory.Builder(context)
.setRequestedVideoEncoderSettings(VideoEncoderSettings.Builder().setBitrate(2_500_000).build())
.build()
val transformer = Transformer.Builder(context)
.setVideoMimeType(MimeTypes.VIDEO_H264)
.setAudioMimeType(MimeTypes.AUDIO_AAC)
.setEncoderFactory(encoderFactory)
.addListener(listener)
.build()
transformer.start(edited, outputPath)
val holder = ProgressHolder()
fun poll(handler: Handler, onProgress: (Int) -> Unit) = handler.postDelayed(object : Runnable {
override fun run() {
if (transformer.getProgress(holder) != Transformer.PROGRESS_STATE_NOT_STARTED) onProgress(holder.progress)
handler.postDelayed(this, 500)
}
}, 500)
ProgressHolder.progress is a percentage from 0 to 100, and polling must stop in onCompleted and onError. In the
completion callback, ExportResult.fileSizeBytes is the real size, which is the number to compare with the estimate and
to send to the API with the upload.
Rotation needs care. Presentation.createForHeight(720) fixes the output height after the rotation is applied, so a
portrait 1080 by 1920 clip becomes 405 by 720. The iOS preset AVAssetExportPreset1280x720 produces 720 by 1280 for the
same clip, since it fits the clip in a 1280 by 720 box (see
iOS video with AVFoundation). To get the same result on both
platforms, use Presentation.createForShortSide(720) in the Media3 versions that provide it, or compute the target
width and height from the clip’s size and rotation with createForWidthAndHeight.
Watching quality in the field
The analytics listener reports which rendition is being loaded and how many frames were dropped, the same numbers that the web page sends to its analytics:
@OptIn(UnstableApi::class)
player.addAnalyticsListener(object : AnalyticsListener {
override fun onDownstreamFormatChanged(eventTime: AnalyticsListener.EventTime, mediaLoadData: MediaLoadData) {
val format = mediaLoadData.trackFormat ?: return
if (mediaLoadData.trackType == C.TRACK_TYPE_VIDEO) report("level", format.height, format.bitrate)
}
override fun onDroppedVideoFrames(eventTime: AnalyticsListener.EventTime, droppedFrames: Int, elapsedMs: Long) {
report("dropped", droppedFrames, elapsedMs.toInt())
}
})
Send the data in batches, not one request per event, and look at the distribution of rungs per network type: if most cellular sessions sit on the lowest rung, the ladder lacks a rung between 360p and 540p for them.
Related pages
-
Video Playback and Streaming on the web, with the same ladder and rendition choice.
-
Video Streaming: HLS, DASH and CMAF packages what the player consumes.