Skip to content

Commit

Permalink
802 player time api (#814)
Browse files Browse the repository at this point in the history
Co-authored-by: Gaëtan Muller <[email protected]>
  • Loading branch information
StaehliJ and MGaetan89 authored Dec 4, 2024
1 parent 47a0ddb commit bd654de
Show file tree
Hide file tree
Showing 13 changed files with 263 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.demo.shared.ui

import kotlinx.datetime.LocalTime
import kotlinx.datetime.format.Padding
import kotlinx.datetime.format.char

/**
* Local time formatter that format [LocalTime] to HH:mm:ss.
*/
val localTimeFormatter by lazy {
LocalTime.Format {
hour(Padding.ZERO)
char(':')
minute(Padding.ZERO)
char(':')
second(Padding.ZERO)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,7 @@ sealed interface NavigationRoutes {

@Serializable
data object ThumbnailShowcase : NavigationRoutes

@Serializable
data object TimeBasedContent : NavigationRoutes
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.res.stringResource
import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.common.Timeline.Window
import androidx.tv.material3.Button
import androidx.tv.material3.DrawerValue
import androidx.tv.material3.Icon
Expand All @@ -51,6 +52,7 @@ import ch.srgssr.pillarbox.demo.shared.R
import ch.srgssr.pillarbox.demo.shared.extension.onDpadEvent
import ch.srgssr.pillarbox.demo.shared.ui.components.PillarboxSlider
import ch.srgssr.pillarbox.demo.shared.ui.getFormatter
import ch.srgssr.pillarbox.demo.shared.ui.localTimeFormatter
import ch.srgssr.pillarbox.demo.shared.ui.player.metrics.MetricsOverlay
import ch.srgssr.pillarbox.demo.shared.ui.settings.MetricsOverlayOptions
import ch.srgssr.pillarbox.demo.tv.ui.player.compose.controls.PlayerError
Expand All @@ -60,19 +62,24 @@ import ch.srgssr.pillarbox.demo.tv.ui.theme.paddings
import ch.srgssr.pillarbox.player.PillarboxExoPlayer
import ch.srgssr.pillarbox.player.currentPositionAsFlow
import ch.srgssr.pillarbox.player.extension.canSeek
import ch.srgssr.pillarbox.player.extension.getUnixTimeMs
import ch.srgssr.pillarbox.ui.extension.availableCommandsAsState
import ch.srgssr.pillarbox.ui.extension.currentMediaMetadataAsState
import ch.srgssr.pillarbox.ui.extension.currentPositionAsState
import ch.srgssr.pillarbox.ui.extension.durationAsState
import ch.srgssr.pillarbox.ui.extension.getCurrentChapterAsState
import ch.srgssr.pillarbox.ui.extension.getCurrentCreditAsState
import ch.srgssr.pillarbox.ui.extension.isCurrentMediaItemLiveAsState
import ch.srgssr.pillarbox.ui.extension.playerErrorAsState
import ch.srgssr.pillarbox.ui.widget.DelayedVisibilityState
import ch.srgssr.pillarbox.ui.widget.maintainVisibleOnFocus
import ch.srgssr.pillarbox.ui.widget.player.PlayerSurface
import ch.srgssr.pillarbox.ui.widget.rememberDelayedVisibilityState
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.map
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.ZERO
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
Expand Down Expand Up @@ -306,9 +313,20 @@ private fun PlayerTimeRow(
var compactMode by remember {
mutableStateOf(true)
}
val isLive by player.isCurrentMediaItemLiveAsState()
val window = remember { Window() }
val positionTime = if (isLive) player.getUnixTimeMs(positionMs, window) else C.TIME_UNSET
val positionLabel = when (positionTime) {
C.TIME_UNSET -> formatter(positionMs.milliseconds)

else -> {
val localTime = Instant.fromEpochMilliseconds(positionTime).toLocalDateTime(TimeZone.currentSystemDefault()).time
localTimeFormatter.format(localTime)
}
}

Text(
text = "${formatter(positionMs.milliseconds)} / ${formatter(duration)}",
text = "$positionLabel / ${formatter(duration)}",
modifier = Modifier.padding(
top = MaterialTheme.paddings.baseline,
bottom = MaterialTheme.paddings.small,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,19 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import ch.srgssr.pillarbox.demo.ui.theme.PillarboxTheme
import kotlinx.coroutines.delay
import kotlinx.datetime.LocalTime
import kotlinx.datetime.format
import kotlinx.datetime.format.Padding
import kotlinx.datetime.format.char
import kotlin.time.Duration
import kotlin.time.Duration.Companion.ZERO
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

Expand All @@ -52,19 +48,17 @@ fun rememberCountdownState(duration: Duration): CountdownState {
* @param duration The countdown duration.
*/
class CountdownState internal constructor(duration: Duration) {
private var countdown by mutableStateOf(duration)
private var _countdown = mutableStateOf(duration.inWholeSeconds.seconds)

/**
* Remaining time [LocalTime].
*/
val remainingTime: State<LocalTime> = derivedStateOf {
LocalTime.fromMillisecondOfDay(countdown.inWholeMilliseconds.toInt())
}
val countdown: State<Duration> = _countdown

internal suspend fun start() {
while (countdown > ZERO) {
while (_countdown.value > ZERO) {
delay(step)
countdown -= step
_countdown.value -= step
}
}

Expand All @@ -73,16 +67,6 @@ class CountdownState internal constructor(duration: Duration) {
}
}

private val formatHms by lazy {
LocalTime.Format {
hour(Padding.ZERO)
char(':')
minute(Padding.ZERO)
char(':')
second(Padding.ZERO)
}
}

/**
* Countdown
*
Expand All @@ -92,9 +76,8 @@ private val formatHms by lazy {
@Composable
fun Countdown(countdownDuration: Duration, modifier: Modifier = Modifier) {
val countdownState = rememberCountdownState(countdownDuration)
val remainingTime by countdownState.remainingTime
val text = remainingTime.format(formatHms)
Text(text, modifier = modifier, color = Color.White)
val remainingTime by countdownState.countdown
Text("$remainingTime", modifier = modifier, color = Color.White)
}

@Preview(showBackground = true)
Expand All @@ -107,7 +90,7 @@ private fun CountdownPreview() {
.background(Color.Black)
) {
Countdown(
countdownDuration = 1.minutes,
countdownDuration = 40.hours + 1.minutes + 32.seconds,
modifier = Modifier.align(Alignment.Center),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,25 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.common.Timeline.Window
import ch.srgssr.pillarbox.demo.shared.ui.components.PillarboxSlider
import ch.srgssr.pillarbox.demo.shared.ui.getFormatter
import ch.srgssr.pillarbox.demo.shared.ui.localTimeFormatter
import ch.srgssr.pillarbox.demo.ui.theme.paddings
import ch.srgssr.pillarbox.player.PillarboxExoPlayer
import ch.srgssr.pillarbox.player.extension.canSeek
import ch.srgssr.pillarbox.player.extension.getUnixTimeMs
import ch.srgssr.pillarbox.ui.ProgressTrackerState
import ch.srgssr.pillarbox.ui.SimpleProgressTrackerState
import ch.srgssr.pillarbox.ui.SmoothProgressTrackerState
import ch.srgssr.pillarbox.ui.extension.availableCommandsAsState
import ch.srgssr.pillarbox.ui.extension.currentBufferedPercentageAsState
import ch.srgssr.pillarbox.ui.extension.durationAsState
import ch.srgssr.pillarbox.ui.extension.isCurrentMediaItemLiveAsState
import kotlinx.coroutines.CoroutineScope
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.ZERO
import kotlin.time.Duration.Companion.milliseconds

Expand Down Expand Up @@ -76,6 +83,7 @@ fun PlayerTimeSlider(
progressTracker: ProgressTrackerState = rememberProgressTrackerState(player = player, smoothTracker = true),
interactionSource: MutableInteractionSource? = null,
) {
val window = remember { Window() }
val rememberedProgressTracker by rememberUpdatedState(progressTracker)
val durationMs by player.durationAsState()
val duration = remember(durationMs) {
Expand All @@ -95,7 +103,20 @@ fun PlayerTimeSlider(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.paddings.mini)
) {
Text(text = formatter(currentProgress), color = Color.White)
val isLive by player.isCurrentMediaItemLiveAsState()
val timePosition = if (isLive) player.getUnixTimeMs(currentProgress.inWholeMilliseconds, window) else C.TIME_UNSET
// We choose to display local time only when it is live, but it is possible to have timestamp inside VoD.
val positionLabel =
when (timePosition) {
C.TIME_UNSET -> formatter(currentProgress)

else -> {
val localTime = Instant.fromEpochMilliseconds(timePosition).toLocalDateTime(TimeZone.currentSystemDefault()).time
localTimeFormatter.format(localTime)
}
}

Text(text = positionLabel, color = Color.White)

PillarboxSlider(
value = currentProgressPercent,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ fun ShowcasesHome(navController: NavController) {

HorizontalDivider()

DemoListItemView(
title = stringResource(R.string.showcase_time_based_content),
modifier = itemModifier,
onClick = { navController.navigate(NavigationRoutes.TimeBasedContent) }
)

HorizontalDivider()

DemoListItemView(
title = stringResource(R.string.adaptive),
modifier = itemModifier,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import ch.srgssr.pillarbox.demo.ui.showcases.misc.ResizablePlayerShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.misc.SmoothSeekingShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.misc.SphericalSurfaceShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.misc.StartAtGivenTimeShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.misc.TimeBasedContent
import ch.srgssr.pillarbox.demo.ui.showcases.misc.TrackingToggleShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.misc.UpdatableMediaItemShowcase
import ch.srgssr.pillarbox.demo.ui.showcases.playlists.CustomPlaybackSettingsShowcase
Expand Down Expand Up @@ -74,6 +75,9 @@ fun NavGraphBuilder.showcasesNavGraph(navController: NavController) {
composable<NavigationRoutes.ThumbnailShowcase>(DemoPageView("ThumbnailShowcase", Levels)) {
ThumbnailView()
}
composable<NavigationRoutes.TimeBasedContent>(DemoPageView("TimeBasedContent", Levels)) {
TimeBasedContent()
}
}

private val Levels = listOf("app", "pillarbox", "showcase")
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import ch.srgssr.pillarbox.player.PillarboxExoPlayer
import ch.srgssr.pillarbox.player.asset.Asset
import ch.srgssr.pillarbox.player.asset.AssetLoader
import kotlinx.datetime.Clock
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes

/**
Expand All @@ -27,7 +29,7 @@ import kotlin.time.Duration.Companion.minutes
class ContentNotYetAvailableViewModel(application: Application) : AndroidViewModel(application) {
private class AlwaysStartDateBlockedAssetLoader(context: Context) : AssetLoader(DefaultMediaSourceFactory(context)) {
private val srgAssetLoader = SRGAssetLoader(context)
private val validFrom = Clock.System.now().plus(1.minutes)
private val validFrom = Clock.System.now().plus(2.days + 1.hours + 34.minutes)
override fun canLoadAsset(mediaItem: MediaItem): Boolean {
return srgAssetLoader.canLoadAsset(mediaItem)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.demo.ui.showcases.misc

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import ch.srgssr.pillarbox.demo.ui.components.DemoListHeaderView
import ch.srgssr.pillarbox.demo.ui.components.DemoListItemView
import ch.srgssr.pillarbox.demo.ui.components.DemoListSectionView
import ch.srgssr.pillarbox.demo.ui.player.DemoPlayerView
import ch.srgssr.pillarbox.demo.ui.theme.paddings
import ch.srgssr.pillarbox.player.extension.seekToUnixTimeMs
import kotlinx.datetime.Clock

/**
* Time-based content that demonstrates how to use timestamp-based api.
*/
@Composable
fun TimeBasedContent() {
val viewModel: TimeBasedContentViewModel = viewModel()
val player = viewModel.player
val timedEvents by viewModel.deltaTimeEvents.collectAsStateWithLifecycle()

LifecycleStartEffect(player) {
player.play()
onStopOrDispose {
player.pause()
}
}
Column {
DemoPlayerView(player = player, modifier = Modifier.weight(1f))
LazyColumn(
modifier = Modifier
.padding(horizontal = MaterialTheme.paddings.baseline)
.weight(1f),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.paddings.small)
) {
item {
DemoListHeaderView("Timed events")
}
item {
DemoListSectionView {
timedEvents.forEachIndexed { index, timedEvent ->
DemoListItemView(
title = timedEvent.name,
subtitle = "Delta time ${timedEvent.delta}",
modifier = Modifier
.fillMaxWidth()
.minimumInteractiveComponentSize()
) {
val now = Clock.System.now()
player.seekToUnixTimeMs((now + timedEvent.delta).toEpochMilliseconds())
}

if (index < timedEvents.lastIndex) {
HorizontalDivider()
}
}
}
}
}
}
}
Loading

0 comments on commit bd654de

Please sign in to comment.