Search code examples
androidkotlinexoplayerandroid-media3

Media3 Video Track Change Issue: Video Appears in a Portion of the Screen


This code allows me to play a video, and with the settings button (the gear icon), I can open the video track selector dialog, but when I change the size, the player gets stuck in a loop on the screen, and the video resizes to a portion of the screen.

This is the ExoplayerScreen.

@UnstableApi
@Preview(device = "id:pixel_5", showSystemUi = true, showBackground = true)
@Composable
fun ExoplayerScreenPreview() {
    ExoplayerScreen()
}

@UnstableApi
@Composable
fun ExoplayerScreen() {
    MyStatusBar(color = colorResource(id = R.color.colorPrimaryDark))
    Scaffold(topBar = { MyToolBar() }, content = { padding ->
        ExoplayerScreenContent(Modifier.padding(padding))
    })
}

@UnstableApi
@Composable
fun ExoplayerScreenContent(modifier: Modifier) {
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(230.dp)

    ) {
        VideoScreen()
    }
}

This is the VideoScreen

@SuppressLint("OpaqueUnitKey")
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable
fun VideoScreen() {
    val context = LocalContext.current
    val playerView = PlayerView(context)

    val exoPlayer = remember {
        ExoPlayer.Builder(context).build().apply {
            setMediaItem(
                MediaItem.fromUri(
                    "https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8"
                )
            )
            prepare()
            play()
            videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
        }
    }

    var isPlaying by remember {
        mutableStateOf(false)
    }

    exoPlayer.addListener(object : Player.Listener {
        override fun onIsPlayingChanged(isPlayingValue: Boolean) {
            isPlaying = isPlayingValue
        }
    })

    DisposableEffect(Box {
        AndroidView(modifier = Modifier.fillMaxSize(), factory = {
            playerView.apply {
                // Resizes the video in order to be able to fill the whole screen
                resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
                player = exoPlayer
                // Hides the default Player Controller
                useController = false
                // Fills the whole screen
                layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
            }
        })

        VideoLayout(
            isPlaying = isPlaying,
            onPlay = { exoPlayer.play() },
            onPause = { exoPlayer.pause() },
            exoPlayer = exoPlayer,
        )
    }) {
        onDispose { exoPlayer.release() }
    }
}

This is the VideoLayout

@Composable
fun VideoLayout(
    isPlaying: Boolean,
    onPlay: () -> Unit,
    onPause: () -> Unit,
    exoPlayer: ExoPlayer,
) {
    Box(modifier = Modifier
        .fillMaxSize()
        .clickable {
            if (isPlaying) {
                onPause()
            } else {
                onPlay()
            }
        }) {
        AnimatedVisibility(
            visible = !isPlaying, enter = fadeIn(tween(200)), exit = fadeOut(tween(200))
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(
                        Color.Black.copy(alpha = 0.6f)
                    ), contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Rounded.Pause, contentDescription = null, tint = Color.White
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(vertical = 15.dp, horizontal = 20.dp),
                contentAlignment = Alignment.BottomEnd
            ) {

                val context = LocalContext.current

                Column(
                    verticalArrangement = Arrangement.spacedBy(15.dp)
                ) {
                    IconButton(onClick = { trackSeleccion(exoPlayer, context) }) {
                        Icon(
                            imageVector = Icons.Rounded.Settings,
                            contentDescription = null,
                            tint = Color.White
                        )
                    }
                    IconButton(onClick = { /*TODO*/ }) {
                        Icon(
                            imageVector = Icons.Rounded.Comment,
                            contentDescription = null,
                            tint = Color.White
                        )
                    }
                    IconButton(onClick = { /*TODO*/ }) {
                        Icon(
                            imageVector = Icons.Rounded.IosShare,
                            contentDescription = null,
                            tint = Color.White
                        )
                    }
                }
            }

        }
    }
}

This is the trackSeleccion

@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
fun trackSeleccion(exoplayer: ExoPlayer, context: Context) {
    val trackSelector = exoplayer.trackSelector as DefaultTrackSelector
    val mappedTrackInfo = trackSelector.currentMappedTrackInfo
    if (mappedTrackInfo != null) {
        val rendererIndex = 2
        val rendererType = mappedTrackInfo.getRendererType(rendererIndex)
        val allowAdaptiveSelections =
            rendererType == C.TRACK_TYPE_VIDEO || (rendererType == C.TRACK_TYPE_AUDIO && mappedTrackInfo.getTypeSupport(
                C.TRACK_TYPE_VIDEO
            ) == MappingTrackSelector.MappedTrackInfo.RENDERER_SUPPORT_NO_TRACKS)


        val builder =
            TrackSelectionDialogBuilder(context, "Selección de pistas", exoplayer, rendererIndex)
        builder.setShowDisableOption(false)
        builder.setAllowAdaptiveSelections(allowAdaptiveSelections)
        builder.setOverrides(exoplayer.trackSelectionParameters.overrides)
        builder.build().show()

    }

    exoplayer.videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING

    Log.e("trackSeleccion", "trackSeleccion: ")

}

The red square is when the player starts with the video, and the blue one is when I change the video track to a lower resolution

enter image description here

I've tried that code, but I can't get the video to stay at the width of the screen when changing resolution, and it only changes the quality.

I'm using Media3.


Solution

  • Following @Hisham's recommendation.

    Finally I've solved the problem with the next code:

    exoplayer.addListener(object : Player.Listener {
            override fun onIsPlayingChanged(isPlayingValue: Boolean) {
                isPlaying = isPlayingValue
            }
    
            override fun onTrackSelectionParametersChanged(parameters: TrackSelectionParameters) {
                super.onTrackSelectionParametersChanged(parameters)
    
                Log.e("VideoScreen", "onTrackSelectionParametersChanged")
    
                val currentProgressTime = exoplayer.currentPosition
    
                exoplayer.stop()
    
                exoplayer.seekTo(currentProgressTime)
    
                exoplayer.apply {
                    prepare()
                    playWhenReady = true
                }
    
            }
    
        })