Last active
October 1, 2026 04:18
-
-
Save esafirm/41ba4aa41c89b1292ca4a36a1e5a66c9 to your computer and use it in GitHub Desktop.
Truly lazy ExoPlayer via ForwardingSimpleBasePlayer - sanity check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.os.Looper | |
| import androidx.annotation.OptIn | |
| import androidx.media3.common.ForwardingSimpleBasePlayer | |
| import androidx.media3.common.MediaItem | |
| import androidx.media3.common.Player | |
| import androidx.media3.common.SimpleBasePlayer | |
| import androidx.media3.common.util.UnstableApi | |
| import androidx.media3.exoplayer.ExoPlayer | |
| import com.google.common.util.concurrent.Futures | |
| import com.google.common.util.concurrent.ListenableFuture | |
| import kotlinx.coroutines.CoroutineScope | |
| import kotlinx.coroutines.Dispatchers | |
| import kotlinx.coroutines.Job | |
| import kotlinx.coroutines.launch | |
| import kotlinx.coroutines.withContext | |
| /** | |
| * Minimal repro for discussion: truly-lazy ExoPlayer behind a stable Player. | |
| * Based on https://github.com/androidx/media/issues/1246#issuecomment-2312827251 | |
| * | |
| * Simplified for readability: production additionally posts callbacks onto the player thread, | |
| * guards the pending slot, buffers a pre-ready seek, and supports onPlayerCreated listeners. | |
| * Assumes the caller drives the handle from the application looper (main, in production). | |
| */ | |
| @OptIn(UnstableApi::class) | |
| class LazyPlayerHandle( | |
| looper: Looper, | |
| private val scope: CoroutineScope, | |
| private val preparation: suspend () -> Unit, | |
| private val createPlayer: () -> ExoPlayer, | |
| ) : ForwardingSimpleBasePlayer(Placeholder(looper)) { | |
| private var realPlayer: ExoPlayer? = null | |
| private var released = false | |
| private var job: Job? = null | |
| // Latest playlist start wins; stop() drops it. | |
| private var pending: (() -> Unit)? = null | |
| // Play/pause intent recorded pre-ready, so a pause survives the swap instead of being | |
| // overwritten by the pending start's play(). | |
| private var playbackIntent: Boolean? = null | |
| // The requested entry, exposed pre-ready so the placeholder can legally report BUFFERING: | |
| // Media3 only permits an empty playlist in STATE_IDLE/STATE_ENDED. | |
| private var pendingMediaItem: MediaItem? = null | |
| /** | |
| * Resolves the play/pause intent for a playlist start: a recorded intent wins, otherwise | |
| * the start plays by default. | |
| */ | |
| fun startPlayWhenReady(): Boolean = playbackIntent ?: true | |
| /** | |
| * Records the entry being requested, so the placeholder reports STATE_BUFFERING until the | |
| * player is swapped in. A stop() (or the swap) drops it, falling back to STATE_IDLE. | |
| */ | |
| fun setPendingMediaItem(mediaItem: MediaItem) { | |
| pendingMediaItem = mediaItem | |
| invalidateState() | |
| } | |
| /** Heavy preparation off-main, player creation on main (Media3 requirement); idempotent. */ | |
| @Synchronized | |
| fun prepareAsync() { | |
| if (released || realPlayer != null || job != null) return | |
| job = scope.launch(Dispatchers.IO) { | |
| try { | |
| preparation() | |
| } catch (_: Throwable) { | |
| // Fall through and still build the player so the handle can become ready. | |
| } | |
| withContext(Dispatchers.Main) { attach() } | |
| } | |
| } | |
| /** | |
| * Runs [action] now when ready, otherwise once at the swap; latest call wins. | |
| * | |
| * Example caller: | |
| * ``` | |
| * currentPlaylist.value = playlist | |
| * handle.setPendingMediaItem(MediaItem.fromUri(playlist.uri)) | |
| * handle.runWhenReady { | |
| * // Re-read latest state here — a newer playlist may have replaced it while preparing. | |
| * val ready = currentPlaylist.value ?: return@runWhenReady | |
| * handle.clearMediaItems() | |
| * handle.setMediaItem(MediaItem.fromUri(ready.uri), fromMs) | |
| * // Resolve through startPlayWhenReady() so a pre-ready pause wins over the play(). | |
| * handle.playWhenReady = handle.startPlayWhenReady() | |
| * handle.prepare() | |
| * } | |
| * ``` | |
| */ | |
| fun runWhenReady(action: () -> Unit) { | |
| if (released) return | |
| if (realPlayer != null) { | |
| action() | |
| return | |
| } | |
| pending = action | |
| prepareAsync() | |
| // Attach may have already run on the race; consuming is idempotent. | |
| if (realPlayer != null) { | |
| pending?.invoke().also { pending = null } | |
| } | |
| } | |
| protected override fun getState(): SimpleBasePlayer.State { | |
| // Once swapped, forward everything to the real player. | |
| if (!released && realPlayer != null) return super.getState() | |
| val builder = SimpleBasePlayer.State.Builder() | |
| .setAvailableCommands(PRE_READY_COMMANDS) | |
| .setPlayWhenReady( | |
| playbackIntent ?: (pendingMediaItem != null), | |
| Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, | |
| ) | |
| // An empty playlist may only be IDLE/ENDED; exposing the requested entry is what makes | |
| // the "still preparing" BUFFERING state legal. | |
| val mediaItem = pendingMediaItem | |
| ?: return builder.setPlaybackState(Player.STATE_IDLE).build() | |
| return builder | |
| .setPlaylist( | |
| listOf(SimpleBasePlayer.MediaItemData.Builder(mediaItem).setMediaItem(mediaItem).build()), | |
| ) | |
| .setPlaybackState(Player.STATE_BUFFERING) | |
| .setIsLoading(true) | |
| .build() | |
| } | |
| override fun handleSetPlayWhenReady(playWhenReady: Boolean): ListenableFuture<*> { | |
| if (realPlayer != null) return super.handleSetPlayWhenReady(playWhenReady) | |
| playbackIntent = playWhenReady | |
| return Futures.immediateVoidFuture() | |
| } | |
| override fun handlePrepare(): ListenableFuture<*> { | |
| if (realPlayer != null) return super.handlePrepare() | |
| // Preparation is owned by this handle; a client's pre-ready prepare() has nothing to do. | |
| return Futures.immediateVoidFuture() | |
| } | |
| override fun handleStop(): ListenableFuture<*> { | |
| if (realPlayer != null) return super.handleStop() | |
| // Nothing started yet, so stopping means dropping the pending start and its intents. | |
| pending = null | |
| playbackIntent = null | |
| pendingMediaItem = null | |
| return Futures.immediateVoidFuture() | |
| } | |
| override fun handleRelease(): ListenableFuture<*> { | |
| if (realPlayer != null) { | |
| val future = super.handleRelease() | |
| realPlayer = null | |
| releasePendingWork() | |
| return future | |
| } | |
| releasePendingWork() | |
| return Futures.immediateVoidFuture() | |
| } | |
| private fun attach() { | |
| if (realPlayer != null || released) return | |
| try { | |
| val player = createPlayer() | |
| setPlayer(player) | |
| realPlayer = player | |
| pendingMediaItem = null | |
| // setPlayer() invalidated while realPlayer was still null, so force a re-read now | |
| // that getState() forwards to the real player. | |
| invalidateState() | |
| // Apply before the action so its newer play/pause commands are not overwritten. | |
| playbackIntent?.let { player.playWhenReady = it } | |
| pending?.invoke().also { pending = null } | |
| playbackIntent = null | |
| } finally { | |
| // Clear even on creation failure so a later prepareAsync() can retry. | |
| synchronized(this) { job = null } | |
| } | |
| } | |
| private fun releasePendingWork() { | |
| released = true | |
| pending = null | |
| pendingMediaItem = null | |
| synchronized(this) { | |
| job?.cancel() | |
| job = null | |
| } | |
| } | |
| private companion object { | |
| val PRE_READY_COMMANDS: Player.Commands = Player.Commands.Builder() | |
| .addAll( | |
| Player.COMMAND_GET_CURRENT_MEDIA_ITEM, | |
| Player.COMMAND_GET_TIMELINE, | |
| Player.COMMAND_PLAY_PAUSE, | |
| Player.COMMAND_PREPARE, | |
| Player.COMMAND_STOP, | |
| Player.COMMAND_RELEASE, | |
| ) | |
| .build() | |
| } | |
| } | |
| // Contributes only the looper the handle runs on; pre-ready state comes from the handle's | |
| // getState() override above, so this placeholder's own state never surfaces. | |
| @OptIn(UnstableApi::class) | |
| private class Placeholder(looper: Looper) : SimpleBasePlayer(looper) { | |
| override fun getState(): State = State.Builder() | |
| .setAvailableCommands( | |
| Player.Commands.Builder() | |
| .addAll( | |
| Player.COMMAND_STOP, | |
| Player.COMMAND_GET_CURRENT_MEDIA_ITEM, | |
| Player.COMMAND_GET_TIMELINE, | |
| ) | |
| .build(), | |
| ) | |
| .build() | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import androidx.media3.common.MediaItem | |
| import kotlinx.coroutines.flow.MutableStateFlow | |
| /** | |
| * How callers drive [LazyPlayerHandle] — mirrors `StandalonePlayerImpl.preparePlaylist`. | |
| * | |
| * The pattern: publish the playlist first and expose it as the handle's pending entry, then let | |
| * [LazyPlayerHandle.runWhenReady] re-read the latest state at the swap, so a playlist replaced | |
| * while preparing is never started stale. | |
| * | |
| * UI consumers should observe the stable handle even during preparation. Register listeners, | |
| * then read its current media item, playback state, and play intent for an initial snapshot; | |
| * waiting for real-player creation misses pre-ready stop and replacement events. | |
| */ | |
| class StandalonePlaybackController( | |
| private val handle: LazyPlayerHandle, | |
| private val currentPlaylist: MutableStateFlow<Playlist?> = MutableStateFlow(null), | |
| ) { | |
| fun preparePlaylist( | |
| playlist: Playlist, | |
| fromMs: Long, | |
| onPrepared: () -> Unit, | |
| ) { | |
| currentPlaylist.value = playlist | |
| // Expose the requested entry so the placeholder reports STATE_BUFFERING while preparing | |
| // (an empty playlist may only be IDLE/ENDED). | |
| handle.setPendingMediaItem(MediaItem.fromUri(playlist.uri)) | |
| handle.runWhenReady { | |
| // A newer playlist may have replaced this one while preparing — always re-read. | |
| val ready = currentPlaylist.value ?: return@runWhenReady | |
| handle.clearMediaItems() | |
| handle.setMediaItem(MediaItem.fromUri(ready.uri), fromMs) | |
| // Sequence matters: mark playWhenReady before prepare(), and resolve it through | |
| // startPlayWhenReady() so a pause recorded pre-ready wins over the start's play(). | |
| handle.playWhenReady = handle.startPlayWhenReady() | |
| handle.prepare() | |
| onPrepared() | |
| } | |
| } | |
| fun stopPlayback() { | |
| handle.playWhenReady = false | |
| handle.stop() | |
| handle.clearMediaItems() | |
| currentPlaylist.value = null | |
| } | |
| } | |
| data class Playlist( | |
| val uri: String, | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment