diff --git a/app/src/main/java/com/github/damontecres/wholphin/data/model/BaseItem.kt b/app/src/main/java/com/github/damontecres/wholphin/data/model/BaseItem.kt index 32e588d7fc..98926b299e 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/data/model/BaseItem.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/data/model/BaseItem.kt @@ -74,15 +74,7 @@ data class BaseItem( } val subtitleLong: String? by lazy { - if (type == BaseItemKind.EPISODE) { - buildList { - add(data.seasonEpisodePadded) - add(data.name) - add(data.premiereDate?.let { formatDateTime(it) }) - }.joinNotBlank(" - ") - } else { - data.productionYear?.toString() - } + data.subtitleLong() } val canDelete: Boolean get() = data.canDelete == true @@ -334,6 +326,10 @@ data class BaseItem( } ?: Destination.MediaItem(this) } + BaseItemKind.RECORDING -> { + Destination.Playback(id, 0) + } + else -> { Destination.MediaItem(this) } @@ -435,3 +431,14 @@ fun createStudioDestination( ) val BaseItem.studioNames get() = data.studios?.mapNotNull { it.name }.orEmpty() + +fun BaseItemDto.subtitleLong(treatAsEpisode: Boolean = type == BaseItemKind.EPISODE): String? = + if (treatAsEpisode) { + buildList { + add(seasonEpisodePadded) + add(name) + add(premiereDate?.let { formatDateTime(it) }) + }.joinNotBlank(" - ") + } else { + productionYear?.toString() + } diff --git a/app/src/main/java/com/github/damontecres/wholphin/services/LiveTvService.kt b/app/src/main/java/com/github/damontecres/wholphin/services/LiveTvService.kt index d89916f039..c81419bd16 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/services/LiveTvService.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/services/LiveTvService.kt @@ -4,6 +4,7 @@ import com.github.damontecres.wholphin.data.model.BaseItem import com.github.damontecres.wholphin.ui.toServerString import org.jellyfin.sdk.api.client.ApiClient import org.jellyfin.sdk.api.client.extensions.liveTvApi +import org.jellyfin.sdk.model.api.RecordingStatus import org.jellyfin.sdk.model.api.TimerInfoDto import java.util.UUID import javax.inject.Inject @@ -30,6 +31,24 @@ class LiveTvService return result } + suspend fun fetchRecordingForProgram(program: BaseItem): BaseItem? { + val timerId = program.data.timerId + val channelId = program.data.channelId + return if (program.data.status == RecordingStatus.IN_PROGRESS.serialName && + timerId != null && + channelId != null + ) { + // Active recording + val recordings by api.liveTvApi.getRecordings( + channelId = channelId.toString(), + isInProgress = true, + ) + recordings.items.firstOrNull { it.timerId == timerId }?.let { BaseItem(it) } + } else { + null + } + } + /** * Cancel a recording by [timerId] * diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CollectionFolderLiveTv.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CollectionFolderLiveTv.kt index 18af298bcf..113e2c3f2d 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CollectionFolderLiveTv.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/CollectionFolderLiveTv.kt @@ -1,18 +1,27 @@ package com.github.damontecres.wholphin.ui.detail +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import androidx.tv.material3.MaterialTheme import com.github.damontecres.wholphin.R import com.github.damontecres.wholphin.data.ServerRepository import com.github.damontecres.wholphin.data.model.BaseItem @@ -20,7 +29,10 @@ import com.github.damontecres.wholphin.data.model.CollectionFolderFilter import com.github.damontecres.wholphin.preferences.UserPreferences import com.github.damontecres.wholphin.services.BackdropService import com.github.damontecres.wholphin.services.NavigationManager +import com.github.damontecres.wholphin.ui.components.BasicDialog import com.github.damontecres.wholphin.ui.components.CollectionFolderView +import com.github.damontecres.wholphin.ui.components.DialogItem +import com.github.damontecres.wholphin.ui.components.DialogPopupContent import com.github.damontecres.wholphin.ui.components.ErrorMessage import com.github.damontecres.wholphin.ui.components.LoadingPage import com.github.damontecres.wholphin.ui.components.TabDetails @@ -36,8 +48,12 @@ import com.github.damontecres.wholphin.util.DataLoadingState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import org.jellyfin.sdk.api.client.ApiClient import org.jellyfin.sdk.api.client.extensions.liveTvApi +import org.jellyfin.sdk.model.api.BaseItemKind +import org.jellyfin.sdk.model.api.RecordingStatus +import org.jellyfin.sdk.model.api.TimerInfoDto import timber.log.Timber import java.util.UUID import javax.inject.Inject @@ -72,10 +88,32 @@ class LiveTvCollectionViewModel } } } + + fun lookupTimerFor(item: BaseItem) { + viewModelScope.launchIO { + val timerId = item.data.timerId + if (timerId != null) { + state.update { it.copy(recordingLookup = DataLoadingState.Loading) } + try { + val timer by api.liveTvApi.getTimer(timerId) + state.update { it.copy(recordingLookup = DataLoadingState.Success(TimerInfo(item, timer))) } + } catch (ex: Exception) { + state.update { it.copy(recordingLookup = DataLoadingState.Error(ex)) } + } + } else { + state.update { it.copy(recordingLookup = DataLoadingState.Error("No timer for recording")) } + } + } + } + + fun clearTimer() { + state.update { it.copy(recordingLookup = DataLoadingState.Pending) } + } } data class LiveTvRecordingFolderState( val folders: DataLoadingState> = DataLoadingState.Pending, + val recordingLookup: DataLoadingState = DataLoadingState.Pending, ) data class TabId( @@ -83,6 +121,13 @@ data class TabId( val id: UUID, ) +data class TimerInfo( + val item: BaseItem, + val timerInfo: TimerInfoDto, +) + +val BaseItem.isInProgressRecording: Boolean get() = type == BaseItemKind.RECORDING && data.status == RecordingStatus.IN_PROGRESS.serialName + @Composable fun CollectionFolderLiveTv( preferences: UserPreferences, @@ -117,7 +162,11 @@ fun CollectionFolderLiveTv( val onClickItem = remember { { position: Int, item: BaseItem -> - viewModel.navigationManager.navigateTo(item.destination()) + if (item.isInProgressRecording) { + viewModel.lookupTimerFor(item) + } else { + viewModel.navigationManager.navigateTo(item.destination()) + } } } @@ -179,4 +228,79 @@ fun CollectionFolderLiveTv( } } } + WatchFromStartDialog( + timer = state.recordingLookup, + onDismissRequest = { viewModel.clearTimer() }, + onClickPlay = { id -> + viewModel.navigationManager.navigateTo(Destination.Playback(id, 0)) + }, + ) +} + +@Composable +fun WatchFromStartDialog( + timer: DataLoadingState, + onDismissRequest: () -> Unit, + onClickPlay: (UUID) -> Unit, +) { + when (timer) { + DataLoadingState.Pending -> { + } + + else -> { + BasicDialog( + onDismissRequest = onDismissRequest, + ) { + val focusRequester = remember { FocusRequester() } + val modifier = Modifier.padding(24.dp) + when (val t = timer) { + is DataLoadingState.Error -> { + ErrorMessage(t, modifier) + } + + DataLoadingState.Loading -> { + Box(modifier) { + CircularProgressIndicator( + color = MaterialTheme.colorScheme.border, + modifier = + Modifier + .align(Alignment.Center) + .size(48.dp), + ) + } + } + + is DataLoadingState.Success -> { + LaunchedEffect(Unit) { focusRequester.requestFocus() } + DialogPopupContent( + title = t.data.item.title ?: "", + waiting = false, + onDismissRequest = onDismissRequest, + dialogItems = + buildList { + add( + DialogItem( + text = R.string.play_from_start, + iconStringRes = R.string.fa_rotate_left, + onClick = { onClickPlay.invoke(t.data.item.id) }, + ), + ) + val channelId = t.data.timerInfo.channelId + if (channelId != null) { + add( + DialogItem( + text = R.string.watch_live, + iconStringRes = R.string.fa_play, + onClick = { onClickPlay.invoke(channelId) }, + ), + ) + } + }, + modifier = modifier.focusRequester(focusRequester), + ) + } + } + } + } + } } diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/Components.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/Components.kt index e5bf4e8f20..173e88dae1 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/Components.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/Components.kt @@ -41,7 +41,7 @@ fun Program( onLongClick: (() -> Unit)?, modifier: Modifier = Modifier, ) { - val startedBeforeGuide = program.start.isBefore(guideStart) + val startedBeforeGuide = remember(program.start, guideStart) { program.start.isBefore(guideStart) } val shape = remember(startedBeforeGuide) { val cornerSize = 4.dp @@ -110,13 +110,13 @@ fun Program( overflow = TextOverflow.Ellipsis, modifier = Modifier, ) - val seasonEpisodeLabel = - formatSeasonEpisode( - program.seasonEpisode?.season, - program.seasonEpisode?.episode, - ) val subtitle = - remember(program, seasonEpisodeLabel) { + remember(program.id) { + val seasonEpisodeLabel = + formatSeasonEpisode( + program.seasonEpisode?.season, + program.seasonEpisode?.episode, + ) listOfNotNull( seasonEpisodeLabel, program.subtitle, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/DvrSchedule.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/DvrSchedule.kt index 5de558c239..4ec5f32f38 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/DvrSchedule.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/DvrSchedule.kt @@ -1,7 +1,6 @@ package com.github.damontecres.wholphin.ui.detail.livetv import android.text.format.DateUtils -import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -39,7 +38,6 @@ import com.github.damontecres.wholphin.ui.SlimItemFields import com.github.damontecres.wholphin.ui.components.ErrorMessage import com.github.damontecres.wholphin.ui.components.LoadingPage import com.github.damontecres.wholphin.ui.launchIO -import com.github.damontecres.wholphin.ui.nav.Destination import com.github.damontecres.wholphin.ui.seasonEpisode import com.github.damontecres.wholphin.ui.tryRequestFocus import com.github.damontecres.wholphin.util.DataLoadingState @@ -181,25 +179,14 @@ fun DvrSchedule( showDialog?.let { item -> val context = LocalContext.current ProgramDialog( - state = DataLoadingState.Success(item), + state = ProgramDialogState(DataLoadingState.Success(item), item), canRecord = true, onDismissRequest = { showDialog = null }, onWatch = { program -> - val channelId = program.data.channelId - if (channelId != null) { - viewModel.navigationManager.navigateTo( - Destination.Playback( - itemId = channelId, - positionMs = 0L, - ), - ) - } else { - Toast - .makeText(context, "Program has no channel ID", Toast.LENGTH_LONG) - .show() - } + showDialog = null + onWatch(context, viewModel.navigationManager, program) }, onRecord = { _, _ -> // no-op diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/LiveTvViewModel.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/LiveTvViewModel.kt index bcba145cc5..5a6066c3ee 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/LiveTvViewModel.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/LiveTvViewModel.kt @@ -36,6 +36,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest @@ -43,6 +44,7 @@ import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.jellyfin.sdk.api.client.ApiClient @@ -63,6 +65,7 @@ import java.util.UUID import javax.inject.Inject import kotlin.math.min import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @@ -110,6 +113,18 @@ class LiveTvViewModel init(it.first, it.second) } } + viewModelScope.launchDefault { + // This loop refreshes the guide every ~30 minutes if the user sits idle on the EPG + val now = LocalDateTime.now() + val future = now.roundDownToHalfHour().plusMinutes(30 + 10) + val hours = hoursBetween(now, future) + // Waits until 10 minutes after the half hour, eg 8:10 or 8:40, then every 30 minutes + delay(hours.toDouble().hours) + while (isActive) { + refreshIfTimeChanged() + delay(30.minutes) + } + } } private fun init( @@ -182,6 +197,26 @@ class LiveTvViewModel } } + /** + * Refreshes the guide data if the guide start time has changed + */ + private fun refreshIfTimeChanged() { + val state = state.value + // Don't run during the initialization + if (state.loading is LoadingState.Success) { + viewModelScope.launchDefault { + val startGuideTime = LocalDateTime.now().roundDownToHalfHour() + val currentStartGuideTime = state.guideTimes.firstOrNull() + Timber.v("refreshIfTimeChanged: startGuideTime=%s, currentStartGuideTime=%s", startGuideTime, currentStartGuideTime) + if (currentStartGuideTime != startGuideTime) { + val newGuideTimes = buildGuideTimes() + _state.update { it.copy(guideTimes = newGuideTimes) } + refreshPrograms(state.channels, state.programs.range) + } + } + } + } + /** * Creates a list of [LocalDateTime] for each hour from now */ @@ -229,7 +264,7 @@ class LiveTvViewModel val maxStartDate = guideStart.plusHours(MAX_HOURS).minusMinutes(1) val minEndDate = guideStart.plusMinutes(1L) val channelsToFetch = channels.subList(channelIndices.first, channelIndices.last + 1) - Timber.v("Fetching programs for $channelIndices channels ${channelsToFetch.size}") + Timber.v("Fetching programs for %s channels of %s @ %s", channelIndices, channelsToFetch.size, guideStart) val request = GetProgramsDto( maxStartDate = maxStartDate, @@ -434,11 +469,18 @@ class LiveTvViewModel } fun fetchProgramForDialog(programId: UUID) { - _programDialogState.update { it.copy(loading = DataLoadingState.Loading) } + _programDialogState.update { it.copy(loading = DataLoadingState.Loading, recording = null) } viewModelScope.launchDefault { try { val result = liveTvService.fetchProgramForDialog(programId) - _programDialogState.update { it.copy(loading = DataLoadingState.Success(result)) } + val recording = liveTvService.fetchRecordingForProgram(result) + Timber.d("Got recording %s for program %s", recording?.id, programId) + _programDialogState.update { + it.copy( + loading = DataLoadingState.Success(result), + recording = recording, + ) + } } catch (ex: CancellationException) { throw ex } catch (ex: Exception) { @@ -579,6 +621,7 @@ data class LiveTvState( data class ProgramDialogState( val loading: DataLoadingState = DataLoadingState.Pending, + val recording: BaseItem? = null, ) data class TvChannel( diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/ProgramDialog.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/ProgramDialog.kt index 04daa26083..40ccb00061 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/ProgramDialog.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/ProgramDialog.kt @@ -1,6 +1,9 @@ package com.github.damontecres.wholphin.ui.detail.livetv +import android.content.Context import android.text.format.DateUtils +import android.widget.Toast +import androidx.annotation.StringRes import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -9,11 +12,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember @@ -21,33 +20,35 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.focus.focusRestorer import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog -import androidx.tv.material3.Icon import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import androidx.tv.material3.surfaceColorAtElevation import com.github.damontecres.wholphin.R import com.github.damontecres.wholphin.data.model.BaseItem +import com.github.damontecres.wholphin.services.NavigationManager +import com.github.damontecres.wholphin.ui.FontAwesome import com.github.damontecres.wholphin.ui.components.CircularProgress import com.github.damontecres.wholphin.ui.components.ErrorMessage import com.github.damontecres.wholphin.ui.components.TextButton import com.github.damontecres.wholphin.ui.ifElse import com.github.damontecres.wholphin.ui.isNotNullOrBlank +import com.github.damontecres.wholphin.ui.nav.Destination import com.github.damontecres.wholphin.ui.seasonEpisode import com.github.damontecres.wholphin.ui.tryRequestFocus import com.github.damontecres.wholphin.util.DataLoadingState +import org.jellyfin.sdk.model.api.BaseItemKind import java.time.LocalDateTime import java.time.ZoneId @Composable fun ProgramDialog( - state: DataLoadingState, + state: ProgramDialogState, canRecord: Boolean, onDismissRequest: () -> Unit, onWatch: (BaseItem) -> Unit, @@ -73,7 +74,7 @@ fun ProgramDialog( Modifier .padding(16.dp), ) { - when (val st = state) { + when (val st = state.loading) { is DataLoadingState.Error -> { ErrorMessage(st) } @@ -92,6 +93,7 @@ fun ProgramDialog( val item = st.data val now = LocalDateTime.now() val dto = item.data + val isSeries = item.data.isSeries ?: false val isRecording = dto.timerId.isNotNullOrBlank() val isSeriesRecording = dto.seriesTimerId.isNotNullOrBlank() LaunchedEffect(Unit) { focusRequester.tryRequestFocus() } @@ -148,126 +150,67 @@ fun ProgramDialog( .fillMaxWidth(), ) { if (now.isAfter(dto.startDate!!) && now.isBefore(dto.endDate!!)) { - TextButton( - onClick = { onWatch.invoke(item) }, - modifier = Modifier, + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, ) { - Row( - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Default.PlayArrow, - contentDescription = stringResource(R.string.delete), - ) - Text( - text = stringResource(R.string.watch_live), + state.recording?.let { recording -> + FaIconButton( + text = stringResource(R.string.play_from_start), + iconStringRes = R.string.fa_rotate_left, + onClick = { onWatch.invoke(recording) }, + modifier = Modifier, ) } + FaIconButton( + text = stringResource(R.string.watch_live), + iconStringRes = R.string.fa_play, + onClick = { onWatch.invoke(item) }, + modifier = Modifier, + ) } } if (canRecord) { val recordFocusRequester = remember { FocusRequester() } - LazyRow( - horizontalArrangement = - Arrangement.spacedBy( - 16.dp, - Alignment.CenterHorizontally, - ), - modifier = - Modifier - .fillMaxWidth() - .focusRestorer(recordFocusRequester), + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier, ) { - if (dto.isSeries ?: false) { - item { - TextButton( - onClick = { - if (isSeriesRecording) { - onCancelRecord.invoke(item, true) - } else { - onRecord.invoke(item, true) - } - }, - modifier = - Modifier.focusRequester(recordFocusRequester), - ) { - Row( - horizontalArrangement = - Arrangement.spacedBy( - 4.dp, - ), - verticalAlignment = Alignment.CenterVertically, - ) { - if (isSeriesRecording) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = null, - tint = Color.Red, - ) - } - Text( - text = - if (isSeriesRecording) { - stringResource( - R.string.cancel_series_recording, - ) - } else { - stringResource(R.string.record_series) - }, - ) + if (isSeries) { + RecordButton( + isRecording = isSeriesRecording, + isSeries = true, + onClick = { + if (isSeriesRecording) { + onCancelRecord.invoke(item, true) + } else { + onRecord.invoke(item, true) } - } - } + }, + modifier = Modifier.focusRequester(recordFocusRequester), + ) } if (dto.endDate?.isAfter(LocalDateTime.now()) ?: true) { // Only show program specific recording button if it hasn't finished yet - item { - TextButton( - onClick = { - if (isRecording) { - onCancelRecord.invoke(item, false) - } else { - onRecord.invoke(item, false) - } - }, - modifier = - Modifier.ifElse( - !(dto.isSeries ?: false), - Modifier.focusRequester( - recordFocusRequester, - ), - ), - ) { - Row( - horizontalArrangement = - Arrangement.spacedBy( - 4.dp, - ), - verticalAlignment = Alignment.CenterVertically, - ) { - if (isRecording) { - Icon( - imageVector = Icons.Default.Close, - contentDescription = null, - tint = Color.Red, - ) - } - Text( - text = - if (isRecording) { - stringResource( - R.string.cancel_recording, - ) - } else { - stringResource( - R.string.record_program, - ) - }, - ) + RecordButton( + isRecording = isRecording, + isSeries = false, + onClick = { + if (isRecording) { + onCancelRecord.invoke(item, false) + } else { + onRecord.invoke(item, false) } - } - } + }, + modifier = + Modifier.ifElse( + !isSeries, + Modifier.focusRequester( + recordFocusRequester, + ), + ), + ) } } } @@ -278,3 +221,102 @@ fun ProgramDialog( } } } + +/** + * Handles the onWatch for [ProgramDialog] + */ +fun onWatch( + context: Context, + navigationManager: NavigationManager, + item: BaseItem, +) { + val channelId = item.data.channelId + if (channelId != null) { + navigationManager.navigateTo( + Destination.Playback( + itemId = channelId, + positionMs = 0L, + ), + ) + } else if (item.type == BaseItemKind.RECORDING) { + navigationManager.navigateTo( + Destination.Playback( + itemId = item.id, + positionMs = 0L, + ), + ) + } else { + Toast + .makeText(context, "Program has no channel ID", Toast.LENGTH_LONG) + .show() + } +} + +@Composable +fun FaIconButton( + text: String, + @StringRes iconStringRes: Int, + onClick: () -> Unit, + modifier: Modifier = Modifier, + iconColor: Color = Color.Unspecified, +) { + TextButton( + onClick = onClick, + modifier = modifier, + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(iconStringRes), + fontFamily = FontAwesome, + color = iconColor, + ) + Text( + text = text, + ) + } + } +} + +@Composable +fun RecordButton( + isRecording: Boolean, + isSeries: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + TextButton( + onClick = onClick, + modifier = modifier, + ) { + Row( + horizontalArrangement = + Arrangement.spacedBy( + 4.dp, + ), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isRecording) { + Text( + text = stringResource(R.string.fa_xmark), + fontFamily = FontAwesome, + color = Color.Red, + ) + } else { + RecordingMarker(true, isSeries) + } + val str = + when { + isRecording && isSeries -> R.string.cancel_series_recording + isRecording && !isSeries -> R.string.cancel_recording + isSeries -> R.string.record_series + else -> R.string.record_program + } + Text( + text = stringResource(str), + ) + } + } +} diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/TvGuideGrid.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/TvGuideGrid.kt index aafaac878b..50067101e3 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/TvGuideGrid.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/detail/livetv/TvGuideGrid.kt @@ -22,9 +22,11 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -64,6 +66,8 @@ import eu.wewox.programguide.ProgramGuide import eu.wewox.programguide.ProgramGuideDimensions import eu.wewox.programguide.ProgramGuideItem import eu.wewox.programguide.rememberSaveableProgramGuideState +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber @@ -71,6 +75,7 @@ import java.time.LocalDateTime import java.time.OffsetDateTime import java.util.UUID import kotlin.math.abs +import kotlin.time.Duration.Companion.minutes @Composable fun TvGuideGrid( @@ -100,10 +105,7 @@ fun TvGuideGrid( LoadingState.Success, -> { val context = LocalContext.current - val programDialogState = - viewModel.programDialogState - .collectAsState() - .value.loading + val programDialogState by viewModel.programDialogState.collectAsState() var showItemDialog by remember { mutableStateOf(null) } val focusRequester = remember { FocusRequester() } @@ -211,19 +213,7 @@ fun TvGuideGrid( onDismissRequest = onDismissRequest, onWatch = { onDismissRequest.invoke() - val channelId = it.data.channelId - if (channelId != null) { - viewModel.navigationManager.navigateTo( - Destination.Playback( - itemId = channelId, - positionMs = 0L, - ), - ) - } else { - Toast - .makeText(context, "Program has no channel ID", Toast.LENGTH_LONG) - .show() - } + onWatch(context, viewModel.navigationManager, it) }, onRecord = { program, series -> viewModel.record( @@ -321,7 +311,7 @@ fun TvGuideGridContent( var focusedChannelIndex by rememberInt(-1) var focusedItem by rememberPosition(RowColumn(0, 0)) - var focusedProgramIndex by rememberInt(0) + var focusedProgramIndex by rememberSaveable(guideTimes) { mutableIntStateOf(0) } LaunchedEffect(onFocus, focusedProgramIndex) { withContext(WholphinDispatchers.Default) { @@ -336,7 +326,6 @@ fun TvGuideGridContent( }.sum() val programIndex = focusedProgramIndex - programsBefore focusedItem = RowColumn(channelIndex, programIndex) - onFocus.invoke(focusedItem) } } } @@ -363,6 +352,13 @@ fun TvGuideGridContent( programFocusRequester.tryRequestFocus() } } + var currentTime by remember { mutableStateOf(ProgramGuideItem.CurrentTime(hoursBetween(guideStart, LocalDateTime.now()))) } + LaunchedEffect(guideStart) { + while (isActive) { + delay(1.minutes) + currentTime = ProgramGuideItem.CurrentTime(hoursBetween(guideStart, LocalDateTime.now())) + } + } Box( modifier = modifier, @@ -375,16 +371,14 @@ fun TvGuideGridContent( guideStartHour = 0f currentTime( layoutInfo = { - ProgramGuideItem.CurrentTime( - hoursBetween(guideStart, LocalDateTime.now()), - ) + currentTime }, ) { Surface( colors = SurfaceDefaults.colors( MaterialTheme.colorScheme.tertiary.copy( - alpha = .25f, + alpha = .4f, ), ), modifier = Modifier, @@ -407,6 +401,7 @@ fun TvGuideGridContent( endHour = hoursBetween(guideStart, end), ) }, + key = { index -> guideTimes[index].toInstant(OffsetDateTime.now().offset).epochSecond }, ) { index -> Box( modifier = @@ -422,18 +417,21 @@ fun TvGuideGridContent( shape = RoundedCornerShape(4.dp), ), ) { - val guideTime = guideTimes[index] - val differentDay = guideTime.toLocalDate() != guideStart.toLocalDate() val time = - DateUtils.formatDateTime( - context, - guideTime - .toInstant(OffsetDateTime.now().offset) - .epochSecond * 1000, - DateUtils.FORMAT_SHOW_TIME or if (differentDay) DateUtils.FORMAT_SHOW_WEEKDAY else 0, - ) + remember(index, guideStart) { + val guideTime = guideTimes[index] + val differentDay = guideTime.toLocalDate() != guideStart.toLocalDate() + DateUtils + .formatDateTime( + context, + guideTime + .toInstant(OffsetDateTime.now().offset) + .epochSecond * 1000, + DateUtils.FORMAT_SHOW_TIME or if (differentDay) DateUtils.FORMAT_SHOW_WEEKDAY else 0, + ).toString() + } Text( - text = time.toString(), + text = time, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding(2.dp), ) @@ -453,6 +451,7 @@ fun TvGuideGridContent( program.startHours + duration, ) }, + key = { programIndex -> programs.programs[programIndex].id.toString() }, ) { programIndex -> val program = programs.programs[programIndex] Program( @@ -495,6 +494,7 @@ fun TvGuideGridContent( layoutInfo = { channelIndex -> ProgramGuideItem.Channel(channelIndex) }, + key = { channelIndex -> channels[channelIndex].id.toString() }, ) { channelIndex -> val channel = channels[channelIndex] Channel( diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/nav/NavDrawer.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/nav/NavDrawer.kt index 100b6cafb1..61eb9b9ca7 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/nav/NavDrawer.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/nav/NavDrawer.kt @@ -534,7 +534,10 @@ fun NavDrawer( ), ) }, - modifier = Modifier, + modifier = + Modifier.focusProperties { + down = FocusRequester.Cancel + }, ) } } diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentMediaInfo.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentMediaInfo.kt index 829915802c..20a34c14a8 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentMediaInfo.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentMediaInfo.kt @@ -19,13 +19,13 @@ import org.jellyfin.sdk.model.extensions.ticks data class CurrentMediaInfo( val sourceId: String?, val videoStream: SimpleVideoStream?, - val audioStreams: List, - val subtitleStreams: List, + val audioStreams: List, + val subtitleStreams: List, val chapters: List, val trickPlayInfo: TrickplayInfoDto?, ) { companion object { - val EMPTY = CurrentMediaInfo(null, null, listOf(), listOf(), listOf(), null) + val EMPTY = CurrentMediaInfo(null, null, emptyList(), emptyList(), emptyList(), null) } } diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentPlayback.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentPlayback.kt index 54663af625..2bada6fca6 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentPlayback.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/CurrentPlayback.kt @@ -18,6 +18,7 @@ import kotlin.time.Duration */ data class CurrentPlayback( val item: BaseItem, + val displayInfo: PlaybackDisplayInfo, val tracks: List, val backend: PlayerBackend, val playMethod: PlayMethod, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/MediaTrack.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/MediaTrack.kt new file mode 100644 index 0000000000..c5a2f99d26 --- /dev/null +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/MediaTrack.kt @@ -0,0 +1,66 @@ +package com.github.damontecres.wholphin.ui.playback + +import com.github.damontecres.wholphin.R +import com.github.damontecres.wholphin.WholphinApplication +import com.github.damontecres.wholphin.data.model.TrackIndex +import com.github.damontecres.wholphin.ui.joinNotBlank +import com.github.damontecres.wholphin.util.TrackSupport + +/** + * Stores basic information about a track (stream) within media + */ +sealed interface MediaTrack { + val id: String + val streamTitle: String? + val displayTitle: String +} + +/** + * A [MediaTrack] from actual media playback such as from [androidx.media3.common.Tracks] + */ +data class PlaybackMediaTrack( + override val id: String, + val trackId: String, + override val streamTitle: String?, + override val displayTitle: String, +) : MediaTrack { + companion object { + fun from(track: TrackSupport): PlaybackMediaTrack? { + return track.id?.let { + val displayTitle = + listOf( + track.format.codecs, + track.format.label, + track.format.language, + ).joinNotBlank(" - ") ?: WholphinApplication.instance.getString(R.string.unknown) + return PlaybackMediaTrack("m_${track.id}", track.id, null, displayTitle) + } + } + } +} + +/** + * A [MediaTrack] representing that the track type is disabled + * + * @see [TrackIndex.DISABLED] + */ +data object MediaTrackDisabled : MediaTrack { + override val id: String = TrackIndex.DISABLED.toString() + override val streamTitle: String? + get() = null + override val displayTitle: String + get() = "" +} + +/** + * A [MediaTrack] representing that the track type is "only forced" + * + * @see [TrackIndex.ONLY_FORCED] + */ +data object StreamTrackOnlyForced : MediaTrack { + override val id: String = TrackIndex.ONLY_FORCED.toString() + override val streamTitle: String? + get() = null + override val displayTitle: String + get() = "" +} diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDialog.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDialog.kt index 3165246f8e..42c656fd98 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDialog.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDialog.kt @@ -41,7 +41,6 @@ import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import androidx.tv.material3.surfaceColorAtElevation import com.github.damontecres.wholphin.R -import com.github.damontecres.wholphin.data.model.TrackIndex import com.github.damontecres.wholphin.preferences.AppPreference import com.github.damontecres.wholphin.ui.AppColors import com.github.damontecres.wholphin.ui.components.SelectedLeadingContent @@ -67,10 +66,10 @@ enum class PlaybackDialogType { data class PlaybackSettings( val showDebugInfo: Boolean, - val audioIndex: Int?, - val audioStreams: List, - val subtitleIndex: Int?, - val subtitleStreams: List, + val audioStreamId: String?, + val audioStreams: List, + val subtitleStreamId: String?, + val subtitleStreams: List, val playbackSpeed: Float, val contentScale: ContentScale, val subtitleDelay: Duration, @@ -111,21 +110,15 @@ fun PlaybackDialog( PlaybackDialogType.CAPTIONS -> { SubtitleChoiceBottomDialog( choices = settings.subtitleStreams, - currentChoice = settings.subtitleIndex, + currentChoiceId = settings.subtitleStreamId, hasDownloadPermission = settings.hasSubtitleDownloadPermission, onDismissRequest = { onControllerInteraction.invoke() onDismissRequest.invoke() }, - onSelectChoice = { subtitleIndex -> + onSelectChoice = { subtitle -> onDismissRequest.invoke() - if (subtitleIndex >= 0) { - onPlaybackActionClick.invoke(PlaybackAction.ToggleCaptions(subtitleIndex)) - } else if (subtitleIndex == TrackIndex.DISABLED) { - onPlaybackActionClick.invoke(PlaybackAction.ToggleCaptions(TrackIndex.DISABLED)) - } else if (subtitleIndex == TrackIndex.ONLY_FORCED) { - onPlaybackActionClick.invoke(PlaybackAction.ToggleCaptions(TrackIndex.ONLY_FORCED)) - } + onPlaybackActionClick.invoke(PlaybackAction.ToggleCaptions(subtitle)) }, onSelectSearch = { onDismissRequest.invoke() @@ -199,13 +192,13 @@ fun PlaybackDialog( PlaybackDialogType.AUDIO -> { StreamChoiceBottomDialog( choices = settings.audioStreams, - currentChoice = settings.audioIndex, + currentChoiceId = settings.audioStreamId, onDismissRequest = { onControllerInteraction.invoke() onDismissRequest.invoke() }, onSelectChoice = { _, choice -> - onPlaybackActionClick.invoke(PlaybackAction.ToggleAudio(choice.index)) + onPlaybackActionClick.invoke(PlaybackAction.ToggleAudio(choice)) }, gravity = rightGravity, ) @@ -310,18 +303,18 @@ fun PlaybackDialog( @Composable fun SubtitleChoiceBottomDialog( - choices: List, + choices: List, onDismissRequest: () -> Unit, - onSelectChoice: (Int) -> Unit, + onSelectChoice: (MediaTrack) -> Unit, onSelectSearch: () -> Unit, gravity: Int, hasDownloadPermission: Boolean, - currentChoice: Int? = null, + currentChoiceId: String? = null, ) { val numberBefore = 2 val initialChoice = remember(choices) { - choices.indexOfFirstOrNull { it.index == currentChoice } + choices.indexOfFirstOrNull { it.id == currentChoiceId } } val scope = rememberCoroutineScope() val listState = @@ -371,13 +364,13 @@ fun SubtitleChoiceBottomDialog( val interactionSource = remember { MutableInteractionSource() } val focused by interactionSource.collectIsFocusedAsState() ListItem( - selected = currentChoice == TrackIndex.DISABLED, + selected = currentChoiceId == MediaTrackDisabled.id, interactionSource = interactionSource, onClick = { - onSelectChoice(TrackIndex.DISABLED) + onSelectChoice(MediaTrackDisabled) }, leadingContent = { - SelectedLeadingContent(currentChoice == TrackIndex.DISABLED) + SelectedLeadingContent(currentChoiceId == MediaTrackDisabled.id) }, headlineContent = { Text( @@ -402,12 +395,12 @@ fun SubtitleChoiceBottomDialog( } item { ListItem( - selected = currentChoice == TrackIndex.ONLY_FORCED, + selected = currentChoiceId == StreamTrackOnlyForced.id, onClick = { - onSelectChoice(TrackIndex.ONLY_FORCED) + onSelectChoice(StreamTrackOnlyForced) }, leadingContent = { - SelectedLeadingContent(currentChoice == TrackIndex.ONLY_FORCED) + SelectedLeadingContent(currentChoiceId == StreamTrackOnlyForced.id) }, headlineContent = { Text( @@ -423,12 +416,12 @@ fun SubtitleChoiceBottomDialog( itemsIndexed(choices) { index, choice -> val interactionSource = remember { MutableInteractionSource() } ListItem( - selected = choice.index == currentChoice, + selected = choice.id == currentChoiceId, onClick = { - onSelectChoice(choice.index) + onSelectChoice(choice) }, leadingContent = { - SelectedLeadingContent(choice.index == currentChoice) + SelectedLeadingContent(choice.id == currentChoiceId) }, headlineContent = { Text( @@ -480,16 +473,16 @@ fun SubtitleChoiceBottomDialog( @Composable fun StreamChoiceBottomDialog( - choices: List, + choices: List, onDismissRequest: () -> Unit, - onSelectChoice: (Int, SimpleMediaStream) -> Unit, + onSelectChoice: (Int, MediaTrack) -> Unit, gravity: Int, - currentChoice: Int? = null, + currentChoiceId: String? = null, ) { val focusRequesters = remember(choices.size) { List(choices.size) { FocusRequester() } } - if (currentChoice != null) { + if (currentChoiceId != null) { LaunchedEffect(Unit) { - choices.indexOfFirstOrNull { it.index == currentChoice }?.let { + choices.indexOfFirstOrNull { it.id == currentChoiceId }?.let { focusRequesters.getOrNull(it)?.tryRequestFocus() } } @@ -527,13 +520,13 @@ fun StreamChoiceBottomDialog( itemsIndexed(choices) { index, choice -> val interactionSource = remember { MutableInteractionSource() } ListItem( - selected = choice.index == currentChoice, + selected = choice.id == currentChoiceId, onClick = { onDismissRequest() onSelectChoice(index, choice) }, leadingContent = { - SelectedLeadingContent(choice.index == currentChoice) + SelectedLeadingContent(choice.id == currentChoiceId) }, headlineContent = { Text( diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDisplayInfo.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDisplayInfo.kt new file mode 100644 index 0000000000..f51098c432 --- /dev/null +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackDisplayInfo.kt @@ -0,0 +1,63 @@ +package com.github.damontecres.wholphin.ui.playback + +import com.github.damontecres.wholphin.data.model.BaseItem +import com.github.damontecres.wholphin.data.model.subtitleLong +import com.github.damontecres.wholphin.services.ImageUrlService +import org.jellyfin.sdk.model.api.BaseItemKind +import org.jellyfin.sdk.model.api.ImageType + +/** + * Information to display on the playback overlay + */ +data class PlaybackDisplayInfo( + val title: String?, + val subtitle: String?, + val logoImageUrl: String?, + val logoText: String?, +) { + companion object { + fun from( + item: BaseItem?, + imageUrlService: ImageUrlService, + ): PlaybackDisplayInfo = + when (item?.type) { + BaseItemKind.TV_CHANNEL -> { + val program = item.data.currentProgram + if (program != null) { + val subtitle = program.subtitleLong(program.isSeries == true) + PlaybackDisplayInfo( + title = program.name, + subtitle = subtitle, + logoImageUrl = imageUrlService.getItemImageUrl(item, ImageType.PRIMARY), + logoText = item.name, + ) + } else { + PlaybackDisplayInfo( + title = item.name, + subtitle = item.subtitleLong, + logoImageUrl = imageUrlService.getItemImageUrl(item, ImageType.PRIMARY), + logoText = null, + ) + } + } + + null -> { + PlaybackDisplayInfo( + title = null, + subtitle = null, + logoImageUrl = null, + logoText = null, + ) + } + + else -> { + PlaybackDisplayInfo( + title = item.title, + subtitle = item.subtitleLong, + logoImageUrl = imageUrlService.getItemImageUrl(item, ImageType.LOGO), + logoText = null, + ) + } + } + } +} diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackPage.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackPage.kt index 86d6465135..c6147b448f 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackPage.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackPage.kt @@ -69,6 +69,7 @@ import androidx.media3.ui.compose.state.rememberPlayPauseButtonState import androidx.media3.ui.compose.state.rememberPresentationState import androidx.tv.material3.MaterialTheme import androidx.tv.material3.surfaceColorAtElevation +import com.github.damontecres.wholphin.data.model.TrackIndex import com.github.damontecres.wholphin.mpv.MpvPlayer import com.github.damontecres.wholphin.preferences.AssPlaybackMode import com.github.damontecres.wholphin.preferences.DpadSeekMode @@ -99,6 +100,7 @@ import com.github.damontecres.wholphin.util.Media3SubtitleOverride import io.github.peerless2012.ass.media.widget.AssSubtitleView import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import org.jellyfin.sdk.model.api.MediaStreamType import org.jellyfin.sdk.model.extensions.ticks import timber.log.Timber import kotlin.time.Duration @@ -297,11 +299,21 @@ fun PlaybackPageContent( } is PlaybackAction.ToggleAudio -> { - viewModel.changeAudioStream(it.index) + when (it.track) { + is PlaybackMediaTrack -> viewModel.activateTrack(it.track.trackId, MediaStreamType.AUDIO) + is SimpleMediaStream -> viewModel.changeAudioStream(it.track.index) + MediaTrackDisabled -> viewModel.changeAudioStream(TrackIndex.DISABLED) + StreamTrackOnlyForced -> throw IllegalArgumentException("Only forced not support for audio") + } } is PlaybackAction.ToggleCaptions -> { - viewModel.changeSubtitleStream(it.index) + when (it.track) { + is PlaybackMediaTrack -> viewModel.activateTrack(it.track.trackId, MediaStreamType.SUBTITLE) + is SimpleMediaStream -> viewModel.changeSubtitleStream(it.track.index) + MediaTrackDisabled -> viewModel.changeSubtitleStream(TrackIndex.DISABLED) + StreamTrackOnlyForced -> viewModel.changeSubtitleStream(TrackIndex.ONLY_FORCED) + } } PlaybackAction.SearchCaptions -> { @@ -476,7 +488,7 @@ fun PlaybackPageContent( .padding(WindowInsets.systemBars.asPaddingValues()) .fillMaxSize() .background(Color.Transparent), - item = state.currentPlayback?.item, + displayInfo = state.currentPlayback?.displayInfo, player = player, controllerViewState = controllerViewState, showPlay = playPauseState.showPlay, @@ -744,9 +756,9 @@ fun PlaybackPageContent( settings = PlaybackSettings( showDebugInfo = showDebugInfo, - audioIndex = state.currentPlayback?.audioIndex, + audioStreamId = state.currentPlayback?.audioIndex?.toString(), audioStreams = state.currentMediaInfo.audioStreams, - subtitleIndex = state.currentPlayback?.subtitleIndex, + subtitleStreamId = state.currentPlayback?.subtitleIndex?.toString(), subtitleStreams = state.currentMediaInfo.subtitleStreams, playbackSpeed = playbackSpeed, contentScale = contentScale, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackViewModel.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackViewModel.kt index 5b951288fe..6341ab90d8 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackViewModel.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/PlaybackViewModel.kt @@ -56,6 +56,7 @@ import com.github.damontecres.wholphin.services.RefreshRateService import com.github.damontecres.wholphin.services.ScreensaverService import com.github.damontecres.wholphin.services.StreamChoiceService import com.github.damontecres.wholphin.services.UserPreferencesService +import com.github.damontecres.wholphin.ui.detail.isInProgressRecording import com.github.damontecres.wholphin.ui.formatBitrate import com.github.damontecres.wholphin.ui.gt import com.github.damontecres.wholphin.ui.isNotNullOrBlank @@ -71,6 +72,8 @@ import com.github.damontecres.wholphin.util.ExceptionHandler import com.github.damontecres.wholphin.util.LoadingState import com.github.damontecres.wholphin.util.PlaybackItemState import com.github.damontecres.wholphin.util.TrackActivityPlaybackListener +import com.github.damontecres.wholphin.util.TrackSupportReason +import com.github.damontecres.wholphin.util.TrackType import com.github.damontecres.wholphin.util.WholphinDispatchers import com.github.damontecres.wholphin.util.checkForSupport import com.github.damontecres.wholphin.util.mpv.mpvDeviceProfile @@ -477,7 +480,7 @@ class PlaybackViewModel this@PlaybackViewModel.currentItem = playlistItem this@PlaybackViewModel.itemId = item.id - val isLiveTv = item.type == BaseItemKind.TV_CHANNEL + val isLiveTv = item.type == BaseItemKind.TV_CHANNEL || item.isInProgressRecording val base = item.data // Use the provided playback parameters or else check if the database has some @@ -672,35 +675,43 @@ class PlaybackViewModel ) _state.update { it.copy(maxBitrate = maxBitrate) } - val response by - api.mediaInfoApi - .getPostedPlaybackInfo( - itemId, - PlaybackInfoDto( - startTimeTicks = null, - deviceProfile = - if (currentPlayer.value!!.backend == PlayerBackend.EXO_PLAYER) { - deviceProfileService.getOrCreateDeviceProfile( - preferences.appPreferences, - serverRepository.currentServer?.serverVersion, - ) - } else { - mpvDeviceProfile - }, - maxAudioChannels = null, - audioStreamIndex = audioIndex, - subtitleStreamIndex = subtitleIndex, - mediaSourceId = sourceId, - alwaysBurnInSubtitleWhenTranscoding = false, - maxStreamingBitrate = maxBitrate.toInt(), - enableDirectPlay = enableDirectPlay, - enableDirectStream = enableDirectStream, - allowVideoStreamCopy = enableDirectStream, - allowAudioStreamCopy = enableDirectStream, - enableTranscoding = true, - autoOpenLiveStream = true, - ), - ) + val response = + try { + api.mediaInfoApi + .getPostedPlaybackInfo( + itemId, + PlaybackInfoDto( + startTimeTicks = null, + deviceProfile = + if (currentPlayer.value!!.backend == PlayerBackend.EXO_PLAYER) { + deviceProfileService.getOrCreateDeviceProfile( + preferences.appPreferences, + serverRepository.currentServer?.serverVersion, + ) + } else { + mpvDeviceProfile + }, + maxAudioChannels = null, + audioStreamIndex = audioIndex, + subtitleStreamIndex = subtitleIndex, + mediaSourceId = sourceId, + alwaysBurnInSubtitleWhenTranscoding = false, + maxStreamingBitrate = maxBitrate.toInt(), + enableDirectPlay = enableDirectPlay, + enableDirectStream = enableDirectStream, + allowVideoStreamCopy = enableDirectStream, + allowAudioStreamCopy = enableDirectStream, + enableTranscoding = true, + autoOpenLiveStream = true, + ), + ).content + } catch (ex: CancellationException) { + throw ex + } catch (ex: Exception) { + Timber.e(ex, "Error in getPostedPlaybackInfo") + _state.update { it.copy(loading = LoadingState.Error(ex)) } + return@withContext + } if (response.errorCode != null) { Timber.e("Error in PostedPlaybackInfo: %s", response.errorCode) _state.update { it.copy(loading = LoadingState.Error(response.errorCode?.serialName)) } @@ -801,6 +812,7 @@ class PlaybackViewModel val playback = CurrentPlayback( item = item, + displayInfo = PlaybackDisplayInfo.from(item, imageUrlService), tracks = listOf(), backend = currentPlayer.value!!.backend, playMethod = transcodeType, @@ -1031,6 +1043,29 @@ class PlaybackViewModel } } + fun activateTrack( + id: String, + type: MediaStreamType, + ) { + viewModelScope.launchDefault { + val result = + TrackSelectionUtils.createTrackSelectionParametersForTrack( + trackSelectionParams = onMain { player.trackSelectionParameters }, + tracks = onMain { player.currentTracks }, + trackId = id, + type = type, + ) + if (result != null) { + updateCurrentPlayback { + it?.copy(subtitleIndex = TrackIndex.UNSPECIFIED) + } + onMain { player.trackSelectionParameters = result } + } else { + // TODO, show message? + } + } + } + fun changeMaxBitrate(newMaxBitrate: Long) { viewModelScope.launchIO { val currentPlayback = state.value.currentPlayback @@ -1109,7 +1144,7 @@ class PlaybackViewModel } override fun onPlaybackStateChanged(playbackState: Int) { - if (playbackState == Player.STATE_ENDED) { + if (playbackState == Player.STATE_ENDED && state.value.loading !is LoadingState.Error) { Timber.v("Playback state is STATE_ENDED") viewModelScope.launchDefault { when (val nextItem = state.value.nextItem()) { @@ -1148,6 +1183,8 @@ class PlaybackViewModel } } } + } else if (playbackState == Player.STATE_ENDED) { + Timber.i("Playback ended, but there is in error state") } } @@ -1404,10 +1441,41 @@ class PlaybackViewModel } override fun onTracksChanged(tracks: Tracks) { + val support = checkForSupport(tracks) updateCurrentPlayback { - it?.copy( - tracks = checkForSupport(tracks), - ) + it?.copy(tracks = support) + } + viewModelScope.launchDefault { + state.value.currentPlayback?.let { currentPlayback -> + if (currentPlayback.item.type == BaseItemKind.TV_CHANNEL && currentPlayback.playMethod == PlayMethod.DIRECT_PLAY) { + // Direct playing live tv, so grab the tracks from the actual video + val audioTracks = + support + .filter { + it.id.isNotNullOrBlank() && + it.supported == TrackSupportReason.HANDLED && + it.type == TrackType.AUDIO + }.mapNotNull { + PlaybackMediaTrack.from(it) + } + + val subtitleTracks = + support + .filter { + it.id.isNotNullOrBlank() && + it.supported == TrackSupportReason.HANDLED && + it.type == TrackType.TEXT + }.mapNotNull { + PlaybackMediaTrack.from(it) + } + updateCurrentMedia { + it.copy( + audioStreams = audioTracks, + subtitleStreams = subtitleTracks, + ) + } + } + } } } diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/SimpleMediaStream.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/SimpleMediaStream.kt index 046990051d..2cb09ed20f 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/SimpleMediaStream.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/SimpleMediaStream.kt @@ -8,13 +8,17 @@ import org.jellyfin.sdk.model.api.MediaStream /** * A slimmer [MediaStream] with minimal data for UI purposes * + * This is also a [MediaTrack] provided by the server's media source + * * @see SimpleVideoStream */ data class SimpleMediaStream( val index: Int, - val streamTitle: String?, - val displayTitle: String, -) { + override val streamTitle: String?, + override val displayTitle: String, +) : MediaTrack { + override val id: String get() = index.toString() + companion object { fun from( resources: Resources, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/TrackSelectionUtils.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/TrackSelectionUtils.kt index 7b37739970..bc8f53e26c 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/TrackSelectionUtils.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/TrackSelectionUtils.kt @@ -172,6 +172,38 @@ object TrackSelectionUtils { } }.sortedWith(compareBy>> { it.second[0] }.thenBy { it.second[1] }) .map { it.first } + + /** + * Create a [TrackSelectionParameters] to activate a specific track identified by its ID + */ + fun createTrackSelectionParametersForTrack( + trackSelectionParams: TrackSelectionParameters, + tracks: Tracks, + trackId: String, + type: MediaStreamType, + ): TrackSelectionParameters? { + val type = + when (type) { + MediaStreamType.AUDIO -> C.TRACK_TYPE_AUDIO + MediaStreamType.SUBTITLE -> C.TRACK_TYPE_TEXT + MediaStreamType.VIDEO -> C.TRACK_TYPE_VIDEO + else -> throw IllegalArgumentException("Type not supported: $type") + } + val group = + tracks.groups + .firstOrNull { group -> + group.type == type && group.length >= 1 && group.trackFormats.any { it.id == trackId } + } + return group?.let { + trackSelectionParams + .buildUpon() + .clearOverridesOfType(type) + .setTrackTypeDisabled(type, false) + .setOverrideForType( + TrackSelectionOverride(group.mediaTrackGroup, 0), + ).build() + } + } } /** diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackController.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackController.kt index 2909e666a9..b1f1d53bbe 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackController.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackController.kt @@ -32,10 +32,10 @@ import androidx.media3.common.Player import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import com.github.damontecres.wholphin.R -import com.github.damontecres.wholphin.data.model.BaseItem import com.github.damontecres.wholphin.ui.formatTime import com.github.damontecres.wholphin.ui.playback.ControllerViewState import com.github.damontecres.wholphin.ui.playback.PlaybackDialogType +import com.github.damontecres.wholphin.ui.playback.PlaybackDisplayInfo import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import org.jellyfin.sdk.model.api.MediaSegmentDto @@ -46,7 +46,7 @@ import kotlin.time.Duration.Companion.seconds @Composable fun PlaybackController( - item: BaseItem?, + displayInfo: PlaybackDisplayInfo?, nextState: OverlayViewState?, player: Player, controllerViewState: ControllerViewState, @@ -70,8 +70,8 @@ fun PlaybackController( modifier = modifier, ) { Controller( - title = item?.title, - subtitle = item?.subtitleLong, + title = displayInfo?.title, + subtitle = displayInfo?.subtitle, player = player, controllerViewState = controllerViewState, showPlay = showPlay, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackControls.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackControls.kt index 45fcdd4c90..500d64b966 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackControls.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackControls.kt @@ -76,6 +76,7 @@ import com.github.damontecres.wholphin.ui.components.TextButton import com.github.damontecres.wholphin.ui.formatDuration import com.github.damontecres.wholphin.ui.indexOfFirstOrNull import com.github.damontecres.wholphin.ui.playback.ControllerViewState +import com.github.damontecres.wholphin.ui.playback.MediaTrack import com.github.damontecres.wholphin.ui.playback.PlaybackDialogType import com.github.damontecres.wholphin.ui.seekBack import com.github.damontecres.wholphin.ui.seekForward @@ -105,11 +106,11 @@ sealed interface PlaybackAction { data object SearchCaptions : PlaybackAction data class ToggleCaptions( - val index: Int, + val track: MediaTrack, ) : PlaybackAction data class ToggleAudio( - val index: Int, + val track: MediaTrack, ) : PlaybackAction data class PlaybackSpeed( diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackDebugOverlay.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackDebugOverlay.kt index 2aecdc65f2..b15fc1fab8 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackDebugOverlay.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackDebugOverlay.kt @@ -32,6 +32,7 @@ import com.github.damontecres.wholphin.ui.formatBytes import com.github.damontecres.wholphin.ui.letNotEmpty import com.github.damontecres.wholphin.ui.playback.AnalyticsState import com.github.damontecres.wholphin.ui.playback.CurrentPlayback +import com.github.damontecres.wholphin.ui.playback.PlaybackDisplayInfo import com.github.damontecres.wholphin.ui.theme.WholphinTheme import com.github.damontecres.wholphin.util.TrackSupport import com.github.damontecres.wholphin.util.TrackSupportReason @@ -213,6 +214,7 @@ fun PlaybackDebugOverlayPreview() { type = BaseItemKind.EPISODE, ), ), + displayInfo = PlaybackDisplayInfo(null, null, null, null), backend = PlayerBackend.EXO_PLAYER, playMethod = PlayMethod.TRANSCODE, playSessionId = "123", diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackOverlay.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackOverlay.kt index ee3c4ac6fb..6ce80553d3 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackOverlay.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/playback/overlay/PlaybackOverlay.kt @@ -25,6 +25,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect @@ -42,24 +43,27 @@ import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.media3.common.Player +import androidx.tv.material3.MaterialTheme +import androidx.tv.material3.Text import coil3.compose.AsyncImage import com.github.damontecres.wholphin.data.model.BaseItem import com.github.damontecres.wholphin.data.model.Chapter import com.github.damontecres.wholphin.data.model.PlaylistItem import com.github.damontecres.wholphin.ui.AppColors -import com.github.damontecres.wholphin.ui.LocalImageUrlService import com.github.damontecres.wholphin.ui.components.TimeDisplay import com.github.damontecres.wholphin.ui.isNotNullOrBlank +import com.github.damontecres.wholphin.ui.logCoilError import com.github.damontecres.wholphin.ui.playback.AnalyticsState import com.github.damontecres.wholphin.ui.playback.ControllerViewState import com.github.damontecres.wholphin.ui.playback.CurrentPlayback import com.github.damontecres.wholphin.ui.playback.PlaybackDialogType -import org.jellyfin.sdk.model.api.ImageType +import com.github.damontecres.wholphin.ui.playback.PlaybackDisplayInfo import org.jellyfin.sdk.model.api.MediaSegmentDto import org.jellyfin.sdk.model.api.TrickplayInfoDto import kotlin.time.Duration @@ -69,7 +73,7 @@ import kotlin.time.Duration */ @Composable fun PlaybackOverlay( - item: BaseItem?, + displayInfo: PlaybackDisplayInfo?, chapters: List, player: Player, controllerViewState: ControllerViewState, @@ -103,12 +107,12 @@ fun PlaybackOverlay( val density = LocalDensity.current val titleHeight = - remember(item?.title, density) { - if (item?.title.isNotNullOrBlank()) with(density) { titleTextSize.toDp() } else 0.dp + remember(displayInfo?.title, density) { + if (displayInfo?.title.isNotNullOrBlank()) with(density) { titleTextSize.toDp() } else 0.dp } val subtitleHeight = - remember(item?.subtitleLong, density) { - if (item?.subtitleLong.isNotNullOrBlank()) with(density) { subtitleTextSize.toDp() } else 0.dp + remember(displayInfo?.subtitle, density) { + if (displayInfo?.subtitle.isNotNullOrBlank()) with(density) { subtitleTextSize.toDp() } else 0.dp } // This will be calculated after composition @@ -187,7 +191,7 @@ fun PlaybackOverlay( } } PlaybackController( - item = item, + displayInfo = displayInfo, nextState = nextState, player = player, controllerViewState = controllerViewState, @@ -296,25 +300,46 @@ fun PlaybackOverlay( } } + var logoImageError by remember(displayInfo?.logoImageUrl) { mutableStateOf(displayInfo?.logoImageUrl.isNullOrBlank()) } // Top - val logoImageUrl = LocalImageUrlService.current.rememberImageUrl(item, ImageType.LOGO) AnimatedVisibility( - visible = !showDebugInfo && logoImageUrl.isNotNullOrBlank() && controllerViewState.controlsVisible, + visible = !showDebugInfo && controllerViewState.controlsVisible, enter = slideIn { IntOffset(x = -it.width / 2, y = -it.height / 2) } + fadeIn(), exit = slideOut { IntOffset(x = -it.width / 2, y = -it.height / 2) } + fadeOut(), modifier = Modifier .align(Alignment.TopStart), ) { - AsyncImage( - model = logoImageUrl, - contentDescription = "Logo", - alignment = Alignment.TopStart, - modifier = - Modifier - .size(width = 240.dp, height = 120.dp) - .padding(16.dp), - ) + if (!logoImageError) { + AsyncImage( + model = displayInfo?.logoImageUrl, + contentDescription = "Logo", + alignment = Alignment.TopStart, + onError = { + logCoilError(displayInfo?.logoImageUrl, it.result) + logoImageError = true + }, + modifier = + Modifier + .size(width = 240.dp, height = 120.dp) + .padding(16.dp), + ) + } else { + displayInfo?.logoText?.let { + // Fallback to displaying the logo as text + Text( + text = it, + style = MaterialTheme.typography.titleLarge, + fontSize = titleTextSize, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier + .widthIn(max = 240.dp) + .padding(16.dp), + ) + } + } } AnimatedVisibility( visible = !showDebugInfo && showClock && controllerViewState.controlsVisible, diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchPage.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchPage.kt index f20222d969..938d8a4485 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchPage.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchPage.kt @@ -1,6 +1,5 @@ package com.github.damontecres.wholphin.ui.search -import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.annotation.StringRes import androidx.compose.animation.AnimatedVisibility @@ -71,6 +70,7 @@ import com.github.damontecres.wholphin.ui.detail.CardGrid import com.github.damontecres.wholphin.ui.detail.CardGridItem import com.github.damontecres.wholphin.ui.detail.GridItemDetails import com.github.damontecres.wholphin.ui.detail.livetv.ProgramDialog +import com.github.damontecres.wholphin.ui.detail.livetv.onWatch import com.github.damontecres.wholphin.ui.nav.Destination import com.github.damontecres.wholphin.ui.onMain import com.github.damontecres.wholphin.ui.titleStringRes @@ -500,22 +500,12 @@ fun SearchPage( val context = LocalContext.current val onDismissRequest = { showProgramDialog = false } ProgramDialog( - state = programDialogState.loading, + state = programDialogState, canRecord = true, onDismissRequest = onDismissRequest, onWatch = { onDismissRequest.invoke() - val channelId = it.data.channelId - if (channelId != null) { - viewModel.navigationManager.navigateTo( - Destination.Playback( - itemId = channelId, - positionMs = 0L, - ), - ) - } else { - Toast.makeText(context, "Program has no channel ID", Toast.LENGTH_LONG).show() - } + onWatch(context, viewModel.navigationManager, it) }, onRecord = { program, series -> viewModel.record( diff --git a/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchViewModel.kt b/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchViewModel.kt index 474ff26e9d..dd3281d746 100644 --- a/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchViewModel.kt +++ b/app/src/main/java/com/github/damontecres/wholphin/ui/search/SearchViewModel.kt @@ -457,7 +457,14 @@ class SearchViewModel viewModelScope.launchDefault { try { val result = liveTvService.fetchProgramForDialog(programId) - _programDialogState.update { it.copy(loading = DataLoadingState.Success(result)) } + val recording = liveTvService.fetchRecordingForProgram(result) + Timber.d("Got recording %s for program %s", recording?.id, programId) + _programDialogState.update { + it.copy( + loading = DataLoadingState.Success(result), + recording = recording, + ) + } } catch (ex: CancellationException) { throw ex } catch (ex: Exception) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 98b35bd3f4..24eb6d0743 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -987,4 +987,5 @@ Managed by server Error Invalid Dolby Vision + Watch from start