Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce PillarboxPreloadManager #726

Merged
merged 23 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,41 @@ data class Playlist(val title: String, val items: List<DemoItem>, val descriptio
DemoItem.OverlapinglockedSegments
)
)
val StoryUrns = Playlist(
title = "Story urns",
items = listOf(
DemoItem.URN(
title = "Mario vs Sonic",
description = "Tataki 1",
urn = "urn:rts:video:13950405"
),
DemoItem.URN(
title = "Pourquoi Beyoncé fait de la country",
description = "Tataki 2",
urn = "urn:rts:video:14815579"
),
DemoItem.URN(
title = "L'île North Sentinel",
description = "Tataki 3",
urn = "urn:rts:video:13795051"
),
DemoItem.URN(
title = "Mourir pour ressembler à une idole",
description = "Tataki 4",
urn = "urn:rts:video:14020134"
),
DemoItem.URN(
title = "Pourquoi les gens mangent des insectes ?",
description = "Tataki 5",
urn = "urn:rts:video:12631996"
),
DemoItem.URN(
title = "Le concert de Beyoncé à Dubai",
description = "Tataki 6",
urn = "urn:rts:video:13752646"
)
)
)
private val googleStreams = Playlist(
title = "Google streams",
items = listOf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import ch.srgssr.pillarbox.player.asset.timeRange.Chapter
import ch.srgssr.pillarbox.player.asset.timeRange.Credit
import ch.srgssr.pillarbox.player.extension.setHandleAudioFocus
import ch.srgssr.pillarbox.player.extension.toRational
import ch.srgssr.pillarbox.player.utils.StringUtil
import kotlinx.coroutines.flow.MutableStateFlow

/**
Expand Down Expand Up @@ -95,11 +96,7 @@ class SimplePlayerViewModel(application: Application) : AndroidViewModel(applica
}

override fun onTimelineChanged(timeline: Timeline, reason: Int) {
val reasonString = when (reason) {
Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED -> "TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED"
Player.TIMELINE_CHANGE_REASON_SOURCE_UPDATE -> "TIMELINE_CHANGE_REASON_SOURCE_UPDATE"
else -> "?"
}
val reasonString = StringUtil.timelineChangeReasonString(reason)
Log.d(
TAG,
"onTimelineChanged $reasonString ${player.currentMediaItem?.mediaId}" +
Expand All @@ -122,13 +119,7 @@ class SimplePlayerViewModel(application: Application) : AndroidViewModel(applica
}

override fun onPlaybackStateChanged(@Player.State playbackState: Int) {
val stateString = when (playbackState) {
Player.STATE_IDLE -> "STATE_IDLE"
Player.STATE_READY -> "STATE_READY"
Player.STATE_BUFFERING -> "STATE_BUFFERING"
Player.STATE_ENDED -> "STATE_ENDED"
else -> "?"
}
val stateString = StringUtil.playerStateString(playbackState)
Log.d(TAG, "onPlaybackStateChanged $stateString ${player.currentMediaItem?.mediaMetadata?.title}")
}

Expand All @@ -137,7 +128,7 @@ class SimplePlayerViewModel(application: Application) : AndroidViewModel(applica
}

override fun onPlayerErrorChanged(error: PlaybackException?) {
Log.d(TAG, "onPlayerErrorChanged $error")
Log.d(TAG, "onPlayerErrorChanged", error)
}

override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,112 +4,205 @@
*/
package ch.srgssr.pillarbox.demo.ui.showcases.layouts

import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.layout.Arrangement
import android.os.Build
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.PagerSnapDistance
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.media3.common.Player
import ch.srgssr.pillarbox.demo.ui.theme.PillarboxTheme
import ch.srgssr.pillarbox.demo.ui.theme.paddings
import ch.srgssr.pillarbox.player.currentPositionAsFlow
import ch.srgssr.pillarbox.player.playbackStateAsFlow
import ch.srgssr.pillarbox.ui.ScaleMode
import ch.srgssr.pillarbox.ui.widget.player.PlayerSurface
import ch.srgssr.pillarbox.ui.widget.player.SurfaceType
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.map
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds

/**
* Optimized story trying to reproduce story-like TikTok or Instagram.
*
* Surface view may sometimes keep on screen. Maybe if we use TextView with PlayerView this strange behavior will disappear.
* Optimized story-like layout.
*/
@Composable
fun OptimizedStory(storyViewModel: StoryViewModel = viewModel()) {
val pagerState = rememberPagerState {
storyViewModel.playlist.items.size
val mediaItems = storyViewModel.mediaItems
val pagerState = rememberPagerState { mediaItems.size }
val settledPage by remember { derivedStateOf { pagerState.settledPage } }
val currentPage by remember { derivedStateOf { pagerState.currentPage } }
LaunchedEffect(settledPage) {
storyViewModel.play(storyViewModel.getPlayer(settledPage))
}
LaunchedEffect(currentPage) {
storyViewModel.setCurrentPage(currentPage)
}
LifecycleStartEffect(pagerState) {
storyViewModel.getPlayerForPageNumber(pagerState.currentPage).play()

onStopOrDispose {
storyViewModel.pauseAllPlayer()
val movablePlayerView = remember {
(0 until storyViewModel.playerCount).map { index ->
movableContentOf {
val player = remember { storyViewModel.getPlayer(index) }
PlayerView(player, modifier = Modifier.fillMaxSize())
}
}
}

val playlist = storyViewModel.playlist.items
Box(modifier = Modifier.fillMaxSize()) {
HorizontalPager(
beyondViewportPageCount = 0,
key = { page -> playlist[page].uri },
VerticalPager(
flingBehavior = PagerDefaults.flingBehavior(
state = pagerState,
pagerSnapDistance = PagerSnapDistance.atMost(0),
snapAnimationSpec = spring(stiffness = Spring.StiffnessHigh)
),
pageSpacing = 1.dp,
state = pagerState
beyondViewportPageCount = 0,
state = pagerState,
) { page ->
// When flinging -> may "load" more that 3 pages
val currentPage = pagerState.currentPage
val player = if (page == currentPage - 1 || page == currentPage + 1 || page == currentPage) {
val playerConfig = storyViewModel.getPlayerAndMediaItemIndexForPage(page)
val playerPage = storyViewModel.getPlayerFromIndex(playerConfig.first)
playerPage.playWhenReady = currentPage == page
playerPage.seekToDefaultPosition(playerConfig.second)
playerPage
} else {
null
LaunchedEffect(page) {
storyViewModel.setupPlayerForPage(page)
}
player?.let {
PlayerSurface(
modifier = Modifier.fillMaxHeight(),
scaleMode = ScaleMode.Crop,
// Using Texture instead of Surface because on Android API 34 animations are not working well due to the hack
// See PlayerSurfaceView in AndroidPlayerSurfaceView
surfaceType = SurfaceType.Texture,
player = player,
)
}
Text(text = "Page $page")
movablePlayerView[page % movablePlayerView.size]()
}
Row(
Modifier

PagerIndicator(
currentPage = settledPage,
pageCount = mediaItems.size,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = MaterialTheme.paddings.small),
)
}
}

@Composable
private fun PlayerView(player: Player, modifier: Modifier = Modifier) {
val progress by remember {
player.currentPositionAsFlow(100.milliseconds)
.map { it / player.duration.coerceAtLeast(1L).toFloat() }
}.collectAsState(0f)

val isBuffering by remember {
player.playbackStateAsFlow().map { it == Player.STATE_BUFFERING }
}.collectAsState(false)

Box(
modifier = modifier,
) {
PlayerSurface(
modifier = Modifier.fillMaxHeight(),
scaleMode = ScaleMode.Crop,
surfaceType = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.UPSIDE_DOWN_CAKE) SurfaceType.Texture else SurfaceType.Surface,
player = player,
defaultAspectRatio = 9 / 16f,
)

if (isBuffering) {
CircularProgressIndicator(
color = Color.White,
modifier = Modifier.align(Alignment.Center),
)
}

LinearProgressIndicator(
progress = { progress },
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
.padding(bottom = MaterialTheme.paddings.baseline),
horizontalArrangement = Arrangement.Center
) {
repeat(playlist.size) { iteration ->
val color = if (pagerState.currentPage == iteration) ColorIndicatorCurrent else ColorIndicator
Box(
modifier = Modifier
.padding(MaterialTheme.paddings.micro)
.size(IndicatorSize)
.drawBehind {
drawCircle(color)
}

)
}
.align(Alignment.BottomCenter),
color = PrimaryComponentColor,
trackColor = SecondaryComponentColor,
gapSize = 0.dp,
drawStopIndicator = {},
)
}
}

@Composable
private fun PagerIndicator(
currentPage: Int,
pageCount: Int,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.background(
color = SurfaceComponentColor,
shape = CircleShape,
)
.padding(MaterialTheme.paddings.micro),
) {
repeat(pageCount) { index ->
val dotColor by animateColorAsState(
targetValue = if (currentPage == index) PrimaryComponentColor else SecondaryComponentColor,
label = "indicator-animation",
)

Box(
modifier = Modifier
.padding(MaterialTheme.paddings.micro)
.size(IndicatorSize)
.drawBehind {
drawCircle(dotColor)
},
)
}
}
}

private val ColorIndicatorCurrent = Color.LightGray.copy(alpha = 0.75f)
private val ColorIndicator = Color.LightGray.copy(alpha = 0.25f)
@Preview
@Composable
private fun PageIndicatorPreview() {
val pageCount = 5
var step by remember { mutableIntStateOf(1) }
var currentPage by remember { mutableIntStateOf(0) }

LaunchedEffect(currentPage) {
delay(1.seconds)
currentPage += step

if (currentPage == pageCount - 1) {
step = -1
} else if (currentPage == 0) {
step = 1
}
}

PillarboxTheme {
PagerIndicator(
currentPage = currentPage,
pageCount = pageCount,
)
}
}

private val ComponentColor = Color.LightGray
private val PrimaryComponentColor = ComponentColor.copy(alpha = 0.88f)
private val SecondaryComponentColor = ComponentColor.copy(alpha = 0.33f)
private val SurfaceComponentColor = ComponentColor.copy(alpha = 0.25f)
private val IndicatorSize = 12.dp
Loading
Loading