Skip to content

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

Polish player, guide, VOD, and dashboard flows

David Nashash1f780edab309
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index d348456f..b29bac9b 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -44,6 +44,21 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:mimeType="audio/x-mpegurl" />
+ <data android:mimeType="audio/mpegurl" />
+ <data android:mimeType="application/x-mpegurl" />
+ <data android:mimeType="application/vnd.apple.mpegurl" />
+ <data android:mimeType="application/mpegurl" />
+ <data android:scheme="content" android:pathPattern=".*\\.m3u" />
+ <data android:scheme="content" android:pathPattern=".*\\.m3u8" />
+ <data android:scheme="file" android:pathPattern=".*\\.m3u" />
+ <data android:scheme="file" android:pathPattern=".*\\.m3u8" />
+ </intent-filter>
+
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.kt
index c56b8d74..80db4919 100644
--- a/app/src/main/java/com/streamvault/app/MainActivity.kt
+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt
@@ -37,6 +37,7 @@ import android.view.View
import java.util.Locale
import android.content.Context
import android.content.ContextWrapper
+import android.net.Uri
import android.content.res.AssetManager
import android.content.res.Resources
import android.speech.RecognizerIntent
@@ -245,6 +246,7 @@ class MainActivity : ComponentActivity() {
private fun Intent.toExternalNavigationRequest(): ExternalNavigationRequest? {
readPlayerRequestExtra()?.let { return ExternalNavigationRequest.Player(it) }
getStringExtra(EXTRA_EXTERNAL_ROUTE)?.let { return ExternalNavigationRequest.Route(it) }
+ readImportedPlaylistUri()?.let { return ExternalNavigationRequest.ImportM3u(it) }
val query = when (action) {
Intent.ACTION_SEARCH,
@@ -260,6 +262,26 @@ class MainActivity : ComponentActivity() {
return query.takeIf { it.isNotBlank() }?.let(ExternalNavigationRequest::Search)
}
+ private fun Intent.readImportedPlaylistUri(): String? {
+ if (action != Intent.ACTION_VIEW) return null
+ val targetUri = data ?: return null
+ val normalizedPath = targetUri.toString().substringBefore('?').lowercase(Locale.ROOT)
+ val mimeType = type?.lowercase(Locale.ROOT).orEmpty()
+ val isPlaylistMime = mimeType in setOf(
+ "audio/x-mpegurl",
+ "audio/mpegurl",
+ "application/x-mpegurl",
+ "application/vnd.apple.mpegurl",
+ "application/mpegurl"
+ )
+ val isPlaylistPath = normalizedPath.endsWith(".m3u") || normalizedPath.endsWith(".m3u8")
+ if (!isPlaylistMime && !isPlaylistPath) return null
+ return when (targetUri.scheme?.lowercase(Locale.ROOT)) {
+ "content", "file" -> targetUri.toString()
+ else -> null
+ }
+ }
+
@Suppress("DEPRECATION")
private fun Intent.readPlayerRequestExtra(): PlayerNavigationRequest? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index 6632648a..270bf225 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -99,5 +99,8 @@ object NetworkModule {
fun provideAuxiliaryPlayerEngine(
@ApplicationContext context: Context,
okHttpClient: OkHttpClient
- ): PlayerEngine = Media3PlayerEngine(context, okHttpClient)
+ ): PlayerEngine = Media3PlayerEngine(context, okHttpClient).apply {
+ enableMediaSession = false
+ bypassAudioFocus = true
+ }
}
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
index 17f43d47..0854c3a4 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -51,7 +51,7 @@ data class PlayerNavigationRequest(
) : Serializable
object Routes {
- const val PROVIDER_SETUP = "provider_setup?providerId={providerId}"
+ const val PROVIDER_SETUP = "provider_setup?providerId={providerId}&importUri={importUri}"
const val HOME = "home"
const val LIVE_TV = "live_tv"
const val LIVE_TV_DESTINATION = "live_tv?categoryId={categoryId}"
@@ -71,7 +71,10 @@ object Routes {
const val MULTI_VIEW = "multi_view"
- fun providerSetup(providerId: Long? = null) = "provider_setup?providerId=${providerId ?: -1L}"
+ fun providerSetup(providerId: Long? = null, importUri: String? = null): String {
+ val encodedImportUri = Uri.encode(importUri ?: "")
+ return "provider_setup?providerId=${providerId ?: -1L}&importUri=$encodedImportUri"
+ }
fun liveTv(categoryId: Long? = null) = if (categoryId == null) LIVE_TV else "$LIVE_TV?categoryId=$categoryId"
fun epg(categoryId: Long? = null, anchorTime: Long? = null, favoritesOnly: Boolean? = null): String {
val resolvedCategoryId = categoryId ?: -1L
@@ -200,6 +203,11 @@ fun AppNavigation(mainActivity: MainActivity) {
mainActivity.clearExternalNavigationRequest()
}
+ is ExternalNavigationRequest.ImportM3u -> {
+ navController.navigate(Routes.providerSetup(importUri = request.uri)) { launchSingleTop = true }
+ mainActivity.clearExternalNavigationRequest()
+ }
+
is ExternalNavigationRequest.Search -> {
navController.navigate(Routes.search(request.query)) { launchSingleTop = true }
mainActivity.clearExternalNavigationRequest()
@@ -245,13 +253,16 @@ fun AppNavigation(mainActivity: MainActivity) {
composable(
route = Routes.PROVIDER_SETUP,
arguments = listOf(
- navArgument("providerId") { type = NavType.LongType; defaultValue = -1L }
+ navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },
+ navArgument("importUri") { type = NavType.StringType; defaultValue = "" }
)
) { backStackEntry ->
val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }
+ val importUri = backStackEntry.arguments?.getString("importUri")?.takeIf { it.isNotBlank() }
ProviderSetupScreen(
editProviderId = providerId,
+ initialImportUri = importUri,
onProviderAdded = dropUnlessResumed {
navController.navigate(Routes.HOME) {
popUpTo(Routes.PROVIDER_SETUP) { inclusive = true }
diff --git a/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt b/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt
index 6a3ee579..cdb0ee67 100644
--- a/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/ExternalNavigationRequest.kt
@@ -4,4 +4,5 @@ sealed interface ExternalNavigationRequest {
data class Search(val query: String) : ExternalNavigationRequest
data class Player(val request: PlayerNavigationRequest) : ExternalNavigationRequest
data class Route(val route: String) : ExternalNavigationRequest
-}
\ No newline at end of file
+ data class ImportM3u(val uri: String) : ExternalNavigationRequest
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
index b2001abc..67e06d4c 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
@@ -1,6 +1,8 @@
package com.streamvault.app.ui.components
import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
@@ -8,10 +10,19 @@ import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.unit.dp
-import com.streamvault.app.ui.theme.LocalSpacing
import androidx.compose.ui.res.stringResource
+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.components.shell.AppSectionHeader
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
// ── Netflix-style horizontal category row ─────────────────────────
@@ -29,14 +40,45 @@ fun <T : Any> CategoryRow(
val resolvedContentTypeSelector: (T) -> Any? = contentTypeSelector ?: { null }
Column(modifier = modifier.fillMaxWidth()) {
- AppSectionHeader(
- title = title,
- modifier = Modifier
- .fillMaxWidth()
- .padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 6.dp),
- actionLabel = onSeeAll?.let { stringResource(R.string.category_see_all) },
- onActionClick = onSeeAll
- )
+ if (onSeeAll != null) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 6.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ AppSectionHeader(title = title)
+ Surface(
+ onClick = onSeeAll,
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = Primary,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.category_see_all),
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp),
+ style = MaterialTheme.typography.labelMedium
+ )
+ }
+ }
+ } else {
+ AppSectionHeader(
+ title = title,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 6.dp)
+ )
+ }
LazyRow(
modifier = Modifier.focusRestorer(),
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
index 62b5d3ba..ccb75beb 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
@@ -39,6 +39,7 @@ fun CategoryOptionsDialog(
onDismissRequest: () -> Unit,
onSetAsDefault: (() -> Unit)? = null,
onRename: (() -> Unit)? = null,
+ onHide: (() -> Unit)? = null,
onToggleLock: (() -> Unit)? = null,
onDelete: (() -> Unit)? = null,
onReorderChannels: (() -> Unit)? = null
@@ -98,6 +99,18 @@ fun CategoryOptionsDialog(
)
}
+ if (onHide != null) {
+ PremiumDialogAction(
+ label = stringResource(R.string.category_options_hide),
+ onClick = {
+ if (canInteract) {
+ onHide()
+ onDismissRequest()
+ }
+ }
+ )
+ }
+
if (onReorderChannels != null) {
PremiumDialogAction(
label = stringResource(R.string.category_options_reorder),
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
index aa441c36..56bb1305 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
@@ -88,6 +88,7 @@ fun AppScreenScaffold(
subtitle: String? = null,
modifier: Modifier = Modifier,
navigationChrome: AppNavigationChrome = AppNavigationChrome.Rail,
+ topBarVisible: Boolean = true,
compactHeader: Boolean = false,
showScreenHeader: Boolean = true,
header: (@Composable ColumnScope.() -> Unit)? = null,
@@ -162,12 +163,14 @@ fun AppScreenScaffold(
vertical = 10.dp
)
) {
- TopNavigationBar(
- currentRoute = currentRoute,
- onNavigate = onNavigate,
- modifier = Modifier.fillMaxWidth()
- )
- Spacer(modifier = Modifier.height(10.dp))
+ if (topBarVisible) {
+ TopNavigationBar(
+ currentRoute = currentRoute,
+ onNavigate = onNavigate,
+ modifier = Modifier.fillMaxWidth()
+ )
+ Spacer(modifier = Modifier.height(10.dp))
+ }
if (showScreenHeader) {
AppScreenHeader(
title = title,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
index 737b4967..47e0344b 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt
@@ -47,6 +47,8 @@ import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDim
import androidx.compose.foundation.BorderStroke
import com.streamvault.app.R
import com.streamvault.app.ui.components.SearchInput
+import com.streamvault.app.ui.components.SelectionChip
+import com.streamvault.app.ui.components.SelectionChipRow
import com.streamvault.app.ui.components.dialogs.PremiumDialog
import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton
@@ -171,7 +173,8 @@ data class VodActionChip(
data class VodCategoryOption(
val name: String,
val count: Int,
- val onClick: () -> Unit
+ val onClick: () -> Unit,
+ val onLongClick: (() -> Unit)? = null
)
@Composable
@@ -235,6 +238,12 @@ fun VodCategoryPickerDialog(
category.onClick()
onDismiss()
},
+ onLongClick = category.onLongClick?.let { action ->
+ {
+ action()
+ onDismiss()
+ }
+ },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = SurfaceElevated,
@@ -283,3 +292,45 @@ fun VodCategoryPickerDialog(
}
)
}
+
+@Composable
+fun VodBrowseOptionsDialog(
+ title: String,
+ filterTitle: String,
+ filterChips: List<SelectionChip>,
+ selectedFilterKey: String,
+ onFilterSelected: (String) -> Unit,
+ sortTitle: String,
+ sortChips: List<SelectionChip>,
+ selectedSortKey: String,
+ onSortSelected: (String) -> Unit,
+ onDismiss: () -> Unit
+) {
+ PremiumDialog(
+ title = title,
+ onDismissRequest = onDismiss,
+ widthFraction = 0.56f,
+ content = {
+ SelectionChipRow(
+ title = filterTitle,
+ chips = filterChips,
+ selectedKey = selectedFilterKey,
+ onChipSelected = onFilterSelected,
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ SelectionChipRow(
+ title = sortTitle,
+ chips = sortChips,
+ selectedKey = selectedSortKey,
+ onChipSelected = onSortSelected,
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ },
+ footer = {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.category_options_cancel),
+ onClick = onDismiss
+ )
+ }
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/model/CategoryDisplayPreferences.kt b/app/src/main/java/com/streamvault/app/ui/model/CategoryDisplayPreferences.kt
new file mode 100644
index 00000000..33984832
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/model/CategoryDisplayPreferences.kt
@@ -0,0 +1,23 @@
+package com.streamvault.app.ui.model
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
+
+fun applyProviderCategoryDisplayPreferences(
+ categories: List<Category>,
+ hiddenCategoryIds: Set<Long>,
+ sortMode: CategorySortMode
+): List<Category> {
+ val visible = categories.filterNot { it.id in hiddenCategoryIds }
+ return when (sortMode) {
+ CategorySortMode.DEFAULT -> visible
+ CategorySortMode.TITLE_ASC -> visible.sortedBy { it.name.lowercase() }
+ CategorySortMode.TITLE_DESC -> visible.sortedByDescending { it.name.lowercase() }
+ CategorySortMode.COUNT_DESC -> visible.sortedWith(
+ compareByDescending<Category> { it.count }.thenBy { it.name.lowercase() }
+ )
+ CategorySortMode.COUNT_ASC -> visible.sortedWith(
+ compareBy<Category> { it.count }.thenBy { it.name.lowercase() }
+ )
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/model/GuideLookupKey.kt b/app/src/main/java/com/streamvault/app/ui/model/GuideLookupKey.kt
new file mode 100644
index 00000000..5ac54a45
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/model/GuideLookupKey.kt
@@ -0,0 +1,8 @@
+package com.streamvault.app.ui.model
+
+import com.streamvault.domain.model.Channel
+
+fun Channel.guideLookupKey(): String? {
+ return epgChannelId?.trim()?.takeIf { it.isNotEmpty() }
+ ?: streamId.takeIf { it > 0L }?.toString()
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
index c7e6e610..58f079a7 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
@@ -693,11 +693,11 @@ private fun rememberDashboardSections(
) {
val preferred = listOf(
DashboardHomeSection.FAVORITE_CHANNELS,
+ DashboardHomeSection.RECENT_CHANNELS,
+ DashboardHomeSection.LIVE_SHORTCUTS,
DashboardHomeSection.CONTINUE_WATCHING,
DashboardHomeSection.RECENT_MOVIES,
- DashboardHomeSection.RECENT_SERIES,
- DashboardHomeSection.LIVE_SHORTCUTS,
- DashboardHomeSection.RECENT_CHANNELS
+ DashboardHomeSection.RECENT_SERIES
)
preferred.filter { section ->
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt
index 503a5656..f457e7b1 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt
@@ -84,11 +84,13 @@ class DashboardViewModel @Inject constructor(
observeContinueWatching(provider.id).onStart { emit(emptyList()) },
movieRepository.getMovies(provider.id).map { movies ->
movies
+ .filterNot(::shouldHideVodFromHome)
.sortedByDescending(::movieFreshnessScore)
.take(MOVIE_SHELF_LIMIT)
}.onStart { emit(emptyList()) },
seriesRepository.getSeries(provider.id).map { series ->
series
+ .filterNot(::shouldHideVodFromHome)
.sortedByDescending(::seriesFreshnessScore)
.take(SERIES_SHELF_LIMIT)
}.onStart { emit(emptyList()) }
@@ -199,42 +201,11 @@ class DashboardViewModel @Inject constructor(
private fun buildLiveContext(providerId: Long): Flow<DashboardLiveContext> =
combine(
getCustomCategories(ContentType.LIVE),
- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, RECENT_CHANNEL_LIMIT)
- .map { history ->
- history
- .filter { it.contentType == ContentType.LIVE }
- .distinctBy { it.contentId }
- .count()
- },
preferencesRepository.getLastLiveCategoryId(providerId),
preferencesRepository.promotedLiveGroupIds
- ) { customCategories, recentCount, lastVisitedCategoryId, promotedGroupIds ->
+ ) { customCategories, lastVisitedCategoryId, promotedGroupIds ->
val lastVisitedCategory = customCategories.firstOrNull { it.id == lastVisitedCategoryId }
val shortcuts = buildList {
- customCategories
- .firstOrNull { it.id == VirtualCategoryIds.FAVORITES && it.count > 0 }
- ?.let {
- add(
- DashboardLiveShortcut(
- label = it.name,
- detail = "${it.count} saved",
- categoryId = it.id,
- type = DashboardShortcutType.FAVORITES
- )
- )
- }
-
- if (recentCount > 0) {
- add(
- DashboardLiveShortcut(
- label = "Recent",
- detail = "$recentCount channels",
- categoryId = VirtualCategoryIds.RECENT,
- type = DashboardShortcutType.RECENT
- )
- )
- }
-
lastVisitedCategory?.let {
add(
DashboardLiveShortcut(
@@ -375,6 +346,22 @@ class DashboardViewModel @Inject constructor(
?: series.id
}
+ private fun shouldHideVodFromHome(movie: Movie): Boolean {
+ if (movie.isAdult || movie.isUserProtected) return true
+ return titleLooksExplicit(movie.name)
+ }
+
+ private fun shouldHideVodFromHome(series: Series): Boolean {
+ if (series.isAdult || series.isUserProtected) return true
+ return titleLooksExplicit(series.name)
+ }
+
+ private fun titleLooksExplicit(title: String): Boolean {
+ val normalized = title.lowercase()
+ val explicitTerms = listOf("porn", "porno", "xxx", "adult", "18+", "sex", "erotic", "hentai")
+ return explicitTerms.any { term -> normalized.contains(term) }
+ }
+
private fun parseDateScore(raw: String?): Long? {
if (raw.isNullOrBlank()) return null
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
index b99aca42..c6698c9c 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
@@ -1,11 +1,13 @@
package com.streamvault.app.ui.screens.epg
+import com.streamvault.app.ui.model.guideLookupKey
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -18,10 +20,12 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -37,12 +41,16 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.tv.material3.Border
@@ -54,7 +62,7 @@ import androidx.tv.material3.Surface
import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
-import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.components.ChannelLogoBadge
import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.components.SearchInput
import com.streamvault.app.ui.components.SelectionChip
@@ -80,7 +88,6 @@ import java.util.Date
import java.util.Locale
import kotlinx.coroutines.delay
import kotlin.math.max
-import kotlin.math.roundToInt
@Composable
fun FullEpgScreen(
@@ -95,9 +102,12 @@ fun FullEpgScreen(
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
var selectedProgram by remember { mutableStateOf<Pair<Channel, Program>?>(null) }
- var showAdvancedOptions by rememberSaveable { mutableStateOf(false) }
- var showSearchBar by rememberSaveable { mutableStateOf(false) }
+ var focusedChannel by remember { mutableStateOf<Channel?>(null) }
+ var focusedProgram by remember { mutableStateOf<Program?>(null) }
+ var topNavVisible by rememberSaveable { mutableStateOf(true) }
var showCategoryPicker by rememberSaveable { mutableStateOf(false) }
+ var showGuideOptions by rememberSaveable { mutableStateOf(false) }
+ var showSearchOverlay by rememberSaveable { mutableStateOf(false) }
val now = rememberGuideNow()
val returnRoute = remember(uiState.selectedCategoryId, uiState.guideAnchorTime, uiState.showFavoritesOnly) {
Routes.epg(
@@ -115,12 +125,46 @@ fun FullEpgScreen(
)
}
+ LaunchedEffect(uiState.channels, uiState.programsByChannel, now) {
+ if (uiState.channels.isEmpty()) {
+ focusedChannel = null
+ focusedProgram = null
+ return@LaunchedEffect
+ }
+ val resolvedChannel = focusedChannel?.let { current ->
+ uiState.channels.firstOrNull { it.id == current.id }
+ } ?: uiState.channels.firstOrNull()
+ focusedChannel = resolvedChannel
+ val resolvedPrograms = resolvedChannel?.let { channel ->
+ channel.guideLookupKey()?.let { lookupKey ->
+ uiState.programsByChannel[lookupKey].orEmpty()
+ }.orEmpty()
+ }.orEmpty()
+ focusedProgram = focusedProgram?.let { focused ->
+ resolvedPrograms.firstOrNull {
+ it.startTime == focused.startTime &&
+ it.endTime == focused.endTime &&
+ it.title == focused.title
+ }
+ } ?: resolvedPrograms.firstOrNull { now in it.startTime until it.endTime }
+ }
+
+ val heroSelection = remember(uiState, focusedChannel, focusedProgram, now) {
+ resolveGuideHeroSelection(
+ uiState = uiState,
+ focusedChannel = focusedChannel,
+ focusedProgram = focusedProgram,
+ now = now
+ )
+ }
+
AppScreenScaffold(
currentRoute = currentRoute,
onNavigate = onNavigate,
title = stringResource(R.string.nav_epg),
subtitle = stringResource(R.string.guide_shell_subtitle),
navigationChrome = AppNavigationChrome.TopBar,
+ topBarVisible = topNavVisible,
compactHeader = true,
showScreenHeader = false
) {
@@ -129,37 +173,8 @@ fun FullEpgScreen(
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
) {
- if (uiState.error == null) {
- GuideHeaderDeck(
- uiState = uiState,
- showSearchBar = showSearchBar || uiState.programSearchQuery.isNotBlank(),
- showAdvancedOptions = showAdvancedOptions,
- onToggleSearch = { showSearchBar = !showSearchBar },
- onOpenCategoryPicker = { showCategoryPicker = true },
- onToggleAdvancedOptions = { showAdvancedOptions = !showAdvancedOptions },
- onProgramSearchQueryChange = viewModel::updateProgramSearchQuery,
- onClearProgramSearch = viewModel::clearProgramSearch,
- onJumpToPreviousDay = viewModel::jumpToPreviousDay,
- onJumpBackward = viewModel::jumpBackward,
- onJumpToNow = viewModel::jumpToNow,
- onJumpForward = viewModel::jumpForward,
- onJumpToPrimeTime = viewModel::jumpToPrimeTime,
- onJumpToNextDay = viewModel::jumpToNextDay,
- onPageBackward = viewModel::pageBackward,
- onJumpBackwardHalfHour = viewModel::jumpBackwardHalfHour,
- onJumpForwardHalfHour = viewModel::jumpForwardHalfHour,
- onPageForward = viewModel::pageForward,
- onJumpToTomorrow = viewModel::jumpToTomorrow,
- onDaySelected = viewModel::jumpToDay,
- onModeSelected = viewModel::selectChannelMode,
- onDensitySelected = viewModel::selectDensity,
- onToggleScheduledOnly = viewModel::toggleScheduledOnly,
- onToggleFavoritesOnly = viewModel::toggleFavoritesOnly
- )
- }
-
when {
- uiState.isLoading -> {
+ uiState.isInitialLoading && uiState.channels.isEmpty() -> {
Box(
modifier = Modifier
.fillMaxWidth()
@@ -223,8 +238,62 @@ fun FullEpgScreen(
}
else -> {
+ ImmersiveGuideHero(
+ selection = heroSelection,
+ providerLabel = uiState.providerSourceLabel,
+ selectedCategoryName = uiState.categories
+ .firstOrNull { it.id == uiState.selectedCategoryId }
+ ?.name
+ .orEmpty(),
+ isGuideStale = uiState.isGuideStale,
+ channelCount = uiState.totalChannelCount,
+ channelsWithSchedule = uiState.channelsWithSchedule,
+ lastUpdatedAt = uiState.lastUpdatedAt,
+ isRefreshing = uiState.isRefreshing,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 14.dp, vertical = 4.dp)
+ )
+ GuideToolbarRow(
+ selectedCategoryName = uiState.categories
+ .firstOrNull { it.id == uiState.selectedCategoryId }
+ ?.name
+ ?: stringResource(R.string.epg_filter_short),
+ onOpenCategoryPicker = {
+ topNavVisible = false
+ showCategoryPicker = true
+ },
+ onJumpToNow = {
+ topNavVisible = false
+ viewModel.jumpToNow()
+ },
+ onOpenSearch = {
+ topNavVisible = false
+ showSearchOverlay = true
+ },
+ onOpenOptions = {
+ topNavVisible = false
+ showGuideOptions = true
+ },
+ onGuideInteract = { topNavVisible = false },
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 14.dp)
+ )
+ if (uiState.isRefreshing) {
+ LinearProgressIndicator(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 14.dp, vertical = 4.dp)
+ .height(3.dp),
+ color = Primary,
+ trackColor = SurfaceHighlight
+ )
+ }
EpgGrid(
- modifier = Modifier.weight(1f),
+ modifier = Modifier
+ .fillMaxWidth()
+ .weight(1f),
channels = uiState.channels,
favoriteChannelIds = uiState.favoriteChannelIds,
programsByChannel = uiState.programsByChannel,
@@ -233,7 +302,20 @@ fun FullEpgScreen(
density = uiState.selectedDensity,
now = now,
onChannelClick = { channel -> onPlayChannel(channel, returnRoute) },
- onProgramClick = { channel, program -> selectedProgram = channel to program }
+ onProgramClick = { channel, program ->
+ topNavVisible = false
+ selectedProgram = channel to program
+ },
+ onChannelFocused = { channel, currentProgram ->
+ topNavVisible = false
+ focusedChannel = channel
+ focusedProgram = currentProgram
+ },
+ onProgramFocused = { channel, program ->
+ topNavVisible = false
+ focusedChannel = channel
+ focusedProgram = program
+ }
)
}
}
@@ -252,226 +334,65 @@ fun FullEpgScreen(
)
}
+ if (showSearchOverlay) {
+ GuideSearchOverlay(
+ query = uiState.programSearchQuery,
+ onQueryChange = viewModel::updateProgramSearchQuery,
+ onClear = viewModel::clearProgramSearch,
+ onDismiss = { showSearchOverlay = false }
+ )
+ }
+
+ if (showGuideOptions) {
+ GuideOptionsOverlay(
+ uiState = uiState,
+ onDismiss = { showGuideOptions = false },
+ onShowAppNavigation = {
+ topNavVisible = true
+ showGuideOptions = false
+ },
+ onJumpToPreviousDay = viewModel::jumpToPreviousDay,
+ onPageBackward = viewModel::pageBackward,
+ onJumpBackwardHalfHour = viewModel::jumpBackwardHalfHour,
+ onJumpBackward = viewModel::jumpBackward,
+ onJumpToNow = viewModel::jumpToNow,
+ onJumpForwardHalfHour = viewModel::jumpForwardHalfHour,
+ onJumpForward = viewModel::jumpForward,
+ onPageForward = viewModel::pageForward,
+ onJumpToPrimeTime = viewModel::jumpToPrimeTime,
+ onJumpToTomorrow = viewModel::jumpToTomorrow,
+ onJumpToNextDay = viewModel::jumpToNextDay,
+ onDaySelected = viewModel::jumpToDay,
+ onModeSelected = viewModel::selectChannelMode,
+ onDensitySelected = viewModel::selectDensity,
+ onToggleScheduledOnly = viewModel::toggleScheduledOnly,
+ onToggleFavoritesOnly = viewModel::toggleFavoritesOnly,
+ onRefresh = viewModel::refresh
+ )
+ }
+
val dialogState = selectedProgram
if (dialogState != null) {
val (channel, program) = dialogState
- val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
- val channelPrograms = channel.epgChannelId?.let { uiState.programsByChannel[it].orEmpty() }.orEmpty()
- val surroundingPrograms = remember(channelPrograms, program) {
- val index = channelPrograms.indexOfFirst { it.startTime == program.startTime && it.endTime == program.endTime && it.title == program.title }
- if (index == -1) {
- channelPrograms.take(4)
- } else {
- channelPrograms.subList(max(0, index - 1), minOf(channelPrograms.size, index + 3))
- }
- }
-
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.55f))
- .clickable(onClick = { selectedProgram = null }, indication = null, interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }),
- contentAlignment = Alignment.CenterEnd
- ) {
- BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
- val isTelevisionDevice = rememberIsTelevisionDevice()
- val panelModifier = when {
- maxWidth < 700.dp -> Modifier
- .fillMaxWidth(0.9f)
- .fillMaxHeight()
- .padding(vertical = 24.dp, horizontal = 24.dp)
- !isTelevisionDevice && maxWidth < 1280.dp -> Modifier
- .fillMaxWidth(0.54f)
- .fillMaxHeight()
- .padding(vertical = 24.dp, horizontal = 24.dp)
- else -> Modifier
- .width(520.dp)
- .fillMaxHeight()
- .padding(vertical = 24.dp, horizontal = 24.dp)
- }
-
- Surface(
- modifier = panelModifier,
- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
- shape = RoundedCornerShape(20.dp)
- ) {
- Column(
- modifier = Modifier
- .fillMaxSize()
- .verticalScroll(rememberScrollState())
- .padding(24.dp),
- verticalArrangement = Arrangement.spacedBy(18.dp)
- ) {
- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
- Text(
- text = program.title,
- style = MaterialTheme.typography.headlineSmall,
- color = OnSurface
- )
- Text(
- text = stringResource(
- R.string.player_time_range_minutes,
- format.format(Date(program.startTime)),
- format.format(Date(program.endTime)),
- program.durationMinutes
- ),
- style = MaterialTheme.typography.bodyMedium,
- color = OnSurfaceDim
- )
- if (program.description.isNotBlank()) {
- Text(
- text = program.description,
- style = MaterialTheme.typography.bodyMedium,
- color = OnSurface
- )
- }
- }
-
- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_channel_label),
- value = channel.name
- )
- uiState.currentProviderName?.let { providerName ->
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_provider_label),
- value = providerName
- )
- }
- if (uiState.providerSourceLabel.isNotBlank()) {
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_provider_type_label),
- value = uiState.providerSourceLabel
- )
- }
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_language_label),
- value = program.lang.ifBlank { stringResource(R.string.epg_program_unknown_value) }
- )
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_replay_label),
- value = when {
- program.hasArchive -> stringResource(R.string.epg_program_replay_ready)
- channel.catchUpSupported -> stringResource(R.string.epg_program_replay_partial)
- else -> stringResource(R.string.epg_program_replay_unavailable)
- }
- )
- if (program.isNowPlaying) {
- GuideProgramMetadataRow(
- label = stringResource(R.string.epg_program_progress_label),
- value = stringResource(
- R.string.epg_program_progress_value,
- (program.progressPercent() * 100f).roundToInt(),
- stringResource(R.string.epg_minutes_remaining, ((program.endTime - now) / 60_000L).coerceAtLeast(0L))
- )
- )
- }
- }
-
- GuideStatusCard(
- isArchiveReady = program.hasArchive,
- providerCatchUpSupported = channel.catchUpSupported,
- isGuideStale = uiState.isGuideStale
- )
-
- if (uiState.providerArchiveSummary.isNotBlank()) {
- GuideProviderTroubleshootingCard(
- summary = uiState.providerArchiveSummary,
- channel = channel,
- program = program,
- isGuideStale = uiState.isGuideStale
- )
- }
-
- if (surroundingPrograms.isNotEmpty()) {
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- Text(
- text = stringResource(R.string.epg_upcoming_schedule),
- style = MaterialTheme.typography.titleMedium,
- color = OnSurface
- )
- surroundingPrograms.forEach { scheduleProgram ->
- val isSelectedProgram = scheduleProgram === program ||
- (scheduleProgram.startTime == program.startTime &&
- scheduleProgram.endTime == program.endTime &&
- scheduleProgram.title == program.title)
- Surface(
- onClick = { selectedProgram = channel to scheduleProgram },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (isSelectedProgram) Primary.copy(alpha = 0.18f) else SurfaceHighlight,
- focusedContainerColor = SurfaceHighlight
- )
- ) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 14.dp, vertical = 12.dp),
- verticalArrangement = Arrangement.spacedBy(4.dp)
- ) {
- Text(
- text = scheduleProgram.title,
- style = MaterialTheme.typography.titleSmall,
- color = if (isSelectedProgram) Primary else OnSurface,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
- Text(
- text = stringResource(R.string.time_range_format, format.format(Date(scheduleProgram.startTime)), format.format(Date(scheduleProgram.endTime))),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
- }
- }
- }
- }
-
- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
- if (program.hasArchive || channel.catchUpSupported) {
- Button(
- onClick = {
- selectedProgram = null
- onPlayArchive(channel, program, returnRoute)
- },
- colors = ButtonDefaults.colors(
- containerColor = Primary,
- contentColor = Color.White
- ),
- modifier = Modifier.fillMaxWidth()
- ) {
- Text(stringResource(R.string.epg_watch_archive))
- }
- }
- Button(
- onClick = {
- selectedProgram = null
- onPlayChannel(channel, returnRoute)
- },
- modifier = Modifier.fillMaxWidth()
- ) {
- Text(stringResource(R.string.epg_watch_live))
- }
- if (uiState.isGuideStale) {
- Button(
- onClick = viewModel::refresh,
- modifier = Modifier.fillMaxWidth(),
- colors = ButtonDefaults.colors(
- containerColor = SurfaceHighlight,
- contentColor = OnSurface
- )
- ) {
- Text(stringResource(R.string.epg_refresh_guide))
- }
- }
- TextButton(onClick = { selectedProgram = null }) {
- Text(stringResource(R.string.settings_cancel))
- }
- }
- }
+ CompactGuideProgramDialog(
+ channel = channel,
+ program = program,
+ providerLabel = uiState.providerSourceLabel,
+ now = now,
+ onDismiss = { selectedProgram = null },
+ onWatchLive = {
+ selectedProgram = null
+ onPlayChannel(channel, returnRoute)
+ },
+ onWatchArchive = if (program.hasArchive || channel.catchUpSupported) {
+ {
+ selectedProgram = null
+ onPlayArchive(channel, program, returnRoute)
}
+ } else {
+ null
}
- }
+ )
}
}
@@ -642,6 +563,7 @@ private fun GuideProgramSearchRow(
query: String,
onQueryChange: (String) -> Unit,
onClear: () -> Unit,
+ focusRequester: FocusRequester? = null,
contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),
showLabel: Boolean = true
) {
@@ -667,7 +589,8 @@ private fun GuideProgramSearchRow(
value = query,
onValueChange = onQueryChange,
placeholder = stringResource(R.string.epg_search_placeholder),
- modifier = Modifier.weight(1f)
+ modifier = Modifier.weight(1f),
+ focusRequester = focusRequester ?: remember { FocusRequester() }
)
if (query.isNotBlank()) {
GuideShortcutChip(
@@ -782,6 +705,7 @@ private fun GuideTimeControlsRow(
onJumpToPrimeTime: () -> Unit,
onJumpToTomorrow: () -> Unit,
onJumpToNextDay: () -> Unit,
+ firstChipFocusRequester: FocusRequester? = null,
contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),
showLabel: Boolean = true
) {
@@ -801,6 +725,7 @@ private fun GuideTimeControlsRow(
LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
item {
GuideShortcutChip(
+ modifier = firstChipFocusRequester?.let { Modifier.focusRequester(it) } ?: Modifier,
label = stringResource(R.string.epg_previous_day),
onClick = onJumpToPreviousDay
)
@@ -1028,15 +953,18 @@ private fun GuideFavoritesRow(
@Composable
private fun GuideShortcutChip(
+ modifier: Modifier = Modifier,
label: String,
- onClick: () -> Unit
+ onClick: () -> Unit,
+ isSelected: Boolean = false
) {
Surface(
onClick = onClick,
+ modifier = modifier,
colors = ClickableSurfaceDefaults.colors(
- containerColor = SurfaceElevated,
+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
focusedContainerColor = SurfaceHighlight,
- contentColor = OnSurface,
+ contentColor = if (isSelected) Primary else OnSurface,
focusedContentColor = OnSurface
),
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
@@ -1049,8 +977,10 @@ private fun GuideShortcutChip(
) {
Text(
text = label,
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
- style = MaterialTheme.typography.labelLarge
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp),
+ style = MaterialTheme.typography.labelMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
}
}
@@ -1107,104 +1037,217 @@ private fun GuideSummaryCard(uiState: EpgUiState) {
windowFormat.format(Date(uiState.guideWindowEnd))
)
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- GuideSummaryPill(
- title = stringResource(
- R.string.epg_showing_channels,
- uiState.channels.size,
- uiState.totalChannelCount
- ),
- subtitle = stringResource(
- R.string.epg_schedule_summary,
- uiState.channelsWithSchedule,
- uiState.channels.size
- ),
- modifier = Modifier.weight(1f)
- )
- GuideSummaryPill(
- title = windowLabel,
- subtitle = lastUpdatedLabel ?: stringResource(R.string.epg_updated_now),
- modifier = Modifier.weight(1f)
- )
- if (uiState.isGuideStale) {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ item {
GuideSummaryPill(
- title = stringResource(R.string.epg_stale_warning),
- subtitle = uiState.providerSourceLabel.ifBlank { stringResource(R.string.nav_epg) },
- modifier = Modifier.weight(1f),
- accent = MaterialTheme.colorScheme.error
+ title = stringResource(
+ R.string.epg_showing_channels,
+ uiState.channels.size,
+ uiState.totalChannelCount
+ ),
+ subtitle = stringResource(
+ R.string.epg_schedule_summary_short,
+ uiState.channelsWithSchedule,
+ uiState.channels.size
+ )
+ )
+ }
+ item {
+ GuideSummaryPill(
+ title = windowLabel,
+ subtitle = lastUpdatedLabel ?: stringResource(R.string.epg_updated_now)
)
}
+ if (uiState.isGuideStale) {
+ item {
+ GuideSummaryPill(
+ title = stringResource(R.string.epg_stale_short),
+ subtitle = uiState.providerSourceLabel.ifBlank { stringResource(R.string.nav_epg) },
+ accent = MaterialTheme.colorScheme.error
+ )
+ }
+ }
}
}
-@Composable
-private fun GuideSummaryPill(
- title: String,
- subtitle: String,
- modifier: Modifier = Modifier,
- accent: Color = Primary
-) {
- Surface(
- modifier = modifier,
- colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight),
- shape = RoundedCornerShape(16.dp)
- ) {
- Column(
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
- verticalArrangement = Arrangement.spacedBy(4.dp)
- ) {
- Text(
- text = title,
- style = MaterialTheme.typography.titleSmall,
- color = OnSurface
- )
- Text(
- text = subtitle,
- style = MaterialTheme.typography.bodySmall,
- color = accent
- )
+private data class GuideHeroSelection(
+ val channel: Channel,
+ val program: Program?,
+ val isFallbackToChannel: Boolean
+)
+
+private fun resolveGuideHeroSelection(
+ uiState: EpgUiState,
+ focusedChannel: Channel?,
+ focusedProgram: Program?,
+ now: Long
+): GuideHeroSelection? {
+ val resolvedChannel = focusedChannel
+ ?.let { current -> uiState.channels.firstOrNull { it.id == current.id } }
+ ?: uiState.channels.firstOrNull()
+ ?: return null
+ val programs = resolvedChannel.guideLookupKey()?.let { lookupKey ->
+ uiState.programsByChannel[lookupKey].orEmpty()
+ }.orEmpty()
+ val resolvedProgram = focusedProgram?.let { focused ->
+ programs.firstOrNull {
+ it.startTime == focused.startTime &&
+ it.endTime == focused.endTime &&
+ it.title == focused.title
}
- }
+ } ?: programs.firstOrNull { now in it.startTime until it.endTime } ?: programs.firstOrNull()
+ return GuideHeroSelection(
+ channel = resolvedChannel,
+ program = resolvedProgram,
+ isFallbackToChannel = resolvedProgram == null
+ )
}
@Composable
-private fun GuideMessageState(
- modifier: Modifier = Modifier,
- title: String,
- subtitle: String?,
- actionLabel: String?,
- onAction: (() -> Unit)?
+private fun ImmersiveGuideHero(
+ selection: GuideHeroSelection?,
+ providerLabel: String,
+ selectedCategoryName: String,
+ isGuideStale: Boolean,
+ channelCount: Int,
+ channelsWithSchedule: Int,
+ lastUpdatedAt: Long?,
+ isRefreshing: Boolean,
+ modifier: Modifier = Modifier
) {
- Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(10.dp),
- modifier = Modifier.padding(horizontal = 32.dp)
+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
+ val currentTime = System.currentTimeMillis()
+ val lastUpdatedLabel = remember(lastUpdatedAt, currentTime) {
+ lastUpdatedAt?.let { updatedAt ->
+ val minutes = ((currentTime - updatedAt).coerceAtLeast(0L) / 60_000L).toInt()
+ if (minutes <= 0) {
+ "Updated just now"
+ } else {
+ "$minutes min ago"
+ }
+ }
+ }
+
+ Surface(
+ modifier = modifier.height(108.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 14.dp, vertical = 10.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ verticalAlignment = Alignment.CenterVertically
) {
- Text(
- text = title,
- style = MaterialTheme.typography.titleLarge,
- color = OnSurface
+ val channel = selection?.channel
+ ChannelLogoBadge(
+ channelName = channel?.name ?: stringResource(R.string.epg_title),
+ logoUrl = channel?.logoUrl,
+ modifier = Modifier
+ .width(64.dp)
+ .height(64.dp),
+ shape = RoundedCornerShape(12.dp)
)
- if (!subtitle.isNullOrBlank()) {
+
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ val program = selection?.program
Text(
- text = subtitle,
- style = MaterialTheme.typography.bodyMedium,
- color = OnSurfaceDim
+ text = program?.title ?: channel?.name ?: stringResource(R.string.epg_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = buildString {
+ channel?.let { append("${it.number}. ${it.name}") }
+ if (providerLabel.isNotBlank()) {
+ if (isNotEmpty()) append(" | ")
+ append(providerLabel)
+ }
+ if (selectedCategoryName.isNotBlank()) {
+ if (isNotEmpty()) append(" | ")
+ append(selectedCategoryName)
+ }
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
+ if (program != null) {
+ Text(
+ text = "${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurface
+ )
+ if (currentTime in program.startTime until program.endTime) {
+ LinearProgressIndicator(
+ progress = { ((currentTime - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp),
+ color = Primary,
+ trackColor = SurfaceHighlight
+ )
+ }
+ Text(
+ text = program.description.ifBlank { stringResource(R.string.epg_hero_no_program_description) },
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ } else {
+ Text(
+ text = stringResource(R.string.epg_no_schedule),
+ style = MaterialTheme.typography.labelLarge,
+ color = OnSurface
+ )
+ Text(
+ text = stringResource(R.string.epg_hero_no_schedule_hint),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
- if (actionLabel != null && onAction != null) {
- Button(
- onClick = onAction,
- colors = ButtonDefaults.colors(
- containerColor = Primary,
- contentColor = Color.White
+
+ Column(
+ modifier = Modifier.widthIn(min = 118.dp, max = 136.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ GuideHeroBadge(text = stringResource(R.string.epg_schedule_summary_short, channelsWithSchedule, channelCount))
+ if (isRefreshing) {
+ GuideHeroBadge(text = stringResource(R.string.epg_loading))
+ }
+ if (selection?.program?.hasArchive == true || selection?.channel?.catchUpSupported == true) {
+ GuideHeroBadge(
+ text = if (selection.program?.hasArchive == true) {
+ stringResource(R.string.epg_program_replay_ready)
+ } else {
+ stringResource(R.string.epg_program_replay_partial)
+ },
+ highlight = true
+ )
+ }
+ if (isGuideStale) {
+ GuideHeroBadge(
+ text = stringResource(R.string.epg_stale_short),
+ accentColor = Color(0xFFFF6B6B)
+ )
+ }
+ if (!lastUpdatedLabel.isNullOrBlank()) {
+ Text(
+ text = lastUpdatedLabel,
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
)
- ) {
- Text(actionLabel)
}
}
}
@@ -1212,8 +1255,485 @@ private fun GuideMessageState(
}
@Composable
-fun EpgGrid(
- modifier: Modifier = Modifier,
+private fun GuideHeroBadge(
+ text: String,
+ highlight: Boolean = false,
+ accentColor: Color = Primary
+) {
+ Surface(
+ shape = RoundedCornerShape(999.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = if (highlight) accentColor.copy(alpha = 0.18f) else SurfaceHighlight
+ )
+ ) {
+ Text(
+ text = text,
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
+ style = MaterialTheme.typography.labelMedium,
+ color = if (highlight) accentColor else OnSurface
+ )
+ }
+}
+
+@Composable
+private fun GuideToolbarRow(
+ selectedCategoryName: String,
+ onOpenCategoryPicker: () -> Unit,
+ onJumpToNow: () -> Unit,
+ onOpenSearch: () -> Unit,
+ onOpenOptions: () -> Unit,
+ onGuideInteract: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Row(
+ modifier = modifier,
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ GuideToolbarButton(
+ label = selectedCategoryName,
+ modifier = Modifier.widthIn(min = 220.dp, max = 300.dp),
+ onClick = onOpenCategoryPicker,
+ onFocused = onGuideInteract
+ )
+ GuideToolbarButton(
+ label = stringResource(R.string.epg_jump_now),
+ onClick = onJumpToNow,
+ onFocused = onGuideInteract
+ )
+ GuideToolbarButton(
+ label = stringResource(R.string.epg_search_label),
+ onClick = onOpenSearch,
+ onFocused = onGuideInteract
+ )
+ GuideToolbarButton(
+ label = stringResource(R.string.epg_options_short),
+ onClick = onOpenOptions,
+ onFocused = onGuideInteract
+ )
+ }
+}
+
+@Composable
+private fun GuideToolbarButton(
+ label: String,
+ modifier: Modifier = Modifier,
+ onClick: () -> Unit,
+ onFocused: () -> Unit
+) {
+ var focused by remember { mutableStateOf(false) }
+ Surface(
+ onClick = onClick,
+ modifier = modifier.onFocusChanged {
+ if (it.isFocused && !focused) onFocused()
+ focused = it.isFocused
+ },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(14.dp)
+ )
+ )
+ ) {
+ Text(
+ text = label,
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
+ style = MaterialTheme.typography.labelLarge,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+}
+
+@Composable
+private fun GuideModalDialog(
+ onDismiss: () -> Unit,
+ contentAlignment: Alignment = Alignment.Center,
+ content: @Composable BoxScope.() -> Unit
+) {
+ Dialog(
+ onDismissRequest = onDismiss,
+ properties = DialogProperties(
+ usePlatformDefaultWidth = false,
+ dismissOnBackPress = true,
+ dismissOnClickOutside = false
+ )
+ ) {
+ Box(
+ modifier = Modifier.fillMaxSize(),
+ contentAlignment = contentAlignment
+ ) {
+ Box(
+ modifier = Modifier
+ .matchParentSize()
+ .background(Color.Black.copy(alpha = 0.68f))
+ .clickable(
+ onClick = onDismiss,
+ indication = null,
+ interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
+ )
+ )
+ content()
+ }
+ }
+}
+
+@Composable
+private fun GuideSearchOverlay(
+ query: String,
+ onQueryChange: (String) -> Unit,
+ onClear: () -> Unit,
+ onDismiss: () -> Unit
+) {
+ val searchFocusRequester = remember { FocusRequester() }
+ LaunchedEffect(Unit) {
+ searchFocusRequester.requestFocus()
+ }
+ GuideModalDialog(
+ onDismiss = onDismiss,
+ contentAlignment = Alignment.TopCenter
+ ) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth(0.72f)
+ .padding(top = 32.dp)
+ .focusGroup(),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(18.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.epg_search_label),
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface
+ )
+ GuideShortcutChip(
+ label = stringResource(R.string.settings_cancel),
+ onClick = onDismiss
+ )
+ }
+ GuideProgramSearchRow(
+ query = query,
+ onQueryChange = onQueryChange,
+ onClear = onClear,
+ focusRequester = searchFocusRequester,
+ contentPadding = PaddingValues(0.dp),
+ showLabel = false
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideOptionsOverlay(
+ uiState: EpgUiState,
+ onDismiss: () -> Unit,
+ onShowAppNavigation: () -> Unit,
+ onJumpToPreviousDay: () -> Unit,
+ onPageBackward: () -> Unit,
+ onJumpBackwardHalfHour: () -> Unit,
+ onJumpBackward: () -> Unit,
+ onJumpToNow: () -> Unit,
+ onJumpForwardHalfHour: () -> Unit,
+ onJumpForward: () -> Unit,
+ onPageForward: () -> Unit,
+ onJumpToPrimeTime: () -> Unit,
+ onJumpToTomorrow: () -> Unit,
+ onJumpToNextDay: () -> Unit,
+ onDaySelected: (Long) -> Unit,
+ onModeSelected: (GuideChannelMode) -> Unit,
+ onDensitySelected: (GuideDensity) -> Unit,
+ onToggleScheduledOnly: () -> Unit,
+ onToggleFavoritesOnly: () -> Unit,
+ onRefresh: () -> Unit
+) {
+ val optionsFocusRequester = remember { FocusRequester() }
+ LaunchedEffect(Unit) {
+ optionsFocusRequester.requestFocus()
+ }
+ GuideModalDialog(onDismiss = onDismiss) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth(0.68f)
+ .fillMaxHeight(0.78f)
+ .focusGroup(),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(vertical = 18.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 18.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.epg_options_short),
+ style = MaterialTheme.typography.headlineSmall,
+ color = OnSurface
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_show_app_navigation),
+ onClick = onShowAppNavigation
+ )
+ GuideShortcutChip(
+ label = stringResource(R.string.settings_cancel),
+ onClick = onDismiss
+ )
+ }
+ }
+ GuideTimeControlsRow(
+ onJumpToPreviousDay = onJumpToPreviousDay,
+ onPageBackward = onPageBackward,
+ onJumpBackwardHalfHour = onJumpBackwardHalfHour,
+ onJumpBackward = onJumpBackward,
+ onJumpToNow = onJumpToNow,
+ onJumpForwardHalfHour = onJumpForwardHalfHour,
+ onJumpForward = onJumpForward,
+ onPageForward = onPageForward,
+ onJumpToPrimeTime = onJumpToPrimeTime,
+ onJumpToTomorrow = onJumpToTomorrow,
+ onJumpToNextDay = onJumpToNextDay,
+ firstChipFocusRequester = optionsFocusRequester
+ )
+ GuideDayRow(
+ selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),
+ onDaySelected = onDaySelected
+ )
+ GuideModeRow(
+ selectedMode = uiState.selectedChannelMode,
+ onModeSelected = onModeSelected
+ )
+ GuideDensityRow(
+ selectedDensity = uiState.selectedDensity,
+ onDensitySelected = onDensitySelected
+ )
+ GuideViewOptionsRow(
+ showScheduledOnly = uiState.showScheduledOnly,
+ onToggleScheduledOnly = onToggleScheduledOnly
+ )
+ GuideFavoritesRow(
+ showFavoritesOnly = uiState.showFavoritesOnly,
+ onToggleFavoritesOnly = onToggleFavoritesOnly
+ )
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp),
+ horizontalArrangement = Arrangement.End
+ ) {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_refresh_guide),
+ onClick = onRefresh
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun CompactGuideProgramDialog(
+ channel: Channel,
+ program: Program,
+ providerLabel: String,
+ now: Long,
+ onDismiss: () -> Unit,
+ onWatchLive: () -> Unit,
+ onWatchArchive: (() -> Unit)?
+) {
+ var showDetails by rememberSaveable(program.startTime, program.endTime, program.title) { mutableStateOf(false) }
+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
+ GuideModalDialog(onDismiss = onDismiss) {
+ Surface(
+ modifier = Modifier.widthIn(min = 420.dp, max = 640.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ Text(
+ text = program.title,
+ style = MaterialTheme.typography.headlineSmall,
+ color = OnSurface,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = "${channel.number}. ${channel.name} | ${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ if (providerLabel.isNotBlank()) {
+ Text(
+ text = providerLabel,
+ style = MaterialTheme.typography.labelMedium,
+ color = Primary
+ )
+ }
+ if (now in program.startTime until program.endTime) {
+ LinearProgressIndicator(
+ progress = { ((now - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp),
+ color = Primary,
+ trackColor = SurfaceHighlight
+ )
+ }
+ if (showDetails) {
+ Text(
+ text = program.description.ifBlank { stringResource(R.string.epg_no_info) },
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurface,
+ maxLines = 6,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Button(
+ onClick = onWatchLive,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(stringResource(R.string.epg_watch_live))
+ }
+ if (onWatchArchive != null) {
+ Button(
+ onClick = onWatchArchive,
+ modifier = Modifier.fillMaxWidth(),
+ colors = ButtonDefaults.colors(
+ containerColor = Primary,
+ contentColor = Color.White
+ )
+ ) {
+ Text(stringResource(R.string.epg_watch_archive))
+ }
+ }
+ Button(
+ onClick = { showDetails = !showDetails },
+ modifier = Modifier.fillMaxWidth(),
+ colors = ButtonDefaults.colors(
+ containerColor = SurfaceHighlight,
+ contentColor = OnSurface
+ )
+ ) {
+ Text(
+ if (showDetails) stringResource(R.string.epg_program_details_hide)
+ else stringResource(R.string.epg_program_details_show)
+ )
+ }
+ TextButton(onClick = onDismiss) {
+ Text(stringResource(R.string.settings_cancel))
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideSummaryPill(
+ title: String,
+ subtitle: String,
+ modifier: Modifier = Modifier,
+ accent: Color = Primary
+) {
+ Surface(
+ modifier = modifier,
+ colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight),
+ shape = RoundedCornerShape(14.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurface
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = accent
+ )
+ }
+ }
+}
+
+@Composable
+private fun GuideMessageState(
+ modifier: Modifier = Modifier,
+ title: String,
+ subtitle: String?,
+ actionLabel: String?,
+ onAction: (() -> Unit)?
+) {
+ Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ modifier = Modifier.padding(horizontal = 32.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface
+ )
+ if (!subtitle.isNullOrBlank()) {
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ }
+ if (actionLabel != null && onAction != null) {
+ Button(
+ onClick = onAction,
+ colors = ButtonDefaults.colors(
+ containerColor = Primary,
+ contentColor = Color.White
+ )
+ ) {
+ Text(actionLabel)
+ }
+ }
+ }
+ }
+}
+
+@Composable
+fun EpgGrid(
+ modifier: Modifier = Modifier,
channels: List<Channel>,
favoriteChannelIds: Set<Long>,
programsByChannel: Map<String, List<Program>>,
@@ -1222,57 +1742,79 @@ fun EpgGrid(
density: GuideDensity,
now: Long,
onChannelClick: (Channel) -> Unit,
- onProgramClick: (Channel, Program) -> Unit
+ onProgramClick: (Channel, Program) -> Unit,
+ onChannelFocused: (Channel, Program?) -> Unit,
+ onProgramFocused: (Channel, Program) -> Unit
) {
- val (channelRailWidth, timelineGap, rowHeight) = when (density) {
- GuideDensity.COMPACT -> Triple(180.dp, 12.dp, 76.dp)
- GuideDensity.COMFORTABLE -> Triple(220.dp, 16.dp, 92.dp)
- GuideDensity.CINEMATIC -> Triple(260.dp, 20.dp, 108.dp)
+ val channelRailWidth = 184.dp
+ val timelineGap = 6.dp
+ val rowHeight = when (density) {
+ GuideDensity.COMPACT -> 36.dp
+ GuideDensity.COMFORTABLE -> 42.dp
+ GuideDensity.CINEMATIC -> 50.dp
}
+ val horizontalScrollState = rememberScrollState()
BoxWithConstraints(
modifier = modifier
.fillMaxSize()
- .padding(horizontal = 24.dp, vertical = 16.dp)
+ .padding(horizontal = 12.dp, vertical = 2.dp)
) {
- val timelineWidth = (maxWidth - channelRailWidth - timelineGap).coerceAtLeast(720.dp)
+ val timelineViewportWidth = (maxWidth - channelRailWidth - timelineGap).coerceAtLeast(640.dp)
+ val totalDuration = (guideWindowEnd - guideWindowStart).coerceAtLeast(1L)
+ val visibleDurationMs = 3 * 60 * 60 * 1000L
+ val calculatedTimelineWidth = timelineViewportWidth * (totalDuration.toFloat() / visibleDurationMs.toFloat())
+ val totalTimelineWidth = if (calculatedTimelineWidth > timelineViewportWidth) {
+ calculatedTimelineWidth
+ } else {
+ timelineViewportWidth
+ }
val markerStepMs = EpgViewModel.HALF_HOUR_SHIFT_MS
- LazyColumn(
- modifier = Modifier.fillMaxSize(),
- verticalArrangement = Arrangement.spacedBy(14.dp)
- ) {
- item(key = "timeline_header") {
- GuideTimelineHeader(
- windowStart = guideWindowStart,
- windowEnd = guideWindowEnd,
- now = now,
- channelRailWidth = channelRailWidth,
- timelineGap = timelineGap,
- timelineWidth = timelineWidth,
- markerStepMs = markerStepMs
- )
- }
- itemsIndexed(
- items = channels,
- key = { index, channel -> epgChannelKey(channel, index) }
- ) { _, channel ->
- val programs = channel.epgChannelId?.let { programsByChannel[it] } ?: emptyList()
- EpgRow(
- channel = channel,
- isFavorite = channel.id in favoriteChannelIds,
- programs = programs,
- now = now,
- windowStart = guideWindowStart,
- windowEnd = guideWindowEnd,
- channelRailWidth = channelRailWidth,
- timelineGap = timelineGap,
- timelineWidth = timelineWidth,
- rowHeight = rowHeight,
- markerStepMs = markerStepMs,
- onChannelClick = { onChannelClick(channel) },
- onProgramClick = { program -> onProgramClick(channel, program) }
- )
+ Column(modifier = Modifier.fillMaxSize()) {
+ GuideTimelineHeader(
+ windowStart = guideWindowStart,
+ windowEnd = guideWindowEnd,
+ now = now,
+ channelRailWidth = channelRailWidth,
+ timelineGap = timelineGap,
+ timelineViewportWidth = timelineViewportWidth,
+ totalTimelineWidth = totalTimelineWidth,
+ markerStepMs = markerStepMs,
+ scrollState = horizontalScrollState
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
+ itemsIndexed(
+ items = channels,
+ key = { index, channel -> epgChannelKey(channel, index) }
+ ) { _, channel ->
+ val programs = channel.guideLookupKey()?.let { lookupKey ->
+ programsByChannel[lookupKey].orEmpty()
+ }.orEmpty()
+ EpgRow(
+ channel = channel,
+ isFavorite = channel.id in favoriteChannelIds,
+ programs = programs,
+ now = now,
+ windowStart = guideWindowStart,
+ windowEnd = guideWindowEnd,
+ channelRailWidth = channelRailWidth,
+ timelineGap = timelineGap,
+ timelineViewportWidth = timelineViewportWidth,
+ totalTimelineWidth = totalTimelineWidth,
+ rowHeight = rowHeight,
+ markerStepMs = markerStepMs,
+ scrollState = horizontalScrollState,
+ onChannelClick = { onChannelClick(channel) },
+ onChannelFocused = { onChannelFocused(channel, it) },
+ onProgramClick = { program -> onProgramClick(channel, program) },
+ onProgramFocused = { program -> onProgramFocused(channel, program) }
+ )
+ }
}
}
}
@@ -1285,8 +1827,10 @@ private fun GuideTimelineHeader(
now: Long,
channelRailWidth: Dp,
timelineGap: Dp,
- timelineWidth: Dp,
- markerStepMs: Long
+ timelineViewportWidth: Dp,
+ totalTimelineWidth: Dp,
+ markerStepMs: Long,
+ scrollState: androidx.compose.foundation.ScrollState
) {
val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)
@@ -1311,13 +1855,13 @@ private fun GuideTimelineHeader(
Row(
modifier = Modifier
.fillMaxWidth()
- .padding(bottom = 4.dp),
+ .padding(bottom = 2.dp),
verticalAlignment = Alignment.Bottom
) {
Spacer(modifier = Modifier.width(channelRailWidth + timelineGap))
Column(
- modifier = Modifier.width(timelineWidth),
- verticalArrangement = Arrangement.spacedBy(8.dp)
+ modifier = Modifier.width(timelineViewportWidth),
+ verticalArrangement = Arrangement.spacedBy(3.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
@@ -1340,57 +1884,55 @@ private fun GuideTimelineHeader(
}
Box(
modifier = Modifier
- .fillMaxWidth()
- .height(44.dp)
+ .width(timelineViewportWidth)
+ .height(22.dp)
) {
- hourMarkers.forEach { marker ->
- val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
- val markerOffset = timelineWidth * markerRatio
- Column(
- modifier = Modifier.padding(start = markerOffset),
- verticalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- Text(
- text = hourFormat.format(Date(marker)),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- Box(
- modifier = Modifier
- .width(1.dp)
- .height(18.dp)
- .background(Color.White.copy(alpha = 0.16f))
- )
- }
- }
- if (now in windowStart..windowEnd) {
+ Row(
+ modifier = Modifier
+ .width(totalTimelineWidth)
+ .horizontalScroll(scrollState)
+ ) {
Box(
modifier = Modifier
- .padding(start = timelineWidth * elapsedRatio)
- .width(2.dp)
- .fillMaxHeight()
- .background(Primary)
- )
+ .width(totalTimelineWidth)
+ .height(22.dp)
+ ) {
+ hourMarkers.forEach { marker ->
+ val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ val markerOffset = totalTimelineWidth * markerRatio
+ Column(
+ modifier = Modifier.padding(start = markerOffset),
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
+ Text(
+ text = hourFormat.format(Date(marker)),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
+ )
+ Box(
+ modifier = Modifier
+ .width(1.dp)
+ .height(10.dp)
+ .background(Color.White.copy(alpha = 0.16f))
+ )
+ }
+ }
+ if (now in windowStart..windowEnd) {
+ Box(
+ modifier = Modifier
+ .padding(start = totalTimelineWidth * elapsedRatio)
+ .width(2.dp)
+ .fillMaxHeight()
+ .background(Primary)
+ )
+ }
+ }
}
}
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = markerLabel,
- style = MaterialTheme.typography.labelMedium,
- color = if (now in windowStart..windowEnd) Primary else OnSurfaceDim
- )
- }
- LinearProgressIndicator(
- progress = { elapsedRatio },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp),
- color = Primary,
- trackColor = SurfaceElevated
+ Text(
+ text = markerLabel,
+ style = MaterialTheme.typography.labelSmall,
+ color = if (now in windowStart..windowEnd) Primary else OnSurfaceDim
)
}
}
@@ -1406,11 +1948,15 @@ fun EpgRow(
windowEnd: Long,
channelRailWidth: Dp,
timelineGap: Dp,
- timelineWidth: Dp,
+ timelineViewportWidth: Dp,
+ totalTimelineWidth: Dp,
rowHeight: Dp,
markerStepMs: Long,
+ scrollState: androidx.compose.foundation.ScrollState,
onChannelClick: () -> Unit,
- onProgramClick: (Program) -> Unit
+ onChannelFocused: (Program?) -> Unit,
+ onProgramClick: (Program) -> Unit,
+ onProgramFocused: (Program) -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)
@@ -1427,7 +1973,12 @@ fun EpgRow(
modifier = Modifier
.width(channelRailWidth)
.fillMaxHeight()
- .onFocusChanged { isFocused = it.isFocused },
+ .onFocusChanged {
+ if (it.isFocused && !isFocused) {
+ onChannelFocused(currentProgram)
+ }
+ isFocused = it.isFocused
+ },
colors = ClickableSurfaceDefaults.colors(
containerColor = SurfaceElevated,
focusedContainerColor = SurfaceHighlight
@@ -1442,56 +1993,68 @@ fun EpgRow(
) {
Row(
modifier = Modifier
- .padding(12.dp)
- .fillMaxSize(),
+ .padding(horizontal = 8.dp, vertical = 6.dp)
+ .fillMaxSize(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
- if (isFavorite) {
- Text(
- text = stringResource(R.string.epg_favorite_badge),
- style = MaterialTheme.typography.labelSmall,
- color = Primary,
- maxLines = 1
- )
- }
+ ChannelLogoBadge(
+ channelName = channel.name,
+ logoUrl = channel.logoUrl,
+ modifier = Modifier
+ .width(24.dp)
+ .height(24.dp),
+ shape = RoundedCornerShape(6.dp)
+ )
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(1.dp)
+ ) {
Text(
- text = stringResource(R.string.channel_number_name_format, channel.number, channel.name),
- style = MaterialTheme.typography.titleMedium,
+ text = "${channel.number}. ${channel.name}",
+ style = MaterialTheme.typography.bodyMedium,
color = if (isFocused) TextPrimary else OnSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
- text = currentProgram?.title ?: stringResource(R.string.epg_no_schedule),
+ text = currentProgram?.title ?: stringResource(R.string.epg_no_schedule_short),
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
+ if (isFavorite || channel.catchUpSupported) {
+ Text(
+ text = if (channel.catchUpSupported) stringResource(R.string.player_archive_badge) else stringResource(R.string.epg_favorite_badge),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
}
Spacer(modifier = Modifier.width(timelineGap))
- if (programs.isEmpty()) {
- Box(
- modifier = Modifier
- .width(timelineWidth)
- .fillMaxHeight()
- .background(SurfaceElevated, RoundedCornerShape(8.dp)),
- contentAlignment = Alignment.Center
- ) {
- Text(stringResource(R.string.epg_no_schedule), color = OnSurfaceDim)
- }
- } else {
- Box(
+ Box(
+ modifier = Modifier
+ .width(timelineViewportWidth)
+ .fillMaxHeight()
+ .background(SurfaceElevated, RoundedCornerShape(8.dp))
+ ) {
+ Row(
modifier = Modifier
- .width(timelineWidth)
- .fillMaxHeight()
- .background(SurfaceElevated, RoundedCornerShape(8.dp))
+ .width(totalTimelineWidth)
+ .horizontalScroll(scrollState)
) {
+ Box(
+ modifier = Modifier
+ .width(totalTimelineWidth)
+ .fillMaxHeight()
+ ) {
val markers = remember(windowStart, windowEnd, markerStepMs) {
buildList {
var marker = windowStart
@@ -1505,7 +2068,7 @@ fun EpgRow(
val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
Box(
modifier = Modifier
- .padding(start = timelineWidth * markerRatio)
+ .padding(start = totalTimelineWidth * markerRatio)
.width(1.dp)
.fillMaxHeight()
.background(Color.White.copy(alpha = 0.08f))
@@ -1515,22 +2078,30 @@ fun EpgRow(
val nowRatio = ((now - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
Box(
modifier = Modifier
- .padding(start = timelineWidth * nowRatio)
+ .padding(start = totalTimelineWidth * nowRatio)
.width(2.dp)
.fillMaxHeight()
.background(Primary)
)
}
- programs.forEach { program ->
- ProgramItem(
- program = program,
- isCurrent = now in program.startTime..program.endTime,
- now = now,
- windowStart = windowStart,
- windowEnd = windowEnd,
- timelineWidth = timelineWidth,
- onClick = { onProgramClick(program) }
- )
+ if (programs.isEmpty()) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Text(stringResource(R.string.epg_no_schedule_short), color = OnSurfaceDim)
+ }
+ } else {
+ programs.forEach { program ->
+ ProgramItem(
+ program = program,
+ isCurrent = now in program.startTime until program.endTime,
+ now = now,
+ windowStart = windowStart,
+ windowEnd = windowEnd,
+ totalTimelineWidth = totalTimelineWidth,
+ onClick = { onProgramClick(program) },
+ onFocused = { onProgramFocused(program) }
+ )
+ }
+ }
}
}
}
@@ -1544,8 +2115,9 @@ fun ProgramItem(
now: Long,
windowStart: Long,
windowEnd: Long,
- timelineWidth: Dp,
- onClick: () -> Unit
+ totalTimelineWidth: Dp,
+ onClick: () -> Unit,
+ onFocused: () -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
@@ -1557,22 +2129,21 @@ fun ProgramItem(
val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))
val startRatio = ((visibleStart - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
- val itemStart = timelineWidth * startRatio
- val itemWidth = (timelineWidth * widthRatio).coerceAtLeast(96.dp)
- val elapsedRatio = if (program.endTime > program.startTime) {
- ((now - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f)
- } else {
- 0f
- }
- val remainingMinutes = ((program.endTime - now) / 60_000L).coerceAtLeast(0L)
+ val itemStart = totalTimelineWidth * startRatio
+ val itemWidth = (totalTimelineWidth * widthRatio).coerceAtLeast(72.dp)
Surface(
onClick = onClick,
modifier = Modifier
- .padding(start = itemStart, top = 6.dp, bottom = 6.dp)
+ .padding(start = itemStart, top = 4.dp, bottom = 4.dp)
.width(itemWidth)
.fillMaxHeight()
- .onFocusChanged { isFocused = it.isFocused },
+ .onFocusChanged {
+ if (it.isFocused && !isFocused) {
+ onFocused()
+ }
+ isFocused = it.isFocused
+ },
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,
focusedContainerColor = SurfaceHighlight
@@ -1587,59 +2158,25 @@ fun ProgramItem(
) {
Column(
modifier = Modifier
- .padding(12.dp)
+ .padding(horizontal = 8.dp, vertical = 6.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
- if (isCurrent) {
- Text(
- text = stringResource(R.string.epg_now_playing),
- style = MaterialTheme.typography.labelSmall,
- color = Primary,
- maxLines = 1
- )
- Spacer(modifier = Modifier.height(4.dp))
- }
Text(
text = program.title,
- style = MaterialTheme.typography.titleSmall,
+ style = MaterialTheme.typography.labelLarge,
color = if (isFocused) TextPrimary else if (isCurrent) Primary else OnSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
- Spacer(modifier = Modifier.height(4.dp))
+ Spacer(modifier = Modifier.height(2.dp))
Text(
text = "$startStr - $endStr",
- style = MaterialTheme.typography.bodySmall,
- color = if (isFocused) TextSecondary else OnSurfaceDim
+ style = MaterialTheme.typography.labelSmall,
+ color = if (isFocused) TextSecondary else OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
- if (program.hasArchive) {
- Spacer(modifier = Modifier.height(4.dp))
- Text(
- text = stringResource(R.string.player_archive_badge),
- style = MaterialTheme.typography.labelSmall,
- color = Primary,
- maxLines = 1
- )
- }
- if (isCurrent) {
- Spacer(modifier = Modifier.height(8.dp))
- LinearProgressIndicator(
- progress = { elapsedRatio },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp),
- color = Primary,
- trackColor = SurfaceHighlight
- )
- Spacer(modifier = Modifier.height(4.dp))
- Text(
- text = stringResource(R.string.epg_minutes_remaining, remainingMinutes),
- style = MaterialTheme.typography.labelSmall,
- color = OnSurfaceDim,
- maxLines = 1
- )
- }
}
}
}
@@ -1695,23 +2232,19 @@ private fun GuideHeaderDeck(
Surface(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 12.dp),
+ .padding(horizontal = 24.dp, vertical = 8.dp),
colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
- shape = RoundedCornerShape(20.dp)
+ shape = RoundedCornerShape(18.dp)
) {
Column(
- modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
- verticalArrangement = Arrangement.spacedBy(14.dp)
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
) {
GuideSummaryCard(uiState = uiState)
- GuideCategoryLauncherRow(
+ GuidePrimaryControlsRow(
categories = uiState.categories,
selectedCategoryId = uiState.selectedCategoryId,
- onOpenCategoryPicker = onOpenCategoryPicker
- )
-
- GuidePrimaryControlsRow(
showSearchBar = showSearchBar,
showAdvancedOptions = showAdvancedOptions,
onJumpToPreviousDay = onJumpToPreviousDay,
@@ -1785,6 +2318,8 @@ private fun GuideHeaderDeck(
@Composable
private fun GuidePrimaryControlsRow(
+ categories: List<Category>,
+ selectedCategoryId: Long,
showSearchBar: Boolean,
showAdvancedOptions: Boolean,
onJumpToPreviousDay: () -> Unit,
@@ -1797,25 +2332,41 @@ private fun GuidePrimaryControlsRow(
onToggleSearch: () -> Unit,
onToggleAdvancedOptions: () -> Unit
) {
- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- item { GuideShortcutChip(label = stringResource(R.string.epg_filter_label), onClick = onOpenCategoryPicker) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_previous_day), onClick = onJumpToPreviousDay) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back), onClick = onJumpBackward) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_now), onClick = onJumpToNow) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward), onClick = onJumpForward) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_prime_time), onClick = onJumpToPrimeTime) }
- item { GuideShortcutChip(label = stringResource(R.string.epg_next_day), onClick = onJumpToNextDay) }
- item {
- GuideShortcutChip(
- label = if (showSearchBar) stringResource(R.string.epg_clear_search) else stringResource(R.string.epg_search_label),
- onClick = onToggleSearch
- )
- }
- item {
- GuideShortcutChip(
- label = stringResource(if (showAdvancedOptions) R.string.epg_hide_options else R.string.epg_show_options),
- onClick = onToggleAdvancedOptions
- )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ GuideCategoryLauncherRow(
+ categories = categories,
+ selectedCategoryId = selectedCategoryId,
+ onOpenCategoryPicker = onOpenCategoryPicker,
+ modifier = Modifier.widthIn(min = 220.dp, max = 360.dp)
+ )
+
+ LazyRow(
+ modifier = Modifier.weight(1f),
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ item { GuideShortcutChip(label = stringResource(R.string.epg_previous_day), onClick = onJumpToPreviousDay) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_now), onClick = onJumpToNow) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_next_day), onClick = onJumpToNextDay) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back), onClick = onJumpBackward) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward), onClick = onJumpForward) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_prime_time), onClick = onJumpToPrimeTime) }
+ item {
+ GuideShortcutChip(
+ label = if (showSearchBar) stringResource(R.string.epg_clear_search) else stringResource(R.string.epg_search_short),
+ onClick = onToggleSearch
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_options_short),
+ onClick = onToggleAdvancedOptions,
+ isSelected = showAdvancedOptions
+ )
+ }
}
}
}
@@ -1824,13 +2375,15 @@ private fun GuidePrimaryControlsRow(
private fun GuideCategoryLauncherRow(
categories: List<Category>,
selectedCategoryId: Long,
- onOpenCategoryPicker: () -> Unit
+ onOpenCategoryPicker: () -> Unit,
+ modifier: Modifier = Modifier
) {
val selectedCategory = remember(categories, selectedCategoryId) {
categories.firstOrNull { it.id == selectedCategoryId }
}
Surface(
onClick = onOpenCategoryPicker,
+ modifier = modifier.widthIn(max = 320.dp),
colors = ClickableSurfaceDefaults.colors(
containerColor = SurfaceHighlight,
focusedContainerColor = SurfaceElevated,
@@ -1848,25 +2401,31 @@ private fun GuideCategoryLauncherRow(
Row(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 14.dp),
+ .padding(horizontal = 14.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(1.dp)
+ ) {
Text(
text = selectedCategory?.name ?: stringResource(R.string.epg_filter_label),
- style = MaterialTheme.typography.titleMedium,
- color = OnSurface
+ style = MaterialTheme.typography.labelLarge,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
Text(
text = "${categories.size} categories",
- style = MaterialTheme.typography.bodySmall,
+ style = MaterialTheme.typography.labelSmall,
color = OnSurfaceDim
)
}
+ Spacer(modifier = Modifier.width(10.dp))
Text(
text = stringResource(R.string.epg_filter_label),
- style = MaterialTheme.typography.labelLarge,
+ style = MaterialTheme.typography.labelMedium,
color = Primary
)
}
@@ -1881,30 +2440,30 @@ private fun GuideCategoryPickerDialog(
onCategorySelected: (Long) -> Unit
) {
var query by rememberSaveable { mutableStateOf("") }
+ val searchFocusRequester = remember { FocusRequester() }
val filteredCategories = remember(categories, query) {
val trimmed = query.trim()
- if (trimmed.isBlank()) {
+ val baseCategories = if (trimmed.isBlank()) {
categories
} else {
categories.filter { it.name.contains(trimmed, ignoreCase = true) }
}
+ val selectedCategory = baseCategories.firstOrNull { it.id == selectedCategoryId }
+ buildList {
+ if (selectedCategory != null) add(selectedCategory)
+ addAll(baseCategories.filterNot { it.id == selectedCategoryId })
+ }
+ }
+ LaunchedEffect(Unit) {
+ searchFocusRequester.requestFocus()
}
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.65f))
- .clickable(
- onClick = onDismiss,
- indication = null,
- interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
- ),
- contentAlignment = Alignment.Center
- ) {
+ GuideModalDialog(onDismiss = onDismiss) {
Surface(
modifier = Modifier
- .fillMaxWidth(0.58f)
- .fillMaxHeight(0.78f),
+ .fillMaxWidth(0.52f)
+ .fillMaxHeight(0.78f)
+ .focusGroup(),
colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
shape = RoundedCornerShape(22.dp)
) {
@@ -1932,7 +2491,7 @@ private fun GuideCategoryPickerDialog(
)
}
GuideShortcutChip(
- label = stringResource(R.string.epg_hide_options),
+ label = stringResource(R.string.settings_cancel),
onClick = onDismiss
)
}
@@ -1941,6 +2500,7 @@ private fun GuideCategoryPickerDialog(
query = query,
onQueryChange = { query = it },
onClear = { query = "" },
+ focusRequester = searchFocusRequester,
contentPadding = PaddingValues(0.dp),
showLabel = false
)
@@ -2012,7 +2572,7 @@ private fun epgCategoryKey(category: Category, index: Int): String {
}
private fun epgChannelKey(channel: Channel, index: Int): String {
- val epgId = channel.epgChannelId?.trim().orEmpty()
+ val epgId = channel.guideLookupKey().orEmpty()
return "channel:${channel.id}:${channel.streamId}:${epgId}:${channel.name.trim()}:$index"
}
@@ -2029,3 +2589,4 @@ private fun dayRelativeLabel(dayStart: Long): String {
}
}
}
+
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 7e673179..7dfa3740 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
@@ -1,7 +1,9 @@
package com.streamvault.app.ui.screens.epg
+import com.streamvault.app.ui.model.guideLookupKey
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferences
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
@@ -12,6 +14,7 @@ import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.data.preferences.PreferencesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
@@ -23,6 +26,7 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
import javax.inject.Inject
data class EpgUiState(
@@ -34,12 +38,13 @@ data class EpgUiState(
val programSearchQuery: String = "",
val showScheduledOnly: Boolean = false,
val selectedChannelMode: GuideChannelMode = GuideChannelMode.ALL,
- val selectedDensity: GuideDensity = GuideDensity.COMFORTABLE,
+ val selectedDensity: GuideDensity = GuideDensity.COMPACT,
val showFavoritesOnly: Boolean = false,
val favoriteChannelIds: Set<Long> = emptySet(),
val channels: List<Channel> = emptyList(),
val programsByChannel: Map<String, List<Program>> = emptyMap(),
- val isLoading: Boolean = true,
+ val isInitialLoading: Boolean = true,
+ val isRefreshing: Boolean = false,
val error: String? = null,
val totalChannelCount: Int = 0,
val channelsWithSchedule: Int = 0,
@@ -73,6 +78,52 @@ private data class GuideChannelSelection(
val favoriteChannelIds: Set<Long>
)
+private data class GuideBaseRequest(
+ val categories: List<Category>,
+ val hiddenCategoryIds: Set<Long>,
+ val resolvedCategoryId: Long,
+ val anchorTime: Long,
+ val favoritesOnly: Boolean,
+ val windowStart: Long,
+ val windowEnd: Long
+)
+
+private data class GuideBaseSnapshot(
+ val providerId: Long,
+ val currentProviderName: String,
+ val providerSourceLabel: String,
+ val providerArchiveSummary: String,
+ val categories: List<Category>,
+ val selectedCategoryId: Long,
+ val showFavoritesOnly: Boolean,
+ val favoriteChannelIds: Set<Long>,
+ val allChannels: List<Channel>,
+ val visibleChannels: List<Channel>,
+ val baseProgramsByChannel: Map<String, List<Program>>,
+ val failedScheduleCount: Int,
+ val lastUpdatedAt: Long,
+ val baseChannelsWithSchedule: Int,
+ val baseGuideStale: Boolean,
+ val guideAnchorTime: Long,
+ val guideWindowStart: Long,
+ val guideWindowEnd: Long
+)
+
+private data class GuideDisplaySnapshot(
+ val channels: List<Channel>,
+ val programsByChannel: Map<String, List<Program>>,
+ val totalChannelCount: Int,
+ val channelsWithSchedule: Int,
+ val isGuideStale: Boolean
+)
+
+private data class GuideBaseComputation(
+ val guideResult: GuideProgramsResult,
+ val now: Long,
+ val channelsWithSchedule: Int,
+ val hasUpcomingData: Boolean
+)
+
@HiltViewModel
class EpgViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
@@ -84,7 +135,7 @@ class EpgViewModel @Inject constructor(
companion object {
const val MAX_CHANNELS = 60
- private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 12
+ private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 24
const val LOOKBACK_MS = 60 * 60 * 1000L
const val LOOKAHEAD_MS = 6 * 60 * 60 * 1000L
const val HALF_HOUR_SHIFT_MS = 30 * 60 * 1000L
@@ -102,14 +153,16 @@ class EpgViewModel @Inject constructor(
private val guideAnchorTime = MutableStateFlow(System.currentTimeMillis())
private val showScheduledOnly = MutableStateFlow(false)
private val selectedChannelMode = MutableStateFlow(GuideChannelMode.ALL)
- private val selectedDensity = MutableStateFlow(GuideDensity.COMFORTABLE)
+ private val selectedDensity = MutableStateFlow(GuideDensity.COMPACT)
private val showFavoritesOnly = MutableStateFlow(false)
private val programSearchQuery = MutableStateFlow("")
private val refreshNonce = MutableStateFlow(0)
+ private val baseGuideSnapshot = MutableStateFlow<GuideBaseSnapshot?>(null)
init {
restoreGuidePreferences()
- observeGuide()
+ observeGuideBase()
+ observeGuidePresentation()
}
fun selectCategory(categoryId: Long) {
@@ -228,10 +281,11 @@ class EpgViewModel @Inject constructor(
}
}
- private fun observeGuide() {
+ private fun observeGuideBase() {
viewModelScope.launch {
providerRepository.getActiveProvider().collectLatest { provider ->
if (provider == null) {
+ baseGuideSnapshot.value = null
_uiState.update {
it.copy(
currentProviderName = null,
@@ -240,8 +294,8 @@ class EpgViewModel @Inject constructor(
categories = emptyList(),
channels = emptyList(),
programsByChannel = emptyMap(),
- programSearchQuery = "",
- isLoading = false,
+ isInitialLoading = false,
+ isRefreshing = false,
error = NO_ACTIVE_PROVIDER,
totalChannelCount = 0,
channelsWithSchedule = 0,
@@ -256,60 +310,48 @@ class EpgViewModel @Inject constructor(
return@collectLatest
}
- channelRepository.getCategories(provider.id).combine(
- combine(
- combine(
- combine(
- selectedCategoryId,
- programSearchQuery,
- guideAnchorTime
- ) { requestedCategoryId, searchQuery, anchorTime ->
- Triple(requestedCategoryId, searchQuery, anchorTime)
- },
- showScheduledOnly,
- selectedChannelMode,
- selectedDensity
- ) { selectionTriple, scheduledOnly, channelMode, density ->
- val (requestedCategoryId, searchQuery, anchorTime) = selectionTriple
- GuideSelectionState(
- requestedCategoryId = requestedCategoryId,
- programSearchQuery = searchQuery,
- anchorTime = anchorTime,
- scheduledOnly = scheduledOnly,
- channelMode = channelMode,
- density = density,
- favoritesOnly = false
- )
- },
- showFavoritesOnly
- ) { selection, favoritesOnly ->
- selection.copy(favoritesOnly = favoritesOnly)
+ channelRepository.getCategories(provider.id)
+ .combine(preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE)) { providerCategories, hiddenCategoryIds ->
+ providerCategories to hiddenCategoryIds
}
- ) { categories, selection ->
- GuideRequest(
- categories = categories,
- requestedCategoryId = selection.requestedCategoryId,
- programSearchQuery = selection.programSearchQuery,
- anchorTime = selection.anchorTime,
- scheduledOnly = selection.scheduledOnly,
- channelMode = selection.channelMode,
- density = selection.density,
- favoritesOnly = selection.favoritesOnly
- )
- }.combine(refreshNonce) { request, _ ->
- request
- }.collectLatest { request ->
+ .combine(preferencesRepository.getCategorySortMode(provider.id, ContentType.LIVE)) { (providerCategories, hiddenCategoryIds), sortMode ->
+ Triple(providerCategories, hiddenCategoryIds, sortMode)
+ }
+ .combine(
+ combine(
+ selectedCategoryId,
+ guideAnchorTime,
+ showFavoritesOnly,
+ refreshNonce
+ ) { requestedCategoryId, anchorTime, favoritesOnly, _ ->
+ Triple(requestedCategoryId, anchorTime, favoritesOnly)
+ }
+ ) { (providerCategories, hiddenCategoryIds, sortMode), selection ->
+ val (requestedCategoryId, anchorTime, favoritesOnly) = selection
+ val visibleProviderCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCategories.filter { it.id != ChannelRepository.ALL_CHANNELS_ID },
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ )
+ val resolvedCategoryId = requestedCategoryId.takeIf { categoryId ->
+ categoryId == ChannelRepository.ALL_CHANNELS_ID || visibleProviderCategories.any { it.id == categoryId }
+ } ?: ChannelRepository.ALL_CHANNELS_ID
+ GuideBaseRequest(
+ categories = visibleProviderCategories,
+ hiddenCategoryIds = hiddenCategoryIds,
+ resolvedCategoryId = resolvedCategoryId,
+ anchorTime = anchorTime,
+ favoritesOnly = favoritesOnly,
+ windowStart = anchorTime - LOOKBACK_MS,
+ windowEnd = anchorTime + LOOKAHEAD_MS
+ )
+ }.collectLatest { request ->
val providerCategories = request.categories
- val requestedCategoryId = request.requestedCategoryId
- val anchorTime = request.anchorTime
val categories = buildList {
add(Category(id = ChannelRepository.ALL_CHANNELS_ID, name = "All Channels"))
- addAll(providerCategories.sortedBy { it.name.lowercase() })
+ addAll(providerCategories)
}
-
- val resolvedCategoryId = requestedCategoryId.takeIf { categoryId ->
- categoryId == ChannelRepository.ALL_CHANNELS_ID || providerCategories.any { it.id == categoryId }
- } ?: ChannelRepository.ALL_CHANNELS_ID
+ val hasVisibleGuide = _uiState.value.channels.isNotEmpty() || _uiState.value.programsByChannel.isNotEmpty()
_uiState.update {
it.copy(
@@ -320,23 +362,20 @@ class EpgViewModel @Inject constructor(
},
providerArchiveSummary = buildProviderArchiveSummary(provider),
categories = categories,
- selectedCategoryId = resolvedCategoryId,
- programSearchQuery = request.programSearchQuery,
- showScheduledOnly = request.scheduledOnly,
- selectedChannelMode = request.channelMode,
- selectedDensity = request.density,
showFavoritesOnly = request.favoritesOnly,
- guideAnchorTime = anchorTime,
- guideWindowStart = anchorTime - LOOKBACK_MS,
- guideWindowEnd = anchorTime + LOOKAHEAD_MS,
- isLoading = true,
+ selectedCategoryId = request.resolvedCategoryId,
+ guideAnchorTime = request.anchorTime,
+ guideWindowStart = request.windowStart,
+ guideWindowEnd = request.windowEnd,
+ isInitialLoading = !hasVisibleGuide,
+ isRefreshing = hasVisibleGuide,
error = null
)
}
combine(
- channelRepository.getChannelsByNumber(provider.id, resolvedCategoryId),
- channelRepository.getChannelsWithoutErrors(provider.id, resolvedCategoryId),
+ channelRepository.getChannelsByNumber(provider.id, request.resolvedCategoryId),
+ channelRepository.getChannelsWithoutErrors(provider.id, request.resolvedCategoryId),
favoriteRepository.getFavorites(ContentType.LIVE)
) { channelsByNumber, healthyChannels, favorites ->
val favoriteIds = favorites.map { it.contentId }.toSet()
@@ -346,71 +385,133 @@ class EpgViewModel @Inject constructor(
} else {
healthyChannels.ifEmpty { channelsByNumber }
}
- if (!request.favoritesOnly) {
- GuideChannelSelection(
- channels = preferredChannels,
- favoriteChannelIds = favoriteIds
+ GuideChannelSelection(
+ channels = preferredChannels.filterNot { channel -> channel.categoryId in request.hiddenCategoryIds },
+ favoriteChannelIds = favoriteIds
+ )
+ }.collectLatest { channelSelection ->
+ val allChannels = channelSelection.channels
+ val visibleChannels = allChannels.take(MAX_CHANNELS)
+ val guideComputation = withContext(Dispatchers.Default) {
+ val loadedGuideResult = loadGuidePrograms(
+ provider = provider,
+ providerId = provider.id,
+ channels = visibleChannels,
+ categoryId = request.resolvedCategoryId,
+ favoritesOnly = request.favoritesOnly,
+ windowStart = request.windowStart,
+ windowEnd = request.windowEnd
)
- } else {
- GuideChannelSelection(
- channels = preferredChannels,
- favoriteChannelIds = favoriteIds
+ val computedNow = System.currentTimeMillis()
+ val computedChannelsWithSchedule = visibleChannels.count { channel ->
+ channel.guideLookupKey()
+ ?.let { lookupKey -> loadedGuideResult.programsByChannel[lookupKey].orEmpty().isNotEmpty() }
+ ?: false
+ }
+ val computedHasUpcomingData = loadedGuideResult.programsByChannel.values.flatten().any { program ->
+ program.endTime > request.windowStart
+ }
+ GuideBaseComputation(
+ guideResult = loadedGuideResult,
+ now = computedNow,
+ channelsWithSchedule = computedChannelsWithSchedule,
+ hasUpcomingData = computedHasUpcomingData
)
}
- }.collectLatest { channelSelection ->
- val visibleChannels = channelSelection.channels.take(MAX_CHANNELS)
- val windowStart = anchorTime - LOOKBACK_MS
- val windowEnd = anchorTime + LOOKAHEAD_MS
- val guideResult = loadGuidePrograms(
- provider = provider,
+ baseGuideSnapshot.value = GuideBaseSnapshot(
providerId = provider.id,
- channels = visibleChannels,
- categoryId = resolvedCategoryId,
- favoritesOnly = request.favoritesOnly,
- searchQuery = request.programSearchQuery,
- windowStart = windowStart,
- windowEnd = windowEnd
+ currentProviderName = provider.name,
+ providerSourceLabel = when (provider.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
+ com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
+ },
+ providerArchiveSummary = buildProviderArchiveSummary(provider),
+ categories = categories,
+ selectedCategoryId = request.resolvedCategoryId,
+ showFavoritesOnly = request.favoritesOnly,
+ favoriteChannelIds = channelSelection.favoriteChannelIds,
+ allChannels = allChannels,
+ visibleChannels = visibleChannels,
+ baseProgramsByChannel = guideComputation.guideResult.programsByChannel,
+ failedScheduleCount = guideComputation.guideResult.failedCount,
+ lastUpdatedAt = guideComputation.now,
+ baseChannelsWithSchedule = guideComputation.channelsWithSchedule,
+ baseGuideStale = visibleChannels.isNotEmpty() && (guideComputation.channelsWithSchedule == 0 || !guideComputation.hasUpcomingData),
+ guideAnchorTime = request.anchorTime,
+ guideWindowStart = request.windowStart,
+ guideWindowEnd = request.windowEnd
)
- val now = System.currentTimeMillis()
- val channelsWithSchedule = guideResult.programsByChannel.count { it.value.isNotEmpty() }
- val hasUpcomingData = guideResult.programsByChannel.values.flatten().any { program ->
- program.endTime > windowStart
- }
- val displayChannels = visibleChannels.filter { channel ->
- val programs = channel.epgChannelId?.let { epgId ->
- guideResult.programsByChannel[epgId].orEmpty()
- }.orEmpty()
- val matchesScheduled = !request.scheduledOnly || programs.isNotEmpty()
- val matchesMode = when (request.channelMode) {
- GuideChannelMode.ALL -> true
- GuideChannelMode.ANCHORED -> programs.any { program ->
- request.anchorTime in program.startTime until program.endTime
- }
- GuideChannelMode.ARCHIVE_READY -> {
- channel.catchUpSupported || programs.any { it.hasArchive }
- }
- }
- matchesScheduled && matchesMode
- }
+ }
+ }
+ }
+ }
+ }
- _uiState.update {
- it.copy(
- favoriteChannelIds = channelSelection.favoriteChannelIds,
- channels = displayChannels,
- programsByChannel = guideResult.programsByChannel,
- isLoading = false,
- error = null,
- totalChannelCount = channelSelection.channels.size,
- channelsWithSchedule = channelsWithSchedule,
- failedScheduleCount = guideResult.failedCount,
- lastUpdatedAt = now,
- isGuideStale = visibleChannels.isNotEmpty() && (channelsWithSchedule == 0 || !hasUpcomingData),
- guideAnchorTime = request.anchorTime,
- guideWindowStart = windowStart,
- guideWindowEnd = windowEnd
- )
- }
+ private fun observeGuidePresentation() {
+ viewModelScope.launch {
+ combine(
+ baseGuideSnapshot,
+ programSearchQuery,
+ showScheduledOnly,
+ selectedChannelMode,
+ selectedDensity
+ ) { baseSnapshot, searchQuery, scheduledOnly, channelMode, density ->
+ GuidePresentationState(
+ baseSnapshot = baseSnapshot,
+ searchQuery = searchQuery.trim(),
+ scheduledOnly = scheduledOnly,
+ channelMode = channelMode,
+ density = density
+ )
+ }.collectLatest { presentation ->
+ val baseSnapshot = presentation.baseSnapshot ?: run {
+ _uiState.update {
+ it.copy(
+ programSearchQuery = presentation.searchQuery,
+ showScheduledOnly = presentation.scheduledOnly,
+ selectedChannelMode = presentation.channelMode,
+ selectedDensity = presentation.density
+ )
}
+ return@collectLatest
+ }
+
+ val displaySnapshot = withContext(Dispatchers.Default) {
+ buildGuideDisplaySnapshot(
+ baseSnapshot = baseSnapshot,
+ searchQuery = presentation.searchQuery,
+ scheduledOnly = presentation.scheduledOnly,
+ channelMode = presentation.channelMode
+ )
+ }
+
+ _uiState.update {
+ it.copy(
+ currentProviderName = baseSnapshot.currentProviderName,
+ providerSourceLabel = baseSnapshot.providerSourceLabel,
+ providerArchiveSummary = baseSnapshot.providerArchiveSummary,
+ categories = baseSnapshot.categories,
+ selectedCategoryId = baseSnapshot.selectedCategoryId,
+ programSearchQuery = presentation.searchQuery,
+ showScheduledOnly = presentation.scheduledOnly,
+ selectedChannelMode = presentation.channelMode,
+ selectedDensity = presentation.density,
+ showFavoritesOnly = baseSnapshot.showFavoritesOnly,
+ favoriteChannelIds = baseSnapshot.favoriteChannelIds,
+ channels = displaySnapshot.channels,
+ programsByChannel = displaySnapshot.programsByChannel,
+ isInitialLoading = false,
+ isRefreshing = false,
+ error = null,
+ totalChannelCount = displaySnapshot.totalChannelCount,
+ channelsWithSchedule = displaySnapshot.channelsWithSchedule,
+ failedScheduleCount = baseSnapshot.failedScheduleCount,
+ lastUpdatedAt = baseSnapshot.lastUpdatedAt,
+ isGuideStale = displaySnapshot.isGuideStale,
+ guideAnchorTime = baseSnapshot.guideAnchorTime,
+ guideWindowStart = baseSnapshot.guideWindowStart,
+ guideWindowEnd = baseSnapshot.guideWindowEnd
+ )
}
}
}
@@ -464,64 +565,53 @@ class EpgViewModel @Inject constructor(
channels: List<Channel>,
categoryId: Long,
favoritesOnly: Boolean,
- searchQuery: String,
windowStart: Long,
windowEnd: Long
): GuideProgramsResult {
- if (channels.isEmpty()) {
- return GuideProgramsResult(emptyMap(), failedCount = 0)
- }
+ return withContext(Dispatchers.IO) {
+ if (channels.isEmpty()) {
+ return@withContext GuideProgramsResult(emptyMap(), failedCount = 0)
+ }
- val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()
- val programsByChannel = runCatching {
- val allowedIds = epgIds.toSet()
- when {
- searchQuery.trim().length >= 2 -> {
- epgRepository.searchPrograms(
- providerId = providerId,
- query = searchQuery,
- startTime = windowStart,
- endTime = windowEnd,
- categoryId = categoryId.takeUnless { it == ChannelRepository.ALL_CHANNELS_ID },
- limit = maxOf(120, channels.size * 12)
- ).first().filter { it.channelId in allowedIds }.groupBy { it.channelId }
- }
+ val guideKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()
+ val xmltvKeys = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf { value -> value.isNotEmpty() } }.distinct()
+ val programsByChannel = runCatching {
+ val allowedIds = guideKeys.toSet()
+ when {
+ categoryId != ChannelRepository.ALL_CHANNELS_ID && !favoritesOnly -> {
+ epgRepository.getProgramsByCategory(
+ providerId = providerId,
+ categoryId = categoryId,
+ startTime = windowStart,
+ endTime = windowEnd
+ ).first().filter { it.channelId in allowedIds }.groupBy { it.channelId }
+ }
- categoryId != ChannelRepository.ALL_CHANNELS_ID && !favoritesOnly -> {
- epgRepository.getProgramsByCategory(
- providerId = providerId,
- categoryId = categoryId,
- startTime = windowStart,
- endTime = windowEnd
- ).first().filter { it.channelId in allowedIds }.groupBy { it.channelId }
+ else -> epgRepository.getProgramsForChannels(providerId, xmltvKeys, windowStart, windowEnd).first()
}
-
- else -> epgRepository.getProgramsForChannels(providerId, epgIds, windowStart, windowEnd).first()
- }
- }.getOrElse { emptyMap() }
-
- val fallbackProgramsByChannel = fetchXtreamGuideFallback(
- provider = provider,
- providerId = providerId,
- channels = channels,
- searchQuery = searchQuery,
- existingProgramsByChannel = programsByChannel,
- windowStart = windowStart,
- windowEnd = windowEnd
- )
- val mergedProgramsByChannel = programsByChannel + fallbackProgramsByChannel
-
- return GuideProgramsResult(
- programsByChannel = mergedProgramsByChannel,
- failedCount = epgIds.count { epgId -> mergedProgramsByChannel[epgId].isNullOrEmpty() }
- )
+ }.getOrElse { emptyMap() }
+
+ val fallbackProgramsByChannel = fetchXtreamGuideFallback(
+ provider = provider,
+ providerId = providerId,
+ channels = channels,
+ existingProgramsByChannel = programsByChannel,
+ windowStart = windowStart,
+ windowEnd = windowEnd
+ )
+ val mergedProgramsByChannel = programsByChannel + fallbackProgramsByChannel
+
+ GuideProgramsResult(
+ programsByChannel = mergedProgramsByChannel,
+ failedCount = guideKeys.count { lookupKey -> mergedProgramsByChannel[lookupKey].isNullOrEmpty() }
+ )
+ }
}
private suspend fun fetchXtreamGuideFallback(
provider: com.streamvault.domain.model.Provider,
providerId: Long,
channels: List<Channel>,
- searchQuery: String,
existingProgramsByChannel: Map<String, List<Program>>,
windowStart: Long,
windowEnd: Long
@@ -529,14 +619,12 @@ class EpgViewModel @Inject constructor(
if (provider.type != com.streamvault.domain.model.ProviderType.XTREAM_CODES) {
return emptyMap()
}
- if (searchQuery.isNotBlank()) {
- return emptyMap()
- }
val missingChannels = channels.filter { channel ->
- !channel.epgChannelId.isNullOrBlank() &&
+ val lookupKey = channel.guideLookupKey()
+ lookupKey != null &&
channel.streamId > 0L &&
- existingProgramsByChannel[channel.epgChannelId].isNullOrEmpty()
+ existingProgramsByChannel[lookupKey].isNullOrEmpty()
}
if (missingChannels.isEmpty()) {
return emptyMap()
@@ -557,8 +645,8 @@ class EpgViewModel @Inject constructor(
.orEmpty()
.filter { program -> program.endTime > windowStart && program.startTime < windowEnd }
.sortedBy { program -> program.startTime }
- val epgId = channel.epgChannelId ?: return@async null
- if (programs.isEmpty()) null else epgId to programs
+ val lookupKey = channel.guideLookupKey() ?: return@async null
+ if (programs.isEmpty()) null else lookupKey to programs
}
}
.awaitAll()
@@ -567,25 +655,105 @@ class EpgViewModel @Inject constructor(
}
}
-}
+ private suspend fun buildGuideDisplaySnapshot(
+ baseSnapshot: GuideBaseSnapshot,
+ searchQuery: String,
+ scheduledOnly: Boolean,
+ channelMode: GuideChannelMode
+ ): GuideDisplaySnapshot {
+ val normalizedQuery = searchQuery.trim()
+ val (candidateChannels, candidateProgramsByChannel) = if (normalizedQuery.isBlank()) {
+ baseSnapshot.visibleChannels to baseSnapshot.baseProgramsByChannel
+ } else {
+ buildSearchGuideSnapshot(baseSnapshot, normalizedQuery)
+ }
-private data class GuideRequest(
- val categories: List<Category>,
- val requestedCategoryId: Long,
- val programSearchQuery: String,
- val anchorTime: Long,
- val scheduledOnly: Boolean,
- val channelMode: GuideChannelMode,
- val density: GuideDensity,
- val favoritesOnly: Boolean
-)
+ val displayChannels = candidateChannels.filter { channel ->
+ val programs = channel.guideLookupKey()
+ ?.let { lookupKey -> candidateProgramsByChannel[lookupKey].orEmpty() }
+ .orEmpty()
+ val matchesScheduled = !scheduledOnly || programs.isNotEmpty()
+ val matchesMode = when (channelMode) {
+ GuideChannelMode.ALL -> true
+ GuideChannelMode.ANCHORED -> programs.any { program ->
+ baseSnapshot.guideAnchorTime in program.startTime until program.endTime
+ }
+ GuideChannelMode.ARCHIVE_READY -> channel.catchUpSupported || programs.any { it.hasArchive }
+ }
+ matchesScheduled && matchesMode
+ }
+ val channelsWithSchedule = candidateChannels.count { channel ->
+ channel.guideLookupKey()
+ ?.let { lookupKey -> candidateProgramsByChannel[lookupKey].orEmpty().isNotEmpty() }
+ ?: false
+ }
+ val hasUpcomingData = candidateProgramsByChannel.values.flatten().any { program ->
+ program.endTime > baseSnapshot.guideWindowStart
+ }
-private data class GuideSelectionState(
- val requestedCategoryId: Long,
- val programSearchQuery: String,
- val anchorTime: Long,
+ return GuideDisplaySnapshot(
+ channels = displayChannels,
+ programsByChannel = candidateProgramsByChannel,
+ totalChannelCount = candidateChannels.size,
+ channelsWithSchedule = channelsWithSchedule,
+ isGuideStale = candidateChannels.isNotEmpty() && (channelsWithSchedule == 0 || !hasUpcomingData)
+ )
+ }
+
+ private suspend fun buildSearchGuideSnapshot(
+ baseSnapshot: GuideBaseSnapshot,
+ searchQuery: String
+ ): Pair<List<Channel>, Map<String, List<Program>>> {
+ val localMatches = baseSnapshot.baseProgramsByChannel
+ .mapValues { (_, programs) ->
+ programs.filter { program ->
+ program.title.contains(searchQuery, ignoreCase = true) ||
+ program.description.contains(searchQuery, ignoreCase = true)
+ }
+ }
+ .filterValues { it.isNotEmpty() }
+
+ val searchedPrograms = runCatching {
+ epgRepository.searchPrograms(
+ providerId = baseSnapshot.providerId,
+ query = searchQuery,
+ startTime = baseSnapshot.guideWindowStart,
+ endTime = baseSnapshot.guideWindowEnd,
+ categoryId = baseSnapshot.selectedCategoryId.takeUnless { it == ChannelRepository.ALL_CHANNELS_ID },
+ limit = maxOf(120, baseSnapshot.allChannels.size * 6)
+ ).first()
+ }.getOrElse { emptyList() }
+
+ val dbMatches = searchedPrograms
+ .groupBy { it.channelId }
+ .mapValues { (_, programs) ->
+ programs
+ .distinctBy { Triple(it.startTime, it.endTime, it.title) }
+ .sortedBy { it.startTime }
+ }
+
+ val mergedPrograms = (localMatches.keys + dbMatches.keys)
+ .associateWith { key ->
+ (localMatches[key].orEmpty() + dbMatches[key].orEmpty())
+ .distinctBy { Triple(it.startTime, it.endTime, it.title) }
+ .sortedBy { it.startTime }
+ }
+ .filterValues { it.isNotEmpty() }
+
+ val matchedChannels = baseSnapshot.allChannels.filter { channel ->
+ channel.guideLookupKey()?.let(mergedPrograms::containsKey) == true
+ }.take(MAX_CHANNELS)
+
+ val matchedChannelKeys = matchedChannels.mapNotNull(Channel::guideLookupKey).toSet()
+ return matchedChannels to mergedPrograms.filterKeys { it in matchedChannelKeys }
+ }
+
+}
+
+private data class GuidePresentationState(
+ val baseSnapshot: GuideBaseSnapshot?,
+ val searchQuery: String,
val scheduledOnly: Boolean,
val channelMode: GuideChannelMode,
- val density: GuideDensity,
- val favoritesOnly: Boolean
+ val density: GuideDensity
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
index 9426d7e3..65ed8476 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
@@ -69,6 +69,7 @@ import com.streamvault.app.ui.screens.multiview.MultiViewViewModel
import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
import com.streamvault.app.navigation.Routes
import com.streamvault.domain.model.VirtualCategoryIds
+import com.streamvault.domain.repository.ChannelRepository
import androidx.compose.ui.viewinterop.AndroidView
import com.streamvault.player.PlayerSurfaceResizeMode
import java.text.SimpleDateFormat
@@ -276,6 +277,9 @@ fun HomeScreen(
viewModel.dismissCategoryOptions()
}
},
+ onHide = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {
+ { viewModel.hideCategory(category) }
+ } else null,
onRename = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {
{ viewModel.requestRenameGroup(category) }
} else null,
@@ -622,10 +626,18 @@ fun HomeScreen(
val preferredChannelId = lastFocusedChannelId
?.takeIf { channelId -> uiState.filteredChannels.any { it.id == channelId } }
?: uiState.filteredChannels.first().id
- val focused = runCatching {
- channelFocusRequesters[preferredChannelId]?.requestFocus()
- }.isSuccess
- if (!focused) runCatching { channelSearchFocusRequester.requestFocus() }
+ lastFocusedChannelId = preferredChannelId
+ preferredRestoreTarget = FocusRestoreTarget.CHANNEL.name
+ shouldRestoreChannelFocus = true
+ scope.launch {
+ kotlinx.coroutines.delay(60)
+ val focused = runCatching {
+ channelFocusRequesters[preferredChannelId]?.requestFocus()
+ }.getOrNull() != null
+ if (!focused) {
+ shouldRestoreChannelFocus = true
+ }
+ }
} else {
runCatching { channelSearchFocusRequester.requestFocus() }
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
index 760560a6..2bbf0737 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
@@ -4,11 +4,14 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.app.di.AuxiliaryPlayerEngine
import com.streamvault.app.tvinput.TvInputChannelSyncManager
+import com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferences
+import com.streamvault.app.ui.model.guideLookupKey
import com.streamvault.app.ui.model.LiveTvChannelMode
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.sync.SyncManager
import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.PlaybackHistory
@@ -119,7 +122,7 @@ class HomeViewModel @Inject constructor(
}.collectLatest { (channels, favorites, epgProgramMap) ->
val favoriteIds = favorites.map { it.contentId }.toSet()
val markedChannels = channels.map { channel ->
- val program = channel.epgChannelId?.let { epgId -> epgProgramMap[epgId] }
+ val program = channel.guideLookupKey()?.let { lookupKey -> epgProgramMap[lookupKey] }
if (favoriteIds.contains(channel.id)) {
channel.copy(isFavorite = true, currentProgram = program)
} else {
@@ -232,8 +235,16 @@ class HomeViewModel @Inject constructor(
channelRepository.getCategories(providerId),
getCustomCategories(),
preferencesRepository.defaultCategoryId,
- preferencesRepository.getLastLiveCategoryId(providerId)
- ) { providerCats, customCats, defaultId, lastVisitedCategoryId ->
+ preferencesRepository.getLastLiveCategoryId(providerId),
+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),
+ preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE)
+ ) { values ->
+ val providerCats = values[0] as List<Category>
+ val customCats = values[1] as List<Category>
+ val defaultId = values[2] as Long?
+ val lastVisitedCategoryId = values[3] as Long?
+ val hiddenCategoryIds = values[4] as Set<Long>
+ val sortMode = values[5] as CategorySortMode
val recentCategory = Category(
id = VirtualCategoryIds.RECENT,
name = "Recent",
@@ -241,6 +252,19 @@ class HomeViewModel @Inject constructor(
isVirtual = true,
count = _uiState.value.recentChannels.size
)
+ val allChannelsCategory = providerCats.firstOrNull { it.id == ChannelRepository.ALL_CHANNELS_ID }
+ ?.copy(count = providerCats.filter { it.id != ChannelRepository.ALL_CHANNELS_ID && it.id !in hiddenCategoryIds }.sumOf(Category::count))
+ ?: Category(
+ id = ChannelRepository.ALL_CHANNELS_ID,
+ name = "All Channels",
+ type = ContentType.LIVE,
+ count = providerCats.filter { it.id != ChannelRepository.ALL_CHANNELS_ID && it.id !in hiddenCategoryIds }.sumOf(Category::count)
+ )
+ val visibleProviderCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCats.filter { it.id != ChannelRepository.ALL_CHANNELS_ID },
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ )
val orderedCategories = buildList {
val favoritesCategory = customCats.find { it.id == VirtualCategoryIds.FAVORITES }
@@ -249,7 +273,8 @@ class HomeViewModel @Inject constructor(
}
add(recentCategory)
addAll(customCats.filter { it.id != VirtualCategoryIds.FAVORITES })
- addAll(providerCats)
+ add(allChannelsCategory)
+ addAll(visibleProviderCategories)
}
CategorySelectionContext(
@@ -408,7 +433,12 @@ class HomeViewModel @Inject constructor(
}
}
- channelsFlow.collect { channels ->
+ combine(
+ channelsFlow,
+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE)
+ ) { channels, hiddenCategoryIds ->
+ channels.filterNot { channel -> channel.categoryId in hiddenCategoryIds }
+ }.collect { channels ->
val numberedChannels = channels.mapIndexed { index, channel ->
channel.copy(number = index + 1)
}
@@ -544,11 +574,12 @@ class HomeViewModel @Inject constructor(
private fun fetchEpgForChannels(providerId: Long, channels: List<Channel>) {
epgJob?.cancel()
- val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()
+ val lookupKeys = channels.mapNotNull(Channel::guideLookupKey).distinct()
+ val xmltvKeys = channels.mapNotNull { it.epgChannelId?.trim()?.takeIf { value -> value.isNotEmpty() } }.distinct()
epgJob = viewModelScope.launch {
- val freshProgramMap = if (epgIds.isNotEmpty()) {
- epgRepository.getNowPlayingForChannelsSnapshot(providerId, epgIds)
+ val freshProgramMap = if (xmltvKeys.isNotEmpty()) {
+ epgRepository.getNowPlayingForChannelsSnapshot(providerId, xmltvKeys)
.mapNotNull { (epgId, program) -> program?.let { epgId to it } }
.toMap()
} else {
@@ -561,7 +592,7 @@ class HomeViewModel @Inject constructor(
)
val mergedProgramMap = freshProgramMap + fallbackProgramMap
- val channelEpgIds = channels.mapNotNull { it.epgChannelId }.toSet()
+ val channelEpgIds = lookupKeys.toSet()
_epgProgramMap.update { existing ->
buildMap {
putAll(existing)
@@ -587,9 +618,10 @@ class HomeViewModel @Inject constructor(
}
val missingChannels = channels.filter { channel ->
- !channel.epgChannelId.isNullOrBlank() &&
+ val lookupKey = channel.guideLookupKey()
+ lookupKey != null &&
channel.streamId > 0L &&
- !existingPrograms.containsKey(channel.epgChannelId)
+ !existingPrograms.containsKey(lookupKey)
}
if (missingChannels.isEmpty()) {
return emptyMap()
@@ -610,8 +642,8 @@ class HomeViewModel @Inject constructor(
val programs = (result as? Result.Success)?.data.orEmpty()
val currentProgram = programs.firstOrNull { it.startTime <= now && it.endTime > now }
?: programs.firstOrNull()
- val epgId = channel.epgChannelId ?: return@async null
- currentProgram?.let { epgId to it }
+ val lookupKey = channel.guideLookupKey() ?: return@async null
+ currentProgram?.let { lookupKey to it }
}
}
.awaitAll()
@@ -922,6 +954,30 @@ class HomeViewModel @Inject constructor(
_uiState.update { it.copy(selectedCategoryForOptions = null) }
}
+ fun hideCategory(category: Category) {
+ if (category.isVirtual || category.id == ChannelRepository.ALL_CHANNELS_ID) return
+ val providerId = _uiState.value.provider?.id ?: return
+ viewModelScope.launch {
+ preferencesRepository.setCategoryHidden(
+ providerId = providerId,
+ type = ContentType.LIVE,
+ categoryId = category.id,
+ hidden = true
+ )
+ if (_uiState.value.selectedCategory?.id == category.id) {
+ val fallbackCategory = _uiState.value.categories.firstOrNull { it.id != category.id }
+ if (fallbackCategory != null) {
+ selectCategory(fallbackCategory)
+ } else {
+ dismissCategoryOptions()
+ }
+ } else {
+ dismissCategoryOptions()
+ }
+ _uiState.update { it.copy(userMessage = "Hidden category '${category.name}'") }
+ }
+ }
+
fun enterChannelReorderMode(category: Category) {
dismissCategoryOptions()
viewModelScope.launch {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt
index 9b86bd01..eddbf409 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt
@@ -1,5 +1,7 @@
package com.streamvault.app.ui.screens.movies
+import android.content.Intent
+import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -29,6 +31,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.compose.ui.platform.LocalContext
import androidx.tv.material3.Border
import androidx.tv.material3.Button
import androidx.tv.material3.ButtonDefaults
@@ -81,6 +84,7 @@ fun MovieDetailScreen(
else -> {
MovieDetailContent(
movie = movie,
+ hasResume = uiState.hasResume,
onPlay = { onPlay(movie) },
onBack = onBack
)
@@ -91,9 +95,11 @@ fun MovieDetailScreen(
@Composable
private fun MovieDetailContent(
movie: Movie,
+ hasResume: Boolean,
onPlay: () -> Unit,
onBack: () -> Unit
) {
+ val context = LocalContext.current
val isTelevisionDevice = rememberIsTelevisionDevice()
BoxWithConstraints(
modifier = Modifier
@@ -158,7 +164,16 @@ private fun MovieDetailContent(
if (compactLayout) {
Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
MoviePoster(movie = movie, posterWidth = posterWidth)
- MovieDetailHeroText(movie = movie, onPlay = onPlay)
+ MovieDetailHeroText(
+ movie = movie,
+ hasResume = hasResume,
+ onPlay = onPlay,
+ onPlayTrailer = {
+ resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->
+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl)))
+ }
+ }
+ )
}
} else {
Row(
@@ -168,7 +183,13 @@ private fun MovieDetailContent(
MoviePoster(movie = movie, posterWidth = posterWidth)
MovieDetailHeroText(
movie = movie,
+ hasResume = hasResume,
onPlay = onPlay,
+ onPlayTrailer = {
+ resolveTrailerUrl(movie.youtubeTrailer)?.let { trailerUrl ->
+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl)))
+ }
+ },
modifier = Modifier.fillMaxWidth()
)
}
@@ -202,9 +223,12 @@ private fun MoviePoster(
@Composable
private fun MovieDetailHeroText(
movie: Movie,
+ hasResume: Boolean,
onPlay: () -> Unit,
+ onPlayTrailer: () -> Unit,
modifier: Modifier = Modifier
) {
+ val hasTrailer = !movie.youtubeTrailer.isNullOrBlank()
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(18.dp)
@@ -241,14 +265,31 @@ private fun MovieDetailHeroText(
MovieFactGrid(movie = movie)
- Button(
- onClick = onPlay,
- colors = ButtonDefaults.colors(
- containerColor = AppColors.Brand,
- contentColor = Color.White
- )
- ) {
- Text(stringResource(R.string.movie_detail_play))
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
+ Button(
+ onClick = onPlay,
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.Brand,
+ contentColor = Color.White
+ )
+ ) {
+ Text(
+ stringResource(
+ if (hasResume) R.string.player_resume else R.string.movie_detail_play
+ )
+ )
+ }
+ if (hasTrailer) {
+ Button(
+ onClick = onPlayTrailer,
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.SurfaceEmphasis,
+ contentColor = AppColors.TextPrimary
+ )
+ ) {
+ Text(stringResource(R.string.movie_detail_trailer))
+ }
+ }
}
Text(
@@ -262,6 +303,17 @@ private fun MovieDetailHeroText(
}
}
+private fun resolveTrailerUrl(rawTrailer: String?): String? {
+ val trailer = rawTrailer?.trim().orEmpty()
+ if (trailer.isBlank()) return null
+ return when {
+ trailer.startsWith("http://", ignoreCase = true) || trailer.startsWith("https://", ignoreCase = true) -> trailer
+ trailer.startsWith("youtu.be/", ignoreCase = true) -> "https://$trailer"
+ trailer.startsWith("www.youtube.com/", ignoreCase = true) || trailer.startsWith("youtube.com/", ignoreCase = true) -> "https://$trailer"
+ else -> "https://www.youtube.com/watch?v=$trailer"
+ }
+}
+
@Composable
private fun MovieFactGrid(movie: Movie) {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt
index c5a7bb1f..8527ab25 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt
@@ -3,9 +3,12 @@ package com.streamvault.app.ui.screens.movies
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.util.isPlaybackComplete
import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.ProviderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@@ -20,10 +23,14 @@ import kotlinx.coroutines.launch
class MovieDetailViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val movieRepository: MovieRepository,
- private val providerRepository: ProviderRepository
+ private val providerRepository: ProviderRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository
) : ViewModel() {
- private val movieId: Long = checkNotNull(savedStateHandle.get<String>("movieId")?.toLongOrNull())
+ private val movieId: Long = checkNotNull(
+ savedStateHandle.get<Long>("movieId")
+ ?: savedStateHandle.get<String>("movieId")?.toLongOrNull()
+ )
private val _uiState = MutableStateFlow(MovieDetailUiState())
val uiState: StateFlow<MovieDetailUiState> = _uiState.asStateFlow()
@@ -42,9 +49,26 @@ class MovieDetailViewModel @Inject constructor(
return@launch
}
+ val playbackHistory = playbackHistoryRepository.getPlaybackHistory(
+ contentId = movieId,
+ contentType = ContentType.MOVIE,
+ providerId = provider.id
+ )
+
when (val result = movieRepository.getMovieDetails(provider.id, movieId)) {
is Result.Success -> _uiState.update {
+ val movie = result.data
+ val movieDurationMs = movie.durationSeconds.takeIf { it > 0 }?.times(1000L) ?: 0L
+ val resumePositionMs = playbackHistory?.resumePositionMs ?: movie.watchProgress
+ val hasResume = resumePositionMs > 5000L && !isPlaybackComplete(
+ progressMs = resumePositionMs,
+ totalDurationMs = playbackHistory?.totalDurationMs?.takeIf { it > 0L } ?: movieDurationMs
+ )
it.copy(isLoading = false, movie = result.data, error = null)
+ .copy(
+ hasResume = hasResume,
+ resumePositionMs = if (hasResume) resumePositionMs else 0L
+ )
}
is Result.Error -> _uiState.update {
it.copy(isLoading = false, error = result.message)
@@ -60,5 +84,7 @@ class MovieDetailViewModel @Inject constructor(
data class MovieDetailUiState(
val isLoading: Boolean = false,
val movie: Movie? = null,
- val error: String? = null
+ val error: String? = null,
+ val hasResume: Boolean = false,
+ val resumePositionMs: Long = 0L
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
index e782d692..dc7f3c51 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
@@ -12,6 +12,7 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.text.BasicTextField
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@@ -72,6 +73,7 @@ import com.streamvault.app.ui.components.shell.VodActionChip
import com.streamvault.app.ui.components.shell.VodActionChipRow
import com.streamvault.app.ui.components.shell.VodCategoryOption
import com.streamvault.app.ui.components.shell.VodCategoryPickerDialog
+import com.streamvault.app.ui.components.shell.VodBrowseOptionsDialog
import com.streamvault.app.ui.components.shell.VodHeroStrip
import com.streamvault.app.ui.components.shell.VodSectionHeader
import com.streamvault.app.ui.screens.vod.HandleVodUserMessage
@@ -183,6 +185,7 @@ fun MoviesScreen(
showPinDialog = true
},
onShowDialog = viewModel::onShowDialog,
+ onShowCategoryOptions = viewModel::showCategoryOptions,
onSelectCategory = viewModel::selectCategory,
onSelectFullLibraryBrowse = viewModel::selectFullLibraryBrowse,
onOpenContinueWatching = {
@@ -235,6 +238,9 @@ fun MoviesScreen(
com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog(
category = category,
onDismissRequest = { viewModel.dismissCategoryOptions() },
+ onHide = if (!category.isVirtual) {
+ { viewModel.hideCategory(category) }
+ } else null,
onRename = if (category.isVirtual && category.id != VodBrowseDefaults.FAVORITES_SENTINEL_ID) {
{ viewModel.requestRenameGroup(category) }
} else null,
@@ -279,6 +285,7 @@ private fun MoviesVodContent(
onMovieClick: (Movie) -> Unit,
onProtectedMovieClick: (Movie) -> Unit,
onShowDialog: (Movie) -> Unit,
+ onShowCategoryOptions: (String) -> Unit,
onSelectCategory: (String?) -> Unit,
onSelectFullLibraryBrowse: () -> Unit,
onOpenContinueWatching: () -> Unit,
@@ -308,10 +315,25 @@ private fun MoviesVodContent(
val heroMovie = freshMovies.firstOrNull() ?: topRatedMovies.firstOrNull() ?: favoriteMovies.firstOrNull()
val categoryOptions = remember(uiState.categoryNames, uiState.categoryCounts) {
uiState.categoryNames.map { name ->
+ val matchedCategory = uiState.providerCategories.firstOrNull { it.name == name }
+ ?: uiState.categories.firstOrNull { it.name == name }
+ ?: if (name == uiState.favoriteCategoryName) {
+ com.streamvault.domain.model.Category(
+ id = VodBrowseDefaults.FAVORITES_SENTINEL_ID,
+ name = uiState.favoriteCategoryName,
+ type = com.streamvault.domain.model.ContentType.MOVIE,
+ isVirtual = true
+ )
+ } else {
+ null
+ }
VodCategoryOption(
name = name,
count = uiState.categoryCounts[name] ?: 0,
- onClick = { onSelectCategory(name) }
+ onClick = { onSelectCategory(name) },
+ onLongClick = matchedCategory?.let { category ->
+ { onShowCategoryOptions(category.name) }
+ }
)
}
}
@@ -431,40 +453,31 @@ private fun MoviesVodContent(
}
if (favoriteMovies.isNotEmpty()) {
- item("favorites_header") {
- VodSectionHeader(
- title = stringResource(R.string.favorites_title),
- onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) }
- )
- }
item("favorites_row") {
- LazyRow(
- contentPadding = PaddingValues(horizontal = 20.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- items(favoriteMovies, key = { it.id }) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
- MovieCard(
- movie = movie,
- isLocked = isLocked,
- onClick = {
- if (isLocked) onProtectedMovieClick(movie) else onMovieClick(movie)
- },
- onLongClick = { onShowDialog(movie) },
- modifier = Modifier.width(favoriteCardWidth)
- )
- }
+ CategoryRow(
+ title = stringResource(R.string.favorites_title),
+ items = favoriteMovies,
+ onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) },
+ keySelector = { it.id }
+ ) { movie ->
+ val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ MovieCard(
+ movie = movie,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) onProtectedMovieClick(movie) else onMovieClick(movie)
+ },
+ onLongClick = { onShowDialog(movie) },
+ modifier = Modifier.width(favoriteCardWidth)
+ )
}
}
}
if (freshMovies.isNotEmpty()) {
- item("fresh_header") {
- VodSectionHeader(title = stringResource(R.string.library_lens_fresh_movies))
- }
item("fresh_row") {
CategoryRow(
- title = "",
+ title = stringResource(R.string.library_lens_fresh_movies),
items = freshMovies,
onSeeAll = null,
keySelector = { it.id }
@@ -481,12 +494,9 @@ private fun MoviesVodContent(
}
if (topRatedMovies.isNotEmpty()) {
- item("top_header") {
- VodSectionHeader(title = stringResource(R.string.library_lens_top_rated))
- }
item("top_row") {
CategoryRow(
- title = "",
+ title = stringResource(R.string.library_lens_top_rated),
items = topRatedMovies,
onSeeAll = null,
keySelector = { it.id }
@@ -508,14 +518,10 @@ private fun MoviesVodContent(
}.take(8),
key = { it.key }
) { (categoryName, movies) ->
- VodSectionHeader(
- title = categoryName,
- onSeeAll = { onSelectCategory(categoryName) }
- )
CategoryRow(
- title = "",
+ title = categoryName,
items = movies,
- onSeeAll = null,
+ onSeeAll = { onSelectCategory(categoryName) },
keySelector = { it.id }
) { movie ->
val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
@@ -536,6 +542,27 @@ private fun MoviesVodContent(
if (uiState.isReorderMode) uiState.filteredMovies else baseMovies
}
var draggingMovie by remember { mutableStateOf<Movie?>(null) }
+ var showBrowseOptions by rememberSaveable(uiState.selectedCategory) { mutableStateOf(false) }
+ var showSearchBar by rememberSaveable(uiState.selectedCategory) { mutableStateOf(searchQuery.isNotBlank()) }
+
+ if (showBrowseOptions) {
+ VodBrowseOptionsDialog(
+ title = stringResource(R.string.nav_movies),
+ filterTitle = stringResource(R.string.library_filter_title),
+ filterChips = movieFilterChips(),
+ selectedFilterKey = selectedFilterType.name,
+ onFilterSelected = { key ->
+ LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
+ },
+ sortTitle = stringResource(R.string.library_sort_title),
+ sortChips = movieSortChips(),
+ selectedSortKey = selectedSortBy.name,
+ onSortSelected = { key ->
+ LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
+ },
+ onDismiss = { showBrowseOptions = false }
+ )
+ }
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 148.dp),
@@ -581,6 +608,20 @@ private fun MoviesVodContent(
onClick = { showCategoryPicker = true }
)
)
+ add(
+ VodActionChip(
+ key = "search_toggle",
+ label = if (showSearchBar) "Hide Search" else "Search",
+ onClick = { showSearchBar = !showSearchBar }
+ )
+ )
+ add(
+ VodActionChip(
+ key = "browse_options",
+ label = "Filters & Sort",
+ onClick = { showBrowseOptions = true }
+ )
+ )
if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
add(
VodActionChip(
@@ -595,52 +636,16 @@ private fun MoviesVodContent(
)
}
- item(span = { GridItemSpan(maxLineSpan) }) {
- SearchInput(
- value = searchQuery,
- onValueChange = onSearchQueryChange,
- placeholder = stringResource(R.string.movies_search_placeholder),
- onSearch = {},
- modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
- )
- }
-
- item(span = { GridItemSpan(maxLineSpan) }) {
- SelectionChipRow(
- title = "",
- chips = movieFilterChips(),
- selectedKey = selectedFilterType.name,
- onChipSelected = { key ->
- LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
- },
- modifier = Modifier.padding(horizontal = 0.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- }
-
- item(span = { GridItemSpan(maxLineSpan) }) {
- SelectionChipRow(
- title = "",
- chips = LibrarySortBy.entries.map { sort ->
- SelectionChip(
- key = sort.name,
- label = when (sort) {
- LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
- LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
- LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
- LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
- LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
- LibrarySortBy.WATCH_COUNT -> "Recent Activity"
- }
- )
- },
- selectedKey = selectedSortBy.name,
- onChipSelected = { key ->
- LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
- },
- modifier = Modifier.padding(horizontal = 0.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
+ if (showSearchBar) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SearchInput(
+ value = searchQuery,
+ onValueChange = onSearchQueryChange,
+ placeholder = stringResource(R.string.movies_search_placeholder),
+ onSearch = {},
+ modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
+ )
+ }
}
}
@@ -725,4 +730,20 @@ private fun movieFilterChips(): List<SelectionChip> {
)
}
+private fun movieSortChips(): List<SelectionChip> {
+ return LibrarySortBy.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ LibrarySortBy.LIBRARY -> "Library Order"
+ LibrarySortBy.TITLE -> "A-Z"
+ LibrarySortBy.RELEASE -> "Newest"
+ LibrarySortBy.UPDATED -> "Recently Updated"
+ LibrarySortBy.RATING -> "Rating"
+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ }
+ )
+ }
+}
+
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
index 10e0c2e8..9f56b5f3 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
@@ -3,7 +3,9 @@ package com.streamvault.app.ui.screens.movies
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferences
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LibraryFilterBy
import com.streamvault.domain.model.LibraryFilterType
@@ -11,6 +13,7 @@ import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.LibrarySortBy
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
@@ -18,7 +21,6 @@ import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.usecase.ContinueWatchingScope
import com.streamvault.domain.usecase.GetContinueWatching
import com.streamvault.domain.usecase.GetCustomCategories
-import com.streamvault.domain.util.isPlaybackComplete
import com.streamvault.app.ui.screens.vod.createVodGroup
import com.streamvault.app.ui.screens.vod.incrementVodSelectedCategoryLoadLimit
import com.streamvault.app.ui.screens.vod.buildVodPreviewCatalog
@@ -36,6 +38,7 @@ import com.streamvault.app.ui.screens.vod.setVodSearchQuery
import com.streamvault.app.ui.screens.vod.setVodFavorite
import com.streamvault.app.ui.screens.vod.updateVodGroupMembership
import com.streamvault.app.ui.screens.vod.VodBrowseDefaults
+import com.streamvault.app.util.isPlaybackComplete
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -94,14 +97,30 @@ class MoviesViewModel @Inject constructor(
getCustomCategories(ContentType.MOVIE),
movieRepository.getCategories(provider.id),
movieRepository.getCategoryItemCounts(provider.id),
- movieRepository.getLibraryCount(provider.id)
- ) { allFavorites, customCategories, providerCategories, providerCategoryCounts, libraryCount ->
+ movieRepository.getLibraryCount(provider.id),
+ preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.MOVIE),
+ preferencesRepository.getCategorySortMode(provider.id, ContentType.MOVIE)
+ ) { values ->
+ val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
+ val customCategories = values[1] as List<Category>
+ val providerCategories = values[2] as List<Category>
+ val providerCategoryCounts = values[3] as Map<Long, Int>
+ val libraryCount = values[4] as Int
+ val hiddenCategoryIds = values[5] as Set<Long>
+ val sortMode = values[6] as CategorySortMode
+ val visibleProviderCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCategories,
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ )
MovieCatalogDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
- providerCategories = providerCategories,
+ providerCategories = visibleProviderCategories,
providerCategoryCounts = providerCategoryCounts,
- libraryCount = libraryCount
+ libraryCount = libraryCount,
+ hiddenCategoryIds = hiddenCategoryIds,
+ categorySortMode = sortMode
)
}.combine(_searchQuery) { dependencies, query ->
MovieCatalogParams(
@@ -111,6 +130,8 @@ class MoviesViewModel @Inject constructor(
providerCategories = dependencies.providerCategories,
providerCategoryCounts = dependencies.providerCategoryCounts,
libraryCount = dependencies.libraryCount,
+ hiddenCategoryIds = dependencies.hiddenCategoryIds,
+ categorySortMode = dependencies.categorySortMode,
query = query.trim()
)
}
@@ -125,7 +146,9 @@ class MoviesViewModel @Inject constructor(
buildSearchCatalog(
movies = searchResults,
allFavorites = params.allFavorites,
- customCategories = params.customCategories
+ customCategories = params.customCategories,
+ providerCategories = params.providerCategories,
+ hiddenCategoryIds = params.hiddenCategoryIds
).copy(libraryCount = searchResults.size)
}
)
@@ -133,12 +156,25 @@ class MoviesViewModel @Inject constructor(
}
.collect { snapshot ->
val isReordering = _uiState.value.isReorderMode
+ val currentSelected = _uiState.value.selectedCategory
+ val preserveSelectedCategory = currentSelected != null && _searchQuery.value.isNotBlank()
+ val resolvedSelected = currentSelected?.takeIf { selected ->
+ preserveSelectedCategory ||
+ selected == _uiState.value.fullLibraryCategoryName ||
+ selected in snapshot.categoryNames
+ }
_uiState.update {
it.copy(
moviesByCategory = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
libraryCount = snapshot.libraryCount,
+ providerCategories = snapshot.providerCategories,
+ selectedCategory = resolvedSelected,
+ selectedCategoryItems = if (resolvedSelected == null) emptyList() else it.selectedCategoryItems,
+ selectedCategoryLoadedCount = if (resolvedSelected == null) 0 else it.selectedCategoryLoadedCount,
+ selectedCategoryTotalCount = if (resolvedSelected == null) 0 else it.selectedCategoryTotalCount,
+ canLoadMoreSelectedCategory = if (resolvedSelected == null) false else it.canLoadMoreSelectedCategory,
filteredMovies = if (isReordering) it.filteredMovies else emptyList(),
isLoading = false,
errorMessage = null
@@ -158,13 +194,26 @@ class MoviesViewModel @Inject constructor(
favoriteRepository.getFavorites(ContentType.MOVIE),
getCustomCategories(ContentType.MOVIE),
movieRepository.getCategories(provider.id),
- movieRepository.getCategoryItemCounts(provider.id)
- ) { allFavorites, customCategories, providerCategories, providerCategoryCounts ->
+ movieRepository.getCategoryItemCounts(provider.id),
+ preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.MOVIE),
+ preferencesRepository.getCategorySortMode(provider.id, ContentType.MOVIE)
+ ) { values ->
+ val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
+ val customCategories = values[1] as List<Category>
+ val providerCategories = values[2] as List<Category>
+ val providerCategoryCounts = values[3] as Map<Long, Int>
+ val hiddenCategoryIds = values[4] as Set<Long>
+ val sortMode = values[5] as CategorySortMode
MovieCategorySelectionDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
- providerCategories = providerCategories,
- providerCategoryCounts = providerCategoryCounts
+ providerCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCategories,
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ ),
+ providerCategoryCounts = providerCategoryCounts,
+ hiddenCategoryIds = hiddenCategoryIds
)
}.combine(
combine(
@@ -193,7 +242,8 @@ class MoviesViewModel @Inject constructor(
allFavorites = dependencies.allFavorites,
customCategories = dependencies.customCategories,
providerCategories = dependencies.providerCategories,
- providerCategoryCounts = dependencies.providerCategoryCounts
+ providerCategoryCounts = dependencies.providerCategoryCounts,
+ hiddenCategoryIds = dependencies.hiddenCategoryIds
)
}
}
@@ -478,13 +528,42 @@ class MoviesViewModel @Inject constructor(
}
viewModelScope.launch {
- createVodGroup(normalizedName, ContentType.MOVIE, favoriteRepository)
- _uiState.update { it.copy(userMessage = "Created group $normalizedName") }
+ when (val result = createVodGroup(normalizedName, ContentType.MOVIE, favoriteRepository)) {
+ is Result.Success -> {
+ val selectedMovie = _uiState.value.selectedMovieForDialog
+ val memberships = if (selectedMovie != null) {
+ updateVodGroupMembership(
+ itemId = selectedMovie.id,
+ groupId = result.data.id,
+ contentType = ContentType.MOVIE,
+ shouldBeMember = true,
+ favoriteRepository = favoriteRepository
+ )
+ } else {
+ _uiState.value.dialogGroupMemberships
+ }
+ _uiState.update {
+ it.copy(
+ dialogGroupMemberships = memberships,
+ userMessage = if (selectedMovie != null) {
+ "Created group $normalizedName and added ${selectedMovie.name}"
+ } else {
+ "Created group $normalizedName"
+ }
+ )
+ }
+ }
+ is Result.Error -> {
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ Result.Loading -> Unit
+ }
}
}
fun showCategoryOptions(categoryName: String) {
val matchedCategory = _uiState.value.categories.find { it.name == categoryName }
+ ?: _uiState.value.providerCategories.find { it.name == categoryName }
?: if (categoryName == VodBrowseDefaults.FAVORITES_CATEGORY) {
Category(
id = VodBrowseDefaults.FAVORITES_SENTINEL_ID,
@@ -505,6 +584,25 @@ class MoviesViewModel @Inject constructor(
_uiState.update { it.copy(selectedCategoryForOptions = null) }
}
+ fun hideCategory(category: Category) {
+ if (category.isVirtual) return
+ viewModelScope.launch {
+ val providerId = providerRepository.getActiveProvider().first()?.id ?: return@launch
+ preferencesRepository.setCategoryHidden(
+ providerId = providerId,
+ type = ContentType.MOVIE,
+ categoryId = category.id,
+ hidden = true
+ )
+ if (_uiState.value.selectedCategory == category.name) {
+ selectCategory(null)
+ } else {
+ dismissCategoryOptions()
+ }
+ _uiState.update { it.copy(userMessage = "Hidden category ${category.name}") }
+ }
+ }
+
fun requestRenameGroup(category: Category) {
if (!category.isVirtual || category.id == VodBrowseDefaults.FAVORITES_SENTINEL_ID) return
_uiState.update {
@@ -661,31 +759,39 @@ class MoviesViewModel @Inject constructor(
providerCategories = params.providerCategories,
providerCategoryCounts = params.providerCategoryCounts,
libraryCount = params.libraryCount,
+ hiddenProviderCategoryIds = params.hiddenCategoryIds,
loadItemsByIds = { ids -> movieRepository.getMoviesByIds(ids).first() },
loadCategoryPreviewRows = { providerId, limit ->
movieRepository.getCategoryPreviewRows(providerId, limit).first()
},
itemId = Movie::id,
+ itemCategoryId = Movie::categoryId,
copyWithFavorite = { movie, isFavorite -> movie.copy(isFavorite = isFavorite) }
)
return MovieCatalogSnapshot(
grouped = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
- libraryCount = snapshot.libraryCount
+ libraryCount = snapshot.libraryCount,
+ providerCategories = params.providerCategories
)
}
private fun buildSearchCatalog(
movies: List<Movie>,
allFavorites: List<com.streamvault.domain.model.Favorite>,
- customCategories: List<Category>
+ customCategories: List<Category>,
+ providerCategories: List<Category>,
+ hiddenCategoryIds: Set<Long>
): MovieCatalogSnapshot {
val snapshot = buildVodSearchCatalog(
items = movies,
allFavorites = allFavorites,
customCategories = customCategories,
+ providerCategories = providerCategories,
+ hiddenProviderCategoryIds = hiddenCategoryIds,
itemId = Movie::id,
+ itemCategoryId = Movie::categoryId,
itemCategoryName = Movie::categoryName,
copyWithFavorite = { movie, isFavorite -> movie.copy(isFavorite = isFavorite) },
uncategorizedName = UNCATEGORIZED
@@ -694,7 +800,8 @@ class MoviesViewModel @Inject constructor(
grouped = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
- libraryCount = snapshot.libraryCount
+ libraryCount = snapshot.libraryCount,
+ providerCategories = providerCategories
)
}
@@ -713,20 +820,15 @@ class MoviesViewModel @Inject constructor(
val (selectedItems, totalCount) = when (request.selectedCategory) {
VodBrowseDefaults.FULL_LIBRARY_CATEGORY -> {
- val result = movieRepository
- .browseMovies(
- LibraryBrowseQuery(
- providerId = request.providerId,
- categoryId = null,
- sortBy = request.sortBy,
- filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
- limit = request.loadLimit,
- offset = 0
- )
- )
- .first()
- result.items to result.totalCount
+ val filteredItems = applyLocalBrowseToMovies(
+ movieRepository.getMovies(request.providerId)
+ .first()
+ .filterNot { movie -> movie.categoryId in request.hiddenCategoryIds },
+ request.filterType,
+ request.sortBy,
+ request.query
+ )
+ filteredItems.take(request.loadLimit) to filteredItems.size
}
VodBrowseDefaults.FAVORITES_CATEGORY -> {
val ids = request.allFavorites
@@ -738,7 +840,9 @@ class MoviesViewModel @Inject constructor(
val items = if (ids.isEmpty()) {
emptyList()
} else {
- movieRepository.getMoviesByIds(ids).first().orderByIds(ids)
+ movieRepository.getMoviesByIds(ids).first()
+ .filterNot { movie -> movie.categoryId in request.hiddenCategoryIds }
+ .orderByIds(ids)
}
val filteredItems = applyLocalBrowseToMovies(
items,
@@ -760,7 +864,9 @@ class MoviesViewModel @Inject constructor(
val items = if (ids.isEmpty()) {
emptyList()
} else {
- movieRepository.getMoviesByIds(ids).first().orderByIds(ids)
+ movieRepository.getMoviesByIds(ids).first()
+ .filterNot { movie -> movie.categoryId in request.hiddenCategoryIds }
+ .orderByIds(ids)
}
val filteredItems = applyLocalBrowseToMovies(
items,
@@ -875,6 +981,8 @@ private data class MovieCatalogParams(
val providerCategories: List<Category>,
val providerCategoryCounts: Map<Long, Int>,
val libraryCount: Int,
+ val hiddenCategoryIds: Set<Long>,
+ val categorySortMode: CategorySortMode,
val query: String
)
@@ -883,14 +991,17 @@ private data class MovieCatalogDependencies(
val customCategories: List<Category>,
val providerCategories: List<Category>,
val providerCategoryCounts: Map<Long, Int>,
- val libraryCount: Int
+ val libraryCount: Int,
+ val hiddenCategoryIds: Set<Long>,
+ val categorySortMode: CategorySortMode
)
private data class MovieCatalogSnapshot(
val grouped: Map<String, List<Movie>>,
val categoryNames: List<String>,
val categoryCounts: Map<String, Int>,
- val libraryCount: Int
+ val libraryCount: Int,
+ val providerCategories: List<Category>
)
private data class MovieLibraryLensDependencies(
@@ -905,7 +1016,8 @@ private data class MovieCategorySelectionDependencies(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>
+ val providerCategoryCounts: Map<Long, Int>,
+ val hiddenCategoryIds: Set<Long>
)
private data class SelectedMovieCategoryRequest(
@@ -918,7 +1030,8 @@ private data class SelectedMovieCategoryRequest(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>
+ val providerCategoryCounts: Map<Long, Int>,
+ val hiddenCategoryIds: Set<Long>
)
private data class SelectedMovieBrowseSelection(
@@ -959,6 +1072,7 @@ data class MoviesUiState(
val showDialog: Boolean = false,
val selectedMovieForDialog: Movie? = null,
val categories: List<Category> = emptyList(),
+ val providerCategories: List<Category> = emptyList(),
val dialogGroupMemberships: List<Long> = emptyList(),
val userMessage: String? = null,
val selectedCategoryForOptions: Category? = null,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
index 44983ffb..29da55e2 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
@@ -23,6 +23,7 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -106,6 +107,12 @@ fun MultiViewScreen(
}
}
+ DisposableEffect(Unit) {
+ onDispose {
+ viewModel.releasePlayersForBackground()
+ }
+ }
+
Box(
modifier = Modifier
.fillMaxSize()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
index 311d28b2..26466851 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
@@ -129,14 +129,29 @@ class MultiViewViewModel @Inject constructor(
observeReplacementCandidates()
}
+ fun releasePlayersForBackground() {
+ cancelSlotStartupJobs()
+ cancelSlotErrorJobs()
+ playerEngines.values.forEach { engine ->
+ runCatching { engine.stop() }
+ runCatching { engine.setVolume(0f) }
+ runCatching { engine.release() }
+ }
+ playerEngines.clear()
+ _uiState.value = _uiState.value.copy(
+ slots = _uiState.value.slots.map { slot ->
+ if (slot.isEmpty) slot else slot.copy(isLoading = false, playerEngine = null)
+ }
+ )
+ }
+
/** Called when MultiViewScreen is opened — spins up player engines for occupied slots */
fun initSlots() {
val initVersion = ++slotInitVersion
telemetryJob?.cancel()
cancelSlotStartupJobs()
cancelSlotErrorJobs()
- playerEngines.values.forEach { it.release() }
- playerEngines.clear()
+ releasePlayersForBackground()
lastDroppedFramesBySlot.clear()
val channels = multiViewManager.slots.value
val deviceActiveSlotLimit = runtimeActiveSlotLimit
@@ -411,11 +426,8 @@ class MultiViewViewModel @Inject constructor(
super.onCleared()
telemetryJob?.cancel()
borderHideJob?.cancel()
- cancelSlotStartupJobs()
- cancelSlotErrorJobs()
unregisterThermalListener()
- playerEngines.values.forEach { it.release() }
- playerEngines.clear()
+ releasePlayersForBackground()
}
private fun cancelSlotStartupJobs() {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index e82d0c66..77abf762 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
@@ -517,7 +517,9 @@ fun PlayerScreen(
true
}
KeyEvent.KEYCODE_MUTE, KeyEvent.KEYCODE_VOLUME_MUTE -> {
- viewModel.toggleMute()
+ if (event.nativeKeyEvent.repeatCount == 0) {
+ viewModel.toggleMute()
+ }
true
}
KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {
@@ -647,7 +649,7 @@ fun PlayerScreen(
}
AnimatedVisibility(
- visible = playerNotice != null,
+ visible = playerNotice != null && !(playbackState == PlaybackState.BUFFERING && playerNotice?.isRetryNotice == false),
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier
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 b0844c94..1bf8b7bf 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
@@ -1,6 +1,7 @@
package com.streamvault.app.ui.screens.player
import android.graphics.Bitmap
+import android.os.SystemClock
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.app.cast.CastConnectionState
@@ -8,6 +9,7 @@ import com.streamvault.app.cast.CastManager
import com.streamvault.app.cast.CastMediaRequest
import com.streamvault.app.cast.CastStartResult
import com.streamvault.app.di.MainPlayerEngine
+import com.streamvault.app.util.isPlaybackComplete
import com.streamvault.app.tv.LauncherRecommendationsManager
import com.streamvault.app.tv.WatchNextManager
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
@@ -32,7 +34,6 @@ import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
-import com.streamvault.domain.util.isPlaybackComplete
import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerEngine
import com.streamvault.player.PlayerError
@@ -133,6 +134,9 @@ class PlayerViewModel @Inject constructor(
private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
private val seekThumbnailProvider: SeekThumbnailProvider
) : ViewModel() {
+ companion object {
+ private const val MUTE_TOGGLE_DEBOUNCE_MS = 250L
+ }
private val _showControls = MutableStateFlow(false)
val showControls: StateFlow<Boolean> = _showControls.asStateFlow()
@@ -215,6 +219,7 @@ class PlayerViewModel @Inject constructor(
private var numericInputCommitJob: Job? = null
private var numericInputFeedbackJob: Job? = null
private var playerNoticeHideJob: Job? = null
+ private var mutePersistJob: Job? = null
private var numericInputBuffer: String = ""
private val triedAlternativeStreams = mutableSetOf<String>()
private val failedStreamsThisSession = mutableMapOf<String, Int>()
@@ -245,15 +250,17 @@ class PlayerViewModel @Inject constructor(
viewModelScope.launch {
playerEngine.playbackState.collect { state ->
_playerDiagnostics.update { it.copy(playbackStateLabel = state.name.replace('_', ' ')) }
- if (state == PlaybackState.READY && currentContentType == ContentType.LIVE) {
+ if (state == PlaybackState.READY) {
zapBufferWatchdogJob?.cancel()
- dismissRetryNoticeIfPresent()
- _currentChannel.value?.let { channel ->
- if (channel.errorCount > 0) {
- logRepositoryFailure(
- operation = "Reset channel error count",
- result = channelRepository.resetChannelErrorCount(channel.id)
- )
+ dismissRecoveredNoticeIfPresent()
+ if (currentContentType == ContentType.LIVE) {
+ _currentChannel.value?.let { channel ->
+ if (channel.errorCount > 0) {
+ logRepositoryFailure(
+ operation = "Reset channel error count",
+ result = channelRepository.resetChannelErrorCount(channel.id)
+ )
+ }
}
}
}
@@ -510,6 +517,7 @@ class PlayerViewModel @Inject constructor(
private var isAppInForeground: Boolean = true
private var shouldResumeAfterForeground: Boolean = false
private var seekPreviewRequestVersion: Long = 0L
+ private var lastMuteToggleAtMs: Long = 0L
val playerError: StateFlow<PlayerError?> = playerEngine.error
.stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)
@@ -1399,11 +1407,11 @@ class PlayerViewModel @Inject constructor(
}
private fun resolvePlaybackErrorMessage(error: PlayerError): String = when (classifyPlaybackError(error)) {
- PlayerRecoveryType.NETWORK -> "The stream stopped responding after retries. Check the network or try another source."
- PlayerRecoveryType.SOURCE -> "This stream failed after retries on the available paths."
- PlayerRecoveryType.DECODER -> "Playback failed in the current decoder path."
+ PlayerRecoveryType.NETWORK -> "This stream is not responding right now. You can retry or try another source."
+ PlayerRecoveryType.SOURCE -> "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 stalled for too long after retries on this stream."
+ 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." }
}
@@ -1626,9 +1634,13 @@ class PlayerViewModel @Inject constructor(
fun seekForward() = playerEngine.seekForward()
fun seekBackward() = playerEngine.seekBackward()
fun toggleMute() {
- val muted = !isMuted.value
- playerEngine.setMuted(muted)
- viewModelScope.launch {
+ 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)
}
}
@@ -1842,8 +1854,9 @@ class PlayerViewModel @Inject constructor(
_playerNotice.value = null
}
- private fun dismissRetryNoticeIfPresent() {
- if (_playerNotice.value?.isRetryNotice == true) {
+ private fun dismissRecoveredNoticeIfPresent() {
+ val notice = _playerNotice.value ?: return
+ if (notice.isRetryNotice || notice.recoveryType != PlayerRecoveryType.UNKNOWN) {
dismissPlayerNotice()
}
}
@@ -1874,7 +1887,7 @@ class PlayerViewModel @Inject constructor(
message: String,
recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
actions: List<PlayerNoticeAction> = emptyList(),
- durationMs: Long = if (actions.isNotEmpty()) 8000L else 3600L,
+ durationMs: Long = if (actions.isNotEmpty()) 6500L else 3200L,
isRetryNotice: Boolean = false
) {
playerNoticeHideJob?.cancel()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
index a3fb69bd..fcde7baa 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt
@@ -21,6 +21,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
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.graphics.Color
@@ -39,6 +40,8 @@ import com.streamvault.app.R
import com.streamvault.app.ui.design.requestFocusSafely
import com.streamvault.app.ui.screens.player.PlayerNoticeAction
import com.streamvault.app.ui.screens.player.PlayerNoticeState
+import com.streamvault.app.ui.screens.player.PlayerRecoveryType
+import com.streamvault.app.ui.theme.AccentAmber
import com.streamvault.app.ui.theme.ErrorColor
import com.streamvault.app.ui.theme.OnBackground
import com.streamvault.app.ui.theme.OnSurface
@@ -62,16 +65,29 @@ fun PlayerNoticeBanner(
) {
if (notice == null) return
- Surface(
- onClick = onDismiss,
+ val (containerColor, focusedContainerColor) = when {
+ notice.isRetryNotice || notice.recoveryType == PlayerRecoveryType.NETWORK || notice.recoveryType == PlayerRecoveryType.CATCH_UP ->
+ Color(0xCC17314E) to Color(0xFF214C78)
+ notice.recoveryType == PlayerRecoveryType.SOURCE ||
+ notice.recoveryType == PlayerRecoveryType.BUFFER_TIMEOUT ||
+ notice.recoveryType == PlayerRecoveryType.DECODER ->
+ Color(0xCC4A3314) to Color(0xFF6D4A19)
+ notice.recoveryType == PlayerRecoveryType.DRM ->
+ Color(0xCC5B1F1F) to Color(0xFFE45757)
+ else -> SurfaceElevated.copy(alpha = 0.96f) to SurfaceHighlight
+ }
+
+ Box(
modifier = modifier,
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Color(0xCC5B1F1F),
- focusedContainerColor = Color(0xFFE45757)
- )
+ contentAlignment = Alignment.TopCenter
) {
- Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 12.dp)) {
+ Column(
+ modifier = Modifier
+ .widthIn(max = 760.dp)
+ .clip(RoundedCornerShape(12.dp))
+ .background(containerColor)
+ .padding(horizontal = 18.dp, vertical = 12.dp)
+ ) {
Text(
text = notice.message,
style = MaterialTheme.typography.bodyMedium,
@@ -86,7 +102,7 @@ fun PlayerNoticeBanner(
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = Color.White.copy(alpha = 0.12f),
- focusedContainerColor = Color.White.copy(alpha = 0.22f)
+ focusedContainerColor = focusedContainerColor
)
) {
Text(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
index ece3ae41..6a53ef59 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt
@@ -51,6 +51,7 @@ import com.streamvault.app.R
fun ProviderSetupScreen(
onProviderAdded: () -> Unit,
editProviderId: Long? = null,
+ initialImportUri: String? = null,
viewModel: ProviderSetupViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
@@ -58,65 +59,73 @@ fun ProviderSetupScreen(
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
+ var selectedTab by rememberSaveable { mutableStateOf(0) } // 0 = Xtream, 1 = M3U
var name by rememberSaveable { mutableStateOf("") }
var m3uUrl by rememberSaveable { mutableStateOf("") }
var fileImportError by rememberSaveable { mutableStateOf<String?>(null) }
-
- val filePickerLauncher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.OpenDocument()
- ) { uri: android.net.Uri? ->
- if (uri != null) {
- coroutineScope.launch(Dispatchers.IO) {
- try {
- val inputStream = context.contentResolver.openInputStream(uri)
- if (inputStream != null) {
- var fileName = "Local_Playlist"
- val cursor = context.contentResolver.query(uri, null, null, null, null)
- cursor?.use {
- if (it.moveToFirst()) {
- val displayNameIndex = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
- if (displayNameIndex != -1) {
- val displayName = it.getString(displayNameIndex)
- if (displayName.contains(".")) {
- fileName = displayName.substringBeforeLast(".")
- } else {
- fileName = displayName
- }
+ var handledInitialImportUri by rememberSaveable { mutableStateOf<String?>(null) }
+
+ fun importM3uUri(uri: android.net.Uri) {
+ coroutineScope.launch(Dispatchers.IO) {
+ try {
+ val inputStream = context.contentResolver.openInputStream(uri)
+ if (inputStream != null) {
+ var fileName = "Local_Playlist"
+ val cursor = context.contentResolver.query(uri, null, null, null, null)
+ cursor?.use {
+ if (it.moveToFirst()) {
+ val displayNameIndex = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
+ if (displayNameIndex != -1) {
+ val displayName = it.getString(displayNameIndex)
+ if (displayName.contains(".")) {
+ fileName = displayName.substringBeforeLast(".")
+ } else {
+ fileName = displayName
}
}
}
+ }
- val outFile = java.io.File(context.filesDir, "m3u_${System.currentTimeMillis()}.m3u")
- outFile.outputStream().use { out ->
- inputStream.copyTo(out)
- }
- cleanupOldImportedM3uFiles(
- filesDir = context.filesDir,
- protectedFileUris = knownLocalM3uUrls + "file://${outFile.absolutePath}",
- keepLatest = 20
- )
+ val extension = if (uri.toString().substringBefore('?').lowercase().endsWith(".m3u8")) "m3u8" else "m3u"
+ val outFile = java.io.File(context.filesDir, "m3u_${System.currentTimeMillis()}.$extension")
+ outFile.outputStream().use { out ->
+ inputStream.copyTo(out)
+ }
+ cleanupOldImportedM3uFiles(
+ filesDir = context.filesDir,
+ protectedFileUris = knownLocalM3uUrls + "file://${outFile.absolutePath}",
+ keepLatest = 20
+ )
- withContext(Dispatchers.Main) {
- m3uUrl = "file://${outFile.absolutePath}"
- if (name.isEmpty()) {
- name = ProviderInputSanitizer.sanitizeProviderNameForEditing(fileName)
- }
- fileImportError = null
- }
- } else {
- withContext(Dispatchers.Main) {
- fileImportError = context.getString(R.string.setup_file_import_failed)
+ withContext(Dispatchers.Main) {
+ viewModel.updateM3uTab(1)
+ m3uUrl = "file://${outFile.absolutePath}"
+ if (name.isEmpty()) {
+ name = ProviderInputSanitizer.sanitizeProviderNameForEditing(fileName)
}
+ fileImportError = null
}
- } catch (e: Exception) {
+ } else {
withContext(Dispatchers.Main) {
- fileImportError = resolveFileImportError(context, e)
+ fileImportError = context.getString(R.string.setup_file_import_failed)
}
}
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ fileImportError = resolveFileImportError(context, e)
+ }
}
}
}
+ val filePickerLauncher = rememberLauncherForActivityResult(
+ contract = ActivityResultContracts.OpenDocument()
+ ) { uri: android.net.Uri? ->
+ if (uri != null) {
+ importM3uUri(uri)
+ }
+ }
+
LaunchedEffect(knownLocalM3uUrls) {
cleanupOldImportedM3uFiles(
filesDir = context.filesDir,
@@ -125,6 +134,17 @@ fun ProviderSetupScreen(
)
}
+ LaunchedEffect(initialImportUri) {
+ val importUri = initialImportUri?.takeIf { it.isNotBlank() } ?: return@LaunchedEffect
+ if (handledInitialImportUri == importUri) return@LaunchedEffect
+ handledInitialImportUri = importUri
+ selectedTab = 1
+ viewModel.updateM3uTab(1)
+ runCatching { android.net.Uri.parse(importUri) }
+ .getOrNull()
+ ?.let(::importM3uUri)
+ }
+
// Navigate on success
LaunchedEffect(uiState.loginSuccess) {
if (uiState.loginSuccess) {
@@ -153,7 +173,6 @@ fun ProviderSetupScreen(
// if (uiState.hasExistingProvider) onProviderAdded()
// }
- var selectedTab by rememberSaveable { mutableStateOf(0) } // 0 = Xtream, 1 = M3U
var serverUrl by rememberSaveable { mutableStateOf("") }
var username by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
index 922959a7..b93f5d87 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt
@@ -26,7 +26,10 @@ class SeriesDetailViewModel @Inject constructor(
private val playbackHistoryRepository: PlaybackHistoryRepository
) : ViewModel() {
- private val seriesId: Long = checkNotNull(savedStateHandle.get<String>("seriesId")?.toLongOrNull())
+ private val seriesId: Long = checkNotNull(
+ savedStateHandle.get<Long>("seriesId")
+ ?: savedStateHandle.get<String>("seriesId")?.toLongOrNull()
+ )
private val _uiState = MutableStateFlow(SeriesDetailUiState())
val uiState: StateFlow<SeriesDetailUiState> = _uiState.asStateFlow()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
index a63aa831..5740166d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
@@ -12,6 +12,7 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.text.BasicTextField
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@@ -72,6 +73,7 @@ import com.streamvault.app.ui.components.shell.VodActionChip
import com.streamvault.app.ui.components.shell.VodActionChipRow
import com.streamvault.app.ui.components.shell.VodCategoryOption
import com.streamvault.app.ui.components.shell.VodCategoryPickerDialog
+import com.streamvault.app.ui.components.shell.VodBrowseOptionsDialog
import com.streamvault.app.ui.components.shell.VodHeroStrip
import com.streamvault.app.ui.components.shell.VodSectionHeader
import com.streamvault.app.ui.screens.vod.HandleVodUserMessage
@@ -183,6 +185,7 @@ fun SeriesScreen(
showPinDialog = true
},
onShowDialog = viewModel::onShowDialog,
+ onShowCategoryOptions = viewModel::showCategoryOptions,
onSelectCategory = viewModel::selectCategory,
onSelectFullLibraryBrowse = viewModel::selectFullLibraryBrowse,
onOpenContinueWatching = {
@@ -243,6 +246,9 @@ fun SeriesScreen(
com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog(
category = category,
onDismissRequest = { viewModel.dismissCategoryOptions() },
+ onHide = if (!category.isVirtual) {
+ { viewModel.hideCategory(category) }
+ } else null,
onRename = if (category.isVirtual && category.id != VodBrowseDefaults.FAVORITES_SENTINEL_ID) {
{ viewModel.requestRenameGroup(category) }
} else null,
@@ -277,6 +283,7 @@ private fun SeriesVodContent(
onSeriesClick: (Long) -> Unit,
onProtectedSeriesClick: (Long) -> Unit,
onShowDialog: (Series) -> Unit,
+ onShowCategoryOptions: (String) -> Unit,
onSelectCategory: (String?) -> Unit,
onSelectFullLibraryBrowse: () -> Unit,
onOpenContinueWatching: () -> Unit,
@@ -306,10 +313,25 @@ private fun SeriesVodContent(
val heroSeries = freshSeries.firstOrNull() ?: topRatedSeries.firstOrNull() ?: favoriteSeries.firstOrNull()
val categoryOptions = remember(uiState.categoryNames, uiState.categoryCounts) {
uiState.categoryNames.map { name ->
+ val matchedCategory = uiState.providerCategories.firstOrNull { it.name == name }
+ ?: uiState.categories.firstOrNull { it.name == name }
+ ?: if (name == uiState.favoriteCategoryName) {
+ com.streamvault.domain.model.Category(
+ id = VodBrowseDefaults.FAVORITES_SENTINEL_ID,
+ name = uiState.favoriteCategoryName,
+ type = com.streamvault.domain.model.ContentType.SERIES,
+ isVirtual = true
+ )
+ } else {
+ null
+ }
VodCategoryOption(
name = name,
count = uiState.categoryCounts[name] ?: 0,
- onClick = { onSelectCategory(name) }
+ onClick = { onSelectCategory(name) },
+ onLongClick = matchedCategory?.let { category ->
+ { onShowCategoryOptions(category.name) }
+ }
)
}
}
@@ -419,38 +441,29 @@ private fun SeriesVodContent(
}
if (favoriteSeries.isNotEmpty()) {
- item("favorites_header") {
- VodSectionHeader(
- title = stringResource(R.string.favorites_title),
- onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) }
- )
- }
item("favorites_row") {
- LazyRow(
- contentPadding = PaddingValues(horizontal = 20.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- items(favoriteSeries, key = { it.id }) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
- SeriesCard(
- series = series,
- isLocked = isLocked,
- onClick = { if (isLocked) onProtectedSeriesClick(series.id) else onSeriesClick(series.id) },
- onLongClick = { onShowDialog(series) },
- modifier = Modifier.width(favoriteCardWidth)
- )
- }
+ CategoryRow(
+ title = stringResource(R.string.favorites_title),
+ items = favoriteSeries,
+ onSeeAll = { onSelectCategory(uiState.favoriteCategoryName) },
+ keySelector = { it.id }
+ ) { series ->
+ val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ SeriesCard(
+ series = series,
+ isLocked = isLocked,
+ onClick = { if (isLocked) onProtectedSeriesClick(series.id) else onSeriesClick(series.id) },
+ onLongClick = { onShowDialog(series) },
+ modifier = Modifier.width(favoriteCardWidth)
+ )
}
}
}
if (freshSeries.isNotEmpty()) {
- item("fresh_header") {
- VodSectionHeader(title = stringResource(R.string.library_lens_fresh_series))
- }
item("fresh_row") {
CategoryRow(
- title = "",
+ title = stringResource(R.string.library_lens_fresh_series),
items = freshSeries,
onSeeAll = null,
keySelector = { it.id }
@@ -467,12 +480,9 @@ private fun SeriesVodContent(
}
if (topRatedSeries.isNotEmpty()) {
- item("top_header") {
- VodSectionHeader(title = stringResource(R.string.library_lens_top_rated))
- }
item("top_row") {
CategoryRow(
- title = "",
+ title = stringResource(R.string.library_lens_top_rated),
items = topRatedSeries,
onSeeAll = null,
keySelector = { it.id }
@@ -494,14 +504,10 @@ private fun SeriesVodContent(
}.take(8),
key = { it.key }
) { (categoryName, seriesList) ->
- VodSectionHeader(
- title = categoryName,
- onSeeAll = { onSelectCategory(categoryName) }
- )
CategoryRow(
- title = "",
+ title = categoryName,
items = seriesList,
- onSeeAll = null,
+ onSeeAll = { onSelectCategory(categoryName) },
keySelector = { it.id }
) { series ->
val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
@@ -522,6 +528,27 @@ private fun SeriesVodContent(
if (uiState.isReorderMode) uiState.filteredSeries else baseSeries
}
var draggingSeries by remember { mutableStateOf<Series?>(null) }
+ var showBrowseOptions by rememberSaveable(uiState.selectedCategory) { mutableStateOf(false) }
+ var showSearchBar by rememberSaveable(uiState.selectedCategory) { mutableStateOf(searchQuery.isNotBlank()) }
+
+ if (showBrowseOptions) {
+ VodBrowseOptionsDialog(
+ title = stringResource(R.string.nav_series),
+ filterTitle = stringResource(R.string.library_filter_title),
+ filterChips = seriesFilterChips(),
+ selectedFilterKey = selectedFilterType.name,
+ onFilterSelected = { key ->
+ LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
+ },
+ sortTitle = stringResource(R.string.library_sort_title),
+ sortChips = seriesSortChips(),
+ selectedSortKey = selectedSortBy.name,
+ onSortSelected = { key ->
+ LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
+ },
+ onDismiss = { showBrowseOptions = false }
+ )
+ }
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 148.dp),
@@ -567,6 +594,20 @@ private fun SeriesVodContent(
onClick = { showCategoryPicker = true }
)
)
+ add(
+ VodActionChip(
+ key = "search_toggle",
+ label = if (showSearchBar) "Hide Search" else "Search",
+ onClick = { showSearchBar = !showSearchBar }
+ )
+ )
+ add(
+ VodActionChip(
+ key = "browse_options",
+ label = "Filters & Sort",
+ onClick = { showBrowseOptions = true }
+ )
+ )
if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
add(
VodActionChip(
@@ -581,52 +622,16 @@ private fun SeriesVodContent(
)
}
- item(span = { GridItemSpan(maxLineSpan) }) {
- SearchInput(
- value = searchQuery,
- onValueChange = onSearchQueryChange,
- placeholder = stringResource(R.string.series_search_placeholder),
- onSearch = {},
- modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
- )
- }
-
- item(span = { GridItemSpan(maxLineSpan) }) {
- SelectionChipRow(
- title = "",
- chips = seriesFilterChips(),
- selectedKey = selectedFilterType.name,
- onChipSelected = { key ->
- LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
- },
- modifier = Modifier.padding(horizontal = 0.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- }
-
- item(span = { GridItemSpan(maxLineSpan) }) {
- SelectionChipRow(
- title = "",
- chips = LibrarySortBy.entries.map { sort ->
- SelectionChip(
- key = sort.name,
- label = when (sort) {
- LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
- LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
- LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
- LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
- LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
- LibrarySortBy.WATCH_COUNT -> "Recent Activity"
- }
- )
- },
- selectedKey = selectedSortBy.name,
- onChipSelected = { key ->
- LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
- },
- modifier = Modifier.padding(horizontal = 0.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
+ if (showSearchBar) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SearchInput(
+ value = searchQuery,
+ onValueChange = onSearchQueryChange,
+ placeholder = stringResource(R.string.series_search_placeholder),
+ onSearch = {},
+ modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
+ )
+ }
}
}
@@ -711,3 +716,19 @@ private fun seriesFilterChips(): List<SelectionChip> {
)
}
+private fun seriesSortChips(): List<SelectionChip> {
+ return LibrarySortBy.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ LibrarySortBy.LIBRARY -> "Library Order"
+ LibrarySortBy.TITLE -> "A-Z"
+ LibrarySortBy.RELEASE -> "Newest"
+ LibrarySortBy.UPDATED -> "Recently Updated"
+ LibrarySortBy.RATING -> "Rating"
+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ }
+ )
+ }
+}
+
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
index ac40110e..d5944fcf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
@@ -2,14 +2,17 @@ package com.streamvault.app.ui.screens.series
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferences
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LibraryFilterBy
import com.streamvault.domain.model.LibraryFilterType
import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.LibrarySortBy
import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
@@ -93,14 +96,29 @@ class SeriesViewModel @Inject constructor(
getCustomCategories(ContentType.SERIES),
seriesRepository.getCategories(provider.id),
seriesRepository.getCategoryItemCounts(provider.id),
- seriesRepository.getLibraryCount(provider.id)
- ) { allFavorites, customCategories, providerCategories, providerCategoryCounts, libraryCount ->
+ seriesRepository.getLibraryCount(provider.id),
+ preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.SERIES),
+ preferencesRepository.getCategorySortMode(provider.id, ContentType.SERIES)
+ ) { values ->
+ val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
+ val customCategories = values[1] as List<Category>
+ val providerCategories = values[2] as List<Category>
+ val providerCategoryCounts = values[3] as Map<Long, Int>
+ val libraryCount = values[4] as Int
+ val hiddenCategoryIds = values[5] as Set<Long>
+ val sortMode = values[6] as CategorySortMode
SeriesCatalogDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
- providerCategories = providerCategories,
+ providerCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCategories,
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ ),
providerCategoryCounts = providerCategoryCounts,
- libraryCount = libraryCount
+ libraryCount = libraryCount,
+ hiddenCategoryIds = hiddenCategoryIds,
+ categorySortMode = sortMode
)
}.combine(_searchQuery) { dependencies, query ->
SeriesCatalogParams(
@@ -110,6 +128,8 @@ class SeriesViewModel @Inject constructor(
providerCategories = dependencies.providerCategories,
providerCategoryCounts = dependencies.providerCategoryCounts,
libraryCount = dependencies.libraryCount,
+ hiddenCategoryIds = dependencies.hiddenCategoryIds,
+ categorySortMode = dependencies.categorySortMode,
query = query.trim()
)
}
@@ -124,7 +144,9 @@ class SeriesViewModel @Inject constructor(
buildSearchCatalog(
series = searchResults,
allFavorites = params.allFavorites,
- customCategories = params.customCategories
+ customCategories = params.customCategories,
+ providerCategories = params.providerCategories,
+ hiddenCategoryIds = params.hiddenCategoryIds
).copy(libraryCount = searchResults.size)
}
)
@@ -132,12 +154,25 @@ class SeriesViewModel @Inject constructor(
}
.collect { snapshot ->
val isReordering = _uiState.value.isReorderMode
+ val currentSelected = _uiState.value.selectedCategory
+ val preserveSelectedCategory = currentSelected != null && _searchQuery.value.isNotBlank()
+ val resolvedSelected = currentSelected?.takeIf { selected ->
+ preserveSelectedCategory ||
+ selected == _uiState.value.fullLibraryCategoryName ||
+ selected in snapshot.categoryNames
+ }
_uiState.update {
it.copy(
seriesByCategory = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
libraryCount = snapshot.libraryCount,
+ providerCategories = snapshot.providerCategories,
+ selectedCategory = resolvedSelected,
+ selectedCategoryItems = if (resolvedSelected == null) emptyList() else it.selectedCategoryItems,
+ selectedCategoryLoadedCount = if (resolvedSelected == null) 0 else it.selectedCategoryLoadedCount,
+ selectedCategoryTotalCount = if (resolvedSelected == null) 0 else it.selectedCategoryTotalCount,
+ canLoadMoreSelectedCategory = if (resolvedSelected == null) false else it.canLoadMoreSelectedCategory,
filteredSeries = if (isReordering) it.filteredSeries else emptyList(),
isLoading = false,
errorMessage = null
@@ -158,14 +193,28 @@ class SeriesViewModel @Inject constructor(
getCustomCategories(ContentType.SERIES),
seriesRepository.getCategories(provider.id),
seriesRepository.getCategoryItemCounts(provider.id),
- playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 2_000)
- ) { allFavorites, customCategories, providerCategories, providerCategoryCounts, history ->
+ playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 2_000),
+ preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.SERIES),
+ preferencesRepository.getCategorySortMode(provider.id, ContentType.SERIES)
+ ) { values ->
+ val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
+ val customCategories = values[1] as List<Category>
+ val providerCategories = values[2] as List<Category>
+ val providerCategoryCounts = values[3] as Map<Long, Int>
+ val history = values[4] as List<PlaybackHistory>
+ val hiddenCategoryIds = values[5] as Set<Long>
+ val sortMode = values[6] as CategorySortMode
SeriesCategorySelectionDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
- providerCategories = providerCategories,
+ providerCategories = applyProviderCategoryDisplayPreferences(
+ categories = providerCategories,
+ hiddenCategoryIds = hiddenCategoryIds,
+ sortMode = sortMode
+ ),
providerCategoryCounts = providerCategoryCounts,
- history = history
+ history = history,
+ hiddenCategoryIds = hiddenCategoryIds
)
}.combine(
combine(
@@ -195,7 +244,8 @@ class SeriesViewModel @Inject constructor(
history = dependencies.history,
customCategories = dependencies.customCategories,
providerCategories = dependencies.providerCategories,
- providerCategoryCounts = dependencies.providerCategoryCounts
+ providerCategoryCounts = dependencies.providerCategoryCounts,
+ hiddenCategoryIds = dependencies.hiddenCategoryIds
)
}
}
@@ -482,13 +532,42 @@ class SeriesViewModel @Inject constructor(
}
viewModelScope.launch {
- createVodGroup(normalizedName, ContentType.SERIES, favoriteRepository)
- _uiState.update { it.copy(userMessage = "Created group $normalizedName") }
+ when (val result = createVodGroup(normalizedName, ContentType.SERIES, favoriteRepository)) {
+ is Result.Success -> {
+ val selectedSeries = _uiState.value.selectedSeriesForDialog
+ val memberships = if (selectedSeries != null) {
+ updateVodGroupMembership(
+ itemId = selectedSeries.id,
+ groupId = result.data.id,
+ contentType = ContentType.SERIES,
+ shouldBeMember = true,
+ favoriteRepository = favoriteRepository
+ )
+ } else {
+ _uiState.value.dialogGroupMemberships
+ }
+ _uiState.update {
+ it.copy(
+ dialogGroupMemberships = memberships,
+ userMessage = if (selectedSeries != null) {
+ "Created group $normalizedName and added ${selectedSeries.name}"
+ } else {
+ "Created group $normalizedName"
+ }
+ )
+ }
+ }
+ is Result.Error -> {
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ Result.Loading -> Unit
+ }
}
}
fun showCategoryOptions(categoryName: String) {
val matchedCategory = _uiState.value.categories.find { it.name == categoryName }
+ ?: _uiState.value.providerCategories.find { it.name == categoryName }
?: if (categoryName == VodBrowseDefaults.FAVORITES_CATEGORY) {
Category(
id = VodBrowseDefaults.FAVORITES_SENTINEL_ID,
@@ -509,6 +588,25 @@ class SeriesViewModel @Inject constructor(
_uiState.update { it.copy(selectedCategoryForOptions = null) }
}
+ fun hideCategory(category: Category) {
+ if (category.isVirtual) return
+ viewModelScope.launch {
+ val providerId = providerRepository.getActiveProvider().first()?.id ?: return@launch
+ preferencesRepository.setCategoryHidden(
+ providerId = providerId,
+ type = ContentType.SERIES,
+ categoryId = category.id,
+ hidden = true
+ )
+ if (_uiState.value.selectedCategory == category.name) {
+ selectCategory(null)
+ } else {
+ dismissCategoryOptions()
+ }
+ _uiState.update { it.copy(userMessage = "Hidden category ${category.name}") }
+ }
+ }
+
fun requestRenameGroup(category: Category) {
if (!category.isVirtual || category.id == VodBrowseDefaults.FAVORITES_SENTINEL_ID) return
_uiState.update {
@@ -665,31 +763,39 @@ class SeriesViewModel @Inject constructor(
providerCategories = params.providerCategories,
providerCategoryCounts = params.providerCategoryCounts,
libraryCount = params.libraryCount,
+ hiddenProviderCategoryIds = params.hiddenCategoryIds,
loadItemsByIds = { ids -> seriesRepository.getSeriesByIds(ids).first() },
loadCategoryPreviewRows = { providerId, limit ->
seriesRepository.getCategoryPreviewRows(providerId, limit).first()
},
itemId = Series::id,
+ itemCategoryId = Series::categoryId,
copyWithFavorite = { series, isFavorite -> series.copy(isFavorite = isFavorite) }
)
return SeriesCatalogSnapshot(
grouped = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
- libraryCount = snapshot.libraryCount
+ libraryCount = snapshot.libraryCount,
+ providerCategories = params.providerCategories
)
}
private fun buildSearchCatalog(
series: List<Series>,
allFavorites: List<com.streamvault.domain.model.Favorite>,
- customCategories: List<Category>
+ customCategories: List<Category>,
+ providerCategories: List<Category>,
+ hiddenCategoryIds: Set<Long>
): SeriesCatalogSnapshot {
val snapshot = buildVodSearchCatalog(
items = series,
allFavorites = allFavorites,
customCategories = customCategories,
+ providerCategories = providerCategories,
+ hiddenProviderCategoryIds = hiddenCategoryIds,
itemId = Series::id,
+ itemCategoryId = Series::categoryId,
itemCategoryName = Series::categoryName,
copyWithFavorite = { series, isFavorite -> series.copy(isFavorite = isFavorite) },
uncategorizedName = UNCATEGORIZED
@@ -698,7 +804,8 @@ class SeriesViewModel @Inject constructor(
grouped = snapshot.grouped,
categoryNames = snapshot.categoryNames,
categoryCounts = snapshot.categoryCounts,
- libraryCount = snapshot.libraryCount
+ libraryCount = snapshot.libraryCount,
+ providerCategories = providerCategories
)
}
@@ -717,20 +824,16 @@ class SeriesViewModel @Inject constructor(
val (selectedItems, totalCount) = when (request.selectedCategory) {
VodBrowseDefaults.FULL_LIBRARY_CATEGORY -> {
- val result = seriesRepository
- .browseSeries(
- LibraryBrowseQuery(
- providerId = request.providerId,
- categoryId = null,
- sortBy = request.sortBy,
- filterBy = LibraryFilterBy(type = request.filterType),
- searchQuery = request.query,
- limit = request.loadLimit,
- offset = 0
- )
- )
- .first()
- result.items to result.totalCount
+ val filteredItems = applyLocalBrowseToSeries(
+ seriesRepository.getSeries(request.providerId)
+ .first()
+ .filterNot { item -> item.categoryId in request.hiddenCategoryIds },
+ request.history,
+ request.filterType,
+ request.sortBy,
+ request.query
+ )
+ filteredItems.take(request.loadLimit) to filteredItems.size
}
VodBrowseDefaults.FAVORITES_CATEGORY -> {
val ids = request.allFavorites
@@ -742,7 +845,9 @@ class SeriesViewModel @Inject constructor(
val items = if (ids.isEmpty()) {
emptyList()
} else {
- seriesRepository.getSeriesByIds(ids).first().orderByIds(ids)
+ seriesRepository.getSeriesByIds(ids).first()
+ .filterNot { item -> item.categoryId in request.hiddenCategoryIds }
+ .orderByIds(ids)
}
val filteredItems = applyLocalBrowseToSeries(
items,
@@ -765,7 +870,9 @@ class SeriesViewModel @Inject constructor(
val items = if (ids.isEmpty()) {
emptyList()
} else {
- seriesRepository.getSeriesByIds(ids).first().orderByIds(ids)
+ seriesRepository.getSeriesByIds(ids).first()
+ .filterNot { item -> item.categoryId in request.hiddenCategoryIds }
+ .orderByIds(ids)
}
val filteredItems = applyLocalBrowseToSeries(
items,
@@ -880,6 +987,8 @@ private data class SeriesCatalogParams(
val providerCategories: List<Category>,
val providerCategoryCounts: Map<Long, Int>,
val libraryCount: Int,
+ val hiddenCategoryIds: Set<Long>,
+ val categorySortMode: CategorySortMode,
val query: String
)
@@ -888,14 +997,17 @@ private data class SeriesCatalogDependencies(
val customCategories: List<Category>,
val providerCategories: List<Category>,
val providerCategoryCounts: Map<Long, Int>,
- val libraryCount: Int
+ val libraryCount: Int,
+ val hiddenCategoryIds: Set<Long>,
+ val categorySortMode: CategorySortMode
)
private data class SeriesCatalogSnapshot(
val grouped: Map<String, List<Series>>,
val categoryNames: List<String>,
val categoryCounts: Map<String, Int>,
- val libraryCount: Int
+ val libraryCount: Int,
+ val providerCategories: List<Category>
)
private data class SeriesLibraryLensDependencies(
@@ -911,7 +1023,8 @@ private data class SeriesCategorySelectionDependencies(
val history: List<PlaybackHistory>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>
+ val providerCategoryCounts: Map<Long, Int>,
+ val hiddenCategoryIds: Set<Long>
)
private data class SelectedSeriesCategoryRequest(
@@ -925,7 +1038,8 @@ private data class SelectedSeriesCategoryRequest(
val history: List<PlaybackHistory>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
- val providerCategoryCounts: Map<Long, Int>
+ val providerCategoryCounts: Map<Long, Int>,
+ val hiddenCategoryIds: Set<Long>
)
private data class SelectedSeriesBrowseSelection(
@@ -966,6 +1080,7 @@ data class SeriesUiState(
val showDialog: Boolean = false,
val selectedSeriesForDialog: Series? = null,
val categories: List<Category> = emptyList(),
+ val providerCategories: List<Category> = emptyList(),
val dialogGroupMemberships: List<Long> = emptyList(),
val userMessage: String? = null,
val selectedCategoryForOptions: Category? = null,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
index b36856c7..d8f36255 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
@@ -41,6 +41,9 @@ import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.model.LiveTvChannelMode
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.manager.BackupConflictStrategy
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.ProviderStatus
@@ -131,6 +134,8 @@ fun SettingsScreen(
var showWifiQualityDialog by rememberSaveable { mutableStateOf(false) }
var showEthernetQualityDialog by rememberSaveable { mutableStateOf(false) }
var showClearHistoryDialog by rememberSaveable { mutableStateOf(false) }
+ var categorySortDialogType by rememberSaveable { mutableStateOf<String?>(null) }
+ var showHiddenCategoriesDialog by rememberSaveable { mutableStateOf(false) }
var pinError by rememberSaveable { mutableStateOf<String?>(null) }
var pendingAction by remember { mutableStateOf<ParentalAction?>(null) }
var pendingProtectionLevel by rememberSaveable { mutableStateOf<Int?>(null) }
@@ -306,6 +311,47 @@ fun SettingsScreen(
)
}
+ item {
+ Spacer(Modifier.height(16.dp))
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_categories_title),
+ subtitle = stringResource(R.string.settings_categories_subtitle)
+ )
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_category_sort_live),
+ value = formatCategorySortModeLabel(
+ uiState.categorySortModes[ContentType.LIVE] ?: CategorySortMode.DEFAULT,
+ context
+ ),
+ onClick = { categorySortDialogType = ContentType.LIVE.name }
+ )
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_category_sort_movies),
+ value = formatCategorySortModeLabel(
+ uiState.categorySortModes[ContentType.MOVIE] ?: CategorySortMode.DEFAULT,
+ context
+ ),
+ onClick = { categorySortDialogType = ContentType.MOVIE.name }
+ )
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_category_sort_series),
+ value = formatCategorySortModeLabel(
+ uiState.categorySortModes[ContentType.SERIES] ?: CategorySortMode.DEFAULT,
+ context
+ ),
+ onClick = { categorySortDialogType = ContentType.SERIES.name }
+ )
+ ClickableSettingsRow(
+ label = stringResource(R.string.settings_hidden_categories_title),
+ value = if (uiState.hiddenCategories.isEmpty()) {
+ stringResource(R.string.settings_hidden_categories_none)
+ } else {
+ stringResource(R.string.settings_hidden_categories_count, uiState.hiddenCategories.size)
+ },
+ onClick = { showHiddenCategoriesDialog = true }
+ )
+ }
+
// Language Settings
item {
Spacer(Modifier.height(16.dp))
@@ -785,6 +831,29 @@ fun SettingsScreen(
)
}
+ categorySortDialogType?.let { typeName ->
+ val type = ContentType.entries.firstOrNull { it.name == typeName }
+ if (type != null) {
+ CategorySortModeDialog(
+ type = type,
+ currentMode = uiState.categorySortModes[type] ?: CategorySortMode.DEFAULT,
+ onDismiss = { categorySortDialogType = null },
+ onModeSelected = { mode ->
+ viewModel.setCategorySortMode(type, mode)
+ categorySortDialogType = null
+ }
+ )
+ }
+ }
+
+ if (showHiddenCategoriesDialog) {
+ HiddenCategoriesDialog(
+ hiddenCategories = uiState.hiddenCategories,
+ onDismiss = { showHiddenCategoriesDialog = false },
+ onUnhide = viewModel::unhideCategory
+ )
+ }
+
if (showPinDialog) {
PinDialog(
onDismissRequest = {
@@ -1045,6 +1114,138 @@ private fun QualityCapSelectionDialog(
}
}
+@Composable
+private fun CategorySortModeDialog(
+ type: ContentType,
+ currentMode: CategorySortMode,
+ onDismiss: () -> Unit,
+ onModeSelected: (CategorySortMode) -> Unit
+) {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ PremiumDialog(
+ title = categoryTypeLabel(type, context),
+ subtitle = categoryTypeDescription(type, context),
+ onDismissRequest = onDismiss,
+ widthFraction = 0.52f,
+ content = {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ CategorySortMode.entries.forEach { mode ->
+ Surface(
+ onClick = { onModeSelected(mode) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (mode == currentMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = Primary.copy(alpha = 0.28f)
+ ),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = formatCategorySortModeLabel(mode, context),
+ style = MaterialTheme.typography.titleSmall,
+ color = if (mode == currentMode) Primary else OnBackground
+ )
+ Text(
+ text = sortModeLabel(mode, context),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ },
+ footer = {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.settings_cancel),
+ onClick = onDismiss
+ )
+ }
+ )
+}
+
+@Composable
+private fun HiddenCategoriesDialog(
+ hiddenCategories: List<Category>,
+ onDismiss: () -> Unit,
+ onUnhide: (Category) -> Unit
+) {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ PremiumDialog(
+ title = stringResource(R.string.settings_hidden_categories_title),
+ subtitle = stringResource(R.string.settings_hidden_categories_subtitle),
+ onDismissRequest = onDismiss,
+ widthFraction = 0.58f,
+ content = {
+ if (hiddenCategories.isEmpty()) {
+ Text(
+ text = stringResource(R.string.settings_hidden_categories_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ } else {
+ LazyColumn(
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(max = 420.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ items(hiddenCategories, key = { "${it.type.name}:${it.id}" }) { category ->
+ Surface(
+ onClick = { onUnhide(category) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = Primary.copy(alpha = 0.22f)
+ ),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = category.name,
+ style = MaterialTheme.typography.titleSmall,
+ color = OnBackground
+ )
+ Text(
+ text = categoryTypeLabel(category.type, context),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ Text(
+ text = stringResource(R.string.settings_unhide_category),
+ style = MaterialTheme.typography.labelLarge,
+ color = Primary,
+ textAlign = TextAlign.End
+ )
+ }
+ }
+ }
+ }
+ }
+ },
+ footer = {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.action_done),
+ onClick = onDismiss
+ )
+ }
+ )
+}
+
@Composable
private fun ParentalControlCard(
level: Int,
@@ -2437,6 +2638,38 @@ private fun formatSpeedTestSummary(
}
}
+private fun sortModeLabel(mode: CategorySortMode, context: android.content.Context): String {
+ return when (mode) {
+ CategorySortMode.DEFAULT -> context.getString(R.string.settings_category_sort_default)
+ CategorySortMode.TITLE_ASC -> context.getString(R.string.settings_category_sort_az)
+ CategorySortMode.TITLE_DESC -> context.getString(R.string.settings_category_sort_za)
+ CategorySortMode.COUNT_DESC -> context.getString(R.string.settings_category_sort_most_items)
+ CategorySortMode.COUNT_ASC -> context.getString(R.string.settings_category_sort_least_items)
+ }
+}
+
+private fun formatCategorySortModeLabel(mode: CategorySortMode, context: android.content.Context): String {
+ return sortModeLabel(mode, context)
+}
+
+private fun categoryTypeLabel(type: ContentType, context: android.content.Context): String {
+ return when (type) {
+ ContentType.LIVE -> context.getString(R.string.settings_category_sort_live)
+ ContentType.MOVIE -> context.getString(R.string.settings_category_sort_movies)
+ ContentType.SERIES -> context.getString(R.string.settings_category_sort_series)
+ ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_sort_series)
+ }
+}
+
+private fun categoryTypeDescription(type: ContentType, context: android.content.Context): String {
+ return when (type) {
+ ContentType.LIVE -> context.getString(R.string.settings_category_type_live_description)
+ ContentType.MOVIE -> context.getString(R.string.settings_category_type_movies_description)
+ ContentType.SERIES -> context.getString(R.string.settings_category_type_series_description)
+ ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_type_series_description)
+ }
+}
+
private fun LiveTvChannelMode.labelResId(): Int = when (this) {
LiveTvChannelMode.COMFORTABLE -> R.string.settings_live_tv_mode_comfortable
LiveTvChannelMode.COMPACT -> R.string.settings_live_tv_mode_compact
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
index b38a5886..47344fc9 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
@@ -14,6 +14,9 @@ import com.streamvault.domain.manager.BackupImportPlan
import com.streamvault.domain.manager.BackupManager
import com.streamvault.domain.manager.BackupPreview
import com.streamvault.domain.manager.RecordingManager
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.CategorySortMode
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ProviderType
@@ -30,6 +33,7 @@ import com.streamvault.domain.usecase.ImportBackupResult
import com.streamvault.domain.usecase.InspectBackupCommand
import com.streamvault.domain.usecase.InspectBackupResult
import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.CategoryRepository
import com.streamvault.domain.repository.SyncMetadataRepository
import com.streamvault.domain.usecase.SyncProvider
import com.streamvault.domain.usecase.SyncProviderCommand
@@ -73,6 +77,7 @@ private data class SettingsPreferenceSnapshot(
class SettingsViewModel @Inject constructor(
application: Application,
private val providerRepository: ProviderRepository,
+ private val categoryRepository: CategoryRepository,
private val preferencesRepository: PreferencesRepository,
private val internetSpeedTestRunner: InternetSpeedTestRunner,
private val backupManager: BackupManager,
@@ -241,6 +246,56 @@ class SettingsViewModel @Inject constructor(
}
}
+ viewModelScope.launch {
+ preferencesRepository.lastActiveProviderId
+ .flatMapLatest { providerId ->
+ if (providerId == null) {
+ flowOf(CategoryManagementSnapshot())
+ } else {
+ combine(
+ preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE),
+ preferencesRepository.getCategorySortMode(providerId, ContentType.MOVIE),
+ preferencesRepository.getCategorySortMode(providerId, ContentType.SERIES),
+ categoryRepository.getCategories(providerId),
+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),
+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.MOVIE),
+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.SERIES)
+ ) { values ->
+ val liveSort = values[0] as CategorySortMode
+ val movieSort = values[1] as CategorySortMode
+ val seriesSort = values[2] as CategorySortMode
+ val categories = values[3] as List<Category>
+ val hiddenLive = values[4] as Set<Long>
+ val hiddenMovies = values[5] as Set<Long>
+ val hiddenSeries = values[6] as Set<Long>
+ val hiddenByType = mapOf(
+ ContentType.LIVE to hiddenLive,
+ ContentType.MOVIE to hiddenMovies,
+ ContentType.SERIES to hiddenSeries
+ )
+ CategoryManagementSnapshot(
+ categorySortModes = mapOf(
+ ContentType.LIVE to liveSort,
+ ContentType.MOVIE to movieSort,
+ ContentType.SERIES to seriesSort
+ ),
+ hiddenCategories = categories
+ .filter { category -> category.id in hiddenByType[category.type].orEmpty() }
+ .sortedWith(compareBy<Category>({ it.type.ordinal }, { it.name.lowercase() }))
+ )
+ }
+ }
+ }
+ .collect { snapshot ->
+ _uiState.update {
+ it.copy(
+ categorySortModes = snapshot.categorySortModes,
+ hiddenCategories = snapshot.hiddenCategories
+ )
+ }
+ }
+ }
+
viewModelScope.launch {
recordingManager.observeRecordingItems().collect { items ->
_uiState.update { it.copy(recordingItems = items.sortedByDescending(RecordingItem::scheduledStartMs)) }
@@ -281,6 +336,26 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun setCategorySortMode(type: ContentType, mode: CategorySortMode) {
+ val providerId = _uiState.value.activeProviderId ?: return
+ viewModelScope.launch {
+ preferencesRepository.setCategorySortMode(providerId, type, mode)
+ }
+ }
+
+ fun unhideCategory(category: Category) {
+ val providerId = _uiState.value.activeProviderId ?: return
+ viewModelScope.launch {
+ preferencesRepository.setCategoryHidden(
+ providerId = providerId,
+ type = category.type,
+ categoryId = category.id,
+ hidden = false
+ )
+ _uiState.update { it.copy(userMessage = "Unhid ${category.name}") }
+ }
+ }
+
fun setDefaultPlaybackSpeed(speed: Float) {
viewModelScope.launch {
preferencesRepository.setPlayerPlaybackSpeed(speed)
@@ -686,7 +761,9 @@ data class SettingsUiState(
val recordingItems: List<RecordingItem> = emptyList(),
val recordingStorageState: RecordingStorageState = RecordingStorageState(),
val isIncognitoMode: Boolean = false,
- val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMFORTABLE
+ val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMFORTABLE,
+ val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),
+ val hiddenCategories: List<Category> = emptyList()
)
data class InternetSpeedTestUiModel(
@@ -696,3 +773,8 @@ data class InternetSpeedTestUiModel(
val recommendedMaxVideoHeight: Int?,
val isEstimated: Boolean
)
+
+private data class CategoryManagementSnapshot(
+ val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),
+ val hiddenCategories: List<Category> = emptyList()
+)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
index 0c6add37..1d064110 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
@@ -17,9 +17,11 @@ suspend fun <Item> buildVodPreviewCatalog(
providerCategories: List<Category>,
providerCategoryCounts: Map<Long, Int>,
libraryCount: Int,
+ hiddenProviderCategoryIds: Set<Long>,
loadItemsByIds: suspend (List<Long>) -> List<Item>,
loadCategoryPreviewRows: suspend (Long, Int) -> Map<Long?, List<Item>>,
itemId: (Item) -> Long,
+ itemCategoryId: (Item) -> Long?,
copyWithFavorite: (Item, Boolean) -> Item
): VodCatalogSnapshot<Item> {
val globalFavoriteIds = allFavorites
@@ -38,6 +40,7 @@ suspend fun <Item> buildVodPreviewCatalog(
.toList()
if (favoritesIds.isNotEmpty()) {
val preview = loadItemsByIds(favoritesIds.take(VodBrowseDefaults.PREVIEW_ROW_LIMIT))
+ .filterNot { item -> itemCategoryId(item) in hiddenProviderCategoryIds }
.let { items -> markVodFavorites(items, globalFavoriteIds, itemId, copyWithFavorite) }
if (preview.isNotEmpty()) {
previewRows[VodBrowseDefaults.FAVORITES_CATEGORY] = preview
@@ -70,6 +73,7 @@ suspend fun <Item> buildVodPreviewCatalog(
customCategoryPreviewIds.forEach { (category, previewIds) ->
if (previewIds.isNotEmpty()) {
val preview = previewIds.mapNotNull(preloadedById::get)
+ .filterNot { item -> itemCategoryId(item) in hiddenProviderCategoryIds }
.let { items -> markVodFavorites(items, globalFavoriteIds, itemId, copyWithFavorite) }
if (preview.isNotEmpty()) {
previewRows[category.name] = preview
@@ -81,7 +85,6 @@ suspend fun <Item> buildVodPreviewCatalog(
val providerPreviews = loadCategoryPreviewRows(providerId, VodBrowseDefaults.PREVIEW_ROW_LIMIT)
providerCategories
- .sortedBy { it.name.lowercase() }
.forEach { category ->
val preview = providerPreviews[category.id].orEmpty()
.let { items -> markVodFavorites(items, globalFavoriteIds, itemId, copyWithFavorite) }
@@ -101,7 +104,10 @@ fun <Item> buildVodSearchCatalog(
items: List<Item>,
allFavorites: List<Favorite>,
customCategories: List<Category>,
+ providerCategories: List<Category>,
+ hiddenProviderCategoryIds: Set<Long>,
itemId: (Item) -> Long,
+ itemCategoryId: (Item) -> Long?,
itemCategoryName: (Item) -> String?,
copyWithFavorite: (Item, Boolean) -> Item,
uncategorizedName: String
@@ -111,7 +117,12 @@ fun <Item> buildVodSearchCatalog(
.filter { it.groupId == null }
.map(Favorite::contentId)
.toSet()
- val enrichedItems = markVodFavorites(items, globalFavoriteIds, itemId, copyWithFavorite)
+ val enrichedItems = markVodFavorites(
+ items.filterNot { item -> itemCategoryId(item) in hiddenProviderCategoryIds },
+ globalFavoriteIds,
+ itemId,
+ copyWithFavorite
+ )
val grouped = enrichedItems
.groupBy { itemCategoryName(it) ?: uncategorizedName }
.toMutableMap()
@@ -132,20 +143,31 @@ fun <Item> buildVodSearchCatalog(
}
val customNames = customCategories.map(Category::name).toSet()
- val categoryNames = grouped.keys.sortedWith(
- compareBy<String> {
- when (it) {
- VodBrowseDefaults.FAVORITES_CATEGORY -> 0
- in customNames -> 1
- else -> 2
+ val preferredProviderNames = providerCategories.map(Category::name)
+ val orderedNames = buildList {
+ if (grouped.containsKey(VodBrowseDefaults.FAVORITES_CATEGORY)) {
+ add(VodBrowseDefaults.FAVORITES_CATEGORY)
+ }
+ customCategories.forEach { category ->
+ if (grouped.containsKey(category.name)) {
+ add(category.name)
}
- }.thenBy { it }
- )
+ }
+ preferredProviderNames.forEach { categoryName ->
+ if (grouped.containsKey(categoryName)) {
+ add(categoryName)
+ }
+ }
+ grouped.keys
+ .filterNot { it == VodBrowseDefaults.FAVORITES_CATEGORY || it in customNames || it in preferredProviderNames }
+ .sortedBy { it.lowercase() }
+ .forEach(::add)
+ }
return VodCatalogSnapshot(
grouped = grouped,
- categoryNames = categoryNames,
- categoryCounts = categoryNames.associateWith { name -> grouped[name]?.size ?: 0 },
+ categoryNames = orderedNames,
+ categoryCounts = orderedNames.associateWith { name -> grouped[name]?.size ?: 0 },
libraryCount = items.size
)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt
index cd2c4ac0..39c6f372 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodFavoriteHelpers.kt
@@ -1,6 +1,8 @@
package com.streamvault.app.ui.screens.vod
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.VirtualGroup
import com.streamvault.domain.repository.FavoriteRepository
data class VodDialogSelection<T>(
@@ -56,6 +58,5 @@ suspend fun createVodGroup(
name: String,
contentType: ContentType,
favoriteRepository: FavoriteRepository
-) {
+): Result<VirtualGroup> =
favoriteRepository.createGroup(name, contentType = contentType)
-}
\ No newline at end of file
diff --git a/app/src/main/java/com/streamvault/app/util/PlaybackCompletion.kt b/app/src/main/java/com/streamvault/app/util/PlaybackCompletion.kt
new file mode 100644
index 00000000..0178bf22
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/util/PlaybackCompletion.kt
@@ -0,0 +1,12 @@
+package com.streamvault.app.util
+
+private const val DEFAULT_PLAYBACK_COMPLETION_THRESHOLD = 0.95f
+
+fun isPlaybackComplete(
+ progressMs: Long,
+ totalDurationMs: Long,
+ threshold: Float = DEFAULT_PLAYBACK_COMPLETION_THRESHOLD
+): Boolean {
+ if (progressMs <= 0L || totalDurationMs <= 0L) return false
+ return progressMs >= (totalDurationMs * threshold).toLong()
+}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index c8885030..e0c3af80 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -117,6 +117,7 @@
<string name="category_options_delete">Delete Group</string>
<string name="category_options_cancel">Cancel</string>
<string name="category_options_reorder">Reorder Items</string>
+ <string name="category_options_hide">Hide Category</string>
<string name="add_group_manage_title">Manage: %1$s</string>
<string name="add_group_close_cd">Close</string>
@@ -236,6 +237,25 @@
<string name="settings_parental_groups_title">Protected Groups</string>
<string name="settings_parental_groups_hint">Lock or unlock categories for the active provider.</string>
<string name="settings_parental_groups_action">Manage</string>
+ <string name="settings_categories_title">Category Preferences</string>
+ <string name="settings_categories_subtitle">Hide provider categories and keep their sort order exactly how you want it.</string>
+ <string name="settings_category_sort_live">Live TV Categories</string>
+ <string name="settings_category_sort_movies">Movie Categories</string>
+ <string name="settings_category_sort_series">Series Categories</string>
+ <string name="settings_hidden_categories_title">Hidden Categories</string>
+ <string name="settings_hidden_categories_subtitle">Restore any provider categories you previously hid from browsing surfaces.</string>
+ <string name="settings_hidden_categories_none">None hidden</string>
+ <string name="settings_hidden_categories_count">%1$d hidden</string>
+ <string name="settings_hidden_categories_empty">No hidden categories right now.</string>
+ <string name="settings_unhide_category">Unhide</string>
+ <string name="settings_category_sort_default">Provider Order</string>
+ <string name="settings_category_sort_az">A-Z</string>
+ <string name="settings_category_sort_za">Z-A</string>
+ <string name="settings_category_sort_most_items">Most Items First</string>
+ <string name="settings_category_sort_least_items">Least Items First</string>
+ <string name="settings_category_type_live_description">Sort and hide provider live groups while keeping All Channels, Favorites, Recent, and custom groups in their pinned positions.</string>
+ <string name="settings_category_type_movies_description">Sort and hide provider movie categories without affecting Favorites, Resume, or custom shelves.</string>
+ <string name="settings_category_type_series_description">Sort and hide provider series categories without affecting Favorites, Continue Watching, or custom shelves.</string>
<string name="settings_playback">Playback</string>
<string name="settings_playback_subtitle">Tune decoder and buffering behavior for smoother playback.</string>
<string name="settings_live_tv_channel_mode">Live TV Channel Mode</string>
@@ -560,7 +580,7 @@
<string name="player_error_unknown">Unknown playback error</string>
<string name="player_retry">Retry</string>
<string name="player_last_channel_action">Last Channel</string>
- <string name="player_try_alternate_stream">Alternate Stream</string>
+ <string name="player_try_alternate_stream">Try another path</string>
<string name="player_open_guide_action">Open Guide</string>
<string name="player_error_back">Or press Back to return</string>
<string name="player_error_live_hint">Retry, jump back to the last channel, or press Back to leave playback.</string>
@@ -669,10 +689,18 @@
<string name="epg_error">Unable to load the TV guide right now.</string>
<string name="epg_no_provider">Add or activate a provider to view the TV guide.</string>
<string name="epg_no_schedule">No schedule data available</string>
+ <string name="epg_no_schedule_short">No schedule</string>
<string name="epg_watch_live">Watch Live</string>
<string name="epg_watch_archive">Play Catch-up</string>
+ <string name="epg_show_app_navigation">Show App Nav</string>
+ <string name="epg_program_details_show">Program Details</string>
+ <string name="epg_program_details_hide">Hide Details</string>
+ <string name="epg_hero_no_schedule_hint">This channel has no guide entries in the current window.</string>
+ <string name="epg_hero_no_program_description">Program details are limited for this entry.</string>
<string name="epg_filter_label">Guide Filter</string>
+ <string name="epg_filter_short">Categories</string>
<string name="epg_search_label">Program Search</string>
+ <string name="epg_search_short">Program Search</string>
<string name="epg_search_placeholder">Search titles in the current guide window...</string>
<string name="epg_clear_search">Clear Search</string>
<string name="epg_time_controls">Guide Window</string>
@@ -719,14 +747,17 @@
<string name="epg_view_scheduled_only_hint">Hide channels with no guide data</string>
<string name="epg_show_options">Show guide options</string>
<string name="epg_hide_options">Hide guide options</string>
+ <string name="epg_options_short">Options</string>
<string name="epg_showing_channels">Showing %1$d of %2$d channels</string>
<string name="epg_schedule_summary">Guide data available on %1$d of %2$d channels</string>
+ <string name="epg_schedule_summary_short">%1$d/%2$d with guide</string>
<string name="epg_window_label">%1$s - %2$s</string>
<string name="epg_timeline_label">Timeline</string>
<string name="epg_now_marker">Now %1$s</string>
<string name="epg_outside_window">Now outside loaded window</string>
<string name="epg_timeline_range_label">%1$s window</string>
<string name="epg_stale_warning">Guide data looks incomplete or stale for this selection.</string>
+ <string name="epg_stale_short">Guide may be stale</string>
<string name="epg_updated_now">Updated just now</string>
<string name="epg_updated_minutes_ago">Updated %1$d min ago</string>
<string name="epg_retry">Retry</string>
@@ -785,6 +816,7 @@
<string name="movie_not_found">Movie not found</string>
<string name="movie_detail_back">Back to library</string>
<string name="movie_detail_play">Play</string>
+ <string name="movie_detail_trailer">Trailer</string>
<string name="movie_plot_fallback">No plot available</string>
<string name="movie_detail_director">Directed By:</string>
<string name="movie_detail_release_date">Release Date:</string>
diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
index 18354bb2..798827f9 100644
--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
@@ -608,7 +608,7 @@ interface EpisodeDao {
@Dao
interface CategoryDao {
- @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY name ASC")
+ @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY id ASC")
fun getByProviderAndType(providerId: Long, type: String): Flow<List<CategoryEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
@@ -650,7 +650,10 @@ interface ProgramDao {
FROM programs
INNER JOIN channels
ON channels.provider_id = programs.provider_id
- AND channels.epg_channel_id = programs.channel_id
+ AND (
+ channels.epg_channel_id = programs.channel_id
+ OR CAST(channels.stream_id AS TEXT) = programs.channel_id
+ )
WHERE programs.provider_id = :providerId
AND channels.category_id = :categoryId
AND programs.end_time > :startTime
@@ -676,7 +679,10 @@ interface ProgramDao {
OR EXISTS (
SELECT 1 FROM channels
WHERE channels.provider_id = programs.provider_id
- AND channels.epg_channel_id = programs.channel_id
+ AND (
+ channels.epg_channel_id = programs.channel_id
+ OR CAST(channels.stream_id AS TEXT) = programs.channel_id
+ )
AND channels.category_id = :categoryId
)
)
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index 0e280b58..02272ef8 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -14,6 +14,8 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.streamvault.data.local.dao.ChannelPreferenceDao
import com.streamvault.data.local.entity.ChannelPreferenceEntity
+import com.streamvault.domain.model.CategorySortMode
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.manager.ParentalPinVerifier
import com.streamvault.domain.manager.ParentalControlSessionState
import com.streamvault.domain.manager.ParentalControlSessionStore
@@ -537,6 +539,59 @@ class PreferencesRepository @Inject constructor(
}
}
+ fun getHiddenCategoryIds(providerId: Long, type: ContentType): Flow<Set<Long>> {
+ val key = stringPreferencesKey(hiddenCategoriesKey(providerId, type))
+ return context.dataStore.data.map { preferences ->
+ preferences[key]
+ ?.split(',')
+ ?.mapNotNull { token -> token.toLongOrNull() }
+ ?.toSet()
+ .orEmpty()
+ }
+ }
+
+ suspend fun setCategoryHidden(
+ providerId: Long,
+ type: ContentType,
+ categoryId: Long,
+ hidden: Boolean
+ ) {
+ val key = stringPreferencesKey(hiddenCategoriesKey(providerId, type))
+ context.dataStore.edit { preferences ->
+ val current = preferences[key]
+ ?.split(',')
+ ?.mapNotNull { token -> token.toLongOrNull() }
+ ?.toMutableSet()
+ ?: mutableSetOf()
+ if (hidden) {
+ current += categoryId
+ } else {
+ current -= categoryId
+ }
+ if (current.isEmpty()) {
+ preferences.remove(key)
+ } else {
+ preferences[key] = current.sorted().joinToString(",")
+ }
+ }
+ }
+
+ fun getCategorySortMode(providerId: Long, type: ContentType): Flow<CategorySortMode> {
+ val key = stringPreferencesKey(categorySortModeKey(providerId, type))
+ return context.dataStore.data.map { preferences ->
+ preferences[key]
+ ?.let { saved -> CategorySortMode.entries.firstOrNull { it.name == saved } }
+ ?: CategorySortMode.DEFAULT
+ }
+ }
+
+ suspend fun setCategorySortMode(providerId: Long, type: ContentType, mode: CategorySortMode) {
+ val key = stringPreferencesKey(categorySortModeKey(providerId, type))
+ context.dataStore.edit { preferences ->
+ preferences[key] = mode.name
+ }
+ }
+
fun getMultiViewPreset(presetIndex: Int): Flow<List<Long>> {
val key = when (presetIndex) {
0 -> PreferencesKeys.MULTIVIEW_PRESET_1
@@ -625,6 +680,12 @@ class PreferencesRepository @Inject constructor(
return java.util.Base64.getEncoder().encodeToString(secret.encoded)
}
+ private fun hiddenCategoriesKey(providerId: Long, type: ContentType): String =
+ "hidden_categories_${providerId}_${type.name}"
+
+ private fun categorySortModeKey(providerId: Long, type: ContentType): String =
+ "category_sort_${providerId}_${type.name}"
+
private fun isPinLockedOut(nowMs: Long = System.currentTimeMillis()): Boolean {
val lockoutUntilMs = parentalSessionPreferences.getLong(ParentalSessionKeys.PIN_LOCKOUT_UNTIL_MS, 0L)
if (lockoutUntilMs <= nowMs) {
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index f19d2f1b..1057c73e 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -24,7 +24,6 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.repository.MovieRepository
-import com.streamvault.domain.util.isPlaybackComplete
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
@@ -242,7 +241,7 @@ class MovieRepositoryImpl @Inject constructor(
val inProgressIds = history
.asSequence()
.filter { it.contentType == ContentType.MOVIE }
- .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !isPlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
+ .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !moviePlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
.map { it.contentId }
.toSet()
val watchCounts = history
@@ -292,8 +291,49 @@ class MovieRepositoryImpl @Inject constructor(
movieDao.getById(movieId)?.toDomain()
override suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie> {
- val movie = movieDao.getById(movieId)?.toDomain()
- return if (movie != null) Result.success(movie) else Result.error("Movie not found")
+ val movieEntity = movieDao.getById(movieId)
+ ?: return Result.error("Movie not found")
+
+ val provider = providerDao.getById(providerId)
+ ?: return Result.error("Provider not found")
+
+ if (provider.type != ProviderType.XTREAM_CODES) {
+ return Result.success(movieEntity.toDomain())
+ }
+
+ val xtreamProvider = try {
+ getOrCreateXtreamProvider(providerId, provider)
+ } catch (e: Exception) {
+ return Result.success(movieEntity.toDomain())
+ }
+
+ return when (val remoteResult = xtreamProvider.getVodInfo(movieEntity.streamId)) {
+ is Result.Success -> {
+ val remoteMovie = remoteResult.data
+ val updatedMovie = movieEntity.copy(
+ name = remoteMovie.name.ifBlank { movieEntity.name },
+ posterUrl = remoteMovie.posterUrl ?: movieEntity.posterUrl,
+ backdropUrl = remoteMovie.backdropUrl ?: movieEntity.backdropUrl,
+ categoryId = remoteMovie.categoryId ?: movieEntity.categoryId,
+ categoryName = remoteMovie.categoryName ?: movieEntity.categoryName,
+ plot = remoteMovie.plot ?: movieEntity.plot,
+ cast = remoteMovie.cast ?: movieEntity.cast,
+ director = remoteMovie.director ?: movieEntity.director,
+ genre = remoteMovie.genre ?: movieEntity.genre,
+ releaseDate = remoteMovie.releaseDate ?: movieEntity.releaseDate,
+ duration = remoteMovie.duration ?: movieEntity.duration,
+ durationSeconds = remoteMovie.durationSeconds.takeIf { it > 0 } ?: movieEntity.durationSeconds,
+ rating = if (remoteMovie.rating > 0f) remoteMovie.rating else movieEntity.rating,
+ year = remoteMovie.year ?: movieEntity.year,
+ tmdbId = remoteMovie.tmdbId ?: movieEntity.tmdbId,
+ youtubeTrailer = remoteMovie.youtubeTrailer ?: movieEntity.youtubeTrailer
+ )
+ movieDao.update(updatedMovie)
+ Result.success((movieDao.getById(movieEntity.id) ?: updatedMovie).toDomain())
+ }
+ is Result.Error -> Result.success(movieEntity.toDomain())
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
}
override suspend fun getStreamInfo(movie: Movie): Result<StreamInfo> = try {
@@ -524,7 +564,7 @@ class MovieRepositoryImpl @Inject constructor(
private fun movieIsInProgress(movie: Movie): Boolean {
if (movie.watchProgress <= 0L) return false
val totalDurationMs = movie.durationSeconds.takeIf { it > 0 }?.times(1000L) ?: 0L
- return !isPlaybackComplete(movie.watchProgress, totalDurationMs)
+ return !moviePlaybackComplete(movie.watchProgress, totalDurationMs)
}
private fun movieReleaseScore(movie: Movie): Long =
@@ -555,4 +595,9 @@ class MovieRepositoryImpl @Inject constructor(
}
}!!.provider
}
+
+ private fun moviePlaybackComplete(progressMs: Long, totalDurationMs: Long): Boolean {
+ if (progressMs <= 0L || totalDurationMs <= 0L) return false
+ return progressMs >= (totalDurationMs * 0.95f).toLong()
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 864d0ec5..faf7331a 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -2219,7 +2219,6 @@ class SyncManager @Inject constructor(
)
}
.distinctBy { it.categoryId }
- .sortedBy { it.name.lowercase() }
.toList()
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/CategorySortMode.kt b/domain/src/main/java/com/streamvault/domain/model/CategorySortMode.kt
new file mode 100644
index 00000000..2d1e4b1a
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/CategorySortMode.kt
@@ -0,0 +1,9 @@
+package com.streamvault.domain.model
+
+enum class CategorySortMode {
+ DEFAULT,
+ TITLE_ASC,
+ TITLE_DESC,
+ COUNT_DESC,
+ COUNT_ASC
+}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index ed602e10..cd377b8b 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -1,68 +1,67 @@
package com.streamvault.player
import android.content.Context
-import android.media.AudioFocusRequest
-import android.media.AudioManager
-import android.net.Uri
-import android.net.ConnectivityManager
-import android.net.NetworkCapabilities
-import android.os.Build
-import android.graphics.Color as AndroidColor
-import android.view.LayoutInflater
-import android.view.View
+import android.os.Handler
+import android.util.Log
import androidx.annotation.OptIn
+import androidx.media3.common.AudioAttributes as Media3AudioAttributes
import androidx.media3.common.C
-import androidx.media3.common.MediaItem
-import androidx.media3.common.PlaybackParameters
+import androidx.media3.common.Format
import androidx.media3.common.PlaybackException
+import androidx.media3.common.PlaybackParameters
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
-import androidx.media3.datasource.DataSource
-import androidx.media3.datasource.okhttp.OkHttpDataSource
+import androidx.media3.exoplayer.DecoderReuseEvaluation
+import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
+import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.ScrubbingModeParameters
-import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
+import androidx.media3.exoplayer.analytics.AnalyticsListener
import androidx.media3.exoplayer.mediacodec.MediaCodecInfo
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
-import androidx.media3.exoplayer.dash.DashMediaSource
-import androidx.media3.exoplayer.hls.HlsMediaSource
-import androidx.media3.exoplayer.rtsp.RtspMediaSource
-import androidx.media3.exoplayer.source.MediaSource
-import androidx.media3.exoplayer.source.ProgressiveMediaSource
-import androidx.media3.exoplayer.analytics.AnalyticsListener
-import androidx.media3.exoplayer.DecoderReuseEvaluation
-
-import androidx.media3.ui.AspectRatioFrameLayout
-import androidx.media3.ui.CaptionStyleCompat
-import androidx.media3.ui.PlayerView
-import androidx.media3.ui.SubtitleView
-import androidx.media3.common.Format
import androidx.media3.session.MediaSession
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.StreamInfo
-import com.streamvault.domain.model.StreamType
import com.streamvault.domain.model.VideoFormat
-import androidx.media3.exoplayer.DefaultLoadControl
-import androidx.media3.common.AudioAttributes as Media3AudioAttributes
-import android.os.Handler
-import android.os.Looper
-import android.os.SystemClock
-import android.util.Log
-import com.streamvault.domain.model.DrmInfo
-import com.streamvault.domain.model.DrmScheme
+import com.streamvault.player.audio.PlayerAudioFocusController
+import com.streamvault.player.playback.DefaultDecoderPreferencePolicy
+import com.streamvault.player.playback.DefaultPlaybackCompatibilityProfile
+import com.streamvault.player.playback.PlaybackCompatibilityProfile
+import com.streamvault.player.playback.PlaybackErrorCategory
+import com.streamvault.player.playback.PlaybackLogSanitizer
+import com.streamvault.player.playback.PlaybackRetryContext
+import com.streamvault.player.playback.PlayerDataSourceFactoryProvider
+import com.streamvault.player.playback.PlayerErrorClassifier
+import com.streamvault.player.playback.PlayerMediaSourceFactory
+import com.streamvault.player.playback.PlayerRetryPolicy
+import com.streamvault.player.playback.PlayerTimeoutProfile
+import com.streamvault.player.playback.PreloadCoordinator
+import com.streamvault.player.playback.ResolvedStreamType
+import com.streamvault.player.playback.StreamTypeResolver
+import com.streamvault.player.stats.PlayerStatsCollector
+import com.streamvault.player.tracks.PlayerTrackController
+import com.streamvault.player.ui.PlayerViewBinder
+import com.streamvault.player.ui.SubtitleStyleController
import dagger.hilt.android.qualifiers.ApplicationContext
-import kotlinx.coroutines.*
-import kotlinx.coroutines.flow.*
-import kotlin.math.abs
-import okhttp3.OkHttpClient
import javax.inject.Inject
-import javax.inject.Singleton
-import java.util.Locale
-import java.util.UUID
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import okhttp3.OkHttpClient
@OptIn(UnstableApi::class)
class Media3PlayerEngine @Inject constructor(
@@ -70,96 +69,33 @@ class Media3PlayerEngine @Inject constructor(
private val okHttpClient: OkHttpClient
) : PlayerEngine {
- private var supervisorJob = SupervisorJob()
- private var scope = CoroutineScope(Dispatchers.Main + supervisorJob)
- private var exoPlayer: ExoPlayer? = null
- private var mediaSession: MediaSession? = null
- private var currentDecoderMode: DecoderMode = DecoderMode.AUTO
- /**
- * When true the track selector caps video at 720p.
- * Set to true for multi-view slots so each instance doesn't compete for 4K bandwidth.
- */
+ companion object {
+ private const val TAG = "Media3PlayerEngine"
+ }
+
var constrainResolutionForMultiView: Boolean = false
- /**
- * Multi-view slots should not compete for global audio focus; only the audible slot needs volume.
- */
var bypassAudioFocus: Boolean = false
- /**
- * Auxiliary players do not need MediaSession registration.
- */
- var enableMediaSession: Boolean = true
- private var pollingJob: Job? = null
- private var lastStreamInfo: StreamInfo? = null
- private var retryCount = 0
- private var lastFrameRate: Float = 0f
- private val handler = Handler(Looper.getMainLooper())
- private var lastBandwidthStatsUpdateMs: Long = 0L
- private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
- private var audioFocusRequest: AudioFocusRequest? = null
- private var hasAudioFocus = false
- private var shouldResumeOnAudioFocusGain = false
- private var currentVolume = 1f
- private var isDucked = false
- private var preferredAudioLanguageTag: String? = null
- private var subtitleStyle: PlayerSubtitleStyle = PlayerSubtitleStyle()
- private var selectedVideoTrackId: String = PLAYER_TRACK_AUTO_ID
- private var preferredWifiMaxVideoHeight: Int? = null
- private var preferredEthernetMaxVideoHeight: Int? = null
- private var boundPlayerView: PlayerView? = null
- /** Tracks the last video width/height so we can detect actual resolution changes. */
- private var lastVideoWidth = 0
- private var lastVideoHeight = 0
- /** Remembers the volume before mute so unmute restores it. */
- private var volumeBeforeMute = 1f
- /** Pre-warmed media source for rapid next-channel start. */
- private var preloadedSource: MediaSource? = null
- private var preloadedStreamInfo: StreamInfo? = null
-
- private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
- when (focusChange) {
- AudioManager.AUDIOFOCUS_GAIN -> {
- hasAudioFocus = true
- isDucked = false
- applyPlayerVolume()
- if (shouldResumeOnAudioFocusGain) {
- shouldResumeOnAudioFocusGain = false
- exoPlayer?.playWhenReady = true
- }
- }
-
- AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
- isDucked = true
- applyPlayerVolume()
- }
-
- AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
- hasAudioFocus = false
- isDucked = false
- shouldResumeOnAudioFocusGain = exoPlayer?.isPlaying == true
- exoPlayer?.playWhenReady = false
- applyPlayerVolume()
- }
-
- AudioManager.AUDIOFOCUS_LOSS -> {
- hasAudioFocus = false
- isDucked = false
- shouldResumeOnAudioFocusGain = false
- exoPlayer?.playWhenReady = false
- applyPlayerVolume()
- }
+ set(value) {
+ field = value
+ audioFocusController.bypassAudioFocus = value
}
- }
+ var enableMediaSession: Boolean = true
- companion object {
- private const val TAG = "Media3PlayerEngine"
- private const val MAX_RETRIES = 3
- private const val RETRY_BASE_DELAY_MS = 3000L
- private const val BANDWIDTH_STATS_MIN_INTERVAL_MS = 1500L
- private const val BUFFERED_DURATION_PUBLISH_STEP_MS = 1000L
- private const val PLAYBACK_CONNECT_TIMEOUT_SECONDS = 15L
- private const val PLAYBACK_READ_TIMEOUT_SECONDS = 30L
- private const val PLAYBACK_WRITE_TIMEOUT_SECONDS = 30L
- }
+ private var supervisorJob = SupervisorJob()
+ private var scope = CoroutineScope(Dispatchers.Main.immediate + supervisorJob)
+ private var exoPlayer: ExoPlayer? = null
+ private var mediaSession: MediaSession? = null
+ private var requestedDecoderMode: DecoderMode = DecoderMode.AUTO
+ private var activeDecoderMode: DecoderMode = DecoderMode.HARDWARE
+ private var lastStreamInfo: StreamInfo? = null
+ private var lastMediaId: String? = null
+ private var currentResolvedStreamType: ResolvedStreamType = ResolvedStreamType.UNKNOWN
+ private var currentTimeoutProfile: PlayerTimeoutProfile = PlayerTimeoutProfile.VOD
+ private var currentRetryPolicy: PlayerRetryPolicy? = null
+ private var currentRetryContext: PlaybackRetryContext? = null
+ private var playbackStarted = false
+ private var retryAttempt = 0
+ private var retryJob: Job? = null
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
override val playbackState: StateFlow<PlaybackState> = _playbackState.asStateFlow()
@@ -182,526 +118,65 @@ class Media3PlayerEngine @Inject constructor(
private val _retryStatus = MutableStateFlow<PlayerRetryStatus?>(null)
override val retryStatus: StateFlow<PlayerRetryStatus?> = _retryStatus.asStateFlow()
- private val _availableAudioTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
- override val availableAudioTracks: StateFlow<List<PlayerTrack>> = _availableAudioTracks.asStateFlow()
-
- private val _availableSubtitleTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
- override val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = _availableSubtitleTracks.asStateFlow()
-
- private val _availableVideoTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
- override val availableVideoTracks: StateFlow<List<PlayerTrack>> = _availableVideoTracks.asStateFlow()
-
private val _playbackSpeed = MutableStateFlow(1f)
override val playbackSpeed: StateFlow<Float> = _playbackSpeed.asStateFlow()
private val _playerStats = MutableStateFlow(PlayerStats())
override val playerStats: StateFlow<PlayerStats> = _playerStats.asStateFlow()
- private val _isMuted = MutableStateFlow(false)
- override val isMuted: StateFlow<Boolean> = _isMuted.asStateFlow()
-
private val _mediaTitle = MutableStateFlow<String?>(null)
override val mediaTitle: StateFlow<String?> = _mediaTitle.asStateFlow()
- private fun effectiveVolume(): Float {
- return when {
- _isMuted.value -> 0f
- isDucked -> (currentVolume * 0.2f).coerceAtLeast(0.05f)
- else -> currentVolume
- }
- }
-
- private fun resolvedMaxVideoHeightForCurrentNetwork(): Int? {
- val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
- val network = connectivityManager?.activeNetwork ?: return null
- val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return null
- val networkPreference = when {
- capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> preferredEthernetMaxVideoHeight
- capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> preferredWifiMaxVideoHeight
- else -> null
- }
- return when {
- constrainResolutionForMultiView && networkPreference != null -> minOf(720, networkPreference)
- constrainResolutionForMultiView -> 720
- else -> networkPreference
- }
- }
-
- private fun applyPlayerVolume() {
- exoPlayer?.volume = effectiveVolume()
- }
-
-
-
- private fun getOrCreatePlayer(): ExoPlayer {
- return exoPlayer ?: createPlayer().also {
- exoPlayer = it
- if (enableMediaSession) {
- mediaSession = MediaSession.Builder(context, it).build()
- }
- }
- }
-
- private fun createPlayer(): ExoPlayer {
- val renderersFactory = (if (shouldDisableVideoDecoderReuseWorkaround()) {
- // Some emulator-style decoders still misbehave during ABR reuse. Keep the
- // workaround there, but let real devices reuse decoders for smoother playback.
- object : DefaultRenderersFactory(context) {
- override fun buildVideoRenderers(
- context: Context,
- extensionRendererMode: Int,
- mediaCodecSelector: MediaCodecSelector,
- enableDecoderFallback: Boolean,
- eventHandler: Handler,
- eventListener: VideoRendererEventListener,
- allowedVideoJoiningTimeMs: Long,
- out: ArrayList<Renderer>
- ) {
- out.add(object : MediaCodecVideoRenderer(
- context,
- mediaCodecSelector,
- allowedVideoJoiningTimeMs,
- enableDecoderFallback,
- eventHandler,
- eventListener,
- 50 // MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY
- ) {
- override fun canReuseCodec(
- codecInfo: MediaCodecInfo,
- oldFormat: Format,
- newFormat: Format
- ): DecoderReuseEvaluation {
- Log.w(TAG, "DECODER_NO_REUSE: ${oldFormat.width}x${oldFormat.height}@${oldFormat.bitrate} -> ${newFormat.width}x${newFormat.height}@${newFormat.bitrate}")
- return DecoderReuseEvaluation(
- codecInfo.name,
- oldFormat,
- newFormat,
- DecoderReuseEvaluation.REUSE_RESULT_NO,
- DecoderReuseEvaluation.DISCARD_REASON_MAX_INPUT_SIZE_EXCEEDED
- )
- }
- })
- }
- }
- } else {
- DefaultRenderersFactory(context)
- }).apply {
- setExtensionRendererMode(
- when (currentDecoderMode) {
- DecoderMode.AUTO -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
- DecoderMode.HARDWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
- DecoderMode.SOFTWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF
- }
- )
- }
-
- // Slightly longer live buffers trade a bit of zap speed for better stability on
- // inconsistent IPTV segments, which reduces stutter and audio underruns.
- val loadControl = DefaultLoadControl.Builder()
- .setBufferDurationsMs(
- 30_000,
- 90_000,
- 2_500,
- 10_000
- )
- .setPrioritizeTimeOverSizeThresholds(true)
- .build()
-
- // Some live IPTV manifests drift around the live edge. Keeping live-speed correction
- // pinned at 1.0x avoids pitchy/crackly audio from subtle speed hunting.
- val livePlaybackSpeedControl = DefaultLivePlaybackSpeedControl.Builder()
- .setFallbackMinPlaybackSpeed(1.0f)
- .setFallbackMaxPlaybackSpeed(1.0f)
- .build()
-
- val trackSelector = androidx.media3.exoplayer.trackselection.DefaultTrackSelector(context).apply {
- if (constrainResolutionForMultiView) {
- parameters = parameters.buildUpon()
- .setMaxVideoSize(1280, 720) // Multi-view: cap each slot at 720p
- .build()
- }
- }
-
- return ExoPlayer.Builder(context, renderersFactory)
- .setTrackSelector(trackSelector)
- .setLoadControl(loadControl)
- .setLivePlaybackSpeedControl(livePlaybackSpeedControl)
- .setSeekBackIncrementMs(10_000)
- .setSeekForwardIncrementMs(10_000)
- .setAudioAttributes(
- Media3AudioAttributes.Builder()
- .setUsage(C.USAGE_MEDIA)
- .setContentType(C.AUDIO_CONTENT_TYPE_UNKNOWN)
- .build(),
- false // Explicitly managed via AudioManager below.
- )
- .build()
- .apply {
- videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
- playbackParameters = PlaybackParameters(_playbackSpeed.value)
- trackSelectionParameters = trackSelectionParameters
- .buildUpon()
- .setPreferredAudioLanguage(preferredAudioLanguageTag)
- .build()
- addAnalyticsListener(object : AnalyticsListener {
- override fun onVideoInputFormatChanged(
- eventTime: AnalyticsListener.EventTime,
- format: Format,
- decoderReuseEvaluation: DecoderReuseEvaluation?
- ) {
- decoderReuseEvaluation?.let { eval ->
- Log.d(TAG, "Decoder reuse eval: result=${eval.result}, discardReasons=${eval.discardReasons}")
- }
- lastFrameRate = format.frameRate.takeIf { it > 0f } ?: lastFrameRate
- _playerStats.update {
- it.copy(
- videoCodec = format.sampleMimeType ?: format.codecs ?: it.videoCodec,
- videoBitrate = format.bitrate.takeIf { b -> b > 0 } ?: it.videoBitrate,
- width = format.width.takeIf { w -> w > 0 } ?: it.width,
- height = format.height.takeIf { h -> h > 0 } ?: it.height
- )
- }
- }
-
- override fun onAudioInputFormatChanged(
- eventTime: AnalyticsListener.EventTime,
- format: Format,
- decoderReuseEvaluation: DecoderReuseEvaluation?
- ) {
- _playerStats.update {
- it.copy(
- audioCodec = format.sampleMimeType ?: format.codecs ?: it.audioCodec
- )
- }
- }
-
- override fun onRenderedFirstFrame(
- eventTime: AnalyticsListener.EventTime,
- output: Any,
- renderTimeMs: Long
- ) { /* no-op */ }
-
- override fun onDroppedVideoFrames(
- eventTime: AnalyticsListener.EventTime,
- droppedFrames: Int,
- elapsedMs: Long
- ) {
- _playerStats.update {
- it.copy(droppedFrames = it.droppedFrames + droppedFrames)
- }
- }
-
- override fun onBandwidthEstimate(
- eventTime: AnalyticsListener.EventTime,
- totalLoadTimeMs: Int,
- totalBytesLoaded: Long,
- bitrateEstimate: Long
- ) {
- val now = SystemClock.elapsedRealtime()
- updatePlayerStats { current ->
- if (!shouldPublishBandwidthEstimate(current.bandwidthEstimate, bitrateEstimate, now)) {
- current
- } else {
- lastBandwidthStatsUpdateMs = now
- current.copy(bandwidthEstimate = bitrateEstimate)
- }
- }
- }
- })
- addListener(object : Player.Listener {
- override fun onPlaybackStateChanged(state: Int) {
- val newState = when (state) {
- Player.STATE_IDLE -> PlaybackState.IDLE
- Player.STATE_BUFFERING -> {
- // Track rebuffering: BUFFERING after READY = rebuffer event
- if (_playbackState.value == PlaybackState.READY) {
- _playerStats.update { it.copy(rebufferCount = it.rebufferCount + 1) }
- }
- PlaybackState.BUFFERING
- }
- Player.STATE_READY -> PlaybackState.READY
- Player.STATE_ENDED -> PlaybackState.ENDED
- else -> PlaybackState.IDLE
- }
- _playbackState.value = newState
- if (newState == PlaybackState.READY) {
- _retryStatus.value = null
- }
- }
-
- override fun onIsPlayingChanged(playing: Boolean) {
- _isPlaying.value = playing
- if (playing) {
- startPolling()
- } else {
- stopPolling()
- }
- }
-
- override fun onVideoSizeChanged(videoSize: androidx.media3.common.VideoSize) {
- Log.d(TAG, "VIDEO_SIZE_CHANGED: ${videoSize.width}x${videoSize.height} (was ${lastVideoWidth}x${lastVideoHeight})")
- _videoFormat.value = VideoFormat(
- width = videoSize.width,
- height = videoSize.height,
- frameRate = lastFrameRate
- )
- if (videoSize.width > 0 && videoSize.height > 0) {
- lastVideoWidth = videoSize.width
- lastVideoHeight = videoSize.height
- }
- }
-
- override fun onPlayerError(error: PlaybackException) {
- // Behind-live-window: just seek to the live edge — no retry counter needed
- if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) {
- Log.w(TAG, "Behind live window — seeking to live edge")
- exoPlayer?.let { p ->
- p.seekToDefaultPosition()
- p.prepare()
- }
- return
- }
- if (retryCount < MAX_RETRIES && isRecoverableError(error)) {
- retryCount++
- Log.w(TAG, "Recoverable error (attempt $retryCount/$MAX_RETRIES), retrying...")
- val streamInfoSnapshot = lastStreamInfo
- _playerStats.update { it.copy(droppedFrames = 0) }
- _retryStatus.value = PlayerRetryStatus(
- attempt = retryCount,
- maxAttempts = MAX_RETRIES,
- delayMs = RETRY_BASE_DELAY_MS
- )
- handler.postDelayed({
- streamInfoSnapshot?.let { prepare(it) }
- }, RETRY_BASE_DELAY_MS)
- } else {
- _retryStatus.value = null
- _error.tryEmit(PlayerError.fromException(error))
- _playbackState.value = PlaybackState.ERROR
- }
- }
-
- override fun onPositionDiscontinuity(
- oldPosition: Player.PositionInfo,
- newPosition: Player.PositionInfo,
- reason: Int
- ) {
- _currentPosition.value = newPosition.positionMs
- }
-
- override fun onMediaMetadataChanged(metadata: androidx.media3.common.MediaMetadata) {
- // ICY / HLS metadata: the stream itself reports a title change.
- val title = metadata.title?.toString()?.takeIf { it.isNotBlank() }
- _mediaTitle.value = title
- }
-
- override fun onTracksChanged(tracks: androidx.media3.common.Tracks) {
- val audioTracks = mutableListOf<PlayerTrack>()
- val subtitleTracks = mutableListOf<PlayerTrack>()
- val videoTracks = mutableListOf<PlayerTrack>()
-
- for (group in tracks.groups) {
- val type = group.mediaTrackGroup.type
- val isAudio = type == C.TRACK_TYPE_AUDIO
- val isText = type == C.TRACK_TYPE_TEXT
- val isVideo = type == C.TRACK_TYPE_VIDEO
-
- if (isAudio || isText || isVideo) {
- for (i in 0 until group.length) {
- val format = group.mediaTrackGroup.getFormat(i)
- val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
- val name = buildTrackName(format = format, trackType = type, index = i)
- val isSelected = when {
- isVideo -> selectedVideoTrackId == id
- else -> group.isTrackSelected(i)
- }
-
- val track = PlayerTrack(
- id = id,
- name = name,
- language = format.language,
- type = when {
- isAudio -> TrackType.AUDIO
- isText -> TrackType.TEXT
- else -> TrackType.VIDEO
- },
- isSelected = isSelected
- )
-
- if (isAudio && group.isTrackSupported(i, false)) {
- audioTracks.add(track)
- } else if (isText && group.isTrackSupported(i, false)) {
- subtitleTracks.add(track)
- } else if (isVideo && group.isTrackSupported(i, false)) {
- videoTracks.add(track)
- }
- }
- }
- }
-
- _availableAudioTracks.value = audioTracks
- _availableSubtitleTracks.value = subtitleTracks
- _availableVideoTracks.value = when {
- videoTracks.size > 1 -> listOf(
- PlayerTrack(
- id = PLAYER_TRACK_AUTO_ID,
- name = "Auto",
- language = null,
- type = TrackType.VIDEO,
- isSelected = selectedVideoTrackId == PLAYER_TRACK_AUTO_ID
- )
- ) + videoTracks
- videoTracks.size == 1 -> listOf(videoTracks.first().copy(isSelected = true))
- else -> emptyList()
- }
- }
- })
- }
- }
+ private val subtitleStyleController = SubtitleStyleController()
+ private val viewBinder = PlayerViewBinder(subtitleStyleController)
+ private val trackController = PlayerTrackController(context)
+ override val availableAudioTracks: StateFlow<List<PlayerTrack>> = trackController.availableAudioTracks
+ override val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = trackController.availableSubtitleTracks
+ override val availableVideoTracks: StateFlow<List<PlayerTrack>> = trackController.availableVideoTracks
+
+ private val audioFocusController = PlayerAudioFocusController(
+ context = context,
+ applyVolume = { volume -> exoPlayer?.volume = volume },
+ setPlayWhenReady = { playWhenReady -> exoPlayer?.playWhenReady = playWhenReady }
+ ).also {
+ it.bypassAudioFocus = bypassAudioFocus
+ }
+ override val isMuted: StateFlow<Boolean> = audioFocusController.isMuted
+
+ private val statsCollector = PlayerStatsCollector(
+ scope = scope,
+ currentPosition = _currentPosition,
+ duration = _duration,
+ videoFormat = _videoFormat,
+ playerStats = _playerStats
+ )
+ private val dataSourceFactoryProvider = PlayerDataSourceFactoryProvider(okHttpClient)
+ private val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider)
+ private val preloadCoordinator = PreloadCoordinator()
+ private val compatibilityProfile: PlaybackCompatibilityProfile = DefaultPlaybackCompatibilityProfile
+ private val decoderPreferencePolicy = DefaultDecoderPreferencePolicy()
override fun prepare(streamInfo: StreamInfo) {
- lastStreamInfo = streamInfo
- retryCount = 0
- _retryStatus.value = null
- lastFrameRate = 0f
- lastBandwidthStatsUpdateMs = 0L
- lastVideoWidth = 0
- lastVideoHeight = 0
- handler.removeCallbacksAndMessages(null)
- val player = getOrCreatePlayer()
- _error.tryEmit(null)
- _playerStats.value = PlayerStats() // reset stats
- _mediaTitle.value = null
- _availableAudioTracks.value = emptyList()
- _availableSubtitleTracks.value = emptyList()
- _availableVideoTracks.value = emptyList()
- selectedVideoTrackId = PLAYER_TRACK_AUTO_ID
- applyPlayerVolume()
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .clearOverridesOfType(C.TRACK_TYPE_AUDIO)
- .clearOverridesOfType(C.TRACK_TYPE_TEXT)
- .clearOverridesOfType(C.TRACK_TYPE_VIDEO)
- .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
- .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
- .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
- .setPreferredAudioLanguage(preferredAudioLanguageTag)
- .apply {
- resolvedMaxVideoHeightForCurrentNetwork()?.let { maxHeight ->
- setMaxVideoSize(Int.MAX_VALUE, maxHeight)
- } ?: clearVideoSizeConstraints()
- }
- .build()
- player.playbackParameters = PlaybackParameters(_playbackSpeed.value)
-
- // If we already preloaded this exact stream, use the cached source
- val mediaSource = if (preloadedStreamInfo?.url == streamInfo.url && preloadedSource != null) {
- preloadedSource!!.also {
- preloadedSource = null
- preloadedStreamInfo = null
- }
- } else {
- preloadedSource = null
- preloadedStreamInfo = null
- val dataSourceFactory = createDataSourceFactory(streamInfo)
- val streamType = streamInfo.streamType.takeIf { it != StreamType.UNKNOWN }
- ?: StreamTypeDetector.detect(streamInfo.url)
- createMediaSource(streamInfo.url, streamType, dataSourceFactory, streamInfo.title, streamInfo.drmInfo)
- }
-
- player.setMediaSource(mediaSource)
- player.prepare()
- _videoFormat.value = VideoFormat(0, 0) // Reset format
- player.playWhenReady = requestAudioFocusIfNeeded()
- }
-
- private fun createDataSourceFactory(streamInfo: StreamInfo): DataSource.Factory {
- val headers = buildMap {
- putAll(streamInfo.headers)
- streamInfo.userAgent?.let { put("User-Agent", it) }
- }
-
- val timeoutClient = okHttpClient.newBuilder()
- .connectTimeout(PLAYBACK_CONNECT_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
- .readTimeout(PLAYBACK_READ_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
- .writeTimeout(PLAYBACK_WRITE_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
- .build()
-
- return if (headers.isNotEmpty()) {
- OkHttpDataSource.Factory(timeoutClient).apply {
- setDefaultRequestProperties(headers)
- }
- } else {
- OkHttpDataSource.Factory(timeoutClient)
- }
- }
-
- private fun createMediaSource(
- url: String,
- streamType: StreamType,
- dataSourceFactory: DataSource.Factory,
- title: String? = null,
- drmInfo: DrmInfo? = null
- ): MediaSource {
- val uri = Uri.parse(url)
- val mediaItem = MediaItem.Builder()
- .setUri(uri)
- .setMediaMetadata(
- androidx.media3.common.MediaMetadata.Builder()
- .setTitle(title)
- .build()
- )
- .apply {
- drmInfo?.let { info ->
- setDrmConfiguration(
- MediaItem.DrmConfiguration.Builder(info.scheme.toUuid())
- .setLicenseUri(info.licenseUrl)
- .setLicenseRequestHeaders(info.headers)
- .setMultiSession(info.multiSession)
- .setForceDefaultLicenseUri(info.forceDefaultLicenseUrl)
- .setPlayClearContentWithoutKey(info.playClearContentWithoutKey)
- .build()
- )
- }
- }
- .build()
-
- return when (streamType) {
- StreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory)
- .setAllowChunklessPreparation(true)
- // Start from the live edge rather than 3 segments behind it
- .createMediaSource(mediaItem)
-
- StreamType.DASH -> DashMediaSource.Factory(dataSourceFactory)
- .createMediaSource(mediaItem)
-
- // PE-H03: RTSP uses its own built-in transport, not OkHttp.
- StreamType.RTSP -> RtspMediaSource.Factory()
- .createMediaSource(mediaItem)
-
- StreamType.MPEG_TS, StreamType.PROGRESSIVE, StreamType.UNKNOWN ->
- ProgressiveMediaSource.Factory(dataSourceFactory)
- .createMediaSource(mediaItem)
- }
+ prepareInternal(streamInfo = streamInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)
}
override fun play() {
- if (requestAudioFocusIfNeeded()) {
+ if (audioFocusController.requestAudioFocusIfNeeded()) {
exoPlayer?.playWhenReady = true
}
}
override fun pause() {
+ retryJob?.cancel()
exoPlayer?.playWhenReady = false
- shouldResumeOnAudioFocusGain = false
- abandonAudioFocusIfHeld()
+ audioFocusController.onPauseOrStop()
}
override fun stop() {
+ retryJob?.cancel()
exoPlayer?.stop()
_playbackState.value = PlaybackState.IDLE
- shouldResumeOnAudioFocusGain = false
- abandonAudioFocusIfHeld()
+ audioFocusController.onPauseOrStop()
}
override fun seekTo(positionMs: Long) {
@@ -711,96 +186,71 @@ class Media3PlayerEngine @Inject constructor(
override fun seekForward(ms: Long) {
exoPlayer?.let { player ->
val duration = player.duration
- // C.TIME_UNSET (-1) is returned for live/unbounded streams — don't coerce against it.
- val newPos = if (duration != C.TIME_UNSET) {
+ val newPosition = if (duration != C.TIME_UNSET) {
(player.currentPosition + ms).coerceAtMost(duration)
} else {
player.currentPosition + ms
}
- player.seekTo(newPos)
+ player.seekTo(newPosition)
}
}
override fun seekBackward(ms: Long) {
- exoPlayer?.let { player ->
- val newPos = (player.currentPosition - ms).coerceAtLeast(0)
- player.seekTo(newPos)
- }
+ exoPlayer?.seekTo((exoPlayer?.currentPosition ?: 0L - ms).coerceAtLeast(0L))
}
override fun setDecoderMode(mode: DecoderMode) {
- if (currentDecoderMode != mode) {
- currentDecoderMode = mode
- val streamInfo = lastStreamInfo ?: return // Nothing playing — just update mode
- val wasPlaying = exoPlayer?.isPlaying ?: false
- val position = exoPlayer?.currentPosition ?: 0
-
- exoPlayer?.release()
- exoPlayer = null
- mediaSession?.release()
- mediaSession = null
-
- // Re-prepare using the original StreamInfo so the custom data source factory
- // (headers, user-agent) is fully rebuilt — not just the bare MediaItem.
- prepare(streamInfo)
- if (position > 0) exoPlayer?.seekTo(position)
- if (!wasPlaying) exoPlayer?.playWhenReady = false
+ if (requestedDecoderMode == mode) return
+ requestedDecoderMode = mode
+ lastStreamInfo?.let { streamInfo ->
+ val wasPlaying = exoPlayer?.playWhenReady == true
+ val position = exoPlayer?.currentPosition
+ prepareInternal(streamInfo, preserveRetryState = false, seekPositionMs = position, autoPlay = wasPlaying)
}
}
override fun setVolume(volume: Float) {
- currentVolume = volume.coerceIn(0f, 1f)
- if (currentVolume > 0f) {
- volumeBeforeMute = currentVolume
- _isMuted.value = false
- }
- applyPlayerVolume()
+ audioFocusController.setVolume(volume)
}
override fun setMuted(muted: Boolean) {
- if (muted == _isMuted.value) {
- applyPlayerVolume()
- return
- }
-
- if (muted) {
- if (currentVolume > 0f) {
- volumeBeforeMute = currentVolume.coerceAtLeast(0.1f)
- }
- _isMuted.value = true
- } else {
- _isMuted.value = false
- if (currentVolume <= 0f) {
- currentVolume = volumeBeforeMute.coerceIn(0.1f, 1f)
- }
- }
-
- applyPlayerVolume()
+ audioFocusController.setMuted(muted)
}
override fun setPlaybackSpeed(speed: Float) {
- val clampedSpeed = speed.coerceIn(0.5f, 2f)
- _playbackSpeed.value = clampedSpeed
- exoPlayer?.playbackParameters = PlaybackParameters(clampedSpeed)
+ val clamped = speed.coerceIn(0.5f, 2f)
+ _playbackSpeed.value = clamped
+ exoPlayer?.playbackParameters = PlaybackParameters(clamped)
}
override fun setPreferredAudioLanguage(languageTag: String?) {
- preferredAudioLanguageTag = languageTag?.trim()?.takeIf { it.isNotBlank() }
- exoPlayer?.let { player ->
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setPreferredAudioLanguage(preferredAudioLanguageTag)
- .build()
- }
+ trackController.setPreferredAudioLanguage(exoPlayer, languageTag)
+ }
+
+ override fun setSubtitleStyle(style: PlayerSubtitleStyle) {
+ subtitleStyleController.updateStyle(style)
+ viewBinder.reapplyStyle()
}
override fun setNetworkQualityPreferences(wifiMaxHeight: Int?, ethernetMaxHeight: Int?) {
- preferredWifiMaxVideoHeight = wifiMaxHeight?.takeIf { it > 0 }
- preferredEthernetMaxVideoHeight = ethernetMaxHeight?.takeIf { it > 0 }
+ trackController.setNetworkQualityPreferences(wifiMaxHeight, ethernetMaxHeight)
+ exoPlayer?.let { player -> trackController.applyInitialParameters(player, constrainResolutionForMultiView) }
+ }
+
+ override fun selectAudioTrack(trackId: String) {
+ exoPlayer?.let { trackController.selectAudioTrack(it, trackId) }
+ }
+
+ override fun selectVideoTrack(trackId: String) {
+ exoPlayer?.let { trackController.selectVideoTrack(it, trackId) }
+ }
+
+ override fun selectSubtitleTrack(trackId: String?) {
+ exoPlayer?.let { trackController.selectSubtitleTrack(it, trackId) }
}
override fun toggleMute() {
- setMuted(!_isMuted.value)
+ audioFocusController.toggleMute()
}
override fun setScrubbingMode(enabled: Boolean) {
@@ -815,425 +265,392 @@ class Media3PlayerEngine @Inject constructor(
override fun preload(streamInfo: StreamInfo?) {
if (streamInfo == null) {
- preloadedSource = null
- preloadedStreamInfo = null
+ preloadCoordinator.invalidate("cleared")
return
}
- // Don't preload the stream that's already playing
if (streamInfo.url == lastStreamInfo?.url) return
- val dataSourceFactory = createDataSourceFactory(streamInfo)
- val streamType = streamInfo.streamType.takeIf { it != StreamType.UNKNOWN }
- ?: StreamTypeDetector.detect(streamInfo.url)
- preloadedSource = createMediaSource(streamInfo.url, streamType, dataSourceFactory, streamInfo.title, streamInfo.drmInfo)
- preloadedStreamInfo = streamInfo
- }
-
- private fun DrmScheme.toUuid(): UUID = when (this) {
- DrmScheme.WIDEVINE -> C.WIDEVINE_UUID
- DrmScheme.PLAYREADY -> C.PLAYREADY_UUID
- DrmScheme.CLEARKEY -> C.CLEARKEY_UUID
- }
- override fun selectAudioTrack(trackId: String) {
- exoPlayer?.let { player ->
- val tracks = player.currentTracks
- for (group in tracks.groups) {
- if (group.mediaTrackGroup.type == C.TRACK_TYPE_AUDIO) {
- for (i in 0 until group.length) {
- val format = group.mediaTrackGroup.getFormat(i)
- val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
- if (id == trackId) {
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
- .setOverrideForType(
- androidx.media3.common.TrackSelectionOverride(
- group.mediaTrackGroup,
- listOf(i)
- )
- )
- .build()
- return
- }
- }
- }
- }
- }
+ val mediaId = mediaSourceFactory.mediaIdFor(streamInfo)
+ val resolvedStreamType = StreamTypeResolver.resolve(streamInfo)
+ val retryContext = PlaybackRetryContext(
+ resolvedStreamType = resolvedStreamType,
+ timeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, resolvedStreamType, preload = true)
+ )
+ val retryPolicy = PlayerRetryPolicy(retryContext) { false }
+ val (_, mediaSource) = mediaSourceFactory.create(
+ streamInfo = streamInfo,
+ resolvedStreamType = resolvedStreamType,
+ retryPolicy = retryPolicy,
+ preload = true
+ )
+ preloadCoordinator.store(mediaId, streamInfo, resolvedStreamType, mediaSource)
}
- override fun selectVideoTrack(trackId: String) {
- exoPlayer?.let { player ->
- selectedVideoTrackId = trackId
- if (trackId == PLAYER_TRACK_AUTO_ID) {
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .clearOverridesOfType(C.TRACK_TYPE_VIDEO)
- .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
- .build()
- _availableVideoTracks.update { existing ->
- existing.map { track ->
- track.copy(isSelected = track.id == PLAYER_TRACK_AUTO_ID)
- }
- }
- return
- }
+ override fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode) =
+ viewBinder.createRenderView(context, resizeMode)
- val tracks = player.currentTracks
- for (group in tracks.groups) {
- if (group.mediaTrackGroup.type == C.TRACK_TYPE_VIDEO) {
- for (i in 0 until group.length) {
- val format = group.mediaTrackGroup.getFormat(i)
- val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
- if (id == trackId) {
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
- .setOverrideForType(
- androidx.media3.common.TrackSelectionOverride(
- group.mediaTrackGroup,
- listOf(i)
- )
- )
- .build()
- _availableVideoTracks.update { existing ->
- existing.map { track ->
- track.copy(isSelected = track.id == trackId)
- }
- }
- return
- }
- }
- }
- }
- selectedVideoTrackId = PLAYER_TRACK_AUTO_ID
- }
+ override fun bindRenderView(renderView: android.view.View, resizeMode: PlayerSurfaceResizeMode) {
+ viewBinder.bind(renderView, getOrCreatePlayer(), resizeMode)
}
- override fun selectSubtitleTrack(trackId: String?) {
- exoPlayer?.let { player ->
- if (trackId == null) {
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
- .clearOverridesOfType(C.TRACK_TYPE_TEXT)
- .build()
- } else {
- val tracks = player.currentTracks
- for (group in tracks.groups) {
- if (group.mediaTrackGroup.type == C.TRACK_TYPE_TEXT) {
- for (i in 0 until group.length) {
- val format = group.mediaTrackGroup.getFormat(i)
- val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
- if (id == trackId) {
- player.trackSelectionParameters = player.trackSelectionParameters
- .buildUpon()
- .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)
- .setOverrideForType(
- androidx.media3.common.TrackSelectionOverride(
- group.mediaTrackGroup,
- listOf(i)
- )
- )
- .build()
- return
- }
- }
- }
- }
- }
- }
+ override fun releaseRenderView(renderView: android.view.View) {
+ viewBinder.release(renderView)
}
override fun release() {
- stopPolling()
- handler.removeCallbacksAndMessages(null)
- shouldResumeOnAudioFocusGain = false
- abandonAudioFocusIfHeld()
- preloadedSource = null
- preloadedStreamInfo = null
+ retryJob?.cancel()
+ retryJob = null
+ preloadCoordinator.release()
+ statsCollector.stop()
+ audioFocusController.release()
mediaSession?.release()
mediaSession = null
- boundPlayerView?.player = null
- boundPlayerView = null
+ viewBinder.clear()
exoPlayer?.release()
exoPlayer = null
lastStreamInfo = null
+ lastMediaId = null
+ currentRetryPolicy = null
+ currentRetryContext = null
+ playbackStarted = false
+ retryAttempt = 0
_retryStatus.value = null
- supervisorJob.cancel()
- supervisorJob = SupervisorJob()
- scope = CoroutineScope(Dispatchers.Main + supervisorJob)
_playbackState.value = PlaybackState.IDLE
_isPlaying.value = false
- _isMuted.value = false
_mediaTitle.value = null
+ trackController.resetSelections()
+ statsCollector.reset()
+ supervisorJob.cancel()
+ supervisorJob = SupervisorJob()
+ scope = CoroutineScope(Dispatchers.Main.immediate + supervisorJob)
+ statsCollector.bind { exoPlayer }
}
- private fun buildTrackName(format: Format, trackType: Int, index: Int): String {
- if (trackType == C.TRACK_TYPE_VIDEO) {
- return buildVideoTrackName(format, index)
+ private fun prepareInternal(
+ streamInfo: StreamInfo,
+ preserveRetryState: Boolean,
+ seekPositionMs: Long?,
+ autoPlay: Boolean
+ ) {
+ retryJob?.cancel()
+ lastStreamInfo = streamInfo
+ val mediaId = mediaSourceFactory.mediaIdFor(streamInfo)
+ if (!preserveRetryState || lastMediaId != mediaId) {
+ retryAttempt = 0
+ _retryStatus.value = null
}
+ if (lastMediaId != mediaId) {
+ decoderPreferencePolicy.resetForMedia(mediaId)
+ }
+ lastMediaId = mediaId
+ playbackStarted = false
+ _error.tryEmit(null)
+ _mediaTitle.value = null
+ trackController.resetSelections()
+ statsCollector.reset()
- val explicitLabel = format.label
- ?.trim()
- ?.takeIf { it.isNotBlank() && !it.matches(Regex("(?i)^track\\s*\\d+$")) }
+ currentResolvedStreamType = StreamTypeResolver.resolve(streamInfo)
+ currentTimeoutProfile = PlayerTimeoutProfile.resolve(streamInfo, currentResolvedStreamType, preload = false)
+ currentRetryContext = PlaybackRetryContext(currentResolvedStreamType, currentTimeoutProfile)
+ currentRetryPolicy = PlayerRetryPolicy(currentRetryContext!!) { playbackStarted }
- if (explicitLabel != null) {
- return explicitLabel
+ val preferredDecoderMode = decoderPreferencePolicy.preferredMode(requestedDecoderMode, mediaId)
+ if (activeDecoderMode != preferredDecoderMode) {
+ activeDecoderMode = preferredDecoderMode
+ recreatePlayer()
}
- val parts = mutableListOf<String>()
- val languageCode = format.language
- ?.takeIf { it.isNotBlank() && it != C.LANGUAGE_UNDETERMINED }
-
- languageCode?.let { code ->
- val locale = Locale.forLanguageTag(code)
- val displayLanguage = locale.getDisplayLanguage(Locale.getDefault())
- .takeIf { it.isNotBlank() }
- ?: locale.displayLanguage.takeIf { it.isNotBlank() }
- if (!displayLanguage.isNullOrBlank()) {
- parts += displayLanguage.replaceFirstChar { char ->
- if (char.isLowerCase()) char.titlecase(Locale.getDefault()) else char.toString()
- }
- }
- }
+ Log.i(
+ TAG,
+ "prepare resolvedStreamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile decoderPreference=$activeDecoderMode target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
- if (trackType == C.TRACK_TYPE_TEXT) {
- if ((format.selectionFlags and C.SELECTION_FLAG_FORCED) != 0) {
- parts += "Forced"
- }
- if ((format.roleFlags and C.ROLE_FLAG_CAPTION) != 0) {
- parts += "CC"
- }
- if ((format.roleFlags and C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND) != 0) {
- parts += "SDH"
- }
- }
+ val player = getOrCreatePlayer()
+ trackController.applyInitialParameters(player, constrainResolutionForMultiView)
+ player.playbackParameters = PlaybackParameters(_playbackSpeed.value)
- if (parts.isNotEmpty()) {
- return parts.joinToString(" ")
- }
+ val mediaSource = preloadCoordinator.tryReuse(mediaId, streamInfo, currentResolvedStreamType)
+ ?: mediaSourceFactory.create(
+ streamInfo = streamInfo,
+ resolvedStreamType = currentResolvedStreamType,
+ retryPolicy = currentRetryPolicy!!,
+ preload = false
+ ).second
+ preloadCoordinator.onPlaybackStarted(mediaId)
+ player.setMediaSource(mediaSource)
+ player.prepare()
+ seekPositionMs?.takeIf { it > 0L }?.let(player::seekTo)
+ player.playWhenReady = autoPlay && audioFocusController.requestAudioFocusIfNeeded()
+ viewBinder.attachPlayer(player)
+ }
- return when (trackType) {
- C.TRACK_TYPE_AUDIO -> "Audio ${index + 1}"
- C.TRACK_TYPE_TEXT -> "Subtitle ${index + 1}"
- else -> "Track ${index + 1}"
+ private fun recreatePlayer() {
+ val existing = exoPlayer
+ if (existing != null) {
+ val currentViewPosition = existing.currentPosition
+ val playWhenReady = existing.playWhenReady
+ mediaSession?.release()
+ mediaSession = null
+ exoPlayer?.release()
+ exoPlayer = null
+ viewBinder.attachPlayer(null)
+ lastStreamInfo?.let { prepareInternal(it, preserveRetryState = true, seekPositionMs = currentViewPosition, autoPlay = playWhenReady) }
}
}
- private fun buildVideoTrackName(format: Format, index: Int): String {
- val parts = mutableListOf<String>()
- val explicitLabel = format.label
- ?.trim()
- ?.takeIf { it.isNotBlank() && !it.matches(Regex("(?i)^track\\s*\\d+$")) }
- val resolutionLabel = when {
- format.height > 0 -> "${format.height}p"
- format.width > 0 && format.height > 0 -> "${format.width}x${format.height}"
- else -> null
+ private fun getOrCreatePlayer(): ExoPlayer {
+ return exoPlayer ?: createPlayer().also { player ->
+ exoPlayer = player
+ statsCollector.bind { exoPlayer }
+ audioFocusController.reapplyVolume()
+ if (enableMediaSession) {
+ mediaSession = MediaSession.Builder(context, player).build()
+ }
}
- val bitrateLabel = format.bitrate
- .takeIf { it > 0 }
- ?.let { bitrate -> String.format(Locale.US, "%.1f Mbps", bitrate / 1_000_000f) }
+ }
- explicitLabel?.let { label ->
- parts += label
- }
- if (!resolutionLabel.isNullOrBlank() && parts.none { it.contains(resolutionLabel, ignoreCase = true) }) {
- parts += resolutionLabel
- }
- if (!bitrateLabel.isNullOrBlank()) {
- parts += bitrateLabel
- }
+ private fun createPlayer(): ExoPlayer {
+ val renderersFactory = buildRenderersFactory()
+ val loadControl = DefaultLoadControl.Builder()
+ .setBufferDurationsMs(
+ 30_000,
+ 90_000,
+ 2_500,
+ 10_000
+ )
+ .setPrioritizeTimeOverSizeThresholds(true)
+ .build()
+ val livePlaybackSpeedControl = DefaultLivePlaybackSpeedControl.Builder()
+ .setFallbackMinPlaybackSpeed(1.0f)
+ .setFallbackMaxPlaybackSpeed(1.0f)
+ .build()
- return parts.firstOrNull()?.takeIf { parts.size == 1 }
- ?: parts.joinToString(separator = " · ").ifBlank { "Quality ${index + 1}" }
- }
- private fun isRecoverableError(error: PlaybackException): Boolean {
- return when (error.errorCode) {
- PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
- PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT,
- PlaybackException.ERROR_CODE_IO_UNSPECIFIED -> true
- else -> false
- }
+ return ExoPlayer.Builder(context, renderersFactory)
+ .setLoadControl(loadControl)
+ .setLivePlaybackSpeedControl(livePlaybackSpeedControl)
+ .setSeekBackIncrementMs(10_000)
+ .setSeekForwardIncrementMs(10_000)
+ .setAudioAttributes(
+ Media3AudioAttributes.Builder()
+ .setUsage(C.USAGE_MEDIA)
+ .setContentType(C.AUDIO_CONTENT_TYPE_UNKNOWN)
+ .build(),
+ false
+ )
+ .build()
+ .apply {
+ videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
+ playbackParameters = PlaybackParameters(_playbackSpeed.value)
+ addAnalyticsListener(createAnalyticsListener())
+ addListener(createPlayerListener())
+ }
}
- private fun startPolling() {
- pollingJob?.cancel()
- pollingJob = scope.launch {
- while (isActive) {
- exoPlayer?.let { player ->
- _currentPosition.value = player.currentPosition
- _duration.value = player.duration.coerceAtLeast(0L)
- // Update buffered duration for diagnostics
- val buffered = player.bufferedPosition - player.currentPosition
- updatePlayerStats { current ->
- val bufferedDurationMs = buffered.coerceAtLeast(0L)
- if (shouldPublishBufferedDuration(current.bufferedDurationMs, bufferedDurationMs)) {
- current.copy(bufferedDurationMs = bufferedDurationMs)
- } else {
- current
+ private fun buildRenderersFactory(): DefaultRenderersFactory {
+ val baseFactory = if (compatibilityProfile.shouldDisableDecoderReuseWorkaround()) {
+ object : DefaultRenderersFactory(context) {
+ override fun buildVideoRenderers(
+ context: Context,
+ extensionRendererMode: Int,
+ mediaCodecSelector: MediaCodecSelector,
+ enableDecoderFallback: Boolean,
+ eventHandler: Handler,
+ eventListener: VideoRendererEventListener,
+ allowedVideoJoiningTimeMs: Long,
+ out: ArrayList<Renderer>
+ ) {
+ out.add(object : MediaCodecVideoRenderer(
+ context,
+ mediaCodecSelector,
+ allowedVideoJoiningTimeMs,
+ enableDecoderFallback,
+ eventHandler,
+ eventListener,
+ 50
+ ) {
+ override fun canReuseCodec(
+ codecInfo: MediaCodecInfo,
+ oldFormat: Format,
+ newFormat: Format
+ ): DecoderReuseEvaluation {
+ return DecoderReuseEvaluation(
+ codecInfo.name,
+ oldFormat,
+ newFormat,
+ DecoderReuseEvaluation.REUSE_RESULT_NO,
+ DecoderReuseEvaluation.DISCARD_REASON_MAX_INPUT_SIZE_EXCEEDED
+ )
}
- }
+ })
}
- delay(250) // PE-M02: 250ms polling for smooth seek-bar animation
}
+ } else {
+ DefaultRenderersFactory(context)
}
- }
- private inline fun updatePlayerStats(transform: (PlayerStats) -> PlayerStats) {
- _playerStats.update { current ->
- val updated = transform(current)
- if (updated == current) current else updated
+ return baseFactory.apply {
+ setExtensionRendererMode(
+ when (activeDecoderMode) {
+ DecoderMode.AUTO, DecoderMode.HARDWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
+ DecoderMode.SOFTWARE -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF
+ }
+ )
}
}
- private fun shouldPublishBandwidthEstimate(
- currentEstimate: Long,
- newEstimate: Long,
- nowMs: Long
- ): Boolean {
- if (newEstimate <= 0L) return false
- if (currentEstimate <= 0L) return true
- val absoluteDelta = abs(newEstimate - currentEstimate)
- val relativeThreshold = (currentEstimate / 8).coerceAtLeast(250_000L)
- return absoluteDelta >= relativeThreshold || nowMs - lastBandwidthStatsUpdateMs >= BANDWIDTH_STATS_MIN_INTERVAL_MS
- }
+ private fun createAnalyticsListener(): AnalyticsListener {
+ return object : AnalyticsListener {
+ override fun onVideoInputFormatChanged(
+ eventTime: AnalyticsListener.EventTime,
+ format: Format,
+ decoderReuseEvaluation: DecoderReuseEvaluation?
+ ) {
+ statsCollector.onVideoFormatChanged(format)
+ }
- private fun shouldPublishBufferedDuration(currentDurationMs: Long, newDurationMs: Long): Boolean {
- return currentDurationMs == 0L || newDurationMs == 0L || abs(newDurationMs - currentDurationMs) >= BUFFERED_DURATION_PUBLISH_STEP_MS
- }
+ override fun onAudioInputFormatChanged(
+ eventTime: AnalyticsListener.EventTime,
+ format: Format,
+ decoderReuseEvaluation: DecoderReuseEvaluation?
+ ) {
+ statsCollector.onAudioFormatChanged(format)
+ }
- private fun shouldDisableVideoDecoderReuseWorkaround(): Boolean {
- val fingerprint = Build.FINGERPRINT.lowercase(Locale.ROOT)
- val hardware = Build.HARDWARE.lowercase(Locale.ROOT)
- val model = Build.MODEL.lowercase(Locale.ROOT)
- return fingerprint.contains("generic") ||
- fingerprint.contains("emulator") ||
- hardware.contains("goldfish") ||
- hardware.contains("ranchu") ||
- model.contains("android sdk built for")
- }
+ override fun onDroppedVideoFrames(
+ eventTime: AnalyticsListener.EventTime,
+ droppedFrames: Int,
+ elapsedMs: Long
+ ) {
+ statsCollector.onDroppedFrames(droppedFrames)
+ }
- private fun stopPolling() {
- pollingJob?.cancel()
- pollingJob = null
- }
+ override fun onBandwidthEstimate(
+ eventTime: AnalyticsListener.EventTime,
+ totalLoadTimeMs: Int,
+ totalBytesLoaded: Long,
+ bitrateEstimate: Long
+ ) {
+ statsCollector.onBandwidthEstimate(bitrateEstimate)
+ }
- override fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode): View {
- // Inflate PlayerView with surface_type="texture_view" —
- // TextureView renders through the GPU/view pipeline, not SurfaceFlinger.
- // This avoids the known Media3 issue where SurfaceView overflows its
- // bounds inside Compose AndroidView (issue #1107), causing zoom/PiP.
- return (LayoutInflater.from(context).inflate(
- R.layout.player_texture_view, null
- ) as PlayerView).apply {
- layoutParams = android.widget.FrameLayout.LayoutParams(
- android.widget.FrameLayout.LayoutParams.MATCH_PARENT,
- android.widget.FrameLayout.LayoutParams.MATCH_PARENT
- )
- setShutterBackgroundColor(AndroidColor.BLACK)
- applyResizeMode(resizeMode)
+ override fun onRenderedFirstFrame(
+ eventTime: AnalyticsListener.EventTime,
+ output: Any,
+ renderTimeMs: Long
+ ) {
+ playbackStarted = true
+ Log.i(
+ TAG,
+ "first-frame-success streamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}"
+ )
+ }
}
}
- override fun bindRenderView(renderView: View, resizeMode: PlayerSurfaceResizeMode) {
- val playerView = renderView as? PlayerView ?: return
- val player = getOrCreatePlayer()
- if (boundPlayerView !== playerView) {
- boundPlayerView?.player = null
- playerView.player = player
- boundPlayerView = playerView
- } else if (playerView.player !== player) {
- playerView.player = player
- }
- playerView.applyResizeMode(resizeMode)
- applySubtitleStyle(playerView)
- }
+ private fun createPlayerListener(): Player.Listener {
+ return object : Player.Listener {
+ override fun onPlaybackStateChanged(state: Int) {
+ val previousState = _playbackState.value
+ _playbackState.value = when (state) {
+ Player.STATE_IDLE -> PlaybackState.IDLE
+ Player.STATE_BUFFERING -> PlaybackState.BUFFERING
+ Player.STATE_READY -> PlaybackState.READY
+ Player.STATE_ENDED -> PlaybackState.ENDED
+ else -> PlaybackState.IDLE
+ }
+ if (previousState == PlaybackState.READY && _playbackState.value == PlaybackState.BUFFERING) {
+ statsCollector.incrementRebufferCount()
+ }
+ if (_playbackState.value == PlaybackState.READY) {
+ _retryStatus.value = null
+ }
+ }
- override fun releaseRenderView(renderView: View) {
- val playerView = renderView as? PlayerView ?: return
- if (playerView.player != null) {
- playerView.player = null
- }
- if (boundPlayerView === playerView) {
- boundPlayerView = null
- }
- }
+ override fun onIsPlayingChanged(isPlaying: Boolean) {
+ _isPlaying.value = isPlaying
+ if (isPlaying) {
+ statsCollector.start()
+ audioFocusController.onPlaybackStarted()
+ } else {
+ statsCollector.stop()
+ }
+ }
- override fun setSubtitleStyle(style: PlayerSubtitleStyle) {
- subtitleStyle = style.copy(textScale = style.textScale.coerceIn(0.75f, 1.75f))
- applySubtitleStyle(boundPlayerView)
- }
+ override fun onPlayerError(error: PlaybackException) {
+ handlePlaybackError(error)
+ }
- private fun applySubtitleStyle(playerView: PlayerView?) {
- val subtitleView = playerView?.subtitleView ?: return
- subtitleView.setStyle(
- CaptionStyleCompat(
- subtitleStyle.foregroundColorArgb,
- subtitleStyle.backgroundColorArgb,
- AndroidColor.TRANSPARENT,
- CaptionStyleCompat.EDGE_TYPE_NONE,
- AndroidColor.TRANSPARENT,
- null
- )
- )
- subtitleView.setFractionalTextSize(
- SubtitleView.DEFAULT_TEXT_SIZE_FRACTION * subtitleStyle.textScale.coerceIn(0.75f, 1.75f)
- )
- }
+ override fun onPositionDiscontinuity(
+ oldPosition: Player.PositionInfo,
+ newPosition: Player.PositionInfo,
+ reason: Int
+ ) {
+ _currentPosition.value = newPosition.positionMs
+ }
+
+ override fun onMediaMetadataChanged(metadata: androidx.media3.common.MediaMetadata) {
+ _mediaTitle.value = metadata.title?.toString()?.takeIf { it.isNotBlank() }
+ }
- private fun PlayerView.applyResizeMode(surfaceResizeMode: PlayerSurfaceResizeMode) {
- resizeMode = when (surfaceResizeMode) {
- PlayerSurfaceResizeMode.FIT -> AspectRatioFrameLayout.RESIZE_MODE_FIT
- PlayerSurfaceResizeMode.FILL -> AspectRatioFrameLayout.RESIZE_MODE_FILL
- PlayerSurfaceResizeMode.ZOOM -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM
+ override fun onTracksChanged(tracks: androidx.media3.common.Tracks) {
+ trackController.onTracksChanged(tracks)
+ }
}
}
- private fun requestAudioFocusIfNeeded(): Boolean {
- if (bypassAudioFocus) {
- if (isDucked) {
- isDucked = false
- applyPlayerVolume()
- }
- return true
+ private fun handlePlaybackError(error: PlaybackException) {
+ val streamInfo = lastStreamInfo
+ val mediaId = lastMediaId
+ val retryPolicy = currentRetryPolicy
+ val retryContext = currentRetryContext
+ val category = PlayerErrorClassifier.classify(error)
+
+ if (streamInfo == null || mediaId == null || retryPolicy == null || retryContext == null) {
+ _retryStatus.value = null
+ _error.tryEmit(PlayerError.fromException(error))
+ _playbackState.value = PlaybackState.ERROR
+ return
}
- if (hasAudioFocus) {
- if (isDucked) {
- isDucked = false
- applyPlayerVolume()
+
+ if (category == PlaybackErrorCategory.DECODER) {
+ val fallbackMode = decoderPreferencePolicy.onDecoderInitFailure(activeDecoderMode, mediaId)
+ if (fallbackMode != null) {
+ Log.w(
+ TAG,
+ "decoder-preference fallback=$fallbackMode mediaId=$mediaId target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+ activeDecoderMode = fallbackMode
+ prepareInternal(streamInfo, preserveRetryState = false, seekPositionMs = exoPlayer?.currentPosition, autoPlay = true)
+ return
}
- return true
}
- val focusRequest = audioFocusRequest ?: buildAudioFocusRequest().also { audioFocusRequest = it }
- val focusResult = audioManager.requestAudioFocus(focusRequest)
- hasAudioFocus = focusResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
- if (!hasAudioFocus) {
- Log.w(TAG, "Audio focus request denied; playback will remain paused")
- return false
- }
- isDucked = false
- applyPlayerVolume()
- return true
- }
- private fun abandonAudioFocusIfHeld() {
- if (!hasAudioFocus) return
- audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
- hasAudioFocus = false
- isDucked = false
- }
+ val nextAttempt = retryAttempt + 1
+ if (retryPolicy.shouldRetry(error, retryContext, playbackStarted, nextAttempt)) {
+ val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)
+ retryAttempt = nextAttempt
+ _retryStatus.value = PlayerRetryStatus(
+ attempt = nextAttempt,
+ maxAttempts = retryPolicy.maxAttempts(error, playbackStarted),
+ delayMs = delayMs
+ )
+ Log.w(
+ TAG,
+ "retry category=$category attempt=$nextAttempt delayMs=$delayMs reason=${retryPolicy.retryReason(error)} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+ retryJob = scope.launch {
+ delay(delayMs)
+ prepareInternal(streamInfo, preserveRetryState = true, seekPositionMs = null, autoPlay = true)
+ }
+ return
+ }
- private fun buildAudioFocusRequest(): AudioFocusRequest {
- val platformAudioAttributes = android.media.AudioAttributes.Builder()
- .setUsage(android.media.AudioAttributes.USAGE_MEDIA)
- .setContentType(android.media.AudioAttributes.CONTENT_TYPE_MOVIE)
- .build()
- return AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
- .setAudioAttributes(platformAudioAttributes)
- .setAcceptsDelayedFocusGain(false)
- .setWillPauseWhenDucked(false)
- .setOnAudioFocusChangeListener(audioFocusChangeListener)
- .build()
+ _retryStatus.value = null
+ Log.e(
+ TAG,
+ "fatal-error category=$category target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
+ )
+ _error.tryEmit(PlayerError.fromException(error))
+ _playbackState.value = PlaybackState.ERROR
}
-
}
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index b0e61a49..2d8cabf3 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -7,6 +7,8 @@ import com.streamvault.domain.model.DrmScheme
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.VideoFormat
import androidx.media3.common.PlaybackException
+import com.streamvault.player.playback.PlaybackErrorCategory
+import com.streamvault.player.playback.PlayerErrorClassifier
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@@ -119,40 +121,22 @@ sealed class PlayerError(val message: String) {
companion object {
fun fromException(e: Throwable): PlayerError {
val msg = e.message ?: "Unknown playback error"
- if (e is PlaybackException) {
- return when (e.errorCode) {
- PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
- PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT,
- PlaybackException.ERROR_CODE_IO_UNSPECIFIED ->
- NetworkError(msg)
- PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS,
- PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
- PlaybackException.ERROR_CODE_IO_NO_PERMISSION,
- PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
- PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE,
- PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED,
- PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED ->
- SourceError(msg)
- PlaybackException.ERROR_CODE_DECODER_INIT_FAILED,
- PlaybackException.ERROR_CODE_DECODER_QUERY_FAILED,
- PlaybackException.ERROR_CODE_DECODING_FAILED,
- PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
- PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED ->
- DecoderError(msg)
- PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR,
- PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED,
- PlaybackException.ERROR_CODE_DRM_DISALLOWED_OPERATION,
- PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED,
- PlaybackException.ERROR_CODE_DRM_LICENSE_EXPIRED,
- PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED,
- PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED,
- PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR,
- PlaybackException.ERROR_CODE_DRM_UNSPECIFIED ->
- DrmError(msg)
- else -> UnknownError(msg)
- }
+ return when (PlayerErrorClassifier.classify(e)) {
+ PlaybackErrorCategory.NETWORK,
+ PlaybackErrorCategory.HTTP_SERVER,
+ PlaybackErrorCategory.HTTP_AUTH,
+ PlaybackErrorCategory.CLEAR_TEXT_BLOCKED,
+ PlaybackErrorCategory.SSL -> NetworkError(msg)
+
+ PlaybackErrorCategory.SOURCE_MALFORMED,
+ PlaybackErrorCategory.LIVE_WINDOW -> SourceError(msg)
+
+ PlaybackErrorCategory.DECODER,
+ PlaybackErrorCategory.FORMAT_UNSUPPORTED -> DecoderError(msg)
+
+ PlaybackErrorCategory.DRM -> DrmError(msg)
+ PlaybackErrorCategory.UNKNOWN -> UnknownError(msg)
}
- return UnknownError(msg)
}
}
}
diff --git a/player/src/main/java/com/streamvault/player/PlayerSubtitleStyle.kt b/player/src/main/java/com/streamvault/player/PlayerSubtitleStyle.kt
index 78f722fc..eff1f77d 100644
--- a/player/src/main/java/com/streamvault/player/PlayerSubtitleStyle.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerSubtitleStyle.kt
@@ -1,7 +1,12 @@
package com.streamvault.player
+import androidx.media3.ui.CaptionStyleCompat
+
data class PlayerSubtitleStyle(
val textScale: Float = 1f,
val foregroundColorArgb: Int = 0xFFFFFFFF.toInt(),
- val backgroundColorArgb: Int = 0x80000000.toInt()
-)
\ No newline at end of file
+ val backgroundColorArgb: Int = 0x80000000.toInt(),
+ val edgeType: Int = CaptionStyleCompat.EDGE_TYPE_OUTLINE,
+ val bottomPaddingFraction: Float = 0.08f,
+ val useEmbeddedStyles: Boolean = true
+)
diff --git a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt b/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
index b1cf2d43..012083e0 100644
--- a/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
+++ b/player/src/main/java/com/streamvault/player/StreamTypeDetector.kt
@@ -1,45 +1,18 @@
package com.streamvault.player
import com.streamvault.domain.model.StreamType
+import com.streamvault.player.playback.ResolvedStreamType
+import com.streamvault.player.playback.StreamTypeResolver
-/**
- * Detects stream type from URL characteristics.
- * Used when the provider doesn't explicitly specify the stream type.
- */
+@Deprecated("Use StreamTypeResolver")
object StreamTypeDetector {
-
fun detect(url: String): StreamType {
- val cleanUrl = url.lowercase().substringBefore("?").substringBefore("#")
- val scheme = cleanUrl.substringBefore("://")
-
- // RTSP / RTSPs — must be handled first; RtspMediaSource doesn't use OkHttp
- if (scheme == "rtsp" || scheme == "rtsps") return StreamType.RTSP
-
- return when {
- // HLS
- cleanUrl.endsWith(".m3u8") -> StreamType.HLS
- url.contains("/hls/", ignoreCase = true) -> StreamType.HLS
- url.contains(".m3u8", ignoreCase = true) -> StreamType.HLS
-
- // DASH
- cleanUrl.endsWith(".mpd") -> StreamType.DASH
- url.contains("/dash/", ignoreCase = true) -> StreamType.DASH
- url.contains(".mpd", ignoreCase = true) -> StreamType.DASH
-
- // MPEG-TS
- cleanUrl.endsWith(".ts") -> StreamType.MPEG_TS
- url.contains("/live/", ignoreCase = true) && !cleanUrl.endsWith(".mp4") -> StreamType.MPEG_TS
-
- // Progressive (MP4, MKV, AVI, etc.)
- cleanUrl.endsWith(".mp4") -> StreamType.PROGRESSIVE
- cleanUrl.endsWith(".mkv") -> StreamType.PROGRESSIVE
- cleanUrl.endsWith(".avi") -> StreamType.PROGRESSIVE
- cleanUrl.endsWith(".flv") -> StreamType.PROGRESSIVE
- cleanUrl.endsWith(".webm") -> StreamType.PROGRESSIVE
- cleanUrl.endsWith(".mov") -> StreamType.PROGRESSIVE
-
- // Unknown — let ExoPlayer figure it out via content sniffing
- else -> StreamType.UNKNOWN
+ return when (StreamTypeResolver.resolve(url = url, isLive = url.contains("/live/", ignoreCase = true))) {
+ ResolvedStreamType.HLS -> StreamType.HLS
+ ResolvedStreamType.DASH -> StreamType.DASH
+ ResolvedStreamType.MPEG_TS_LIVE -> StreamType.MPEG_TS
+ ResolvedStreamType.PROGRESSIVE -> StreamType.PROGRESSIVE
+ ResolvedStreamType.UNKNOWN -> StreamType.UNKNOWN
}
}
}
diff --git a/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt b/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt
new file mode 100644
index 00000000..b4b32834
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/audio/PlayerAudioFocusController.kt
@@ -0,0 +1,165 @@
+package com.streamvault.player.audio
+
+import android.content.Context
+import android.media.AudioFocusRequest
+import android.media.AudioManager
+import android.util.Log
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+class PlayerAudioFocusController(
+ context: Context,
+ private val applyVolume: (Float) -> Unit,
+ private val setPlayWhenReady: (Boolean) -> Unit
+) {
+ private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ private var audioFocusRequest: AudioFocusRequest? = null
+ private var hasAudioFocus = false
+ private var shouldResumeOnAudioFocusGain = false
+ private var isDucked = false
+ private var currentVolume = 1f
+ private var volumeBeforeMute = 1f
+
+ private val _isMuted = MutableStateFlow(false)
+ val isMuted: StateFlow<Boolean> = _isMuted.asStateFlow()
+
+ var bypassAudioFocus: Boolean = false
+
+ private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
+ when (focusChange) {
+ AudioManager.AUDIOFOCUS_GAIN -> {
+ hasAudioFocus = true
+ isDucked = false
+ dispatchVolume()
+ if (shouldResumeOnAudioFocusGain) {
+ shouldResumeOnAudioFocusGain = false
+ setPlayWhenReady(true)
+ }
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
+ isDucked = true
+ dispatchVolume()
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
+ hasAudioFocus = false
+ isDucked = false
+ shouldResumeOnAudioFocusGain = true
+ setPlayWhenReady(false)
+ dispatchVolume()
+ }
+
+ AudioManager.AUDIOFOCUS_LOSS -> {
+ hasAudioFocus = false
+ isDucked = false
+ shouldResumeOnAudioFocusGain = false
+ setPlayWhenReady(false)
+ dispatchVolume()
+ }
+ }
+ }
+
+ fun requestAudioFocusIfNeeded(): Boolean {
+ if (bypassAudioFocus || hasAudioFocus) {
+ isDucked = false
+ dispatchVolume()
+ return true
+ }
+ val request = audioFocusRequest ?: buildAudioFocusRequest().also { audioFocusRequest = it }
+ val granted = audioManager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
+ hasAudioFocus = granted
+ if (!granted) {
+ Log.w(TAG, "audio-focus denied")
+ return false
+ }
+ isDucked = false
+ dispatchVolume()
+ return true
+ }
+
+ fun onPauseOrStop() {
+ shouldResumeOnAudioFocusGain = false
+ abandonAudioFocusIfHeld()
+ }
+
+ fun onPlaybackStarted() {
+ shouldResumeOnAudioFocusGain = false
+ }
+
+ fun setVolume(volume: Float) {
+ currentVolume = volume.coerceIn(0f, 1f)
+ if (currentVolume > 0f) {
+ volumeBeforeMute = currentVolume
+ _isMuted.value = false
+ }
+ dispatchVolume()
+ }
+
+ fun setMuted(muted: Boolean) {
+ if (muted == _isMuted.value) {
+ dispatchVolume()
+ return
+ }
+ if (muted) {
+ if (currentVolume > 0f) {
+ volumeBeforeMute = currentVolume.coerceAtLeast(0.1f)
+ }
+ _isMuted.value = true
+ } else {
+ _isMuted.value = false
+ if (currentVolume <= 0f) {
+ currentVolume = volumeBeforeMute.coerceIn(0.1f, 1f)
+ }
+ }
+ dispatchVolume()
+ }
+
+ fun toggleMute() {
+ setMuted(!_isMuted.value)
+ }
+
+ fun reapplyVolume() {
+ dispatchVolume()
+ }
+
+ fun release() {
+ shouldResumeOnAudioFocusGain = false
+ abandonAudioFocusIfHeld()
+ }
+
+ private fun dispatchVolume() {
+ applyVolume(
+ when {
+ _isMuted.value -> 0f
+ isDucked -> (currentVolume * 0.2f).coerceAtLeast(0.05f)
+ else -> currentVolume
+ }
+ )
+ }
+
+ private fun abandonAudioFocusIfHeld() {
+ if (!hasAudioFocus) return
+ audioFocusRequest?.let(audioManager::abandonAudioFocusRequest)
+ hasAudioFocus = false
+ isDucked = false
+ }
+
+ private fun buildAudioFocusRequest(): AudioFocusRequest {
+ val attributes = android.media.AudioAttributes.Builder()
+ .setUsage(android.media.AudioAttributes.USAGE_MEDIA)
+ .setContentType(android.media.AudioAttributes.CONTENT_TYPE_MOVIE)
+ .build()
+ return AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
+ .setAudioAttributes(attributes)
+ .setAcceptsDelayedFocusGain(false)
+ .setWillPauseWhenDucked(false)
+ .setOnAudioFocusChangeListener(audioFocusChangeListener)
+ .build()
+ }
+
+ companion object {
+ private const val TAG = "PlayerAudioFocus"
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt b/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt
new file mode 100644
index 00000000..087ac057
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/DecoderPreferencePolicy.kt
@@ -0,0 +1,31 @@
+package com.streamvault.player.playback
+
+import com.streamvault.domain.model.DecoderMode
+
+interface DecoderPreferencePolicy {
+ fun preferredMode(requestedMode: DecoderMode, mediaId: String): DecoderMode
+ fun onDecoderInitFailure(requestedMode: DecoderMode, mediaId: String): DecoderMode?
+ fun resetForMedia(mediaId: String)
+}
+
+class DefaultDecoderPreferencePolicy : DecoderPreferencePolicy {
+ private val softwareRetriedMediaIds = mutableSetOf<String>()
+
+ override fun preferredMode(requestedMode: DecoderMode, mediaId: String): DecoderMode {
+ return when (requestedMode) {
+ DecoderMode.SOFTWARE -> DecoderMode.SOFTWARE
+ DecoderMode.HARDWARE, DecoderMode.AUTO -> DecoderMode.HARDWARE
+ }
+ }
+
+ override fun onDecoderInitFailure(requestedMode: DecoderMode, mediaId: String): DecoderMode? {
+ if (requestedMode == DecoderMode.SOFTWARE) return null
+ if (!softwareRetriedMediaIds.add(mediaId)) return null
+ return DecoderMode.SOFTWARE
+ }
+
+ override fun resetForMedia(mediaId: String) {
+ softwareRetriedMediaIds.remove(mediaId)
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackCompatibilityProfile.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackCompatibilityProfile.kt
new file mode 100644
index 00000000..59b017e5
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackCompatibilityProfile.kt
@@ -0,0 +1,22 @@
+package com.streamvault.player.playback
+
+import android.os.Build
+import java.util.Locale
+
+interface PlaybackCompatibilityProfile {
+ fun shouldDisableDecoderReuseWorkaround(): Boolean
+}
+
+object DefaultPlaybackCompatibilityProfile : PlaybackCompatibilityProfile {
+ override fun shouldDisableDecoderReuseWorkaround(): Boolean {
+ val fingerprint = Build.FINGERPRINT.lowercase(Locale.ROOT)
+ val hardware = Build.HARDWARE.lowercase(Locale.ROOT)
+ val model = Build.MODEL.lowercase(Locale.ROOT)
+ return fingerprint.contains("generic") ||
+ fingerprint.contains("emulator") ||
+ hardware.contains("goldfish") ||
+ hardware.contains("ranchu") ||
+ model.contains("android sdk built for")
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
new file mode 100644
index 00000000..ddd526e8
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
@@ -0,0 +1,32 @@
+package com.streamvault.player.playback
+
+import java.net.URI
+
+internal object PlaybackLogSanitizer {
+ fun sanitizeUrl(url: String?): String {
+ if (url.isNullOrBlank()) return "<unknown>"
+ val uri = runCatching { URI(url) }.getOrNull() ?: return "<malformed>"
+ val host = uri.host ?: "<unknown-host>"
+ val sanitizedPath = sanitizePath(uri.path.orEmpty())
+ return if (sanitizedPath.isBlank()) host else "$host$sanitizedPath"
+ }
+
+ fun sanitizeMessage(message: String?): String {
+ if (message.isNullOrBlank()) return "unknown"
+ return credentialQueryRegex.replace(message) { match ->
+ "${match.groupValues[1]}<redacted>"
+ }.let(::sanitizePathSegments)
+ }
+
+ private fun sanitizePath(path: String): String = sanitizePathSegments(path).take(120)
+
+ private fun sanitizePathSegments(value: String): String {
+ return credentialPathRegex.replace(value) { match ->
+ "${match.groupValues[1]}${match.groupValues[2]}/<redacted>/<redacted>${match.groupValues[3]}"
+ }
+ }
+
+ private val credentialQueryRegex = Regex("""([?&](?:username|password|token|auth)=)[^&#\s]+""", RegexOption.IGNORE_CASE)
+ private val credentialPathRegex =
+ Regex("""(/)(live|movie|series|timeshift|timeshifts)/[^/\s]+/[^/\s]+([^?\s#]*)""", RegexOption.IGNORE_CASE)
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
new file mode 100644
index 00000000..b5be1c7a
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
@@ -0,0 +1,40 @@
+package com.streamvault.player.playback
+
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.okhttp.OkHttpDataSource
+import com.streamvault.domain.model.StreamInfo
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit
+import okhttp3.OkHttpClient
+
+class PlayerDataSourceFactoryProvider(
+ private val baseClient: OkHttpClient
+) {
+ private val clientsByProfile = ConcurrentHashMap<PlayerTimeoutProfile, OkHttpClient>()
+
+ fun createFactory(
+ streamInfo: StreamInfo,
+ resolvedStreamType: ResolvedStreamType,
+ preload: Boolean = false
+ ): Pair<PlayerTimeoutProfile, DataSource.Factory> {
+ val profile = PlayerTimeoutProfile.resolve(streamInfo, resolvedStreamType, preload)
+ val headers = buildMap {
+ putAll(streamInfo.headers)
+ streamInfo.userAgent?.takeIf { it.isNotBlank() }?.let { put("User-Agent", it) }
+ }
+ val client = clientsByProfile.computeIfAbsent(profile) {
+ baseClient.newBuilder()
+ .connectTimeout(profile.connectTimeoutMs, TimeUnit.MILLISECONDS)
+ .readTimeout(profile.readTimeoutMs, TimeUnit.MILLISECONDS)
+ .writeTimeout(profile.writeTimeoutMs, TimeUnit.MILLISECONDS)
+ .build()
+ }
+ val factory = OkHttpDataSource.Factory(client).apply {
+ if (headers.isNotEmpty()) {
+ setDefaultRequestProperties(headers)
+ }
+ }
+ return profile to factory
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerErrorClassifier.kt b/player/src/main/java/com/streamvault/player/playback/PlayerErrorClassifier.kt
new file mode 100644
index 00000000..1f902240
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerErrorClassifier.kt
@@ -0,0 +1,105 @@
+package com.streamvault.player.playback
+
+import androidx.media3.common.ParserException
+import androidx.media3.common.PlaybackException
+import androidx.media3.datasource.HttpDataSource
+import androidx.media3.exoplayer.mediacodec.MediaCodecRenderer
+import androidx.media3.exoplayer.source.BehindLiveWindowException
+import java.io.EOFException
+import java.net.ConnectException
+import java.net.SocketTimeoutException
+import java.net.UnknownHostException
+import javax.net.ssl.SSLException
+import javax.net.ssl.SSLHandshakeException
+
+enum class PlaybackErrorCategory {
+ NETWORK,
+ HTTP_AUTH,
+ HTTP_SERVER,
+ FORMAT_UNSUPPORTED,
+ DECODER,
+ DRM,
+ SOURCE_MALFORMED,
+ LIVE_WINDOW,
+ CLEAR_TEXT_BLOCKED,
+ SSL,
+ UNKNOWN
+}
+
+object PlayerErrorClassifier {
+ fun classify(error: Throwable): PlaybackErrorCategory {
+ val chain = generateSequence(error) { it.cause }.toList()
+ val playbackException = chain.filterIsInstance<PlaybackException>().firstOrNull()
+ val httpError = chain.filterIsInstance<HttpDataSource.InvalidResponseCodeException>().firstOrNull()
+
+ val httpCode = httpError?.responseCode
+ ?: when (playbackException?.errorCode) {
+ PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS -> parseHttpStatus(playbackException.message)
+ else -> null
+ }
+ ?: chain.firstNotNullOfOrNull { parseHttpStatus(it.message) }
+
+ return when {
+ chain.any { it is BehindLiveWindowException } ||
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW ->
+ PlaybackErrorCategory.LIVE_WINDOW
+ httpCode == 401 || httpCode == 403 -> PlaybackErrorCategory.HTTP_AUTH
+ httpCode in setOf(408, 429, 500, 502, 503, 504) -> PlaybackErrorCategory.HTTP_SERVER
+ chain.any { it is SSLHandshakeException || it is SSLException } ||
+ chain.any { it.message?.contains("certificate", ignoreCase = true) == true } ->
+ PlaybackErrorCategory.SSL
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED ||
+ chain.any { it.message?.contains("cleartext", ignoreCase = true) == true } ->
+ PlaybackErrorCategory.CLEAR_TEXT_BLOCKED
+ chain.any { it is MediaCodecRenderer.DecoderInitializationException } ||
+ chain.any {
+ it.message?.contains("decoder init", ignoreCase = true) == true ||
+ it.message?.contains("codec init", ignoreCase = true) == true
+ } ||
+ playbackException?.errorCode in decoderErrors ->
+ PlaybackErrorCategory.DECODER
+ playbackException?.errorCode in drmErrors -> PlaybackErrorCategory.DRM
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED ||
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES ||
+ chain.any { it.message?.contains("unsupported", ignoreCase = true) == true } ->
+ PlaybackErrorCategory.FORMAT_UNSUPPORTED
+ chain.any { it is ParserException } ||
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED ||
+ playbackException?.errorCode == PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED ->
+ PlaybackErrorCategory.SOURCE_MALFORMED
+ chain.any { it is SocketTimeoutException || it is ConnectException || it is UnknownHostException || it is EOFException } ||
+ playbackException?.errorCode in networkErrors ->
+ PlaybackErrorCategory.NETWORK
+ else -> PlaybackErrorCategory.UNKNOWN
+ }
+ }
+
+ private fun parseHttpStatus(message: String?): Int? {
+ return Regex("""\b(401|403|408|429|500|502|503|504)\b""").find(message.orEmpty())
+ ?.groupValues
+ ?.getOrNull(1)
+ ?.toIntOrNull()
+ }
+
+ private val networkErrors = setOf(
+ PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
+ PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT,
+ PlaybackException.ERROR_CODE_IO_UNSPECIFIED
+ )
+ private val decoderErrors = setOf(
+ PlaybackException.ERROR_CODE_DECODER_INIT_FAILED,
+ PlaybackException.ERROR_CODE_DECODER_QUERY_FAILED,
+ PlaybackException.ERROR_CODE_DECODING_FAILED
+ )
+ private val drmErrors = setOf(
+ PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR,
+ PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED,
+ PlaybackException.ERROR_CODE_DRM_DISALLOWED_OPERATION,
+ PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED,
+ PlaybackException.ERROR_CODE_DRM_LICENSE_EXPIRED,
+ PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED,
+ PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED,
+ PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR,
+ PlaybackException.ERROR_CODE_DRM_UNSPECIFIED
+ )
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
new file mode 100644
index 00000000..d1942422
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
@@ -0,0 +1,112 @@
+package com.streamvault.player.playback
+
+import android.net.Uri
+import android.util.Log
+import androidx.media3.common.MediaItem
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.extractor.DefaultExtractorsFactory
+import androidx.media3.exoplayer.dash.DashMediaSource
+import androidx.media3.exoplayer.hls.HlsMediaSource
+import androidx.media3.exoplayer.rtsp.RtspMediaSource
+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
+import androidx.media3.exoplayer.source.MediaSource
+import androidx.media3.exoplayer.source.ProgressiveMediaSource
+import com.streamvault.domain.model.DrmInfo
+import com.streamvault.domain.model.DrmScheme
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import java.util.UUID
+import androidx.media3.common.C
+
+@UnstableApi
+class PlayerMediaSourceFactory(
+ private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider
+) {
+ fun create(
+ streamInfo: StreamInfo,
+ resolvedStreamType: ResolvedStreamType,
+ retryPolicy: PlayerRetryPolicy,
+ preload: Boolean = false
+ ): Pair<PlayerTimeoutProfile, MediaSource> {
+ val (timeoutProfile, dataSourceFactory) = dataSourceFactoryProvider.createFactory(
+ streamInfo = streamInfo,
+ resolvedStreamType = resolvedStreamType,
+ preload = preload
+ )
+ val mediaItem = buildMediaItem(streamInfo)
+ val mediaSource = when {
+ streamInfo.streamType == StreamType.RTSP -> RtspMediaSource.Factory().createMediaSource(mediaItem)
+ resolvedStreamType == ResolvedStreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory)
+ .setAllowChunklessPreparation(true)
+ .setLoadErrorHandlingPolicy(retryPolicy)
+ .createMediaSource(mediaItem)
+
+ resolvedStreamType == ResolvedStreamType.DASH -> DashMediaSource.Factory(dataSourceFactory)
+ .setLoadErrorHandlingPolicy(retryPolicy)
+ .createMediaSource(mediaItem)
+
+ resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> ProgressiveMediaSource.Factory(
+ dataSourceFactory,
+ DefaultExtractorsFactory().setTsExtractorFlags(0)
+ )
+ .setLoadErrorHandlingPolicy(retryPolicy)
+ .createMediaSource(mediaItem)
+
+ resolvedStreamType == ResolvedStreamType.PROGRESSIVE -> ProgressiveMediaSource.Factory(dataSourceFactory)
+ .setLoadErrorHandlingPolicy(retryPolicy)
+ .createMediaSource(mediaItem)
+
+ else -> DefaultMediaSourceFactory(dataSourceFactory)
+ .setLoadErrorHandlingPolicy(retryPolicy)
+ .createMediaSource(mediaItem)
+ }
+
+ Log.i(
+ TAG,
+ "media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ )
+ return timeoutProfile to mediaSource
+ }
+
+ private fun buildMediaItem(streamInfo: StreamInfo): MediaItem {
+ return MediaItem.Builder()
+ .setUri(Uri.parse(streamInfo.url))
+ .setMediaId(mediaIdFor(streamInfo))
+ .setMediaMetadata(
+ androidx.media3.common.MediaMetadata.Builder()
+ .setTitle(streamInfo.title)
+ .build()
+ )
+ .apply {
+ streamInfo.drmInfo?.let { drmInfo ->
+ setDrmConfiguration(
+ MediaItem.DrmConfiguration.Builder(drmInfo.scheme.toUuid())
+ .setLicenseUri(drmInfo.licenseUrl)
+ .setLicenseRequestHeaders(drmInfo.headers)
+ .setMultiSession(drmInfo.multiSession)
+ .setForceDefaultLicenseUri(drmInfo.forceDefaultLicenseUrl)
+ .setPlayClearContentWithoutKey(drmInfo.playClearContentWithoutKey)
+ .build()
+ )
+ }
+ }
+ .build()
+ }
+
+ fun mediaIdFor(streamInfo: StreamInfo): String {
+ val drmKey = streamInfo.drmInfo?.let { "${it.scheme}:${it.licenseUrl}" }.orEmpty()
+ return "${streamInfo.url}|${streamInfo.title.orEmpty()}|$drmKey".hashCode().toString()
+ }
+
+ private fun DrmScheme.toUuid(): UUID = when (this) {
+ DrmScheme.WIDEVINE -> C.WIDEVINE_UUID
+ DrmScheme.PLAYREADY -> C.PLAYREADY_UUID
+ DrmScheme.CLEARKEY -> C.CLEARKEY_UUID
+ }
+
+ companion object {
+ private const val TAG = "PlayerMediaSourceFactory"
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt
new file mode 100644
index 00000000..4bd4719b
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt
@@ -0,0 +1,123 @@
+package com.streamvault.player.playback
+
+import androidx.media3.common.C
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.HttpDataSource
+import androidx.media3.exoplayer.source.BehindLiveWindowException
+import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy
+import java.net.ConnectException
+import java.net.SocketTimeoutException
+import java.net.UnknownHostException
+
+data class PlaybackRetryContext(
+ val resolvedStreamType: ResolvedStreamType,
+ val timeoutProfile: PlayerTimeoutProfile
+) {
+ val isLive: Boolean
+ get() = resolvedStreamType == ResolvedStreamType.HLS || resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE
+}
+
+@UnstableApi
+class PlayerRetryPolicy(
+ private val streamContext: PlaybackRetryContext,
+ private val playbackStarted: () -> Boolean
+) : LoadErrorHandlingPolicy {
+ fun maxAttempts(error: Throwable, playbackStarted: Boolean): Int {
+ return maxAttemptsFor(error, streamContext, playbackStarted)
+ }
+
+ fun shouldRetry(
+ error: Throwable,
+ streamContext: PlaybackRetryContext,
+ playbackStarted: Boolean,
+ attempt: Int
+ ): Boolean {
+ val category = PlayerErrorClassifier.classify(error)
+ if (playbackStarted && category in setOf(
+ PlaybackErrorCategory.DECODER,
+ PlaybackErrorCategory.FORMAT_UNSUPPORTED,
+ PlaybackErrorCategory.DRM
+ )
+ ) {
+ return false
+ }
+ val maxAttempts = maxAttemptsFor(error, streamContext, playbackStarted)
+ return attempt <= maxAttempts && maxAttempts > 0
+ }
+
+ fun retryDelayMs(error: Throwable, attempt: Int): Long {
+ if (PlayerErrorClassifier.classify(error) == PlaybackErrorCategory.LIVE_WINDOW) return 0L
+ return when (attempt) {
+ 1 -> 1_000L
+ 2 -> 2_500L
+ else -> 5_000L
+ }.coerceAtMost(5_000L)
+ }
+
+ fun retryReason(error: Throwable): String {
+ return when (PlayerErrorClassifier.classify(error)) {
+ PlaybackErrorCategory.LIVE_WINDOW -> "refresh-live-window"
+ PlaybackErrorCategory.NETWORK -> "transient-network"
+ PlaybackErrorCategory.HTTP_SERVER -> "server-retryable"
+ else -> "retryable-source"
+ }
+ }
+
+ override fun getFallbackSelectionFor(
+ fallbackOptions: LoadErrorHandlingPolicy.FallbackOptions,
+ loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo
+ ): LoadErrorHandlingPolicy.FallbackSelection? = null
+
+ override fun getMinimumLoadableRetryCount(dataType: Int): Int {
+ return when {
+ dataType == C.DATA_TYPE_MANIFEST -> 3
+ dataType == C.DATA_TYPE_MEDIA -> if (streamContext.resolvedStreamType == ResolvedStreamType.PROGRESSIVE) 2 else 2
+ else -> 1
+ }
+ }
+
+ override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long {
+ val attempt = loadErrorInfo.errorCount
+ val error = loadErrorInfo.exception
+ val started = playbackStarted()
+ if (!shouldRetry(error, streamContext, started, attempt)) {
+ return C.TIME_UNSET
+ }
+ return retryDelayMs(error, attempt)
+ }
+
+ override fun onLoadTaskConcluded(loadTaskId: Long) = Unit
+
+ private fun maxAttemptsFor(
+ error: Throwable,
+ streamContext: PlaybackRetryContext,
+ playbackStarted: Boolean
+ ): Int {
+ return when (PlayerErrorClassifier.classify(error)) {
+ PlaybackErrorCategory.DRM,
+ PlaybackErrorCategory.DECODER,
+ PlaybackErrorCategory.CLEAR_TEXT_BLOCKED,
+ PlaybackErrorCategory.SSL,
+ PlaybackErrorCategory.HTTP_AUTH,
+ PlaybackErrorCategory.FORMAT_UNSUPPORTED -> 0
+
+ PlaybackErrorCategory.LIVE_WINDOW -> 1
+ PlaybackErrorCategory.HTTP_SERVER -> if (streamContext.isLive) 3 else 2
+ PlaybackErrorCategory.NETWORK -> when {
+ error.hasCause<UnknownHostException>() -> 1
+ error.hasCause<SocketTimeoutException>() || error.hasCause<ConnectException>() ->
+ if (streamContext.isLive) 3 else 2
+ !playbackStarted -> if (streamContext.isLive) 3 else 2
+ else -> 1
+ }
+
+ PlaybackErrorCategory.SOURCE_MALFORMED -> if (playbackStarted) 0 else 1
+ PlaybackErrorCategory.UNKNOWN -> if (playbackStarted) 0 else 1
+ }
+ }
+
+ private inline fun <reified T : Throwable> Throwable.hasCause(): Boolean {
+ return generateSequence(this) { it.cause }.any { it is T }
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt b/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt
new file mode 100644
index 00000000..4b14fd29
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerTimeoutProfile.kt
@@ -0,0 +1,50 @@
+package com.streamvault.player.playback
+
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+
+enum class PlayerTimeoutProfile(
+ val connectTimeoutMs: Long,
+ val readTimeoutMs: Long,
+ val writeTimeoutMs: Long
+) {
+ LIVE(
+ connectTimeoutMs = 12_000L,
+ readTimeoutMs = 20_000L,
+ writeTimeoutMs = 20_000L
+ ),
+ VOD(
+ connectTimeoutMs = 15_000L,
+ readTimeoutMs = 45_000L,
+ writeTimeoutMs = 30_000L
+ ),
+ PROGRESSIVE(
+ connectTimeoutMs = 15_000L,
+ readTimeoutMs = 35_000L,
+ writeTimeoutMs = 30_000L
+ ),
+ PRELOAD(
+ connectTimeoutMs = 10_000L,
+ readTimeoutMs = 15_000L,
+ writeTimeoutMs = 15_000L
+ );
+
+ companion object {
+ fun resolve(
+ streamInfo: StreamInfo,
+ resolvedStreamType: ResolvedStreamType,
+ preload: Boolean
+ ): PlayerTimeoutProfile {
+ if (preload) return PRELOAD
+ if (streamInfo.streamType == StreamType.RTSP) return LIVE
+ return when {
+ resolvedStreamType == ResolvedStreamType.HLS -> LIVE
+ resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> LIVE
+ resolvedStreamType == ResolvedStreamType.PROGRESSIVE -> PROGRESSIVE
+ streamInfo.streamType == StreamType.PROGRESSIVE -> PROGRESSIVE
+ else -> VOD
+ }
+ }
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt b/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt
new file mode 100644
index 00000000..ab809667
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt
@@ -0,0 +1,119 @@
+package com.streamvault.player.playback
+
+import android.util.Log
+import androidx.media3.exoplayer.source.MediaSource
+import com.streamvault.domain.model.StreamInfo
+
+class PreloadCoordinator(
+ private val nowMs: () -> Long = { System.currentTimeMillis() }
+) {
+ var currentPreloadedMediaId: String? = null
+ private set
+ var currentPreloadedUrlHash: String? = null
+ private set
+ var preloadedMediaSource: MediaSource? = null
+ private set
+ var createdAtMs: Long = 0L
+ private set
+
+ private var currentResolvedType: ResolvedStreamType? = null
+ private var currentDrmKey: String? = null
+ private var currentHeadersHash: Int? = null
+
+ fun store(mediaId: String, streamInfo: StreamInfo, resolvedType: ResolvedStreamType, mediaSource: MediaSource) {
+ currentPreloadedMediaId = mediaId
+ currentPreloadedUrlHash = normalizedUrlHash(streamInfo.url)
+ preloadedMediaSource = mediaSource
+ currentResolvedType = resolvedType
+ currentDrmKey = drmKey(streamInfo)
+ currentHeadersHash = headersHash(streamInfo)
+ createdAtMs = nowMs()
+ safeLog("preload stored mediaId=$mediaId type=$resolvedType target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}")
+ }
+
+ fun tryReuse(mediaId: String, streamInfo: StreamInfo, resolvedType: ResolvedStreamType): MediaSource? {
+ val result = when {
+ preloadedMediaSource == null -> null
+ isExpired() -> {
+ invalidate("expired")
+ null
+ }
+ currentPreloadedMediaId != mediaId -> {
+ invalidate("different-media-id")
+ null
+ }
+ currentPreloadedUrlHash != normalizedUrlHash(streamInfo.url) -> {
+ invalidate("different-url")
+ null
+ }
+ currentResolvedType != resolvedType -> {
+ invalidate("different-stream-type")
+ null
+ }
+ currentDrmKey != drmKey(streamInfo) -> {
+ invalidate("different-drm")
+ null
+ }
+ currentHeadersHash != headersHash(streamInfo) -> {
+ invalidate("different-headers")
+ null
+ }
+ else -> preloadedMediaSource
+ }
+ if (result != null) {
+ safeLog("preload reused mediaId=$mediaId target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}")
+ clear()
+ }
+ return result
+ }
+
+ fun onPlaybackStarted(mediaId: String) {
+ if (currentPreloadedMediaId != null && currentPreloadedMediaId != mediaId) {
+ invalidate("playback-started-different-media")
+ }
+ }
+
+ fun invalidate(reason: String) {
+ if (preloadedMediaSource != null) {
+ safeLog("preload invalidated reason=$reason mediaId=$currentPreloadedMediaId")
+ }
+ clear()
+ }
+
+ fun release() {
+ invalidate("release")
+ }
+
+ fun isExpired(): Boolean = preloadedMediaSource != null && nowMs() - createdAtMs > PRELOAD_EXPIRY_MS
+
+ private fun clear() {
+ currentPreloadedMediaId = null
+ currentPreloadedUrlHash = null
+ preloadedMediaSource = null
+ currentResolvedType = null
+ currentDrmKey = null
+ currentHeadersHash = null
+ createdAtMs = 0L
+ }
+
+ private fun normalizedUrlHash(url: String): String {
+ return url.trim().substringBefore('#').hashCode().toString()
+ }
+
+ private fun drmKey(streamInfo: StreamInfo): String? {
+ return streamInfo.drmInfo?.let { "${it.scheme}:${it.licenseUrl}:${it.headers.hashCode()}" }
+ }
+
+ private fun headersHash(streamInfo: StreamInfo): Int {
+ return (streamInfo.headers.toSortedMap() + ("User-Agent" to (streamInfo.userAgent ?: ""))).hashCode()
+ }
+
+ companion object {
+ private const val TAG = "PreloadCoordinator"
+ private const val PRELOAD_EXPIRY_MS = 2 * 60 * 1000L
+ }
+
+ private fun safeLog(message: String) {
+ runCatching { Log.i(TAG, message) }
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt
new file mode 100644
index 00000000..ac20e275
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt
@@ -0,0 +1,59 @@
+package com.streamvault.player.playback
+
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import java.net.URI
+import java.util.Locale
+
+enum class ResolvedStreamType {
+ HLS,
+ DASH,
+ PROGRESSIVE,
+ MPEG_TS_LIVE,
+ UNKNOWN
+}
+
+object StreamTypeResolver {
+ private val progressiveExtensions = listOf(".mp4", ".mkv", ".avi", ".mov", ".mp3", ".aac", ".m4a")
+ private val hlsMimeHints = listOf(
+ "application/vnd.apple.mpegurl",
+ "application/x-mpegurl"
+ )
+ private val dashMimeHints = listOf("application/dash+xml")
+
+ fun resolve(streamInfo: StreamInfo, mimeType: String? = null): ResolvedStreamType {
+ return when (streamInfo.streamType) {
+ StreamType.HLS -> ResolvedStreamType.HLS
+ StreamType.DASH -> ResolvedStreamType.DASH
+ StreamType.MPEG_TS -> ResolvedStreamType.MPEG_TS_LIVE
+ StreamType.PROGRESSIVE -> ResolvedStreamType.PROGRESSIVE
+ else -> resolve(url = streamInfo.url, mimeType = mimeType, isLive = isLive(streamInfo))
+ }
+ }
+
+ fun resolve(url: String, mimeType: String? = null, isLive: Boolean = false): ResolvedStreamType {
+ val normalizedMimeType = mimeType?.trim()?.lowercase(Locale.ROOT)
+ val path = runCatching { URI(url).path.orEmpty() }.getOrDefault(url)
+ .substringBefore('?')
+ .substringBefore('#')
+ .lowercase(Locale.ROOT)
+ return when {
+ normalizedMimeType != null && hlsMimeHints.any(normalizedMimeType::contains) -> ResolvedStreamType.HLS
+ normalizedMimeType != null && dashMimeHints.any(normalizedMimeType::contains) -> ResolvedStreamType.DASH
+ path.contains(".m3u8") -> ResolvedStreamType.HLS
+ path.contains(".mpd") -> ResolvedStreamType.DASH
+ path.endsWith(".ts") -> ResolvedStreamType.MPEG_TS_LIVE
+ isLive && path.contains("/live/") && progressiveExtensions.none(path::endsWith) ->
+ ResolvedStreamType.MPEG_TS_LIVE
+ progressiveExtensions.any(path::endsWith) -> ResolvedStreamType.PROGRESSIVE
+ else -> ResolvedStreamType.UNKNOWN
+ }
+ }
+
+ private fun isLive(streamInfo: StreamInfo): Boolean {
+ return streamInfo.streamType == StreamType.MPEG_TS ||
+ streamInfo.url.contains("/live/", ignoreCase = true) ||
+ streamInfo.catchUpUrl != null
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt
new file mode 100644
index 00000000..30512bc4
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt
@@ -0,0 +1,126 @@
+package com.streamvault.player.stats
+
+import androidx.media3.common.Format
+import androidx.media3.exoplayer.ExoPlayer
+import com.streamvault.domain.model.VideoFormat
+import com.streamvault.player.PlayerStats
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+
+class PlayerStatsCollector(
+ private val scope: CoroutineScope,
+ private val currentPosition: MutableStateFlow<Long>,
+ private val duration: MutableStateFlow<Long>,
+ private val videoFormat: MutableStateFlow<VideoFormat>,
+ private val playerStats: MutableStateFlow<PlayerStats>
+) {
+ private var positionJob: Job? = null
+ private var bufferedJob: Job? = null
+ private var statsJob: Job? = null
+ private var playerProvider: (() -> ExoPlayer?)? = null
+ private var lastVideoFormat: Format? = null
+ private var lastAudioFormat: Format? = null
+ private var lastFrameRate = 0f
+ private var lastBandwidthEstimate = 0L
+ private var droppedFrames = 0
+
+ fun bind(playerProvider: () -> ExoPlayer?) {
+ this.playerProvider = playerProvider
+ }
+
+ fun reset() {
+ lastVideoFormat = null
+ lastAudioFormat = null
+ lastFrameRate = 0f
+ lastBandwidthEstimate = 0L
+ droppedFrames = 0
+ currentPosition.value = 0L
+ duration.value = 0L
+ videoFormat.value = VideoFormat(0, 0)
+ playerStats.value = PlayerStats()
+ }
+
+ fun onVideoFormatChanged(format: Format) {
+ lastVideoFormat = format
+ lastFrameRate = format.frameRate.takeIf { it > 0f } ?: lastFrameRate
+ }
+
+ fun onAudioFormatChanged(format: Format) {
+ lastAudioFormat = format
+ }
+
+ fun onDroppedFrames(count: Int) {
+ droppedFrames += count
+ }
+
+ fun onBandwidthEstimate(bitrateEstimate: Long) {
+ if (bitrateEstimate > 0L) {
+ lastBandwidthEstimate = bitrateEstimate
+ }
+ }
+
+ fun incrementRebufferCount() {
+ playerStats.value = playerStats.value.copy(rebufferCount = playerStats.value.rebufferCount + 1)
+ }
+
+ fun start() {
+ stop()
+ positionJob = scope.launch {
+ while (isActive) {
+ playerProvider?.invoke()?.let { player ->
+ currentPosition.value = player.currentPosition
+ duration.value = player.duration.coerceAtLeast(0L)
+ }
+ delay(250L)
+ }
+ }
+ bufferedJob = scope.launch {
+ while (isActive) {
+ playerProvider?.invoke()?.let { player ->
+ val bufferedDuration = (player.bufferedPosition - player.currentPosition).coerceAtLeast(0L)
+ playerStats.value = playerStats.value.copy(bufferedDurationMs = bufferedDuration)
+ }
+ delay(500L)
+ }
+ }
+ statsJob = scope.launch {
+ while (isActive) {
+ playerProvider?.invoke()?.let { player ->
+ val video = lastVideoFormat
+ val audio = lastAudioFormat
+ videoFormat.value = VideoFormat(
+ width = video?.width?.takeIf { it > 0 } ?: 0,
+ height = video?.height?.takeIf { it > 0 } ?: 0,
+ frameRate = lastFrameRate,
+ bitrate = video?.bitrate?.takeIf { it > 0 } ?: 0,
+ codecV = video?.sampleMimeType ?: video?.codecs,
+ codecA = audio?.sampleMimeType ?: audio?.codecs
+ )
+ playerStats.value = playerStats.value.copy(
+ videoCodec = video?.sampleMimeType ?: video?.codecs ?: playerStats.value.videoCodec,
+ audioCodec = audio?.sampleMimeType ?: audio?.codecs ?: playerStats.value.audioCodec,
+ videoBitrate = video?.bitrate?.takeIf { it > 0 } ?: playerStats.value.videoBitrate,
+ droppedFrames = droppedFrames,
+ width = video?.width?.takeIf { it > 0 } ?: playerStats.value.width,
+ height = video?.height?.takeIf { it > 0 } ?: playerStats.value.height,
+ bandwidthEstimate = lastBandwidthEstimate
+ )
+ }
+ delay(1000L)
+ }
+ }
+ }
+
+ fun stop() {
+ positionJob?.cancel()
+ bufferedJob?.cancel()
+ statsJob?.cancel()
+ positionJob = null
+ bufferedJob = null
+ statsJob = null
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt
new file mode 100644
index 00000000..a06fbb7a
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt
@@ -0,0 +1,261 @@
+package com.streamvault.player.tracks
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import androidx.media3.common.C
+import androidx.media3.common.Format
+import androidx.media3.common.TrackSelectionOverride
+import androidx.media3.common.Tracks
+import androidx.media3.exoplayer.ExoPlayer
+import com.streamvault.player.PLAYER_TRACK_AUTO_ID
+import com.streamvault.player.PlayerTrack
+import com.streamvault.player.TrackType
+import java.util.Locale
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+
+class PlayerTrackController(
+ private val context: Context
+) {
+ private val _availableAudioTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
+ val availableAudioTracks: StateFlow<List<PlayerTrack>> = _availableAudioTracks.asStateFlow()
+
+ private val _availableSubtitleTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
+ val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = _availableSubtitleTracks.asStateFlow()
+
+ private val _availableVideoTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
+ val availableVideoTracks: StateFlow<List<PlayerTrack>> = _availableVideoTracks.asStateFlow()
+
+ private var selectedVideoTrackId: String = PLAYER_TRACK_AUTO_ID
+ private var preferredAudioLanguageTag: String? = null
+ private var preferredWifiMaxVideoHeight: Int? = null
+ private var preferredEthernetMaxVideoHeight: Int? = null
+
+ fun resetSelections() {
+ _availableAudioTracks.value = emptyList()
+ _availableSubtitleTracks.value = emptyList()
+ _availableVideoTracks.value = emptyList()
+ selectedVideoTrackId = PLAYER_TRACK_AUTO_ID
+ }
+
+ fun applyInitialParameters(player: ExoPlayer, constrainResolutionForMultiView: Boolean) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .clearOverridesOfType(C.TRACK_TYPE_AUDIO)
+ .clearOverridesOfType(C.TRACK_TYPE_TEXT)
+ .clearOverridesOfType(C.TRACK_TYPE_VIDEO)
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
+ .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
+ .setPreferredAudioLanguage(preferredAudioLanguageTag)
+ .apply {
+ resolvedMaxVideoHeightForCurrentNetwork(constrainResolutionForMultiView)?.let { maxHeight ->
+ setMaxVideoSize(Int.MAX_VALUE, maxHeight)
+ } ?: clearVideoSizeConstraints()
+ }
+ .build()
+ }
+
+ fun setPreferredAudioLanguage(player: ExoPlayer?, languageTag: String?) {
+ preferredAudioLanguageTag = languageTag?.trim()?.takeIf { it.isNotBlank() }
+ player?.trackSelectionParameters = player?.trackSelectionParameters
+ ?.buildUpon()
+ ?.setPreferredAudioLanguage(preferredAudioLanguageTag)
+ ?.build()
+ ?: return
+ }
+
+ fun setNetworkQualityPreferences(wifiMaxHeight: Int?, ethernetMaxHeight: Int?) {
+ preferredWifiMaxVideoHeight = wifiMaxHeight?.takeIf { it > 0 }
+ preferredEthernetMaxVideoHeight = ethernetMaxHeight?.takeIf { it > 0 }
+ }
+
+ fun onTracksChanged(tracks: Tracks) {
+ val audioTracks = mutableListOf<PlayerTrack>()
+ val subtitleTracks = mutableListOf<PlayerTrack>()
+ val videoTracks = mutableListOf<PlayerTrack>()
+
+ for (group in tracks.groups) {
+ val type = group.mediaTrackGroup.type
+ val isAudio = type == C.TRACK_TYPE_AUDIO
+ val isText = type == C.TRACK_TYPE_TEXT
+ val isVideo = type == C.TRACK_TYPE_VIDEO
+
+ if (isAudio || isText || isVideo) {
+ for (index in 0 until group.length) {
+ val format = group.mediaTrackGroup.getFormat(index)
+ val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$index"
+ val track = PlayerTrack(
+ id = id,
+ name = buildTrackName(format, type, index),
+ language = format.language,
+ type = when {
+ isAudio -> TrackType.AUDIO
+ isText -> TrackType.TEXT
+ else -> TrackType.VIDEO
+ },
+ isSelected = if (isVideo) selectedVideoTrackId == id else group.isTrackSelected(index)
+ )
+ when {
+ isAudio && group.isTrackSupported(index, false) -> audioTracks += track
+ isText && group.isTrackSupported(index, false) -> subtitleTracks += track
+ isVideo && group.isTrackSupported(index, false) -> videoTracks += track
+ }
+ }
+ }
+ }
+
+ _availableAudioTracks.value = audioTracks
+ _availableSubtitleTracks.value = subtitleTracks
+ _availableVideoTracks.value = when {
+ videoTracks.size > 1 -> listOf(
+ PlayerTrack(
+ id = PLAYER_TRACK_AUTO_ID,
+ name = "Auto",
+ language = null,
+ type = TrackType.VIDEO,
+ isSelected = selectedVideoTrackId == PLAYER_TRACK_AUTO_ID
+ )
+ ) + videoTracks
+ videoTracks.size == 1 -> listOf(videoTracks.first().copy(isSelected = true))
+ else -> emptyList()
+ }
+ }
+
+ fun selectAudioTrack(player: ExoPlayer, trackId: String) {
+ val override = findOverride(player.currentTracks, C.TRACK_TYPE_AUDIO, trackId) ?: return
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
+ .setOverrideForType(override)
+ .build()
+ }
+
+ fun selectVideoTrack(player: ExoPlayer, trackId: String) {
+ selectedVideoTrackId = trackId
+ if (trackId == PLAYER_TRACK_AUTO_ID) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .clearOverridesOfType(C.TRACK_TYPE_VIDEO)
+ .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
+ .build()
+ } else {
+ val override = findOverride(player.currentTracks, C.TRACK_TYPE_VIDEO, trackId) ?: return
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, false)
+ .setOverrideForType(override)
+ .build()
+ }
+ _availableVideoTracks.update { tracks ->
+ tracks.map { it.copy(isSelected = it.id == trackId) }
+ }
+ }
+
+ fun selectSubtitleTrack(player: ExoPlayer, trackId: String?) {
+ if (trackId == null) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
+ .clearOverridesOfType(C.TRACK_TYPE_TEXT)
+ .build()
+ return
+ }
+ val override = findOverride(player.currentTracks, C.TRACK_TYPE_TEXT, trackId) ?: return
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)
+ .setOverrideForType(override)
+ .build()
+ }
+
+ private fun findOverride(tracks: Tracks, trackType: Int, trackId: String): TrackSelectionOverride? {
+ for (group in tracks.groups) {
+ if (group.mediaTrackGroup.type != trackType) continue
+ for (index in 0 until group.length) {
+ val format = group.mediaTrackGroup.getFormat(index)
+ val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$index"
+ if (id == trackId) {
+ return TrackSelectionOverride(group.mediaTrackGroup, listOf(index))
+ }
+ }
+ }
+ return null
+ }
+
+ private fun resolvedMaxVideoHeightForCurrentNetwork(constrainResolutionForMultiView: Boolean): Int? {
+ val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
+ val network = connectivityManager?.activeNetwork ?: return null
+ val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return null
+ val networkPreference = when {
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> preferredEthernetMaxVideoHeight
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> preferredWifiMaxVideoHeight
+ else -> null
+ }
+ return when {
+ constrainResolutionForMultiView && networkPreference != null -> minOf(720, networkPreference)
+ constrainResolutionForMultiView -> 720
+ else -> networkPreference
+ }
+ }
+
+ private fun buildTrackName(format: Format, trackType: Int, index: Int): String {
+ if (trackType == C.TRACK_TYPE_VIDEO) return buildVideoTrackName(format, index)
+
+ val explicitLabel = format.label
+ ?.trim()
+ ?.takeIf { it.isNotBlank() && !it.matches(Regex("(?i)^track\\s*\\d+$")) }
+ if (explicitLabel != null) return explicitLabel
+
+ val parts = mutableListOf<String>()
+ format.language
+ ?.takeIf { it.isNotBlank() && it != C.LANGUAGE_UNDETERMINED }
+ ?.let { code ->
+ val locale = Locale.forLanguageTag(code)
+ val display = locale.getDisplayLanguage(Locale.getDefault())
+ .takeIf { it.isNotBlank() }
+ ?: locale.displayLanguage.takeIf { it.isNotBlank() }
+ if (!display.isNullOrBlank()) {
+ parts += display.replaceFirstChar {
+ if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
+ }
+ }
+ }
+
+ if (trackType == C.TRACK_TYPE_TEXT) {
+ if ((format.selectionFlags and C.SELECTION_FLAG_FORCED) != 0) parts += "Forced"
+ if ((format.roleFlags and C.ROLE_FLAG_CAPTION) != 0) parts += "CC"
+ if ((format.roleFlags and C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND) != 0) parts += "SDH"
+ }
+
+ if (parts.isNotEmpty()) return parts.joinToString(" ")
+ return when (trackType) {
+ C.TRACK_TYPE_AUDIO -> "Audio ${index + 1}"
+ C.TRACK_TYPE_TEXT -> "Subtitle ${index + 1}"
+ else -> "Track ${index + 1}"
+ }
+ }
+
+ private fun buildVideoTrackName(format: Format, index: Int): String {
+ val parts = mutableListOf<String>()
+ val explicitLabel = format.label
+ ?.trim()
+ ?.takeIf { it.isNotBlank() && !it.matches(Regex("(?i)^track\\s*\\d+$")) }
+ val resolutionLabel = when {
+ format.height > 0 -> "${format.height}p"
+ format.width > 0 && format.height > 0 -> "${format.width}x${format.height}"
+ else -> null
+ }
+ val bitrateLabel = format.bitrate.takeIf { it > 0 }
+ ?.let { bitrate -> String.format(Locale.US, "%.1f Mbps", bitrate / 1_000_000f) }
+ explicitLabel?.let(parts::add)
+ if (!resolutionLabel.isNullOrBlank() && parts.none { it.contains(resolutionLabel, true) }) parts += resolutionLabel
+ if (!bitrateLabel.isNullOrBlank()) parts += bitrateLabel
+ return parts.firstOrNull()?.takeIf { parts.size == 1 }
+ ?: parts.joinToString(" · ").ifBlank { "Quality ${index + 1}" }
+ }
+}
+
diff --git a/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt b/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt
new file mode 100644
index 00000000..694eb799
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt
@@ -0,0 +1,74 @@
+package com.streamvault.player.ui
+
+import android.content.Context
+import android.graphics.Color
+import android.view.LayoutInflater
+import android.view.View
+import android.widget.FrameLayout
+import androidx.media3.ui.AspectRatioFrameLayout
+import androidx.media3.ui.PlayerView
+import com.streamvault.player.PlayerSurfaceResizeMode
+import com.streamvault.player.R
+
+class PlayerViewBinder(
+ private val subtitleStyleController: SubtitleStyleController
+) {
+ private var boundPlayerView: PlayerView? = null
+ private var boundResizeMode: PlayerSurfaceResizeMode = PlayerSurfaceResizeMode.FIT
+
+ fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode): View {
+ return (LayoutInflater.from(context).inflate(R.layout.player_texture_view, null) as PlayerView).apply {
+ layoutParams = FrameLayout.LayoutParams(
+ FrameLayout.LayoutParams.MATCH_PARENT,
+ FrameLayout.LayoutParams.MATCH_PARENT
+ )
+ setShutterBackgroundColor(Color.BLACK)
+ applyResizeMode(resizeMode)
+ }
+ }
+
+ fun bind(renderView: View, player: androidx.media3.exoplayer.ExoPlayer, resizeMode: PlayerSurfaceResizeMode) {
+ val playerView = renderView as? PlayerView ?: return
+ boundResizeMode = resizeMode
+ if (boundPlayerView !== playerView) {
+ boundPlayerView?.player = null
+ playerView.player = player
+ boundPlayerView = playerView
+ } else if (playerView.player !== player) {
+ playerView.player = player
+ }
+ playerView.applyResizeMode(resizeMode)
+ subtitleStyleController.apply(playerView)
+ }
+
+ fun attachPlayer(player: androidx.media3.exoplayer.ExoPlayer?) {
+ boundPlayerView?.player = player
+ boundPlayerView?.applyResizeMode(boundResizeMode)
+ subtitleStyleController.apply(boundPlayerView)
+ }
+
+ fun release(renderView: View) {
+ val playerView = renderView as? PlayerView ?: return
+ playerView.player = null
+ if (boundPlayerView === playerView) {
+ boundPlayerView = null
+ }
+ }
+
+ fun clear() {
+ boundPlayerView?.player = null
+ boundPlayerView = null
+ }
+
+ fun reapplyStyle() {
+ subtitleStyleController.apply(boundPlayerView)
+ }
+
+ private fun PlayerView.applyResizeMode(surfaceResizeMode: PlayerSurfaceResizeMode) {
+ resizeMode = when (surfaceResizeMode) {
+ PlayerSurfaceResizeMode.FIT -> AspectRatioFrameLayout.RESIZE_MODE_FIT
+ PlayerSurfaceResizeMode.FILL -> AspectRatioFrameLayout.RESIZE_MODE_FILL
+ PlayerSurfaceResizeMode.ZOOM -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM
+ }
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/ui/SubtitleStyleController.kt b/player/src/main/java/com/streamvault/player/ui/SubtitleStyleController.kt
new file mode 100644
index 00000000..61f61517
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/ui/SubtitleStyleController.kt
@@ -0,0 +1,39 @@
+package com.streamvault.player.ui
+
+import android.graphics.Color
+import androidx.media3.ui.CaptionStyleCompat
+import androidx.media3.ui.PlayerView
+import androidx.media3.ui.SubtitleView
+import com.streamvault.player.PlayerSubtitleStyle
+
+class SubtitleStyleController {
+ private var style: PlayerSubtitleStyle = PlayerSubtitleStyle()
+
+ fun updateStyle(style: PlayerSubtitleStyle) {
+ this.style = style.copy(
+ textScale = style.textScale.coerceIn(0.75f, 1.75f),
+ bottomPaddingFraction = style.bottomPaddingFraction.coerceIn(0f, 0.25f)
+ )
+ }
+
+ fun apply(playerView: PlayerView?) {
+ val subtitleView = playerView?.subtitleView ?: return
+ subtitleView.setApplyEmbeddedStyles(style.useEmbeddedStyles)
+ subtitleView.setApplyEmbeddedFontSizes(style.useEmbeddedStyles)
+ subtitleView.setStyle(
+ CaptionStyleCompat(
+ style.foregroundColorArgb,
+ style.backgroundColorArgb,
+ Color.TRANSPARENT,
+ style.edgeType,
+ Color.BLACK,
+ null
+ )
+ )
+ subtitleView.setFractionalTextSize(
+ SubtitleView.DEFAULT_TEXT_SIZE_FRACTION * style.textScale
+ )
+ subtitleView.setBottomPaddingFraction(style.bottomPaddingFraction)
+ }
+}
+
diff --git a/player/src/test/java/com/streamvault/player/StreamTypeDetectorTest.kt b/player/src/test/java/com/streamvault/player/StreamTypeDetectorTest.kt
deleted file mode 100644
index 2415f319..00000000
--- a/player/src/test/java/com/streamvault/player/StreamTypeDetectorTest.kt
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.streamvault.player
-
-import com.google.common.truth.Truth.assertThat
-import com.streamvault.domain.model.StreamType
-import org.junit.Test
-
-class StreamTypeDetectorTest {
-
- @Test
- fun `m3u8 extension detected as HLS`() {
- assertThat(StreamTypeDetector.detect("http://example.com/stream.m3u8"))
- .isEqualTo(StreamType.HLS)
- }
-
- @Test
- fun `m3u8 with query params detected as HLS`() {
- assertThat(StreamTypeDetector.detect("http://example.com/stream.m3u8?token=abc"))
- .isEqualTo(StreamType.HLS)
- }
-
- @Test
- fun `hls path segment detected as HLS`() {
- assertThat(StreamTypeDetector.detect("http://example.com/hls/stream"))
- .isEqualTo(StreamType.HLS)
- }
-
- @Test
- fun `mpd extension detected as DASH`() {
- assertThat(StreamTypeDetector.detect("http://example.com/manifest.mpd"))
- .isEqualTo(StreamType.DASH)
- }
-
- @Test
- fun `dash path segment detected as DASH`() {
- assertThat(StreamTypeDetector.detect("http://example.com/dash/stream"))
- .isEqualTo(StreamType.DASH)
- }
-
- @Test
- fun `ts extension detected as MPEG_TS`() {
- assertThat(StreamTypeDetector.detect("http://example.com/channel.ts"))
- .isEqualTo(StreamType.MPEG_TS)
- }
-
- @Test
- fun `live path without mp4 detected as MPEG_TS`() {
- assertThat(StreamTypeDetector.detect("http://example.com/live/channel1"))
- .isEqualTo(StreamType.MPEG_TS)
- }
-
- @Test
- fun `live path with mp4 detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/live/movie.mp4"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `mp4 detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/movie.mp4"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `mkv detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/movie.mkv"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `avi detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/movie.avi"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `flv detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/video.flv"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `webm detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/video.webm"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `mov detected as PROGRESSIVE`() {
- assertThat(StreamTypeDetector.detect("http://example.com/video.mov"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-
- @Test
- fun `unknown url returns UNKNOWN`() {
- assertThat(StreamTypeDetector.detect("http://example.com/stream"))
- .isEqualTo(StreamType.UNKNOWN)
- }
-
- @Test
- fun `case insensitive detection`() {
- assertThat(StreamTypeDetector.detect("http://example.com/STREAM.M3U8"))
- .isEqualTo(StreamType.HLS)
- }
-
- @Test
- fun `fragment stripped before matching`() {
- assertThat(StreamTypeDetector.detect("http://example.com/video.mp4#t=10"))
- .isEqualTo(StreamType.PROGRESSIVE)
- }
-}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerErrorClassifierTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerErrorClassifierTest.kt
new file mode 100644
index 00000000..4a8e4ceb
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerErrorClassifierTest.kt
@@ -0,0 +1,35 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import androidx.media3.exoplayer.source.BehindLiveWindowException
+import java.io.IOException
+import javax.net.ssl.SSLHandshakeException
+import org.junit.Test
+
+class PlayerErrorClassifierTest {
+
+ @Test
+ fun `401 maps to auth`() {
+ assertThat(PlayerErrorClassifier.classify(IOException("HTTP 401")))
+ .isEqualTo(PlaybackErrorCategory.HTTP_AUTH)
+ }
+
+ @Test
+ fun `500 maps to server`() {
+ assertThat(PlayerErrorClassifier.classify(IOException("HTTP 500")))
+ .isEqualTo(PlaybackErrorCategory.HTTP_SERVER)
+ }
+
+ @Test
+ fun `ssl exception maps to ssl`() {
+ assertThat(PlayerErrorClassifier.classify(SSLHandshakeException("certificate verify failed")))
+ .isEqualTo(PlaybackErrorCategory.SSL)
+ }
+
+ @Test
+ fun `behind live window maps to live window`() {
+ assertThat(PlayerErrorClassifier.classify(BehindLiveWindowException()))
+ .isEqualTo(PlaybackErrorCategory.LIVE_WINDOW)
+ }
+}
+
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt
new file mode 100644
index 00000000..716c2b70
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt
@@ -0,0 +1,55 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import androidx.media3.exoplayer.source.BehindLiveWindowException
+import java.io.IOException
+import javax.net.ssl.SSLHandshakeException
+import org.junit.Test
+
+class PlayerRetryPolicyTest {
+
+ private val liveContext = PlaybackRetryContext(
+ resolvedStreamType = ResolvedStreamType.HLS,
+ timeoutProfile = PlayerTimeoutProfile.LIVE
+ )
+
+ private val policy = PlayerRetryPolicy(liveContext) { false }
+
+ @Test
+ fun `500 before first frame retries 3 times with expected backoff`() {
+ val error = IOException("HTTP 500")
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 1)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 2)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 3)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 4)).isFalse()
+ assertThat(policy.retryDelayMs(error, 1)).isEqualTo(1000L)
+ assertThat(policy.retryDelayMs(error, 2)).isEqualTo(2500L)
+ assertThat(policy.retryDelayMs(error, 3)).isEqualTo(5000L)
+ }
+
+ @Test
+ fun `403 never retries`() {
+ assertThat(policy.shouldRetry(IOException("HTTP 403"), liveContext, playbackStarted = false, attempt = 1))
+ .isFalse()
+ }
+
+ @Test
+ fun `ssl error never retries`() {
+ assertThat(policy.shouldRetry(SSLHandshakeException("bad cert"), liveContext, playbackStarted = false, attempt = 1))
+ .isFalse()
+ }
+
+ @Test
+ fun `behind live window retries once`() {
+ val error = BehindLiveWindowException()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 1)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 2)).isFalse()
+ assertThat(policy.retryDelayMs(error, 1)).isEqualTo(0L)
+ }
+
+ @Test
+ fun `decoder init failure does not go through network retry policy`() {
+ val error = IllegalStateException("decoder init failed")
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 1)).isFalse()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerTimeoutProfileTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerTimeoutProfileTest.kt
new file mode 100644
index 00000000..5733fc6c
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerTimeoutProfileTest.kt
@@ -0,0 +1,42 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StreamInfo
+import org.junit.Test
+
+class PlayerTimeoutProfileTest {
+
+ @Test
+ fun `hls live selects live timeout profile`() {
+ assertThat(
+ PlayerTimeoutProfile.resolve(
+ streamInfo = StreamInfo(url = "http://example.com/live/1.m3u8"),
+ resolvedStreamType = ResolvedStreamType.HLS,
+ preload = false
+ )
+ ).isEqualTo(PlayerTimeoutProfile.LIVE)
+ }
+
+ @Test
+ fun `preload always selects preload profile`() {
+ assertThat(
+ PlayerTimeoutProfile.resolve(
+ streamInfo = StreamInfo(url = "http://example.com/movie.mp4"),
+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,
+ preload = true
+ )
+ ).isEqualTo(PlayerTimeoutProfile.PRELOAD)
+ }
+
+ @Test
+ fun `progressive file selects progressive timeout profile`() {
+ assertThat(
+ PlayerTimeoutProfile.resolve(
+ streamInfo = StreamInfo(url = "http://example.com/movie.mp4"),
+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,
+ preload = false
+ )
+ ).isEqualTo(PlayerTimeoutProfile.PROGRESSIVE)
+ }
+}
+
diff --git a/player/src/test/java/com/streamvault/player/playback/PreloadCoordinatorTest.kt b/player/src/test/java/com/streamvault/player/playback/PreloadCoordinatorTest.kt
new file mode 100644
index 00000000..af053450
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PreloadCoordinatorTest.kt
@@ -0,0 +1,73 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.DrmInfo
+import com.streamvault.domain.model.DrmScheme
+import com.streamvault.domain.model.StreamInfo
+import java.lang.reflect.Proxy
+import androidx.media3.exoplayer.source.MediaSource
+import org.junit.Test
+
+class PreloadCoordinatorTest {
+
+ @Test
+ fun `same item same url under two minutes reuses`() {
+ var now = 1_000L
+ val coordinator = PreloadCoordinator { now }
+ val source = fakeMediaSource()
+ val info = StreamInfo(url = "http://example.com/movie.mp4")
+ coordinator.store("1", info, ResolvedStreamType.PROGRESSIVE, source)
+
+ assertThat(coordinator.tryReuse("1", info, ResolvedStreamType.PROGRESSIVE)).isSameInstanceAs(source)
+ }
+
+ @Test
+ fun `different url invalidates`() {
+ var now = 1_000L
+ val coordinator = PreloadCoordinator { now }
+ coordinator.store("1", StreamInfo(url = "http://example.com/a.mp4"), ResolvedStreamType.PROGRESSIVE, fakeMediaSource())
+
+ assertThat(coordinator.tryReuse("1", StreamInfo(url = "http://example.com/b.mp4"), ResolvedStreamType.PROGRESSIVE)).isNull()
+ }
+
+ @Test
+ fun `different stream type invalidates`() {
+ var now = 1_000L
+ val coordinator = PreloadCoordinator { now }
+ val info = StreamInfo(url = "http://example.com/live/channel.ts")
+ coordinator.store("1", info, ResolvedStreamType.MPEG_TS_LIVE, fakeMediaSource())
+
+ assertThat(coordinator.tryReuse("1", info, ResolvedStreamType.HLS)).isNull()
+ }
+
+ @Test
+ fun `older than two minutes expires`() {
+ var now = 1_000L
+ val coordinator = PreloadCoordinator { now }
+ val info = StreamInfo(
+ url = "http://example.com/movie.mp4",
+ drmInfo = DrmInfo(DrmScheme.WIDEVINE, "http://license")
+ )
+ coordinator.store("1", info, ResolvedStreamType.PROGRESSIVE, fakeMediaSource())
+ now += 121_000L
+
+ assertThat(coordinator.tryReuse("1", info, ResolvedStreamType.PROGRESSIVE)).isNull()
+ }
+
+ private fun fakeMediaSource(): MediaSource {
+ return Proxy.newProxyInstance(
+ MediaSource::class.java.classLoader,
+ arrayOf(MediaSource::class.java)
+ ) { _, method, _ ->
+ when (method.returnType) {
+ Boolean::class.javaPrimitiveType -> false
+ Int::class.javaPrimitiveType -> 0
+ Long::class.javaPrimitiveType -> 0L
+ Float::class.javaPrimitiveType -> 0f
+ Double::class.javaPrimitiveType -> 0.0
+ Unit::class.java -> Unit
+ else -> null
+ }
+ } as MediaSource
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt
new file mode 100644
index 00000000..baf6be1f
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt
@@ -0,0 +1,38 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StreamTypeResolverTest {
+
+ @Test
+ fun `m3u8 resolves to HLS`() {
+ assertThat(StreamTypeResolver.resolve("http://example.com/channel.m3u8"))
+ .isEqualTo(ResolvedStreamType.HLS)
+ }
+
+ @Test
+ fun `mpd resolves to DASH`() {
+ assertThat(StreamTypeResolver.resolve("http://example.com/manifest.mpd"))
+ .isEqualTo(ResolvedStreamType.DASH)
+ }
+
+ @Test
+ fun `live url resolves to MPEG TS live`() {
+ assertThat(StreamTypeResolver.resolve("http://example.com/live/channel1", isLive = true))
+ .isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)
+ }
+
+ @Test
+ fun `mp4 resolves to progressive`() {
+ assertThat(StreamTypeResolver.resolve("http://example.com/movie.mp4"))
+ .isEqualTo(ResolvedStreamType.PROGRESSIVE)
+ }
+
+ @Test
+ fun `unknown url resolves to unknown`() {
+ assertThat(StreamTypeResolver.resolve("http://example.com/stream"))
+ .isEqualTo(ResolvedStreamType.UNKNOWN)
+ }
+}
+