Skip to content

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

Guide live preview pane

ab427dc883537
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 1a77d2c2..5321b17d 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -669,16 +669,18 @@ fun AppNavigation(mainActivity: MainActivity) {
onBack = {
val route = safePlayerRequest.returnRoute
if (!route.isNullOrBlank() && navController.popBackStack(route, false)) {
+ // Popped back to the exact route already in the backstack (same VM, handoff works)
Unit
- } else if (!route.isNullOrBlank()) {
- navController.navigate(route) {
+ } else if (!navController.popBackStack()) {
+ // Nothing left to pop — navigate to the return route or home as a last resort
+ val fallback = route?.takeIf { it.isNotBlank() } ?: Routes.HOME
+ navController.navigate(fallback) {
popUpTo(Routes.PLAYER) { inclusive = true }
launchSingleTop = true
restoreState = true
}
- } else {
- navController.popBackStack()
}
+ // else: plain popBackStack() succeeded — returns to existing Guide entry, preserving EpgViewModel
},
onNavigate = { route ->
navController.navigateIfResumed(route) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt
index b5371867..64aa83cf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt
@@ -118,6 +118,7 @@ internal fun EpgGrid(
guideWindowEnd: Long,
density: GuideDensity,
onChannelClick: (Channel) -> Unit,
+ onChannelLongClick: ((Channel, Program?) -> Unit)? = null,
onProgramClick: (Channel, Program) -> Unit,
onChannelFocused: (Channel, Program?, Boolean) -> Unit,
onProgramFocused: (Channel, Program, Boolean) -> Unit,
@@ -190,6 +191,7 @@ internal fun EpgGrid(
markerStepMs = markerStepMs,
scrollState = horizontalScrollState,
onChannelClick = { onChannelClick(channel) },
+ onChannelLongClick = onChannelLongClick?.let { cb -> { prog -> cb(channel, prog) } },
onChannelFocused = { onChannelFocused(channel, it, isFirstRow) },
onProgramClick = { program -> onProgramClick(channel, program) },
onProgramFocused = { program -> onProgramFocused(channel, program, isFirstRow) }
@@ -336,6 +338,7 @@ fun EpgRow(
markerStepMs: Long,
scrollState: androidx.compose.foundation.ScrollState,
onChannelClick: () -> Unit,
+ onChannelLongClick: ((Program?) -> Unit)? = null,
onChannelFocused: (Program?) -> Unit,
onProgramClick: (Program) -> Unit,
onProgramFocused: (Program) -> Unit
@@ -365,6 +368,13 @@ fun EpgRow(
) {
TvClickableSurface(
onClick = onChannelClick,
+ onLongClick = onChannelLongClick?.let { cb ->
+ {
+ val prog = currentProgram
+ ?: programs.minByOrNull { kotlin.math.abs(it.startTime - now) }
+ cb(prog)
+ }
+ },
modifier = Modifier
.width(channelRailWidth)
.fillMaxHeight()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt
index 2677c2cc..ac1042ae 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt
@@ -1,16 +1,22 @@
package com.streamvault.app.ui.screens.epg
import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
@@ -20,12 +26,15 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.MaterialTheme
@@ -34,6 +43,7 @@ import androidx.tv.material3.SurfaceDefaults
import androidx.tv.material3.Text
import com.streamvault.app.R
import com.streamvault.app.ui.components.ChannelLogoBadge
+import com.streamvault.app.ui.components.PlayerRenderView
import com.streamvault.app.ui.model.isArchivePlayable
import com.streamvault.app.ui.interaction.TvClickableSurface
import com.streamvault.app.ui.model.guideLookupKey
@@ -47,6 +57,9 @@ import com.streamvault.app.ui.theme.SurfaceElevated
import com.streamvault.app.ui.theme.SurfaceHighlight
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Program
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerRenderSurfaceType
+import com.streamvault.player.PlayerSurfaceResizeMode
import java.util.Date
internal data class GuideHeroSelection(
@@ -295,6 +308,150 @@ internal fun GuideHeroBadge(
}
}
+@Composable
+internal fun GuidePreviewPane(
+ previewPlayerEngine: PlayerEngine?,
+ isPreviewLoading: Boolean,
+ focusedChannel: Channel?,
+ focusedProgram: Program?,
+ modifier: Modifier = Modifier
+) {
+ val renderSurfaceType by (previewPlayerEngine?.renderSurfaceType)?.collectAsStateWithLifecycle(
+ initialValue = PlayerRenderSurfaceType.SURFACE_VIEW
+ ) ?: remember { mutableStateOf(PlayerRenderSurfaceType.SURFACE_VIEW) }
+ val now = currentGuideNow()
+ val appTimeFormat = LocalAppTimeFormat.current
+ val timeFormat = remember(appTimeFormat) { appTimeFormat.createTimeFormat() }
+
+ Surface(
+ modifier = modifier.height(150.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(10.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ // Video preview area (16:9 at 90dp height = 160dp wide)
+ Box(
+ modifier = Modifier
+ .fillMaxHeight()
+ .aspectRatio(16f / 9f)
+ .background(Color.Black, RoundedCornerShape(12.dp))
+ .clip(RoundedCornerShape(12.dp)),
+ contentAlignment = Alignment.Center
+ ) {
+ if (previewPlayerEngine != null) {
+ PlayerRenderView(
+ playerEngine = previewPlayerEngine,
+ resizeMode = PlayerSurfaceResizeMode.FIT,
+ surfaceType = renderSurfaceType,
+ modifier = Modifier.fillMaxSize()
+ )
+ if (isPreviewLoading) {
+ CircularProgressIndicator(
+ color = Primary,
+ strokeWidth = 2.dp,
+ modifier = Modifier.size(22.dp)
+ )
+ }
+ } else {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ modifier = Modifier.padding(horizontal = 12.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.live_preview_placeholder_title),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim,
+ textAlign = TextAlign.Center
+ )
+ }
+ }
+ }
+
+ // Program info
+ val channel = focusedChannel
+ val program = focusedProgram
+ if (channel != null) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ ChannelLogoBadge(
+ channelName = channel.name,
+ logoUrl = channel.logoUrl,
+ modifier = Modifier.size(32.dp),
+ shape = RoundedCornerShape(8.dp)
+ )
+ Text(
+ text = if (channel.number > 0) "${channel.number}. ${channel.name}" else channel.name,
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ if (program != null) {
+ Text(
+ text = program.title,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = "${timeFormat.format(Date(program.startTime))} – ${timeFormat.format(Date(program.endTime))}",
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
+ )
+ 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(0.6f)
+ .height(3.dp),
+ color = Primary,
+ trackColor = SurfaceHighlight
+ )
+ }
+ if (program.description.isNotBlank()) {
+ Text(
+ text = 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.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ } else {
+ Text(
+ text = stringResource(R.string.epg_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.weight(1f)
+ )
+ }
+ }
+ }
+}
+
@Composable
internal fun GuideToolbarRow(
selectedCategoryName: String,
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 85b95830..5858985e 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
@@ -43,6 +43,7 @@ import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -189,7 +190,8 @@ fun FullEpgScreen(
when (action) {
is LockedGuideAction.SelectCategory -> viewModel.selectCategory(action.category.id)
is LockedGuideAction.OpenProgram -> selectedProgram = action.channel to action.program
- is LockedGuideAction.PlayChannel ->
+ is LockedGuideAction.PlayChannel -> {
+ viewModel.handoffOrClearForFullscreen(action.channel)
onPlayChannel(
action.channel,
playerCategoryId,
@@ -197,7 +199,9 @@ fun FullEpgScreen(
uiState.combinedProfileId,
action.returnRoute
)
- is LockedGuideAction.PlayArchive ->
+ }
+ is LockedGuideAction.PlayArchive -> {
+ viewModel.clearPreview()
onPlayArchive(
action.channel,
action.program,
@@ -206,6 +210,7 @@ fun FullEpgScreen(
uiState.combinedProfileId,
action.returnRoute
)
+ }
}
}
@@ -215,6 +220,10 @@ fun FullEpgScreen(
showPinDialog = true
}
+ DisposableEffect(viewModel) {
+ onDispose { viewModel.clearPreview() }
+ }
+
LaunchedEffect(initialCategoryId, initialAnchorTime, initialFavoritesOnly) {
viewModel.applyNavigationContext(
categoryId = initialCategoryId,
@@ -383,8 +392,9 @@ fun FullEpgScreen(
else -> {
GuideNowProvider {
- GuideHeroSection(
- uiState = uiState,
+ GuidePreviewPane(
+ previewPlayerEngine = uiState.previewPlayerEngine,
+ isPreviewLoading = uiState.isPreviewLoading,
focusedChannel = focusedChannel,
focusedProgram = focusedProgram,
modifier = Modifier
@@ -438,7 +448,8 @@ fun FullEpgScreen(
onChannelClick = { channel ->
if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))
- } else {
+ } else if (uiState.previewChannelId == channel.id) {
+ viewModel.handoffOrClearForFullscreen(channel)
onPlayChannel(
channel,
playerCategoryId,
@@ -446,6 +457,33 @@ fun FullEpgScreen(
uiState.combinedProfileId,
returnRoute
)
+ } else {
+ viewModel.previewChannel(channel)
+ }
+ },
+ onChannelLongClick = { channel, currentProgram ->
+ topNavVisible = false
+ if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
+ requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))
+ } else {
+ val program = currentProgram ?: run {
+ // No EPG match — synthesize a 1-hour "now" program so
+ // the dialog still shows Record / Record Daily / Weekly.
+ val now = System.currentTimeMillis()
+ Program(
+ channelId = channel.id.toString(),
+ title = channel.name,
+ startTime = now,
+ endTime = now + 60L * 60L * 1000L
+ )
+ }
+ // Delay so the long-press key-release lands on the
+ // channel cell, not on an auto-focused button inside
+ // the dialog (which would auto-fire "Watch Live").
+ scope.launch {
+ kotlinx.coroutines.delay(350)
+ selectedProgram = channel to program
+ }
}
},
onProgramClick = { channel, program ->
@@ -609,6 +647,7 @@ fun FullEpgScreen(
if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
requestLockedGuideAction(LockedGuideAction.PlayChannel(channel, returnRoute))
} else {
+ viewModel.handoffOrClearForFullscreen(channel)
onPlayChannel(
channel,
playerCategoryId,
@@ -624,6 +663,7 @@ fun FullEpgScreen(
if (isGuideChannelLocked(channel, categoriesById, uiState.parentalControlLevel)) {
requestLockedGuideAction(LockedGuideAction.PlayArchive(channel, program, returnRoute))
} else {
+ viewModel.clearPreview()
onPlayArchive(
channel,
program,
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 27b9b110..487dc8ba 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
@@ -61,6 +61,15 @@ import kotlinx.coroutines.withContext
import java.time.Instant
import java.time.ZoneId
import javax.inject.Inject
+import android.app.Application
+import com.streamvault.app.R
+import com.streamvault.app.di.AuxiliaryPlayerEngine
+import com.streamvault.app.player.LivePreviewHandoffManager
+import com.streamvault.app.player.PreviewHandoffSource
+import com.streamvault.app.plugins.StreamVaultPluginManager
+import com.streamvault.player.PlaybackState
+import com.streamvault.player.PlayerEngine
+import javax.inject.Provider as InjectProvider
data class RecordingConflictInfo(
val conflictingItems: List<RecordingItem>,
@@ -97,7 +106,11 @@ data class EpgUiState(
val guideWindowEnd: Long = DEFAULT_NOW + EpgViewModel.LOOKAHEAD_MS,
val recordingMessage: String? = null,
val pendingRecordingConflict: RecordingConflictInfo? = null,
- val hasMoreChannels: Boolean = false
+ val hasMoreChannels: Boolean = false,
+ val previewPlayerEngine: PlayerEngine? = null,
+ val isPreviewLoading: Boolean = false,
+ val previewErrorMessage: String? = null,
+ val previewChannelId: Long? = null,
) {
companion object {
private val DEFAULT_NOW = System.currentTimeMillis()
@@ -252,9 +265,15 @@ class EpgViewModel @Inject constructor(
private val programReminderManager: ProgramReminderManager,
private val getCustomCategories: GetCustomCategories,
private val scheduleRecording: ScheduleRecording,
- private val recordingManager: RecordingManager
+ private val recordingManager: RecordingManager,
+ @param:AuxiliaryPlayerEngine private val playerEngineProvider: InjectProvider<PlayerEngine>,
+ private val pluginManager: StreamVaultPluginManager,
+ private val livePreviewHandoffManager: LivePreviewHandoffManager,
+ application: Application,
) : ViewModel() {
+ private val appContext = application
+
companion object {
const val MAX_CHANNELS = 60
private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 10
@@ -291,11 +310,22 @@ class EpgViewModel @Inject constructor(
private var prefetchJob: Deferred<GuidePrefetchedPage?>? = null
private var loadMoreJob: Job? = null
private var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()
+ private var previewPlayerEngine: PlayerEngine? = null
+ private var previewSessionVersion: Long = 0L
+ private var previewPlaybackJob: Job? = null
+ private var previewErrorJob: Job? = null
init {
restoreGuidePreferences()
observeGuideBase()
observeGuidePresentation()
+ viewModelScope.launch {
+ livePreviewHandoffManager.reverseSessionFlow.collect { session ->
+ if (session != null && session.source == PreviewHandoffSource.GUIDE) {
+ resumePreviewFromHandoff()
+ }
+ }
+ }
}
fun selectCategory(categoryId: Long) {
@@ -322,6 +352,192 @@ class EpgViewModel @Inject constructor(
suspend fun verifyPin(pin: String): Boolean =
preferencesRepository.verifyParentalPin(pin)
+ fun previewChannel(channel: Channel) {
+ if (_uiState.value.previewChannelId == channel.id && _uiState.value.previewPlayerEngine != null) return
+ val version = ++previewSessionVersion
+ val engine = previewPlayerEngine ?: playerEngineProvider.get().also { previewPlayerEngine = it }
+ previewPlaybackJob?.cancel()
+ previewErrorJob?.cancel()
+ _uiState.update {
+ it.copy(
+ previewChannelId = channel.id,
+ previewPlayerEngine = engine,
+ isPreviewLoading = true,
+ previewErrorMessage = null
+ )
+ }
+ previewPlaybackJob = viewModelScope.launch {
+ engine.playbackState.collectLatest { state ->
+ if (!isActivePreviewSession(version, channel.id)) return@collectLatest
+ _uiState.update { s ->
+ s.copy(
+ isPreviewLoading = state == PlaybackState.IDLE || state == PlaybackState.BUFFERING,
+ previewErrorMessage = when {
+ state == PlaybackState.ERROR && s.previewErrorMessage.isNullOrBlank() ->
+ appContext.getString(R.string.live_preview_failed)
+ state != PlaybackState.ERROR -> null
+ else -> s.previewErrorMessage
+ }
+ )
+ }
+ }
+ }
+ previewErrorJob = viewModelScope.launch {
+ engine.error.collectLatest { error ->
+ if (!isActivePreviewSession(version, channel.id)) return@collectLatest
+ if (error != null) {
+ _uiState.update {
+ it.copy(
+ isPreviewLoading = false,
+ previewErrorMessage = error.message.ifBlank { appContext.getString(R.string.live_preview_failed) }
+ )
+ }
+ }
+ }
+ }
+ viewModelScope.launch {
+ when (val result = channelRepository.getStreamInfo(channel)) {
+ is Result.Success -> {
+ if (!isActivePreviewSession(version, channel.id)) return@launch
+ val preparedStreamInfo = when (val r = pluginManager.preparePlaybackStreamInfo(result.data)) {
+ is Result.Success -> r.data
+ is Result.Error -> {
+ if (!isActivePreviewSession(version, channel.id)) return@launch
+ _uiState.update {
+ it.copy(isPreviewLoading = false, previewErrorMessage = r.message.ifBlank { appContext.getString(R.string.live_preview_failed) })
+ }
+ return@launch
+ }
+ Result.Loading -> result.data
+ }
+ if (!isActivePreviewSession(version, channel.id)) return@launch
+ engine.stop()
+ engine.setDecoderMode(preferencesRepository.playerDecoderMode.first())
+ engine.setSurfaceMode(preferencesRepository.playerSurfaceMode.first())
+ engine.prepare(preparedStreamInfo)
+ engine.setVolume(1f)
+ engine.play()
+ livePreviewHandoffManager.registerPreviewSession(
+ channel = channel,
+ streamInfo = preparedStreamInfo,
+ engine = engine,
+ source = PreviewHandoffSource.GUIDE
+ )
+ }
+ is Result.Error -> {
+ if (!isActivePreviewSession(version, channel.id)) return@launch
+ _uiState.update { it.copy(isPreviewLoading = false, previewErrorMessage = result.message) }
+ }
+ Result.Loading -> Unit
+ }
+ }
+ }
+
+ fun beginPreviewHandoff(channel: Channel): Boolean {
+ val engine = previewPlayerEngine ?: return false
+ if (_uiState.value.previewChannelId != channel.id) return false
+ if (!livePreviewHandoffManager.beginFullscreenHandoff(channel.id, engine)) return false
+
+ previewSessionVersion++
+ previewPlaybackJob?.cancel()
+ previewErrorJob?.cancel()
+ previewPlaybackJob = null
+ previewErrorJob = null
+ previewPlayerEngine = null
+ _uiState.update {
+ it.copy(
+ previewChannelId = null,
+ previewPlayerEngine = null,
+ isPreviewLoading = false,
+ previewErrorMessage = null
+ )
+ }
+ return true
+ }
+
+ fun resumePreviewFromHandoff() {
+ val session = livePreviewHandoffManager.consumeReverseHandoff(PreviewHandoffSource.GUIDE) ?: return
+ val engine = session.engine
+ previewSessionVersion++
+ val version = previewSessionVersion
+ previewPlaybackJob?.cancel()
+ previewErrorJob?.cancel()
+ previewPlaybackJob = null
+ previewErrorJob = null
+ previewPlayerEngine?.stop()
+ previewPlayerEngine?.release()
+ previewPlayerEngine = engine
+ (engine as? com.streamvault.player.Media3PlayerEngine)?.let {
+ it.enableMediaSession = false
+ it.bypassAudioFocus = true
+ }
+ engine.play()
+ livePreviewHandoffManager.registerPreviewSession(
+ channelId = session.channelId,
+ providerId = session.providerId,
+ streamInfo = session.streamInfo,
+ engine = engine,
+ source = PreviewHandoffSource.GUIDE
+ )
+ _uiState.update {
+ it.copy(
+ previewChannelId = session.channelId,
+ previewPlayerEngine = engine,
+ isPreviewLoading = false,
+ previewErrorMessage = null
+ )
+ }
+ previewPlaybackJob = viewModelScope.launch {
+ engine.playbackState.collectLatest { state ->
+ if (!isActivePreviewSession(version, session.channelId)) return@collectLatest
+ if (state == PlaybackState.ERROR && _uiState.value.previewErrorMessage == null) {
+ _uiState.update { it.copy(previewErrorMessage = appContext.getString(R.string.live_preview_failed)) }
+ }
+ }
+ }
+ }
+
+ fun clearPreview() {
+ val engine = previewPlayerEngine ?: return
+ previewSessionVersion++
+ previewPlaybackJob?.cancel()
+ previewErrorJob?.cancel()
+ previewPlaybackJob = null
+ previewErrorJob = null
+ livePreviewHandoffManager.clear(engine)
+ engine.stop()
+ engine.release()
+ previewPlayerEngine = null
+ _uiState.update {
+ it.copy(
+ previewChannelId = null,
+ previewPlayerEngine = null,
+ isPreviewLoading = false,
+ previewErrorMessage = null
+ )
+ }
+ }
+
+ /**
+ * Call before navigating to the fullscreen player. If `channel` matches the current preview,
+ * hands the engine off; otherwise releases the preview so two streams can't run in parallel.
+ */
+ fun handoffOrClearForFullscreen(channel: Channel) {
+ if (!beginPreviewHandoff(channel)) clearPreview()
+ }
+
+ private fun isActivePreviewSession(version: Long, channelId: Long): Boolean =
+ version == previewSessionVersion && _uiState.value.previewChannelId == channelId
+
+ override fun onCleared() {
+ super.onCleared()
+ previewPlaybackJob?.cancel()
+ previewErrorJob?.cancel()
+ previewPlayerEngine?.stop()
+ previewPlayerEngine?.release()
+ previewPlayerEngine = null
+ }
+
fun unlockCategory(categoryId: Long) {
val providerId = baseGuideSnapshot.value?.providerId?.takeIf { it > 0L } ?: return
parentalControlManager.unlockCategory(providerId, categoryId)