Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Refactor player and EPG view models

David Nashash342eae81a364
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
index fae0f4b0..4bc2ddc0 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
@@ -44,6 +44,7 @@ import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
@@ -829,22 +830,9 @@ class EpgViewModel @Inject constructor(
data.copy(showAllChannels = showAll)
}
.combine(
- combine(
- selectedCategoryId,
- startupCategoryId,
- guideAnchorTime,
- showFavoritesOnly,
- refreshNonce
- ) { requestedCategoryId, startupSelectionId, anchorTime, favoritesOnly, _ ->
- GuideSelectionSeed(
- requestedCategoryId = startupSelectionId ?: requestedCategoryId,
- anchorTime = anchorTime,
- favoritesOnly = favoritesOnly,
- isStartupSelection = startupSelectionId != null
- )
- }.combine(preferencesRepository.parentalControlLevel) { selection, parentalControlLevel ->
- selection to parentalControlLevel
- }.combine(parentalControlManager.unlockedCategoriesForProvider(provider.id)) { (selection, parentalControlLevel), unlockedCategoryIds ->
+ guideSelectionStateFlow().combine(
+ parentalControlManager.unlockedCategoriesForProvider(provider.id)
+ ) { (selection, parentalControlLevel), unlockedCategoryIds ->
GuideSelectionRequest(
requestedCategoryId = selection.requestedCategoryId,
anchorTime = selection.anchorTime,
@@ -885,15 +873,13 @@ class EpgViewModel @Inject constructor(
}.collectLatest { request ->
val categories = request.categories
val hasVisibleGuide = _uiState.value.channels.isNotEmpty() || _uiState.value.programsByChannel.isNotEmpty()
+ val providerSourceLabel = buildProviderSourceLabel(provider)
+ val providerArchiveSummary = buildProviderArchiveSummary(provider)
_uiState.update {
it.copy(
currentProviderName = provider.name,
- providerSourceLabel = when (provider.type) {
- com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
- com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
- com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
- },
- providerArchiveSummary = buildProviderArchiveSummary(provider),
+ providerSourceLabel = providerSourceLabel,
+ providerArchiveSummary = providerArchiveSummary,
categories = categories,
parentalControlLevel = request.parentalControlLevel,
showFavoritesOnly = request.favoritesOnly,
@@ -924,12 +910,8 @@ class EpgViewModel @Inject constructor(
publishGuideSnapshot(
providerId = provider.id,
providerName = provider.name,
- providerSourceLabel = when (provider.type) {
- com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
- com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
- com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
- },
- providerArchiveSummary = buildProviderArchiveSummary(provider),
+ providerSourceLabel = providerSourceLabel,
+ providerArchiveSummary = providerArchiveSummary,
categories = categories,
request = request,
channelSelection = channelSelection,
@@ -961,22 +943,7 @@ class EpgViewModel @Inject constructor(
providerIdsFlow.flatMapLatest { providerIds ->
getCustomCategories(providerIds, ContentType.LIVE)
},
- combine(
- selectedCategoryId,
- startupCategoryId,
- guideAnchorTime,
- showFavoritesOnly,
- refreshNonce
- ) { requestedCategoryId, startupSelectionId, anchorTime, favoritesOnly, _ ->
- GuideSelectionSeed(
- requestedCategoryId = startupSelectionId ?: requestedCategoryId,
- anchorTime = anchorTime,
- favoritesOnly = favoritesOnly,
- isStartupSelection = startupSelectionId != null
- )
- }.combine(preferencesRepository.parentalControlLevel) { selection, parentalControlLevel ->
- selection to parentalControlLevel
- }
+ guideSelectionStateFlow()
) { combinedCategories, providerIds, customCategories, selection ->
combinedCategoriesById = combinedCategories.associateBy { it.category.id }
CombinedGuideDependencies(
@@ -1099,6 +1066,27 @@ class EpgViewModel @Inject constructor(
else combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)
}
+ private fun guideSelectionSeedFlow(): Flow<GuideSelectionSeed> =
+ combine(
+ selectedCategoryId,
+ startupCategoryId,
+ guideAnchorTime,
+ showFavoritesOnly,
+ refreshNonce
+ ) { requestedCategoryId, startupSelectionId, anchorTime, favoritesOnly, _ ->
+ GuideSelectionSeed(
+ requestedCategoryId = startupSelectionId ?: requestedCategoryId,
+ anchorTime = anchorTime,
+ favoritesOnly = favoritesOnly,
+ isStartupSelection = startupSelectionId != null
+ )
+ }
+
+ private fun guideSelectionStateFlow(): Flow<Pair<GuideSelectionSeed, Int>> =
+ guideSelectionSeedFlow().combine(preferencesRepository.parentalControlLevel) { selection, parentalControlLevel ->
+ selection to parentalControlLevel
+ }
+
private suspend fun publishGuideSnapshot(
providerId: Long,
providerName: String,
@@ -1275,6 +1263,14 @@ class EpgViewModel @Inject constructor(
}
}
+ private fun buildProviderSourceLabel(provider: com.streamvault.domain.model.Provider): String {
+ return when (provider.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
+ com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
+ com.streamvault.domain.model.ProviderType.STALKER_PORTAL -> "Stalker/MAG Portal"
+ }
+ }
+
private fun buildProviderArchiveSummary(provider: com.streamvault.domain.model.Provider): String {
return when (provider.type) {
com.streamvault.domain.model.ProviderType.XTREAM_CODES ->
@@ -1330,19 +1326,11 @@ class EpgViewModel @Inject constructor(
providerId: Long,
request: GuideBaseRequest
) = when (request.resolvedCategoryId) {
- ChannelRepository.ALL_CHANNELS_ID -> combine(
- channelRepository.getChannelsByCategoryPage(providerId, request.resolvedCategoryId, MAX_CHANNELS),
- channelRepository.getChannelsWithoutErrorsPage(providerId, request.resolvedCategoryId, MAX_CHANNELS),
- favoriteRepository.getFavorites(providerId, ContentType.LIVE)
- ) { channelsByNumber, healthyChannels, favorites ->
- val favoriteIds = favorites.map { it.contentId }.toSet()
- if (request.favoritesOnly) {
- healthyChannels.filter { it.id in favoriteIds }
- .ifEmpty { channelsByNumber.filter { it.id in favoriteIds } }
- } else {
- healthyChannels.ifEmpty { channelsByNumber }
- }
- }
+ ChannelRepository.ALL_CHANNELS_ID -> loadPreferredGuideChannelsPage(
+ providerId = providerId,
+ categoryId = request.resolvedCategoryId,
+ favoritesOnly = request.favoritesOnly
+ )
VirtualCategoryIds.FAVORITES -> favoriteRepository.getFavorites(providerId, ContentType.LIVE)
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
@@ -1352,18 +1340,28 @@ class EpgViewModel @Inject constructor(
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
.flatMapLatest { ids -> loadGuideChannelsByOrderedIds(ids, providerId) }
- else -> combine(
- channelRepository.getChannelsByCategoryPage(providerId, request.resolvedCategoryId, MAX_CHANNELS),
- channelRepository.getChannelsWithoutErrorsPage(providerId, request.resolvedCategoryId, MAX_CHANNELS),
- favoriteRepository.getFavorites(providerId, ContentType.LIVE)
- ) { channelsByNumber, healthyChannels, favorites ->
- val favoriteIds = favorites.map { it.contentId }.toSet()
- if (request.favoritesOnly) {
- healthyChannels.filter { it.id in favoriteIds }
- .ifEmpty { channelsByNumber.filter { it.id in favoriteIds } }
- } else {
- healthyChannels.ifEmpty { channelsByNumber }
- }
+ else -> loadPreferredGuideChannelsPage(
+ providerId = providerId,
+ categoryId = request.resolvedCategoryId,
+ favoritesOnly = request.favoritesOnly
+ )
+ }
+
+ private fun loadPreferredGuideChannelsPage(
+ providerId: Long,
+ categoryId: Long,
+ favoritesOnly: Boolean
+ ): Flow<List<Channel>> = combine(
+ channelRepository.getChannelsByCategoryPage(providerId, categoryId, MAX_CHANNELS),
+ channelRepository.getChannelsWithoutErrorsPage(providerId, categoryId, MAX_CHANNELS),
+ favoriteRepository.getFavorites(providerId, ContentType.LIVE)
+ ) { channelsByNumber, healthyChannels, favorites ->
+ val favoriteIds = favorites.map { it.contentId }.toSet()
+ if (favoritesOnly) {
+ healthyChannels.filter { it.id in favoriteIds }
+ .ifEmpty { channelsByNumber.filter { it.id in favoriteIds } }
+ } else {
+ healthyChannels.ifEmpty { channelsByNumber }
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
new file mode 100644
index 00000000..23df4e51
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
@@ -0,0 +1,141 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LiveChannelVariant
+import kotlinx.coroutines.launch
+
+fun PlayerViewModel.hasAlternateStream(): Boolean {
+ if (isCatchUpPlayback()) {
+ return nextCatchUpVariant() != null
+ }
+ if (currentContentType != ContentType.LIVE) return false
+ val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return false
+ return nextLiveVariant(channel) != null ||
+ selectNextAlternateUrl(
+ candidateUrls = channel.alternativeStreams,
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ ) != null
+}
+
+fun PlayerViewModel.tryAlternateStream(): Boolean {
+ if (isCatchUpPlayback()) {
+ return tryNextCatchUpVariantInternal()
+ }
+ if (currentContentType != ContentType.LIVE) return false
+ val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return false
+ return tryAlternateStreamInternal(channel)
+}
+
+internal fun PlayerViewModel.tryAlternateStreamInternal(channel: Channel): Boolean {
+ nextLiveVariant(channel)?.let { nextVariant ->
+ val updatedChannel = channel.withSelectedVariant(nextVariant.rawChannelId)?.sanitizedForPlayer() ?: return@let
+ val requestVersion = beginPlaybackSession()
+ triedAlternativeStreams.add(nextVariant.streamUrl)
+ currentContentId = updatedChannel.id
+ currentStreamUrl = updatedChannel.streamUrl
+ currentTitle = nextVariant.originalName.ifBlank { updatedChannel.name }
+ playbackTitleFlow.value = currentTitle
+ currentChannelFlow.value = updatedChannel
+ if (currentChannelIndex in channelList.indices) {
+ channelList = channelList.mapIndexed { index, existing ->
+ if (index == currentChannelIndex || existing.logicalGroupId == updatedChannel.logicalGroupId) {
+ updatedChannel
+ } else {
+ existing
+ }
+ }
+ currentChannelFlowList.value = channelList
+ }
+ if (currentChannelIndex >= 0) {
+ displayChannelNumberFlow.value = resolveChannelNumber(updatedChannel, currentChannelIndex)
+ }
+ refreshCurrentChannelRecording()
+ updateChannelDiagnostics(updatedChannel)
+ updateStreamClass("Variant")
+ viewModelScope.launch {
+ preferencesRepository.setPreferredLiveVariant(
+ providerId = updatedChannel.providerId,
+ logicalGroupId = updatedChannel.logicalGroupId,
+ rawChannelId = nextVariant.rawChannelId
+ )
+ val streamInfo = resolvePlaybackStreamInfo(
+ logicalUrl = nextVariant.streamUrl,
+ internalContentId = updatedChannel.id,
+ providerId = updatedChannel.providerId,
+ contentType = ContentType.LIVE
+ ) ?: return@launch
+ if (!isActivePlaybackSession(requestVersion, nextVariant.streamUrl)) return@launch
+ recordLivePlayback(updatedChannel)
+ requestEpg(
+ providerId = updatedChannel.providerId,
+ epgChannelId = updatedChannel.epgChannelId,
+ streamId = updatedChannel.streamId,
+ internalChannelId = updatedChannel.id
+ )
+ if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
+ playerEngine.play()
+ }
+ return true
+ }
+
+ val nextStream = selectNextAlternateUrl(
+ candidateUrls = channel.alternativeStreams,
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ ) ?: return false
+
+ val requestVersion = beginPlaybackSession()
+ triedAlternativeStreams.add(nextStream)
+ currentStreamUrl = nextStream
+ updateStreamClass("Alternate")
+ viewModelScope.launch {
+ val streamInfo = resolvePlaybackStreamInfo(nextStream, channel.id, channel.providerId, ContentType.LIVE)
+ ?: return@launch
+ if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
+ if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
+ playerEngine.play()
+ }
+ return true
+}
+
+private fun PlayerViewModel.nextLiveVariant(channel: Channel): LiveChannelVariant? {
+ return selectNextLiveVariant(
+ variants = channel.variants,
+ currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ )
+}
+
+internal fun PlayerViewModel.isCatchUpPlayback(): Boolean = isCatchUpPlayback.value
+
+private fun PlayerViewModel.nextCatchUpVariant(): String? {
+ return selectNextAlternateUrl(
+ candidateUrls = pendingCatchUpUrls,
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ )
+}
+
+internal fun PlayerViewModel.tryNextCatchUpVariantInternal(): Boolean {
+ val nextStream = nextCatchUpVariant() ?: return false
+ val requestVersion = beginPlaybackSession()
+ triedAlternativeStreams.add(nextStream)
+ currentStreamUrl = nextStream
+ updateStreamClass("Catch-up")
+ viewModelScope.launch {
+ val streamInfo = resolvePlaybackStreamInfo(nextStream, currentContentId, currentProviderId, ContentType.LIVE)
+ ?: return@launch
+ if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
+ if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
+ playerEngine.play()
+ }
+ return true
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
new file mode 100644
index 00000000..779fa93c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
@@ -0,0 +1,57 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.LiveChannelVariant
+
+internal fun buildPlayerRecoveryActions(
+ hasAlternateStream: Boolean,
+ hasLastChannel: Boolean,
+ shouldOfferGuide: Boolean
+): List<PlayerNoticeAction> {
+ val actions = mutableListOf(PlayerNoticeAction.RETRY)
+ if (hasAlternateStream) {
+ actions += PlayerNoticeAction.ALTERNATE_STREAM
+ }
+ if (hasLastChannel) {
+ actions += PlayerNoticeAction.LAST_CHANNEL
+ }
+ if (shouldOfferGuide) {
+ actions += PlayerNoticeAction.OPEN_GUIDE
+ }
+ return actions
+}
+
+internal fun selectNextAlternateUrl(
+ candidateUrls: List<String>,
+ currentStreamUrl: String,
+ triedAlternativeStreams: Set<String>,
+ failedStreamsThisSession: Map<String, Int>
+): String? {
+ return candidateUrls.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl &&
+ altUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[altUrl] ?: 0) == 0
+ } ?: candidateUrls.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
+ }
+}
+
+internal fun selectNextLiveVariant(
+ variants: List<LiveChannelVariant>,
+ currentVariantId: Long,
+ currentStreamUrl: String,
+ triedAlternativeStreams: Set<String>,
+ failedStreamsThisSession: Map<String, Int>
+): LiveChannelVariant? {
+ return variants.firstOrNull { variant ->
+ variant.rawChannelId != currentVariantId &&
+ variant.streamUrl.isNotBlank() &&
+ variant.streamUrl != currentStreamUrl &&
+ variant.streamUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[variant.streamUrl] ?: 0) == 0
+ } ?: variants.firstOrNull { variant ->
+ variant.rawChannelId != currentVariantId &&
+ variant.streamUrl.isNotBlank() &&
+ variant.streamUrl != currentStreamUrl &&
+ variant.streamUrl !in triedAlternativeStreams
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt
new file mode 100644
index 00000000..6362864a
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt
@@ -0,0 +1,68 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Episode
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+private const val AUTO_PLAY_MIN_WATCHED_MS = 5_000L
+private const val AUTO_PLAY_COUNTDOWN_SECONDS = 10
+
+internal suspend fun PlayerViewModel.persistPlaybackCompletion() {
+ val durationMs = playerEngine.duration.value
+ val completedHistory = buildPlaybackHistorySnapshot(
+ positionMs = durationMs.coerceAtLeast(playerEngine.currentPosition.value),
+ durationMs = durationMs
+ ) ?: return
+ logRepositoryFailure(
+ operation = "Mark playback watched",
+ result = markAsWatched(completedHistory)
+ )
+ watchNextManager.refreshWatchNext()
+ launcherRecommendationsManager.refreshRecommendations()
+}
+
+internal fun PlayerViewModel.handlePlaybackEnded() {
+ if (currentContentType == ContentType.LIVE) return
+ viewModelScope.launch {
+ persistPlaybackCompletion()
+ if (currentContentType == ContentType.SERIES_EPISODE) {
+ val position = playerEngine.currentPosition.value
+ val duration = playerEngine.duration.value
+ if (position > AUTO_PLAY_MIN_WATCHED_MS || duration > 0L) {
+ val next = nextEpisode.value ?: return@launch
+ if (autoPlayNextEpisodeEnabled) {
+ startAutoPlayCountdown(next)
+ }
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.startAutoPlayCountdown(episode: Episode) {
+ autoPlayCountdownJob?.cancel()
+ autoPlayCountdownJob = viewModelScope.launch {
+ for (remaining in AUTO_PLAY_COUNTDOWN_SECONDS downTo 1) {
+ _autoPlayCountdown.value = AutoPlayCountdownUiState(
+ episode = episode,
+ secondsRemaining = remaining
+ )
+ delay(1_000L)
+ }
+ _autoPlayCountdown.value = null
+ playEpisode(episode, showResumePrompt = false)
+ }
+}
+
+fun PlayerViewModel.cancelAutoPlay() {
+ autoPlayCountdownJob?.cancel()
+ autoPlayCountdownJob = null
+ _autoPlayCountdown.value = null
+}
+
+fun PlayerViewModel.playNextEpisodeNow() {
+ val episode = autoPlayCountdown.value?.episode ?: nextEpisode.value ?: return
+ cancelAutoPlay()
+ playEpisode(episode, showResumePrompt = false)
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt
new file mode 100644
index 00000000..92a90f4e
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt
@@ -0,0 +1,93 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import kotlinx.coroutines.launch
+
+internal suspend fun PlayerViewModel.startCatchUpPlayback(
+ urls: List<String>,
+ title: String,
+ recoveryAction: String,
+ requestVersionOverride: Long? = null
+) {
+ val requestVersion = requestVersionOverride ?: beginPlaybackSession()
+ val candidates = urls
+ .asSequence()
+ .map { it.trim() }
+ .filter { it.isNotBlank() }
+ .distinct()
+ .toList()
+ val primaryUrl = candidates.firstOrNull() ?: return
+
+ currentTitle = title
+ pendingCatchUpUrls = candidates
+ triedAlternativeStreams.clear()
+ triedAlternativeStreams.add(primaryUrl)
+ currentStreamUrl = primaryUrl
+ updateStreamClass("Catch-up")
+ appendRecoveryAction(recoveryAction)
+
+ val catchupStream = StreamInfo(
+ url = primaryUrl,
+ title = currentTitle,
+ streamType = StreamType.UNKNOWN
+ )
+ if (!preparePlayer(catchupStream, requestVersion)) return
+ playerEngine.play()
+}
+
+fun PlayerViewModel.playCatchUp(program: Program) {
+ viewModelScope.launch {
+ val requestVersion = prepareRequestVersion
+ val start = program.startTime / 1000L
+ val end = program.endTime / 1000L
+ val streamId = currentChannelFlow.value?.id ?: 0L
+ val providerId = currentProviderId
+
+ if (providerId == -1L || streamId == 0L) {
+ setLastFailureReason("Catch-up playback needs a valid live channel context.")
+ showPlayerNotice(
+ message = "Catch-up playback needs a valid live channel context.",
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ return@launch
+ }
+
+ val catchUpUrls = try {
+ providerRepository.buildCatchUpUrls(providerId, streamId, start, end)
+ } catch (e: CredentialDecryptionException) {
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
+ showPlayerNotice(
+ message = e.message ?: CredentialDecryptionException.MESSAGE,
+ recoveryType = PlayerRecoveryType.SOURCE,
+ actions = buildRecoveryActions(PlayerRecoveryType.SOURCE)
+ )
+ return@launch
+ }
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ if (catchUpUrls.isNotEmpty()) {
+ startCatchUpPlayback(
+ urls = catchUpUrls,
+ title = "${currentChannelFlow.value?.name ?: ""}: ${program.title}",
+ recoveryAction = "Started program replay"
+ )
+ } else {
+ val reason = resolveCatchUpFailureMessage(
+ currentChannelFlow.value,
+ archiveRequested = true,
+ programHasArchive = program.hasArchive
+ )
+ setLastFailureReason(reason)
+ showPlayerNotice(
+ message = reason,
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelNavigationSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelNavigationSupport.kt
new file mode 100644
index 00000000..cdae15ce
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelNavigationSupport.kt
@@ -0,0 +1,39 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Channel
+
+internal fun resolveLiveChannelIndex(
+ channelList: List<Channel>,
+ currentChannelIndex: Int,
+ currentContentId: Long,
+ currentStreamUrl: String
+): Int {
+ if (channelList.isEmpty()) return -1
+
+ val currentIndexMatchesChannel = currentChannelIndex in channelList.indices && run {
+ val currentChannel = channelList[currentChannelIndex]
+ currentChannel.id == currentContentId || currentChannel.streamUrl == currentStreamUrl
+ }
+ if (currentIndexMatchesChannel) {
+ return currentChannelIndex
+ }
+
+ val indexByContentId = when {
+ currentContentId > 0 -> channelList.indexOfFirst { it.id == currentContentId }
+ else -> -1
+ }
+ if (indexByContentId != -1) {
+ return indexByContentId
+ }
+
+ return channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
+}
+
+internal fun computeWrappedChannelIndex(
+ resolvedIndex: Int,
+ channelCount: Int,
+ offset: Int
+): Int {
+ if (resolvedIndex == -1 || channelCount <= 0) return -1
+ return ((resolvedIndex + offset) % channelCount + channelCount) % channelCount
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
new file mode 100644
index 00000000..5aed5ce3
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
@@ -0,0 +1,160 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
+import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.SeriesRepository
+
+internal data class SeriesEpisodeResolution(
+ val resolvedEpisode: Episode?,
+ val nextEpisode: Episode?,
+ val resolvedArtworkUrl: String?,
+ val resolvedTitle: String?,
+ val resolvedSeasonNumber: Int?,
+ val resolvedEpisodeNumber: Int?
+)
+
+internal data class PlayerPlaybackStreamResolution(
+ val streamInfo: StreamInfo?,
+ val credentialFailureMessage: String? = null
+)
+
+internal fun buildSeriesEpisodeResolution(
+ series: Series,
+ episodeId: Long,
+ seasonNumber: Int?,
+ episodeNumber: Int?,
+ currentContentType: ContentType,
+ currentArtworkUrl: String?
+): SeriesEpisodeResolution {
+ val resolvedEpisode = resolveEpisode(series, episodeId, seasonNumber, episodeNumber)
+ return SeriesEpisodeResolution(
+ resolvedEpisode = resolvedEpisode,
+ nextEpisode = resolvedEpisode?.let { findNextEpisode(series, it) },
+ resolvedArtworkUrl = if (resolvedEpisode != null && currentContentType == ContentType.SERIES_EPISODE) {
+ resolvedEpisode.coverUrl ?: currentArtworkUrl ?: series.posterUrl ?: series.backdropUrl
+ } else {
+ currentArtworkUrl
+ },
+ resolvedTitle = if (resolvedEpisode != null && currentContentType == ContentType.SERIES_EPISODE) {
+ buildEpisodePlaybackTitle(resolvedEpisode)
+ } else {
+ null
+ },
+ resolvedSeasonNumber = resolvedEpisode?.seasonNumber ?: seasonNumber,
+ resolvedEpisodeNumber = resolvedEpisode?.episodeNumber ?: episodeNumber
+ )
+}
+
+internal suspend fun resolvePlayerPlaybackStreamInfo(
+ logicalUrl: String,
+ internalContentId: Long,
+ providerId: Long,
+ contentType: ContentType,
+ currentTitle: String,
+ currentSeries: Series?,
+ currentEpisode: Episode?,
+ channelRepository: ChannelRepository,
+ movieRepository: MovieRepository,
+ seriesRepository: SeriesRepository,
+ xtreamStreamUrlResolver: XtreamStreamUrlResolver
+): PlayerPlaybackStreamResolution {
+ var fallbackStreamId: Long? = null
+ var fallbackContainerExtension: String? = null
+
+ if (providerId > 0L && internalContentId > 0L) {
+ when (contentType) {
+ ContentType.LIVE -> {
+ channelRepository.getChannel(internalContentId)?.let { channel ->
+ fallbackStreamId = channel.streamId.takeIf { it > 0L }
+ ?: channel.epgChannelId?.toLongOrNull()
+ channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ }
+ }
+
+ ContentType.MOVIE -> {
+ movieRepository.getMovie(internalContentId)?.let { movie ->
+ fallbackStreamId = movie.streamId.takeIf { it > 0L }
+ fallbackContainerExtension = movie.containerExtension
+ movieRepository.getStreamInfo(movie).getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ }
+ }
+
+ ContentType.SERIES,
+ ContentType.SERIES_EPISODE -> {
+ val episode = when {
+ currentEpisode?.id == internalContentId -> currentEpisode
+ else -> currentSeries
+ ?.seasons
+ .sanitizedForPlayer()
+ .asSequence()
+ .flatMap { it.episodes.asSequence() }
+ .firstOrNull { it.id == internalContentId }
+ }
+ episode?.let {
+ fallbackStreamId = it.episodeId.takeIf { episodeId -> episodeId > 0L } ?: it.id
+ fallbackContainerExtension = it.containerExtension
+ seriesRepository.getEpisodeStreamInfo(it).getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ xtreamStreamUrlResolver.resolveWithMetadata(
+ url = logicalUrl,
+ fallbackProviderId = providerId.takeIf { it > 0 },
+ fallbackStreamId = fallbackStreamId,
+ fallbackContentType = contentType,
+ fallbackContainerExtension = fallbackContainerExtension
+ )?.let { resolved ->
+ val ext = resolved.containerExtension ?: fallbackContainerExtension
+ return PlayerPlaybackStreamResolution(
+ streamInfo = StreamInfo(
+ url = resolved.url,
+ title = currentTitle,
+ headers = resolved.headers,
+ userAgent = resolved.userAgent,
+ streamType = StreamType.fromContainerExtension(ext),
+ containerExtension = ext,
+ expirationTime = resolved.expirationTime
+ )
+ )
+ }
+ } catch (e: CredentialDecryptionException) {
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ credentialFailureMessage = e.message ?: CredentialDecryptionException.MESSAGE
+ )
+ }
+
+ return PlayerPlaybackStreamResolution(
+ streamInfo = logicalUrl.takeIf { it.isNotBlank() }?.let {
+ StreamInfo(
+ url = it,
+ title = currentTitle,
+ streamType = StreamType.fromContainerExtension(fallbackContainerExtension),
+ containerExtension = fallbackContainerExtension
+ )
+ }
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerDiagnosticsSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerDiagnosticsSupport.kt
new file mode 100644
index 00000000..3dc0de10
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerDiagnosticsSupport.kt
@@ -0,0 +1,33 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Channel
+
+internal fun updateChannelDiagnosticsState(
+ currentState: PlayerDiagnosticsUiState,
+ channel: Channel
+): PlayerDiagnosticsUiState {
+ val archiveLabel = when {
+ channel.catchUpSupported && (channel.streamId > 0L || !channel.catchUpSource.isNullOrBlank()) ->
+ "Catch-up supported (${channel.catchUpDays} days)"
+ channel.catchUpSupported ->
+ "Provider advertises catch-up, but replay metadata is incomplete."
+ else -> "No archive support advertised"
+ }
+ val hints = buildList {
+ if (channel.errorCount > 0) {
+ add("This channel has failed ${channel.errorCount} time(s) recently.")
+ }
+ if (channel.alternativeStreams.isNotEmpty()) {
+ add("${channel.alternativeStreams.size} alternate stream path(s) available.")
+ }
+ if (channel.catchUpSupported && channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank()) {
+ add("Replay may fail because this provider did not expose a catch-up template.")
+ }
+ }
+ return currentState.copy(
+ alternativeStreamCount = channel.alternativeStreams.size,
+ channelErrorCount = channel.errorCount,
+ archiveSupportLabel = archiveLabel,
+ troubleshootingHints = hints.take(4)
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt
new file mode 100644
index 00000000..ba101d27
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt
@@ -0,0 +1,83 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+private const val EPG_REFRESH_INTERVAL_MS = 30_000L
+
+internal fun PlayerViewModel.fetchEpg(
+ providerId: Long,
+ internalChannelId: Long,
+ epgChannelId: String?,
+ streamId: Long = 0L
+) {
+ epgJob?.cancel()
+ if (providerId <= 0L || (internalChannelId <= 0L && epgChannelId == null && streamId <= 0L)) {
+ clearEpgState()
+ return
+ }
+
+ val requestKey = EpgRequestKey(
+ providerId = providerId,
+ internalChannelId = internalChannelId,
+ epgChannelId = epgChannelId,
+ streamId = streamId
+ )
+
+ epgJob = viewModelScope.launch {
+ while (true) {
+ val now = System.currentTimeMillis()
+ val start = now - (24 * 60 * 60 * 1000L)
+ val end = now + (6 * 60 * 60 * 1000L)
+ val programs = epgRepository.getResolvedProgramsForPlaybackChannel(
+ providerId = providerId,
+ internalChannelId = internalChannelId,
+ epgChannelId = epgChannelId,
+ streamId = streamId,
+ startTime = start,
+ endTime = end
+ )
+
+ if (activeEpgRequestKey != requestKey) return@launch
+
+ if (programs.isNotEmpty()) {
+ applyProgramTimeline(programs, now)
+ } else {
+ applyRemoteProgramFallback(providerId, epgChannelId, streamId, now)
+ if (activeEpgRequestKey != requestKey) return@launch
+ }
+
+ delay(EPG_REFRESH_INTERVAL_MS)
+ }
+ }
+}
+
+internal suspend fun PlayerViewModel.applyRemoteProgramFallback(
+ providerId: Long,
+ epgChannelId: String?,
+ streamId: Long,
+ now: Long
+) {
+ if (streamId <= 0L) {
+ clearEpgState()
+ return
+ }
+
+ val result = providerRepository.getProgramsForLiveStream(
+ providerId = providerId,
+ streamId = streamId,
+ epgChannelId = epgChannelId,
+ limit = 12
+ )
+ val programs = (result as? com.streamvault.domain.model.Result.Success)?.data
+ ?.sortedBy { it.startTime }
+ .orEmpty()
+
+ if (programs.isEmpty()) {
+ clearEpgState()
+ return
+ }
+
+ applyProgramTimeline(programs, now)
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpisodePlaybackSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpisodePlaybackSupport.kt
new file mode 100644
index 00000000..5988fbe0
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpisodePlaybackSupport.kt
@@ -0,0 +1,53 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Series
+
+internal fun resolveEpisode(
+ series: Series,
+ episodeId: Long,
+ seasonNumber: Int?,
+ episodeNumber: Int?
+): Episode? {
+ val episodes = series.seasons
+ .sanitizedForPlayer()
+ .sortedBy { it.seasonNumber }
+ .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }
+ return episodes.firstOrNull {
+ it.id == episodeId || it.matchesPlaybackEpisode(episodeId, seasonNumber, episodeNumber)
+ } ?: episodes.firstOrNull {
+ it.seasonNumber == seasonNumber && it.episodeNumber == episodeNumber
+ }
+}
+
+internal fun findNextEpisode(series: Series, episode: Episode): Episode? {
+ val orderedEpisodes = series.seasons
+ .sanitizedForPlayer()
+ .sortedBy { it.seasonNumber }
+ .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }
+ val currentIndex = orderedEpisodes.indexOfFirst {
+ it.id == episode.id ||
+ it.playbackEpisodeIdentity() == episode.playbackEpisodeIdentity() ||
+ (it.seasonNumber == episode.seasonNumber && it.episodeNumber == episode.episodeNumber)
+ }
+ return orderedEpisodes.getOrNull(currentIndex + 1)
+}
+
+internal fun Episode.playbackEpisodeIdentity(): Long =
+ episodeId.takeIf { it > 0L } ?: id
+
+internal fun Episode.matchesPlaybackEpisode(
+ requestedEpisodeId: Long,
+ requestedSeasonNumber: Int?,
+ requestedEpisodeNumber: Int?
+): Boolean {
+ val identity = playbackEpisodeIdentity()
+ return (requestedEpisodeId > 0L && identity == requestedEpisodeId) ||
+ (requestedSeasonNumber != null &&
+ requestedEpisodeNumber != null &&
+ seasonNumber == requestedSeasonNumber &&
+ episodeNumber == requestedEpisodeNumber)
+}
+
+internal fun buildEpisodePlaybackTitle(episode: Episode): String =
+ "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}"
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
new file mode 100644
index 00000000..c75374e2
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
@@ -0,0 +1,147 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.player.PlayerEngine
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+private const val LIFECYCLE_TOKEN_RENEWAL_LEAD_MS = 60_000L
+private const val LIFECYCLE_TOKEN_RENEWAL_CHECK_INTERVAL_MS = 10_000L
+
+internal fun PlayerViewModel.startProgressTracking() {
+ progressTrackingJob?.cancel()
+ if (currentContentType == ContentType.LIVE) return
+
+ progressTrackingJob = viewModelScope.launch {
+ while (true) {
+ delay(5000)
+ if (!isAppInForeground || !playerEngine.isPlaying.value) continue
+ persistPlaybackProgress()
+ }
+ }
+}
+
+internal suspend fun PlayerViewModel.persistPlaybackProgress() {
+ val pos = playerEngine.currentPosition.value
+ val dur = playerEngine.duration.value
+
+ if (pos > 0 && dur > 0) {
+ val history = buildPlaybackHistorySnapshot(pos, dur) ?: return
+ logRepositoryFailure(
+ operation = "Persist playback resume position",
+ result = playbackHistoryRepository.updateResumePosition(history)
+ )
+ watchNextManager.refreshWatchNext()
+ launcherRecommendationsManager.refreshRecommendations()
+ }
+}
+
+internal fun PlayerViewModel.startTokenRenewalMonitoring(expirationTime: Long?) {
+ tokenRenewalJob?.cancel()
+ tokenRenewalJob = null
+ val expiry = expirationTime?.takeIf { it > 0L } ?: return
+ val requestVersion = prepareRequestVersion
+ tokenRenewalJob = viewModelScope.launch {
+ while (true) {
+ delay(LIFECYCLE_TOKEN_RENEWAL_CHECK_INTERVAL_MS)
+ if (!playerEngine.isPlaying.value) continue
+ val remaining = expiry - System.currentTimeMillis()
+ if (remaining > LIFECYCLE_TOKEN_RENEWAL_LEAD_MS) continue
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ val refreshed = resolvePlaybackStreamInfo(
+ logicalUrl = currentStreamUrl,
+ internalContentId = currentContentId,
+ providerId = currentProviderId,
+ contentType = currentContentType
+ ) ?: return@launch
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ currentResolvedPlaybackUrl = refreshed.url
+ playerEngine.renewStreamUrl(refreshed)
+ startTokenRenewalMonitoring(refreshed.expirationTime)
+ return@launch
+ }
+ }
+}
+
+fun PlayerViewModel.onAppBackgrounded() {
+ if (!isAppInForeground) return
+ isAppInForeground = false
+ shouldResumeAfterForeground = playerEngine.isPlaying.value
+ if (shouldResumeAfterForeground) {
+ playerEngine.pause()
+ }
+ if (currentContentType != ContentType.LIVE) {
+ viewModelScope.launch {
+ persistPlaybackProgress()
+ playbackHistoryRepository.flushPendingProgress()
+ }
+ }
+}
+
+fun PlayerViewModel.onAppForegrounded() {
+ if (isAppInForeground) return
+ isAppInForeground = true
+ if (shouldResumeAfterForeground && !resumePrompt.value.show) {
+ playerEngine.play()
+ }
+ shouldResumeAfterForeground = false
+}
+
+fun PlayerViewModel.onPlayerScreenDisposed() {
+ if (currentContentType != ContentType.LIVE) {
+ viewModelScope.launch {
+ persistPlaybackProgress()
+ playbackHistoryRepository.flushPendingProgress()
+ }
+ }
+ playerEngine.stopLiveTimeshift()
+ clearPlaybackTimers()
+}
+
+internal fun PlayerViewModel.clearPlaybackTimers() {
+ stopPlaybackTimerJob?.cancel()
+ idleStandbyTimerJob?.cancel()
+ stopPlaybackTimerJob = null
+ idleStandbyTimerJob = null
+ stopPlaybackTimerEndsAtMs = 0L
+ idleStandbyTimerEndsAtMs = 0L
+ playbackTimerDefaultsApplied = false
+ sleepTimerExitEmitted = false
+ _sleepTimerUiState.value = SleepTimerUiState()
+}
+
+fun PlayerViewModel.handOffPlaybackToMultiView() {
+ if (currentContentType != ContentType.LIVE) {
+ viewModelScope.launch { persistPlaybackProgress() }
+ }
+ playerEngine.stopLiveTimeshift()
+ livePreviewHandoffManager.clear(playerEngine)
+ playerEngine.release()
+}
+
+internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine) {
+ onPlayerScreenDisposed()
+ channelInfoHideJob?.cancel()
+ liveOverlayHideJob?.cancel()
+ diagnosticsHideJob?.cancel()
+ numericInputCommitJob?.cancel()
+ numericInputFeedbackJob?.cancel()
+ playerNoticeHideJob?.cancel()
+ epgJob?.cancel()
+ playlistJob?.cancel()
+ controlsHideJob?.cancel()
+ zapOverlayJob?.cancel()
+ zapBufferWatchdogJob?.cancel()
+ progressTrackingJob?.cancel()
+ tokenRenewalJob?.cancel()
+ aspectRatioJob?.cancel()
+ recentChannelsJob?.cancel()
+ lastVisitedCategoryJob?.cancel()
+ seekThumbnailProvider.clearCache()
+ livePreviewHandoffManager.clear(playerEngine)
+ playerEngine.release()
+ if (mainPlayerEngine !== playerEngine) {
+ mainPlayerEngine.release()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt
new file mode 100644
index 00000000..64cdd242
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt
@@ -0,0 +1,110 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+fun PlayerViewModel.dismissPlayerNotice() {
+ playerNoticeHideJob?.cancel()
+ _playerNotice.value = null
+}
+
+internal fun PlayerViewModel.dismissRecoveredNoticeIfPresent() {
+ val notice = _playerNotice.value ?: return
+ if (notice.isRetryNotice || notice.recoveryType != PlayerRecoveryType.UNKNOWN) {
+ dismissPlayerNotice()
+ }
+}
+
+fun PlayerViewModel.runPlayerNoticeAction(action: PlayerNoticeAction) {
+ when (action) {
+ PlayerNoticeAction.RETRY -> {
+ appendRecoveryAction("Manual retry")
+ retryStream(currentStreamUrl, currentChannelFlow.value?.epgChannelId)
+ }
+ PlayerNoticeAction.LAST_CHANNEL -> {
+ appendRecoveryAction("Returned to last channel")
+ zapToLastChannel()
+ }
+ PlayerNoticeAction.ALTERNATE_STREAM -> {
+ appendRecoveryAction("Manual alternate stream")
+ tryAlternateStream()
+ }
+ PlayerNoticeAction.OPEN_GUIDE -> {
+ appendRecoveryAction("Opened guide from recovery")
+ openEpgOverlay()
+ }
+ }
+ dismissPlayerNotice()
+}
+
+internal fun PlayerViewModel.showPlayerNotice(
+ message: String,
+ recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
+ actions: List<PlayerNoticeAction> = emptyList(),
+ durationMs: Long = playerNoticeTimeoutMs,
+ isRetryNotice: Boolean = false
+) {
+ playerNoticeHideJob?.cancel()
+ _playerNotice.value = PlayerNoticeState(
+ message = message,
+ recoveryType = recoveryType,
+ actions = actions.distinct(),
+ isRetryNotice = isRetryNotice
+ )
+ playerNoticeHideJob = viewModelScope.launch {
+ delay(durationMs)
+ if (_playerNotice.value?.message == message) {
+ _playerNotice.value = null
+ }
+ }
+}
+
+internal fun PlayerViewModel.showRetryNotice(status: com.streamvault.player.PlayerRetryStatus) {
+ val formatLabel = resolvePlaybackFormatLabel(
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ currentStreamUrl = currentStreamUrl
+ )
+ val message = "Retrying $formatLabel ${status.attempt}/${status.maxAttempts} in ${status.delayMs / 1000}s..."
+ showPlayerNotice(
+ message = message,
+ recoveryType = PlayerRecoveryType.NETWORK,
+ durationMs = maxOf(playerNoticeTimeoutMs, status.delayMs + 1500L),
+ isRetryNotice = true
+ )
+}
+
+fun PlayerViewModel.restartCurrentProgram() {
+ val program = currentProgram.value ?: return
+ if (program.hasArchive || (currentChannelFlow.value?.catchUpSupported == true)) {
+ playCatchUp(program)
+ }
+}
+
+fun PlayerViewModel.retryStream(streamUrl: String, epgChannelId: String?) {
+ if (isCatchUpPlayback.value) {
+ val requestVersion = beginPlaybackSession()
+ viewModelScope.launch {
+ val streamInfo = resolvePlaybackStreamInfo(streamUrl, currentContentId, currentProviderId, currentContentType)
+ ?: return@launch
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
+ playerEngine.play()
+ }
+ return
+ }
+ val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L
+ prepare(
+ streamUrl = streamUrl,
+ epgChannelId = epgChannelId,
+ internalChannelId = currentId,
+ categoryId = currentCategoryId,
+ providerId = currentProviderId,
+ isVirtual = isVirtualCategory,
+ combinedProfileId = currentCombinedProfileId,
+ combinedSourceFilterProviderId = currentCombinedSourceFilterProviderId,
+ contentType = currentContentType.name,
+ title = currentTitle
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt
new file mode 100644
index 00000000..4befaf2e
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt
@@ -0,0 +1,109 @@
+package com.streamvault.app.ui.screens.player
+
+import android.os.SystemClock
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Episode
+import com.streamvault.player.timeshift.LiveTimeshiftStatus
+import kotlinx.coroutines.launch
+
+private const val PLAYBACK_CONTROL_MUTE_TOGGLE_DEBOUNCE_MS = 250L
+
+fun PlayerViewModel.seekForward() {
+ notifyUserActivity()
+ playerEngine.seekForward()
+}
+
+fun PlayerViewModel.seekBackward() {
+ notifyUserActivity()
+ playerEngine.seekBackward()
+}
+
+fun PlayerViewModel.seekToLiveEdge() {
+ notifyUserActivity()
+ playerEngine.seekToLiveEdge()
+}
+
+fun PlayerViewModel.playEpisode(episode: Episode, showResumePrompt: Boolean = true) {
+ prepare(
+ streamUrl = episode.streamUrl,
+ epgChannelId = null,
+ internalChannelId = episode.id,
+ categoryId = -1,
+ providerId = episode.providerId,
+ isVirtual = false,
+ contentType = ContentType.SERIES_EPISODE.name,
+ title = buildEpisodePlaybackTitle(episode),
+ artworkUrl = episode.coverUrl ?: currentSeries.value?.posterUrl ?: currentSeries.value?.backdropUrl,
+ seriesId = currentSeriesId ?: episode.seriesId.takeIf { it > 0L },
+ seasonNumber = episode.seasonNumber,
+ episodeNumber = episode.episodeNumber,
+ showResumePrompt = showResumePrompt
+ )
+}
+
+fun PlayerViewModel.toggleMute() {
+ val now = SystemClock.elapsedRealtime()
+ if (now - lastMuteToggleAtMs < PLAYBACK_CONTROL_MUTE_TOGGLE_DEBOUNCE_MS) return
+ lastMuteToggleAtMs = now
+ playerEngine.toggleMute()
+ val muted = playerEngine.isMuted.value
+ mutePersistJob?.cancel()
+ mutePersistJob = viewModelScope.launch {
+ preferencesRepository.setPlayerMuted(muted)
+ }
+}
+
+fun PlayerViewModel.toggleControls() {
+ closeChannelInfoOverlay()
+ showControlsFlow.value = !showControlsFlow.value
+ if (!showControlsFlow.value) {
+ clearSeekPreview()
+ }
+}
+
+fun PlayerViewModel.toggleAspectRatio() {
+ val nextRatio = when (_aspectRatio.value) {
+ AspectRatio.FIT -> AspectRatio.FILL
+ AspectRatio.FILL -> AspectRatio.ZOOM
+ AspectRatio.ZOOM -> AspectRatio.FIT
+ }
+ _aspectRatio.value = nextRatio
+
+ if (currentContentId != -1L) {
+ viewModelScope.launch {
+ preferencesRepository.setAspectRatioForChannel(currentContentId, nextRatio.name)
+ }
+ }
+}
+
+fun PlayerViewModel.dismissResumePrompt(resume: Boolean) {
+ val prompt = _resumePrompt.value
+ _resumePrompt.value = ResumePromptState()
+ if (resume && prompt.positionMs > 0) {
+ playerEngine.seekTo(prompt.positionMs)
+ }
+ playerEngine.play()
+}
+
+fun PlayerViewModel.play() {
+ notifyUserActivity()
+ if (
+ currentContentType == ContentType.LIVE &&
+ timeshiftConfig.enabled &&
+ timeshiftUiState.value.engineState.status == LiveTimeshiftStatus.PAUSED_BEHIND_LIVE
+ ) {
+ playerEngine.resumeTimeshift()
+ } else {
+ playerEngine.play()
+ }
+}
+
+fun PlayerViewModel.pause() {
+ notifyUserActivity()
+ if (currentContentType == ContentType.LIVE && timeshiftConfig.enabled) {
+ playerEngine.pauseTimeshift()
+ } else {
+ playerEngine.pause()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackHistorySupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackHistorySupport.kt
new file mode 100644
index 00000000..6f9bdf02
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackHistorySupport.kt
@@ -0,0 +1,39 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.PlaybackHistory
+
+internal fun buildPlaybackHistorySnapshot(
+ positionMs: Long,
+ durationMs: Long,
+ currentContentId: Long,
+ currentProviderId: Long,
+ currentContentType: ContentType,
+ currentTitle: String,
+ currentArtworkUrl: String?,
+ currentStreamUrl: String,
+ currentSeriesId: Long?,
+ currentEpisode: Episode?,
+ currentSeasonNumber: Int?,
+ currentEpisodeNumber: Int?,
+ lastWatchedAt: Long = System.currentTimeMillis()
+): PlaybackHistory? {
+ if (positionMs < 0 || durationMs <= 0 || currentContentId == -1L || currentProviderId == -1L) {
+ return null
+ }
+ return PlaybackHistory(
+ contentId = currentContentId,
+ contentType = currentContentType,
+ providerId = currentProviderId,
+ title = currentTitle,
+ posterUrl = currentArtworkUrl,
+ streamUrl = currentStreamUrl,
+ resumePositionMs = positionMs,
+ totalDurationMs = durationMs,
+ lastWatchedAt = lastWatchedAt,
+ seriesId = currentSeriesId,
+ seasonNumber = currentEpisode?.seasonNumber ?: currentSeasonNumber,
+ episodeNumber = currentEpisode?.episodeNumber ?: currentEpisodeNumber
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackMessageSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackMessageSupport.kt
new file mode 100644
index 00000000..87ff2b8a
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackMessageSupport.kt
@@ -0,0 +1,45 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Channel
+import java.util.Locale
+
+internal fun isAuthExpiryPlaybackError(message: String?): Boolean {
+ val normalized = message.orEmpty().lowercase(Locale.ROOT)
+ return "401" in normalized ||
+ "403" in normalized ||
+ "unauthorized" in normalized ||
+ "forbidden" in normalized ||
+ "authentication" in normalized ||
+ "token" in normalized ||
+ "expired" in normalized
+}
+
+internal fun resolveCatchUpFailureMessage(
+ channel: Channel?,
+ archiveRequested: Boolean,
+ programHasArchive: Boolean
+): String {
+ if (!archiveRequested || channel == null) {
+ return "Catch-up playback needs a valid live channel context."
+ }
+ return when {
+ !channel.catchUpSupported && !programHasArchive ->
+ "This channel does not advertise archive support on the current provider."
+ channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank() ->
+ "The provider advertises catch-up, but did not expose replay metadata for this channel."
+ else ->
+ "Replay is unavailable for the selected program right now."
+ }
+}
+
+internal fun resolvePlaybackFormatLabel(
+ currentResolvedPlaybackUrl: String,
+ currentStreamUrl: String
+): String {
+ val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }.lowercase(Locale.ROOT)
+ return when {
+ url.contains("ext=m3u8") || url.endsWith(".m3u8") -> "HLS"
+ url.contains("ext=ts") || url.endsWith(".ts") -> "TS"
+ else -> "stream"
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt
new file mode 100644
index 00000000..33c92290
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt
@@ -0,0 +1,256 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LiveChannelObservedQuality
+import com.streamvault.domain.model.VideoFormat
+import com.streamvault.player.AUDIO_VIDEO_OFFSET_MAX_MS
+import com.streamvault.player.AUDIO_VIDEO_OFFSET_MIN_MS
+import com.streamvault.player.PlaybackState
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+fun PlayerViewModel.selectAudioTrack(trackId: String) {
+ playerEngine.selectAudioTrack(trackId)
+}
+
+fun PlayerViewModel.selectSubtitleTrack(trackId: String?) {
+ playerEngine.selectSubtitleTrack(trackId)
+}
+
+fun PlayerViewModel.selectVideoQuality(trackId: String) {
+ playerEngine.selectVideoTrack(trackId)
+}
+
+fun PlayerViewModel.selectLiveVariant(rawChannelId: Long) {
+ val currentChannel = currentChannelFlow.value?.sanitizedForPlayer() ?: return
+ val updatedChannel = currentChannel.withSelectedVariant(rawChannelId)?.sanitizedForPlayer() ?: return
+ if (updatedChannel.selectedVariantId == currentChannel.selectedVariantId) return
+
+ val requestVersion = beginPlaybackSession()
+ triedAlternativeStreams.clear()
+ currentContentId = updatedChannel.id
+ currentStreamUrl = updatedChannel.streamUrl
+ currentTitle = updatedChannel.currentVariant?.originalName ?: updatedChannel.name
+ playbackTitleFlow.value = currentTitle
+ currentChannelFlow.value = updatedChannel
+ if (currentChannelIndex in channelList.indices) {
+ channelList = channelList.mapIndexed { index, existing ->
+ if (index == currentChannelIndex || existing.logicalGroupId == updatedChannel.logicalGroupId) {
+ updatedChannel
+ } else {
+ existing
+ }
+ }
+ currentChannelFlowList.value = channelList
+ }
+ if (currentChannelIndex >= 0) {
+ displayChannelNumberFlow.value = resolveChannelNumber(updatedChannel, currentChannelIndex)
+ }
+ refreshCurrentChannelRecording()
+ updateChannelDiagnostics(updatedChannel)
+ updateStreamClass("Variant")
+ viewModelScope.launch {
+ preferencesRepository.setPreferredLiveVariant(
+ providerId = updatedChannel.providerId,
+ logicalGroupId = updatedChannel.logicalGroupId,
+ rawChannelId = rawChannelId
+ )
+ val streamInfo = resolvePlaybackStreamInfo(
+ logicalUrl = updatedChannel.streamUrl,
+ internalContentId = updatedChannel.id,
+ providerId = updatedChannel.providerId,
+ contentType = ContentType.LIVE
+ ) ?: return@launch
+ if (!isActivePlaybackSession(requestVersion, updatedChannel.streamUrl)) return@launch
+ if (currentContentType == ContentType.LIVE) {
+ recordLivePlayback(updatedChannel)
+ requestEpg(
+ providerId = updatedChannel.providerId,
+ epgChannelId = updatedChannel.epgChannelId,
+ streamId = updatedChannel.streamId,
+ internalChannelId = updatedChannel.id
+ )
+ }
+ if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
+ playerEngine.play()
+ }
+}
+
+fun PlayerViewModel.recordLiveVariantObservation(playbackState: PlaybackState, videoFormat: VideoFormat) {
+ if (currentContentType != ContentType.LIVE || playbackState != PlaybackState.READY || videoFormat.isEmpty) {
+ return
+ }
+ val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return
+ val rawChannelId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id
+ if (rawChannelId <= 0L) return
+ val signature = buildString {
+ append(rawChannelId)
+ append('|')
+ append(videoFormat.width)
+ append('|')
+ append(videoFormat.height)
+ append('|')
+ append(videoFormat.bitrate)
+ append('|')
+ append(videoFormat.frameRate)
+ }
+ if (signature == lastRecordedVariantObservationSignature) return
+ lastRecordedVariantObservationSignature = signature
+
+ viewModelScope.launch {
+ val existing = preferencesRepository.liveVariantObservations.first()[rawChannelId]
+ preferencesRepository.recordLiveVariantObservation(
+ rawChannelId = rawChannelId,
+ observedQuality = LiveChannelObservedQuality(
+ lastObservedWidth = videoFormat.width,
+ lastObservedHeight = videoFormat.height,
+ lastObservedBitrate = videoFormat.bitrate,
+ lastObservedFrameRate = videoFormat.frameRate,
+ successCount = (existing?.successCount ?: 0) + 1,
+ lastSuccessfulAt = System.currentTimeMillis()
+ )
+ )
+ }
+}
+
+fun PlayerViewModel.setPlaybackSpeed(speed: Float) {
+ val normalizedSpeed = speed.coerceIn(0.5f, 2f)
+ playerEngine.setPlaybackSpeed(normalizedSpeed)
+ viewModelScope.launch {
+ preferencesRepository.setPlayerPlaybackSpeed(normalizedSpeed)
+ }
+}
+
+fun PlayerViewModel.previewAudioVideoOffset(offsetMs: Int) {
+ audioVideoOffsetPreviewMs.value = offsetMs.coerceIn(AUDIO_VIDEO_OFFSET_MIN_MS, AUDIO_VIDEO_OFFSET_MAX_MS)
+}
+
+fun PlayerViewModel.adjustAudioVideoOffset(deltaMs: Int) {
+ val current = audioVideoOffsetPreviewMs.value ?: _audioVideoOffsetUiState.value.effectiveOffsetMs
+ previewAudioVideoOffset(current + deltaMs)
+}
+
+fun PlayerViewModel.resetAudioVideoOffsetPreview() {
+ previewAudioVideoOffset(0)
+}
+
+fun PlayerViewModel.dismissAudioVideoOffsetPreview() {
+ audioVideoOffsetPreviewMs.value = null
+}
+
+fun PlayerViewModel.saveAudioVideoOffsetForChannel() {
+ val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
+ val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
+ viewModelScope.launch {
+ preferencesRepository.setAudioVideoOffsetForChannel(channelId, offsetMs)
+ audioVideoOffsetPreviewMs.value = null
+ }
+}
+
+fun PlayerViewModel.saveAudioVideoOffsetAsGlobal() {
+ val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
+ val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L }
+ viewModelScope.launch {
+ preferencesRepository.setPlayerAudioVideoOffsetMs(offsetMs)
+ if (channelId != null) {
+ preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
+ }
+ audioVideoOffsetPreviewMs.value = null
+ }
+}
+
+fun PlayerViewModel.useGlobalAudioVideoOffset() {
+ val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
+ viewModelScope.launch {
+ preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
+ audioVideoOffsetPreviewMs.value = null
+ }
+}
+
+fun PlayerViewModel.seekTo(positionMs: Long) {
+ notifyUserActivity()
+ playerEngine.seekTo(positionMs)
+ clearSeekPreview()
+}
+
+fun PlayerViewModel.setScrubbingMode(enabled: Boolean) {
+ playerEngine.setScrubbingMode(enabled)
+ if (!enabled) {
+ clearSeekPreview()
+ }
+}
+
+fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {
+ if (positionMs == null || currentContentType == ContentType.LIVE) {
+ clearSeekPreview()
+ return
+ }
+
+ val previewPositionMs = positionMs.coerceAtLeast(0L)
+ val previewUrl = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+ val canExtractFrame = previewUrl.isNotBlank() && seekThumbnailProvider.supportsFrameExtraction(previewUrl)
+
+ _seekPreview.update { current ->
+ current.copy(
+ visible = true,
+ positionMs = previewPositionMs,
+ artworkUrl = currentArtworkUrl,
+ title = currentTitle,
+ isLoading = canExtractFrame,
+ frameBitmap = if (canExtractFrame) current.frameBitmap else null
+ )
+ }
+
+ seekPreviewJob?.cancel()
+ if (!canExtractFrame) {
+ return
+ }
+
+ val requestVersion = ++seekPreviewRequestVersion
+ seekPreviewJob = viewModelScope.launch {
+ delay(120)
+ val bitmap = seekThumbnailProvider.loadFrame(previewUrl, previewPositionMs)
+ if (requestVersion != seekPreviewRequestVersion) return@launch
+
+ _seekPreview.update { current ->
+ if (!current.visible || current.positionMs != previewPositionMs) {
+ current
+ } else {
+ current.copy(
+ frameBitmap = bitmap,
+ artworkUrl = currentArtworkUrl,
+ title = currentTitle,
+ isLoading = false
+ )
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.startThumbnailPreload() {
+ thumbnailPreloadJob?.cancel()
+ val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+ if (url.isBlank() || !seekThumbnailProvider.supportsFrameExtraction(url)) return
+ val durationMs = playerEngine.duration.value
+ if (durationMs <= 0L) return
+ thumbnailPreloadJob = viewModelScope.launch(Dispatchers.Default) {
+ val bucketMs = 10_000L
+ var pos = 0L
+ while (pos <= durationMs) {
+ ensureActive()
+ seekThumbnailProvider.loadFrame(url, pos)
+ pos += bucketMs
+ }
+ }
+}
+
+internal fun PlayerViewModel.clearSeekPreview() {
+ seekPreviewJob?.cancel()
+ seekPreviewRequestVersion++
+ _seekPreview.value = SeekPreviewState()
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackProbeSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackProbeSupport.kt
new file mode 100644
index 00000000..9a3911b3
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackProbeSupport.kt
@@ -0,0 +1,30 @@
+package com.streamvault.app.ui.screens.player
+
+internal data class PlaybackProbeFailure(
+ val message: String,
+ val recoveryType: PlayerRecoveryType
+)
+
+internal fun resolvePlaybackProbeFailure(responseCode: Int): PlaybackProbeFailure? = when (responseCode) {
+ 401, 403 -> PlaybackProbeFailure(
+ message = "This provider stream was rejected ($responseCode Unauthorized/Forbidden).",
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+
+ 456 -> PlaybackProbeFailure(
+ message = "This provider rejected playback for this channel (HTTP 456). The MAC or subscription may not have access to this stream.",
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+
+ 404 -> PlaybackProbeFailure(
+ message = "This provider stream is unavailable right now (404).",
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+
+ in 500..599 -> PlaybackProbeFailure(
+ message = "The provider returned a server error for this stream ($responseCode).",
+ recoveryType = PlayerRecoveryType.NETWORK
+ )
+
+ else -> null
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackRecoverySupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackRecoverySupport.kt
new file mode 100644
index 00000000..71ff9281
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackRecoverySupport.kt
@@ -0,0 +1,46 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.player.PlayerError
+
+internal fun classifyPlaybackError(error: PlayerError): PlayerRecoveryType = when (error) {
+ is PlayerError.NetworkError -> {
+ if (error.message.contains("timeout", ignoreCase = true)) {
+ PlayerRecoveryType.BUFFER_TIMEOUT
+ } else if (
+ error.message.contains("HTTP 456", ignoreCase = true) ||
+ error.message.contains("access denied", ignoreCase = true)
+ ) {
+ PlayerRecoveryType.SOURCE
+ } else {
+ PlayerRecoveryType.NETWORK
+ }
+ }
+
+ is PlayerError.SourceError -> PlayerRecoveryType.SOURCE
+ is PlayerError.DecoderError -> PlayerRecoveryType.DECODER
+ is PlayerError.DrmError -> PlayerRecoveryType.DRM
+ is PlayerError.UnknownError -> {
+ if (error.message.contains("timeout", ignoreCase = true)) {
+ PlayerRecoveryType.BUFFER_TIMEOUT
+ } else {
+ PlayerRecoveryType.UNKNOWN
+ }
+ }
+}
+
+internal fun resolvePlaybackErrorMessage(error: PlayerError): String = when (classifyPlaybackError(error)) {
+ PlayerRecoveryType.NETWORK -> "This stream is not responding right now. You can retry or try another source."
+ PlayerRecoveryType.SOURCE -> when {
+ error.message.contains("HTTP 456", ignoreCase = true) ||
+ error.message.contains("access denied", ignoreCase = true) ->
+ "This provider rejected playback for this channel. The MAC or subscription may not have access to this stream."
+
+ else -> "We couldn't start this stream on the available paths."
+ }
+
+ PlayerRecoveryType.DECODER -> "This stream could not play in the current decoder mode."
+ PlayerRecoveryType.DRM -> "Playback requires valid DRM credentials or a supported device security level."
+ PlayerRecoveryType.BUFFER_TIMEOUT -> "Playback stayed stuck buffering for too long on this stream."
+ PlayerRecoveryType.CATCH_UP -> "Replay is unavailable for the selected program."
+ PlayerRecoveryType.UNKNOWN -> error.message.ifBlank { "Playback failed for an unknown reason." }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt
new file mode 100644
index 00000000..e257062e
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackUrlSupport.kt
@@ -0,0 +1,32 @@
+package com.streamvault.app.ui.screens.player
+
+internal fun String?.safeTrimmedOrNull(): String? {
+ val value = this ?: return null
+ return value.trim().takeIf { it.isNotEmpty() }
+}
+
+internal fun resolvePlaybackIdentityUrl(
+ currentResolvedPlaybackUrl: String,
+ currentStreamUrl: String
+): String = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+
+internal fun resolvePlaybackProbeCacheKey(
+ currentStreamUrl: String,
+ url: String
+): String = currentStreamUrl.takeIf { it.isNotBlank() } ?: url
+
+internal fun matchesActivePlaybackSession(
+ requestVersion: Long,
+ activeRequestVersion: Long,
+ expectedLogicalUrl: String? = null,
+ currentResolvedPlaybackUrl: String,
+ currentStreamUrl: String
+): Boolean {
+ if (requestVersion != activeRequestVersion) return false
+ val expectedUrl = expectedLogicalUrl?.takeIf { it.isNotBlank() } ?: return true
+ val activeUrl = resolvePlaybackIdentityUrl(
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ currentStreamUrl = currentStreamUrl
+ )
+ return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl == expectedUrl
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt
new file mode 100644
index 00000000..2f3e373a
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt
@@ -0,0 +1,358 @@
+@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
+
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.app.ui.model.orderedByRequestedRawIds
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ChannelNumberingMode
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.model.VirtualCategoryIds
+import com.streamvault.domain.repository.ChannelRepository
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+
+internal fun PlayerViewModel.observeCombinedLivePlaylist(
+ profileId: Long,
+ categoryId: Long
+): Flow<List<Channel>> = when {
+ categoryId == ChannelRepository.ALL_CHANNELS_ID -> {
+ combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }
+ val flows = combinedCategories.map { combinedM3uRepository.getCombinedChannels(profileId, it) }
+ if (flows.isEmpty()) {
+ flowOf(emptyList())
+ } else {
+ combine(flows) { arrays ->
+ arrays.toList().flatMap { it }
+ }.map(::applyCombinedSourceProviderFilter)
+ }
+ }
+ }
+
+ categoryId == VirtualCategoryIds.RECENT -> {
+ combinedProviderIdsFlow(profileId)
+ .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 24) }
+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
+ }
+
+ categoryId == VirtualCategoryIds.FAVORITES -> {
+ combinedProviderIdsFlow(profileId)
+ .flatMapLatest { providerIds -> observeLiveFavorites(effectiveCombinedProviderIds(providerIds)) }
+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
+ }
+
+ categoryId < 0L -> {
+ favoriteRepository.getFavoritesByGroup(-categoryId)
+ .map { favorites ->
+ favorites
+ .sortedBy { it.position }
+ .let { groupFavorites ->
+ currentCombinedSourceFilterProviderId?.let { selectedProviderId ->
+ groupFavorites.filter { it.providerId == selectedProviderId }
+ } ?: groupFavorites
+ }
+ .map { it.contentId }
+ }
+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
+ }
+
+ else -> {
+ combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }
+ val combinedCategory = combinedCategoriesById[categoryId]
+ if (combinedCategory == null) {
+ flowOf(emptyList())
+ } else {
+ combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)
+ .map(::applyCombinedSourceProviderFilter)
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.observeRecentChannels() {
+ recentChannelsJob?.cancel()
+ if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {
+ recentChannelsFlow.value = emptyList()
+ return
+ }
+
+ recentChannelsJob = viewModelScope.launch {
+ val recentFlow = currentCombinedProfileId?.let { profileId ->
+ combinedProviderIdsFlow(profileId)
+ .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 12) }
+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
+ } ?: playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)
+ .map { history ->
+ history.asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .toList()
+ }
+ .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids) }
+
+ combine(recentFlow, preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->
+ numberingMode to channels
+ }.collect { (numberingMode, channels) ->
+ channelNumberingMode = numberingMode
+ val currentListNumbers = channelList.withIndex().associate { (index, channel) ->
+ channel.id to resolveChannelNumber(channel, index)
+ }
+ recentChannelsFlow.value = channels
+ .filterNot { it.id == currentContentId }
+ .map { channel ->
+ currentListNumbers[channel.id]?.let { number ->
+ channel.copy(number = number)
+ } ?: channel
+ }
+ }
+ }
+}
+
+internal fun PlayerViewModel.observeLastVisitedCategory() {
+ lastVisitedCategoryJob?.cancel()
+ if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {
+ _lastVisitedCategory.value = null
+ return
+ }
+
+ lastVisitedCategoryJob = viewModelScope.launch {
+ val categoriesFlow = currentCombinedProfileId?.let { profileId ->
+ combinedProviderIdsFlow(profileId).flatMapLatest { providerIds ->
+ combine(
+ combinedM3uRepository.getCombinedCategories(profileId),
+ getCustomCategories(providerIds, ContentType.LIVE)
+ ) { combinedCategories, customCategories ->
+ combinedCategoriesById = combinedCategories.associateBy { it.category.id }
+ buildCombinedLiveCategories(combinedCategories, customCategories) to null
+ }
+ }
+ } ?: combine(
+ channelRepository.getCategories(currentProviderId),
+ getCustomCategories(currentProviderId, ContentType.LIVE),
+ preferencesRepository.getLastLiveCategoryId(currentProviderId)
+ ) { providerCategories, customCategories, lastVisitedCategoryId ->
+ val allCategories = customCategories + providerCategories
+ val lastVisited = if (lastVisitedCategoryId == null || lastVisitedCategoryId == VirtualCategoryIds.RECENT) {
+ null
+ } else {
+ allCategories.firstOrNull { it.id == lastVisitedCategoryId }
+ }
+ allCategories to lastVisited
+ }
+
+ categoriesFlow.collect { (allCategories, lastVisited) ->
+ availableCategoriesFlow.value = allCategories
+ _lastVisitedCategory.value = lastVisited
+ }
+ }
+}
+
+fun PlayerViewModel.openLastVisitedCategory() {
+ val category = _lastVisitedCategory.value ?: return
+ if (currentContentType != ContentType.LIVE) return
+
+ currentCategoryId = category.id
+ activeCategoryIdFlow.value = category.id
+ isVirtualCategory = category.isVirtual
+ loadPlaylist(
+ categoryId = category.id,
+ providerId = currentProviderId,
+ isVirtual = category.isVirtual,
+ initialChannelId = currentContentId
+ )
+ openChannelListOverlay()
+}
+
+internal fun PlayerViewModel.loadPlaylist(
+ categoryId: Long,
+ providerId: Long,
+ isVirtual: Boolean,
+ initialChannelId: Long
+) {
+ playlistJob?.cancel()
+ playlistJob = viewModelScope.launch {
+ val flows = currentCombinedProfileId?.let { profileId ->
+ observeCombinedLivePlaylist(profileId, categoryId)
+ } ?: if (isVirtual) {
+ if (categoryId == VirtualCategoryIds.RECENT) {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)
+ .map { history ->
+ history.asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .toList()
+ }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ unsorted.orderedByRequestedRawIds(ids)
+ }
+ }
+ } else if (categoryId == VirtualCategoryIds.FAVORITES) {
+ favoriteRepository.getFavorites(currentProviderId, ContentType.LIVE)
+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ unsorted.orderedByRequestedRawIds(ids)
+ }
+ }
+ } else {
+ val groupId = if (categoryId < 0) -categoryId else categoryId
+ favoriteRepository.getFavoritesByGroup(groupId)
+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ unsorted.orderedByRequestedRawIds(ids)
+ }
+ }
+ }
+ } else {
+ channelRepository.getChannelsByNumber(providerId, categoryId)
+ }
+
+ combine(flows, preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->
+ val displayedChannels = when (numberingMode) {
+ ChannelNumberingMode.GROUP -> channels.mapIndexed { index, channel ->
+ channel.copy(number = index + 1)
+ }
+ ChannelNumberingMode.PROVIDER -> channels
+ ChannelNumberingMode.HIDDEN -> channels.map { it.copy(number = 0) }
+ }
+ numberingMode to displayedChannels.sanitizedChannelsForPlayer()
+ }.collect { (numberingMode, displayedChannels) ->
+ channelNumberingMode = numberingMode
+ channelList = displayedChannels
+ currentChannelFlowList.value = displayedChannels
+ val targetId = if (currentContentId != -1L) currentContentId else initialChannelId
+ if (targetId != -1L) {
+ currentChannelIndex = channelList.indexOfFirst { it.id == targetId }
+ }
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
+ }
+
+ if (currentChannelIndex != -1) {
+ currentChannelFlow.value = channelList[currentChannelIndex].sanitizedForPlayer()
+ refreshCurrentChannelRecording()
+ val channel = channelList[currentChannelIndex]
+ displayChannelNumberFlow.value = resolveChannelNumber(channel, currentChannelIndex)
+ } else if (displayedChannels.isNotEmpty() && currentContentId != -1L) {
+ showPlayerNotice(
+ message = "Channel not found in current playlist",
+ recoveryType = PlayerRecoveryType.SOURCE,
+ actions = listOf(PlayerNoticeAction.OPEN_GUIDE)
+ )
+ }
+ }
+ }
+}
+
+private fun PlayerViewModel.applyCombinedSourceProviderFilter(channels: List<Channel>): List<Channel> {
+ val selectedProviderId = currentCombinedSourceFilterProviderId ?: return channels
+ return channels.filter { it.providerId == selectedProviderId }
+}
+
+private fun PlayerViewModel.loadLiveChannelsByOrderedIds(
+ ids: List<Long>,
+ providerId: Long? = null
+): Flow<List<Channel>> = if (ids.isEmpty()) {
+ flowOf(emptyList())
+} else {
+ channelRepository.getChannelsByIds(ids).map { unsorted ->
+ val filtered = providerId?.let { requiredProviderId ->
+ unsorted.filter { it.providerId == requiredProviderId }
+ } ?: unsorted
+ filtered.orderedByRequestedRawIds(ids)
+ }
+}
+
+private fun PlayerViewModel.combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {
+ emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())
+}.map { members ->
+ currentCombinedProfileMembers = members
+ members.filter { it.enabled }.map { it.providerId }
+}
+
+private fun PlayerViewModel.effectiveCombinedProviderIds(providerIds: List<Long>): List<Long> =
+ currentCombinedSourceFilterProviderId?.let { selectedProviderId ->
+ providerIds.filter { it == selectedProviderId }
+ } ?: providerIds
+
+private fun PlayerViewModel.observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {
+ 0 -> flowOf(emptyList())
+ 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)
+ else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)
+}
+
+private fun PlayerViewModel.observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {
+ 0 -> flowOf(emptyList())
+ 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)
+ .map { history ->
+ history.asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .take(limit)
+ .toList()
+ }
+
+ else -> combine(providerIds.map { providerId ->
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)
+ }) { histories ->
+ histories.toList()
+ .flatMap { it }
+ .asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.providerId to it.contentId }
+ .map { it.contentId }
+ .take(limit)
+ .toList()
+ }
+}
+
+private fun buildCombinedLiveCategories(
+ combinedCategories: List<com.streamvault.domain.model.CombinedCategory>,
+ customCategories: List<Category>
+): List<Category> = buildList {
+ val favoritesCategory = customCategories.find { it.id == VirtualCategoryIds.FAVORITES }
+ if (favoritesCategory != null) {
+ add(favoritesCategory)
+ }
+ add(
+ Category(
+ id = VirtualCategoryIds.RECENT,
+ name = "Recent",
+ type = ContentType.LIVE,
+ isVirtual = true,
+ count = 0
+ )
+ )
+ addAll(customCategories.filter { it.id != VirtualCategoryIds.FAVORITES })
+ add(
+ Category(
+ id = ChannelRepository.ALL_CHANNELS_ID,
+ name = "All Channels",
+ type = ContentType.LIVE,
+ count = combinedCategories.sumOf { it.category.count }
+ )
+ )
+ addAll(combinedCategories.map { it.category })
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt
new file mode 100644
index 00000000..813a5c13
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt
@@ -0,0 +1,133 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.domain.model.ContentType
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.launch
+
+internal fun PlayerViewModel.finalizePreparedPlaybackContext(
+ requestVersion: Long,
+ streamUrl: String,
+ providerId: Long,
+ categoryId: Long,
+ isVirtual: Boolean,
+ internalChannelId: Long,
+ epgChannelId: String?,
+ shouldReloadPlaylist: Boolean,
+ hasArchiveRequest: Boolean,
+ archiveStartMs: Long?,
+ archiveEndMs: Long?,
+ archiveTitle: String?
+) {
+ if (shouldReloadPlaylist) {
+ currentCategoryId = categoryId
+ activeCategoryIdFlow.value = categoryId
+ isVirtualCategory = isVirtual
+ loadPlaylist(categoryId, providerId, isVirtual, internalChannelId)
+ } else {
+ if (channelList.isNotEmpty() && internalChannelId != -1L) {
+ currentChannelIndex = channelList.indexOfFirst { it.id == internalChannelId }
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == streamUrl }
+ }
+ }
+ }
+
+ if (currentContentType == ContentType.LIVE && hasArchiveRequest) {
+ playerEngine.stopLiveTimeshift()
+ viewModelScope.launch {
+ val catchUpUrls = try {
+ providerRepository.buildCatchUpUrls(
+ providerId = currentProviderId,
+ streamId = currentContentId,
+ start = (archiveStartMs ?: 0L) / 1000L,
+ end = (archiveEndMs ?: 0L) / 1000L
+ )
+ } catch (e: CredentialDecryptionException) {
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
+ showPlayerNotice(
+ message = e.message ?: CredentialDecryptionException.MESSAGE,
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+ return@launch
+ }
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ if (catchUpUrls.isNotEmpty()) {
+ startCatchUpPlayback(
+ urls = catchUpUrls,
+ title = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle,
+ recoveryAction = "Opened catch-up stream",
+ requestVersionOverride = requestVersion
+ )
+ } else {
+ val reason = resolveCatchUpFailureMessage(currentChannelFlow.value, archiveRequested = true, programHasArchive = true)
+ setLastFailureReason(reason)
+ showPlayerNotice(
+ message = reason,
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ }
+ }
+ }
+
+ if (currentContentType == ContentType.LIVE) {
+ requestEpg(
+ providerId = currentProviderId,
+ epgChannelId = epgChannelId,
+ internalChannelId = internalChannelId
+ )
+ } else {
+ requestEpg(providerId = -1L, epgChannelId = null)
+ }
+ observeRecentChannels()
+ observeLastVisitedCategory()
+
+ aspectRatioJob?.cancel()
+ _aspectRatio.value = AspectRatio.FIT
+ if (internalChannelId != -1L) {
+ aspectRatioJob = viewModelScope.launch {
+ preferencesRepository.getAspectRatioForChannel(internalChannelId).collect { savedRatio ->
+ _aspectRatio.value = try {
+ savedRatio?.let { AspectRatio.valueOf(it) } ?: AspectRatio.FIT
+ } catch (_: Exception) {
+ AspectRatio.FIT
+ }
+ }
+ }
+
+ viewModelScope.launch {
+ val channel = channelRepository.getChannel(internalChannelId)
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ currentChannelFlow.value = channel
+ refreshCurrentChannelRecording()
+ if (channel != null) {
+ currentTitle = channel.name.ifBlank { currentTitle }
+ playbackTitleFlow.value = currentTitle
+ currentStreamUrl = if (isCatchUpPlayback()) currentStreamUrl else channel.streamUrl
+ updateStreamClass(
+ when {
+ isCatchUpPlayback() -> "Catch-up"
+ streamUrl == channel.streamUrl -> "Primary"
+ channel.alternativeStreams.contains(streamUrl) -> "Alternate"
+ else -> "Direct"
+ }
+ )
+ if (currentContentType == ContentType.LIVE) {
+ recordLivePlayback(channel)
+ requestEpg(
+ providerId = currentProviderId,
+ epgChannelId = channel.epgChannelId,
+ streamId = channel.streamId,
+ internalChannelId = channel.id
+ )
+ }
+ updateChannelDiagnostics(channel)
+ }
+ }
+ }
+
+ startProgressTracking()
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
new file mode 100644
index 00000000..86244584
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
@@ -0,0 +1,99 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.PlayerSurfaceMode
+import kotlinx.coroutines.launch
+
+internal fun PlayerViewModel.applyPrepareSessionState(
+ streamUrl: String,
+ internalChannelId: Long,
+ categoryId: Long,
+ providerId: Long,
+ combinedProfileId: Long?,
+ combinedSourceFilterProviderId: Long?,
+ contentType: String,
+ title: String,
+ artworkUrl: String?,
+ seriesId: Long?,
+ seasonNumber: Int?,
+ episodeNumber: Int?,
+ hasArchiveRequest: Boolean,
+ preferredDecoderMode: DecoderMode,
+ preferredSurfaceMode: PlayerSurfaceMode
+): Boolean {
+ val previousProviderId = currentProviderId
+ val previousCategoryId = currentCategoryId
+ val previousCombinedProfileId = currentCombinedProfileId
+ val previousCombinedSourceFilterProviderId = currentCombinedSourceFilterProviderId
+ val shouldReloadPlaylist = categoryId != -1L &&
+ (
+ categoryId != previousCategoryId ||
+ providerId != previousProviderId ||
+ combinedProfileId != previousCombinedProfileId ||
+ combinedSourceFilterProviderId != previousCombinedSourceFilterProviderId
+ )
+
+ clearSeekPreview()
+ currentResolvedPlaybackUrl = ""
+ currentStreamUrl = streamUrl
+ currentContentId = internalChannelId
+ currentTitle = title
+ playbackTitleFlow.value = title
+ currentArtworkUrl = artworkUrl
+ currentContentType = try {
+ ContentType.valueOf(contentType)
+ } catch (_: Exception) {
+ ContentType.LIVE
+ }
+ currentProviderId = providerId
+ currentCombinedProfileId = combinedProfileId?.takeIf { it > 0L }
+ currentCombinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L }
+ currentSeriesId = seriesId?.takeIf { it > 0L }
+ currentSeasonNumber = seasonNumber
+ currentEpisodeNumber = episodeNumber
+ val streamClassLabel = if (hasArchiveRequest) "Catch-up" else "Primary"
+ applyDefaultPlaybackTimersIfNeeded()
+
+ if (currentContentType == ContentType.LIVE && currentCombinedProfileId != null) {
+ val activeCombinedProfileId = currentCombinedProfileId
+ viewModelScope.launch {
+ val members = activeCombinedProfileId?.let { combinedM3uRepository.getProfile(it)?.members }.orEmpty()
+ if (currentCombinedProfileId == activeCombinedProfileId) {
+ currentCombinedProfileMembers = members
+ }
+ }
+ } else {
+ currentCombinedProfileMembers = emptyList()
+ combinedCategoriesById = emptyMap()
+ }
+
+ if (!hasArchiveRequest) {
+ pendingCatchUpUrls = emptyList()
+ }
+ if (currentContentType != ContentType.SERIES_EPISODE || providerId <= 0 || currentSeriesId == null) {
+ clearSeriesEpisodeContext()
+ }
+ if (currentContentType != ContentType.LIVE) {
+ lastRecordedLivePlaybackKey = null
+ recentChannelsJob?.cancel()
+ recentChannelsFlow.value = emptyList()
+ lastVisitedCategoryJob?.cancel()
+ _lastVisitedCategory.value = null
+ playerEngine.stopLiveTimeshift()
+ }
+
+ hasRetriedWithSoftwareDecoder = false
+ playerEngine.setDecoderMode(preferredDecoderMode)
+ playerEngine.setSurfaceMode(preferredSurfaceMode)
+ updateDecoderMode(preferredDecoderMode)
+ updateStreamClass(streamClassLabel)
+
+ triedAlternativeStreams.clear()
+ if (!hasArchiveRequest) {
+ triedAlternativeStreams.add(streamUrl)
+ }
+
+ return shouldReloadPlaylist
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProgramTimelineSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProgramTimelineSupport.kt
new file mode 100644
index 00000000..f891d21e
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProgramTimelineSupport.kt
@@ -0,0 +1,36 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Program
+
+internal data class PlayerProgramTimeline(
+ val currentProgram: Program?,
+ val nextProgram: Program?,
+ val programHistory: List<Program>,
+ val upcomingPrograms: List<Program>
+)
+
+internal fun buildProgramTimeline(
+ programs: List<Program>,
+ now: Long,
+ catchUpSupported: Boolean,
+ maxHistoryItems: Int,
+ maxUpcomingItems: Int
+): PlayerProgramTimeline {
+ val sortedPrograms = programs.sortedBy { it.startTime }
+ val currentProgram = sortedPrograms.firstOrNull { it.startTime <= now && it.endTime > now }
+ val nextProgram = sortedPrograms.firstOrNull { it.startTime > now }
+ val programHistory = sortedPrograms
+ .filter { it.endTime <= now && (it.hasArchive || catchUpSupported) }
+ .sortedByDescending { it.startTime }
+ .take(maxHistoryItems)
+ val upcomingPrograms = sortedPrograms
+ .filter { it.endTime > now || it == currentProgram }
+ .sortedBy { it.startTime }
+ .take(maxUpcomingItems)
+ return PlayerProgramTimeline(
+ currentProgram = currentProgram,
+ nextProgram = nextProgram,
+ programHistory = programHistory,
+ upcomingPrograms = upcomingPrograms
+ )
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt
new file mode 100644
index 00000000..9e7881de
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt
@@ -0,0 +1,115 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.player.PlaybackState
+import com.streamvault.player.PlayerError
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+internal fun PlayerViewModel.buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> {
+ return buildPlayerRecoveryActions(
+ hasAlternateStream = hasAlternateStream(),
+ hasLastChannel = hasLastChannel(),
+ shouldOfferGuide = recoveryType == PlayerRecoveryType.CATCH_UP && currentContentType == ContentType.LIVE
+ )
+}
+
+internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(
+ error: PlayerError,
+ requestVersion: Long,
+ playbackUrl: String
+): Boolean {
+ if (hasRetriedXtreamAuthRefresh) return false
+ if (error !is PlayerError.NetworkError) return false
+ if (!isAuthExpiryPlaybackError(error.message)) return false
+ if (!isXtreamPlaybackSession()) return false
+
+ val refreshedStreamInfo = resolvePlaybackStreamInfo(
+ logicalUrl = currentStreamUrl,
+ internalContentId = currentContentId,
+ providerId = currentProviderId,
+ contentType = currentContentType
+ ) ?: return false
+
+ if (!isActivePlaybackSession(requestVersion, playbackUrl)) return false
+
+ hasRetriedXtreamAuthRefresh = true
+ probePassedPlaybackKeys.remove(
+ resolvePlaybackProbeCacheKey(
+ currentStreamUrl = currentStreamUrl,
+ url = playbackUrl
+ )
+ )
+ setLastFailureReason(error.message)
+ appendRecoveryAction("Refreshed provider playback URL after auth failure")
+ showPlayerNotice(
+ message = "Refreshing the provider playback URL…",
+ recoveryType = PlayerRecoveryType.NETWORK,
+ actions = buildRecoveryActions(PlayerRecoveryType.NETWORK),
+ isRetryNotice = true
+ )
+ if (!preparePlayer(refreshedStreamInfo, requestVersion)) return true
+ playerEngine.play()
+ return true
+}
+
+internal suspend fun PlayerViewModel.isXtreamPlaybackSession(): Boolean {
+ val providerId = currentProviderId.takeIf { it > 0L } ?: return false
+ val provider = providerRepository.getProvider(providerId) ?: return false
+ if (
+ provider.type != ProviderType.XTREAM_CODES &&
+ provider.type != ProviderType.STALKER_PORTAL
+ ) {
+ return false
+ }
+ return xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) ||
+ xtreamStreamUrlResolver.isInternalStreamUrl(currentResolvedPlaybackUrl)
+}
+
+internal fun PlayerViewModel.fallbackToPreviousChannel(reason: String): Boolean {
+ val fallbackIndex = previousChannelIndex
+ if (fallbackIndex in channelList.indices && fallbackIndex != currentChannelIndex) {
+ android.util.Log.w("PlayerVM", "Falling back to previous channel: $reason")
+ val savedPrevious = previousChannelIndex
+ changeChannel(fallbackIndex, isAutoFallback = true)
+ previousChannelIndex = savedPrevious
+ return true
+ }
+ return false
+}
+
+internal fun PlayerViewModel.scheduleZapBufferWatchdog(targetIndex: Int) {
+ if (!zapAutoRevertEnabled) return
+ zapBufferWatchdogJob?.cancel()
+ val requestVersion = prepareRequestVersion
+ zapBufferWatchdogJob = viewModelScope.launch {
+ repeat(15) {
+ delay(1000)
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ if (currentChannelIndex != targetIndex) return@launch
+ val state = playerEngine.playbackState.value
+ if (state == PlaybackState.READY || state == PlaybackState.ENDED) return@launch
+ }
+ if (!isActivePlaybackSession(requestVersion)) return@launch
+ val stillOnTarget = currentChannelIndex == targetIndex
+ val state = playerEngine.playbackState.value
+ val stalled = state == PlaybackState.BUFFERING || state == PlaybackState.ERROR
+ if (stillOnTarget && stalled) {
+ markStreamFailure(currentStreamUrl)
+ setLastFailureReason("Channel timed out in buffering state")
+ appendRecoveryAction("Buffer watchdog triggered")
+ val recovered = fallbackToPreviousChannel("Channel timed out in buffering state")
+ showPlayerNotice(
+ message = if (recovered) {
+ "That channel stalled too long. Returned to the last channel."
+ } else {
+ "That channel stalled too long. Try another source or open the guide."
+ },
+ recoveryType = PlayerRecoveryType.BUFFER_TIMEOUT,
+ actions = buildRecoveryActions(PlayerRecoveryType.BUFFER_TIMEOUT)
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt
new file mode 100644
index 00000000..4c07f240
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt
@@ -0,0 +1,157 @@
+package com.streamvault.app.ui.screens.player
+
+import android.os.SystemClock
+import androidx.lifecycle.viewModelScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+fun PlayerViewModel.setStopPlaybackTimer(minutes: Int) {
+ val normalized = sanitizePlaybackTimerMinutes(minutes, PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES)
+ if (normalized == 0) {
+ disableStopPlaybackTimer()
+ return
+ }
+ stopPlaybackTimerEndsAtMs = SystemClock.elapsedRealtime() + normalized * 60_000L
+ sleepTimerExitEmitted = false
+ updateSleepTimerState(stopMinutes = normalized)
+ startStopPlaybackTimerJob(normalized)
+ showPlayerNotice(message = "Playback will stop in ${formatTimerMinutesNotice(normalized)}.")
+}
+
+fun PlayerViewModel.setIdleStandbyTimer(minutes: Int) {
+ val normalized = sanitizePlaybackTimerMinutes(minutes, PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES)
+ if (normalized == 0) {
+ disableIdleStandbyTimer()
+ return
+ }
+ idleStandbyTimerEndsAtMs = SystemClock.elapsedRealtime() + normalized * 60_000L
+ sleepTimerExitEmitted = false
+ updateSleepTimerState(idleMinutes = normalized)
+ startIdleStandbyTimerJob(normalized)
+ showPlayerNotice(message = "Idle standby will be allowed after ${formatTimerMinutesNotice(normalized)} without activity.")
+}
+
+fun PlayerViewModel.extendStopPlaybackTimer(minutes: Int = 30) {
+ val current = _sleepTimerUiState.value
+ if (!current.stopTimerActive) return
+ stopPlaybackTimerEndsAtMs += minutes * 60_000L
+ sleepTimerExitEmitted = false
+ updateSleepTimerState(stopMinutes = current.stopTimerMinutes)
+}
+
+fun PlayerViewModel.extendIdleStandbyTimer(minutes: Int = 30) {
+ val current = _sleepTimerUiState.value
+ if (!current.idleTimerActive) return
+ idleStandbyTimerEndsAtMs += minutes * 60_000L
+ sleepTimerExitEmitted = false
+ updateSleepTimerState(idleMinutes = current.idleTimerMinutes)
+}
+
+fun PlayerViewModel.disableStopPlaybackTimer() {
+ stopPlaybackTimerJob?.cancel()
+ stopPlaybackTimerJob = null
+ stopPlaybackTimerEndsAtMs = 0L
+ _sleepTimerUiState.update { it.copy(stopTimerMinutes = 0, stopRemainingMs = 0L) }
+}
+
+fun PlayerViewModel.disableIdleStandbyTimer() {
+ idleStandbyTimerJob?.cancel()
+ idleStandbyTimerJob = null
+ idleStandbyTimerEndsAtMs = 0L
+ _sleepTimerUiState.update { it.copy(idleTimerMinutes = 0, idleRemainingMs = 0L) }
+}
+
+fun PlayerViewModel.notifyUserActivity() {
+ val current = _sleepTimerUiState.value
+ if (!current.idleTimerActive) return
+ idleStandbyTimerEndsAtMs = SystemClock.elapsedRealtime() + current.idleTimerMinutes * 60_000L
+ updateSleepTimerState(idleMinutes = current.idleTimerMinutes)
+}
+
+fun PlayerViewModel.consumeSleepTimerExitEvent() {
+ _sleepTimerExitEvent.value = 0
+}
+
+internal fun PlayerViewModel.applyDefaultPlaybackTimersIfNeeded() {
+ if (playbackTimerDefaultsApplied) return
+ playbackTimerDefaultsApplied = true
+ sleepTimerExitEmitted = false
+ viewModelScope.launch {
+ val stopMinutes = sanitizePlaybackTimerMinutes(
+ preferencesRepository.defaultStopPlaybackTimerMinutes.first(),
+ PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES
+ )
+ val idleMinutes = sanitizePlaybackTimerMinutes(
+ preferencesRepository.defaultIdleStandbyTimerMinutes.first(),
+ PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES
+ )
+ if (!playbackTimerDefaultsApplied || _sleepTimerUiState.value.stopTimerActive || _sleepTimerUiState.value.idleTimerActive) {
+ return@launch
+ }
+ if (stopMinutes > 0) {
+ setStopPlaybackTimer(stopMinutes)
+ }
+ if (idleMinutes > 0) {
+ setIdleStandbyTimer(idleMinutes)
+ }
+ }
+}
+
+internal fun PlayerViewModel.startStopPlaybackTimerJob(minutes: Int) {
+ stopPlaybackTimerJob?.cancel()
+ stopPlaybackTimerJob = viewModelScope.launch {
+ while (true) {
+ val remainingMs = updateSleepTimerState(stopMinutes = minutes).stopRemainingMs
+ if (remainingMs <= 0L) {
+ expirePlaybackTimer()
+ return@launch
+ }
+ delay(PlayerViewModel.TIMER_TICK_MS)
+ }
+ }
+}
+
+internal fun PlayerViewModel.startIdleStandbyTimerJob(minutes: Int) {
+ idleStandbyTimerJob?.cancel()
+ idleStandbyTimerJob = viewModelScope.launch {
+ while (true) {
+ val remainingMs = updateSleepTimerState(idleMinutes = minutes).idleRemainingMs
+ if (remainingMs <= 0L) {
+ expirePlaybackTimer()
+ return@launch
+ }
+ delay(PlayerViewModel.TIMER_TICK_MS)
+ }
+ }
+}
+
+internal fun PlayerViewModel.updateSleepTimerState(
+ stopMinutes: Int = _sleepTimerUiState.value.stopTimerMinutes,
+ idleMinutes: Int = _sleepTimerUiState.value.idleTimerMinutes
+): SleepTimerUiState {
+ val next = computeSleepTimerUiState(
+ current = _sleepTimerUiState.value,
+ nowElapsedMs = SystemClock.elapsedRealtime(),
+ stopPlaybackTimerEndsAtMs = stopPlaybackTimerEndsAtMs,
+ idleStandbyTimerEndsAtMs = idleStandbyTimerEndsAtMs,
+ stopMinutes = stopMinutes,
+ idleMinutes = idleMinutes
+ )
+ _sleepTimerUiState.value = next
+ return next
+}
+
+internal fun PlayerViewModel.expirePlaybackTimer() {
+ if (sleepTimerExitEmitted) return
+ sleepTimerExitEmitted = true
+ stopPlaybackTimerJob?.cancel()
+ idleStandbyTimerJob?.cancel()
+ stopPlaybackTimerJob = null
+ idleStandbyTimerJob = null
+ stopPlaybackTimerEndsAtMs = 0L
+ idleStandbyTimerEndsAtMs = 0L
+ _sleepTimerUiState.value = SleepTimerUiState()
+ _sleepTimerExitEvent.value += 1
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 008818c9..30ab9e87 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -9,7 +9,6 @@ import com.streamvault.app.cast.CastMediaRequest
import com.streamvault.app.cast.CastStartResult
import com.streamvault.app.di.MainPlayerEngine
import com.streamvault.app.player.LivePreviewHandoffManager
-import com.streamvault.app.ui.model.orderedByRequestedRawIds
import com.streamvault.app.util.isPlaybackComplete
import com.streamvault.app.tv.LauncherRecommendationsManager
import com.streamvault.app.tv.WatchNextManager
@@ -69,7 +68,6 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject
-import java.util.Locale
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -78,29 +76,28 @@ import okhttp3.Request
class PlayerViewModel @Inject constructor(
@param:MainPlayerEngine
private val mainPlayerEngine: PlayerEngine,
- private val epgRepository: EpgRepository,
+ internal val epgRepository: EpgRepository,
internal val channelRepository: ChannelRepository,
internal val movieRepository: MovieRepository,
private val seriesRepository: SeriesRepository,
- private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
+ internal val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
internal val playbackHistoryRepository: PlaybackHistoryRepository,
- private val providerRepository: com.streamvault.domain.repository.ProviderRepository,
- private val combinedM3uRepository: CombinedM3uRepository,
- private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
- private val getCustomCategories: GetCustomCategories,
- private val markAsWatched: MarkAsWatched,
+ internal val providerRepository: com.streamvault.domain.repository.ProviderRepository,
+ internal val combinedM3uRepository: CombinedM3uRepository,
+ internal val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
+ internal val getCustomCategories: GetCustomCategories,
+ internal val markAsWatched: MarkAsWatched,
internal val scheduleRecordingUseCase: ScheduleRecording,
internal val recordingManager: RecordingManager,
- private val watchNextManager: WatchNextManager,
- private val launcherRecommendationsManager: LauncherRecommendationsManager,
+ internal val watchNextManager: WatchNextManager,
+ internal val launcherRecommendationsManager: LauncherRecommendationsManager,
internal val castManager: CastManager,
- private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
- private val seekThumbnailProvider: SeekThumbnailProvider,
- private val livePreviewHandoffManager: LivePreviewHandoffManager,
+ internal val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
+ internal val seekThumbnailProvider: SeekThumbnailProvider,
+ internal val livePreviewHandoffManager: LivePreviewHandoffManager,
private val okHttpClient: OkHttpClient,
) : ViewModel() {
companion object {
- private const val MUTE_TOGGLE_DEBOUNCE_MS = 250L
private const val MAX_PROGRAM_HISTORY_ITEMS = 18
private const val MAX_UPCOMING_PROGRAM_ITEMS = 24
private const val PLAYER_EPG_REFRESH_INTERVAL_MS = 30_000L
@@ -110,8 +107,8 @@ class PlayerViewModel @Inject constructor(
private const val TOKEN_RENEWAL_CHECK_INTERVAL_MS = 10_000L
private const val LOW_BANDWIDTH_THRESHOLD_BPS = 500_000L
private const val LOW_BANDWIDTH_DURATION_SECONDS = 30
- private val PLAYBACK_TIMER_PRESETS_MINUTES = setOf(0, 15, 30, 45, 60, 90, 120)
- private const val TIMER_TICK_MS = 1_000L
+ internal val PLAYBACK_TIMER_PRESETS_MINUTES = setOf(0, 15, 30, 45, 60, 90, 120)
+ internal const val TIMER_TICK_MS = 1_000L
}
private val activePlayerEngineFlow = MutableStateFlow(mainPlayerEngine)
@@ -152,16 +149,16 @@ class PlayerViewModel @Inject constructor(
private val _nextEpisode = MutableStateFlow<Episode?>(null)
val nextEpisode: StateFlow<Episode?> = _nextEpisode.asStateFlow()
- private val _autoPlayCountdown = MutableStateFlow<AutoPlayCountdownUiState?>(null)
+ internal val _autoPlayCountdown = MutableStateFlow<AutoPlayCountdownUiState?>(null)
val autoPlayCountdown: StateFlow<AutoPlayCountdownUiState?> = _autoPlayCountdown.asStateFlow()
internal val playbackTitleFlow = MutableStateFlow("")
val playbackTitle: StateFlow<String> = playbackTitleFlow.asStateFlow()
- private val _resumePrompt = MutableStateFlow(ResumePromptState())
+ internal val _resumePrompt = MutableStateFlow(ResumePromptState())
val resumePrompt: StateFlow<ResumePromptState> = _resumePrompt.asStateFlow()
- private val _aspectRatio = MutableStateFlow(AspectRatio.FIT)
+ internal val _aspectRatio = MutableStateFlow(AspectRatio.FIT)
val aspectRatio: StateFlow<AspectRatio> = _aspectRatio.asStateFlow()
internal val showChannelListOverlayFlow = MutableStateFlow(false)
@@ -170,13 +167,13 @@ class PlayerViewModel @Inject constructor(
internal val showEpgOverlayFlow = MutableStateFlow(false)
val showEpgOverlay: StateFlow<Boolean> = showEpgOverlayFlow.asStateFlow()
- private val currentChannelFlowList = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())
+ internal val currentChannelFlowList = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())
val currentChannelList: StateFlow<List<com.streamvault.domain.model.Channel>> = currentChannelFlowList.asStateFlow()
internal val recentChannelsFlow = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())
val recentChannels: StateFlow<List<com.streamvault.domain.model.Channel>> = recentChannelsFlow.asStateFlow()
- private val _lastVisitedCategory = MutableStateFlow<Category?>(null)
+ internal val _lastVisitedCategory = MutableStateFlow<Category?>(null)
val lastVisitedCategory: StateFlow<Category?> = _lastVisitedCategory.asStateFlow()
internal val showCategoryListOverlayFlow = MutableStateFlow(false)
@@ -200,14 +197,14 @@ class PlayerViewModel @Inject constructor(
internal val showDiagnosticsFlow = MutableStateFlow(false)
val showDiagnostics: StateFlow<Boolean> = showDiagnosticsFlow.asStateFlow()
- private val _playerNotice = MutableStateFlow<PlayerNoticeState?>(null)
+ internal val _playerNotice = MutableStateFlow<PlayerNoticeState?>(null)
val playerNotice: StateFlow<PlayerNoticeState?> = _playerNotice.asStateFlow()
private val _playerDiagnostics = MutableStateFlow(PlayerDiagnosticsUiState())
val playerDiagnostics: StateFlow<PlayerDiagnosticsUiState> = _playerDiagnostics.asStateFlow()
- private val audioVideoOffsetPreviewMs = MutableStateFlow<Int?>(null)
- private val _audioVideoOffsetUiState = MutableStateFlow(PlayerAudioVideoOffsetUiState())
+ internal val audioVideoOffsetPreviewMs = MutableStateFlow<Int?>(null)
+ internal val _audioVideoOffsetUiState = MutableStateFlow(PlayerAudioVideoOffsetUiState())
val audioVideoOffsetUiState: StateFlow<PlayerAudioVideoOffsetUiState> = _audioVideoOffsetUiState.asStateFlow()
- private val _seekPreview = MutableStateFlow(SeekPreviewState())
+ internal val _seekPreview = MutableStateFlow(SeekPreviewState())
val seekPreview: StateFlow<SeekPreviewState> = _seekPreview.asStateFlow()
private val _recordingItems = MutableStateFlow<List<RecordingItem>>(emptyList())
val recordingItems: StateFlow<List<RecordingItem>> = _recordingItems.asStateFlow()
@@ -215,9 +212,9 @@ class PlayerViewModel @Inject constructor(
val currentChannelRecording: StateFlow<RecordingItem?> = currentChannelFlowRecording.asStateFlow()
private val _timeshiftUiState = MutableStateFlow(PlayerTimeshiftUiState())
val timeshiftUiState: StateFlow<PlayerTimeshiftUiState> = _timeshiftUiState.asStateFlow()
- private val _sleepTimerUiState = MutableStateFlow(SleepTimerUiState())
+ internal val _sleepTimerUiState = MutableStateFlow(SleepTimerUiState())
val sleepTimerUiState: StateFlow<SleepTimerUiState> = _sleepTimerUiState.asStateFlow()
- private val _sleepTimerExitEvent = MutableStateFlow(0)
+ internal val _sleepTimerExitEvent = MutableStateFlow(0)
val sleepTimerExitEvent: StateFlow<Int> = _sleepTimerExitEvent.asStateFlow()
internal var channelInfoHideJob: Job? = null
@@ -225,37 +222,37 @@ class PlayerViewModel @Inject constructor(
internal var diagnosticsHideJob: Job? = null
internal var numericInputCommitJob: Job? = null
internal var numericInputFeedbackJob: Job? = null
- private var playerNoticeHideJob: Job? = null
- private var mutePersistJob: Job? = null
+ internal var playerNoticeHideJob: Job? = null
+ internal var mutePersistJob: Job? = null
private var recoveryJob: Job? = null
internal var numericInputBuffer: String = ""
internal val triedAlternativeStreams = mutableSetOf<String>()
- private val failedStreamsThisSession = mutableMapOf<String, Int>()
- private var hasRetriedWithSoftwareDecoder = false
- private var hasRetriedXtreamAuthRefresh = false
- private val probePassedPlaybackKeys = mutableSetOf<String>()
+ internal val failedStreamsThisSession = mutableMapOf<String, Int>()
+ internal var hasRetriedWithSoftwareDecoder = false
+ internal var hasRetriedXtreamAuthRefresh = false
+ internal val probePassedPlaybackKeys = mutableSetOf<String>()
private val notifiedRecordingFailureIds = mutableSetOf<String>()
internal var lastRecordedLivePlaybackKey: Pair<Long, Long>? = null
private var currentStreamClassLabel: String = "Primary"
- private var lastRecordedVariantObservationSignature: String? = null
- private var prepareRequestVersion: Long = 0L
+ internal var lastRecordedVariantObservationSignature: String? = null
+ internal var prepareRequestVersion: Long = 0L
internal var currentArtworkUrl: String? = null
- private var currentResolvedPlaybackUrl: String = ""
+ internal var currentResolvedPlaybackUrl: String = ""
internal var pendingCatchUpUrls: List<String> = emptyList()
internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP
set(value) {
field = value
rebuildChannelNumberIndex()
}
- private var activeEpgRequestKey: EpgRequestKey? = null
+ internal var activeEpgRequestKey: EpgRequestKey? = null
internal var playerControlsTimeoutMs: Long = 5_000L
internal var liveOverlayTimeoutMs: Long = 4_000L
- private var playerNoticeTimeoutMs: Long = 6_000L
+ internal var playerNoticeTimeoutMs: Long = 6_000L
internal var diagnosticsTimeoutMs: Long = 15_000L
private var preferredDecoderMode: DecoderMode = DecoderMode.AUTO
private var preferredSurfaceMode: com.streamvault.domain.model.PlayerSurfaceMode =
com.streamvault.domain.model.PlayerSurfaceMode.AUTO
- private var timeshiftConfig: TimeshiftConfig = TimeshiftConfig()
+ internal var timeshiftConfig: TimeshiftConfig = TimeshiftConfig()
// Zapping state
//
@@ -291,42 +288,42 @@ class PlayerViewModel @Inject constructor(
internal var currentContentId: Long = -1L
internal var currentContentType: ContentType = ContentType.LIVE
internal var currentTitle: String = ""
- private var currentSeriesId: Long? = null
- private var currentSeasonNumber: Int? = null
- private var currentEpisodeNumber: Int? = null
+ internal var currentSeriesId: Long? = null
+ internal var currentSeasonNumber: Int? = null
+ internal var currentEpisodeNumber: Int? = null
internal var isVirtualCategory: Boolean = false
- private var currentCombinedProfileMembers: List<CombinedM3uProfileMember> = emptyList()
- private var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()
+ internal var currentCombinedProfileMembers: List<CombinedM3uProfileMember> = emptyList()
+ internal var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()
private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLE
- private var epgJob: Job? = null
- private var playlistJob: Job? = null
- private var recentChannelsJob: Job? = null
- private var lastVisitedCategoryJob: Job? = null
+ internal var epgJob: Job? = null
+ internal var playlistJob: Job? = null
+ internal var recentChannelsJob: Job? = null
+ internal var lastVisitedCategoryJob: Job? = null
internal var controlsHideJob: Job? = null
- private var seekPreviewJob: Job? = null
- private var thumbnailPreloadJob: Job? = null
+ internal var seekPreviewJob: Job? = null
+ internal var thumbnailPreloadJob: Job? = null
private var lowBandwidthMonitorJob: Job? = null
- private var progressTrackingJob: Job? = null
- private var tokenRenewalJob: Job? = null
- private var stopPlaybackTimerJob: Job? = null
- private var idleStandbyTimerJob: Job? = null
+ internal var progressTrackingJob: Job? = null
+ internal var tokenRenewalJob: Job? = null
+ internal var stopPlaybackTimerJob: Job? = null
+ internal var idleStandbyTimerJob: Job? = null
internal var zapOverlayJob: Job? = null
- private var aspectRatioJob: Job? = null
+ internal var aspectRatioJob: Job? = null
internal var zapBufferWatchdogJob: Job? = null
- private var autoPlayCountdownJob: Job? = null
+ internal var autoPlayCountdownJob: Job? = null
internal var zapAutoRevertEnabled: Boolean = true
- private var autoPlayNextEpisodeEnabled: Boolean = true
- private var isAppInForeground: Boolean = true
- private var shouldResumeAfterForeground: Boolean = false
- private var seekPreviewRequestVersion: Long = 0L
- private var lastMuteToggleAtMs: Long = 0L
- private var stopPlaybackTimerEndsAtMs: Long = 0L
- private var idleStandbyTimerEndsAtMs: Long = 0L
+ internal var autoPlayNextEpisodeEnabled: Boolean = true
+ internal var isAppInForeground: Boolean = true
+ internal var shouldResumeAfterForeground: Boolean = false
+ internal var seekPreviewRequestVersion: Long = 0L
+ internal var lastMuteToggleAtMs: Long = 0L
+ internal var stopPlaybackTimerEndsAtMs: Long = 0L
+ internal var idleStandbyTimerEndsAtMs: Long = 0L
private var defaultStopPlaybackTimerMinutes: Int = 0
private var defaultIdleStandbyTimerMinutes: Int = 0
- private var playbackTimerDefaultsApplied = false
- private var sleepTimerExitEmitted = false
+ internal var playbackTimerDefaultsApplied = false
+ internal var sleepTimerExitEmitted = false
val castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState
@@ -422,11 +419,6 @@ class PlayerViewModel @Inject constructor(
playerEngine.startLiveTimeshift(streamInfo, channelKey, timeshiftConfig)
}
- private fun String?.safeTrimmedOrNull(): String? {
- val value = this ?: return null
- return value.trim().takeIf { it.isNotEmpty() }
- }
-
init {
viewModelScope.launch {
activePlayerEngineFlow.flatMapLatest { it.error }.collect { error ->
@@ -662,7 +654,10 @@ class PlayerViewModel @Inject constructor(
private fun handlePlaybackError(error: PlayerError) {
val requestVersion = prepareRequestVersion
- val playbackUrl = currentPlaybackIdentityUrl()
+ val playbackUrl = resolvePlaybackIdentityUrl(
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ currentStreamUrl = currentStreamUrl
+ )
recoveryJob?.cancel()
if (error is PlayerError.DecoderError && !hasRetriedWithSoftwareDecoder) {
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
@@ -825,11 +820,6 @@ class PlayerViewModel @Inject constructor(
}
}
- private data class PlaybackProbeFailure(
- val message: String,
- val recoveryType: PlayerRecoveryType
- )
-
val playerError: StateFlow<PlayerError?> by lazy(LazyThreadSafetyMode.NONE) {
activeEngineFlowState(initialValue = null) { it.error }
}
@@ -856,241 +846,6 @@ class PlayerViewModel @Inject constructor(
.stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), true)
}
- fun selectAudioTrack(trackId: String) {
- playerEngine.selectAudioTrack(trackId)
- }
-
- fun selectSubtitleTrack(trackId: String?) {
- playerEngine.selectSubtitleTrack(trackId)
- }
-
- fun selectVideoQuality(trackId: String) {
- playerEngine.selectVideoTrack(trackId)
- }
-
- fun selectLiveVariant(rawChannelId: Long) {
- val currentChannel = currentChannelFlow.value?.sanitizedForPlayer() ?: return
- val updatedChannel = currentChannel.withSelectedVariant(rawChannelId)?.sanitizedForPlayer() ?: return
- if (updatedChannel.selectedVariantId == currentChannel.selectedVariantId) return
-
- val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.clear()
- currentContentId = updatedChannel.id
- currentStreamUrl = updatedChannel.streamUrl
- currentTitle = updatedChannel.currentVariant?.originalName ?: updatedChannel.name
- playbackTitleFlow.value = currentTitle
- currentChannelFlow.value = updatedChannel
- if (currentChannelIndex in channelList.indices) {
- channelList = channelList.mapIndexed { index, existing ->
- if (index == currentChannelIndex || existing.logicalGroupId == updatedChannel.logicalGroupId) {
- updatedChannel
- } else {
- existing
- }
- }
- currentChannelFlowList.value = channelList
- }
- if (currentChannelIndex >= 0) {
- displayChannelNumberFlow.value = resolveChannelNumber(updatedChannel, currentChannelIndex)
- }
- refreshCurrentChannelRecording()
- updateChannelDiagnostics(updatedChannel)
- updateStreamClass("Variant")
- viewModelScope.launch {
- preferencesRepository.setPreferredLiveVariant(
- providerId = updatedChannel.providerId,
- logicalGroupId = updatedChannel.logicalGroupId,
- rawChannelId = rawChannelId
- )
- val streamInfo = resolvePlaybackStreamInfo(
- logicalUrl = updatedChannel.streamUrl,
- internalContentId = updatedChannel.id,
- providerId = updatedChannel.providerId,
- contentType = ContentType.LIVE
- ) ?: return@launch
- if (!isActivePlaybackSession(requestVersion, updatedChannel.streamUrl)) return@launch
- if (currentContentType == ContentType.LIVE) {
- recordLivePlayback(updatedChannel)
- requestEpg(
- providerId = updatedChannel.providerId,
- epgChannelId = updatedChannel.epgChannelId,
- streamId = updatedChannel.streamId,
- internalChannelId = updatedChannel.id
- )
- }
- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
- playerEngine.play()
- }
- }
-
- fun recordLiveVariantObservation(playbackState: PlaybackState, videoFormat: VideoFormat) {
- if (currentContentType != ContentType.LIVE || playbackState != PlaybackState.READY || videoFormat.isEmpty) {
- return
- }
- val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return
- val rawChannelId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id
- if (rawChannelId <= 0L) return
- val signature = buildString {
- append(rawChannelId)
- append('|')
- append(videoFormat.width)
- append('|')
- append(videoFormat.height)
- append('|')
- append(videoFormat.bitrate)
- append('|')
- append(videoFormat.frameRate)
- }
- if (signature == lastRecordedVariantObservationSignature) return
- lastRecordedVariantObservationSignature = signature
-
- viewModelScope.launch {
- val existing = preferencesRepository.liveVariantObservations.first()[rawChannelId]
- preferencesRepository.recordLiveVariantObservation(
- rawChannelId = rawChannelId,
- observedQuality = LiveChannelObservedQuality(
- lastObservedWidth = videoFormat.width,
- lastObservedHeight = videoFormat.height,
- lastObservedBitrate = videoFormat.bitrate,
- lastObservedFrameRate = videoFormat.frameRate,
- successCount = (existing?.successCount ?: 0) + 1,
- lastSuccessfulAt = System.currentTimeMillis()
- )
- )
- }
- }
-
- fun setPlaybackSpeed(speed: Float) {
- val normalizedSpeed = speed.coerceIn(0.5f, 2f)
- playerEngine.setPlaybackSpeed(normalizedSpeed)
- viewModelScope.launch {
- preferencesRepository.setPlayerPlaybackSpeed(normalizedSpeed)
- }
- }
-
- fun previewAudioVideoOffset(offsetMs: Int) {
- audioVideoOffsetPreviewMs.value = offsetMs.coerceIn(AUDIO_VIDEO_OFFSET_MIN_MS, AUDIO_VIDEO_OFFSET_MAX_MS)
- }
-
- fun adjustAudioVideoOffset(deltaMs: Int) {
- val current = audioVideoOffsetPreviewMs.value ?: _audioVideoOffsetUiState.value.effectiveOffsetMs
- previewAudioVideoOffset(current + deltaMs)
- }
-
- fun resetAudioVideoOffsetPreview() {
- previewAudioVideoOffset(0)
- }
-
- fun dismissAudioVideoOffsetPreview() {
- audioVideoOffsetPreviewMs.value = null
- }
-
- fun saveAudioVideoOffsetForChannel() {
- val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
- val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
- viewModelScope.launch {
- preferencesRepository.setAudioVideoOffsetForChannel(channelId, offsetMs)
- audioVideoOffsetPreviewMs.value = null
- }
- }
-
- fun saveAudioVideoOffsetAsGlobal() {
- val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
- val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L }
- viewModelScope.launch {
- preferencesRepository.setPlayerAudioVideoOffsetMs(offsetMs)
- if (channelId != null) {
- preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
- }
- audioVideoOffsetPreviewMs.value = null
- }
- }
-
- fun useGlobalAudioVideoOffset() {
- val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
- viewModelScope.launch {
- preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
- audioVideoOffsetPreviewMs.value = null
- }
- }
-
- fun seekTo(positionMs: Long) {
- notifyUserActivity()
- playerEngine.seekTo(positionMs)
- clearSeekPreview()
- }
-
- fun setScrubbingMode(enabled: Boolean) {
- playerEngine.setScrubbingMode(enabled)
- if (!enabled) {
- clearSeekPreview()
- }
- }
-
- fun updateSeekPreview(positionMs: Long?) {
- if (positionMs == null || currentContentType == ContentType.LIVE) {
- clearSeekPreview()
- return
- }
-
- val previewPositionMs = positionMs.coerceAtLeast(0L)
- val previewUrl = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
- val canExtractFrame = previewUrl.isNotBlank() && seekThumbnailProvider.supportsFrameExtraction(previewUrl)
-
- _seekPreview.update { current ->
- current.copy(
- visible = true,
- positionMs = previewPositionMs,
- artworkUrl = currentArtworkUrl,
- title = currentTitle,
- isLoading = canExtractFrame,
- frameBitmap = if (canExtractFrame) current.frameBitmap else null
- )
- }
-
- seekPreviewJob?.cancel()
- if (!canExtractFrame) {
- return
- }
-
- val requestVersion = ++seekPreviewRequestVersion
- seekPreviewJob = viewModelScope.launch {
- delay(120)
- val bitmap = seekThumbnailProvider.loadFrame(previewUrl, previewPositionMs)
- if (requestVersion != seekPreviewRequestVersion) return@launch
-
- _seekPreview.update { current ->
- if (!current.visible || current.positionMs != previewPositionMs) {
- current
- } else {
- current.copy(
- frameBitmap = bitmap,
- artworkUrl = currentArtworkUrl,
- title = currentTitle,
- isLoading = false
- )
- }
- }
- }
- }
-
- private fun startThumbnailPreload() {
- thumbnailPreloadJob?.cancel()
- val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
- if (url.isBlank() || !seekThumbnailProvider.supportsFrameExtraction(url)) return
- val durationMs = playerEngine.duration.value
- if (durationMs <= 0L) return
- thumbnailPreloadJob = viewModelScope.launch(Dispatchers.Default) {
- val bucketMs = 10_000L
- var pos = 0L
- while (pos <= durationMs) {
- ensureActive()
- seekThumbnailProvider.loadFrame(url, pos)
- pos += bucketMs
- }
- }
- }
-
internal fun beginPlaybackSession(): Long {
recoveryJob?.cancel()
thumbnailPreloadJob?.cancel()
@@ -1099,7 +854,7 @@ class PlayerViewModel @Inject constructor(
return ++prepareRequestVersion
}
- private fun clearSeriesEpisodeContext() {
+ internal fun clearSeriesEpisodeContext() {
currentSeriesId = null
currentSeasonNumber = null
currentEpisodeNumber = null
@@ -1109,54 +864,6 @@ class PlayerViewModel @Inject constructor(
cancelAutoPlay()
}
- private fun resolveEpisode(
- series: Series,
- episodeId: Long,
- seasonNumber: Int?,
- episodeNumber: Int?
- ): Episode? {
- val episodes = series.seasons
- .sanitizedForPlayer()
- .sortedBy { it.seasonNumber }
- .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }
- return episodes.firstOrNull {
- it.id == episodeId || it.matchesPlaybackEpisode(episodeId, seasonNumber, episodeNumber)
- }
- ?: episodes.firstOrNull { it.seasonNumber == seasonNumber && it.episodeNumber == episodeNumber }
- }
-
- private fun findNextEpisode(series: Series, episode: Episode): Episode? {
- val orderedEpisodes = series.seasons
- .sanitizedForPlayer()
- .sortedBy { it.seasonNumber }
- .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }
- val currentIndex = orderedEpisodes.indexOfFirst {
- it.id == episode.id ||
- it.playbackEpisodeIdentity() == episode.playbackEpisodeIdentity() ||
- (it.seasonNumber == episode.seasonNumber && it.episodeNumber == episode.episodeNumber)
- }
- return orderedEpisodes.getOrNull(currentIndex + 1)
- }
-
- private fun Episode.playbackEpisodeIdentity(): Long =
- episodeId.takeIf { it > 0L } ?: id
-
- private fun Episode.matchesPlaybackEpisode(
- requestedEpisodeId: Long,
- requestedSeasonNumber: Int?,
- requestedEpisodeNumber: Int?
- ): Boolean {
- val identity = playbackEpisodeIdentity()
- return (requestedEpisodeId > 0L && identity == requestedEpisodeId) ||
- (requestedSeasonNumber != null &&
- requestedEpisodeNumber != null &&
- seasonNumber == requestedSeasonNumber &&
- episodeNumber == requestedEpisodeNumber)
- }
-
- private fun buildEpisodePlaybackTitle(episode: Episode): String =
- "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}"
-
private suspend fun loadSeriesEpisodeContext(
requestVersion: Long,
providerId: Long,
@@ -1169,22 +876,26 @@ class PlayerViewModel @Inject constructor(
is Result.Success -> {
if (!isActivePlaybackSession(requestVersion)) return null
val series = result.data.sanitizedForPlayer()
- val resolvedEpisode = resolveEpisode(series, episodeId, seasonNumber, episodeNumber)
+ val resolution = buildSeriesEpisodeResolution(
+ series = series,
+ episodeId = episodeId,
+ seasonNumber = seasonNumber,
+ episodeNumber = episodeNumber,
+ currentContentType = currentContentType,
+ currentArtworkUrl = currentArtworkUrl
+ )
_currentSeries.value = series
- _currentEpisode.value = resolvedEpisode
- _nextEpisode.value = resolvedEpisode?.let { findNextEpisode(series, it) }
+ _currentEpisode.value = resolution.resolvedEpisode
+ _nextEpisode.value = resolution.nextEpisode
currentSeriesId = seriesId
- currentSeasonNumber = resolvedEpisode?.seasonNumber ?: seasonNumber
- currentEpisodeNumber = resolvedEpisode?.episodeNumber ?: episodeNumber
- if (resolvedEpisode != null && currentContentType == ContentType.SERIES_EPISODE) {
- currentArtworkUrl = resolvedEpisode.coverUrl
- ?: currentArtworkUrl
- ?: series.posterUrl
- ?: series.backdropUrl
- currentTitle = buildEpisodePlaybackTitle(resolvedEpisode)
+ currentSeasonNumber = resolution.resolvedSeasonNumber
+ currentEpisodeNumber = resolution.resolvedEpisodeNumber
+ if (resolution.resolvedEpisode != null && currentContentType == ContentType.SERIES_EPISODE) {
+ currentArtworkUrl = resolution.resolvedArtworkUrl
+ currentTitle = resolution.resolvedTitle ?: currentTitle
playbackTitleFlow.value = currentTitle
}
- resolvedEpisode
+ resolution.resolvedEpisode
}
else -> {
@@ -1200,99 +911,34 @@ class PlayerViewModel @Inject constructor(
}
}
- private fun buildPlaybackHistorySnapshot(
+ internal fun buildPlaybackHistorySnapshot(
positionMs: Long,
durationMs: Long
- ): PlaybackHistory? {
- if (positionMs < 0 || durationMs <= 0 || currentContentId == -1L || currentProviderId == -1L) {
- return null
- }
- return PlaybackHistory(
- contentId = currentContentId,
- contentType = currentContentType,
- providerId = currentProviderId,
- title = currentTitle,
- posterUrl = currentArtworkUrl,
- streamUrl = currentStreamUrl,
- resumePositionMs = positionMs,
- totalDurationMs = durationMs,
- lastWatchedAt = System.currentTimeMillis(),
- seriesId = currentSeriesId,
- seasonNumber = _currentEpisode.value?.seasonNumber ?: currentSeasonNumber,
- episodeNumber = _currentEpisode.value?.episodeNumber ?: currentEpisodeNumber
- )
- }
-
- private suspend fun persistPlaybackCompletion() {
- val durationMs = playerEngine.duration.value
- val completedHistory = buildPlaybackHistorySnapshot(
- positionMs = durationMs.coerceAtLeast(playerEngine.currentPosition.value),
- durationMs = durationMs
- ) ?: return
- logRepositoryFailure(
- operation = "Mark playback watched",
- result = markAsWatched(completedHistory)
- )
- watchNextManager.refreshWatchNext()
- launcherRecommendationsManager.refreshRecommendations()
- }
-
- private fun handlePlaybackEnded() {
- if (currentContentType == ContentType.LIVE) return
- viewModelScope.launch {
- persistPlaybackCompletion()
- if (currentContentType == ContentType.SERIES_EPISODE) {
- val position = playerEngine.currentPosition.value
- val duration = playerEngine.duration.value
- if (position > MIN_WATCHED_FOR_AUTO_PLAY_MS || duration > 0L) {
- val next = _nextEpisode.value ?: return@launch
- if (autoPlayNextEpisodeEnabled) {
- startAutoPlayCountdown(next)
- }
- }
- }
- }
- }
-
- private fun startAutoPlayCountdown(episode: Episode) {
- autoPlayCountdownJob?.cancel()
- autoPlayCountdownJob = viewModelScope.launch {
- for (remaining in AUTO_PLAY_COUNTDOWN_SECONDS downTo 1) {
- _autoPlayCountdown.value = AutoPlayCountdownUiState(
- episode = episode,
- secondsRemaining = remaining
- )
- delay(1_000L)
- }
- _autoPlayCountdown.value = null
- playEpisode(episode, showResumePrompt = false)
- }
- }
-
- fun cancelAutoPlay() {
- autoPlayCountdownJob?.cancel()
- autoPlayCountdownJob = null
- _autoPlayCountdown.value = null
- }
-
- fun playNextEpisodeNow() {
- val episode = _autoPlayCountdown.value?.episode ?: _nextEpisode.value ?: return
- cancelAutoPlay()
- playEpisode(episode, showResumePrompt = false)
- }
-
- private fun currentPlaybackIdentityUrl(): String =
- currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
+ ): PlaybackHistory? = buildPlaybackHistorySnapshot(
+ positionMs = positionMs,
+ durationMs = durationMs,
+ currentContentId = currentContentId,
+ currentProviderId = currentProviderId,
+ currentContentType = currentContentType,
+ currentTitle = currentTitle,
+ currentArtworkUrl = currentArtworkUrl,
+ currentStreamUrl = currentStreamUrl,
+ currentSeriesId = currentSeriesId,
+ currentEpisode = _currentEpisode.value,
+ currentSeasonNumber = currentSeasonNumber,
+ currentEpisodeNumber = currentEpisodeNumber
+ )
internal fun isActivePlaybackSession(
requestVersion: Long,
expectedLogicalUrl: String? = null
- ): Boolean {
- if (requestVersion != prepareRequestVersion) return false
- val expectedUrl = expectedLogicalUrl?.takeIf { it.isNotBlank() } ?: return true
- val activeUrl = currentPlaybackIdentityUrl()
- return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl == expectedUrl
- }
+ ): Boolean = matchesActivePlaybackSession(
+ requestVersion = requestVersion,
+ activeRequestVersion = prepareRequestVersion,
+ expectedLogicalUrl = expectedLogicalUrl,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ currentStreamUrl = currentStreamUrl
+ )
internal fun requestEpg(
providerId: Long,
@@ -1376,7 +1022,12 @@ class PlayerViewModel @Inject constructor(
false
} else {
currentResolvedPlaybackUrl = session.streamInfo.url
- probePassedPlaybackKeys.add(playbackProbeCacheKey(session.streamInfo.url))
+ probePassedPlaybackKeys.add(
+ resolvePlaybackProbeCacheKey(
+ currentStreamUrl = currentStreamUrl,
+ url = session.streamInfo.url
+ )
+ )
playerEngine.play()
startTokenRenewalMonitoring(session.streamInfo.expirationTime)
maybeStartLiveTimeshift(session.streamInfo)
@@ -1424,7 +1075,12 @@ class PlayerViewModel @Inject constructor(
)
return false
}
- probePassedPlaybackKeys.add(playbackProbeCacheKey(streamInfo.url))
+ probePassedPlaybackKeys.add(
+ resolvePlaybackProbeCacheKey(
+ currentStreamUrl = currentStreamUrl,
+ url = streamInfo.url
+ )
+ )
applyPlaybackPreferences()
if (!isActivePlaybackSession(requestVersion)) return false
currentResolvedPlaybackUrl = streamInfo.url
@@ -1451,25 +1107,7 @@ class PlayerViewModel @Inject constructor(
}
.build()
okHttpClient.newCall(request).execute().use { response ->
- when (response.code) {
- 401, 403 -> PlaybackProbeFailure(
- message = "This provider stream was rejected (${response.code} Unauthorized/Forbidden).",
- recoveryType = PlayerRecoveryType.SOURCE
- )
- 456 -> PlaybackProbeFailure(
- message = "This provider rejected playback for this channel (HTTP 456). The MAC or subscription may not have access to this stream.",
- recoveryType = PlayerRecoveryType.SOURCE
- )
- 404 -> PlaybackProbeFailure(
- message = "This provider stream is unavailable right now (404).",
- recoveryType = PlayerRecoveryType.SOURCE
- )
- in 500..599 -> PlaybackProbeFailure(
- message = "The provider returned a server error for this stream (${response.code}).",
- recoveryType = PlayerRecoveryType.NETWORK
- )
- else -> null
- }
+ resolvePlaybackProbeFailure(response.code)
}
}
}.getOrNull()
@@ -1479,7 +1117,10 @@ class PlayerViewModel @Inject constructor(
if (!url.startsWith("http://") && !url.startsWith("https://")) return false
val providerId = currentProviderId.takeIf { it > 0L } ?: return false
val provider = providerRepository.getProvider(providerId) ?: return false
- val cacheKey = playbackProbeCacheKey(url)
+ val cacheKey = resolvePlaybackProbeCacheKey(
+ currentStreamUrl = currentStreamUrl,
+ url = url
+ )
if (provider.type != com.streamvault.domain.model.ProviderType.STALKER_PORTAL && cacheKey in probePassedPlaybackKeys) {
return false
}
@@ -1490,9 +1131,6 @@ class PlayerViewModel @Inject constructor(
(xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) || xtreamStreamUrlResolver.isInternalStreamUrl(url))
}
- private fun playbackProbeCacheKey(url: String): String =
- currentStreamUrl.takeIf { it.isNotBlank() } ?: url
-
fun prepare(
streamUrl: String,
epgChannelId: String?,
@@ -1519,70 +1157,23 @@ class PlayerViewModel @Inject constructor(
archiveEndMs > archiveStartMs &&
try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE } == ContentType.LIVE
val requestVersion = beginPlaybackSession()
- val previousProviderId = currentProviderId
- val previousCategoryId = currentCategoryId
- val previousCombinedProfileId = currentCombinedProfileId
- val previousCombinedSourceFilterProviderId = currentCombinedSourceFilterProviderId
- val shouldReloadPlaylist = categoryId != -1L &&
- (
- categoryId != previousCategoryId ||
- providerId != previousProviderId ||
- combinedProfileId != previousCombinedProfileId ||
- combinedSourceFilterProviderId != previousCombinedSourceFilterProviderId
- )
- clearSeekPreview()
- currentResolvedPlaybackUrl = ""
- currentStreamUrl = streamUrl
- currentContentId = internalChannelId
- currentTitle = title
- playbackTitleFlow.value = title
- currentArtworkUrl = artworkUrl
- currentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }
- currentProviderId = providerId
- currentCombinedProfileId = combinedProfileId?.takeIf { it > 0L }
- currentCombinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L }
- currentSeriesId = seriesId?.takeIf { it > 0L }
- currentSeasonNumber = seasonNumber
- currentEpisodeNumber = episodeNumber
- currentStreamClassLabel = if (hasArchiveRequest) "Catch-up" else "Primary"
- applyDefaultPlaybackTimersIfNeeded()
- if (currentContentType == ContentType.LIVE && currentCombinedProfileId != null) {
- val activeCombinedProfileId = currentCombinedProfileId
- viewModelScope.launch {
- val members = activeCombinedProfileId?.let { combinedM3uRepository.getProfile(it)?.members }.orEmpty()
- if (currentCombinedProfileId == activeCombinedProfileId) {
- currentCombinedProfileMembers = members
- }
- }
- } else {
- currentCombinedProfileMembers = emptyList()
- combinedCategoriesById = emptyMap()
- }
- if (!hasArchiveRequest) {
- pendingCatchUpUrls = emptyList()
- }
- if (currentContentType != ContentType.SERIES_EPISODE || providerId <= 0 || currentSeriesId == null) {
- clearSeriesEpisodeContext()
- }
- if (currentContentType != ContentType.LIVE) {
- lastRecordedLivePlaybackKey = null
- recentChannelsJob?.cancel()
- recentChannelsFlow.value = emptyList()
- lastVisitedCategoryJob?.cancel()
- _lastVisitedCategory.value = null
- playerEngine.stopLiveTimeshift()
- }
- hasRetriedWithSoftwareDecoder = false
- playerEngine.setDecoderMode(preferredDecoderMode)
- playerEngine.setSurfaceMode(preferredSurfaceMode)
- updateDecoderMode(preferredDecoderMode)
- updateStreamClass(currentStreamClassLabel)
-
- // Reset tried streams for manual switch
- triedAlternativeStreams.clear()
- if (!hasArchiveRequest) {
- triedAlternativeStreams.add(streamUrl)
- }
+ val shouldReloadPlaylist = applyPrepareSessionState(
+ streamUrl = streamUrl,
+ internalChannelId = internalChannelId,
+ categoryId = categoryId,
+ providerId = providerId,
+ combinedProfileId = combinedProfileId,
+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,
+ contentType = contentType,
+ title = title,
+ artworkUrl = artworkUrl,
+ seriesId = seriesId,
+ seasonNumber = seasonNumber,
+ episodeNumber = episodeNumber,
+ hasArchiveRequest = hasArchiveRequest,
+ preferredDecoderMode = preferredDecoderMode,
+ preferredSurfaceMode = preferredSurfaceMode
+ )
if (!hasArchiveRequest) {
viewModelScope.launch {
@@ -1684,1596 +1275,125 @@ class PlayerViewModel @Inject constructor(
_playerDiagnostics.update { it.copy(providerName = "", providerSourceLabel = "") }
}
- // Load playlist if context changed
- if (shouldReloadPlaylist) {
- currentCategoryId = categoryId
- activeCategoryIdFlow.value = categoryId
- isVirtualCategory = isVirtual
- loadPlaylist(categoryId, providerId, isVirtual, internalChannelId)
- } else {
- // If playlist already loaded, just update index
- if (channelList.isNotEmpty() && internalChannelId != -1L) {
- currentChannelIndex = channelList.indexOfFirst { it.id == internalChannelId }
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == streamUrl }
- }
- }
- }
-
- if (currentContentType == ContentType.LIVE && hasArchiveRequest) {
- playerEngine.stopLiveTimeshift()
- viewModelScope.launch {
- val catchUpUrls = try {
- providerRepository.buildCatchUpUrls(
- providerId = currentProviderId,
- streamId = currentContentId,
- start = archiveStartMs / 1000L,
- end = archiveEndMs / 1000L
- )
- } catch (e: CredentialDecryptionException) {
- if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
- showPlayerNotice(
- message = e.message ?: CredentialDecryptionException.MESSAGE,
- recoveryType = PlayerRecoveryType.SOURCE
- )
- return@launch
- }
- if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- if (catchUpUrls.isNotEmpty()) {
- startCatchUpPlayback(
- urls = catchUpUrls,
- title = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle,
- recoveryAction = "Opened catch-up stream",
- requestVersionOverride = requestVersion
- )
- } else {
- val reason = resolveCatchUpFailureMessage(currentChannelFlow.value, archiveRequested = true, programHasArchive = true)
- setLastFailureReason(reason)
- showPlayerNotice(
- message = reason,
- recoveryType = PlayerRecoveryType.CATCH_UP,
- actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
- )
- }
- }
- }
+ finalizePreparedPlaybackContext(
+ requestVersion = requestVersion,
+ streamUrl = streamUrl,
+ providerId = providerId,
+ categoryId = categoryId,
+ isVirtual = isVirtual,
+ internalChannelId = internalChannelId,
+ epgChannelId = epgChannelId,
+ shouldReloadPlaylist = shouldReloadPlaylist,
+ hasArchiveRequest = hasArchiveRequest,
+ archiveStartMs = archiveStartMs,
+ archiveEndMs = archiveEndMs,
+ archiveTitle = archiveTitle
+ )
+ }
- // Fetch EPG if ID provided
- if (currentContentType == ContentType.LIVE) {
- requestEpg(
- providerId = currentProviderId,
- epgChannelId = epgChannelId,
- internalChannelId = internalChannelId
- )
- } else {
- requestEpg(providerId = -1L, epgChannelId = null)
- }
- observeRecentChannels()
- observeLastVisitedCategory()
-
- // Load Aspect Ratio safely (fallback to FIT if none saved)
- aspectRatioJob?.cancel()
- _aspectRatio.value = AspectRatio.FIT
- if (internalChannelId != -1L) {
- aspectRatioJob = viewModelScope.launch {
- preferencesRepository.getAspectRatioForChannel(internalChannelId).collect { savedRatio ->
- _aspectRatio.value = try {
- savedRatio?.let { AspectRatio.valueOf(it) } ?: AspectRatio.FIT
- } catch (e: Exception) {
- AspectRatio.FIT
- }
- }
- }
-
- // Fetch Channel for tracking alternative streams (video qualities)
- viewModelScope.launch {
- val channel = channelRepository.getChannel(internalChannelId)
- if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- currentChannelFlow.value = channel
- refreshCurrentChannelRecording()
- if (channel != null) {
- currentTitle = channel.name.ifBlank { currentTitle }
- playbackTitleFlow.value = currentTitle
- currentStreamUrl = if (currentStreamClassLabel == "Catch-up") currentStreamUrl else channel.streamUrl
- updateStreamClass(
- when {
- currentStreamClassLabel == "Catch-up" -> "Catch-up"
- streamUrl == channel.streamUrl -> "Primary"
- channel.alternativeStreams.contains(streamUrl) -> "Alternate"
- else -> "Direct"
- }
- )
- if (currentContentType == ContentType.LIVE) {
- recordLivePlayback(channel)
- requestEpg(
- providerId = currentProviderId,
- epgChannelId = channel.epgChannelId,
- streamId = channel.streamId,
- internalChannelId = channel.id
- )
- }
- updateChannelDiagnostics(channel)
- }
- }
- }
+ internal fun applyProgramTimeline(programs: List<Program>, now: Long) {
+ val timeline = buildProgramTimeline(
+ programs = programs,
+ now = now,
+ catchUpSupported = currentChannelFlow.value?.catchUpSupported == true,
+ maxHistoryItems = MAX_PROGRAM_HISTORY_ITEMS,
+ maxUpcomingItems = MAX_UPCOMING_PROGRAM_ITEMS
+ )
+ _currentProgram.value = timeline.currentProgram
+ _nextProgram.value = timeline.nextProgram
+ _programHistory.value = timeline.programHistory
+ _upcomingPrograms.value = timeline.upcomingPrograms
+ }
- // 2. Start Progress Tracking for VODs
- startProgressTracking()
+ internal fun clearEpgState() {
+ _currentProgram.value = null
+ _nextProgram.value = null
+ _programHistory.value = emptyList()
+ _upcomingPrograms.value = emptyList()
}
- private fun startProgressTracking() {
- progressTrackingJob?.cancel()
- if (currentContentType == ContentType.LIVE) return
+ // Store current URL to find index later
+ internal var currentStreamUrl: String = ""
- progressTrackingJob = viewModelScope.launch {
- while (true) {
- delay(5000) // Track every 5 seconds
- if (!isAppInForeground || !playerEngine.isPlaying.value) continue
- persistPlaybackProgress()
- }
- }
+ private fun resolveCurrentLiveChannelIndex(): Int {
+ currentChannelIndex = resolveLiveChannelIndex(
+ channelList = channelList,
+ currentChannelIndex = currentChannelIndex,
+ currentContentId = currentContentId,
+ currentStreamUrl = currentStreamUrl
+ )
+ return currentChannelIndex
}
- private suspend fun persistPlaybackProgress() {
- val pos = playerEngine.currentPosition.value
- val dur = playerEngine.duration.value
+ internal fun wrappedChannelIndex(offset: Int): Int {
+ val resolvedIndex = resolveCurrentLiveChannelIndex()
+ return computeWrappedChannelIndex(
+ resolvedIndex = resolvedIndex,
+ channelCount = channelList.size,
+ offset = offset
+ )
+ }
- if (pos > 0 && dur > 0) {
- val history = buildPlaybackHistorySnapshot(pos, dur) ?: return
- logRepositoryFailure(
- operation = "Persist playback resume position",
- result = playbackHistoryRepository.updateResumePosition(history)
- )
- watchNextManager.refreshWatchNext()
- launcherRecommendationsManager.refreshRecommendations()
- }
+ internal fun markStreamFailure(streamUrl: String) {
+ if (streamUrl.isBlank()) return
+ failedStreamsThisSession[streamUrl] = (failedStreamsThisSession[streamUrl] ?: 0) + 1
}
- private fun startTokenRenewalMonitoring(expirationTime: Long?) {
- tokenRenewalJob?.cancel()
- tokenRenewalJob = null
- val expiry = expirationTime?.takeIf { it > 0L } ?: return
- val requestVersion = prepareRequestVersion
- tokenRenewalJob = viewModelScope.launch {
- while (true) {
- delay(TOKEN_RENEWAL_CHECK_INTERVAL_MS)
- if (!playerEngine.isPlaying.value) continue
- val remaining = expiry - System.currentTimeMillis()
- if (remaining > TOKEN_RENEWAL_LEAD_MS) continue
- if (!isActivePlaybackSession(requestVersion)) return@launch
- val refreshed = resolvePlaybackStreamInfo(
- logicalUrl = currentStreamUrl,
- internalContentId = currentContentId,
- providerId = currentProviderId,
- contentType = currentContentType
- ) ?: return@launch
- if (!isActivePlaybackSession(requestVersion)) return@launch
- currentResolvedPlaybackUrl = refreshed.url
- playerEngine.renewStreamUrl(refreshed)
- startTokenRenewalMonitoring(refreshed.expirationTime)
- return@launch
- }
- }
+ internal fun updateDecoderMode(mode: DecoderMode) {
+ _playerDiagnostics.update { it.copy(decoderMode = mode) }
}
- fun onAppBackgrounded() {
- if (!isAppInForeground) return
- isAppInForeground = false
- shouldResumeAfterForeground = playerEngine.isPlaying.value
- if (shouldResumeAfterForeground) {
- playerEngine.pause()
- }
- if (currentContentType != ContentType.LIVE) {
- viewModelScope.launch {
- persistPlaybackProgress()
- playbackHistoryRepository.flushPendingProgress()
- }
- }
+ internal fun updateStreamClass(label: String) {
+ currentStreamClassLabel = label
+ _isCatchUpPlayback.value = (label == "Catch-up")
+ _playerDiagnostics.update { it.copy(streamClassLabel = label) }
}
- fun onAppForegrounded() {
- if (isAppInForeground) return
- isAppInForeground = true
- if (shouldResumeAfterForeground && !_resumePrompt.value.show) {
- playerEngine.play()
+ internal fun updateChannelDiagnostics(channel: com.streamvault.domain.model.Channel) {
+ _playerDiagnostics.update { currentState ->
+ updateChannelDiagnosticsState(
+ currentState = currentState,
+ channel = channel
+ )
}
- shouldResumeAfterForeground = false
}
- fun onPlayerScreenDisposed() {
- if (currentContentType != ContentType.LIVE) {
- viewModelScope.launch {
- persistPlaybackProgress()
- playbackHistoryRepository.flushPendingProgress()
- }
- }
- playerEngine.stopLiveTimeshift()
- clearPlaybackTimers()
+ internal fun setLastFailureReason(message: String?) {
+ _playerDiagnostics.update { it.copy(lastFailureReason = message?.takeIf { reason -> reason.isNotBlank() }) }
}
- fun handOffPlaybackToMultiView() {
- if (currentContentType != ContentType.LIVE) {
- viewModelScope.launch { persistPlaybackProgress() }
+ internal fun appendRecoveryAction(action: String) {
+ if (action.isBlank()) return
+ _playerDiagnostics.update { state ->
+ state.copy(recentRecoveryActions = (listOf(action) + state.recentRecoveryActions).distinct().take(5))
}
- playerEngine.stopLiveTimeshift()
- livePreviewHandoffManager.clear(playerEngine)
- playerEngine.release()
}
- private fun fetchEpg(
- providerId: Long,
- internalChannelId: Long,
- epgChannelId: String?,
- streamId: Long = 0L
- ) {
- epgJob?.cancel()
- if (providerId <= 0L || (internalChannelId <= 0L && epgChannelId == null && streamId <= 0L)) {
- clearEpgState()
- return
- }
-
- val requestKey = EpgRequestKey(
- providerId = providerId,
- internalChannelId = internalChannelId,
- epgChannelId = epgChannelId,
- streamId = streamId
- )
-
- epgJob = viewModelScope.launch {
- while (true) {
- val now = System.currentTimeMillis()
- val start = now - (24 * 60 * 60 * 1000L)
- val end = now + (6 * 60 * 60 * 1000L)
- val programs = epgRepository.getResolvedProgramsForPlaybackChannel(
- providerId = providerId,
- internalChannelId = internalChannelId,
- epgChannelId = epgChannelId,
- streamId = streamId,
- startTime = start,
- endTime = end
- )
-
- if (activeEpgRequestKey != requestKey) return@launch
-
- if (programs.isNotEmpty()) {
- applyProgramTimeline(programs, now)
- } else {
- applyRemoteProgramFallback(providerId, epgChannelId, streamId, now)
- if (activeEpgRequestKey != requestKey) return@launch
- }
-
- delay(PLAYER_EPG_REFRESH_INTERVAL_MS)
- }
- }
- }
-
- private fun applyProgramTimeline(programs: List<Program>, now: Long) {
- val catchUpSupported = currentChannelFlow.value?.catchUpSupported == true
- val sortedPrograms = programs.sortedBy { it.startTime }
- val current = sortedPrograms.firstOrNull { it.startTime <= now && it.endTime > now }
- _currentProgram.value = current
- _nextProgram.value = sortedPrograms.firstOrNull { it.startTime > now }
- _programHistory.value = sortedPrograms
- .filter { it.endTime <= now && (it.hasArchive || catchUpSupported) }
- .sortedByDescending { it.startTime }
- .take(MAX_PROGRAM_HISTORY_ITEMS)
- _upcomingPrograms.value = sortedPrograms
- .filter { it.endTime > now || it == current }
- .sortedBy { it.startTime }
- .take(MAX_UPCOMING_PROGRAM_ITEMS)
- }
-
- private suspend fun applyRemoteProgramFallback(
- providerId: Long,
- epgChannelId: String?,
- streamId: Long,
- now: Long
- ) {
- if (streamId <= 0L) {
- clearEpgState()
- return
- }
-
- val result = providerRepository.getProgramsForLiveStream(
- providerId = providerId,
- streamId = streamId,
- epgChannelId = epgChannelId,
- limit = 12
- )
- val programs = (result as? com.streamvault.domain.model.Result.Success)?.data
- ?.sortedBy { it.startTime }
- .orEmpty()
-
- if (programs.isEmpty()) {
- clearEpgState()
- return
- }
-
- applyProgramTimeline(programs, now)
- }
-
- private fun clearEpgState() {
- _currentProgram.value = null
- _nextProgram.value = null
- _programHistory.value = emptyList()
- _upcomingPrograms.value = emptyList()
- }
-
- internal fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {
- playlistJob?.cancel()
- playlistJob = viewModelScope.launch {
- val flows = currentCombinedProfileId?.let { profileId ->
- observeCombinedLivePlaylist(profileId, categoryId)
- } ?: if (isVirtual) {
- if (categoryId == VirtualCategoryIds.RECENT) {
- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)
- .map { history ->
- history.asSequence()
- .filter { it.contentType == ContentType.LIVE }
- .sortedByDescending { it.lastWatchedAt }
- .distinctBy { it.contentId }
- .map { it.contentId }
- .toList()
- }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
- unsorted.orderedByRequestedRawIds(ids)
- }
- }
- } else if (categoryId == VirtualCategoryIds.FAVORITES) {
- // Global Favorites — preserve user-defined position order
- favoriteRepository.getFavorites(currentProviderId, com.streamvault.domain.model.ContentType.LIVE)
- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
- unsorted.orderedByRequestedRawIds(ids)
- }
- }
- } else {
- val groupId = if (categoryId < 0) -categoryId else categoryId
- favoriteRepository.getFavoritesByGroup(groupId)
- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
- unsorted.orderedByRequestedRawIds(ids)
- }
- }
- }
- } else {
- channelRepository.getChannelsByNumber(providerId, categoryId)
- }
-
- combine(flows, preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->
- val displayedChannels = when (numberingMode) {
- ChannelNumberingMode.GROUP -> channels.mapIndexed { index, channel ->
- channel.copy(number = index + 1)
- }
- ChannelNumberingMode.PROVIDER -> channels
- ChannelNumberingMode.HIDDEN -> channels.map { it.copy(number = 0) }
- }
- numberingMode to displayedChannels.sanitizedChannelsForPlayer()
- }.collect { (numberingMode, displayedChannels) ->
- channelNumberingMode = numberingMode
- channelList = displayedChannels
- currentChannelFlowList.value = displayedChannels
- // Recalculate index based on current content ID (keeps overlay correct after zap/auto-revert)
- val targetId = if (currentContentId != -1L) currentContentId else initialChannelId
- if (targetId != -1L) {
- currentChannelIndex = channelList.indexOfFirst { it.id == targetId }
- }
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
- }
-
- if (currentChannelIndex != -1) {
- currentChannelFlow.value = channelList[currentChannelIndex].sanitizedForPlayer()
- refreshCurrentChannelRecording()
- val ch = channelList[currentChannelIndex]
- displayChannelNumberFlow.value = resolveChannelNumber(ch, currentChannelIndex)
- } else if (displayedChannels.isNotEmpty() && currentContentId != -1L) {
- // Channel was removed from the provider playlist
- showPlayerNotice(
- message = "Channel not found in current playlist",
- recoveryType = PlayerRecoveryType.SOURCE,
- actions = listOf(PlayerNoticeAction.OPEN_GUIDE)
- )
- }
- }
- }
- }
-
- // Store current URL to find index later
- internal var currentStreamUrl: String = ""
-
- private fun observeCombinedLivePlaylist(profileId: Long, categoryId: Long): Flow<List<com.streamvault.domain.model.Channel>> = when {
- categoryId == ChannelRepository.ALL_CHANNELS_ID -> {
- combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
- combinedCategoriesById = combinedCategories.associateBy { it.category.id }
- val flows = combinedCategories.map { combinedM3uRepository.getCombinedChannels(profileId, it) }
- if (flows.isEmpty()) {
- flowOf(emptyList())
- } else {
- combine(flows) { arrays ->
- arrays.toList().flatMap { it }
- }.map(::applyCombinedSourceProviderFilter)
- }
- }
- }
-
- categoryId == VirtualCategoryIds.RECENT -> {
- combinedProviderIdsFlow(profileId)
- .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 24) }
- .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
- }
-
- categoryId == VirtualCategoryIds.FAVORITES -> {
- combinedProviderIdsFlow(profileId)
- .flatMapLatest { providerIds -> observeLiveFavorites(effectiveCombinedProviderIds(providerIds)) }
- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
- .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
- }
-
- categoryId < 0L -> {
- favoriteRepository.getFavoritesByGroup(-categoryId)
- .map { favorites ->
- favorites
- .sortedBy { it.position }
- .let { groupFavorites ->
- currentCombinedSourceFilterProviderId?.let { selectedProviderId ->
- groupFavorites.filter { it.providerId == selectedProviderId }
- } ?: groupFavorites
- }
- .map { it.contentId }
- }
- .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
- }
-
- else -> {
- combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
- combinedCategoriesById = combinedCategories.associateBy { it.category.id }
- val combinedCategory = combinedCategoriesById[categoryId]
- if (combinedCategory == null) {
- flowOf(emptyList())
- } else {
- combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)
- .map(::applyCombinedSourceProviderFilter)
- }
- }
- }
- }
-
- private fun applyCombinedSourceProviderFilter(channels: List<com.streamvault.domain.model.Channel>): List<com.streamvault.domain.model.Channel> {
- val selectedProviderId = currentCombinedSourceFilterProviderId ?: return channels
- return channels.filter { it.providerId == selectedProviderId }
- }
-
- private fun loadLiveChannelsByOrderedIds(ids: List<Long>, providerId: Long? = null): Flow<List<com.streamvault.domain.model.Channel>> =
- if (ids.isEmpty()) {
- flowOf(emptyList())
- } else {
- channelRepository.getChannelsByIds(ids).map { unsorted ->
- val filtered = providerId?.let { requiredProviderId ->
- unsorted.filter { it.providerId == requiredProviderId }
- } ?: unsorted
- filtered.orderedByRequestedRawIds(ids)
- }
- }
-
- private fun combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {
- emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())
- }.map { members ->
- currentCombinedProfileMembers = members
- members.filter { it.enabled }.map { it.providerId }
- }
-
- private fun effectiveCombinedProviderIds(providerIds: List<Long>): List<Long> =
- currentCombinedSourceFilterProviderId?.let { selectedProviderId ->
- providerIds.filter { it == selectedProviderId }
- } ?: providerIds
-
- private fun observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {
- 0 -> flowOf(emptyList())
- 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)
- else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)
- }
-
- private fun observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {
- 0 -> flowOf(emptyList())
- 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)
- .map { history ->
- history.asSequence()
- .filter { it.contentType == ContentType.LIVE }
- .sortedByDescending { it.lastWatchedAt }
- .distinctBy { it.contentId }
- .map { it.contentId }
- .take(limit)
- .toList()
- }
- else -> combine(providerIds.map { providerId ->
- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)
- }) { histories ->
- histories.toList()
- .flatMap { it }
- .asSequence()
- .filter { it.contentType == ContentType.LIVE }
- .sortedByDescending { it.lastWatchedAt }
- .distinctBy { it.providerId to it.contentId }
- .map { it.contentId }
- .take(limit)
- .toList()
- }
- }
-
- private fun observeRecentChannels() {
- recentChannelsJob?.cancel()
- if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {
- recentChannelsFlow.value = emptyList()
- return
- }
-
- recentChannelsJob = viewModelScope.launch {
- val recentFlow = currentCombinedProfileId?.let { profileId ->
- combinedProviderIdsFlow(profileId)
- .flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 12) }
- .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
- } ?: playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)
- .map { history ->
- history.asSequence()
- .filter { it.contentType == ContentType.LIVE }
- .sortedByDescending { it.lastWatchedAt }
- .distinctBy { it.contentId }
- .map { it.contentId }
- .toList()
- }
- .flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids) }
-
- combine(
- recentFlow,
- preferencesRepository.liveChannelNumberingMode
- ) { channels, numberingMode ->
- numberingMode to channels
- }.collect { (numberingMode, channels) ->
- channelNumberingMode = numberingMode
- val currentListNumbers = channelList.withIndex().associate { (index, channel) ->
- channel.id to resolveChannelNumber(channel, index)
- }
- recentChannelsFlow.value = channels
- .filterNot { it.id == currentContentId }
- .map { channel ->
- currentListNumbers[channel.id]?.let { number ->
- channel.copy(number = number)
- } ?: channel
- }
- }
- }
- }
-
- private fun observeLastVisitedCategory() {
- lastVisitedCategoryJob?.cancel()
- if (currentContentType != ContentType.LIVE || (currentProviderId <= 0 && currentCombinedProfileId == null)) {
- _lastVisitedCategory.value = null
- return
- }
-
- lastVisitedCategoryJob = viewModelScope.launch {
- val categoriesFlow = currentCombinedProfileId?.let { profileId ->
- combinedProviderIdsFlow(profileId).flatMapLatest { providerIds ->
- combine(
- combinedM3uRepository.getCombinedCategories(profileId),
- getCustomCategories(providerIds, ContentType.LIVE)
- ) { combinedCategories, customCategories ->
- combinedCategoriesById = combinedCategories.associateBy { it.category.id }
- buildList {
- val favoritesCategory = customCategories.find { it.id == VirtualCategoryIds.FAVORITES }
- if (favoritesCategory != null) {
- add(favoritesCategory)
- }
- add(
- Category(
- id = VirtualCategoryIds.RECENT,
- name = "Recent",
- type = ContentType.LIVE,
- isVirtual = true,
- count = 0
- )
- )
- addAll(customCategories.filter { it.id != VirtualCategoryIds.FAVORITES })
- add(
- Category(
- id = ChannelRepository.ALL_CHANNELS_ID,
- name = "All Channels",
- type = ContentType.LIVE,
- count = combinedCategories.sumOf { it.category.count }
- )
- )
- addAll(combinedCategories.map { it.category })
- } to null
- }
- }
- } ?: combine(
- channelRepository.getCategories(currentProviderId),
- getCustomCategories(currentProviderId, ContentType.LIVE),
- preferencesRepository.getLastLiveCategoryId(currentProviderId)
- ) { providerCategories, customCategories, lastVisitedCategoryId ->
- val allCategories = customCategories + providerCategories
- val lastVisited = if (lastVisitedCategoryId == null || lastVisitedCategoryId == VirtualCategoryIds.RECENT) {
- null
- } else {
- allCategories.firstOrNull { it.id == lastVisitedCategoryId }
- }
- allCategories to lastVisited
- }
-
- categoriesFlow.collect { (allCategories, lastVisited) ->
- availableCategoriesFlow.value = allCategories
- _lastVisitedCategory.value = lastVisited
- }
- }
- }
-
- fun openLastVisitedCategory() {
- val category = _lastVisitedCategory.value ?: return
- if (currentContentType != ContentType.LIVE) return
-
- currentCategoryId = category.id
- activeCategoryIdFlow.value = category.id
- isVirtualCategory = category.isVirtual
- loadPlaylist(
- categoryId = category.id,
- providerId = currentProviderId,
- isVirtual = category.isVirtual,
- initialChannelId = currentContentId
- )
- openChannelListOverlay()
- }
-
- private fun resolveCurrentLiveChannelIndex(): Int {
- if (channelList.isEmpty()) return -1
-
- val currentIndexMatchesChannel = currentChannelIndex in channelList.indices && run {
- val currentChannel = channelList[currentChannelIndex]
- currentChannel.id == currentContentId || currentChannel.streamUrl == currentStreamUrl
- }
- if (currentIndexMatchesChannel) {
- return currentChannelIndex
- }
-
- currentChannelIndex = when {
- currentContentId > 0 -> channelList.indexOfFirst { it.id == currentContentId }
- else -> -1
- }
-
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
- }
-
- return currentChannelIndex
- }
-
- internal fun wrappedChannelIndex(offset: Int): Int {
- val resolvedIndex = resolveCurrentLiveChannelIndex()
- if (resolvedIndex == -1) return -1
- val size = channelList.size
- return ((resolvedIndex + offset) % size + size) % size
- }
-
- private fun classifyPlaybackError(error: PlayerError): PlayerRecoveryType = when (error) {
- is PlayerError.NetworkError -> {
- if (error.message.contains("timeout", ignoreCase = true)) {
- PlayerRecoveryType.BUFFER_TIMEOUT
- } else if (
- error.message.contains("HTTP 456", ignoreCase = true) ||
- error.message.contains("access denied", ignoreCase = true)
- ) {
- PlayerRecoveryType.SOURCE
- } else {
- PlayerRecoveryType.NETWORK
- }
- }
- is PlayerError.SourceError -> PlayerRecoveryType.SOURCE
- is PlayerError.DecoderError -> PlayerRecoveryType.DECODER
- is PlayerError.DrmError -> PlayerRecoveryType.DRM
- is PlayerError.UnknownError -> {
- if (error.message.contains("timeout", ignoreCase = true)) {
- PlayerRecoveryType.BUFFER_TIMEOUT
- } else {
- PlayerRecoveryType.UNKNOWN
- }
- }
- }
-
- private fun resolvePlaybackErrorMessage(error: PlayerError): String = when (classifyPlaybackError(error)) {
- PlayerRecoveryType.NETWORK -> "This stream is not responding right now. You can retry or try another source."
- PlayerRecoveryType.SOURCE -> when {
- error.message.contains("HTTP 456", ignoreCase = true) ||
- error.message.contains("access denied", ignoreCase = true) ->
- "This provider rejected playback for this channel. The MAC or subscription may not have access to this stream."
- else -> "We couldn't start this stream on the available paths."
- }
- PlayerRecoveryType.DECODER -> "This stream could not play in the current decoder mode."
- PlayerRecoveryType.DRM -> "Playback requires valid DRM credentials or a supported device security level."
- PlayerRecoveryType.BUFFER_TIMEOUT -> "Playback stayed stuck buffering for too long on this stream."
- PlayerRecoveryType.CATCH_UP -> "Replay is unavailable for the selected program."
- PlayerRecoveryType.UNKNOWN -> error.message.ifBlank { "Playback failed for an unknown reason." }
- }
-
- private fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> {
- val actions = mutableListOf(PlayerNoticeAction.RETRY)
- if (hasAlternateStream()) {
- actions += PlayerNoticeAction.ALTERNATE_STREAM
- }
- if (hasLastChannel()) {
- actions += PlayerNoticeAction.LAST_CHANNEL
- }
- if (recoveryType == PlayerRecoveryType.CATCH_UP && currentContentType == ContentType.LIVE) {
- actions += PlayerNoticeAction.OPEN_GUIDE
- }
- return actions
- }
-
- private fun markStreamFailure(streamUrl: String) {
- if (streamUrl.isBlank()) return
- failedStreamsThisSession[streamUrl] = (failedStreamsThisSession[streamUrl] ?: 0) + 1
- }
-
- private fun updateDecoderMode(mode: DecoderMode) {
- _playerDiagnostics.update { it.copy(decoderMode = mode) }
- }
-
- internal fun updateStreamClass(label: String) {
- currentStreamClassLabel = label
- _isCatchUpPlayback.value = (label == "Catch-up")
- _playerDiagnostics.update { it.copy(streamClassLabel = label) }
- }
-
- private fun updateChannelDiagnostics(channel: com.streamvault.domain.model.Channel) {
- val archiveLabel = when {
- channel.catchUpSupported && (channel.streamId > 0L || !channel.catchUpSource.isNullOrBlank()) ->
- "Catch-up supported (${channel.catchUpDays} days)"
- channel.catchUpSupported ->
- "Provider advertises catch-up, but replay metadata is incomplete."
- else -> "No archive support advertised"
- }
- val hints = buildList {
- if (channel.errorCount > 0) {
- add("This channel has failed ${channel.errorCount} time(s) recently.")
- }
- if (channel.alternativeStreams.isNotEmpty()) {
- add("${channel.alternativeStreams.size} alternate stream path(s) available.")
- }
- if (channel.catchUpSupported && channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank()) {
- add("Replay may fail because this provider did not expose a catch-up template.")
- }
- }
- _playerDiagnostics.update {
- it.copy(
- alternativeStreamCount = channel.alternativeStreams.size,
- channelErrorCount = channel.errorCount,
- archiveSupportLabel = archiveLabel,
- troubleshootingHints = hints.take(4)
- )
- }
- }
-
- private suspend fun tryRefreshXtreamPlaybackAfterAuthError(
- error: PlayerError,
- requestVersion: Long,
- playbackUrl: String
- ): Boolean {
- if (hasRetriedXtreamAuthRefresh) return false
- if (error !is PlayerError.NetworkError) return false
- if (!isAuthExpiryPlaybackError(error.message)) return false
- if (!isXtreamPlaybackSession()) return false
-
- val refreshedStreamInfo = resolvePlaybackStreamInfo(
- logicalUrl = currentStreamUrl,
- internalContentId = currentContentId,
- providerId = currentProviderId,
- contentType = currentContentType
- ) ?: return false
-
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return false
-
- hasRetriedXtreamAuthRefresh = true
- probePassedPlaybackKeys.remove(playbackProbeCacheKey(playbackUrl))
- setLastFailureReason(error.message)
- appendRecoveryAction("Refreshed provider playback URL after auth failure")
- showPlayerNotice(
- message = "Refreshing the provider playback URL…",
- recoveryType = PlayerRecoveryType.NETWORK,
- actions = buildRecoveryActions(PlayerRecoveryType.NETWORK),
- isRetryNotice = true
- )
- if (!preparePlayer(refreshedStreamInfo, requestVersion)) return true
- playerEngine.play()
- return true
- }
-
- private suspend fun isXtreamPlaybackSession(): Boolean {
- val providerId = currentProviderId.takeIf { it > 0L } ?: return false
- val provider = providerRepository.getProvider(providerId) ?: return false
- if (
- provider.type != ProviderType.XTREAM_CODES &&
- provider.type != ProviderType.STALKER_PORTAL
- ) {
- return false
- }
- return xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) ||
- xtreamStreamUrlResolver.isInternalStreamUrl(currentResolvedPlaybackUrl)
- }
-
- private fun isAuthExpiryPlaybackError(message: String?): Boolean {
- val normalized = message.orEmpty().lowercase(Locale.ROOT)
- return "401" in normalized ||
- "403" in normalized ||
- "unauthorized" in normalized ||
- "forbidden" in normalized ||
- "authentication" in normalized ||
- "token" in normalized ||
- "expired" in normalized
- }
-
- private fun setLastFailureReason(message: String?) {
- _playerDiagnostics.update { it.copy(lastFailureReason = message?.takeIf { reason -> reason.isNotBlank() }) }
- }
-
- private fun appendRecoveryAction(action: String) {
- if (action.isBlank()) return
- _playerDiagnostics.update { state ->
- state.copy(recentRecoveryActions = (listOf(action) + state.recentRecoveryActions).distinct().take(5))
- }
- }
-
- fun hasAlternateStream(): Boolean {
- if (isCatchUpPlayback()) {
- return pendingCatchUpUrls.any { altUrl ->
- altUrl != currentStreamUrl &&
- altUrl !in triedAlternativeStreams &&
- (failedStreamsThisSession[altUrl] ?: 0) == 0
- }
- }
- if (currentContentType != ContentType.LIVE) return false
- val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return false
- return nextLiveVariant(channel) != null || channel.alternativeStreams.any { altUrl ->
- altUrl != currentStreamUrl &&
- altUrl !in triedAlternativeStreams &&
- (failedStreamsThisSession[altUrl] ?: 0) == 0
- }
- }
-
- fun tryAlternateStream(): Boolean {
- if (isCatchUpPlayback()) {
- return tryNextCatchUpVariantInternal()
- }
- if (currentContentType != ContentType.LIVE) return false
- val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return false
- return tryAlternateStreamInternal(channel)
- }
-
- private fun tryAlternateStreamInternal(channel: com.streamvault.domain.model.Channel): Boolean {
- nextLiveVariant(channel)?.let { nextVariant ->
- val updatedChannel = channel.withSelectedVariant(nextVariant.rawChannelId)?.sanitizedForPlayer() ?: return@let
- val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(nextVariant.streamUrl)
- currentContentId = updatedChannel.id
- currentStreamUrl = updatedChannel.streamUrl
- currentTitle = nextVariant.originalName.ifBlank { updatedChannel.name }
- playbackTitleFlow.value = currentTitle
- currentChannelFlow.value = updatedChannel
- if (currentChannelIndex in channelList.indices) {
- channelList = channelList.mapIndexed { index, existing ->
- if (index == currentChannelIndex || existing.logicalGroupId == updatedChannel.logicalGroupId) {
- updatedChannel
- } else {
- existing
- }
- }
- currentChannelFlowList.value = channelList
- }
- if (currentChannelIndex >= 0) {
- displayChannelNumberFlow.value = resolveChannelNumber(updatedChannel, currentChannelIndex)
- }
- refreshCurrentChannelRecording()
- updateChannelDiagnostics(updatedChannel)
- updateStreamClass("Variant")
- viewModelScope.launch {
- preferencesRepository.setPreferredLiveVariant(
- providerId = updatedChannel.providerId,
- logicalGroupId = updatedChannel.logicalGroupId,
- rawChannelId = nextVariant.rawChannelId
- )
- val streamInfo = resolvePlaybackStreamInfo(
- logicalUrl = nextVariant.streamUrl,
- internalContentId = updatedChannel.id,
- providerId = updatedChannel.providerId,
- contentType = ContentType.LIVE
- ) ?: return@launch
- if (!isActivePlaybackSession(requestVersion, nextVariant.streamUrl)) return@launch
- recordLivePlayback(updatedChannel)
- requestEpg(
- providerId = updatedChannel.providerId,
- epgChannelId = updatedChannel.epgChannelId,
- streamId = updatedChannel.streamId,
- internalChannelId = updatedChannel.id
- )
- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
- playerEngine.play()
- }
- return true
- }
-
- val nextStream = channel.alternativeStreams.firstOrNull { altUrl ->
- altUrl != currentStreamUrl &&
- altUrl !in triedAlternativeStreams &&
- (failedStreamsThisSession[altUrl] ?: 0) == 0
- } ?: channel.alternativeStreams.firstOrNull { altUrl ->
- altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
- } ?: return false
-
- val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(nextStream)
- currentStreamUrl = nextStream
- updateStreamClass("Alternate")
- viewModelScope.launch {
- val streamInfo = resolvePlaybackStreamInfo(nextStream, channel.id, channel.providerId, ContentType.LIVE)
- ?: return@launch
- if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
- playerEngine.play()
- }
- return true
- }
-
- private fun nextLiveVariant(channel: com.streamvault.domain.model.Channel): com.streamvault.domain.model.LiveChannelVariant? {
- val currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id
- return channel.variants.firstOrNull { variant ->
- variant.rawChannelId != currentVariantId &&
- variant.streamUrl.isNotBlank() &&
- variant.streamUrl != currentStreamUrl &&
- variant.streamUrl !in triedAlternativeStreams &&
- (failedStreamsThisSession[variant.streamUrl] ?: 0) == 0
- } ?: channel.variants.firstOrNull { variant ->
- variant.rawChannelId != currentVariantId &&
- variant.streamUrl.isNotBlank() &&
- variant.streamUrl != currentStreamUrl &&
- variant.streamUrl !in triedAlternativeStreams
- }
- }
-
- private fun isCatchUpPlayback(): Boolean = currentStreamClassLabel == "Catch-up"
-
- private fun nextCatchUpVariant(): String? {
- return pendingCatchUpUrls.firstOrNull { altUrl ->
- altUrl != currentStreamUrl &&
- altUrl !in triedAlternativeStreams &&
- (failedStreamsThisSession[altUrl] ?: 0) == 0
- } ?: pendingCatchUpUrls.firstOrNull { altUrl ->
- altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
- }
- }
-
- private fun tryNextCatchUpVariantInternal(): Boolean {
- val nextStream = nextCatchUpVariant() ?: return false
- val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(nextStream)
- currentStreamUrl = nextStream
- updateStreamClass("Catch-up")
- viewModelScope.launch {
- val streamInfo = resolvePlaybackStreamInfo(nextStream, currentContentId, currentProviderId, ContentType.LIVE)
- ?: return@launch
- if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
- playerEngine.play()
- }
- return true
- }
-
- internal fun scheduleZapBufferWatchdog(targetIndex: Int) {
- if (!zapAutoRevertEnabled) return
- zapBufferWatchdogJob?.cancel()
- val requestVersion = prepareRequestVersion
- zapBufferWatchdogJob = viewModelScope.launch {
- // Check every second for 15 s; back off immediately once the stream starts playing
- repeat(15) {
- delay(1000)
- if (!isActivePlaybackSession(requestVersion)) return@launch
- if (currentChannelIndex != targetIndex) return@launch
- val state = playerEngine.playbackState.value
- if (state == PlaybackState.READY || state == PlaybackState.ENDED) return@launch
- }
- if (!isActivePlaybackSession(requestVersion)) return@launch
- val stillOnTarget = currentChannelIndex == targetIndex
- val state = playerEngine.playbackState.value
- val stalled = state == PlaybackState.BUFFERING || state == PlaybackState.ERROR
- if (stillOnTarget && stalled) {
- markStreamFailure(currentStreamUrl)
- setLastFailureReason("Channel timed out in buffering state")
- appendRecoveryAction("Buffer watchdog triggered")
- val recovered = fallbackToPreviousChannel("Channel timed out in buffering state")
- showPlayerNotice(
- message = if (recovered) {
- "That channel stalled too long. Returned to the last channel."
- } else {
- "That channel stalled too long. Try another source or open the guide."
- },
- recoveryType = PlayerRecoveryType.BUFFER_TIMEOUT,
- actions = buildRecoveryActions(PlayerRecoveryType.BUFFER_TIMEOUT)
- )
- }
- }
- }
-
- private fun fallbackToPreviousChannel(reason: String): Boolean {
- val fallbackIndex = previousChannelIndex
- if (fallbackIndex in channelList.indices && fallbackIndex != currentChannelIndex) {
- android.util.Log.w("PlayerVM", "Falling back to previous channel: $reason")
- // Save before changeChannel overwrites previousChannelIndex with the bad channel's index
- val savedPrevious = previousChannelIndex
- changeChannel(fallbackIndex, isAutoFallback = true)
- // Restore so that zapToLastChannel and a spurious second watchdog don't point at the bad channel
- previousChannelIndex = savedPrevious
- return true
- }
- return false
- }
-
- fun play() {
- notifyUserActivity()
- if (currentContentType == ContentType.LIVE &&
- timeshiftConfig.enabled &&
- timeshiftUiState.value.engineState.status == LiveTimeshiftStatus.PAUSED_BEHIND_LIVE
- ) {
- playerEngine.resumeTimeshift()
- } else {
- playerEngine.play()
- }
- }
-
- fun pause() {
- notifyUserActivity()
- if (currentContentType == ContentType.LIVE && timeshiftConfig.enabled) {
- playerEngine.pauseTimeshift()
- } else {
- playerEngine.pause()
- }
- }
-
- fun setStopPlaybackTimer(minutes: Int) {
- val normalized = sanitizePlaybackTimerMinutes(minutes, PLAYBACK_TIMER_PRESETS_MINUTES)
- if (normalized == 0) {
- disableStopPlaybackTimer()
- return
- }
- stopPlaybackTimerEndsAtMs = SystemClock.elapsedRealtime() + normalized * 60_000L
- sleepTimerExitEmitted = false
- updateSleepTimerState(stopMinutes = normalized)
- startStopPlaybackTimerJob(normalized)
- showPlayerNotice(message = "Playback will stop in ${formatTimerMinutesNotice(normalized)}.")
- }
-
- fun setIdleStandbyTimer(minutes: Int) {
- val normalized = sanitizePlaybackTimerMinutes(minutes, PLAYBACK_TIMER_PRESETS_MINUTES)
- if (normalized == 0) {
- disableIdleStandbyTimer()
- return
- }
- idleStandbyTimerEndsAtMs = SystemClock.elapsedRealtime() + normalized * 60_000L
- sleepTimerExitEmitted = false
- updateSleepTimerState(idleMinutes = normalized)
- startIdleStandbyTimerJob(normalized)
- showPlayerNotice(message = "Idle standby will be allowed after ${formatTimerMinutesNotice(normalized)} without activity.")
- }
-
- fun extendStopPlaybackTimer(minutes: Int = 30) {
- val current = _sleepTimerUiState.value
- if (!current.stopTimerActive) return
- stopPlaybackTimerEndsAtMs += minutes * 60_000L
- sleepTimerExitEmitted = false
- updateSleepTimerState(stopMinutes = current.stopTimerMinutes)
- }
-
- fun extendIdleStandbyTimer(minutes: Int = 30) {
- val current = _sleepTimerUiState.value
- if (!current.idleTimerActive) return
- idleStandbyTimerEndsAtMs += minutes * 60_000L
- sleepTimerExitEmitted = false
- updateSleepTimerState(idleMinutes = current.idleTimerMinutes)
- }
-
- fun disableStopPlaybackTimer() {
- stopPlaybackTimerJob?.cancel()
- stopPlaybackTimerJob = null
- stopPlaybackTimerEndsAtMs = 0L
- _sleepTimerUiState.update { it.copy(stopTimerMinutes = 0, stopRemainingMs = 0L) }
- }
-
- fun disableIdleStandbyTimer() {
- idleStandbyTimerJob?.cancel()
- idleStandbyTimerJob = null
- idleStandbyTimerEndsAtMs = 0L
- _sleepTimerUiState.update { it.copy(idleTimerMinutes = 0, idleRemainingMs = 0L) }
- }
-
- fun notifyUserActivity() {
- val current = _sleepTimerUiState.value
- if (!current.idleTimerActive) return
- idleStandbyTimerEndsAtMs = SystemClock.elapsedRealtime() + current.idleTimerMinutes * 60_000L
- updateSleepTimerState(idleMinutes = current.idleTimerMinutes)
- }
-
- fun consumeSleepTimerExitEvent() {
- _sleepTimerExitEvent.value = 0
- }
-
- private fun applyDefaultPlaybackTimersIfNeeded() {
- if (playbackTimerDefaultsApplied) return
- playbackTimerDefaultsApplied = true
- sleepTimerExitEmitted = false
- viewModelScope.launch {
- val stopMinutes = sanitizePlaybackTimerMinutes(
- preferencesRepository.defaultStopPlaybackTimerMinutes.first(),
- PLAYBACK_TIMER_PRESETS_MINUTES
- )
- val idleMinutes = sanitizePlaybackTimerMinutes(
- preferencesRepository.defaultIdleStandbyTimerMinutes.first(),
- PLAYBACK_TIMER_PRESETS_MINUTES
- )
- if (!playbackTimerDefaultsApplied || _sleepTimerUiState.value.stopTimerActive || _sleepTimerUiState.value.idleTimerActive) {
- return@launch
- }
- if (stopMinutes > 0) {
- setStopPlaybackTimer(stopMinutes)
- }
- if (idleMinutes > 0) {
- setIdleStandbyTimer(idleMinutes)
- }
- }
- }
-
- private fun startStopPlaybackTimerJob(minutes: Int) {
- stopPlaybackTimerJob?.cancel()
- stopPlaybackTimerJob = viewModelScope.launch {
- while (true) {
- val remainingMs = updateSleepTimerState(stopMinutes = minutes).stopRemainingMs
- if (remainingMs <= 0L) {
- expirePlaybackTimer()
- return@launch
- }
- delay(TIMER_TICK_MS)
- }
- }
- }
-
- private fun startIdleStandbyTimerJob(minutes: Int) {
- idleStandbyTimerJob?.cancel()
- idleStandbyTimerJob = viewModelScope.launch {
- while (true) {
- val remainingMs = updateSleepTimerState(idleMinutes = minutes).idleRemainingMs
- if (remainingMs <= 0L) {
- expirePlaybackTimer()
- return@launch
- }
- delay(TIMER_TICK_MS)
- }
- }
- }
-
- private fun updateSleepTimerState(
- stopMinutes: Int = _sleepTimerUiState.value.stopTimerMinutes,
- idleMinutes: Int = _sleepTimerUiState.value.idleTimerMinutes
- ): SleepTimerUiState {
- val next = computeSleepTimerUiState(
- current = _sleepTimerUiState.value,
- nowElapsedMs = SystemClock.elapsedRealtime(),
- stopPlaybackTimerEndsAtMs = stopPlaybackTimerEndsAtMs,
- idleStandbyTimerEndsAtMs = idleStandbyTimerEndsAtMs,
- stopMinutes = stopMinutes,
- idleMinutes = idleMinutes
- )
- _sleepTimerUiState.value = next
- return next
- }
-
- private fun expirePlaybackTimer() {
- if (sleepTimerExitEmitted) return
- sleepTimerExitEmitted = true
- stopPlaybackTimerJob?.cancel()
- idleStandbyTimerJob?.cancel()
- stopPlaybackTimerJob = null
- idleStandbyTimerJob = null
- stopPlaybackTimerEndsAtMs = 0L
- idleStandbyTimerEndsAtMs = 0L
- _sleepTimerUiState.value = SleepTimerUiState()
- _sleepTimerExitEvent.value += 1
- }
-
- private fun clearPlaybackTimers() {
- stopPlaybackTimerJob?.cancel()
- idleStandbyTimerJob?.cancel()
- stopPlaybackTimerJob = null
- idleStandbyTimerJob = null
- stopPlaybackTimerEndsAtMs = 0L
- idleStandbyTimerEndsAtMs = 0L
- playbackTimerDefaultsApplied = false
- sleepTimerExitEmitted = false
- _sleepTimerUiState.value = SleepTimerUiState()
- }
-
- fun seekForward() {
- notifyUserActivity()
- playerEngine.seekForward()
- }
-
- fun seekBackward() {
- notifyUserActivity()
- playerEngine.seekBackward()
- }
-
- fun seekToLiveEdge() {
- notifyUserActivity()
- playerEngine.seekToLiveEdge()
- }
-
- fun playEpisode(episode: Episode, showResumePrompt: Boolean = true) {
- prepare(
- streamUrl = episode.streamUrl,
- epgChannelId = null,
- internalChannelId = episode.id,
- categoryId = -1,
- providerId = episode.providerId,
- isVirtual = false,
- contentType = ContentType.SERIES_EPISODE.name,
- title = buildEpisodePlaybackTitle(episode),
- artworkUrl = episode.coverUrl ?: _currentSeries.value?.posterUrl ?: _currentSeries.value?.backdropUrl,
- seriesId = currentSeriesId ?: episode.seriesId.takeIf { it > 0L },
- seasonNumber = episode.seasonNumber,
- episodeNumber = episode.episodeNumber,
- showResumePrompt = showResumePrompt
- )
- }
-
- fun toggleMute() {
- val now = SystemClock.elapsedRealtime()
- if (now - lastMuteToggleAtMs < MUTE_TOGGLE_DEBOUNCE_MS) return
- lastMuteToggleAtMs = now
- playerEngine.toggleMute()
- val muted = playerEngine.isMuted.value
- mutePersistJob?.cancel()
- mutePersistJob = viewModelScope.launch {
- preferencesRepository.setPlayerMuted(muted)
- }
- }
-
- fun toggleControls() {
- closeChannelInfoOverlay()
- showControlsFlow.value = !showControlsFlow.value
- if (!showControlsFlow.value) {
- clearSeekPreview()
- }
- }
-
- private fun clearSeekPreview() {
- seekPreviewJob?.cancel()
- seekPreviewRequestVersion++
- _seekPreview.value = SeekPreviewState()
- }
-
- fun toggleAspectRatio() {
- val nextRatio = when (_aspectRatio.value) {
- AspectRatio.FIT -> AspectRatio.FILL
- AspectRatio.FILL -> AspectRatio.ZOOM
- AspectRatio.ZOOM -> AspectRatio.FIT
- }
- _aspectRatio.value = nextRatio
-
- // Save instantly if we have a valid channel ID
- if (currentContentId != -1L) {
- viewModelScope.launch {
- preferencesRepository.setAspectRatioForChannel(currentContentId, nextRatio.name)
- }
- }
- }
-
- private suspend fun startCatchUpPlayback(
- urls: List<String>,
- title: String,
- recoveryAction: String,
- requestVersionOverride: Long? = null
- ) {
- val requestVersion = requestVersionOverride ?: beginPlaybackSession()
- val candidates = urls
- .asSequence()
- .map { it.trim() }
- .filter { it.isNotBlank() }
- .distinct()
- .toList()
- val primaryUrl = candidates.firstOrNull() ?: return
-
- currentTitle = title
- pendingCatchUpUrls = candidates
- triedAlternativeStreams.clear()
- triedAlternativeStreams.add(primaryUrl)
- currentStreamUrl = primaryUrl
- updateStreamClass("Catch-up")
- appendRecoveryAction(recoveryAction)
-
- val catchupStream = com.streamvault.domain.model.StreamInfo(
- url = primaryUrl,
- title = currentTitle,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- if (!preparePlayer(catchupStream, requestVersion)) return
- playerEngine.play()
- }
-
- fun playCatchUp(program: Program) {
- viewModelScope.launch {
- val requestVersion = prepareRequestVersion
- val start = program.startTime / 1000L
- val end = program.endTime / 1000L
- val streamId = currentChannelFlow.value?.id ?: 0L
- val providerId = currentProviderId
-
- if (providerId == -1L || streamId == 0L) {
- setLastFailureReason("Catch-up playback needs a valid live channel context.")
- showPlayerNotice(
- message = "Catch-up playback needs a valid live channel context.",
- recoveryType = PlayerRecoveryType.CATCH_UP,
- actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
- )
- return@launch
- }
-
- val catchUpUrls = try {
- providerRepository.buildCatchUpUrls(providerId, streamId, start, end)
- } catch (e: CredentialDecryptionException) {
- if (!isActivePlaybackSession(requestVersion)) return@launch
- setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
- showPlayerNotice(
- message = e.message ?: CredentialDecryptionException.MESSAGE,
- recoveryType = PlayerRecoveryType.SOURCE,
- actions = buildRecoveryActions(PlayerRecoveryType.SOURCE)
- )
- return@launch
- }
- if (!isActivePlaybackSession(requestVersion)) return@launch
- if (catchUpUrls.isNotEmpty()) {
- startCatchUpPlayback(
- urls = catchUpUrls,
- title = "${currentChannelFlow.value?.name ?: ""}: ${program.title}",
- recoveryAction = "Started program replay"
- )
- } else {
- val reason = resolveCatchUpFailureMessage(currentChannelFlow.value, archiveRequested = true, programHasArchive = program.hasArchive)
- setLastFailureReason(reason)
- showPlayerNotice(
- message = reason,
- recoveryType = PlayerRecoveryType.CATCH_UP,
- actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
- )
- }
- }
- }
-
- private fun resolveCatchUpFailureMessage(
- channel: com.streamvault.domain.model.Channel?,
- archiveRequested: Boolean,
- programHasArchive: Boolean
- ): String {
- if (!archiveRequested || channel == null) {
- return "Catch-up playback needs a valid live channel context."
- }
- return when {
- !channel.catchUpSupported && !programHasArchive ->
- "This channel does not advertise archive support on the current provider."
- channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank() ->
- "The provider advertises catch-up, but did not expose replay metadata for this channel."
- else ->
- "Replay is unavailable for the selected program right now."
- }
- }
-
- fun dismissPlayerNotice() {
- playerNoticeHideJob?.cancel()
- _playerNotice.value = null
- }
-
- private fun dismissRecoveredNoticeIfPresent() {
- val notice = _playerNotice.value ?: return
- if (notice.isRetryNotice || notice.recoveryType != PlayerRecoveryType.UNKNOWN) {
- dismissPlayerNotice()
- }
- }
-
- fun runPlayerNoticeAction(action: PlayerNoticeAction) {
- when (action) {
- PlayerNoticeAction.RETRY -> {
- appendRecoveryAction("Manual retry")
- retryStream(currentStreamUrl, currentChannelFlow.value?.epgChannelId)
- }
- PlayerNoticeAction.LAST_CHANNEL -> {
- appendRecoveryAction("Returned to last channel")
- zapToLastChannel()
- }
- PlayerNoticeAction.ALTERNATE_STREAM -> {
- appendRecoveryAction("Manual alternate stream")
- tryAlternateStream()
- }
- PlayerNoticeAction.OPEN_GUIDE -> {
- appendRecoveryAction("Opened guide from recovery")
- openEpgOverlay()
- }
- }
- dismissPlayerNotice()
- }
-
- internal fun showPlayerNotice(
- message: String,
- recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
- actions: List<PlayerNoticeAction> = emptyList(),
- durationMs: Long = playerNoticeTimeoutMs,
- isRetryNotice: Boolean = false
- ) {
- playerNoticeHideJob?.cancel()
- _playerNotice.value = PlayerNoticeState(
- message = message,
- recoveryType = recoveryType,
- actions = actions.distinct(),
- isRetryNotice = isRetryNotice
- )
- playerNoticeHideJob = viewModelScope.launch {
- delay(durationMs)
- if (_playerNotice.value?.message == message) {
- _playerNotice.value = null
- }
- }
- }
-
- private fun showRetryNotice(status: com.streamvault.player.PlayerRetryStatus) {
- val formatLabel = currentPlaybackFormatLabel()
- val message = "Retrying $formatLabel ${status.attempt}/${status.maxAttempts} in ${status.delayMs / 1000}s..."
- showPlayerNotice(
- message = message,
- recoveryType = PlayerRecoveryType.NETWORK,
- durationMs = maxOf(playerNoticeTimeoutMs, status.delayMs + 1500L),
- isRetryNotice = true
- )
- }
-
- private fun currentPlaybackFormatLabel(): String {
- val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }.lowercase(Locale.ROOT)
- return when {
- url.contains("ext=m3u8") || url.endsWith(".m3u8") -> "HLS"
- url.contains("ext=ts") || url.endsWith(".ts") -> "TS"
- else -> "stream"
- }
- }
-
- fun restartCurrentProgram() {
- val program = _currentProgram.value ?: return
- if (program.hasArchive || (currentChannelFlow.value?.catchUpSupported == true)) {
- playCatchUp(program)
- }
- }
-
- fun retryStream(streamUrl: String, epgChannelId: String?) {
- if (isCatchUpPlayback()) {
- val requestVersion = beginPlaybackSession()
- viewModelScope.launch {
- val streamInfo = resolvePlaybackStreamInfo(streamUrl, currentContentId, currentProviderId, currentContentType)
- ?: return@launch
- if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- if (!preparePlayer(streamInfo.copy(title = streamInfo.title ?: currentTitle), requestVersion)) return@launch
- playerEngine.play()
- }
- return
- }
- val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L
- prepare(
- streamUrl = streamUrl,
- epgChannelId = epgChannelId,
- internalChannelId = currentId,
- categoryId = currentCategoryId,
- providerId = currentProviderId,
- isVirtual = isVirtualCategory,
- combinedProfileId = currentCombinedProfileId,
- combinedSourceFilterProviderId = currentCombinedSourceFilterProviderId,
- contentType = currentContentType.name,
- title = currentTitle
- )
- }
-
- internal suspend fun resolvePlaybackStreamInfo(
- logicalUrl: String,
- internalContentId: Long,
+ internal suspend fun resolvePlaybackStreamInfo(
+ logicalUrl: String,
+ internalContentId: Long,
providerId: Long,
contentType: ContentType
): com.streamvault.domain.model.StreamInfo? {
- var fallbackStreamId: Long? = null
- var fallbackContainerExtension: String? = null
-
- if (providerId > 0L && internalContentId > 0L) {
- when (contentType) {
- ContentType.LIVE -> {
- channelRepository.getChannel(internalContentId)?.let { channel ->
- fallbackStreamId = channel.streamId.takeIf { it > 0L }
- ?: channel.epgChannelId?.toLongOrNull()
- channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
- return resolved.copy(title = resolved.title ?: currentTitle)
- }
- }
- }
-
- ContentType.MOVIE -> {
- movieRepository.getMovie(internalContentId)?.let { movie ->
- fallbackStreamId = movie.streamId.takeIf { it > 0L }
- fallbackContainerExtension = movie.containerExtension
- movieRepository.getStreamInfo(movie).getOrNull()?.let { resolved ->
- return resolved.copy(title = resolved.title ?: currentTitle)
- }
- }
- }
-
- ContentType.SERIES,
- ContentType.SERIES_EPISODE -> {
- val episode = when {
- _currentEpisode.value?.id == internalContentId -> _currentEpisode.value
- else -> _currentSeries.value
- ?.seasons
- .sanitizedForPlayer()
- ?.asSequence()
- ?.flatMap { it.episodes.asSequence() }
- ?.firstOrNull { it.id == internalContentId }
- }
- episode?.let {
- fallbackStreamId = it.episodeId.takeIf { episodeId -> episodeId > 0L } ?: it.id
- fallbackContainerExtension = it.containerExtension
- seriesRepository.getEpisodeStreamInfo(it).getOrNull()?.let { resolved ->
- return resolved.copy(title = resolved.title ?: currentTitle)
- }
- }
- }
- }
- }
-
- try {
- xtreamStreamUrlResolver.resolveWithMetadata(
- url = logicalUrl,
- fallbackProviderId = providerId.takeIf { it > 0 },
- fallbackStreamId = fallbackStreamId,
- fallbackContentType = contentType,
- fallbackContainerExtension = fallbackContainerExtension
- )?.let { resolved ->
- val ext = resolved.containerExtension ?: fallbackContainerExtension
- return com.streamvault.domain.model.StreamInfo(
- url = resolved.url,
- title = currentTitle,
- headers = resolved.headers,
- userAgent = resolved.userAgent,
- streamType = com.streamvault.domain.model.StreamType.fromContainerExtension(ext),
- containerExtension = ext,
- expirationTime = resolved.expirationTime
- )
- }
- } catch (e: CredentialDecryptionException) {
- val message = e.message ?: CredentialDecryptionException.MESSAGE
+ val resolution = resolvePlayerPlaybackStreamInfo(
+ logicalUrl = logicalUrl,
+ internalContentId = internalContentId,
+ providerId = providerId,
+ contentType = contentType,
+ currentTitle = currentTitle,
+ currentSeries = currentSeries.value,
+ currentEpisode = currentEpisode.value,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository,
+ xtreamStreamUrlResolver = xtreamStreamUrlResolver
+ )
+ resolution.credentialFailureMessage?.let { message ->
setLastFailureReason(message)
showPlayerNotice(message = message, recoveryType = PlayerRecoveryType.SOURCE)
return null
}
-
- return logicalUrl.takeIf { it.isNotBlank() }?.let {
- com.streamvault.domain.model.StreamInfo(
- url = it,
- title = currentTitle,
- streamType = com.streamvault.domain.model.StreamType.fromContainerExtension(fallbackContainerExtension),
- containerExtension = fallbackContainerExtension
- )
- }
+ return resolution.streamInfo
}
internal suspend fun resolvePlaybackUrl(
@@ -3288,39 +1408,8 @@ class PlayerViewModel @Inject constructor(
contentType = contentType
)?.url
- fun dismissResumePrompt(resume: Boolean) {
- val prompt = _resumePrompt.value
- _resumePrompt.value = ResumePromptState() // hide
- if (resume && prompt.positionMs > 0) {
- playerEngine.seekTo(prompt.positionMs)
- }
- playerEngine.play()
- }
-
override fun onCleared() {
super.onCleared()
- onPlayerScreenDisposed()
- channelInfoHideJob?.cancel()
- liveOverlayHideJob?.cancel()
- diagnosticsHideJob?.cancel()
- numericInputCommitJob?.cancel()
- numericInputFeedbackJob?.cancel()
- playerNoticeHideJob?.cancel()
- epgJob?.cancel()
- playlistJob?.cancel()
- controlsHideJob?.cancel()
- zapOverlayJob?.cancel()
- zapBufferWatchdogJob?.cancel()
- progressTrackingJob?.cancel()
- tokenRenewalJob?.cancel()
- aspectRatioJob?.cancel()
- recentChannelsJob?.cancel()
- lastVisitedCategoryJob?.cancel()
- seekThumbnailProvider.clearCache()
- livePreviewHandoffManager.clear(playerEngine)
- playerEngine.release()
- if (mainPlayerEngine !== playerEngine) {
- mainPlayerEngine.release()
- }
+ cleanupAfterCleared(mainPlayerEngine)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
new file mode 100644
index 00000000..981d7d80
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerAuxiliaryOverlays.kt
@@ -0,0 +1,942 @@
+package com.streamvault.app.ui.screens.player.overlay
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.basicMarquee
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+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.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalLayoutDirection
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.LayoutDirection
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.components.shell.StatusPill
+import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.screens.player.PlayerDiagnosticsUiState
+import com.streamvault.app.ui.time.LocalAppTimeFormat
+import com.streamvault.app.ui.time.createTimeFormat
+import com.streamvault.app.ui.interaction.TvClickableSurface
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Program
+import com.streamvault.player.PlayerStats
+import java.util.Date
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+import com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceVariant
+import com.streamvault.app.ui.design.AppColors.TextSecondary as TextSecondary
+import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
+
+@Composable
+fun ChannelListOverlay(
+ channels: List<Channel>,
+ recentChannels: List<Channel>,
+ currentChannelId: Long,
+ overlayFocusRequester: FocusRequester = remember { FocusRequester() },
+ lastVisitedCategoryName: String? = null,
+ onOpenLastGroup: () -> Unit = {},
+ onOpenCategories: () -> Unit = {},
+ onSelectChannel: (Long) -> Unit,
+ onDismiss: () -> Unit,
+ onOverlayInteracted: () -> Unit = {}
+) {
+ val listState = rememberLazyListState()
+ val currentIndex = remember(channels, currentChannelId) {
+ channels.indexOfFirst { it.id == currentChannelId }.coerceAtLeast(0)
+ }
+ val channelNumbersById = remember(channels) {
+ channels.mapIndexed { index, channel ->
+ channel.id to (channel.number.takeIf { it > 0 } ?: (index + 1))
+ }.toMap()
+ }
+ val canScrollUp by remember { derivedStateOf { listState.canScrollBackward } }
+ val canScrollDown by remember { derivedStateOf { listState.canScrollForward } }
+ val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
+ val headerItemCount = remember(lastVisitedCategoryName, recentChannels) {
+ var count = 2
+ if (!lastVisitedCategoryName.isNullOrBlank()) count++
+ if (recentChannels.isNotEmpty()) count++
+ count
+ }
+
+ LaunchedEffect(channels, currentIndex, headerItemCount) {
+ if (channels.isNotEmpty()) {
+ listState.scrollToItem(headerItemCount + currentIndex)
+ }
+ }
+
+ BackHandler { onDismiss() }
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.18f))
+ ) {
+ BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
+ val isTelevisionDevice = rememberIsTelevisionDevice()
+ val panelModifier = if (maxWidth < 700.dp) {
+ Modifier
+ .fillMaxWidth(0.9f)
+ .fillMaxHeight()
+ .padding(20.dp)
+ } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
+ Modifier
+ .fillMaxWidth(0.5f)
+ .fillMaxHeight()
+ .padding(20.dp)
+ } else {
+ Modifier
+ .width(540.dp)
+ .fillMaxWidth()
+ .fillMaxHeight()
+ .padding(20.dp)
+ }
+
+ Box(modifier = panelModifier) {
+ PlayerOverlayPanel(modifier = Modifier.fillMaxSize()) {
+ androidx.compose.foundation.lazy.LazyColumn(
+ state = listState,
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = PaddingValues(top = 10.dp, bottom = 20.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ item {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 8.dp, vertical = 8.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.player_channel_list_title, channels.size),
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary
+ )
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ TvClickableSurface(
+ onClick = {
+ onOverlayInteracted()
+ onOpenLastGroup()
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.SurfaceEmphasis,
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.onFocusChanged {
+ if (it.isFocused) onOverlayInteracted()
+ }
+ ) {
+ Text(
+ text = stringResource(R.string.player_last_group_label, lastVisitedCategoryName),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
+ }
+ }
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ item {
+ Text(
+ text = stringResource(R.string.player_last_group_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 8.dp)
+ )
+ }
+ }
+ item {
+ Text(
+ text = stringResource(R.string.player_channel_list_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
+ )
+ }
+ if (recentChannels.isNotEmpty()) {
+ item {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 4.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.player_recent_channels),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp)
+ )
+ LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
+ ) {
+ itemsIndexed(
+ recentChannels,
+ key = { index, channel ->
+ "recent:${channel.id}:${channel.streamId}:${channel.epgChannelId.orEmpty()}:${index}"
+ }
+ ) { index, channel ->
+ TvClickableSurface(
+ onClick = {
+ onOverlayInteracted()
+ onSelectChannel(channel.id)
+ onDismiss()
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.SurfaceEmphasis,
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.onFocusChanged {
+ if (it.isFocused) onOverlayInteracted()
+ }
+ ) {
+ Row(
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ val recentNumber = channelNumbersById[channel.id]
+ ?.toString()
+ ?.padStart(2, '0')
+ ?: channel.number
+ .takeIf { it > 0 }
+ ?.toString()
+ ?.padStart(2, '0')
+ ?: "--"
+ Text(
+ text = recentNumber,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp),
+ color = Color.White.copy(alpha = 0.75f)
+ )
+ Text(
+ text = channel.name,
+ style = MaterialTheme.typography.bodySmall.copy(fontSize = 13.sp),
+ color = Color.White,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ items(channels.size) { index ->
+ val channel = channels[index]
+ val isSelected = channel.id == currentChannelId
+ val shouldRequestFocus = isSelected
+ val channelNumber = channel.number.takeIf { it > 0 } ?: (index + 1)
+ var isFocused by remember { mutableStateOf(false) }
+ val bgColor = when {
+ isFocused -> Primary
+ isSelected -> Primary.copy(alpha = 0.20f)
+ else -> AppColors.Surface.copy(alpha = 0.68f)
+ }
+
+ TvClickableSurface(
+ onClick = {
+ onSelectChannel(channel.id)
+ onDismiss()
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 3.dp)
+ .onFocusChanged { focusState ->
+ isFocused = focusState.isFocused
+ if (focusState.isFocused) {
+ onOverlayInteracted()
+ }
+ }
+ .then(
+ if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
+ else Modifier
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = bgColor,
+ focusedContainerColor = bgColor
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = channelNumber.toString().padStart(2, '0'),
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 13.sp),
+ color = Color.White.copy(alpha = 0.72f),
+ textAlign = TextAlign.Start,
+ modifier = Modifier.width(32.dp)
+ )
+ Text(
+ text = channel.name,
+ style = MaterialTheme.typography.bodyLarge.copy(fontSize = 17.sp),
+ color = Color.White,
+ maxLines = 1,
+ overflow = if (isFocused) TextOverflow.Clip else TextOverflow.Ellipsis,
+ modifier = Modifier
+ .weight(1f)
+ .then(
+ if (isFocused) {
+ Modifier.basicMarquee(
+ iterations = Int.MAX_VALUE,
+ initialDelayMillis = 600,
+ repeatDelayMillis = 900,
+ velocity = 20.dp
+ )
+ } else {
+ Modifier
+ }
+ )
+ )
+ if (isSelected) {
+ StatusPill(
+ label = stringResource(R.string.player_channel_selected),
+ containerColor = AppColors.BrandMuted
+ )
+ }
+ if (channel.catchUpSupported) {
+ StatusPill(
+ label = stringResource(R.string.player_archive_badge),
+ containerColor = AppColors.Warning,
+ contentColor = Color.Black
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ AnimatedVisibility(
+ visible = canScrollUp,
+ enter = fadeIn(),
+ exit = fadeOut(),
+ modifier = Modifier.align(Alignment.TopCenter)
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(48.dp)
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(AppColors.Canvas.copy(alpha = 0.9f), Color.Transparent)
+ ),
+ RoundedCornerShape(topStart = 26.dp, topEnd = 26.dp)
+ ),
+ contentAlignment = Alignment.TopCenter
+ ) {
+ Text(
+ text = "\u25b2",
+ color = Color.White.copy(alpha = 0.55f),
+ style = MaterialTheme.typography.labelMedium,
+ modifier = Modifier.padding(top = 8.dp)
+ )
+ }
+ }
+
+ AnimatedVisibility(
+ visible = canScrollDown,
+ enter = fadeIn(),
+ exit = fadeOut(),
+ modifier = Modifier.align(Alignment.BottomCenter)
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(48.dp)
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(Color.Transparent, AppColors.Canvas.copy(alpha = 0.9f))
+ ),
+ RoundedCornerShape(bottomStart = 26.dp, bottomEnd = 26.dp)
+ ),
+ contentAlignment = Alignment.BottomCenter
+ ) {
+ Text(
+ text = "\u25bc",
+ color = Color.White.copy(alpha = 0.55f),
+ style = MaterialTheme.typography.labelMedium,
+ modifier = Modifier.padding(bottom = 8.dp)
+ )
+ }
+ }
+
+ TvClickableSurface(
+ onClick = {
+ onOverlayInteracted()
+ onOpenCategories()
+ },
+ modifier = Modifier
+ .align(if (isRtl) Alignment.CenterEnd else Alignment.CenterStart)
+ .offset(x = if (isRtl) 28.dp else (-28).dp)
+ .onFocusChanged { if (it.isFocused) onOverlayInteracted() },
+ shape = ClickableSurfaceDefaults.shape(
+ if (isRtl) RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp)
+ else RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)
+ ),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.92f),
+ focusedContainerColor = Primary
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .width(28.dp)
+ .height(96.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center
+ ) {
+ Text(
+ text = if (isRtl) "\u25ba" else "\u25c4",
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.85f)
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+fun EpgOverlay(
+ currentChannel: Channel?,
+ displayChannelNumber: Int,
+ currentProgram: Program?,
+ nextProgram: Program?,
+ upcomingPrograms: List<Program>,
+ onDismiss: () -> Unit,
+ onOpenArchiveBrowser: (() -> Unit)? = null,
+ onOverlayInteracted: () -> Unit = {}
+) {
+ val appTimeFormat = LocalAppTimeFormat.current
+ val timeFormat = remember(appTimeFormat) { appTimeFormat.createTimeFormat() }
+ val listState = rememberLazyListState()
+ val filteredUpcoming = remember(upcomingPrograms, currentProgram, nextProgram) {
+ upcomingPrograms.filter { it.id != currentProgram?.id && it.id != nextProgram?.id }
+ }
+ val displayPrograms = remember(filteredUpcoming, nextProgram) {
+ if (nextProgram != null) listOf(nextProgram) + filteredUpcoming else filteredUpcoming
+ }
+
+ BackHandler { onDismiss() }
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.18f))
+ ) {
+ BoxWithConstraints(
+ modifier = Modifier
+ .fillMaxSize()
+ .align(Alignment.CenterEnd)
+ ) {
+ val isTelevisionDevice = rememberIsTelevisionDevice()
+ val panelModifier = if (maxWidth < 700.dp) {
+ Modifier
+ .fillMaxWidth(0.9f)
+ .padding(24.dp)
+ } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
+ Modifier
+ .fillMaxWidth(0.54f)
+ .padding(24.dp)
+ } else {
+ Modifier
+ .width(520.dp)
+ .padding(24.dp)
+ }
+
+ PlayerOverlayPanel(modifier = panelModifier) {
+ androidx.compose.foundation.lazy.LazyColumn(
+ state = listState,
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ item {
+ Text(
+ text = stringResource(R.string.epg_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ if (currentChannel != null) {
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.channel_number_name_format, displayChannelNumber, currentChannel.name),
+ style = MaterialTheme.typography.headlineSmall,
+ color = Color.White,
+ fontWeight = FontWeight.Bold
+ )
+ if (currentChannel.catchUpSupported) {
+ Spacer(Modifier.height(8.dp))
+ if (onOpenArchiveBrowser != null) {
+ QuickActionButton(
+ icon = stringResource(R.string.player_catchup_badge),
+ label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
+ onClick = {
+ onOverlayInteracted()
+ onOpenArchiveBrowser()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ } else {
+ StatusPill(
+ label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
+ containerColor = AppColors.BrandMuted
+ )
+ }
+ }
+ }
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.player_epg_overlay_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+
+ item {
+ androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.epg_now_playing),
+ style = MaterialTheme.typography.labelMedium,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ Spacer(Modifier.height(8.dp))
+ if (currentProgram != null) {
+ Text(
+ currentProgram.title,
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextPrimary,
+ fontWeight = FontWeight.Bold
+ )
+ Spacer(Modifier.height(4.dp))
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ text = stringResource(R.string.time_range_format, timeFormat.format(Date(currentProgram.startTime)), timeFormat.format(Date(currentProgram.endTime))),
+ style = MaterialTheme.typography.bodyMedium,
+ color = TextSecondary
+ )
+ Spacer(Modifier.width(12.dp))
+ Text(
+ text = stringResource(R.string.label_duration_min, currentProgram.durationMinutes),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ if (currentProgram.lang.isNotEmpty()) {
+ Spacer(Modifier.width(8.dp))
+ Text(
+ text = currentProgram.lang.uppercase(),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary.copy(alpha = 0.7f)
+ )
+ }
+ }
+ Spacer(Modifier.height(4.dp))
+ val now = System.currentTimeMillis()
+ val start = currentProgram.startTime
+ val end = currentProgram.endTime
+ if (start in 1..<end) {
+ val progress = (now - start).toFloat() / (end - start)
+ val remainingMin = ((end - now) / 60000).toInt().coerceAtLeast(0)
+ androidx.compose.material3.LinearProgressIndicator(
+ progress = { progress.coerceIn(0f, 1f) },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp),
+ color = Primary,
+ trackColor = AppColors.SurfaceEmphasis
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ text = stringResource(R.string.player_minutes_remaining, remainingMin),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ if (!currentProgram.description.isNullOrEmpty()) {
+ val description = currentProgram.description.orEmpty()
+ Spacer(Modifier.height(12.dp))
+ Text(
+ description,
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White.copy(alpha = 0.7f),
+ maxLines = 6,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ } else {
+ Text(stringResource(R.string.epg_no_info), color = OnSurfaceDim)
+ }
+ }
+
+ if (upcomingPrograms.isNotEmpty()) {
+ item {
+ Spacer(Modifier.height(8.dp))
+ androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.epg_upcoming_schedule),
+ style = MaterialTheme.typography.labelMedium,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ }
+ items(displayPrograms.size) { index ->
+ val program = displayPrograms[index]
+ val isNext = index == 0 && nextProgram != null
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(
+ if (isNext) Primary.copy(alpha = 0.08f) else Color.Transparent
+ )
+ ) {
+ Column(modifier = Modifier.padding(12.dp)) {
+ if (isNext) {
+ Text(
+ text = stringResource(R.string.epg_up_next),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ Spacer(Modifier.height(4.dp))
+ }
+ Text(
+ text = program.title,
+ style = MaterialTheme.typography.bodyLarge,
+ color = if (isNext) Color.White else Color.White.copy(alpha = 0.8f),
+ fontWeight = if (isNext) FontWeight.Bold else FontWeight.Normal,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Spacer(Modifier.height(2.dp))
+ Row {
+ Text(
+ text = stringResource(R.string.time_range_format, timeFormat.format(Date(program.startTime)), timeFormat.format(Date(program.endTime))),
+ style = MaterialTheme.typography.bodySmall,
+ color = TextSecondary
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(
+ text = stringResource(R.string.label_duration_min, program.durationMinutes),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ if (program.hasArchive) {
+ Spacer(Modifier.width(8.dp))
+ StatusPill(
+ label = stringResource(R.string.player_archive_badge),
+ containerColor = AppColors.Warning,
+ contentColor = Color.Black
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+fun DiagnosticsOverlay(
+ stats: PlayerStats,
+ diagnostics: PlayerDiagnosticsUiState,
+ modifier: Modifier = Modifier
+) {
+ PlayerOverlayPanel(modifier = modifier.width(320.dp)) {
+ Column(
+ modifier = Modifier
+ .heightIn(max = 300.dp)
+ .fillMaxWidth()
+ .verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.player_diagnostics_title),
+ color = Primary,
+ style = MaterialTheme.typography.labelMedium.copy(fontSize = 11.sp),
+ fontWeight = FontWeight.Bold
+ )
+ PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_source))
+ if (diagnostics.providerName.isNotBlank()) {
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_provider), diagnostics.providerName)
+ }
+ if (diagnostics.providerSourceLabel.isNotBlank()) {
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_source), diagnostics.providerSourceLabel)
+ }
+ PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_playback))
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_decoder), diagnostics.decoderMode.name)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_active_decoder), diagnostics.activeDecoderName)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_surface), diagnostics.renderSurfaceType)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_stream_class), diagnostics.streamClassLabel)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_playback_state), diagnostics.playbackStateLabel)
+ if (diagnostics.archiveSupportLabel.isNotBlank()) {
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_archive), diagnostics.archiveSupportLabel)
+ }
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_alternates), diagnostics.alternativeStreamCount.toString())
+ if (diagnostics.channelErrorCount > 0) {
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_channel_errors), diagnostics.channelErrorCount.toString())
+ }
+ PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_video))
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_resolution), "${stats.width}x${stats.height}")
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_video_codec), stats.videoCodec)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_video_bitrate), "${stats.videoBitrate / 1000} kbps")
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_dropped_frames), stats.droppedFrames.toString())
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_video_stalls), diagnostics.videoStallCount.toString())
+ if (diagnostics.lastVideoFrameAgoMs > 0L) {
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_last_frame), "${diagnostics.lastVideoFrameAgoMs} ms")
+ }
+ if (stats.ttffMs > 0L) {
+ PlayerMetaRow("TTFF", "${stats.ttffMs} ms")
+ }
+ PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_audio))
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_audio_codec), stats.audioCodec)
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_av_offset), formatOffsetLabel(diagnostics.audioVideoOffsetMs))
+ PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_recovery))
+ diagnostics.lastFailureReason?.let { reason ->
+ PlayerMetaRow(stringResource(R.string.player_diagnostics_last_failure), reason, maxLines = 3)
+ }
+ if (diagnostics.recentRecoveryActions.isNotEmpty()) {
+ Text(
+ text = stringResource(R.string.player_diagnostics_recovery_actions),
+ color = Primary,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ fontWeight = FontWeight.Bold
+ )
+ diagnostics.recentRecoveryActions.forEach { action ->
+ Text(
+ text = action,
+ color = AppColors.TextSecondary,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ if (diagnostics.troubleshootingHints.isNotEmpty()) {
+ Text(
+ text = stringResource(R.string.player_diagnostics_troubleshooting),
+ color = Primary,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ fontWeight = FontWeight.Bold
+ )
+ diagnostics.troubleshootingHints.forEach { hint ->
+ Text(
+ text = hint,
+ color = AppColors.TextSecondary,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+}
+
+private fun formatOffsetLabel(offsetMs: Int): String = when {
+ offsetMs > 0 -> "+$offsetMs ms"
+ offsetMs < 0 -> "$offsetMs ms"
+ else -> "0 ms"
+}
+
+@Composable
+fun CategoryListOverlay(
+ categories: List<com.streamvault.domain.model.Category>,
+ currentCategoryId: Long,
+ overlayFocusRequester: FocusRequester = remember { FocusRequester() },
+ onSelectCategory: (com.streamvault.domain.model.Category) -> Unit,
+ onDismiss: () -> Unit,
+ onOverlayInteracted: () -> Unit = {}
+) {
+ val listState = rememberLazyListState()
+ val currentIndex = remember(categories, currentCategoryId) {
+ categories.indexOfFirst { it.id == currentCategoryId }.coerceAtLeast(0)
+ }
+
+ LaunchedEffect(categories, currentIndex) {
+ if (categories.isNotEmpty()) {
+ listState.scrollToItem(currentIndex)
+ }
+ }
+
+ BackHandler { onDismiss() }
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.18f))
+ ) {
+ BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
+ val isTelevisionDevice = rememberIsTelevisionDevice()
+ val panelModifier = if (maxWidth < 700.dp) {
+ Modifier
+ .fillMaxWidth(0.9f)
+ .fillMaxHeight()
+ .padding(20.dp)
+ } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
+ Modifier
+ .fillMaxWidth(0.5f)
+ .fillMaxHeight()
+ .padding(20.dp)
+ } else {
+ Modifier
+ .width(500.dp)
+ .fillMaxWidth()
+ .fillMaxHeight()
+ .padding(20.dp)
+ }
+
+ Box(modifier = panelModifier) {
+ PlayerOverlayPanel(modifier = Modifier.fillMaxSize()) {
+ androidx.compose.foundation.lazy.LazyColumn(
+ state = listState,
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ item {
+ Text(
+ text = stringResource(R.string.label_categories),
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 12.dp)
+ )
+ }
+ items(categories.size) { index ->
+ val category = categories[index]
+ val isSelected = category.id == currentCategoryId
+ var isFocused by remember { mutableStateOf(false) }
+ val shouldRequestFocus = isSelected
+ val bgColor = when {
+ isFocused -> Primary
+ isSelected -> Primary.copy(alpha = 0.20f)
+ else -> AppColors.Surface.copy(alpha = 0.68f)
+ }
+
+ TvClickableSurface(
+ onClick = {
+ onSelectCategory(category)
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 2.dp)
+ .onFocusChanged { focusState ->
+ isFocused = focusState.isFocused
+ if (focusState.isFocused) {
+ onOverlayInteracted()
+ }
+ }
+ .then(
+ if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
+ else Modifier
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = bgColor,
+ focusedContainerColor = bgColor
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ Text(
+ text = category.name,
+ style = MaterialTheme.typography.bodyLarge,
+ color = Color.White,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f)
+ )
+ if (isSelected) {
+ Text(
+ text = "●",
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.8f),
+ modifier = Modifier.padding(start = 8.dp)
+ )
+ } else if (category.count > 0) {
+ Text(
+ text = category.count.toString(),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.45f),
+ modifier = Modifier.padding(start = 8.dp)
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
new file mode 100644
index 00000000..7c348da9
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerChannelInfoOverlay.kt
@@ -0,0 +1,1014 @@
+package com.streamvault.app.ui.screens.player.overlay
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.border
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+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.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusProperties
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.ui.components.ChannelLogoBadge
+import com.streamvault.app.ui.components.shell.StatusPill
+import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.interaction.TvClickableSurface
+import com.streamvault.app.ui.screens.player.PlayerTimeshiftUiState
+import com.streamvault.app.ui.time.LocalAppTimeFormat
+import com.streamvault.app.ui.time.createTimeFormat
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.RecordingStatus
+import com.streamvault.player.timeshift.LiveTimeshiftStatus
+import java.util.Date
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
+
+@Composable
+fun ChannelInfoOverlay(
+ currentChannel: Channel?,
+ displayChannelNumber: Int,
+ currentProgram: Program?,
+ nextProgram: Program?,
+ focusRequester: FocusRequester,
+ lastVisitedCategoryName: String?,
+ onDismiss: () -> Unit,
+ onOverlayInteracted: () -> Unit,
+ onOpenFullEpg: () -> Unit,
+ onOpenLastGroup: () -> Unit,
+ currentRecordingStatus: RecordingStatus?,
+ onStartRecording: () -> Unit,
+ onStopRecording: () -> Unit,
+ onScheduleRecording: () -> Unit,
+ onScheduleDailyRecording: () -> Unit,
+ onScheduleWeeklyRecording: () -> Unit,
+ onRestartProgram: () -> Unit,
+ onOpenArchive: () -> Unit,
+ onToggleAspectRatio: () -> Unit,
+ onToggleDiagnostics: () -> Unit,
+ onTogglePlayPause: () -> Unit,
+ onSeekBackward: () -> Unit,
+ onSeekForward: () -> Unit,
+ onSeekToLiveEdge: () -> Unit,
+ isPlaying: Boolean,
+ currentAspectRatio: String,
+ isDiagnosticsEnabled: Boolean,
+ onOpenSplitScreen: () -> Unit = {},
+ subtitleTrackCount: Int = 0,
+ audioTrackCount: Int = 0,
+ videoQualityCount: Int = 0,
+ channelVariantCount: Int = 0,
+ isMuted: Boolean = false,
+ onToggleMute: () -> Unit = {},
+ onOpenSubtitleTracks: () -> Unit = {},
+ onOpenAudioTracks: () -> Unit = {},
+ onOpenVideoTracks: () -> Unit = {},
+ onOpenVariants: () -> Unit = {},
+ onOpenAudioVideoSync: () -> Unit = {},
+ onEnterPictureInPicture: () -> Unit = {},
+ isCastConnected: Boolean = false,
+ onCast: () -> Unit = {},
+ onStopCasting: () -> Unit = {},
+ timeshiftUiState: PlayerTimeshiftUiState = PlayerTimeshiftUiState(),
+ onTransientPanelVisibilityChanged: (Boolean) -> Unit = {}
+) {
+ val appTimeFormat = LocalAppTimeFormat.current
+ val timeFormat = remember(appTimeFormat) { appTimeFormat.createTimeFormat() }
+ val showTimeshiftControls = timeshiftUiState.available && !isCastConnected
+ val hasCatchUpOptions = currentChannel?.catchUpSupported == true || currentProgram?.hasArchive == true
+ var expandedPanel by remember { mutableStateOf<ChannelInfoPanel?>(null) }
+ val recordButtonFocusRequester = remember { FocusRequester() }
+ val catchUpButtonFocusRequester = remember { FocusRequester() }
+ val liveDvrPanelFocusRequester = remember { FocusRequester() }
+ val recordPanelFocusRequester = remember { FocusRequester() }
+ val catchUpPanelFocusRequester = remember { FocusRequester() }
+
+ fun handleMainActionFocus(ownerPanel: ChannelInfoPanel?) {
+ onOverlayInteracted()
+ if (expandedPanel != null && expandedPanel != ownerPanel) {
+ expandedPanel = null
+ }
+ }
+
+ fun togglePanel(panel: ChannelInfoPanel) {
+ expandedPanel = if (expandedPanel == panel) null else panel
+ }
+
+ LaunchedEffect(showTimeshiftControls, hasCatchUpOptions) {
+ expandedPanel = when (expandedPanel) {
+ ChannelInfoPanel.LIVE_DVR -> expandedPanel.takeIf { showTimeshiftControls }
+ ChannelInfoPanel.CATCH_UP -> expandedPanel.takeIf { hasCatchUpOptions }
+ else -> expandedPanel
+ }
+ }
+
+ LaunchedEffect(expandedPanel) {
+ onTransientPanelVisibilityChanged(expandedPanel != null)
+ }
+
+ androidx.compose.runtime.DisposableEffect(Unit) {
+ onDispose { onTransientPanelVisibilityChanged(false) }
+ }
+
+ BackHandler {
+ if (expandedPanel != null) {
+ expandedPanel = null
+ } else {
+ onDismiss()
+ }
+ }
+
+ PlayerOverlayPanel(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 40.dp, vertical = 16.dp)
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ if (currentChannel != null) {
+ Box(
+ modifier = Modifier
+ .size(44.dp)
+ .clip(RoundedCornerShape(12.dp))
+ .border(1.dp, AppColors.Focus.copy(alpha = 0.05f), RoundedCornerShape(12.dp))
+ ) {
+ ChannelLogoBadge(
+ channelName = currentChannel.name,
+ logoUrl = currentChannel.logoUrl,
+ backgroundColor = AppColors.SurfaceEmphasis.copy(alpha = 0.46f),
+ contentPadding = PaddingValues(6.dp),
+ textStyle = MaterialTheme.typography.labelLarge,
+ textColor = AppColors.TextSecondary,
+ modifier = Modifier.fillMaxSize()
+ )
+ }
+ }
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ if (displayChannelNumber > 0) {
+ StatusPill(
+ label = stringResource(R.string.player_live_channel, displayChannelNumber),
+ containerColor = AppColors.BrandMuted
+ )
+ }
+ if (showTimeshiftControls) {
+ StatusPill(
+ label = stringResource(R.string.player_live_rewind_badge),
+ containerColor = AppColors.SurfaceEmphasis
+ )
+ }
+ if (currentRecordingStatus == RecordingStatus.RECORDING) {
+ StatusPill(
+ label = stringResource(R.string.player_recording_badge),
+ containerColor = AppColors.Live
+ )
+ } else if (currentRecordingStatus == RecordingStatus.SCHEDULED) {
+ StatusPill(
+ label = stringResource(R.string.player_recording_scheduled_badge),
+ containerColor = AppColors.BrandMuted
+ )
+ }
+ if (currentChannel != null) {
+ Text(
+ text = currentChannel.name,
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextPrimary,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f, fill = false)
+ )
+ }
+ currentChannel?.currentVariant
+ ?.takeIf { channelVariantCount > 1 }
+ ?.attributes
+ ?.toOverlayBadgeLabel()
+ ?.takeIf { it.isNotBlank() }
+ ?.let { variantLabel ->
+ StatusPill(
+ label = variantLabel,
+ containerColor = AppColors.SurfaceEmphasis
+ )
+ }
+ if (currentChannel?.catchUpSupported == true) {
+ StatusPill(
+ label = stringResource(R.string.player_catchup_badge),
+ containerColor = AppColors.Live
+ )
+ }
+ }
+
+ if (currentProgram != null) {
+ Text(
+ text = currentProgram.title,
+ style = MaterialTheme.typography.titleSmall,
+ color = AppColors.TextPrimary,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(
+ R.string.player_time_range_minutes,
+ timeFormat.format(Date(currentProgram.startTime)),
+ timeFormat.format(Date(currentProgram.endTime)),
+ currentProgram.durationMinutes
+ ),
+ style = MaterialTheme.typography.labelSmall,
+ color = AppColors.TextSecondary,
+ maxLines = 1
+ )
+ val now = System.currentTimeMillis()
+ val start = currentProgram.startTime
+ val end = currentProgram.endTime
+ if (start in 1..<end) {
+ val progress = (now - start).toFloat() / (end - start)
+ val remainingMin = ((end - now) / 60000).toInt().coerceAtLeast(0)
+ androidx.compose.material3.LinearProgressIndicator(
+ progress = { progress.coerceIn(0f, 1f) },
+ modifier = Modifier
+ .weight(1f)
+ .height(4.dp)
+ .clip(RoundedCornerShape(999.dp)),
+ color = Primary,
+ trackColor = AppColors.SurfaceEmphasis.copy(alpha = 0.45f)
+ )
+ Text(
+ text = stringResource(R.string.player_minutes_remaining, remainingMin),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim,
+ maxLines = 1
+ )
+ }
+ }
+ if (nextProgram != null) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.player_next_label),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary
+ )
+ Text(
+ text = nextProgram.title,
+ style = MaterialTheme.typography.labelSmall,
+ color = AppColors.TextSecondary,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f)
+ )
+ Text(
+ text = timeFormat.format(Date(nextProgram.startTime)),
+ style = MaterialTheme.typography.labelSmall,
+ color = AppColors.TextTertiary
+ )
+ }
+ }
+ } else {
+ Text(
+ text = stringResource(R.string.player_no_guide_data),
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary,
+ fontWeight = FontWeight.Medium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+
+ if (showTimeshiftControls && expandedPanel == ChannelInfoPanel.LIVE_DVR) {
+ CompactTimeshiftTransport(
+ timeshiftUiState = timeshiftUiState,
+ isPlaying = isPlaying,
+ onOverlayInteracted = onOverlayInteracted,
+ onTogglePlayPause = onTogglePlayPause,
+ onSeekBackward = onSeekBackward,
+ onSeekForward = onSeekForward,
+ onSeekToLiveEdge = onSeekToLiveEdge,
+ firstFocusRequester = liveDvrPanelFocusRequester,
+ ownerFocusRequester = focusRequester
+ )
+ }
+
+ LazyRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ contentPadding = PaddingValues(end = 8.dp)
+ ) {
+ item {
+ QuickActionButton(
+ icon = if (showTimeshiftControls) "DVR" else stringResource(R.string.player_action_playback),
+ label = if (showTimeshiftControls) {
+ stringResource(R.string.player_live_dvr_controls)
+ } else if (isPlaying) {
+ stringResource(R.string.player_pause)
+ } else {
+ stringResource(R.string.player_play)
+ },
+ onClick = {
+ if (showTimeshiftControls) {
+ togglePanel(ChannelInfoPanel.LIVE_DVR)
+ } else {
+ onTogglePlayPause()
+ }
+ },
+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.LIVE_DVR.takeIf { showTimeshiftControls }) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {
+ Primary.copy(alpha = 0.30f)
+ } else {
+ Primary.copy(alpha = 0.20f)
+ },
+ focusedContainerColor = Primary,
+ pressedContainerColor = Primary.copy(alpha = 0.8f)
+ ),
+ modifier = Modifier
+ .focusRequester(focusRequester)
+ .focusProperties {
+ if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {
+ up = liveDvrPanelFocusRequester
+ }
+ }
+ )
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_mute),
+ label = if (isMuted) stringResource(R.string.player_unmute) else stringResource(R.string.player_mute),
+ onClick = onToggleMute,
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ if (subtitleTrackCount > 0) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_subs),
+ label = stringResource(R.string.player_subs),
+ onClick = onOpenSubtitleTracks,
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ if (videoQualityCount > 0) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_quality),
+ label = stringResource(R.string.player_quality_short),
+ onClick = onOpenVideoTracks,
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ if (channelVariantCount > 1) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_variants),
+ label = stringResource(R.string.player_variants_short),
+ onClick = onOpenVariants,
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ if (audioTrackCount > 0) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_audio),
+ label = stringResource(R.string.player_audio),
+ onClick = onOpenAudioTracks,
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ if (!isCastConnected) {
+ item {
+ QuickActionButton(
+ icon = "A/V",
+ label = stringResource(R.string.player_av_sync_short),
+ onClick = {
+ expandedPanel = null
+ onOpenAudioVideoSync()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_guide),
+ label = stringResource(R.string.player_epg_short),
+ onClick = {
+ expandedPanel = null
+ onDismiss()
+ onOpenFullEpg()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_split),
+ label = stringResource(R.string.player_multiview_short),
+ onClick = {
+ expandedPanel = null
+ onDismiss()
+ onOpenSplitScreen()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_diagnostics),
+ label = stringResource(R.string.player_stats),
+ onClick = {
+ expandedPanel = null
+ onToggleDiagnostics()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_group),
+ label = lastVisitedCategoryName,
+ onClick = {
+ expandedPanel = null
+ onOpenLastGroup()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+ item {
+ QuickActionButton(
+ icon = "REC",
+ label = stringResource(R.string.player_record),
+ onClick = { togglePanel(ChannelInfoPanel.RECORD) },
+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.RECORD) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (expandedPanel == ChannelInfoPanel.RECORD) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,
+ focusedContainerColor = Primary.copy(alpha = 0.85f)
+ ),
+ modifier = Modifier
+ .focusRequester(recordButtonFocusRequester)
+ .focusProperties {
+ if (expandedPanel == ChannelInfoPanel.RECORD) {
+ up = recordPanelFocusRequester
+ }
+ }
+ )
+ }
+ if (hasCatchUpOptions) {
+ item {
+ QuickActionButton(
+ icon = "C-UP",
+ label = stringResource(R.string.player_catchup_badge),
+ onClick = { togglePanel(ChannelInfoPanel.CATCH_UP) },
+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.CATCH_UP) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (expandedPanel == ChannelInfoPanel.CATCH_UP) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,
+ focusedContainerColor = Primary.copy(alpha = 0.85f)
+ ),
+ modifier = Modifier
+ .focusRequester(catchUpButtonFocusRequester)
+ .focusProperties {
+ if (expandedPanel == ChannelInfoPanel.CATCH_UP) {
+ up = catchUpPanelFocusRequester
+ }
+ }
+ )
+ }
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_cast),
+ label = if (isCastConnected) stringResource(R.string.player_stop_casting) else stringResource(R.string.player_cast),
+ onClick = {
+ expandedPanel = null
+ if (isCastConnected) onStopCasting() else onCast()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_pip),
+ label = stringResource(R.string.player_pip_short),
+ onClick = {
+ expandedPanel = null
+ onEnterPictureInPicture()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_action_view),
+ label = currentAspectRatio,
+ onClick = {
+ expandedPanel = null
+ onToggleAspectRatio()
+ },
+ onInteraction = { handleMainActionFocus(null) }
+ )
+ }
+ }
+
+ when (expandedPanel) {
+ ChannelInfoPanel.RECORD -> {
+ ChannelInfoActionMenuTray(
+ title = stringResource(R.string.player_record_options),
+ actions = buildList {
+ if (currentRecordingStatus == RecordingStatus.RECORDING || currentRecordingStatus == RecordingStatus.SCHEDULED) {
+ add(
+ ChannelInfoMenuEntry(
+ label = if (currentRecordingStatus == RecordingStatus.SCHEDULED) {
+ stringResource(R.string.player_cancel_scheduled_recording)
+ } else {
+ stringResource(R.string.player_stop_recording)
+ }
+ ) {
+ expandedPanel = null
+ onStopRecording()
+ }
+ )
+ } else {
+ add(
+ ChannelInfoMenuEntry(stringResource(R.string.player_record_now)) {
+ expandedPanel = null
+ onStartRecording()
+ }
+ )
+ }
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_recording)) {
+ expandedPanel = null
+ onScheduleRecording()
+ })
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_daily_recording)) {
+ expandedPanel = null
+ onScheduleDailyRecording()
+ })
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_weekly_recording)) {
+ expandedPanel = null
+ onScheduleWeeklyRecording()
+ })
+ },
+ onInteraction = onOverlayInteracted,
+ firstActionFocusRequester = recordPanelFocusRequester,
+ ownerFocusRequester = recordButtonFocusRequester
+ )
+ }
+
+ ChannelInfoPanel.CATCH_UP -> {
+ ChannelInfoActionMenuTray(
+ title = stringResource(R.string.player_catchup_options),
+ actions = buildList {
+ if (currentProgram?.hasArchive == true) {
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_restart)) {
+ expandedPanel = null
+ onRestartProgram()
+ onDismiss()
+ })
+ }
+ if (currentChannel?.catchUpSupported == true) {
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_archive)) {
+ expandedPanel = null
+ onDismiss()
+ onOpenArchive()
+ })
+ }
+ add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_guide_catchup)) {
+ expandedPanel = null
+ onDismiss()
+ onOpenFullEpg()
+ })
+ },
+ onInteraction = onOverlayInteracted,
+ firstActionFocusRequester = catchUpPanelFocusRequester,
+ ownerFocusRequester = catchUpButtonFocusRequester
+ )
+ }
+
+ ChannelInfoPanel.LIVE_DVR,
+ null -> Unit
+ }
+ }
+ }
+}
+
+private enum class ChannelInfoPanel {
+ LIVE_DVR,
+ RECORD,
+ CATCH_UP
+}
+
+private fun com.streamvault.domain.model.LiveChannelVariantAttributes.toOverlayBadgeLabel(): String {
+ val parts = buildList {
+ resolutionLabel?.let(::add)
+ codecLabel?.takeIf { it == "HEVC" || it == "AV1" }?.let(::add)
+ frameRate?.takeIf { it >= 50 }?.let { add("${it}fps") }
+ if (isHdr) {
+ add("HDR")
+ }
+ sourceHint?.takeIf { it == "Backup" || it == "Alternate" || it == "Lite" || it == "Mobile" }?.let(::add)
+ }
+ return parts.joinToString(" ")
+}
+
+private data class ChannelInfoMenuEntry(
+ val label: String,
+ val onClick: () -> Unit
+)
+
+@Composable
+private fun CompactTimeshiftTransport(
+ timeshiftUiState: PlayerTimeshiftUiState,
+ isPlaying: Boolean,
+ onOverlayInteracted: () -> Unit,
+ onTogglePlayPause: () -> Unit,
+ onSeekBackward: () -> Unit,
+ onSeekForward: () -> Unit,
+ onSeekToLiveEdge: () -> Unit,
+ firstFocusRequester: FocusRequester,
+ ownerFocusRequester: FocusRequester
+) {
+ val transportReady = timeshiftUiState.bufferDepthMs > 1_000L &&
+ timeshiftUiState.engineState.status != LiveTimeshiftStatus.PREPARING
+ val behindLive = timeshiftUiState.bufferedBehindLiveMs.coerceAtLeast(0L)
+ val bufferDepth = timeshiftUiState.bufferDepthMs.coerceAtLeast(0L)
+ val liveProgress = if (bufferDepth > 0L) {
+ ((bufferDepth - behindLive).toFloat() / bufferDepth.toFloat()).coerceIn(0f, 1f)
+ } else {
+ 1f
+ }
+ val statusLine = when {
+ !transportReady -> timeshiftUiState.statusMessage.ifBlank {
+ stringResource(R.string.player_live_timeshift_buffering)
+ }
+ behindLive > 1_000L -> stringResource(
+ R.string.player_live_offset,
+ formatTimeLabel(behindLive)
+ )
+ else -> stringResource(R.string.player_live_ready)
+ }
+ var lastTransportActionAtMs by remember { mutableStateOf(0L) }
+
+ fun runTransportAction(enabled: Boolean, action: () -> Unit) {
+ if (!enabled) return
+ val now = System.currentTimeMillis()
+ if (now - lastTransportActionAtMs < 240L) return
+ lastTransportActionAtMs = now
+ onOverlayInteracted()
+ action()
+ }
+
+ Surface(
+ shape = RoundedCornerShape(18.dp),
+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Surface(
+ shape = RoundedCornerShape(14.dp),
+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 9.dp, vertical = 7.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.player_live_rewind_badge),
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ color = Primary
+ )
+ Text(
+ text = statusLine,
+ style = MaterialTheme.typography.titleSmall.copy(fontSize = 20.sp),
+ color = Color.White,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = stringResource(
+ R.string.player_live_buffer_depth,
+ formatTimeLabel(bufferDepth)
+ ),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White.copy(alpha = 0.7f)
+ )
+ }
+ }
+
+ Row(
+ modifier = Modifier.weight(1f),
+ horizontalArrangement = Arrangement.End,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ CompactTransportButton(
+ topLabel = stringResource(R.string.player_rewind),
+ mainLabel = stringResource(R.string.player_seek_back_10),
+ enabled = transportReady,
+ onInteraction = onOverlayInteracted,
+ onClick = { runTransportAction(transportReady, onSeekBackward) },
+ modifier = Modifier
+ .focusRequester(firstFocusRequester)
+ .focusProperties { down = ownerFocusRequester }
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ TvClickableSurface(
+ onClick = { runTransportAction(transportReady, onTogglePlayPause) },
+ enabled = transportReady,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.88f),
+ focusedContainerColor = Primary,
+ disabledContainerColor = Primary.copy(alpha = 0.28f)
+ ),
+ modifier = Modifier
+ .size(52.dp)
+ .focusProperties { down = ownerFocusRequester }
+ ) {
+ Box(
+ modifier = Modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ if (isPlaying) {
+ Text(
+ text = "II",
+ style = MaterialTheme.typography.headlineSmall,
+ color = Color.White
+ )
+ } else {
+ androidx.tv.material3.Icon(
+ imageVector = Icons.Default.PlayArrow,
+ contentDescription = stringResource(R.string.player_play),
+ tint = Color.White,
+ modifier = Modifier.size(26.dp)
+ )
+ }
+ }
+ }
+ Spacer(modifier = Modifier.width(8.dp))
+ CompactTransportButton(
+ topLabel = stringResource(R.string.player_forward),
+ mainLabel = stringResource(R.string.player_seek_forward_10),
+ enabled = transportReady && timeshiftUiState.canSeekToLive,
+ onInteraction = onOverlayInteracted,
+ onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekForward) },
+ modifier = Modifier.focusProperties { down = ownerFocusRequester }
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ CompactTransportButton(
+ topLabel = stringResource(R.string.player_live_ready),
+ mainLabel = stringResource(R.string.player_jump_to_live_short),
+ enabled = transportReady && timeshiftUiState.canSeekToLive,
+ highlighted = !timeshiftUiState.canSeekToLive,
+ onInteraction = onOverlayInteracted,
+ onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekToLiveEdge) },
+ modifier = Modifier.focusProperties { down = ownerFocusRequester }
+ )
+ }
+ }
+
+ androidx.compose.material3.LinearProgressIndicator(
+ progress = { liveProgress },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp)
+ .clip(RoundedCornerShape(999.dp)),
+ color = Primary,
+ trackColor = Color.White.copy(alpha = 0.16f)
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.player_live_buffer_start),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.52f)
+ )
+ Text(
+ text = if (behindLive > 1_000L) {
+ stringResource(R.string.player_live_offset, formatTimeLabel(behindLive))
+ } else {
+ stringResource(R.string.player_live_ready)
+ },
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.76f)
+ )
+ Text(
+ text = stringResource(R.string.player_live_buffer_end),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.52f)
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun CompactTransportButton(
+ topLabel: String,
+ mainLabel: String,
+ enabled: Boolean,
+ highlighted: Boolean = false,
+ onInteraction: () -> Unit,
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ TvClickableSurface(
+ onClick = onClick,
+ enabled = enabled,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (highlighted) {
+ Primary.copy(alpha = 0.18f)
+ } else {
+ Color.White.copy(alpha = 0.08f)
+ },
+ focusedContainerColor = Primary.copy(alpha = 0.86f),
+ disabledContainerColor = Color.White.copy(alpha = 0.04f)
+ ),
+ modifier = modifier
+ .widthIn(min = 68.dp)
+ .onFocusChanged {
+ if (it.isFocused) onInteraction()
+ }
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(1.dp)
+ ) {
+ Text(
+ text = topLabel,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ color = Color.White.copy(alpha = if (enabled) 0.72f else 0.32f)
+ )
+ Text(
+ text = mainLabel,
+ style = MaterialTheme.typography.titleSmall.copy(fontSize = 16.sp),
+ color = if (enabled) Color.White else Color.White.copy(alpha = 0.32f),
+ fontWeight = FontWeight.Bold
+ )
+ }
+ }
+}
+
+@Composable
+private fun ChannelInfoActionMenuTray(
+ title: String,
+ actions: List<ChannelInfoMenuEntry>,
+ onInteraction: () -> Unit,
+ firstActionFocusRequester: FocusRequester,
+ ownerFocusRequester: FocusRequester
+) {
+ if (actions.isEmpty()) return
+
+ Surface(
+ shape = RoundedCornerShape(18.dp),
+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.labelLarge,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ itemsIndexed(actions) { index, action ->
+ CompactMenuActionButton(
+ text = action.label,
+ onClick = action.onClick,
+ onInteraction = onInteraction,
+ modifier = (if (index == 0) Modifier.focusRequester(firstActionFocusRequester) else Modifier)
+ .focusProperties { down = ownerFocusRequester }
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun CompactMenuActionButton(
+ text: String,
+ onClick: () -> Unit,
+ onInteraction: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ TvClickableSurface(
+ onClick = {
+ onInteraction()
+ onClick()
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f),
+ focusedContainerColor = Color.White.copy(alpha = 0.16f)
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.0f),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = androidx.compose.foundation.BorderStroke(1.5.dp, Color.White.copy(alpha = 0.75f))
+ )
+ ),
+ modifier = modifier
+ .onFocusChanged {
+ if (it.isFocused) onInteraction()
+ }
+ ) {
+ Text(
+ text = text,
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White,
+ fontWeight = FontWeight.Medium,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayShared.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayShared.kt
new file mode 100644
index 00000000..7d8d7e19
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayShared.kt
@@ -0,0 +1,179 @@
+package com.streamvault.app.ui.screens.player.overlay
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.basicMarquee
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.interaction.TvClickableSurface
+import java.util.Locale
+import com.streamvault.app.ui.design.AppColors.Brand as Primary
+
+@Composable
+internal fun PlayerOverlayPanel(
+ modifier: Modifier = Modifier,
+ content: @Composable ColumnScope.() -> Unit
+) {
+ Surface(
+ modifier = modifier,
+ shape = RoundedCornerShape(26.dp),
+ border = Border(
+ border = androidx.compose.foundation.BorderStroke(
+ 1.dp,
+ AppColors.Focus.copy(alpha = 0.05f)
+ )
+ ),
+ colors = androidx.tv.material3.SurfaceDefaults.colors(
+ containerColor = AppColors.Canvas.copy(alpha = 0.38f)
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(
+ AppColors.BrandMuted.copy(alpha = 0.06f),
+ AppColors.SurfaceElevated.copy(alpha = 0.34f),
+ AppColors.Surface.copy(alpha = 0.28f)
+ )
+ )
+ )
+ .padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ content = content
+ )
+ }
+}
+
+@Composable
+internal fun PlayerMetaRow(label: String, value: String, maxLines: Int = 1) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.Top
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ color = AppColors.TextTertiary,
+ modifier = Modifier.weight(0.44f)
+ )
+ Text(
+ text = value,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ color = AppColors.TextPrimary,
+ modifier = Modifier.weight(0.56f),
+ maxLines = maxLines,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+}
+
+@Composable
+internal fun PlayerOverlaySectionLabel(text: String) {
+ Text(
+ text = text,
+ color = Primary,
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ fontWeight = FontWeight.Bold
+ )
+}
+
+internal fun formatTimeLabel(ms: Long): String {
+ val totalSeconds = (ms / 1_000L).coerceAtLeast(0L)
+ val hours = totalSeconds / 3_600L
+ val minutes = (totalSeconds % 3_600L) / 60L
+ val seconds = totalSeconds % 60L
+ return if (hours > 0L) {
+ String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds)
+ } else {
+ String.format(Locale.getDefault(), "%d:%02d", minutes, seconds)
+ }
+}
+
+@Composable
+internal fun QuickActionButton(
+ icon: String,
+ label: String,
+ modifier: Modifier = Modifier,
+ colors: androidx.tv.material3.ClickableSurfaceColors = ClickableSurfaceDefaults.colors(
+ containerColor = AppColors.SurfaceEmphasis,
+ focusedContainerColor = Primary.copy(alpha = 0.85f)
+ ),
+ onInteraction: () -> Unit = {},
+ onClick: () -> Unit
+) {
+ TvClickableSurface(
+ onClick = {
+ onInteraction()
+ onClick()
+ },
+ modifier = modifier
+ .widthIn(min = 84.dp, max = 138.dp)
+ .onFocusChanged {
+ if (it.isFocused) onInteraction()
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = colors,
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.01f)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
+ horizontalAlignment = Alignment.Start,
+ verticalArrangement = Arrangement.spacedBy(0.dp)
+ ) {
+ AnimatedContent(
+ targetState = icon,
+ transitionSpec = {
+ (fadeIn() + scaleIn()).togetherWith(fadeOut() + scaleOut())
+ },
+ label = "iconToggle"
+ ) { targetIcon ->
+ Text(
+ text = targetIcon.uppercase(Locale.getDefault()),
+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
+ color = AppColors.BrandStrong,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Text(
+ text = label,
+ style = MaterialTheme.typography.bodySmall.copy(fontSize = 10.sp),
+ color = AppColors.TextPrimary,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
deleted file mode 100644
index 998c5169..00000000
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
+++ /dev/null
@@ -1,2060 +0,0 @@
-package com.streamvault.app.ui.screens.player.overlay
-
-import androidx.activity.compose.BackHandler
-import androidx.compose.animation.AnimatedContent
-import androidx.compose.animation.AnimatedVisibility
-import androidx.compose.animation.fadeIn
-import androidx.compose.animation.fadeOut
-import androidx.compose.animation.scaleIn
-import androidx.compose.animation.scaleOut
-import androidx.compose.animation.togetherWith
-import androidx.compose.foundation.background
-import androidx.compose.foundation.basicMarquee
-import androidx.compose.foundation.border
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.BoxWithConstraints
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.ColumnScope
-import androidx.compose.foundation.layout.PaddingValues
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.fillMaxHeight
-import androidx.compose.foundation.layout.fillMaxWidth
-import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.heightIn
-import androidx.compose.foundation.layout.offset
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.layout.widthIn
-import androidx.compose.foundation.lazy.LazyRow
-import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.lazy.itemsIndexed
-import androidx.compose.foundation.lazy.rememberLazyListState
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.filled.PlayArrow
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.LaunchedEffect
-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.draw.clip
-import androidx.compose.ui.focus.FocusRequester
-import androidx.compose.ui.focus.focusProperties
-import androidx.compose.ui.focus.focusRequester
-import androidx.compose.ui.focus.onFocusChanged
-import androidx.compose.ui.graphics.Brush
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.platform.LocalLayoutDirection
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.unit.LayoutDirection
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.compose.foundation.rememberScrollState
-import androidx.compose.foundation.verticalScroll
-import androidx.tv.material3.ClickableSurfaceDefaults
-import androidx.tv.material3.Border
-import androidx.tv.material3.MaterialTheme
-import androidx.tv.material3.Surface
-import androidx.tv.material3.SurfaceDefaults
-import androidx.tv.material3.Text
-import coil3.compose.AsyncImage
-import com.streamvault.app.R
-import com.streamvault.app.device.rememberIsTelevisionDevice
-import com.streamvault.app.ui.components.ChannelLogoBadge
-import com.streamvault.app.ui.components.rememberCrossfadeImageModel
-import com.streamvault.app.ui.components.shell.StatusPill
-import com.streamvault.app.ui.design.AppColors
-import com.streamvault.app.ui.screens.player.PlayerDiagnosticsUiState
-import com.streamvault.app.ui.screens.player.PlayerTimeshiftUiState
-import com.streamvault.app.ui.time.LocalAppTimeFormat
-import com.streamvault.app.ui.time.createTimeFormat
-import com.streamvault.domain.model.RecordingStatus
-import com.streamvault.app.ui.design.AppColors.Brand as Primary
-import com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceVariant
-import com.streamvault.app.ui.design.AppColors.TextSecondary as TextSecondary
-import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
-import com.streamvault.domain.model.Channel
-import com.streamvault.domain.model.Program
-import com.streamvault.player.PlayerStats
-import com.streamvault.player.timeshift.LiveTimeshiftStatus
-import java.util.Date
-import java.util.Locale
-import com.streamvault.app.ui.interaction.TvClickableSurface
-import com.streamvault.app.ui.interaction.TvButton
-import com.streamvault.app.ui.interaction.TvIconButton
-
-@Composable
-private fun PlayerOverlayPanel(
- modifier: Modifier = Modifier,
- content: @Composable ColumnScope.() -> Unit
-) {
- Surface(
- modifier = modifier,
- shape = RoundedCornerShape(26.dp),
- border = Border(
- border = androidx.compose.foundation.BorderStroke(
- 1.dp,
- AppColors.Focus.copy(alpha = 0.05f)
- )
- ),
- colors = androidx.tv.material3.SurfaceDefaults.colors(
- containerColor = AppColors.Canvas.copy(alpha = 0.38f)
- )
- ) {
- Column(
- modifier = Modifier
- .background(
- Brush.verticalGradient(
- colors = listOf(
- AppColors.BrandMuted.copy(alpha = 0.06f),
- AppColors.SurfaceElevated.copy(alpha = 0.34f),
- AppColors.Surface.copy(alpha = 0.28f)
- )
- )
- )
- .padding(14.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp),
- content = content
- )
- }
-}
-
-@Composable
-private fun PlayerMetaRow(label: String, value: String, maxLines: Int = 1) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.Top
- ) {
- Text(
- text = label,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- color = AppColors.TextTertiary,
- modifier = Modifier.weight(0.44f)
- )
- Text(
- text = value,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- color = AppColors.TextPrimary,
- modifier = Modifier.weight(0.56f),
- maxLines = maxLines,
- overflow = TextOverflow.Ellipsis
- )
- }
-}
-
-@Composable
-private fun PlayerOverlaySectionLabel(text: String) {
- Text(
- text = text,
- color = Primary,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- fontWeight = FontWeight.Bold
- )
-}
-
-@Composable
-fun ChannelInfoOverlay(
- currentChannel: Channel?,
- displayChannelNumber: Int,
- currentProgram: Program?,
- nextProgram: Program?,
- focusRequester: FocusRequester,
- lastVisitedCategoryName: String?,
- onDismiss: () -> Unit,
- onOverlayInteracted: () -> Unit,
- onOpenFullEpg: () -> Unit,
- onOpenLastGroup: () -> Unit,
- currentRecordingStatus: RecordingStatus?,
- onStartRecording: () -> Unit,
- onStopRecording: () -> Unit,
- onScheduleRecording: () -> Unit,
- onScheduleDailyRecording: () -> Unit,
- onScheduleWeeklyRecording: () -> Unit,
- onRestartProgram: () -> Unit,
- onOpenArchive: () -> Unit,
- onToggleAspectRatio: () -> Unit,
- onToggleDiagnostics: () -> Unit,
- onTogglePlayPause: () -> Unit,
- onSeekBackward: () -> Unit,
- onSeekForward: () -> Unit,
- onSeekToLiveEdge: () -> Unit,
- isPlaying: Boolean,
- currentAspectRatio: String,
- isDiagnosticsEnabled: Boolean,
- onOpenSplitScreen: () -> Unit = {},
- subtitleTrackCount: Int = 0,
- audioTrackCount: Int = 0,
- videoQualityCount: Int = 0,
- channelVariantCount: Int = 0,
- isMuted: Boolean = false,
- onToggleMute: () -> Unit = {},
- onOpenSubtitleTracks: () -> Unit = {},
- onOpenAudioTracks: () -> Unit = {},
- onOpenVideoTracks: () -> Unit = {},
- onOpenVariants: () -> Unit = {},
- onOpenAudioVideoSync: () -> Unit = {},
- onEnterPictureInPicture: () -> Unit = {},
- isCastConnected: Boolean = false,
- onCast: () -> Unit = {},
- onStopCasting: () -> Unit = {},
- timeshiftUiState: PlayerTimeshiftUiState = PlayerTimeshiftUiState(),
- onTransientPanelVisibilityChanged: (Boolean) -> Unit = {}
-) {
- val appTimeFormat = LocalAppTimeFormat.current
- val timeFormat = remember(appTimeFormat) { appTimeFormat.createTimeFormat() }
- val showTimeshiftControls = timeshiftUiState.available && !isCastConnected
- val hasCatchUpOptions = currentChannel?.catchUpSupported == true || currentProgram?.hasArchive == true
- var expandedPanel by remember { mutableStateOf<ChannelInfoPanel?>(null) }
- val recordButtonFocusRequester = remember { FocusRequester() }
- val catchUpButtonFocusRequester = remember { FocusRequester() }
- val liveDvrPanelFocusRequester = remember { FocusRequester() }
- val recordPanelFocusRequester = remember { FocusRequester() }
- val catchUpPanelFocusRequester = remember { FocusRequester() }
-
- fun handleMainActionFocus(ownerPanel: ChannelInfoPanel?) {
- onOverlayInteracted()
- if (expandedPanel != null && expandedPanel != ownerPanel) {
- expandedPanel = null
- }
- }
-
- fun togglePanel(panel: ChannelInfoPanel) {
- expandedPanel = if (expandedPanel == panel) null else panel
- }
-
- LaunchedEffect(showTimeshiftControls, hasCatchUpOptions) {
- expandedPanel = when (expandedPanel) {
- ChannelInfoPanel.LIVE_DVR -> expandedPanel.takeIf { showTimeshiftControls }
- ChannelInfoPanel.CATCH_UP -> expandedPanel.takeIf { hasCatchUpOptions }
- else -> expandedPanel
- }
- }
-
- LaunchedEffect(expandedPanel) {
- onTransientPanelVisibilityChanged(expandedPanel != null)
- }
-
- androidx.compose.runtime.DisposableEffect(Unit) {
- onDispose { onTransientPanelVisibilityChanged(false) }
- }
-
- BackHandler {
- if (expandedPanel != null) {
- expandedPanel = null
- } else {
- onDismiss()
- }
- }
-
- PlayerOverlayPanel(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 40.dp, vertical = 16.dp)
- ) {
- Column(
- modifier = Modifier.fillMaxWidth(),
- verticalArrangement = Arrangement.spacedBy(8.dp)
- ) {
- Column(
- modifier = Modifier.fillMaxWidth(),
- verticalArrangement = Arrangement.spacedBy(4.dp)
- ) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- if (currentChannel != null) {
- Box(
- modifier = Modifier
- .size(44.dp)
- .clip(RoundedCornerShape(12.dp))
- .border(1.dp, AppColors.Focus.copy(alpha = 0.05f), RoundedCornerShape(12.dp))
- ) {
- ChannelLogoBadge(
- channelName = currentChannel.name,
- logoUrl = currentChannel.logoUrl,
- backgroundColor = AppColors.SurfaceEmphasis.copy(alpha = 0.46f),
- contentPadding = PaddingValues(6.dp),
- textStyle = MaterialTheme.typography.labelLarge,
- textColor = AppColors.TextSecondary,
- modifier = Modifier.fillMaxSize()
- )
- }
- }
- Column(
- modifier = Modifier.weight(1f),
- verticalArrangement = Arrangement.spacedBy(4.dp)
- ) {
- Row(
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- if (displayChannelNumber > 0) {
- StatusPill(
- label = stringResource(R.string.player_live_channel, displayChannelNumber),
- containerColor = AppColors.BrandMuted
- )
- }
- if (showTimeshiftControls) {
- StatusPill(
- label = stringResource(R.string.player_live_rewind_badge),
- containerColor = AppColors.SurfaceEmphasis
- )
- }
- if (currentRecordingStatus == RecordingStatus.RECORDING) {
- StatusPill(
- label = stringResource(R.string.player_recording_badge),
- containerColor = AppColors.Live
- )
- } else if (currentRecordingStatus == RecordingStatus.SCHEDULED) {
- StatusPill(
- label = stringResource(R.string.player_recording_scheduled_badge),
- containerColor = AppColors.BrandMuted
- )
- }
- if (currentChannel != null) {
- Text(
- text = currentChannel.name,
- style = MaterialTheme.typography.titleMedium,
- color = AppColors.TextPrimary,
- fontWeight = FontWeight.Bold,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f, fill = false)
- )
- }
- currentChannel?.currentVariant
- ?.takeIf { channelVariantCount > 1 }
- ?.attributes
- ?.toOverlayBadgeLabel()
- ?.takeIf { it.isNotBlank() }
- ?.let { variantLabel ->
- StatusPill(
- label = variantLabel,
- containerColor = AppColors.SurfaceEmphasis
- )
- }
- if (currentChannel?.catchUpSupported == true) {
- StatusPill(
- label = stringResource(R.string.player_catchup_badge),
- containerColor = AppColors.Live
- )
- }
- }
-
- if (currentProgram != null) {
- Text(
- text = currentProgram.title,
- style = MaterialTheme.typography.titleSmall,
- color = AppColors.TextPrimary,
- fontWeight = FontWeight.Bold,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(10.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = stringResource(
- R.string.player_time_range_minutes,
- timeFormat.format(Date(currentProgram.startTime)),
- timeFormat.format(Date(currentProgram.endTime)),
- currentProgram.durationMinutes
- ),
- style = MaterialTheme.typography.labelSmall,
- color = AppColors.TextSecondary,
- maxLines = 1
- )
- val now = System.currentTimeMillis()
- val start = currentProgram.startTime
- val end = currentProgram.endTime
- if (start in 1..<end) {
- val progress = (now - start).toFloat() / (end - start)
- val remainingMin = ((end - now) / 60000).toInt().coerceAtLeast(0)
- androidx.compose.material3.LinearProgressIndicator(
- progress = { progress.coerceIn(0f, 1f) },
- modifier = Modifier
- .weight(1f)
- .height(4.dp)
- .clip(RoundedCornerShape(999.dp)),
- color = Primary,
- trackColor = AppColors.SurfaceEmphasis.copy(alpha = 0.45f)
- )
- Text(
- text = stringResource(R.string.player_minutes_remaining, remainingMin),
- style = MaterialTheme.typography.labelSmall,
- color = OnSurfaceDim,
- maxLines = 1
- )
- }
- }
- if (nextProgram != null) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = stringResource(R.string.player_next_label),
- style = MaterialTheme.typography.labelSmall,
- color = Primary
- )
- Text(
- text = nextProgram.title,
- style = MaterialTheme.typography.labelSmall,
- color = AppColors.TextSecondary,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f)
- )
- Text(
- text = timeFormat.format(Date(nextProgram.startTime)),
- style = MaterialTheme.typography.labelSmall,
- color = AppColors.TextTertiary
- )
- }
- }
- } else {
- Text(
- text = stringResource(R.string.player_no_guide_data),
- style = MaterialTheme.typography.bodySmall,
- color = AppColors.TextSecondary,
- fontWeight = FontWeight.Medium,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
- }
- }
-
- if (showTimeshiftControls && expandedPanel == ChannelInfoPanel.LIVE_DVR) {
- CompactTimeshiftTransport(
- timeshiftUiState = timeshiftUiState,
- isPlaying = isPlaying,
- onOverlayInteracted = onOverlayInteracted,
- onTogglePlayPause = onTogglePlayPause,
- onSeekBackward = onSeekBackward,
- onSeekForward = onSeekForward,
- onSeekToLiveEdge = onSeekToLiveEdge,
- firstFocusRequester = liveDvrPanelFocusRequester,
- ownerFocusRequester = focusRequester
- )
- }
-
- LazyRow(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(6.dp),
- verticalAlignment = Alignment.CenterVertically,
- contentPadding = PaddingValues(end = 8.dp)
- ) {
- item {
- QuickActionButton(
- icon = if (showTimeshiftControls) "DVR" else stringResource(R.string.player_action_playback),
- label = if (showTimeshiftControls) {
- stringResource(R.string.player_live_dvr_controls)
- } else if (isPlaying) {
- stringResource(R.string.player_pause)
- } else {
- stringResource(R.string.player_play)
- },
- onClick = {
- if (showTimeshiftControls) {
- togglePanel(ChannelInfoPanel.LIVE_DVR)
- } else {
- onTogglePlayPause()
- }
- },
- onInteraction = { handleMainActionFocus(ChannelInfoPanel.LIVE_DVR.takeIf { showTimeshiftControls }) },
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {
- Primary.copy(alpha = 0.30f)
- } else {
- Primary.copy(alpha = 0.20f)
- },
- focusedContainerColor = Primary,
- pressedContainerColor = Primary.copy(alpha = 0.8f)
- ),
- modifier = Modifier
- .focusRequester(focusRequester)
- .focusProperties {
- if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {
- up = liveDvrPanelFocusRequester
- }
- }
- )
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_mute),
- label = if (isMuted) stringResource(R.string.player_unmute) else stringResource(R.string.player_mute),
- onClick = onToggleMute,
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- if (subtitleTrackCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_subs),
- label = stringResource(R.string.player_subs),
- onClick = onOpenSubtitleTracks,
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- if (videoQualityCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_quality),
- label = stringResource(R.string.player_quality_short),
- onClick = onOpenVideoTracks,
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- if (channelVariantCount > 1) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_variants),
- label = stringResource(R.string.player_variants_short),
- onClick = onOpenVariants,
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- if (audioTrackCount > 0) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_audio),
- label = stringResource(R.string.player_audio),
- onClick = onOpenAudioTracks,
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- if (!isCastConnected) {
- item {
- QuickActionButton(
- icon = "A/V",
- label = stringResource(R.string.player_av_sync_short),
- onClick = {
- expandedPanel = null
- onOpenAudioVideoSync()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_guide),
- label = stringResource(R.string.player_epg_short),
- onClick = {
- expandedPanel = null
- onDismiss()
- onOpenFullEpg()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_split),
- label = stringResource(R.string.player_multiview_short),
- onClick = {
- expandedPanel = null
- onDismiss()
- onOpenSplitScreen()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_diagnostics),
- label = stringResource(R.string.player_stats),
- onClick = {
- expandedPanel = null
- onToggleDiagnostics()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- if (!lastVisitedCategoryName.isNullOrBlank()) {
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_group),
- label = lastVisitedCategoryName,
- onClick = {
- expandedPanel = null
- onOpenLastGroup()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
- item {
- QuickActionButton(
- icon = "REC",
- label = stringResource(R.string.player_record),
- onClick = { togglePanel(ChannelInfoPanel.RECORD) },
- onInteraction = { handleMainActionFocus(ChannelInfoPanel.RECORD) },
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (expandedPanel == ChannelInfoPanel.RECORD) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,
- focusedContainerColor = Primary.copy(alpha = 0.85f)
- ),
- modifier = Modifier
- .focusRequester(recordButtonFocusRequester)
- .focusProperties {
- if (expandedPanel == ChannelInfoPanel.RECORD) {
- up = recordPanelFocusRequester
- }
- }
- )
- }
- if (hasCatchUpOptions) {
- item {
- QuickActionButton(
- icon = "C-UP",
- label = stringResource(R.string.player_catchup_badge),
- onClick = { togglePanel(ChannelInfoPanel.CATCH_UP) },
- onInteraction = { handleMainActionFocus(ChannelInfoPanel.CATCH_UP) },
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (expandedPanel == ChannelInfoPanel.CATCH_UP) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,
- focusedContainerColor = Primary.copy(alpha = 0.85f)
- ),
- modifier = Modifier
- .focusRequester(catchUpButtonFocusRequester)
- .focusProperties {
- if (expandedPanel == ChannelInfoPanel.CATCH_UP) {
- up = catchUpPanelFocusRequester
- }
- }
- )
- }
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_cast),
- label = if (isCastConnected) stringResource(R.string.player_stop_casting) else stringResource(R.string.player_cast),
- onClick = {
- expandedPanel = null
- if (isCastConnected) onStopCasting() else onCast()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_pip),
- label = stringResource(R.string.player_pip_short),
- onClick = {
- expandedPanel = null
- onEnterPictureInPicture()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- item {
- QuickActionButton(
- icon = stringResource(R.string.player_action_view),
- label = currentAspectRatio,
- onClick = {
- expandedPanel = null
- onToggleAspectRatio()
- },
- onInteraction = { handleMainActionFocus(null) }
- )
- }
- }
-
- when (expandedPanel) {
- ChannelInfoPanel.RECORD -> {
- ChannelInfoActionMenuTray(
- title = stringResource(R.string.player_record_options),
- actions = buildList {
- if (currentRecordingStatus == RecordingStatus.RECORDING || currentRecordingStatus == RecordingStatus.SCHEDULED) {
- add(
- ChannelInfoMenuEntry(
- label = if (currentRecordingStatus == RecordingStatus.SCHEDULED) {
- stringResource(R.string.player_cancel_scheduled_recording)
- } else {
- stringResource(R.string.player_stop_recording)
- }
- ) {
- expandedPanel = null
- onStopRecording()
- }
- )
- } else {
- add(
- ChannelInfoMenuEntry(stringResource(R.string.player_record_now)) {
- expandedPanel = null
- onStartRecording()
- }
- )
- }
- add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_recording)) {
- expandedPanel = null
- onScheduleRecording()
- })
- add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_daily_recording)) {
- expandedPanel = null
- onScheduleDailyRecording()
- })
- add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_weekly_recording)) {
- expandedPanel = null
- onScheduleWeeklyRecording()
- })
- },
- onInteraction = onOverlayInteracted,
- firstActionFocusRequester = recordPanelFocusRequester,
- ownerFocusRequester = recordButtonFocusRequester
- )
- }
-
- ChannelInfoPanel.CATCH_UP -> {
- ChannelInfoActionMenuTray(
- title = stringResource(R.string.player_catchup_options),
- actions = buildList {
- if (currentProgram?.hasArchive == true) {
- add(ChannelInfoMenuEntry(stringResource(R.string.player_restart)) {
- expandedPanel = null
- onRestartProgram()
- onDismiss()
- })
- }
- if (currentChannel?.catchUpSupported == true) {
- add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_archive)) {
- expandedPanel = null
- onDismiss()
- onOpenArchive()
- })
- }
- add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_guide_catchup)) {
- expandedPanel = null
- onDismiss()
- onOpenFullEpg()
- })
- },
- onInteraction = onOverlayInteracted,
- firstActionFocusRequester = catchUpPanelFocusRequester,
- ownerFocusRequester = catchUpButtonFocusRequester
- )
- }
-
- ChannelInfoPanel.LIVE_DVR,
- null -> Unit
- }
- }
- }
-}
-
-private enum class ChannelInfoPanel {
- LIVE_DVR,
- RECORD,
- CATCH_UP
-}
-
-private fun com.streamvault.domain.model.LiveChannelVariantAttributes.toOverlayBadgeLabel(): String {
- val parts = buildList {
- resolutionLabel?.let(::add)
- codecLabel?.takeIf { it == "HEVC" || it == "AV1" }?.let(::add)
- frameRate?.takeIf { it >= 50 }?.let { add("${it}fps") }
- if (isHdr) {
- add("HDR")
- }
- sourceHint?.takeIf { it == "Backup" || it == "Alternate" || it == "Lite" || it == "Mobile" }?.let(::add)
- }
- return parts.joinToString(" ")
-}
-
-private data class ChannelInfoMenuEntry(
- val label: String,
- val onClick: () -> Unit
-)
-
-@Composable
-private fun CompactTimeshiftTransport(
- timeshiftUiState: PlayerTimeshiftUiState,
- isPlaying: Boolean,
- onOverlayInteracted: () -> Unit,
- onTogglePlayPause: () -> Unit,
- onSeekBackward: () -> Unit,
- onSeekForward: () -> Unit,
- onSeekToLiveEdge: () -> Unit,
- firstFocusRequester: FocusRequester,
- ownerFocusRequester: FocusRequester
-) {
- val transportReady = timeshiftUiState.bufferDepthMs > 1_000L &&
- timeshiftUiState.engineState.status != LiveTimeshiftStatus.PREPARING
- val behindLive = timeshiftUiState.bufferedBehindLiveMs.coerceAtLeast(0L)
- val bufferDepth = timeshiftUiState.bufferDepthMs.coerceAtLeast(0L)
- val liveProgress = if (bufferDepth > 0L) {
- ((bufferDepth - behindLive).toFloat() / bufferDepth.toFloat()).coerceIn(0f, 1f)
- } else {
- 1f
- }
- val statusLine = when {
- !transportReady -> timeshiftUiState.statusMessage.ifBlank {
- stringResource(R.string.player_live_timeshift_buffering)
- }
- behindLive > 1_000L -> stringResource(
- R.string.player_live_offset,
- formatTimeLabel(behindLive)
- )
- else -> stringResource(R.string.player_live_ready)
- }
- var lastTransportActionAtMs by remember { mutableStateOf(0L) }
-
- fun runTransportAction(enabled: Boolean, action: () -> Unit) {
- if (!enabled) return
- val now = System.currentTimeMillis()
- if (now - lastTransportActionAtMs < 240L) return
- lastTransportActionAtMs = now
- onOverlayInteracted()
- action()
- }
-
- Surface(
- shape = RoundedCornerShape(18.dp),
- colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))
- ) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 12.dp, vertical = 10.dp),
- verticalArrangement = Arrangement.spacedBy(10.dp)
- ) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Surface(
- shape = RoundedCornerShape(14.dp),
- colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 9.dp, vertical = 7.dp),
- verticalArrangement = Arrangement.spacedBy(2.dp)
- ) {
- Text(
- text = stringResource(R.string.player_live_rewind_badge),
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- color = Primary
- )
- Text(
- text = statusLine,
- style = MaterialTheme.typography.titleSmall.copy(fontSize = 20.sp),
- color = Color.White,
- fontWeight = FontWeight.Bold
- )
- Text(
- text = stringResource(
- R.string.player_live_buffer_depth,
- formatTimeLabel(bufferDepth)
- ),
- style = MaterialTheme.typography.labelMedium,
- color = Color.White.copy(alpha = 0.7f)
- )
- }
- }
-
- Row(
- modifier = Modifier.weight(1f),
- horizontalArrangement = Arrangement.End,
- verticalAlignment = Alignment.CenterVertically
- ) {
- CompactTransportButton(
- topLabel = stringResource(R.string.player_rewind),
- mainLabel = stringResource(R.string.player_seek_back_10),
- enabled = transportReady,
- onInteraction = onOverlayInteracted,
- onClick = { runTransportAction(transportReady, onSeekBackward) },
- modifier = Modifier
- .focusRequester(firstFocusRequester)
- .focusProperties { down = ownerFocusRequester }
- )
- Spacer(modifier = Modifier.width(8.dp))
- TvClickableSurface(
- onClick = { runTransportAction(transportReady, onTogglePlayPause) },
- enabled = transportReady,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Primary.copy(alpha = 0.88f),
- focusedContainerColor = Primary,
- disabledContainerColor = Primary.copy(alpha = 0.28f)
- ),
- modifier = Modifier
- .size(52.dp)
- .focusProperties { down = ownerFocusRequester }
- ) {
- Box(
- modifier = Modifier.fillMaxSize(),
- contentAlignment = Alignment.Center
- ) {
- if (isPlaying) {
- Text(
- text = "II",
- style = MaterialTheme.typography.headlineSmall,
- color = Color.White
- )
- } else {
- androidx.tv.material3.Icon(
- imageVector = Icons.Default.PlayArrow,
- contentDescription = stringResource(R.string.player_play),
- tint = Color.White,
- modifier = Modifier.size(26.dp)
- )
- }
- }
- }
- Spacer(modifier = Modifier.width(8.dp))
- CompactTransportButton(
- topLabel = stringResource(R.string.player_forward),
- mainLabel = stringResource(R.string.player_seek_forward_10),
- enabled = transportReady && timeshiftUiState.canSeekToLive,
- onInteraction = onOverlayInteracted,
- onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekForward) },
- modifier = Modifier.focusProperties { down = ownerFocusRequester }
- )
- Spacer(modifier = Modifier.width(8.dp))
- CompactTransportButton(
- topLabel = stringResource(R.string.player_live_ready),
- mainLabel = stringResource(R.string.player_jump_to_live_short),
- enabled = transportReady && timeshiftUiState.canSeekToLive,
- highlighted = !timeshiftUiState.canSeekToLive,
- onInteraction = onOverlayInteracted,
- onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekToLiveEdge) },
- modifier = Modifier.focusProperties { down = ownerFocusRequester }
- )
- }
- }
-
- androidx.compose.material3.LinearProgressIndicator(
- progress = { liveProgress },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp)
- .clip(RoundedCornerShape(999.dp)),
- color = Primary,
- trackColor = Color.White.copy(alpha = 0.16f)
- )
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = stringResource(R.string.player_live_buffer_start),
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.52f)
- )
- Text(
- text = if (behindLive > 1_000L) {
- stringResource(R.string.player_live_offset, formatTimeLabel(behindLive))
- } else {
- stringResource(R.string.player_live_ready)
- },
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.76f)
- )
- Text(
- text = stringResource(R.string.player_live_buffer_end),
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.52f)
- )
- }
- }
- }
-}
-
-@Composable
-private fun CompactTransportButton(
- topLabel: String,
- mainLabel: String,
- enabled: Boolean,
- highlighted: Boolean = false,
- onInteraction: () -> Unit,
- onClick: () -> Unit,
- modifier: Modifier = Modifier
-) {
- TvClickableSurface(
- onClick = onClick,
- enabled = enabled,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (highlighted) {
- Primary.copy(alpha = 0.18f)
- } else {
- Color.White.copy(alpha = 0.08f)
- },
- focusedContainerColor = Primary.copy(alpha = 0.86f),
- disabledContainerColor = Color.White.copy(alpha = 0.04f)
- ),
- modifier = modifier
- .widthIn(min = 68.dp)
- .onFocusChanged {
- if (it.isFocused) onInteraction()
- }
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(1.dp)
- ) {
- Text(
- text = topLabel,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- color = Color.White.copy(alpha = if (enabled) 0.72f else 0.32f)
- )
- Text(
- text = mainLabel,
- style = MaterialTheme.typography.titleSmall.copy(fontSize = 16.sp),
- color = if (enabled) Color.White else Color.White.copy(alpha = 0.32f),
- fontWeight = FontWeight.Bold
- )
- }
- }
-}
-
-@Composable
-private fun ChannelInfoActionMenuTray(
- title: String,
- actions: List<ChannelInfoMenuEntry>,
- onInteraction: () -> Unit,
- firstActionFocusRequester: FocusRequester,
- ownerFocusRequester: FocusRequester
-) {
- if (actions.isEmpty()) return
-
- Surface(
- shape = RoundedCornerShape(18.dp),
- colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))
- ) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 12.dp, vertical = 10.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp)
- ) {
- Text(
- text = title,
- style = MaterialTheme.typography.labelLarge,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- LazyRow(
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- itemsIndexed(actions) { index, action ->
- CompactMenuActionButton(
- text = action.label,
- onClick = action.onClick,
- onInteraction = onInteraction,
- modifier = (if (index == 0) Modifier.focusRequester(firstActionFocusRequester) else Modifier)
- .focusProperties { down = ownerFocusRequester }
- )
- }
- }
- }
- }
-}
-
-@Composable
-private fun CompactMenuActionButton(
- text: String,
- onClick: () -> Unit,
- onInteraction: () -> Unit,
- modifier: Modifier = Modifier
-) {
- TvClickableSurface(
- onClick = {
- onInteraction()
- onClick()
- },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Color.White.copy(alpha = 0.08f),
- focusedContainerColor = Color.White.copy(alpha = 0.16f)
- ),
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1.0f),
- border = ClickableSurfaceDefaults.border(
- focusedBorder = Border(
- border = androidx.compose.foundation.BorderStroke(1.5.dp, Color.White.copy(alpha = 0.75f))
- )
- ),
- modifier = modifier
- .onFocusChanged {
- if (it.isFocused) onInteraction()
- }
- ) {
- Text(
- text = text,
- style = MaterialTheme.typography.bodyMedium,
- color = Color.White,
- fontWeight = FontWeight.Medium,
- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
- )
- }
-}
-
-private fun formatTimeLabel(ms: Long): String {
- val totalSeconds = (ms / 1_000L).coerceAtLeast(0L)
- val hours = totalSeconds / 3_600L
- val minutes = (totalSeconds % 3_600L) / 60L
- val seconds = totalSeconds % 60L
- return if (hours > 0L) {
- String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds)
- } else {
- String.format(Locale.getDefault(), "%d:%02d", minutes, seconds)
- }
-}
-
-@Composable
-private fun QuickActionButton(
- icon: String,
- label: String,
- modifier: Modifier = Modifier,
- colors: androidx.tv.material3.ClickableSurfaceColors = ClickableSurfaceDefaults.colors(
- containerColor = AppColors.SurfaceEmphasis,
- focusedContainerColor = Primary.copy(alpha = 0.85f)
- ),
- onInteraction: () -> Unit = {},
- onClick: () -> Unit
-) {
- TvClickableSurface(
- onClick = {
- onInteraction()
- onClick()
- },
- modifier = modifier
- .widthIn(min = 84.dp, max = 138.dp)
- .onFocusChanged {
- if (it.isFocused) onInteraction()
- },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = colors,
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1.01f)
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
- horizontalAlignment = Alignment.Start,
- verticalArrangement = Arrangement.spacedBy(0.dp)
- ) {
- AnimatedContent(
- targetState = icon,
- transitionSpec = {
- (fadeIn() + scaleIn()).togetherWith(fadeOut() + scaleOut())
- },
- label = "iconToggle"
- ) { targetIcon ->
- Text(
- text = targetIcon.uppercase(Locale.getDefault()),
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- color = AppColors.BrandStrong,
- fontWeight = FontWeight.Bold,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- Text(
- text = label,
- style = MaterialTheme.typography.bodySmall.copy(fontSize = 10.sp),
- color = AppColors.TextPrimary,
- fontWeight = FontWeight.Bold,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
-}
-
-@Composable
-fun ChannelListOverlay(
- channels: List<Channel>,
- recentChannels: List<Channel>,
- currentChannelId: Long,
- overlayFocusRequester: FocusRequester = remember { FocusRequester() },
- lastVisitedCategoryName: String? = null,
- onOpenLastGroup: () -> Unit = {},
- onOpenCategories: () -> Unit = {},
- onSelectChannel: (Long) -> Unit,
- onDismiss: () -> Unit,
- onOverlayInteracted: () -> Unit = {}
-) {
- val listState = rememberLazyListState()
- val currentIndex = remember(channels, currentChannelId) {
- channels.indexOfFirst { it.id == currentChannelId }.coerceAtLeast(0)
- }
- val channelNumbersById = remember(channels) {
- channels.mapIndexed { index, channel ->
- channel.id to (channel.number.takeIf { it > 0 } ?: (index + 1))
- }.toMap()
- }
- val canScrollUp by remember { derivedStateOf { listState.canScrollBackward } }
- val canScrollDown by remember { derivedStateOf { listState.canScrollForward } }
- val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
- // Count header items before the channels list so we can map channel index → lazy index
- val headerItemCount = remember(lastVisitedCategoryName, recentChannels) {
- var count = 2 // title row + channel list hint (always present)
- if (!lastVisitedCategoryName.isNullOrBlank()) count++ // last group hint
- if (recentChannels.isNotEmpty()) count++ // recent channels row
- count
- }
-
- LaunchedEffect(channels, currentIndex, headerItemCount) {
- if (channels.isNotEmpty()) {
- listState.scrollToItem(headerItemCount + currentIndex)
- }
- }
-
- BackHandler { onDismiss() }
-
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.18f))
- ) {
- BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
- val isTelevisionDevice = rememberIsTelevisionDevice()
- val panelModifier = if (maxWidth < 700.dp) {
- Modifier
- .fillMaxWidth(0.9f)
- .fillMaxHeight()
- .padding(20.dp)
- } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
- Modifier
- .fillMaxWidth(0.5f)
- .fillMaxHeight()
- .padding(20.dp)
- } else {
- Modifier
- .width(540.dp)
- .fillMaxWidth()
- .fillMaxHeight()
- .padding(20.dp)
- }
-
- Box(modifier = panelModifier) {
- PlayerOverlayPanel(modifier = Modifier.fillMaxSize()) {
- androidx.compose.foundation.lazy.LazyColumn(
- state = listState,
- modifier = Modifier.fillMaxSize(),
- contentPadding = PaddingValues(top = 10.dp, bottom = 20.dp),
- verticalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- item {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 8.dp, vertical = 8.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = stringResource(R.string.player_channel_list_title, channels.size),
- style = MaterialTheme.typography.titleMedium,
- color = Primary
- )
- if (!lastVisitedCategoryName.isNullOrBlank()) {
- TvClickableSurface(
- onClick = {
- onOverlayInteracted()
- onOpenLastGroup()
- },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = AppColors.SurfaceEmphasis,
- focusedContainerColor = Primary
- ),
- modifier = Modifier.onFocusChanged {
- if (it.isFocused) onOverlayInteracted()
- }
- ) {
- Text(
- text = stringResource(R.string.player_last_group_label, lastVisitedCategoryName),
- style = MaterialTheme.typography.labelMedium,
- color = Color.White,
- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
- )
- }
- }
- }
- }
- if (!lastVisitedCategoryName.isNullOrBlank()) {
- item {
- Text(
- text = stringResource(R.string.player_last_group_hint),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim,
- modifier = Modifier.padding(horizontal = 8.dp)
- )
- }
- }
- item {
- Text(
- text = stringResource(R.string.player_channel_list_hint),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim,
- modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
- )
- }
- if (recentChannels.isNotEmpty()) {
- item {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(vertical = 4.dp)
- ) {
- Text(
- text = stringResource(R.string.player_recent_channels),
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim,
- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp)
- )
- LazyRow(
- horizontalArrangement = Arrangement.spacedBy(8.dp),
- contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
- ) {
- itemsIndexed(
- recentChannels,
- key = { index, channel ->
- "recent:${channel.id}:${channel.streamId}:${channel.epgChannelId.orEmpty()}:${index}"
- }
- ) { index, channel ->
- TvClickableSurface(
- onClick = {
- onOverlayInteracted()
- onSelectChannel(channel.id)
- onDismiss()
- },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = AppColors.SurfaceEmphasis,
- focusedContainerColor = Primary
- ),
- modifier = Modifier.onFocusChanged {
- if (it.isFocused) onOverlayInteracted()
- }
- ) {
- Row(
- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(8.dp)
- ) {
- val recentNumber = channelNumbersById[channel.id]
- ?.toString()
- ?.padStart(2, '0')
- ?: channel.number
- .takeIf { it > 0 }
- ?.toString()
- ?.padStart(2, '0')
- ?: "--"
- Text(
- text = recentNumber,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 12.sp),
- color = Color.White.copy(alpha = 0.75f)
- )
- Text(
- text = channel.name,
- style = MaterialTheme.typography.bodySmall.copy(fontSize = 13.sp),
- color = Color.White,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
- }
- }
- }
- }
- }
- items(channels.size) { index ->
- val channel = channels[index]
- val isSelected = channel.id == currentChannelId
- val shouldRequestFocus = isSelected
- val channelNumber = channel.number.takeIf { it > 0 } ?: (index + 1)
- var isFocused by remember { mutableStateOf(false) }
- val bgColor = when {
- isFocused -> Primary
- isSelected -> Primary.copy(alpha = 0.20f)
- else -> AppColors.Surface.copy(alpha = 0.68f)
- }
-
- TvClickableSurface(
- onClick = {
- onSelectChannel(channel.id)
- onDismiss()
- },
- modifier = Modifier
- .fillMaxWidth()
- .padding(vertical = 3.dp)
- .onFocusChanged { focusState ->
- isFocused = focusState.isFocused
- if (focusState.isFocused) {
- onOverlayInteracted()
- }
- }
- .then(
- if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
- else Modifier
- ),
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = bgColor,
- focusedContainerColor = bgColor
- )
- ) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 10.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(10.dp)
- ) {
- Text(
- text = channelNumber.toString().padStart(2, '0'),
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 13.sp),
- color = Color.White.copy(alpha = 0.72f),
- textAlign = TextAlign.Start,
- modifier = Modifier.width(32.dp)
- )
- Text(
- text = channel.name,
- style = MaterialTheme.typography.bodyLarge.copy(fontSize = 17.sp),
- color = Color.White,
- maxLines = 1,
- overflow = if (isFocused) TextOverflow.Clip else TextOverflow.Ellipsis,
- modifier = Modifier
- .weight(1f)
- .then(
- if (isFocused) {
- Modifier.basicMarquee(
- iterations = Int.MAX_VALUE,
- initialDelayMillis = 600,
- repeatDelayMillis = 900,
- velocity = 20.dp
- )
- } else {
- Modifier
- }
- )
- )
- if (isSelected) {
- StatusPill(
- label = stringResource(R.string.player_channel_selected),
- containerColor = AppColors.BrandMuted
- )
- }
- if (channel.catchUpSupported) {
- StatusPill(
- label = stringResource(R.string.player_archive_badge),
- containerColor = AppColors.Warning,
- contentColor = Color.Black
- )
- }
- }
- }
- }
- }
- }
-
- // Up arrow — fades in when there are channels scrolled above the visible area
- AnimatedVisibility(
- visible = canScrollUp,
- enter = fadeIn(),
- exit = fadeOut(),
- modifier = Modifier.align(Alignment.TopCenter)
- ) {
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(48.dp)
- .background(
- Brush.verticalGradient(
- colors = listOf(AppColors.Canvas.copy(alpha = 0.9f), Color.Transparent)
- ),
- RoundedCornerShape(topStart = 26.dp, topEnd = 26.dp)
- ),
- contentAlignment = Alignment.TopCenter
- ) {
- Text(
- text = "\u25b2",
- color = Color.White.copy(alpha = 0.55f),
- style = MaterialTheme.typography.labelMedium,
- modifier = Modifier.padding(top = 8.dp)
- )
- }
- }
-
- // Down arrow — fades in when there are channels below the visible area
- AnimatedVisibility(
- visible = canScrollDown,
- enter = fadeIn(),
- exit = fadeOut(),
- modifier = Modifier.align(Alignment.BottomCenter)
- ) {
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(48.dp)
- .background(
- Brush.verticalGradient(
- colors = listOf(Color.Transparent, AppColors.Canvas.copy(alpha = 0.9f))
- ),
- RoundedCornerShape(bottomStart = 26.dp, bottomEnd = 26.dp)
- ),
- contentAlignment = Alignment.BottomCenter
- ) {
- Text(
- text = "\u25bc",
- color = Color.White.copy(alpha = 0.55f),
- style = MaterialTheme.typography.labelMedium,
- modifier = Modifier.padding(bottom = 8.dp)
- )
- }
- }
-
- // Vertical categories tab — fixed to the left edge, always visible
- TvClickableSurface(
- onClick = {
- onOverlayInteracted()
- onOpenCategories()
- },
- modifier = Modifier
- .align(if (isRtl) Alignment.CenterEnd else Alignment.CenterStart)
- .offset(x = if (isRtl) 28.dp else (-28).dp)
- .onFocusChanged { if (it.isFocused) onOverlayInteracted() },
- shape = ClickableSurfaceDefaults.shape(
- if (isRtl) RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp)
- else RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)
- ),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.92f),
- focusedContainerColor = Primary
- )
- ) {
- Column(
- modifier = Modifier
- .width(28.dp)
- .height(96.dp),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.Center
- ) {
- Text(
- text = if (isRtl) "\u25ba" else "\u25c4",
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.85f)
- )
- }
- }
- }
- }
- }
-}
-
-@Composable
-fun EpgOverlay(
- currentChannel: Channel?,
- displayChannelNumber: Int,
- currentProgram: Program?,
- nextProgram: Program?,
- upcomingPrograms: List<Program>,
- onDismiss: () -> Unit,
- onOpenArchiveBrowser: (() -> Unit)? = null,
- onOverlayInteracted: () -> Unit = {}
-) {
- val appTimeFormat = LocalAppTimeFormat.current
- val timeFormat = remember(appTimeFormat) { appTimeFormat.createTimeFormat() }
- val listState = rememberLazyListState()
- val filteredUpcoming = remember(upcomingPrograms, currentProgram, nextProgram) {
- upcomingPrograms.filter { it.id != currentProgram?.id && it.id != nextProgram?.id }
- }
- val displayPrograms = remember(filteredUpcoming, nextProgram) {
- if (nextProgram != null) listOf(nextProgram) + filteredUpcoming else filteredUpcoming
- }
-
- BackHandler { onDismiss() }
-
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.18f))
- ) {
- BoxWithConstraints(
- modifier = Modifier
- .fillMaxSize()
- .align(Alignment.CenterEnd)
- ) {
- val isTelevisionDevice = rememberIsTelevisionDevice()
- val panelModifier = if (maxWidth < 700.dp) {
- Modifier
- .fillMaxWidth(0.9f)
- .padding(24.dp)
- } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
- Modifier
- .fillMaxWidth(0.54f)
- .padding(24.dp)
- } else {
- Modifier
- .width(520.dp)
- .padding(24.dp)
- }
-
- PlayerOverlayPanel(modifier = panelModifier) {
- androidx.compose.foundation.lazy.LazyColumn(
- state = listState,
- modifier = Modifier.fillMaxSize(),
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- item {
- Text(
- text = stringResource(R.string.epg_title),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- if (currentChannel != null) {
- Spacer(Modifier.height(8.dp))
- Text(
- text = stringResource(R.string.channel_number_name_format, displayChannelNumber, currentChannel.name),
- style = MaterialTheme.typography.headlineSmall,
- color = Color.White,
- fontWeight = FontWeight.Bold
- )
- if (currentChannel.catchUpSupported) {
- Spacer(Modifier.height(8.dp))
- if (onOpenArchiveBrowser != null) {
- QuickActionButton(
- icon = stringResource(R.string.player_catchup_badge),
- label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
- onClick = {
- onOverlayInteracted()
- onOpenArchiveBrowser()
- },
- onInteraction = onOverlayInteracted
- )
- } else {
- StatusPill(
- label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
- containerColor = AppColors.BrandMuted
- )
- }
- }
- }
- Spacer(Modifier.height(8.dp))
- Text(
- text = stringResource(R.string.player_epg_overlay_hint),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
-
- item {
- androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
- Spacer(Modifier.height(8.dp))
- Text(
- text = stringResource(R.string.epg_now_playing),
- style = MaterialTheme.typography.labelMedium,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- Spacer(Modifier.height(8.dp))
- if (currentProgram != null) {
- Text(
- currentProgram.title,
- style = MaterialTheme.typography.titleMedium,
- color = AppColors.TextPrimary,
- fontWeight = FontWeight.Bold
- )
- Spacer(Modifier.height(4.dp))
- Row(verticalAlignment = Alignment.CenterVertically) {
- Text(
- text = stringResource(R.string.time_range_format, timeFormat.format(Date(currentProgram.startTime)), timeFormat.format(Date(currentProgram.endTime))),
- style = MaterialTheme.typography.bodyMedium,
- color = TextSecondary
- )
- Spacer(Modifier.width(12.dp))
- Text(
- text = stringResource(R.string.label_duration_min, currentProgram.durationMinutes),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- if (currentProgram.lang.isNotEmpty()) {
- Spacer(Modifier.width(8.dp))
- Text(
- text = currentProgram.lang.uppercase(),
- style = MaterialTheme.typography.labelSmall,
- color = Primary.copy(alpha = 0.7f)
- )
- }
- }
- Spacer(Modifier.height(4.dp))
- val now = System.currentTimeMillis()
- val start = currentProgram.startTime
- val end = currentProgram.endTime
- if (start in 1..<end) {
- val progress = (now - start).toFloat() / (end - start)
- val remainingMin = ((end - now) / 60000).toInt().coerceAtLeast(0)
- androidx.compose.material3.LinearProgressIndicator(
- progress = { progress.coerceIn(0f, 1f) },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp),
- color = Primary,
- trackColor = AppColors.SurfaceEmphasis
- )
- Spacer(Modifier.height(4.dp))
- Text(
- text = stringResource(R.string.player_minutes_remaining, remainingMin),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
- if (!currentProgram.description.isNullOrEmpty()) {
- val description = currentProgram.description.orEmpty()
- Spacer(Modifier.height(12.dp))
- Text(
- description,
- style = MaterialTheme.typography.bodyMedium,
- color = Color.White.copy(alpha = 0.7f),
- maxLines = 6,
- overflow = TextOverflow.Ellipsis
- )
- }
- } else {
- Text(stringResource(R.string.epg_no_info), color = OnSurfaceDim)
- }
- }
-
- if (upcomingPrograms.isNotEmpty()) {
- item {
- Spacer(Modifier.height(8.dp))
- androidx.compose.material3.HorizontalDivider(color = SurfaceVariant)
- Spacer(Modifier.height(8.dp))
- Text(
- text = stringResource(R.string.epg_upcoming_schedule),
- style = MaterialTheme.typography.labelMedium,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- }
- items(displayPrograms.size) { index ->
- val program = displayPrograms[index]
- val isNext = index == 0 && nextProgram != null
-
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(12.dp))
- .background(
- if (isNext) Primary.copy(alpha = 0.08f) else Color.Transparent
- )
- ) {
- Column(modifier = Modifier.padding(12.dp)) {
- if (isNext) {
- Text(
- text = stringResource(R.string.epg_up_next),
- style = MaterialTheme.typography.labelSmall,
- color = Primary,
- fontWeight = FontWeight.Bold
- )
- Spacer(Modifier.height(4.dp))
- }
- Text(
- text = program.title,
- style = MaterialTheme.typography.bodyLarge,
- color = if (isNext) Color.White else Color.White.copy(alpha = 0.8f),
- fontWeight = if (isNext) FontWeight.Bold else FontWeight.Normal,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- Spacer(Modifier.height(2.dp))
- Row {
- Text(
- text = stringResource(R.string.time_range_format, timeFormat.format(Date(program.startTime)), timeFormat.format(Date(program.endTime))),
- style = MaterialTheme.typography.bodySmall,
- color = TextSecondary
- )
- Spacer(Modifier.width(8.dp))
- Text(
- text = stringResource(R.string.label_duration_min, program.durationMinutes),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- if (program.hasArchive) {
- Spacer(Modifier.width(8.dp))
- StatusPill(
- label = stringResource(R.string.player_archive_badge),
- containerColor = AppColors.Warning,
- contentColor = Color.Black
- )
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
-}
-
-@Composable
-fun DiagnosticsOverlay(
- stats: PlayerStats,
- diagnostics: PlayerDiagnosticsUiState,
- modifier: Modifier = Modifier
-) {
- PlayerOverlayPanel(modifier = modifier.width(320.dp)) {
- Column(
- modifier = Modifier
- .heightIn(max = 300.dp)
- .fillMaxWidth()
- .verticalScroll(rememberScrollState()),
- verticalArrangement = Arrangement.spacedBy(3.dp)
- ) {
- Text(
- text = stringResource(R.string.player_diagnostics_title),
- color = Primary,
- style = MaterialTheme.typography.labelMedium.copy(fontSize = 11.sp),
- fontWeight = FontWeight.Bold
- )
- PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_source))
- if (diagnostics.providerName.isNotBlank()) {
- PlayerMetaRow(stringResource(R.string.player_diagnostics_provider), diagnostics.providerName)
- }
- if (diagnostics.providerSourceLabel.isNotBlank()) {
- PlayerMetaRow(stringResource(R.string.player_diagnostics_source), diagnostics.providerSourceLabel)
- }
- PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_playback))
- PlayerMetaRow(stringResource(R.string.player_diagnostics_decoder), diagnostics.decoderMode.name)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_active_decoder), diagnostics.activeDecoderName)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_surface), diagnostics.renderSurfaceType)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_stream_class), diagnostics.streamClassLabel)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_playback_state), diagnostics.playbackStateLabel)
- if (diagnostics.archiveSupportLabel.isNotBlank()) {
- PlayerMetaRow(stringResource(R.string.player_diagnostics_archive), diagnostics.archiveSupportLabel)
- }
- PlayerMetaRow(stringResource(R.string.player_diagnostics_alternates), diagnostics.alternativeStreamCount.toString())
- if (diagnostics.channelErrorCount > 0) {
- PlayerMetaRow(stringResource(R.string.player_diagnostics_channel_errors), diagnostics.channelErrorCount.toString())
- }
- PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_video))
- PlayerMetaRow(stringResource(R.string.player_diagnostics_resolution), "${stats.width}x${stats.height}")
- PlayerMetaRow(stringResource(R.string.player_diagnostics_video_codec), stats.videoCodec)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_video_bitrate), "${stats.videoBitrate / 1000} kbps")
- PlayerMetaRow(stringResource(R.string.player_diagnostics_dropped_frames), stats.droppedFrames.toString())
- PlayerMetaRow(stringResource(R.string.player_diagnostics_video_stalls), diagnostics.videoStallCount.toString())
- if (diagnostics.lastVideoFrameAgoMs > 0L) {
- PlayerMetaRow(stringResource(R.string.player_diagnostics_last_frame), "${diagnostics.lastVideoFrameAgoMs} ms")
- }
- if (stats.ttffMs > 0L) {
- PlayerMetaRow("TTFF", "${stats.ttffMs} ms")
- }
- PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_audio))
- PlayerMetaRow(stringResource(R.string.player_diagnostics_audio_codec), stats.audioCodec)
- PlayerMetaRow(stringResource(R.string.player_diagnostics_av_offset), formatOffsetLabel(diagnostics.audioVideoOffsetMs))
- PlayerOverlaySectionLabel(stringResource(R.string.player_diagnostics_section_recovery))
- diagnostics.lastFailureReason?.let { reason ->
- PlayerMetaRow(stringResource(R.string.player_diagnostics_last_failure), reason, maxLines = 3)
- }
- if (diagnostics.recentRecoveryActions.isNotEmpty()) {
- Text(
- text = stringResource(R.string.player_diagnostics_recovery_actions),
- color = Primary,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- fontWeight = FontWeight.Bold
- )
- diagnostics.recentRecoveryActions.forEach { action ->
- Text(
- text = action,
- color = AppColors.TextSecondary,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
- if (diagnostics.troubleshootingHints.isNotEmpty()) {
- Text(
- text = stringResource(R.string.player_diagnostics_troubleshooting),
- color = Primary,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- fontWeight = FontWeight.Bold
- )
- diagnostics.troubleshootingHints.forEach { hint ->
- Text(
- text = hint,
- color = AppColors.TextSecondary,
- style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- }
- }
- }
- }
-}
-
-private fun formatOffsetLabel(offsetMs: Int): String = when {
- offsetMs > 0 -> "+$offsetMs ms"
- offsetMs < 0 -> "$offsetMs ms"
- else -> "0 ms"
-}
-
-@Composable
-fun CategoryListOverlay(
- categories: List<com.streamvault.domain.model.Category>,
- currentCategoryId: Long,
- overlayFocusRequester: FocusRequester = remember { FocusRequester() },
- onSelectCategory: (com.streamvault.domain.model.Category) -> Unit,
- onDismiss: () -> Unit,
- onOverlayInteracted: () -> Unit = {}
-) {
- val listState = rememberLazyListState()
- val currentIndex = remember(categories, currentCategoryId) {
- categories.indexOfFirst { it.id == currentCategoryId }.coerceAtLeast(0)
- }
-
- LaunchedEffect(categories, currentIndex) {
- if (categories.isNotEmpty()) {
- listState.scrollToItem(currentIndex)
- }
- }
-
- BackHandler { onDismiss() }
-
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.18f))
- ) {
- BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
- val isTelevisionDevice = rememberIsTelevisionDevice()
- val panelModifier = if (maxWidth < 700.dp) {
- Modifier
- .fillMaxWidth(0.9f)
- .fillMaxHeight()
- .padding(20.dp)
- } else if (!isTelevisionDevice && maxWidth < 1280.dp) {
- Modifier
- .fillMaxWidth(0.5f)
- .fillMaxHeight()
- .padding(20.dp)
- } else {
- Modifier
- .width(500.dp)
- .fillMaxWidth()
- .fillMaxHeight()
- .padding(20.dp)
- }
-
- Box(modifier = panelModifier) {
- PlayerOverlayPanel(modifier = Modifier.fillMaxSize()) {
- androidx.compose.foundation.lazy.LazyColumn(
- state = listState,
- modifier = Modifier.fillMaxSize(),
- contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp),
- verticalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- item {
- Text(
- text = stringResource(R.string.label_categories),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(horizontal = 8.dp, vertical = 12.dp)
- )
- }
- items(categories.size) { index ->
- val category = categories[index]
- val isSelected = category.id == currentCategoryId
- var isFocused by remember { mutableStateOf(false) }
- val shouldRequestFocus = isSelected
- val bgColor = when {
- isFocused -> Primary
- isSelected -> Primary.copy(alpha = 0.20f)
- else -> AppColors.Surface.copy(alpha = 0.68f)
- }
-
- TvClickableSurface(
- onClick = {
- onSelectCategory(category)
- },
- modifier = Modifier
- .fillMaxWidth()
- .padding(vertical = 2.dp)
- .onFocusChanged { focusState ->
- isFocused = focusState.isFocused
- if (focusState.isFocused) onOverlayInteracted()
- }
- .then(
- if (shouldRequestFocus) Modifier.focusRequester(overlayFocusRequester)
- else Modifier
- ),
- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = bgColor,
- focusedContainerColor = bgColor
- )
- ) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 14.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.SpaceBetween
- ) {
- Text(
- text = category.name,
- style = MaterialTheme.typography.bodyLarge,
- color = Color.White,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f)
- )
- if (isSelected) {
- Text(
- text = "●",
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.8f),
- modifier = Modifier.padding(start = 8.dp)
- )
- } else if (category.count > 0) {
- Text(
- text = category.count.toString(),
- style = MaterialTheme.typography.labelSmall,
- color = Color.White.copy(alpha = 0.45f),
- modifier = Modifier.padding(start = 8.dp)
- )
- }
- }
- }
- }
- }
- }
- }
- }
- }
-}
diff --git a/docs/settings-refactor-review-checklist.md b/docs/settings-refactor-review-checklist.md
deleted file mode 100644
index c608de7f..00000000
--- a/docs/settings-refactor-review-checklist.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Settings Refactor Review Checklist
-
-Generated from the current working tree against `master` on 2026-04-29.
-
-Use this file in phases:
-
-1. Compare each extracted file against the original logic on `master` and tick `Drift` when behavior still matches.
-2. Check the current branch entrypoints and call sites, then tick `Wiring` when the new file is connected in the right place.
-3. Tick `Done` only after both checks are complete for that row.
-
-## Phase 1: Orchestration And State Wiring
-
-Reviewed on 2026-04-29. No drift or wiring findings recorded in this phase.
-
-| Done | Drift | Wiring | Status | File | Focus |
-| --- | --- | --- | --- | --- | --- |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt | top-level settings screen composition |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt | category-to-section content routing |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt | dialog wiring hub |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenOverlays.kt | overlay and browser dialog wiring |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogState.kt | remembered dialog and screen state |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenState.kt | derived labels and screen helpers |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsNavigationRail.kt | navigation rail extraction |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt | main `SettingsUiState` home |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt | registration entrypoints and main coordinator |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt | preference snapshot observation surface |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsObserverRegistrations.kt | observer registration splits |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDerivedStateObservers.kt | provider diagnostics and category derived flows |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsGuideDefaultCategoryBindings.kt | guide category options flow |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt | snapshot-to-ui-state mapping |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt | preference snapshot and sync enums |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsOperationalModels.kt | diagnostics and maintenance models |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateModels.kt | app update model split |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateFormatting.kt | app update label formatting |
-
-## Phase 2: Shared UI And Dialog Infrastructure
-
-Reviewed on 2026-04-29. No drift or wiring findings recorded in this phase.
-
-| Done | Drift | Wiring | Status | File | Focus |
-| --- | --- | --- | --- | --- | --- |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRowComponents.kt | reusable settings rows and quick-filter dialog |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSelectionDialogComponents.kt | selection dialog shell and level options |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSelectionDialogs.kt | quality and sort selection dialogs |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSharedUiComponents.kt | shared chips, overview cards, text field |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt | shared formatting helpers |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsTimeoutValueDialog.kt | timeout editing dialog |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsValueDialogs.kt | timer, offset, and text value dialogs |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsModeDialogs.kt | mode picker dialogs |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlayerPreferenceDialogs.kt | player preference dialog bundle |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceDialogs.kt | preference dialog aggregation |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProtectionDialogs.kt | parental PIN and level dialogs |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsLiveTvComponents.kt | live TV and parental card components |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt | backup and about sections |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt | backup import preview dialog |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncOverlay.kt | sync blocking overlay |
-
-## Phase 3: Browsing, Provider, And EPG Slices
-
-Reviewed on 2026-04-29. No drift or wiring findings recorded in this phase.
-
-| Done | Drift | Wiring | Status | File | Focus |
-| --- | --- | --- | --- | --- | --- |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBrowsingSection.kt | browsing section extraction |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPlaybackSection.kt | playback section extraction |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPrivacySection.kt | privacy section extraction |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt | provider section orchestration |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt | provider component call sites |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt | provider tabs, badges, compact stats |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderCardSections.kt | provider actions and warning panels |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt | provider diagnostics rendering |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderManagementDialogs.kt | provider management dialog wiring |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSyncDialogs.kt | provider sync dialog flows |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsCombinedM3uComponents.kt | combined M3U widgets and dialogs |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt | EPG section orchestration |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgAssignmentComponents.kt | provider assignment UI |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSourceComponents.kt | EPG source cards and add flow |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsInternetSpeedTestCard.kt | speed test card extraction |
-
-## Phase 4: Recording Slice
-
-Reviewed on 2026-04-29. Clean after restoring dialog ownership to the top-level settings dialog hub.
-
-| Done | Drift | Wiring | Status | File | Focus |
-| --- | --- | --- | --- | --- | --- |
-| [x] | [x] | [x] | modified | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt | legacy recording component call sites |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingSection.kt | recording section and browser entrypoint |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingDialogs.kt | recording-related dialogs |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingDashboardCards.kt | dashboard cards |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingItemComponents.kt | recording item cards and actions |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingBrowserDialog.kt | recording browser shell |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingBrowserDisplay.kt | browser display helpers |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingBrowserSidebarControls.kt | browser filters and search |
-| [x] | [x] | [x] | new | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingBrowserDetailSections.kt | browser detail metrics and actions |
-
-Phase 4 note: `SettingsRecordingDialogs.kt` now owns only recording-specific dialogs. `BackupImportPreviewDialog` and the clear-history confirmation were returned to `SettingsScreenDialogs.kt`, matching the top-level ownership shape used in `master` without changing visible behavior.
-
-## Removed Source Files To Map During Review
-
-These are not review targets on their own, but they are the original surfaces to compare against when checking extraction drift.
-
-| Done | Drift | Wiring | Status | File | Focus |
-| --- | --- | --- | --- | --- | --- |
-| [x] | [x] | - | deleted | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt | compare old dialog logic against extracted dialog files |
-| [x] | [x] | - | deleted | app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt | compare old models and helpers against extracted model files |
-
-## Notes
-
-- `Drift` means the extracted file still matches the behavior that lived in `master`.
-- `Wiring` means the current branch still calls, observes, or renders that behavior from the correct owner.
-- If a row fails review, leave `Done` unchecked and add a short note in the `Focus` column or below the table before moving on.
\ No newline at end of file