StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Implement state management for player navigation and cleanup on exit
David Nashash2de655d505e7
diff --git a/app/src/main/java/com/streamvault/app/navigation/NavControllerNavigator.kt b/app/src/main/java/com/streamvault/app/navigation/NavControllerNavigator.ktindex 26d4aea2..ab5ce235 100644--- a/app/src/main/java/com/streamvault/app/navigation/NavControllerNavigator.kt+++ b/app/src/main/java/com/streamvault/app/navigation/NavControllerNavigator.kt@@ -120,20 +120,25 @@ internal class NavControllerNavigator(currentDestinationId?.let { destinationId ->popUpTo(destinationId) {inclusive = true- saveState = true+ saveState = shouldSaveCurrentState()}}}return true}+ private fun shouldSaveCurrentState(): Boolean =+ shouldSaveCurrentStateOnReplacement(+ navController.currentBackStackEntry?.destination?.route+ )+private fun NavOptionsBuilder.apply(options: NavigationOptions) {launchSingleTop = options.launchSingleToprestoreState = options.restoreStateoptions.popUpTo?.let { destination ->popUpTo(AppRouteCodec.encode(destination)) {inclusive = options.inclusive- saveState = options.saveState+ saveState = options.saveState && shouldSaveCurrentState()}}}diff --git a/app/src/main/java/com/streamvault/app/navigation/ReturnNavigationPolicy.kt b/app/src/main/java/com/streamvault/app/navigation/ReturnNavigationPolicy.ktindex e690c250..3b0c73c2 100644--- a/app/src/main/java/com/streamvault/app/navigation/ReturnNavigationPolicy.kt+++ b/app/src/main/java/com/streamvault/app/navigation/ReturnNavigationPolicy.kt@@ -17,3 +17,11 @@ internal fun planReturnNavigation(hasPreviousEntry -> ReturnNavigationPlan.PopPreviouselse -> ReturnNavigationPlan.NavigateHome}++/**+ * Player entries must never be saved while being popped. Saving the entry keeps its+ * ViewModelStore alive, which in turn keeps the ExoPlayer and MediaSession alive after the+ * player UI is gone. Other destinations can keep the previous save-state behavior.+ */+internal fun shouldSaveCurrentStateOnReplacement(currentRoute: String?): Boolean =+ currentRoute != AppRoutePatterns.PLAYERdiff --git a/app/src/test/java/com/streamvault/app/navigation/ReturnNavigationPolicyTest.kt b/app/src/test/java/com/streamvault/app/navigation/ReturnNavigationPolicyTest.ktindex d3520f8b..6b3ada50 100644--- a/app/src/test/java/com/streamvault/app/navigation/ReturnNavigationPolicyTest.kt+++ b/app/src/test/java/com/streamvault/app/navigation/ReturnNavigationPolicyTest.kt@@ -36,4 +36,14 @@ class ReturnNavigationPolicyTest {)).isEqualTo(ReturnNavigationPlan.NavigateHome)}++ @Test+ fun playerStateIsNeverSavedWhileReplacingIt() {+ assertThat(shouldSaveCurrentStateOnReplacement(AppRoutePatterns.PLAYER)).isFalse()+ }++ @Test+ fun nonPlayerStateKeepsExistingSaveStateBehavior() {+ assertThat(shouldSaveCurrentStateOnReplacement(AppRoutePatterns.LIVE_TV)).isTrue()+ }}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 757d4f6a..2f6f703e 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -19,6 +19,7 @@ All notable product changes are recorded in this document.- VOD timelines can now be scrubbed with the D-pad in 10-second steps; holding a direction previews repeated seeks, and releasing applies the selected position.### Fixed+- Fixed live TV continuing to play in the background after leaving the player, including when exiting while a channel was still loading. Playback and the Android media session are now released immediately, and abandoned Home or Guide previews are closed.- Fixed Hardware Only video decoding being overridden after live TV stalls; recovery now preserves explicit audio and video decoder settings and excludes software video decoders in Hardware Only mode.- Fixed channel numbers appearing in Guide Favorites views and selected-channel details when Live TV numbering is set to Hidden.- Fixed external subtitles disappearing after playback retries, reconnects, buffering, or when replaying a movie: attached subtitles are restored with the rebuilt source, downloaded OpenSubtitles files are kept in durable app storage and remembered for that movie, and replaced subtitle files are cleaned up.diff --git a/feature/live/src/main/java/com/streamvault/feature/live/home/LiveHomeScreen.kt b/feature/live/src/main/java/com/streamvault/feature/live/home/LiveHomeScreen.ktindex ebb3a58a..55346336 100644--- a/feature/live/src/main/java/com/streamvault/feature/live/home/LiveHomeScreen.kt+++ b/feature/live/src/main/java/com/streamvault/feature/live/home/LiveHomeScreen.kt@@ -191,6 +191,12 @@ fun LiveHomeScreen(}}+ LaunchedEffect(isProMode) {+ if (!isProMode) {+ viewModel.clearPreview()+ }+ }+val hasOverlay = showPinDialog || showSplitManagerDialog || pendingSplitPlannerChannel != null ||showAddQuickFilterDialog || showHiddenCategoriesDialog || showHiddenChannelsDialog ||uiState.showDialog || uiState.showDeleteGroupDialog ||diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.ktindex fa2e3d12..4fa9af1f 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt@@ -268,6 +268,16 @@ fun PlayerViewModel.onPlayerScreenDisposed(): Job? {playerEngine.stopLiveTimeshift()stopLiveTranslationSession()clearPlaybackTimers()+ // The screen is gone, even when navigation kept the ViewModelStore alive. Cancel any+ // in-flight preparation before it can finish and start playback in the background, and+ // pause the engine in case it was already playing. Terminal cleanup owns the engine and+ // may hand it back to a preview surface, so it skips these steps.+ if (!terminalPlaybackCleanupStarted) {+ playbackSessionCoordinator.invalidate()+ if (playerEngine.playbackState.value != PlaybackState.IDLE) {+ playerEngine.pause()+ }+ }return progressFlush}@@ -295,6 +305,7 @@ fun PlayerViewModel.handOffPlaybackToMultiView(): Job? {}internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine) {+ terminalPlaybackCleanupStarted = trueonPlayerScreenDisposed()channelInfoHideJob?.cancel()liveOverlayHideJob?.cancel()@@ -335,6 +346,7 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine))mainPlayerEngine.resetForReuse()} else {+ playerPreviewCoordinator.discardPendingFullscreenHandoff(mainPlayerEngine)playerPreviewCoordinator.clear(activeEngine)if (activeEngine === mainPlayerEngine) {mainPlayerEngine.resetForReuse()diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinator.ktindex 4c9c17ae..4ca395f0 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinator.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinator.kt@@ -29,6 +29,19 @@ class PlayerPreviewCoordinator @Inject constructor(internal fun clear(engine: PlayerEngine?) {handoffManager.clear(engine)+ adoptedHandoffSource = null+ }++ /**+ * Releases a preview engine that was handed to a fullscreen player that never claimed it.+ * Without this, leaving the player before adoption leaves that engine playing until the+ * handoff timeout expires.+ */+ internal fun discardPendingFullscreenHandoff(mainEngine: PlayerEngine) {+ val pending = handoffManager.discardPendingFullscreenHandoff() ?: return+ if (pending.engine !== mainEngine) {+ pending.engine.release()+ }}/**diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.ktindex 67ec2245..869ef6f7 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt@@ -345,6 +345,7 @@ class PlayerViewModel @Inject constructor(playerPlaybackContextCoordinator.pendingCatchUpUrls = value}internal var livePlaybackReadyForCurrentSession: Boolean = false+ internal var terminalPlaybackCleanupStarted: Boolean = falseinternal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUPset(value) {field = valuediff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManager.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManager.ktindex 309e92b7..ae7f9d3a 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManager.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManager.kt@@ -95,6 +95,18 @@ class LivePreviewHandoffManager @Inject constructor() {session = null}+ /**+ * Removes a fullscreen handoff that was never claimed. The caller owns releasing the+ * returned engine.+ */+ fun discardPendingFullscreenHandoff(): LivePreviewHandoffSession? {+ val current = session ?: return null+ if (!current.pendingFullscreen) return null+ pendingReleaseJob?.cancel()+ session = null+ return current+ }+fun beginReverseHandoff(channel: Channel,streamInfo: StreamInfo,diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinatorTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinatorTest.ktindex e5414005..353b3f07 100644--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinatorTest.kt+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreviewCoordinatorTest.kt@@ -18,6 +18,7 @@ import org.junit.Afterimport org.junit.Beforeimport org.junit.Testimport org.mockito.kotlin.mock+import org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@OptIn(ExperimentalCoroutinesApi::class)@@ -112,6 +113,33 @@ class PlayerPreviewCoordinatorTest {assertThat(coordinator.consumeAdoptedHandoffSource()).isNull()}+ @Test+ fun `clearing the handoff forgets the recorded reverse source`() = runTest(testDispatcher) {+ val coordinator = coordinator()+ val channel = channel(id = 13L, providerId = 3L)++ assertThat(adopt(coordinator, channel, PreviewHandoffSource.HOME)).isTrue()++ coordinator.clear(engineCoordinator.currentEngine)++ assertThat(coordinator.consumeAdoptedHandoffSource()).isNull()+ }++ @Test+ fun `discarding a pending fullscreen handoff releases the preview engine`() = runTest(testDispatcher) {+ val coordinator = coordinator()+ val previewEngine = mock<PlayerEngine>()+ val channel = channel(id = 14L, providerId = 3L)+ val streamInfo = StreamInfo(url = "https://example.com/live.m3u8", title = channel.name)++ handoffManager.registerPreviewSession(channel, streamInfo, previewEngine)+ handoffManager.beginFullscreenHandoff(channel.id, previewEngine)++ coordinator.discardPendingFullscreenHandoff(engineCoordinator.mainEngine)++ verify(previewEngine).release()+ }+private fun channel(id: Long, providerId: Long): Channel = Channel(id = id,name = "Preview $id",diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManagerTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManagerTest.ktindex b790c509..c045d58d 100644--- a/feature/playback/src/test/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManagerTest.kt+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/preview/LivePreviewHandoffManagerTest.kt@@ -13,6 +13,7 @@ import org.junit.Afterimport org.junit.Beforeimport org.junit.Testimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.verifyNoInteractionsimport kotlinx.coroutines.test.setMain@@ -68,6 +69,38 @@ class LivePreviewHandoffManagerTest {verify(engine).release()}+ @Test+ fun `discarding a pending handoff removes it without waiting for the timeout`() = runTest(testDispatcher) {+ val manager = LivePreviewHandoffManager()+ val engine = mock<PlayerEngine>()+ val channel = channel(id = 100L, providerId = 5L)+ val streamInfo = StreamInfo(url = "https://example.com/preview.ts", title = channel.name)++ manager.registerPreviewSession(channel, streamInfo, engine)+ assertThat(manager.beginFullscreenHandoff(channel.id, engine)).isTrue()++ val pending = manager.discardPendingFullscreenHandoff()++ assertThat(pending?.engine).isSameInstanceAs(engine)+ assertThat(manager.consumeFullscreenHandoff(channel.id, channel.providerId)).isNull()+ advanceTimeBy(15_001L)+ testDispatcher.scheduler.runCurrent()+ verify(engine, never()).release()+ }++ @Test+ fun `discarding does not take a session that was never handed to fullscreen`() = runTest(testDispatcher) {+ val manager = LivePreviewHandoffManager()+ val engine = mock<PlayerEngine>()+ val channel = channel(id = 101L, providerId = 5L)+ val streamInfo = StreamInfo(url = "https://example.com/preview.ts", title = channel.name)++ manager.registerPreviewSession(channel, streamInfo, engine)++ assertThat(manager.discardPendingFullscreenHandoff()).isNull()+ assertThat(manager.consumeFullscreenHandoff(channel.id, channel.providerId)).isNull()+ }+@Testfun `reverse handoff session is visible on flow after beginReverseHandoff`() = runTest(testDispatcher) {val manager = LivePreviewHandoffManager()