Skip to content

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

feat(player): implement player recovery policy and associated coordinators

David Nashashc097b42361fb
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinator.kt
index f2330203..8a15af11 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinator.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinator.kt
@@ -1,33 +1,73 @@
package com.streamvault.app.ui.screens.player
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicLong
/**
- * Immutable identity gate for one player preparation/session.
+ * Owns the lifetime of one player preparation/session.
*
- * Network, recovery, guide, and token-renewal callbacks may outlive the request that created
- * them. Callers must validate the returned id before applying any result to UI or the player.
+ * Session work must be launched through this coordinator. Starting a new session cancels the
+ * previous session's child scope, while the id remains available for guarding callbacks that
+ * complete outside of the coroutine hierarchy.
*/
-internal class PlaybackSessionCoordinator {
- data class Session(val id: Long)
+internal class PlaybackSessionCoordinator(
+ private val parentScope: CoroutineScope
+) {
+ class Session internal constructor(
+ val id: Long,
+ internal val scope: CoroutineScope
+ )
private val nextId = AtomicLong()
@Volatile
- private var activeSession = Session(0L)
+ private var activeSession: Session? = null
val currentId: Long
- get() = activeSession.id
+ get() = activeSession?.id ?: 0L
+ @Synchronized
fun begin(): Session {
- val session = Session(nextId.incrementAndGet())
- activeSession = session
- return session
+ activeSession?.scope?.cancel()
+ val sessionJob = SupervisorJob(parentScope.coroutineContext[Job])
+ val scopedSession = Session(
+ id = nextId.incrementAndGet(),
+ scope = CoroutineScope(parentScope.coroutineContext + sessionJob)
+ )
+ activeSession = scopedSession
+ return scopedSession
}
- fun isCurrent(id: Long): Boolean = activeSession.id == id
+ fun isCurrent(id: Long): Boolean {
+ val session = activeSession
+ return session?.id == id && session.scope.isActive
+ }
+
+ fun scope(id: Long): CoroutineScope? {
+ val session = activeSession
+ if (session?.id != id || !session.scope.isActive) return null
+ return session.scope
+ }
+
+ /**
+ * Launches work in the current session scope. A stale session returns no job and cannot
+ * accidentally restart work after a newer session has replaced it.
+ */
+ fun launch(id: Long, block: suspend () -> Unit): Job? {
+ val session = activeSession ?: return null
+ if (session.id != id || !session.scope.isActive) return null
+ return session.scope.launch { block() }
+ }
+ @Synchronized
fun invalidate() {
- activeSession = Session(nextId.incrementAndGet())
+ activeSession?.scope?.cancel()
+ activeSession = null
+ nextId.incrementAndGet()
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
index 8daf8ea6..de169be1 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
@@ -1,6 +1,5 @@
package com.streamvault.app.ui.screens.player
-import androidx.lifecycle.viewModelScope
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
import kotlinx.coroutines.launch
@@ -16,8 +15,8 @@ fun PlayerViewModel.hasAlternateStream(): Boolean {
currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
currentStreamUrl = currentStreamUrl,
currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession,
+ triedAlternativeStreams = playerRecoveryCoordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = playerRecoveryCoordinator.failedStreamSnapshot(),
preferXtreamTsFallback = false
) != null
}
@@ -41,8 +40,8 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(
currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
currentStreamUrl = currentStreamUrl,
currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession,
+ triedAlternativeStreams = playerRecoveryCoordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = playerRecoveryCoordinator.failedStreamSnapshot(),
preferXtreamTsFallback = preferXtreamTsFallback,
allowXtreamTsFallback = allowXtreamTsFallback
) ?: run {
@@ -66,7 +65,7 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(
val updatedChannel = channel.withSelectedVariant(nextVariant.rawChannelId)?.sanitizedForPlayer()
?: return false
val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(nextVariant.streamUrl)
+ playerRecoveryCoordinator.markStreamAttempt(nextVariant.streamUrl)
currentContentId = updatedChannel.id
currentStreamUrl = updatedChannel.streamUrl
currentTitle = nextVariant.originalName.ifBlank { updatedChannel.name }
@@ -88,8 +87,8 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(
refreshCurrentChannelRecording()
updateChannelDiagnostics(updatedChannel)
updateStreamClass("Variant")
- viewModelScope.launch {
- preferencesRepository.setPreferredLiveVariant(
+ playbackSessionScope(requestVersion)?.launch {
+ playerPreferencesCoordinator.setPreferredLiveVariant(
providerId = updatedChannel.providerId,
logicalGroupId = updatedChannel.logicalGroupId,
rawChannelId = nextVariant.rawChannelId
@@ -115,7 +114,7 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(
val requestVersion = beginPlaybackSession()
val nextStream = candidate.url
- triedAlternativeStreams.add(nextStream)
+ playerRecoveryCoordinator.markStreamAttempt(nextStream)
currentStreamUrl = nextStream
updateStreamClass(
when (candidate.kind) {
@@ -124,7 +123,7 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(
LiveRecoveryCandidateKind.VARIANT -> "Variant"
}
)
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val streamInfo = resolvePlaybackStreamInfo(nextStream, channel.id, channel.providerId, ContentType.LIVE)
?: return@launch
if (!isActivePlaybackSession(requestVersion, nextStream)) return@launch
@@ -140,18 +139,18 @@ private fun PlayerViewModel.nextCatchUpVariant(): String? {
return selectNextAlternateUrl(
candidateUrls = pendingCatchUpUrls,
currentStreamUrl = currentStreamUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession
+ triedAlternativeStreams = playerRecoveryCoordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = playerRecoveryCoordinator.failedStreamSnapshot()
)
}
internal fun PlayerViewModel.tryNextCatchUpVariantInternal(): Boolean {
val nextStream = nextCatchUpVariant() ?: return false
val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(nextStream)
+ playerRecoveryCoordinator.markStreamAttempt(nextStream)
currentStreamUrl = nextStream
updateStreamClass("Catch-up")
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val streamInfo = resolveCatchUpStreamInfo(
candidateUrl = nextStream,
title = currentTitle,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
index 08e49d06..191ac8b8 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
@@ -22,24 +22,6 @@ internal data class LiveRecoveryCandidate(
val variant: LiveChannelVariant? = null
)
-internal fun buildPlayerRecoveryActions(
- hasAlternateStream: Boolean,
- hasLastChannel: Boolean,
- shouldOfferGuide: Boolean
-): List<PlayerNoticeAction> {
- val actions = mutableListOf(PlayerNoticeAction.RETRY)
- if (hasAlternateStream) {
- actions += PlayerNoticeAction.ALTERNATE_STREAM
- }
- if (hasLastChannel) {
- actions += PlayerNoticeAction.LAST_CHANNEL
- }
- if (shouldOfferGuide) {
- actions += PlayerNoticeAction.OPEN_GUIDE
- }
- return actions
-}
-
internal fun selectNextAlternateUrl(
candidateUrls: List<String>,
currentStreamUrl: String,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt
index 6362864a..d73440bf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAutoPlayActions.kt
@@ -17,15 +17,15 @@ internal suspend fun PlayerViewModel.persistPlaybackCompletion() {
) ?: return
logRepositoryFailure(
operation = "Mark playback watched",
- result = markAsWatched(completedHistory)
+ result = playbackHistoryCoordinator.markAsWatched(completedHistory)
)
- watchNextManager.refreshWatchNext()
- launcherRecommendationsManager.refreshRecommendations()
+ playbackHistoryCoordinator.refreshPlaybackSurfaces()
}
internal fun PlayerViewModel.handlePlaybackEnded() {
if (currentContentType == ContentType.LIVE) return
- viewModelScope.launch {
+ val requestVersion = prepareRequestVersion
+ playbackSessionScope(requestVersion)?.launch {
persistPlaybackCompletion()
if (currentContentType == ContentType.SERIES_EPISODE) {
val position = playerEngine.currentPosition.value
@@ -42,7 +42,7 @@ internal fun PlayerViewModel.handlePlaybackEnded() {
internal fun PlayerViewModel.startAutoPlayCountdown(episode: Episode) {
autoPlayCountdownJob?.cancel()
- autoPlayCountdownJob = viewModelScope.launch {
+ autoPlayCountdownJob = playbackSessionScope()?.launch {
for (remaining in AUTO_PLAY_COUNTDOWN_SECONDS downTo 1) {
_autoPlayCountdown.value = AutoPlayCountdownUiState(
episode = episode,
@@ -65,4 +65,4 @@ fun PlayerViewModel.playNextEpisodeNow() {
val episode = autoPlayCountdown.value?.episode ?: nextEpisode.value ?: return
cancelAutoPlay()
playEpisode(episode, showResumePrompt = false)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastCoordinator.kt
new file mode 100644
index 00000000..bfd3843c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastCoordinator.kt
@@ -0,0 +1,47 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.app.cast.CastConnectionState
+import com.streamvault.app.cast.CastManager
+import com.streamvault.app.cast.CastMediaRequest
+import com.streamvault.app.cast.CastMediaRequestBuildResult
+import com.streamvault.app.cast.CastMediaRequestFactory
+import com.streamvault.app.cast.CastPlaybackCoordinator
+import com.streamvault.app.cast.CastPlaybackEvent
+import com.streamvault.app.cast.CastStartResult
+import com.streamvault.domain.model.StreamInfo
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.StateFlow
+import javax.inject.Inject
+
+/** Bundles cast route lifecycle, request construction, and playback events for the player. */
+class PlayerCastCoordinator @Inject constructor(
+ private val castManager: CastManager,
+ private val requestFactory: CastMediaRequestFactory,
+ private val playbackCoordinator: CastPlaybackCoordinator
+) {
+ val connectionState: StateFlow<CastConnectionState> = castManager.connectionState
+ val playbackEvents: Flow<CastPlaybackEvent> = playbackCoordinator.playbackEvents
+
+ internal suspend fun startCasting(request: CastMediaRequest): CastStartResult =
+ playbackCoordinator.startCasting(request)
+
+ internal fun stopCasting() {
+ castManager.stopCasting()
+ }
+
+ internal fun buildFromStreamInfo(
+ streamInfo: StreamInfo,
+ title: String,
+ subtitle: String?,
+ artworkUrl: String?,
+ isLive: Boolean,
+ startPositionMs: Long
+ ): CastMediaRequestBuildResult = requestFactory.buildFromStreamInfo(
+ streamInfo = streamInfo,
+ title = title,
+ subtitle = subtitle,
+ artworkUrl = artworkUrl,
+ isLive = isLive,
+ startPositionMs = startPositionMs
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt
index fce926f8..deb49c11 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCatchUpActions.kt
@@ -2,9 +2,9 @@ package com.streamvault.app.ui.screens.player
import androidx.lifecycle.viewModelScope
import com.streamvault.app.ui.model.isArchivePlayable
-import com.streamvault.data.security.CredentialDecryptionException
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StreamInfo
import kotlinx.coroutines.launch
@@ -34,7 +34,7 @@ internal suspend fun PlayerViewModel.startCatchUpPlayback(
currentTitle = title
pendingCatchUpUrls = candidates
- triedAlternativeStreams.clear()
+ playerRecoveryCoordinator.clearStreamAttempts()
updateStreamClass("Catch-up")
appendRecoveryAction(recoveryAction)
@@ -43,7 +43,7 @@ internal suspend fun PlayerViewModel.startCatchUpPlayback(
candidates.forEachIndexed { index, candidateUrl ->
if (!isActivePlaybackSession(requestVersion)) return
currentStreamUrl = candidateUrl
- triedAlternativeStreams.add(candidateUrl)
+ playerRecoveryCoordinator.markStreamAttempt(candidateUrl)
appendRecoveryAction("Trying catch-up candidate ${index + 1}/${candidates.size}")
android.util.Log.i(
"PlayerVM",
@@ -127,17 +127,19 @@ fun PlayerViewModel.playCatchUp(program: Program) {
return@launch
}
- val catchUpUrls = try {
- providerRepository.buildCatchUpUrls(providerId, streamId, start, end)
- } catch (e: CredentialDecryptionException) {
+ val catchUpUrls = when (val catchUpResult = playerProviderCoordinator.buildCatchUpUrls(providerId, streamId, start, end)) {
+ is Result.Success -> catchUpResult.data
+ is Result.Error -> {
if (!isActivePlaybackSession(requestVersion)) return@launch
- setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
+ setLastFailureReason(catchUpResult.message)
showPlayerNotice(
- message = e.message ?: CredentialDecryptionException.MESSAGE,
+ message = catchUpResult.message,
recoveryType = PlayerRecoveryType.SOURCE,
actions = buildRecoveryActions(PlayerRecoveryType.SOURCE)
)
return@launch
+ }
+ is Result.Loading -> return@launch
}
if (!isActivePlaybackSession(requestVersion)) return@launch
if (catchUpUrls.isNotEmpty()) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelCoordinator.kt
new file mode 100644
index 00000000..4709d51c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerChannelCoordinator.kt
@@ -0,0 +1,37 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.repository.ChannelRepository
+import kotlinx.coroutines.flow.Flow
+import javax.inject.Inject
+
+/** Owns channel catalog lookup and channel-scoped playback/error mutations for the player. */
+class PlayerChannelCoordinator @Inject constructor(
+ private val repository: ChannelRepository
+) {
+ internal fun getCategories(providerId: Long): Flow<List<Category>> =
+ repository.getCategories(providerId)
+
+ internal fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>> =
+ repository.getChannelsByIds(ids)
+
+ internal fun getChannelsByNumber(providerId: Long, categoryId: Long): Flow<List<Channel>> =
+ repository.getChannelsByNumber(providerId, categoryId)
+
+ internal suspend fun getChannel(channelId: Long): Channel? =
+ repository.getChannel(channelId)
+
+ internal suspend fun getStreamInfo(
+ channel: Channel,
+ preferStableUrl: Boolean = false
+ ): Result<StreamInfo> = repository.getStreamInfo(channel, preferStableUrl)
+
+ internal suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> =
+ repository.incrementChannelErrorCount(channelId)
+
+ internal suspend fun resetChannelErrorCount(channelId: Long): Result<Unit> =
+ repository.resetChannelErrorCount(channelId)
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
index 41ff8bdc..3f08fb90 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
@@ -1,17 +1,9 @@
package com.streamvault.app.ui.screens.player
-import com.streamvault.data.remote.stalker.StalkerPlaybackResolutionException
-import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
-import com.streamvault.data.security.CredentialDecryptionException
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Episode
-import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import com.streamvault.domain.model.StreamInfo
-import com.streamvault.domain.model.StreamType
-import com.streamvault.domain.repository.ChannelRepository
-import com.streamvault.domain.repository.MovieRepository
-import com.streamvault.domain.repository.SeriesRepository
internal data class SeriesEpisodeResolution(
val resolvedEpisode: Episode?,
@@ -26,7 +18,11 @@ internal data class PlayerPlaybackStreamResolution(
val streamInfo: StreamInfo?,
val credentialFailureMessage: String? = null,
val resolutionFailureMessage: String? = null
-)
+) {
+ internal val failureMessage: String?
+ get() = sequenceOf(credentialFailureMessage, resolutionFailureMessage)
+ .firstOrNull { !it.isNullOrBlank() }
+}
internal fun shouldUseStoredLiveStreamInfo(
logicalUrl: String,
@@ -66,154 +62,4 @@ internal fun buildSeriesEpisodeResolution(
resolvedEpisodeNumber = resolvedEpisode?.episodeNumber ?: episodeNumber
)
}
-
-internal suspend fun resolvePlayerPlaybackStreamInfo(
- logicalUrl: String,
- internalContentId: Long,
- providerId: Long,
- contentType: ContentType,
- currentTitle: String,
- currentSeries: Series?,
- currentEpisode: Episode?,
- channelRepository: ChannelRepository,
- movieRepository: MovieRepository,
- seriesRepository: SeriesRepository,
- xtreamStreamUrlResolver: XtreamStreamUrlResolver
-): PlayerPlaybackStreamResolution {
- var fallbackStreamId: Long? = null
- var fallbackContainerExtension: String? = null
-
- if (providerId > 0L && internalContentId > 0L) {
- when (contentType) {
- ContentType.LIVE -> {
- channelRepository.getChannel(internalContentId)?.let { channel ->
- fallbackStreamId = channel.streamId.takeIf { it > 0L }
- ?: channel.epgChannelId?.toLongOrNull()
- if (shouldUseStoredLiveStreamInfo(logicalUrl, channel.streamUrl)) {
- channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
- return PlayerPlaybackStreamResolution(
- streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
- )
- }
- }
- }
- }
-
- ContentType.MOVIE,
- ContentType.VOD -> {
- movieRepository.getMovie(internalContentId)?.let { movie ->
- fallbackStreamId = movie.streamId.takeIf { it > 0L }
- fallbackContainerExtension = movie.containerExtension
- val streamInfoResult = movieRepository.getStreamInfo(movie)
- if (streamInfoResult.isSuccess) {
- streamInfoResult.getOrNull()?.let { resolved ->
- return PlayerPlaybackStreamResolution(
- streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
- )
- }
- } else {
- (streamInfoResult as? Result.Error)?.message?.let { errorMsg ->
- return PlayerPlaybackStreamResolution(
- streamInfo = null,
- resolutionFailureMessage = errorMsg
- )
- }
- }
- }
- }
-
- ContentType.SERIES,
- ContentType.SERIES_EPISODE -> {
- val episode = when {
- currentEpisode?.id == internalContentId ||
- currentEpisode?.playbackEpisodeIdentity() == internalContentId -> currentEpisode
- else -> currentSeries
- ?.seasons
- .sanitizedForPlayer()
- .asSequence()
- .flatMap { it.episodes.asSequence() }
- .firstOrNull {
- it.id == internalContentId ||
- it.playbackEpisodeIdentity() == internalContentId
- }
- }
- episode?.let {
- fallbackStreamId = it.episodeId.takeIf { episodeId -> episodeId > 0L } ?: it.id
- fallbackContainerExtension = it.containerExtension
- val streamInfoResult = seriesRepository.getEpisodeStreamInfo(it)
- if (streamInfoResult.isSuccess) {
- streamInfoResult.getOrNull()?.let { resolved ->
- return PlayerPlaybackStreamResolution(
- streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
- )
- }
- } else {
- (streamInfoResult as? Result.Error)?.message?.let { errorMsg ->
- return PlayerPlaybackStreamResolution(
- streamInfo = null,
- resolutionFailureMessage = errorMsg
- )
- }
- }
- }
- }
- }
- }
-
- try {
- xtreamStreamUrlResolver.resolveAndCommitMetadata(
- url = logicalUrl,
- fallbackProviderId = providerId.takeIf { it > 0 },
- fallbackStreamId = fallbackStreamId,
- fallbackContentType = contentType,
- fallbackContainerExtension = fallbackContainerExtension
- )?.let { resolved ->
- val ext = resolved.containerExtension ?: fallbackContainerExtension
- return PlayerPlaybackStreamResolution(
- streamInfo = StreamInfo(
- url = resolved.url,
- title = currentTitle,
- headers = resolved.headers,
- userAgent = resolved.userAgent,
- playbackTransportPolicy = resolved.playbackTransportPolicy,
- allowInvalidSsl = resolved.allowInvalidSsl,
- proxyHost = resolved.proxyHost,
- proxyPort = resolved.proxyPort,
- streamType = StreamType.fromContainerExtension(ext),
- containerExtension = ext,
- expirationTime = resolved.expirationTime
- )
- )
- }
- } catch (e: CredentialDecryptionException) {
- return PlayerPlaybackStreamResolution(
- streamInfo = null,
- credentialFailureMessage = e.message ?: CredentialDecryptionException.MESSAGE
- )
- } catch (e: StalkerPlaybackResolutionException) {
- return PlayerPlaybackStreamResolution(
- streamInfo = null,
- resolutionFailureMessage = e.message
- ?: "We couldn't resolve a playable Stalker stream for this item."
- )
- }
-
- val isLogicalInternalUrl = xtreamStreamUrlResolver.isInternalStreamUrl(logicalUrl)
- if (isLogicalInternalUrl) {
- return PlayerPlaybackStreamResolution(
- streamInfo = null,
- resolutionFailureMessage = "This portal requires a different playback path than the default command."
- )
- }
-
- return PlayerPlaybackStreamResolution(
- streamInfo = logicalUrl.takeIf { it.isNotBlank() }?.let {
- StreamInfo(
- url = it,
- title = currentTitle,
- streamType = StreamType.fromContainerExtension(fallbackContainerExtension),
- containerExtension = fallbackContainerExtension
- )
- }
- )
-}
+// Provider-backed stream resolution lives in PlayerContentResolver.
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolver.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolver.kt
new file mode 100644
index 00000000..6fd02c5f
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolver.kt
@@ -0,0 +1,219 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.data.remote.xtream.ProviderPlaybackResolver
+import com.streamvault.data.remote.stalker.StalkerPlaybackResolutionException
+import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import com.streamvault.domain.model.VodMovieVariant
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.SeriesRepository
+import javax.inject.Inject
+
+/**
+ * Feature-owned boundary for resolving player content and provider playback URLs.
+ *
+ * The ViewModel supplies only the current playback context. Repository lookup, provider URL
+ * resolution, and credential/provider-specific failure translation stay behind this boundary.
+ */
+class PlayerContentResolver @Inject constructor(
+ private val channelRepository: ChannelRepository,
+ private val movieRepository: MovieRepository,
+ private val seriesRepository: SeriesRepository,
+ private val providerPlaybackResolver: ProviderPlaybackResolver
+) {
+ internal suspend fun resolvePlaybackStream(
+ logicalUrl: String,
+ internalContentId: Long,
+ providerId: Long,
+ contentType: ContentType,
+ currentTitle: String,
+ currentSeries: Series?,
+ currentEpisode: Episode?
+ ): PlayerPlaybackStreamResolution = resolvePlayerPlaybackStreamInfo(
+ logicalUrl = logicalUrl,
+ internalContentId = internalContentId,
+ providerId = providerId,
+ contentType = contentType,
+ currentTitle = currentTitle,
+ currentSeries = currentSeries,
+ currentEpisode = currentEpisode,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository,
+ xtreamStreamUrlResolver = providerPlaybackResolver
+ )
+
+ internal fun isInternalStreamUrl(url: String?): Boolean = providerPlaybackResolver.isInternalStreamUrl(url)
+
+ internal suspend fun getMovie(movieId: Long): Movie? = movieRepository.getMovie(movieId)
+
+ internal suspend fun getMovieVariants(movieId: Long): List<VodMovieVariant> =
+ movieRepository.getMovieVariants(movieId)
+
+ internal suspend fun getMovieStreamInfo(movie: Movie): Result<StreamInfo> =
+ movieRepository.getStreamInfo(movie)
+
+ internal suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series> =
+ seriesRepository.getSeriesDetails(providerId, seriesId)
+
+ internal suspend fun getEpisodeById(episodeId: Long): Episode? =
+ seriesRepository.getEpisodeById(episodeId)
+}
+
+internal suspend fun resolvePlayerPlaybackStreamInfo(
+ logicalUrl: String,
+ internalContentId: Long,
+ providerId: Long,
+ contentType: ContentType,
+ currentTitle: String,
+ currentSeries: Series?,
+ currentEpisode: Episode?,
+ channelRepository: ChannelRepository,
+ movieRepository: MovieRepository,
+ seriesRepository: SeriesRepository,
+ xtreamStreamUrlResolver: ProviderPlaybackResolver
+): PlayerPlaybackStreamResolution {
+ var fallbackStreamId: Long? = null
+ var fallbackContainerExtension: String? = null
+
+ if (providerId > 0L && internalContentId > 0L) {
+ when (contentType) {
+ ContentType.LIVE -> {
+ channelRepository.getChannel(internalContentId)?.let { channel ->
+ fallbackStreamId = channel.streamId.takeIf { it > 0L }
+ ?: channel.epgChannelId?.toLongOrNull()
+ if (shouldUseStoredLiveStreamInfo(logicalUrl, channel.streamUrl)) {
+ channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ }
+ }
+ }
+
+ ContentType.MOVIE,
+ ContentType.VOD -> {
+ movieRepository.getMovie(internalContentId)?.let { movie ->
+ fallbackStreamId = movie.streamId.takeIf { it > 0L }
+ fallbackContainerExtension = movie.containerExtension
+ val streamInfoResult = movieRepository.getStreamInfo(movie)
+ if (streamInfoResult.isSuccess) {
+ streamInfoResult.getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ } else {
+ (streamInfoResult as? Result.Error)?.message?.let { errorMsg ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ resolutionFailureMessage = errorMsg
+ )
+ }
+ }
+ }
+ }
+
+ ContentType.SERIES,
+ ContentType.SERIES_EPISODE -> {
+ val episode = when {
+ currentEpisode?.id == internalContentId ||
+ currentEpisode?.playbackEpisodeIdentity() == internalContentId -> currentEpisode
+ else -> currentSeries
+ ?.seasons
+ .sanitizedForPlayer()
+ .asSequence()
+ .flatMap { it.episodes.asSequence() }
+ .firstOrNull {
+ it.id == internalContentId ||
+ it.playbackEpisodeIdentity() == internalContentId
+ }
+ }
+ episode?.let {
+ fallbackStreamId = it.episodeId.takeIf { episodeId -> episodeId > 0L } ?: it.id
+ fallbackContainerExtension = it.containerExtension
+ val streamInfoResult = seriesRepository.getEpisodeStreamInfo(it)
+ if (streamInfoResult.isSuccess) {
+ streamInfoResult.getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
+ } else {
+ (streamInfoResult as? Result.Error)?.message?.let { errorMsg ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ resolutionFailureMessage = errorMsg
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ xtreamStreamUrlResolver.resolveAndCommitMetadata(
+ url = logicalUrl,
+ fallbackProviderId = providerId.takeIf { it > 0 },
+ fallbackStreamId = fallbackStreamId,
+ fallbackContentType = contentType,
+ fallbackContainerExtension = fallbackContainerExtension
+ )?.let { resolved ->
+ val ext = resolved.containerExtension ?: fallbackContainerExtension
+ return PlayerPlaybackStreamResolution(
+ streamInfo = StreamInfo(
+ url = resolved.url,
+ title = currentTitle,
+ headers = resolved.headers,
+ userAgent = resolved.userAgent,
+ playbackTransportPolicy = resolved.playbackTransportPolicy,
+ allowInvalidSsl = resolved.allowInvalidSsl,
+ proxyHost = resolved.proxyHost,
+ proxyPort = resolved.proxyPort,
+ streamType = StreamType.fromContainerExtension(ext),
+ containerExtension = ext,
+ expirationTime = resolved.expirationTime
+ )
+ )
+ }
+ } catch (e: CredentialDecryptionException) {
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ credentialFailureMessage = e.message ?: CredentialDecryptionException.MESSAGE
+ )
+ } catch (e: StalkerPlaybackResolutionException) {
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ resolutionFailureMessage = e.message
+ ?: "We couldn't resolve a playable Stalker stream for this item."
+ )
+ }
+
+ val isLogicalInternalUrl = xtreamStreamUrlResolver.isInternalStreamUrl(logicalUrl)
+ if (isLogicalInternalUrl) {
+ return PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ resolutionFailureMessage = "This portal requires a different playback path than the default command."
+ )
+ }
+
+ return PlayerPlaybackStreamResolution(
+ streamInfo = logicalUrl.takeIf { it.isNotBlank() }?.let {
+ StreamInfo(
+ url = it,
+ title = currentTitle,
+ streamType = StreamType.fromContainerExtension(fallbackContainerExtension),
+ containerExtension = fallbackContainerExtension
+ )
+ }
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinator.kt
new file mode 100644
index 00000000..1a68a17e
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinator.kt
@@ -0,0 +1,30 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.app.di.MainPlayerEngine
+import com.streamvault.player.PlayerEngine
+import dagger.hilt.android.scopes.ViewModelScoped
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import javax.inject.Inject
+
+/** Owns the active engine and the MediaSession handoff between engine instances. */
+@ViewModelScoped
+class PlayerEngineCoordinator @Inject constructor(
+ @param:MainPlayerEngine
+ val mainEngine: PlayerEngine
+) {
+ private val _activeEngine = MutableStateFlow(mainEngine)
+ val activeEngine: StateFlow<PlayerEngine> = _activeEngine.asStateFlow()
+
+ val currentEngine: PlayerEngine
+ get() = _activeEngine.value
+
+ fun switchTo(engine: PlayerEngine) {
+ if (_activeEngine.value === engine) return
+ // Media3 session IDs must be globally unique. Disable the outgoing session before the
+ // incoming engine is observed by the ViewModel's engine-derived flows.
+ _activeEngine.value.setMediaSessionEnabled(false)
+ _activeEngine.value = engine
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt
index ba101d27..b1fbdaf4 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgActions.kt
@@ -1,83 +1,27 @@
package com.streamvault.app.ui.screens.player
-import androidx.lifecycle.viewModelScope
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
-
-private const val EPG_REFRESH_INTERVAL_MS = 30_000L
-
internal fun PlayerViewModel.fetchEpg(
providerId: Long,
internalChannelId: Long,
epgChannelId: String?,
streamId: Long = 0L
) {
- epgJob?.cancel()
if (providerId <= 0L || (internalChannelId <= 0L && epgChannelId == null && streamId <= 0L)) {
- clearEpgState()
- return
- }
-
- val requestKey = EpgRequestKey(
- providerId = providerId,
- internalChannelId = internalChannelId,
- epgChannelId = epgChannelId,
- streamId = streamId
- )
-
- epgJob = viewModelScope.launch {
- while (true) {
- val now = System.currentTimeMillis()
- val start = now - (24 * 60 * 60 * 1000L)
- val end = now + (6 * 60 * 60 * 1000L)
- val programs = epgRepository.getResolvedProgramsForPlaybackChannel(
- providerId = providerId,
- internalChannelId = internalChannelId,
- epgChannelId = epgChannelId,
- streamId = streamId,
- startTime = start,
- endTime = end
- )
-
- if (activeEpgRequestKey != requestKey) return@launch
-
- if (programs.isNotEmpty()) {
- applyProgramTimeline(programs, now)
- } else {
- applyRemoteProgramFallback(providerId, epgChannelId, streamId, now)
- if (activeEpgRequestKey != requestKey) return@launch
- }
-
- delay(EPG_REFRESH_INTERVAL_MS)
- }
- }
-}
-
-internal suspend fun PlayerViewModel.applyRemoteProgramFallback(
- providerId: Long,
- epgChannelId: String?,
- streamId: Long,
- now: Long
-) {
- if (streamId <= 0L) {
- clearEpgState()
+ epgCoordinator.clear(::clearEpgState)
return
}
- val result = providerRepository.getProgramsForLiveStream(
- providerId = providerId,
- streamId = streamId,
- epgChannelId = epgChannelId,
- limit = 12
+ val requestVersion = prepareRequestVersion
+ epgCoordinator.request(
+ scope = playbackSessionScope(requestVersion),
+ sessionId = requestVersion,
+ requestKey = EpgRequestKey(
+ providerId = providerId,
+ internalChannelId = internalChannelId,
+ epgChannelId = epgChannelId,
+ streamId = streamId
+ ),
+ onPrograms = ::applyProgramTimeline,
+ onClear = ::clearEpgState
)
- val programs = (result as? com.streamvault.domain.model.Result.Success)?.data
- ?.sortedBy { it.startTime }
- .orEmpty()
-
- if (programs.isEmpty()) {
- clearEpgState()
- return
- }
-
- applyProgramTimeline(programs, now)
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinator.kt
new file mode 100644
index 00000000..5042378c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinator.kt
@@ -0,0 +1,91 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.ProviderRepository
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import javax.inject.Inject
+
+private const val EPG_REFRESH_INTERVAL_MS = 30_000L
+
+/** Owns the refresh and fallback lifecycle for the player guide timeline. */
+class PlayerEpgCoordinator @Inject constructor(
+ private val epgRepository: EpgRepository,
+ private val providerRepository: ProviderRepository
+) {
+ private data class RequestIdentity(
+ val sessionId: Long,
+ val requestKey: EpgRequestKey
+ )
+
+ private var activeRequest: RequestIdentity? = null
+ private var refreshJob: Job? = null
+
+ internal fun request(
+ scope: CoroutineScope?,
+ sessionId: Long,
+ requestKey: EpgRequestKey,
+ onPrograms: (List<Program>, Long) -> Unit,
+ onClear: () -> Unit
+ ) {
+ val requestIdentity = RequestIdentity(sessionId = sessionId, requestKey = requestKey)
+ if (requestIdentity == activeRequest && refreshJob?.isActive == true) return
+ refreshJob?.cancel()
+ activeRequest = requestIdentity
+ refreshJob = scope?.launch {
+ while (true) {
+ val now = System.currentTimeMillis()
+ val programs = resolvePrograms(requestKey, now)
+ if (activeRequest != requestIdentity) return@launch
+ if (programs.isEmpty()) {
+ onClear()
+ } else {
+ onPrograms(programs, now)
+ }
+ delay(EPG_REFRESH_INTERVAL_MS)
+ }
+ }
+ }
+
+ internal fun clear(onClear: () -> Unit) {
+ refreshJob?.cancel()
+ refreshJob = null
+ activeRequest = null
+ onClear()
+ }
+
+ internal fun cancel() {
+ refreshJob?.cancel()
+ refreshJob = null
+ activeRequest = null
+ }
+
+ private suspend fun resolvePrograms(requestKey: EpgRequestKey, now: Long): List<Program> {
+ val localPrograms = epgRepository.getResolvedProgramsForPlaybackChannel(
+ providerId = requestKey.providerId,
+ internalChannelId = requestKey.internalChannelId,
+ epgChannelId = requestKey.epgChannelId,
+ streamId = requestKey.streamId,
+ startTime = now - (24 * 60 * 60 * 1000L),
+ endTime = now + (6 * 60 * 60 * 1000L)
+ )
+ if (localPrograms.isNotEmpty()) return localPrograms
+ if (requestKey.streamId <= 0L) return emptyList()
+
+ return when (
+ val result = providerRepository.getProgramsForLiveStream(
+ providerId = requestKey.providerId,
+ streamId = requestKey.streamId,
+ epgChannelId = requestKey.epgChannelId,
+ limit = 12
+ )
+ ) {
+ is Result.Success -> result.data.sortedBy { it.startTime }
+ else -> emptyList()
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinator.kt
new file mode 100644
index 00000000..ccac575a
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinator.kt
@@ -0,0 +1,49 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Program
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import javax.inject.Inject
+
+/** Projects a fetched guide window into the program slices consumed by player UI. */
+class PlayerGuideTimelineCoordinator @Inject constructor() {
+ private companion object {
+ const val MAX_HISTORY_ITEMS = 18
+ const val MAX_UPCOMING_ITEMS = 24
+ }
+
+ private val _currentProgram = MutableStateFlow<Program?>(null)
+ val currentProgram: StateFlow<Program?> = _currentProgram.asStateFlow()
+
+ private val _nextProgram = MutableStateFlow<Program?>(null)
+ val nextProgram: StateFlow<Program?> = _nextProgram.asStateFlow()
+
+ private val _programHistory = MutableStateFlow<List<Program>>(emptyList())
+ val programHistory: StateFlow<List<Program>> = _programHistory.asStateFlow()
+
+ private val _upcomingPrograms = MutableStateFlow<List<Program>>(emptyList())
+ val upcomingPrograms: StateFlow<List<Program>> = _upcomingPrograms.asStateFlow()
+
+ internal fun apply(programs: List<Program>, now: Long, channel: Channel?) {
+ val timeline = buildProgramTimeline(
+ programs = programs,
+ now = now,
+ channel = channel,
+ maxHistoryItems = MAX_HISTORY_ITEMS,
+ maxUpcomingItems = MAX_UPCOMING_ITEMS
+ )
+ _currentProgram.value = timeline.currentProgram
+ _nextProgram.value = timeline.nextProgram
+ _programHistory.value = timeline.programHistory
+ _upcomingPrograms.value = timeline.upcomingPrograms
+ }
+
+ internal fun clear() {
+ _currentProgram.value = null
+ _nextProgram.value = null
+ _programHistory.value = emptyList()
+ _upcomingPrograms.value = emptyList()
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerHistoryCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerHistoryCoordinator.kt
new file mode 100644
index 00000000..4a154807
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerHistoryCoordinator.kt
@@ -0,0 +1,55 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.app.tv.LauncherRecommendationsManager
+import com.streamvault.app.tv.WatchNextManager
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.usecase.MarkAsWatched
+import kotlinx.coroutines.flow.Flow
+import javax.inject.Inject
+
+/** Keeps player history reads and writes behind one feature-scoped boundary. */
+class PlayerHistoryCoordinator @Inject constructor(
+ private val repository: PlaybackHistoryRepository,
+ private val watchNextManager: WatchNextManager,
+ private val launcherRecommendationsManager: LauncherRecommendationsManager,
+ private val markAsWatched: MarkAsWatched
+) {
+ internal fun recentlyWatchedByProvider(providerId: Long, limit: Int): Flow<List<PlaybackHistory>> =
+ repository.getRecentlyWatchedByProvider(providerId, limit)
+
+ internal suspend fun getPlaybackHistory(
+ contentId: Long,
+ contentType: ContentType,
+ providerId: Long,
+ seriesId: Long?,
+ seasonNumber: Int?,
+ episodeNumber: Int?
+ ): PlaybackHistory? = repository.getPlaybackHistory(
+ contentId = contentId,
+ contentType = contentType,
+ providerId = providerId,
+ seriesId = seriesId,
+ seasonNumber = seasonNumber,
+ episodeNumber = episodeNumber
+ )
+
+ internal suspend fun recordPlayback(history: PlaybackHistory): Result<Unit> =
+ repository.recordPlayback(history)
+
+ internal suspend fun markAsWatched(history: PlaybackHistory): Result<Unit> =
+ markAsWatched(history)
+
+ internal suspend fun updateResumePosition(history: PlaybackHistory): Result<Unit> =
+ repository.updateResumePosition(history)
+
+ internal suspend fun flushPendingProgress(): Result<Unit> =
+ repository.flushPendingProgress()
+
+ internal suspend fun refreshPlaybackSurfaces() {
+ watchNextManager.refreshWatchNext()
+ launcherRecommendationsManager.refreshRecommendations()
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
index b40cf89a..e7265a34 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLifecycleActions.kt
@@ -14,7 +14,8 @@ internal fun PlayerViewModel.startProgressTracking() {
progressTrackingJob?.cancel()
if (currentContentType == ContentType.LIVE) return
- progressTrackingJob = viewModelScope.launch {
+ val requestVersion = prepareRequestVersion
+ progressTrackingJob = playbackSessionScope(requestVersion)?.launch {
while (true) {
delay(30_000)
if (!isAppInForeground || !playerEngine.isPlaying.value) continue
@@ -31,10 +32,9 @@ internal suspend fun PlayerViewModel.persistPlaybackProgress() {
val history = buildPlaybackHistorySnapshot(pos, dur) ?: return
logRepositoryFailure(
operation = "Persist playback resume position",
- result = playbackHistoryRepository.updateResumePosition(history)
+ result = playbackHistoryCoordinator.updateResumePosition(history)
)
- watchNextManager.refreshWatchNext()
- launcherRecommendationsManager.refreshRecommendations()
+ playbackHistoryCoordinator.refreshPlaybackSurfaces()
}
}
@@ -43,7 +43,7 @@ internal fun PlayerViewModel.startTokenRenewalMonitoring(expirationTime: Long?)
tokenRenewalJob = null
val expiry = expirationTime?.takeIf { it > 0L } ?: return
val requestVersion = prepareRequestVersion
- tokenRenewalJob = viewModelScope.launch {
+ tokenRenewalJob = playbackSessionScope(requestVersion)?.launch {
while (true) {
delay(LIFECYCLE_TOKEN_RENEWAL_CHECK_INTERVAL_MS)
if (!playerEngine.isPlaying.value) continue
@@ -76,7 +76,7 @@ fun PlayerViewModel.onAppBackgrounded() {
if (currentContentType != ContentType.LIVE) {
viewModelScope.launch {
persistPlaybackProgress()
- playbackHistoryRepository.flushPendingProgress()
+ playbackHistoryCoordinator.flushPendingProgress()
}
}
}
@@ -94,7 +94,7 @@ fun PlayerViewModel.onPlayerScreenDisposed() {
if (currentContentType != ContentType.LIVE) {
viewModelScope.launch {
persistPlaybackProgress()
- playbackHistoryRepository.flushPendingProgress()
+ playbackHistoryCoordinator.flushPendingProgress()
}
}
playerEngine.stopLiveTimeshift()
@@ -120,7 +120,7 @@ fun PlayerViewModel.handOffPlaybackToMultiView() {
}
playerEngine.stopLiveTimeshift()
stopLiveTranslationSession()
- livePreviewHandoffManager.clear(playerEngine)
+ playerPreviewCoordinator.clear(playerEngine)
}
internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine) {
@@ -131,7 +131,7 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine)
numericInputCommitJob?.cancel()
numericInputFeedbackJob?.cancel()
playerNoticeHideJob?.cancel()
- epgJob?.cancel()
+ epgCoordinator.cancel()
playlistJob?.cancel()
controlsHideJob?.cancel()
zapOverlayJob?.cancel()
@@ -144,7 +144,7 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine)
thumbnailPreloadJob?.cancel()
inFlightThumbnailPreloadKey = null
lastCompletedThumbnailPreloadKey = null
- seekThumbnailProvider.clearCache()
+ playerThumbnailCoordinator.clearCache()
val activeEngine = playerEngine
val channel = currentChannel.value
@@ -157,7 +157,7 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine)
&& activeEngine.playbackState.value != PlaybackState.ERROR
if (canReverseHandoff) {
- livePreviewHandoffManager.beginReverseHandoff(
+ playerPreviewCoordinator.beginReverseHandoff(
channel = channel!!,
streamInfo = streamInfo!!,
engine = activeEngine,
@@ -165,7 +165,7 @@ internal fun PlayerViewModel.cleanupAfterCleared(mainPlayerEngine: PlayerEngine)
)
mainPlayerEngine.resetForReuse()
} else {
- livePreviewHandoffManager.clear(activeEngine)
+ playerPreviewCoordinator.clear(activeEngine)
if (activeEngine === mainPlayerEngine) {
mainPlayerEngine.resetForReuse()
} else {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
index f0b8bc27..1681eab5 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerLiveTranslationActions.kt
@@ -1,8 +1,6 @@
package com.streamvault.app.ui.screens.player
import androidx.lifecycle.viewModelScope
-import com.streamvault.app.player.LiveTranslationClient
-import com.streamvault.app.player.LiveTranslationSession
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ProviderType
import kotlinx.coroutines.flow.first
@@ -16,8 +14,8 @@ import kotlinx.coroutines.launch
* supported live stream) any running session is stopped.
*/
internal suspend fun PlayerViewModel.refreshLiveTranslationAvailability() {
- val enabled = preferencesRepository.playerLiveTranslationEnabled.first()
- val provider = if (currentProviderId > 0L) providerRepository.getProvider(currentProviderId) else null
+ val enabled = playerPreferencesCoordinator.playerLiveTranslationEnabled.first()
+ val provider = if (currentProviderId > 0L) playerProviderCoordinator.getProvider(currentProviderId) else null
val available = shouldEnableLiveTranslationSession(enabled, currentContentType, provider?.type)
_liveTranslationAvailable.value = available
if (!available && liveTranslationActive.value) {
@@ -35,7 +33,7 @@ internal fun PlayerViewModel.activateLiveTranslation() {
/** Invoked when the user picks a regular subtitle track or "Off" from the subtitle menu. */
internal fun PlayerViewModel.deactivateLiveTranslation() {
- if (!liveTranslationActive.value && liveTranslationSession == null) return
+ if (!liveTranslationActive.value && !playerTranslationCoordinator.isActive) return
stopLiveTranslationSession()
}
@@ -48,8 +46,8 @@ internal suspend fun PlayerViewModel.evaluateLiveTranslationSession() {
stopLiveTranslationSession()
return
}
- val enabled = preferencesRepository.playerLiveTranslationEnabled.first()
- val provider = providerRepository.getProvider(currentProviderId)
+ val enabled = playerPreferencesCoordinator.playerLiveTranslationEnabled.first()
+ val provider = playerProviderCoordinator.getProvider(currentProviderId)
if (!shouldEnableLiveTranslationSession(enabled, currentContentType, provider?.type)) {
stopLiveTranslationSession()
return
@@ -58,11 +56,12 @@ internal suspend fun PlayerViewModel.evaluateLiveTranslationSession() {
stopLiveTranslationSession()
return
}
- val endpoint = preferencesRepository.playerLiveTranslationEndpoint.first()
- val session = LiveTranslationSession(
- scope = viewModelScope,
+ val endpoint = playerPreferencesCoordinator.playerLiveTranslationEndpoint.first()
+ val sessionScope = playbackSessionScope() ?: return
+ playerTranslationCoordinator.start(
+ scope = sessionScope,
playerEngine = playerEngine,
- client = LiveTranslationClient(okHttpClient, endpoint),
+ endpoint = endpoint,
logicalUrl = currentStreamUrl,
providerId = currentProviderId,
contentId = currentContentId,
@@ -73,14 +72,10 @@ internal suspend fun PlayerViewModel.evaluateLiveTranslationSession() {
showPlayerNotice(message = message, recoveryType = PlayerRecoveryType.NETWORK)
}
)
- stopLiveTranslationSession(clearActiveState = false)
- liveTranslationSession = session
- session.start()
}
internal fun PlayerViewModel.stopLiveTranslationSession(clearActiveState: Boolean = true) {
- liveTranslationSession?.stop()
- liveTranslationSession = null
+ playerTranslationCoordinator.stop()
playerEngine.clearInjectedSubtitleCues()
_liveTranslationDetectedLanguage.value = null
if (clearActiveState) {
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerMovieFallbackSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerMovieFallbackSupport.kt
index f55c17dc..047c8b7b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerMovieFallbackSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerMovieFallbackSupport.kt
@@ -15,18 +15,18 @@ internal suspend fun PlayerViewModel.tryFallbackToAvcMovieVariant(
): Boolean {
if (currentContentType != com.streamvault.domain.model.ContentType.MOVIE) return false
if (currentProviderId <= 0L || currentContentId <= 0L) return false
- if (hasRetriedWithAvcMovieVariant) return false
+ if (playerRecoveryCoordinator.retriedWithAvcMovieVariant) return false
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return false
- val currentMovie = movieRepository.getMovie(currentContentId) ?: return false
- val variants = movieRepository.getMovieVariants(currentContentId)
+ val currentMovie = playerContentResolver.getMovie(currentContentId) ?: return false
+ val variants = playerContentResolver.getMovieVariants(currentContentId)
val fallbackVariant = selectAvcMovieFallbackVariant(currentMovie, variants) ?: return false
- val fallbackMovie = movieRepository.getMovie(fallbackVariant.rawMovieId) ?: return false
- val fallbackStreamInfo = movieRepository.getStreamInfo(fallbackMovie).getOrNull() ?: return false
+ val fallbackMovie = playerContentResolver.getMovie(fallbackVariant.rawMovieId) ?: return false
+ val fallbackStreamInfo = playerContentResolver.getMovieStreamInfo(fallbackMovie).getOrNull() ?: return false
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return false
- hasRetriedWithAvcMovieVariant = true
+ playerRecoveryCoordinator.retriedWithAvcMovieVariant = true
currentContentId = fallbackMovie.id
currentStreamUrl = fallbackMovie.streamUrl
currentTitle = fallbackMovie.name
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt
index b49e5032..33c483e7 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt
@@ -100,7 +100,7 @@ fun PlayerViewModel.restartCurrentProgram() {
fun PlayerViewModel.retryStream(streamUrl: String, epgChannelId: String?) {
if (isCatchUpPlayback.value) {
val requestVersion = beginPlaybackSession()
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val streamInfo = resolvePlaybackStreamInfo(streamUrl, currentContentId, currentProviderId, currentContentType)
?: return@launch
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinator.kt
new file mode 100644
index 00000000..69607dfa
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinator.kt
@@ -0,0 +1,23 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StreamInfo
+import javax.inject.Inject
+
+/** Owns the mutable identity of the item currently being prepared or played. */
+class PlayerPlaybackContextCoordinator @Inject constructor() {
+ internal var currentStreamUrl: String = ""
+ internal var currentResolvedPlaybackUrl: String = ""
+ internal var currentResolvedStreamInfo: StreamInfo? = null
+ internal var currentContentId: Long = -1L
+ internal var currentProviderId: Long = -1L
+ internal var currentContentType: ContentType = ContentType.LIVE
+ internal var currentTitle: String = ""
+ internal var currentArtworkUrl: String? = null
+ internal var pendingCatchUpUrls: List<String> = emptyList()
+
+ internal fun clearResolvedStream() {
+ currentResolvedPlaybackUrl = ""
+ currentResolvedStreamInfo = null
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt
index 4befaf2e..8ad0e2a8 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackControlActions.kt
@@ -50,7 +50,7 @@ fun PlayerViewModel.toggleMute() {
val muted = playerEngine.isMuted.value
mutePersistJob?.cancel()
mutePersistJob = viewModelScope.launch {
- preferencesRepository.setPlayerMuted(muted)
+ playerPreferencesCoordinator.setPlayerMuted(muted)
}
}
@@ -72,7 +72,7 @@ fun PlayerViewModel.toggleAspectRatio() {
if (currentContentId != -1L) {
viewModelScope.launch {
- preferencesRepository.setAspectRatioForChannel(currentContentId, nextRatio.name)
+ playerPreferencesCoordinator.setAspectRatioForChannel(currentContentId, nextRatio.name)
}
}
}
@@ -106,4 +106,4 @@ fun PlayerViewModel.pause() {
} else {
playerEngine.pause()
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt
index e914d0c8..a0792016 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaybackPreferenceActions.kt
@@ -82,7 +82,7 @@ fun PlayerViewModel.selectLiveVariant(rawChannelId: Long) {
if (updatedChannel.selectedVariantId == currentChannel.selectedVariantId) return
val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.clear()
+ playerRecoveryCoordinator.clearStreamAttempts()
currentContentId = updatedChannel.id
currentStreamUrl = updatedChannel.streamUrl
currentTitle = updatedChannel.currentVariant?.originalName ?: updatedChannel.name
@@ -104,8 +104,8 @@ fun PlayerViewModel.selectLiveVariant(rawChannelId: Long) {
refreshCurrentChannelRecording()
updateChannelDiagnostics(updatedChannel)
updateStreamClass("Variant")
- viewModelScope.launch {
- preferencesRepository.setPreferredLiveVariant(
+ playbackSessionScope(requestVersion)?.launch {
+ playerPreferencesCoordinator.setPreferredLiveVariant(
providerId = updatedChannel.providerId,
logicalGroupId = updatedChannel.logicalGroupId,
rawChannelId = rawChannelId
@@ -140,10 +140,10 @@ fun PlayerViewModel.selectStreamFormat(formatUrl: String) {
if (formatUrl == currentStreamUrl) return
val requestVersion = beginPlaybackSession()
- triedAlternativeStreams.add(formatUrl)
+ playerRecoveryCoordinator.markStreamAttempt(formatUrl)
currentStreamUrl = formatUrl
updateStreamClass("Format")
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val streamInfo = resolvePlaybackStreamInfo(
logicalUrl = formatUrl,
internalContentId = channel.id,
@@ -178,8 +178,8 @@ fun PlayerViewModel.recordLiveVariantObservation(playbackState: PlaybackState, v
lastRecordedVariantObservationSignature = signature
viewModelScope.launch {
- val existing = preferencesRepository.liveVariantObservations.first()[rawChannelId]
- preferencesRepository.recordLiveVariantObservation(
+ val existing = playerPreferencesCoordinator.liveVariantObservations.first()[rawChannelId]
+ playerPreferencesCoordinator.recordLiveVariantObservation(
rawChannelId = rawChannelId,
observedQuality = LiveChannelObservedQuality(
lastObservedWidth = videoFormat.width,
@@ -201,8 +201,8 @@ fun PlayerViewModel.recordMovieVariantSuccessObservation() {
lastRecordedVodVariantObservationSignature = signature
viewModelScope.launch {
- val existing = preferencesRepository.vodVariantObservations.first()[rawMovieId]
- preferencesRepository.recordVodVariantObservation(
+ val existing = playerPreferencesCoordinator.vodVariantObservations.first()[rawMovieId]
+ playerPreferencesCoordinator.recordVodVariantObservation(
rawItemId = rawMovieId,
observation = VodVariantObservation(
successCount = (existing?.successCount ?: 0) + 1,
@@ -231,8 +231,8 @@ fun PlayerViewModel.recordMovieVariantFailureObservation(error: PlayerError) {
lastRecordedVodVariantObservationSignature = signature
viewModelScope.launch {
- val existing = preferencesRepository.vodVariantObservations.first()[rawMovieId]
- preferencesRepository.recordVodVariantObservation(
+ val existing = playerPreferencesCoordinator.vodVariantObservations.first()[rawMovieId]
+ playerPreferencesCoordinator.recordVodVariantObservation(
rawItemId = rawMovieId,
observation = VodVariantObservation(
successCount = existing?.successCount ?: 0,
@@ -248,7 +248,7 @@ fun PlayerViewModel.setPlaybackSpeed(speed: Float) {
val normalizedSpeed = speed.coerceIn(0.5f, 2f)
playerEngine.setPlaybackSpeed(normalizedSpeed)
viewModelScope.launch {
- preferencesRepository.setPlayerPlaybackSpeed(normalizedSpeed)
+ playerPreferencesCoordinator.setPlayerPlaybackSpeed(normalizedSpeed)
}
}
@@ -273,7 +273,7 @@ fun PlayerViewModel.saveAudioVideoOffsetForChannel() {
val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
viewModelScope.launch {
- preferencesRepository.setAudioVideoOffsetForChannel(channelId, offsetMs)
+ playerPreferencesCoordinator.setAudioVideoOffsetForChannel(channelId, offsetMs)
audioVideoOffsetPreviewMs.value = null
}
}
@@ -282,9 +282,9 @@ fun PlayerViewModel.saveAudioVideoOffsetAsGlobal() {
val offsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L }
viewModelScope.launch {
- preferencesRepository.setPlayerAudioVideoOffsetMs(offsetMs)
+ playerPreferencesCoordinator.setPlayerAudioVideoOffsetMs(offsetMs)
if (channelId != null) {
- preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
+ playerPreferencesCoordinator.clearAudioVideoOffsetForChannel(channelId)
}
audioVideoOffsetPreviewMs.value = null
}
@@ -293,7 +293,7 @@ fun PlayerViewModel.saveAudioVideoOffsetAsGlobal() {
fun PlayerViewModel.useGlobalAudioVideoOffset() {
val channelId = currentChannelFlow.value?.id?.takeIf { it > 0L } ?: return
viewModelScope.launch {
- preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
+ playerPreferencesCoordinator.clearAudioVideoOffsetForChannel(channelId)
audioVideoOffsetPreviewMs.value = null
}
}
@@ -319,7 +319,7 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {
val previewPositionMs = positionMs.coerceAtLeast(0L)
val previewUrl = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
- val canExtractFrame = previewUrl.isNotBlank() && seekThumbnailProvider.supportsFrameExtraction(previewUrl)
+ val canExtractFrame = previewUrl.isNotBlank() && playerThumbnailCoordinator.supportsFrameExtraction(previewUrl)
_seekPreview.update { current ->
current.copy(
@@ -340,7 +340,7 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {
val requestVersion = ++seekPreviewRequestVersion
seekPreviewJob = viewModelScope.launch {
delay(120)
- val bitmap = seekThumbnailProvider.loadFrame(previewUrl, previewPositionMs)
+ val bitmap = playerThumbnailCoordinator.loadFrame(previewUrl, previewPositionMs)
if (requestVersion != seekPreviewRequestVersion) return@launch
_seekPreview.update { current ->
@@ -360,7 +360,7 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {
internal fun PlayerViewModel.startThumbnailPreload() {
val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }
- if (url.isBlank() || !seekThumbnailProvider.supportsFrameExtraction(url)) return
+ if (url.isBlank() || !playerThumbnailCoordinator.supportsFrameExtraction(url)) return
if (!shouldStartThumbnailPreload(url, lastCompletedThumbnailPreloadKey, inFlightThumbnailPreloadKey)) return
val durationMs = playerEngine.duration.value
if (durationMs <= 0L) return
@@ -376,7 +376,7 @@ internal fun PlayerViewModel.startThumbnailPreload() {
try {
preloadPositions.forEach { positionMs ->
ensureActive()
- seekThumbnailProvider.loadFrame(url, positionMs)
+ playerThumbnailCoordinator.loadFrame(url, positionMs)
}
lastCompletedThumbnailPreloadKey = url
} finally {
@@ -391,4 +391,4 @@ internal fun PlayerViewModel.clearSeekPreview() {
seekPreviewJob?.cancel()
seekPreviewRequestVersion++
_seekPreview.value = SeekPreviewState()
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt
index f4df01ce..554c6311 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistActions.kt
@@ -2,7 +2,6 @@
package com.streamvault.app.ui.screens.player
-import androidx.lifecycle.viewModelScope
import com.streamvault.app.ui.model.orderedByRequestedRawIds
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
@@ -24,9 +23,9 @@ internal fun PlayerViewModel.observeCombinedLivePlaylist(
categoryId: Long
): Flow<List<Channel>> = when {
categoryId == ChannelRepository.ALL_CHANNELS_ID -> {
- combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
+ playerPlaylistCoordinator.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
combinedCategoriesById = combinedCategories.associateBy { it.category.id }
- val flows = combinedCategories.map { combinedM3uRepository.getCombinedChannels(profileId, it) }
+ val flows = combinedCategories.map { playerPlaylistCoordinator.getCombinedChannels(profileId, it) }
if (flows.isEmpty()) {
flowOf(emptyList())
} else {
@@ -51,7 +50,7 @@ internal fun PlayerViewModel.observeCombinedLivePlaylist(
}
categoryId < 0L -> {
- favoriteRepository.getFavoritesByGroup(-categoryId)
+ playerPlaylistCoordinator.getFavoritesByGroup(-categoryId)
.map { favorites ->
favorites
.sortedBy { it.position }
@@ -66,13 +65,13 @@ internal fun PlayerViewModel.observeCombinedLivePlaylist(
}
else -> {
- combinedM3uRepository.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
+ playerPlaylistCoordinator.getCombinedCategories(profileId).flatMapLatest { combinedCategories ->
combinedCategoriesById = combinedCategories.associateBy { it.category.id }
val combinedCategory = combinedCategoriesById[categoryId]
if (combinedCategory == null) {
flowOf(emptyList())
} else {
- combinedM3uRepository.getCombinedChannels(profileId, combinedCategory)
+ playerPlaylistCoordinator.getCombinedChannels(profileId, combinedCategory)
.map(::applyCombinedSourceProviderFilter)
}
}
@@ -86,12 +85,12 @@ internal fun PlayerViewModel.observeRecentChannels() {
return
}
- recentChannelsJob = viewModelScope.launch {
+ recentChannelsJob = playbackSessionScope()?.launch {
val recentFlow = currentCombinedProfileId?.let { profileId ->
combinedProviderIdsFlow(profileId)
.flatMapLatest { providerIds -> observeRecentLiveIds(effectiveCombinedProviderIds(providerIds), 12) }
.flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids, currentCombinedSourceFilterProviderId) }
- } ?: playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)
+ } ?: playbackHistoryCoordinator.recentlyWatchedByProvider(currentProviderId, limit = 12)
.map { history ->
history.asSequence()
.filter { it.contentType == ContentType.LIVE }
@@ -102,7 +101,7 @@ internal fun PlayerViewModel.observeRecentChannels() {
}
.flatMapLatest { ids -> loadLiveChannelsByOrderedIds(ids) }
- combine(recentFlow, preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->
+ combine(recentFlow, playerPreferencesCoordinator.liveChannelNumberingMode) { channels, numberingMode ->
numberingMode to channels
}.collect { (numberingMode, channels) ->
channelNumberingMode = numberingMode
@@ -127,22 +126,22 @@ internal fun PlayerViewModel.observeLastVisitedCategory() {
return
}
- lastVisitedCategoryJob = viewModelScope.launch {
+ lastVisitedCategoryJob = playbackSessionScope()?.launch {
val categoriesFlow = currentCombinedProfileId?.let { profileId ->
combinedProviderIdsFlow(profileId).flatMapLatest { providerIds ->
combine(
- combinedM3uRepository.getCombinedCategories(profileId),
- getCustomCategories(providerIds, ContentType.LIVE)
+ playerPlaylistCoordinator.getCombinedCategories(profileId),
+ playerPlaylistCoordinator.getCustomCategories(providerIds)
) { combinedCategories, customCategories ->
combinedCategoriesById = combinedCategories.associateBy { it.category.id }
buildCombinedLiveCategories(combinedCategories, customCategories) to null
}
}
} ?: combine(
- channelRepository.getCategories(currentProviderId),
- getCustomCategories(currentProviderId, ContentType.LIVE),
- preferencesRepository.getLastLiveCategoryId(currentProviderId),
- preferencesRepository.getHiddenCategoryIds(currentProviderId, ContentType.LIVE)
+ playerPlaylistCoordinator.getCategories(currentProviderId),
+ playerPlaylistCoordinator.getCustomCategories(listOf(currentProviderId)),
+ playerPreferencesCoordinator.getLastLiveCategoryId(currentProviderId),
+ playerPreferencesCoordinator.getHiddenCategoryIds(currentProviderId, ContentType.LIVE)
) { providerCategories, customCategories, lastVisitedCategoryId, hiddenCategoryIds ->
val visibleProviderCategories = providerCategories.filter { category ->
category.id == ChannelRepository.ALL_CHANNELS_ID || category.id !in hiddenCategoryIds
@@ -197,12 +196,12 @@ internal fun PlayerViewModel.loadPlaylist(
initialChannelId: Long
) {
playlistJob?.cancel()
- playlistJob = viewModelScope.launch {
+ playlistJob = playbackSessionScope()?.launch {
val flows = currentCombinedProfileId?.let { profileId ->
observeCombinedLivePlaylist(profileId, categoryId)
} ?: if (isVirtual) {
if (categoryId == VirtualCategoryIds.RECENT) {
- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)
+ playbackHistoryCoordinator.recentlyWatchedByProvider(providerId, limit = 24)
.map { history ->
history.asSequence()
.filter { it.contentType == ContentType.LIVE }
@@ -213,35 +212,35 @@ internal fun PlayerViewModel.loadPlaylist(
}
.flatMapLatest { ids ->
if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ else playerPlaylistCoordinator.getChannelsByIds(ids).map { unsorted ->
unsorted.orderedByRequestedRawIds(ids)
}
}
} else if (categoryId == VirtualCategoryIds.FAVORITES) {
- favoriteRepository.getFavorites(currentProviderId, ContentType.LIVE)
+ playerPlaylistCoordinator.getFavorites(currentProviderId)
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
.flatMapLatest { ids ->
if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ else playerPlaylistCoordinator.getChannelsByIds(ids).map { unsorted ->
unsorted.orderedByRequestedRawIds(ids)
}
}
} else {
val groupId = if (categoryId < 0) -categoryId else categoryId
- favoriteRepository.getFavoritesByGroup(groupId)
+ playerPlaylistCoordinator.getFavoritesByGroup(groupId)
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
.flatMapLatest { ids ->
if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ else playerPlaylistCoordinator.getChannelsByIds(ids).map { unsorted ->
unsorted.orderedByRequestedRawIds(ids)
}
}
}
} else {
- channelRepository.getChannelsByNumber(providerId, categoryId)
+ playerPlaylistCoordinator.getChannelsByNumber(providerId, categoryId)
}
- combine(flows, preferencesRepository.liveChannelNumberingMode) { channels, numberingMode ->
+ combine(flows, playerPreferencesCoordinator.liveChannelNumberingMode) { channels, numberingMode ->
val displayedChannels = when (numberingMode) {
ChannelNumberingMode.GROUP -> channels.mapIndexed { index, channel ->
channel.copy(number = index + 1)
@@ -289,7 +288,7 @@ private fun PlayerViewModel.loadLiveChannelsByOrderedIds(
): Flow<List<Channel>> = if (ids.isEmpty()) {
flowOf(emptyList())
} else {
- channelRepository.getChannelsByIds(ids).map { unsorted ->
+ playerPlaylistCoordinator.getChannelsByIds(ids).map { unsorted ->
val filtered = providerId?.let { requiredProviderId ->
unsorted.filter { it.providerId == requiredProviderId }
} ?: unsorted
@@ -298,7 +297,7 @@ private fun PlayerViewModel.loadLiveChannelsByOrderedIds(
}
private fun PlayerViewModel.combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {
- emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())
+ emit(playerPlaylistCoordinator.getProfile(profileId)?.members.orEmpty())
}.map { members ->
currentCombinedProfileMembers = members
members.filter { it.enabled }.map { it.providerId }
@@ -311,13 +310,13 @@ private fun PlayerViewModel.effectiveCombinedProviderIds(providerIds: List<Long>
private fun PlayerViewModel.observeLiveFavorites(providerIds: List<Long>): Flow<List<Favorite>> = when (providerIds.size) {
0 -> flowOf(emptyList())
- 1 -> favoriteRepository.getFavorites(providerIds.first(), ContentType.LIVE)
- else -> favoriteRepository.getFavorites(providerIds, ContentType.LIVE)
+ 1 -> playerPlaylistCoordinator.getFavorites(providerIds.first())
+ else -> playerPlaylistCoordinator.getFavorites(providerIds)
}
private fun PlayerViewModel.observeRecentLiveIds(providerIds: List<Long>, limit: Int): Flow<List<Long>> = when (providerIds.size) {
0 -> flowOf(emptyList())
- 1 -> playbackHistoryRepository.getRecentlyWatchedByProvider(providerIds.first(), limit)
+ 1 -> playbackHistoryCoordinator.recentlyWatchedByProvider(providerIds.first(), limit)
.map { history ->
history.asSequence()
.filter { it.contentType == ContentType.LIVE }
@@ -329,7 +328,7 @@ private fun PlayerViewModel.observeRecentLiveIds(providerIds: List<Long>, limit:
}
else -> combine(providerIds.map { providerId ->
- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit)
+ playbackHistoryCoordinator.recentlyWatchedByProvider(providerId, limit)
}) { histories ->
histories.toList()
.flatMap { it }
@@ -370,4 +369,4 @@ private fun buildCombinedLiveCategories(
)
)
addAll(combinedCategories.map { it.category })
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistCoordinator.kt
new file mode 100644
index 00000000..e4394665
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPlaylistCoordinator.kt
@@ -0,0 +1,53 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.CombinedCategory
+import com.streamvault.domain.model.CombinedM3uProfile
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.repository.CombinedM3uRepository
+import com.streamvault.domain.repository.FavoriteRepository
+import com.streamvault.domain.usecase.GetCustomCategories
+import kotlinx.coroutines.flow.Flow
+import javax.inject.Inject
+
+/** Owns provider/favorite/category data access used to build live playlists. */
+class PlayerPlaylistCoordinator @Inject constructor(
+ private val favoriteRepository: FavoriteRepository,
+ private val combinedM3uRepository: CombinedM3uRepository,
+ private val getCustomCategories: GetCustomCategories,
+ private val channelCoordinator: PlayerChannelCoordinator
+) {
+ internal fun getFavorites(providerId: Long): Flow<List<Favorite>> =
+ favoriteRepository.getFavorites(providerId, ContentType.LIVE)
+
+ internal fun getFavorites(providerIds: List<Long>): Flow<List<Favorite>> =
+ favoriteRepository.getFavorites(providerIds, ContentType.LIVE)
+
+ internal fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>> =
+ favoriteRepository.getFavoritesByGroup(groupId)
+
+ internal fun getCustomCategories(providerIds: List<Long>): Flow<List<Category>> =
+ getCustomCategories(providerIds, ContentType.LIVE)
+
+ internal fun getCategories(providerId: Long): Flow<List<Category>> =
+ channelCoordinator.getCategories(providerId)
+
+ internal fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>> =
+ channelCoordinator.getChannelsByIds(ids)
+
+ internal fun getChannelsByNumber(providerId: Long, categoryId: Long): Flow<List<Channel>> =
+ channelCoordinator.getChannelsByNumber(providerId, categoryId)
+
+ internal fun getCombinedCategories(profileId: Long): Flow<List<CombinedCategory>> =
+ combinedM3uRepository.getCombinedCategories(profileId)
+
+ internal fun getCombinedChannels(
+ profileId: Long,
+ category: CombinedCategory
+ ): Flow<List<Channel>> = combinedM3uRepository.getCombinedChannels(profileId, category)
+
+ internal suspend fun getProfile(profileId: Long): CombinedM3uProfile? =
+ combinedM3uRepository.getProfile(profileId)
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreferencesCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreferencesCoordinator.kt
new file mode 100644
index 00000000..ca609f6a
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreferencesCoordinator.kt
@@ -0,0 +1,117 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LiveChannelObservedQuality
+import com.streamvault.domain.model.VodVariantObservation
+import javax.inject.Inject
+
+/**
+ * Player-facing preferences boundary.
+ *
+ * The player should depend on the preferences it needs, not on the full
+ * application preferences store. Keeping this adapter in the feature also
+ * gives preference reads and writes one seam for future migration to a
+ * player-specific settings source.
+ */
+class PlayerPreferencesCoordinator @Inject constructor(
+ private val preferencesRepository: PreferencesRepository,
+) {
+ internal val appLanguage get() = preferencesRepository.appLanguage
+ internal val autoPlayNextEpisode get() = preferencesRepository.autoPlayNextEpisode
+ internal val defaultIdleStandbyTimerMinutes get() = preferencesRepository.defaultIdleStandbyTimerMinutes
+ internal val defaultStopPlaybackTimerMinutes get() = preferencesRepository.defaultStopPlaybackTimerMinutes
+ internal val liveChannelNumberingMode get() = preferencesRepository.liveChannelNumberingMode
+ internal val liveVariantObservations get() = preferencesRepository.liveVariantObservations
+ internal val parentalControlLevel get() = preferencesRepository.parentalControlLevel
+ internal val playerAudioDecoderMode get() = preferencesRepository.playerAudioDecoderMode
+ internal val playerAudioOutputPreference get() = preferencesRepository.playerAudioOutputPreference
+ internal val playerAudioVideoOffsetMs get() = preferencesRepository.playerAudioVideoOffsetMs
+ internal val playerCompatibilityMemoryEnabled get() = preferencesRepository.playerCompatibilityMemoryEnabled
+ internal val playerControlsTimeoutSeconds get() = preferencesRepository.playerControlsTimeoutSeconds
+ internal val playerDiagnosticsTimeoutSeconds get() = preferencesRepository.playerDiagnosticsTimeoutSeconds
+ internal val playerEthernetMaxVideoHeight get() = preferencesRepository.playerEthernetMaxVideoHeight
+ internal val playerExternalPlaybackMode get() = preferencesRepository.playerExternalPlaybackMode
+ internal val playerFastRetryOnTransientFailures get() = preferencesRepository.playerFastRetryOnTransientFailures
+ internal val playerLiveOverlayTimeoutSeconds get() = preferencesRepository.playerLiveOverlayTimeoutSeconds
+ internal val playerLiveTranslationEnabled get() = preferencesRepository.playerLiveTranslationEnabled
+ internal val playerLiveTranslationEndpoint get() = preferencesRepository.playerLiveTranslationEndpoint
+ internal val playerMediaSessionEnabled get() = preferencesRepository.playerMediaSessionEnabled
+ internal val playerMuted get() = preferencesRepository.playerMuted
+ internal val playerNoticeTimeoutSeconds get() = preferencesRepository.playerNoticeTimeoutSeconds
+ internal val playerPlaybackBufferMode get() = preferencesRepository.playerPlaybackBufferMode
+ internal val playerPlaybackSpeed get() = preferencesRepository.playerPlaybackSpeed
+ internal val playerSubtitleBackgroundColor get() = preferencesRepository.playerSubtitleBackgroundColor
+ internal val playerSubtitleTextColor get() = preferencesRepository.playerSubtitleTextColor
+ internal val playerSubtitleTextScale get() = preferencesRepository.playerSubtitleTextScale
+ internal val playerSurfaceMode get() = preferencesRepository.playerSurfaceMode
+ internal val playerTimeshiftBackend get() = preferencesRepository.playerTimeshiftBackend
+ internal val playerTimeshiftDepthMinutes get() = preferencesRepository.playerTimeshiftDepthMinutes
+ internal val playerTimeshiftEnabled get() = preferencesRepository.playerTimeshiftEnabled
+ internal val playerVideoDecoderMode get() = preferencesRepository.playerVideoDecoderMode
+ internal val playerVodHttpProtocolMode get() = preferencesRepository.playerVodHttpProtocolMode
+ internal val playerWifiMaxVideoHeight get() = preferencesRepository.playerWifiMaxVideoHeight
+ internal val preventStandbyDuringPlayback get() = preferencesRepository.preventStandbyDuringPlayback
+ internal val preferredAudioLanguage get() = preferencesRepository.preferredAudioLanguage
+ internal val remoteShortcutPreferences get() = preferencesRepository.remoteShortcutPreferences
+ internal val vodVariantObservations get() = preferencesRepository.vodVariantObservations
+ internal val zapAutoRevert get() = preferencesRepository.zapAutoRevert
+
+ internal fun getAspectRatioForChannel(channelId: Long) =
+ preferencesRepository.getAspectRatioForChannel(channelId)
+
+ internal fun getHiddenCategoryIds(providerId: Long, type: ContentType) =
+ preferencesRepository.getHiddenCategoryIds(providerId, type)
+
+ internal fun getLastLiveCategoryId(providerId: Long) =
+ preferencesRepository.getLastLiveCategoryId(providerId)
+
+ internal fun observeAudioVideoOffsetForChannel(channelId: Long) =
+ preferencesRepository.observeAudioVideoOffsetForChannel(channelId)
+
+ internal suspend fun clearAudioVideoOffsetForChannel(channelId: Long) {
+ preferencesRepository.clearAudioVideoOffsetForChannel(channelId)
+ }
+
+ internal suspend fun recordLiveVariantObservation(
+ rawChannelId: Long,
+ observedQuality: LiveChannelObservedQuality,
+ ) {
+ preferencesRepository.recordLiveVariantObservation(rawChannelId, observedQuality)
+ }
+
+ internal suspend fun recordVodVariantObservation(
+ rawItemId: Long,
+ observation: VodVariantObservation,
+ ) {
+ preferencesRepository.recordVodVariantObservation(rawItemId, observation)
+ }
+
+ internal suspend fun setAspectRatioForChannel(channelId: Long, ratio: String) {
+ preferencesRepository.setAspectRatioForChannel(channelId, ratio)
+ }
+
+ internal suspend fun setAudioVideoOffsetForChannel(channelId: Long, offsetMs: Int) {
+ preferencesRepository.setAudioVideoOffsetForChannel(channelId, offsetMs)
+ }
+
+ internal suspend fun setPlayerAudioVideoOffsetMs(offsetMs: Int) {
+ preferencesRepository.setPlayerAudioVideoOffsetMs(offsetMs)
+ }
+
+ internal suspend fun setPlayerMuted(muted: Boolean) {
+ preferencesRepository.setPlayerMuted(muted)
+ }
+
+ internal suspend fun setPlayerPlaybackSpeed(speed: Float) {
+ preferencesRepository.setPlayerPlaybackSpeed(speed)
+ }
+
+ internal suspend fun setPreferredLiveVariant(
+ providerId: Long,
+ logicalGroupId: String,
+ rawChannelId: Long,
+ ) {
+ preferencesRepository.setPreferredLiveVariant(providerId, logicalGroupId, rawChannelId)
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt
index 0e588b36..9ed35d97 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationContextActions.kt
@@ -1,8 +1,8 @@
package com.streamvault.app.ui.screens.player
import androidx.lifecycle.viewModelScope
-import com.streamvault.data.security.CredentialDecryptionException
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Result
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@@ -36,22 +36,24 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext(
if (currentContentType == ContentType.LIVE && hasArchiveRequest) {
playerEngine.stopLiveTimeshift()
- viewModelScope.launch {
- val catchUpUrls = try {
- providerRepository.buildCatchUpUrls(
+ playbackSessionScope(requestVersion)?.launch {
+ val catchUpUrls = when (val catchUpResult = playerProviderCoordinator.buildCatchUpUrls(
providerId = currentProviderId,
streamId = currentContentId,
start = (archiveStartMs ?: 0L) / 1000L,
end = (archiveEndMs ?: 0L) / 1000L
- )
- } catch (e: CredentialDecryptionException) {
- if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
- showPlayerNotice(
- message = e.message ?: CredentialDecryptionException.MESSAGE,
- recoveryType = PlayerRecoveryType.SOURCE
- )
- return@launch
+ )) {
+ is Result.Success -> catchUpResult.data
+ is Result.Error -> {
+ if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ setLastFailureReason(catchUpResult.message)
+ showPlayerNotice(
+ message = catchUpResult.message,
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+ return@launch
+ }
+ is Result.Loading -> return@launch
}
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
if (catchUpUrls.isNotEmpty()) {
@@ -89,8 +91,8 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext(
aspectRatioJob?.cancel()
_aspectRatio.value = AspectRatio.FIT
if (shouldResolveChannelPlaybackContext(currentContentType.name, internalChannelId)) {
- aspectRatioJob = viewModelScope.launch {
- preferencesRepository.getAspectRatioForChannel(internalChannelId).collect { savedRatio ->
+ aspectRatioJob = playbackSessionScope(requestVersion)?.launch {
+ playerPreferencesCoordinator.getAspectRatioForChannel(internalChannelId).collect { savedRatio ->
_aspectRatio.value = try {
savedRatio?.let { AspectRatio.valueOf(it) } ?: AspectRatio.FIT
} catch (_: Exception) {
@@ -99,8 +101,8 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext(
}
}
- viewModelScope.launch {
- val channel = channelRepository.getChannel(internalChannelId)
+ playbackSessionScope(requestVersion)?.launch {
+ val channel = playerChannelCoordinator.getChannel(internalChannelId)
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
currentChannelFlow.value = channel
refreshCurrentChannelRecording()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationCoordinator.kt
new file mode 100644
index 00000000..8a2fb89d
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationCoordinator.kt
@@ -0,0 +1,200 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.app.plugins.StreamVaultPluginManager
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result as DomainResult
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.playback.applyPlaybackTransportPolicy
+import com.streamvault.player.playback.applyUnsafeTlsBypass
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request as HttpRequest
+import java.net.InetSocketAddress
+import java.net.Proxy
+import javax.inject.Inject
+
+/** Owns the provider/plugin preparation and player configuration boundary. */
+class PlayerPreparationCoordinator @Inject constructor(
+ private val pluginManager: StreamVaultPluginManager,
+ private val playerPreferencesCoordinator: PlayerPreferencesCoordinator,
+ private val providerRepository: com.streamvault.domain.repository.ProviderRepository,
+ private val okHttpClient: OkHttpClient,
+ private val playerEngineCoordinator: PlayerEngineCoordinator,
+ private val playerContentResolver: PlayerContentResolver
+) {
+ internal data class Request(
+ val streamInfo: StreamInfo,
+ val contentType: ContentType,
+ val providerId: Long,
+ val currentStreamUrl: String?,
+ val probePassedPlaybackKeys: Set<String>,
+ val probeBeforePlayback: Boolean,
+ val audioVideoOffsetMs: Int
+ )
+
+ internal sealed interface Result {
+ data class Success(
+ val streamInfo: StreamInfo,
+ val probeCacheKey: String?
+ ) : Result
+
+ data class Failure(
+ val message: String,
+ val recoveryType: PlayerRecoveryType
+ ) : Result
+ }
+
+ internal suspend fun prepare(
+ request: Request,
+ isCurrent: () -> Boolean
+ ): Result? {
+ if (!isCurrent()) return null
+
+ val expiry = request.streamInfo.expirationTime
+ if (expiry != null && expiry > 0L && expiry < System.currentTimeMillis()) {
+ return Result.Failure(
+ message = "This stream's subscription has expired. Please renew your subscription with the provider.",
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
+ }
+
+ var preparedStreamInfo = request.streamInfo
+ when (val pluginPrepareResult = pluginManager.preparePlaybackStreamInfo(request.streamInfo)) {
+ is DomainResult.Error -> {
+ return Result.Failure(
+ message = pluginPrepareResult.message,
+ recoveryType = PlayerRecoveryType.NETWORK
+ )
+ }
+
+ DomainResult.Loading -> Unit
+ is DomainResult.Success -> preparedStreamInfo = pluginPrepareResult.data
+ }
+
+ var probeCacheKey: String? = null
+ if (request.probeBeforePlayback && shouldProbePlaybackUrl(request, preparedStreamInfo.url)) {
+ probePlaybackUrl(preparedStreamInfo)?.let { failure ->
+ return Result.Failure(failure.message, failure.recoveryType)
+ }
+ probeCacheKey = resolvePlaybackProbeCacheKey(
+ currentStreamUrl = request.currentStreamUrl,
+ url = preparedStreamInfo.url
+ )
+ }
+
+ if (!isCurrent()) return null
+ applyPlaybackPreferences(
+ engine = playerEngineCoordinator.currentEngine,
+ contentType = request.contentType,
+ audioVideoOffsetMs = request.audioVideoOffsetMs
+ )
+ if (!isCurrent()) return null
+
+ val engine = playerEngineCoordinator.currentEngine
+ engine.prepare(preparedStreamInfo)
+ return Result.Success(
+ streamInfo = preparedStreamInfo,
+ probeCacheKey = probeCacheKey
+ )
+ }
+
+ internal suspend fun applyPlaybackPreferences(
+ engine: PlayerEngine,
+ contentType: ContentType,
+ audioVideoOffsetMs: Int
+ ) {
+ engine.setMuted(playerPreferencesCoordinator.playerMuted.first())
+ engine.setPlaybackSpeed(
+ if (contentType == ContentType.LIVE) {
+ 1f
+ } else {
+ playerPreferencesCoordinator.playerPlaybackSpeed.first()
+ }
+ )
+ engine.setPreferredAudioLanguage(
+ resolvePreferredAudioLanguage(
+ preferredAudioLanguage = playerPreferencesCoordinator.preferredAudioLanguage.first(),
+ appLanguage = playerPreferencesCoordinator.appLanguage.first()
+ )
+ )
+ engine.setNetworkQualityPreferences(
+ wifiMaxHeight = playerPreferencesCoordinator.playerWifiMaxVideoHeight.first(),
+ ethernetMaxHeight = playerPreferencesCoordinator.playerEthernetMaxVideoHeight.first()
+ )
+ engine.setSurfaceMode(playerPreferencesCoordinator.playerSurfaceMode.first())
+ engine.setPlaybackBufferMode(playerPreferencesCoordinator.playerPlaybackBufferMode.first())
+ engine.setVodHttpProtocolMode(playerPreferencesCoordinator.playerVodHttpProtocolMode.first())
+ engine.setFastRetryOnTransientFailures(playerPreferencesCoordinator.playerFastRetryOnTransientFailures.first())
+ engine.setAudioVideoOffsetMs(audioVideoOffsetMs)
+ }
+
+ private suspend fun shouldProbePlaybackUrl(request: Request, url: String): Boolean {
+ if (!url.startsWith("http://") && !url.startsWith("https://")) return false
+ val providerId = request.providerId.takeIf { it > 0L } ?: return false
+ val provider = providerRepository.getProvider(providerId) ?: return false
+ val cacheKey = resolvePlaybackProbeCacheKey(
+ currentStreamUrl = request.currentStreamUrl,
+ url = url
+ )
+ if (provider.type != ProviderType.STALKER_PORTAL &&
+ cacheKey in request.probePassedPlaybackKeys
+ ) {
+ return false
+ }
+ return (
+ provider.type == ProviderType.XTREAM_CODES ||
+ provider.type == ProviderType.STALKER_PORTAL
+ ) && (
+ playerContentResolver.isInternalStreamUrl(request.currentStreamUrl) ||
+ playerContentResolver.isInternalStreamUrl(url)
+ )
+ }
+
+ private suspend fun probePlaybackUrl(streamInfo: StreamInfo): PlaybackProbeFailure? {
+ return runCatching {
+ withContext(Dispatchers.IO) {
+ val request = HttpRequest.Builder()
+ .url(streamInfo.url)
+ .get()
+ .header("Range", "bytes=0-0")
+ .apply {
+ streamInfo.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }
+ streamInfo.headers.forEach { (name, value) -> header(name, value) }
+ }
+ .build()
+ val probeClient = if (
+ streamInfo.playbackTransportPolicy != null ||
+ streamInfo.allowInvalidSsl ||
+ streamInfo.proxyHost.isNotBlank()
+ ) {
+ okHttpClient.newBuilder()
+ .apply {
+ val transportPolicy = streamInfo.playbackTransportPolicy
+ if (transportPolicy != null) {
+ applyPlaybackTransportPolicy(transportPolicy)
+ } else if (streamInfo.allowInvalidSsl) {
+ applyUnsafeTlsBypass()
+ }
+ streamInfo.httpProxy()?.let { proxy(it) }
+ }
+ .build()
+ } else {
+ okHttpClient
+ }
+ probeClient.newCall(request).execute().use { response ->
+ resolvePlaybackProbeFailure(response.code)
+ }
+ }
+ }.getOrNull()
+ }
+
+ private fun StreamInfo.httpProxy(): Proxy? {
+ val host = proxyHost.trim().takeIf { it.isNotBlank() } ?: return null
+ val port = proxyPort ?: return null
+ return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
index 36d80501..f32017a1 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreparationSetupActions.kt
@@ -100,7 +100,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(
if (currentContentType == ContentType.LIVE && currentCombinedProfileId != null) {
val activeCombinedProfileId = currentCombinedProfileId
viewModelScope.launch {
- val members = activeCombinedProfileId?.let { combinedM3uRepository.getProfile(it)?.members }.orEmpty()
+ val members = activeCombinedProfileId?.let { playerPlaylistCoordinator.getProfile(it)?.members }.orEmpty()
if (currentCombinedProfileId == activeCombinedProfileId) {
currentCombinedProfileMembers = members
}
@@ -125,8 +125,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(
playerEngine.stopLiveTimeshift()
}
- hasRetriedWithSoftwareDecoder = false
- hasRetriedWithAvcMovieVariant = false
+ playerRecoveryCoordinator.resetPreparationAttempts()
playerEngine.setDecoderModes(
audioMode = preferredAudioDecoderMode,
videoMode = preferredVideoDecoderMode
@@ -138,9 +137,9 @@ internal fun PlayerViewModel.applyPrepareSessionState(
)
updateStreamClass(streamClassLabel)
- triedAlternativeStreams.clear()
+ playerRecoveryCoordinator.clearStreamAttempts()
if (!hasArchiveRequest) {
- triedAlternativeStreams.add(streamUrl)
+ playerRecoveryCoordinator.markStreamAttempt(streamUrl)
}
return shouldReloadPlaylist
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreviewCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreviewCoordinator.kt
new file mode 100644
index 00000000..c1d854e1
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerPreviewCoordinator.kt
@@ -0,0 +1,112 @@
+package com.streamvault.app.ui.screens.player
+
+import android.os.Build
+import com.streamvault.app.player.LivePreviewHandoffManager
+import com.streamvault.app.player.PreviewHandoffSource
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import com.streamvault.player.Media3PlayerEngine
+import com.streamvault.player.PlayerEngine
+import android.util.Log
+import kotlinx.coroutines.flow.first
+import javax.inject.Inject
+
+/** Owns preview/fullscreen handoff lifecycle for the player feature. */
+class PlayerPreviewCoordinator @Inject constructor(
+ private val handoffManager: LivePreviewHandoffManager,
+ private val engineCoordinator: PlayerEngineCoordinator,
+ private val preparationCoordinator: PlayerPreparationCoordinator,
+ private val preferencesCoordinator: PlayerPreferencesCoordinator,
+) {
+ internal fun consumeFullscreenHandoff(
+ channelId: Long,
+ providerId: Long?
+ ): LivePreviewHandoffManager.LivePreviewHandoffSession? =
+ handoffManager.consumeFullscreenHandoff(channelId, providerId)
+
+ internal fun clear(engine: PlayerEngine?) {
+ handoffManager.clear(engine)
+ }
+
+ internal fun beginReverseHandoff(
+ channel: Channel,
+ streamInfo: StreamInfo,
+ engine: PlayerEngine,
+ source: PreviewHandoffSource
+ ) {
+ handoffManager.beginReverseHandoff(channel, streamInfo, engine, source)
+ }
+
+ internal suspend fun tryAdoptFullscreenHandoff(
+ channelId: Long,
+ providerId: Long,
+ contentType: ContentType,
+ audioVideoOffsetMs: Int,
+ isCurrent: () -> Boolean,
+ onAdopted: (StreamInfo) -> Unit,
+ onStarted: (StreamInfo) -> Unit,
+ ): Boolean {
+ if (contentType != ContentType.LIVE) return false
+
+ val session = consumeFullscreenHandoff(
+ channelId = channelId,
+ providerId = providerId.takeIf { it > 0L }
+ ) ?: return false
+
+ if (shouldBypassForFireTvLiveHls(session.streamInfo)) {
+ logInfo("Skipping preview handoff for Fire TV live HLS; fullscreen will prepare a fresh session.")
+ clear(session.engine)
+ session.engine.release()
+ return false
+ }
+
+ val adoptedEngine = session.engine
+ return runCatching {
+ adoptedEngine.clearRenderBinding()
+ engineCoordinator.mainEngine.setMediaSessionEnabled(false)
+ engineCoordinator.switchTo(adoptedEngine)
+ (adoptedEngine as? Media3PlayerEngine)?.let {
+ it.bypassAudioFocus = false
+ it.enableMediaSession = preferencesCoordinator.playerMediaSessionEnabled.first()
+ it.constrainResolutionForMultiView = false
+ }
+ preparationCoordinator.applyPlaybackPreferences(
+ engine = adoptedEngine,
+ contentType = contentType,
+ audioVideoOffsetMs = audioVideoOffsetMs
+ )
+ if (!isCurrent()) {
+ engineCoordinator.switchTo(engineCoordinator.mainEngine)
+ adoptedEngine.release()
+ false
+ } else {
+ onAdopted(session.streamInfo)
+ adoptedEngine.resetLiveHandoffGrace()
+ engineCoordinator.currentEngine.play()
+ onStarted(session.streamInfo)
+ true
+ }
+ }.getOrElse {
+ clear(adoptedEngine)
+ if (engineCoordinator.currentEngine === adoptedEngine) {
+ engineCoordinator.switchTo(engineCoordinator.mainEngine)
+ }
+ adoptedEngine.release()
+ false
+ }
+ }
+
+ private fun shouldBypassForFireTvLiveHls(streamInfo: StreamInfo): Boolean {
+ val isAmazonMediaTek = Build.MANUFACTURER.equals("Amazon", ignoreCase = true) &&
+ Build.HARDWARE.orEmpty().startsWith("mt", ignoreCase = true)
+ val isHls = streamInfo.streamType == StreamType.HLS ||
+ streamInfo.url.substringBefore('?').endsWith(".m3u8", ignoreCase = true)
+ return isAmazonMediaTek && isHls
+ }
+
+ private fun logInfo(message: String) {
+ runCatching { Log.i("PlayerVM", message) }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinator.kt
new file mode 100644
index 00000000..5f27a9b0
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinator.kt
@@ -0,0 +1,26 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.data.security.CredentialDecryptionException
+import javax.inject.Inject
+
+/** Feature-owned provider access for playback, catch-up, and recovery decisions. */
+class PlayerProviderCoordinator @Inject constructor(
+ private val repository: ProviderRepository
+) {
+ internal suspend fun getProvider(providerId: Long): LegacyProvider? =
+ repository.getProvider(providerId)
+
+ internal suspend fun buildCatchUpUrls(
+ providerId: Long,
+ streamId: Long,
+ start: Long,
+ end: Long
+ ): Result<List<String>> = try {
+ Result.success(repository.buildCatchUpUrls(providerId, streamId, start, end))
+ } catch (error: CredentialDecryptionException) {
+ Result.error(error.message ?: CredentialDecryptionException.MESSAGE, error)
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecordingCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecordingCoordinator.kt
new file mode 100644
index 00000000..2adf0acf
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecordingCoordinator.kt
@@ -0,0 +1,28 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.manager.RecordingManager
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingRequest
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.usecase.ScheduleRecording
+import com.streamvault.domain.usecase.ScheduleRecordingCommand
+import kotlinx.coroutines.flow.Flow
+import javax.inject.Inject
+
+/** Owns recording observation and player-originated recording commands. */
+class PlayerRecordingCoordinator @Inject constructor(
+ private val recordingManager: RecordingManager,
+ private val scheduleRecording: ScheduleRecording
+) {
+ internal fun observeRecordingItems(): Flow<List<RecordingItem>> =
+ recordingManager.observeRecordingItems()
+
+ internal suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem> =
+ recordingManager.startManualRecording(request)
+
+ internal suspend fun scheduleRecording(command: ScheduleRecordingCommand): Result<RecordingItem> =
+ scheduleRecording(command)
+
+ internal suspend fun stopRecording(recordingId: String): Result<Unit> =
+ recordingManager.stopRecording(recordingId)
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt
index 772ca3bf..445bcced 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryActions.kt
@@ -7,12 +7,11 @@ import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerError
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
-import java.util.Locale
private const val PROVIDER_AUTH_RETRY_GRACE_MS = 1_200L
internal fun PlayerViewModel.buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> {
- return buildPlayerRecoveryActions(
+ return PlayerRecoveryPolicy.buildActions(
hasAlternateStream = hasAlternateStream(),
hasLastChannel = hasLastChannel(),
shouldOfferGuide = recoveryType == PlayerRecoveryType.CATCH_UP && currentContentType == ContentType.LIVE
@@ -22,26 +21,15 @@ internal fun PlayerViewModel.buildRecoveryActions(recoveryType: PlayerRecoveryTy
internal fun shouldAttemptProviderAuthRetry(
providerType: ProviderType,
contentType: ContentType
-): Boolean = contentType == ContentType.LIVE &&
- (providerType == ProviderType.XTREAM_CODES || providerType == ProviderType.STALKER_PORTAL)
+): Boolean = PlayerRecoveryPolicy.shouldAttemptProviderAuthRetry(providerType, contentType)
internal fun shouldCooldownLivePreloadAfterError(message: String?): Boolean {
- val normalized = message.orEmpty().lowercase(Locale.ROOT)
- return "401" in normalized ||
- "403" in normalized ||
- "429" in normalized ||
- "509" in normalized ||
- "forbidden" in normalized ||
- "unauthorized" in normalized ||
- "too many" in normalized ||
- "max connection" in normalized ||
- "provider limit" in normalized ||
- "connection limit" in normalized
+ return PlayerRecoveryPolicy.shouldCooldownLivePreloadAfterError(message)
}
internal fun PlayerViewModel.cooldownLivePreloadForCurrentProvider(reason: String) {
val providerId = currentProviderId.takeIf { it > 0L } ?: return
- if (livePreloadCooldownProviderIds.add(providerId)) {
+ if (playerRecoveryCoordinator.markLivePreloadCoolingDown(providerId)) {
appendRecoveryAction("Disabled live preload for provider: $reason")
playerEngine.preload(null)
}
@@ -52,7 +40,7 @@ internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(
requestVersion: Long,
playbackUrl: String
): Boolean {
- if (hasRetriedXtreamAuthRefresh) return false
+ if (!playerRecoveryCoordinator.canRetryXtreamAuthRefresh()) return false
if (error !is PlayerError.NetworkError) return false
if (!isAuthExpiryPlaybackError(error.message)) return false
if (!isXtreamPlaybackSession()) return false
@@ -66,7 +54,7 @@ internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return false
- hasRetriedXtreamAuthRefresh = true
+ playerRecoveryCoordinator.markXtreamAuthRefreshRetried()
probePassedPlaybackKeys.remove(
resolvePlaybackProbeCacheKey(
currentStreamUrl = currentStreamUrl,
@@ -78,8 +66,7 @@ internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(
appendRecoveryAction("Retrying provider playback from a fresh live URL")
delay(PROVIDER_AUTH_RETRY_GRACE_MS)
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return true
- currentResolvedPlaybackUrl = ""
- currentResolvedStreamInfo = null
+ clearResolvedStream()
playerEngine.preload(null)
if (!preparePlayer(refreshedStreamInfo, requestVersion, probeBeforePlayback = false)) return true
playerEngine.play()
@@ -88,7 +75,7 @@ internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(
internal suspend fun PlayerViewModel.isXtreamPlaybackSession(): Boolean {
val providerId = currentProviderId.takeIf { it > 0L } ?: return false
- val provider = providerRepository.getProvider(providerId) ?: return false
+ val provider = playerProviderCoordinator.getProvider(providerId) ?: return false
return shouldAttemptProviderAuthRetry(provider.type, currentContentType)
}
@@ -108,7 +95,7 @@ internal fun PlayerViewModel.scheduleZapBufferWatchdog(targetIndex: Int) {
if (!zapAutoRevertEnabled) return
zapBufferWatchdogJob?.cancel()
val requestVersion = prepareRequestVersion
- zapBufferWatchdogJob = viewModelScope.launch {
+ zapBufferWatchdogJob = playbackSessionScope(requestVersion)?.launch {
repeat(15) {
delay(1000)
if (!isActivePlaybackSession(requestVersion)) return@launch
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinator.kt
new file mode 100644
index 00000000..2195b6e8
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinator.kt
@@ -0,0 +1,76 @@
+package com.streamvault.app.ui.screens.player
+
+import javax.inject.Inject
+
+/**
+ * Owns retry guards and provider preload cooldowns for the player feature.
+ *
+ * Recovery actions still live beside the ViewModel until their host callbacks
+ * are fully separated, but their mutable attempt state no longer belongs to
+ * the UI model or leaks across playback sessions.
+ */
+class PlayerRecoveryCoordinator @Inject constructor() {
+ private var sessionId: Long = Long.MIN_VALUE
+ private var softwareDecoderRetryUsed = false
+ private var avcMovieVariantRetryUsed = false
+ private var xtreamAuthRefreshRetryUsed = false
+ private val livePreloadCooldownProviderIds = mutableSetOf<Long>()
+ private val triedStreamUrls = mutableSetOf<String>()
+ private val failedStreamCounts = mutableMapOf<String, Int>()
+
+ internal fun beginSession(newSessionId: Long) {
+ if (sessionId == newSessionId) return
+ sessionId = newSessionId
+ xtreamAuthRefreshRetryUsed = false
+ resetPreparationAttempts()
+ // A new preparation/recovery transition is not a new root playback identity. Keep
+ // attempted and failed URLs until an explicit root playback change clears them.
+ }
+
+ internal fun resetPreparationAttempts() {
+ softwareDecoderRetryUsed = false
+ avcMovieVariantRetryUsed = false
+ }
+
+ internal var retriedWithSoftwareDecoder: Boolean
+ get() = softwareDecoderRetryUsed
+ set(value) {
+ softwareDecoderRetryUsed = value
+ }
+
+ internal var retriedWithAvcMovieVariant: Boolean
+ get() = avcMovieVariantRetryUsed
+ set(value) {
+ avcMovieVariantRetryUsed = value
+ }
+
+ internal fun canRetryXtreamAuthRefresh(): Boolean = !xtreamAuthRefreshRetryUsed
+
+ internal fun markXtreamAuthRefreshRetried() {
+ xtreamAuthRefreshRetryUsed = true
+ }
+
+ internal fun isLivePreloadCoolingDown(providerId: Long): Boolean =
+ providerId in livePreloadCooldownProviderIds
+
+ internal fun markLivePreloadCoolingDown(providerId: Long): Boolean =
+ livePreloadCooldownProviderIds.add(providerId)
+
+ internal fun streamAttemptSnapshot(): Set<String> = triedStreamUrls.toSet()
+
+ internal fun failedStreamSnapshot(): Map<String, Int> = failedStreamCounts.toMap()
+
+ internal fun markStreamAttempt(streamUrl: String) {
+ if (streamUrl.isNotBlank()) triedStreamUrls.add(streamUrl)
+ }
+
+ internal fun clearStreamAttempts() {
+ triedStreamUrls.clear()
+ failedStreamCounts.clear()
+ }
+
+ internal fun markStreamFailure(streamUrl: String) {
+ if (streamUrl.isBlank()) return
+ failedStreamCounts[streamUrl] = (failedStreamCounts[streamUrl] ?: 0) + 1
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinator.kt
new file mode 100644
index 00000000..db2e1a7f
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinator.kt
@@ -0,0 +1,281 @@
+package com.streamvault.app.ui.screens.player
+
+import android.util.Log
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerError
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import javax.inject.Inject
+
+private const val PROVIDER_AUTH_RETRY_GRACE_MS = 1_200L
+
+internal data class PlayerRecoveryRequest(
+ val error: PlayerError,
+ val requestVersion: Long,
+ val playbackUrl: String,
+ val contentType: ContentType,
+ val currentStreamUrl: String,
+ val resolvedStreamInfo: StreamInfo?,
+ val channel: Channel?,
+ val isCatchUp: Boolean,
+ val currentProgramHasArchive: Boolean,
+ val livePlaybackReady: Boolean,
+)
+
+internal interface PlayerRecoveryExecutionPort {
+ val appPackageName: String
+ val playerEngine: PlayerEngine
+ val recoveryState: PlayerRecoveryCoordinator
+
+ fun isActivePlaybackSession(requestVersion: Long, playbackUrl: String): Boolean
+ fun tryAlternateStream(
+ channel: Channel,
+ preferXtreamTsFallback: Boolean = false,
+ allowXtreamTsFallback: Boolean = true,
+ ): Boolean
+ fun tryNextCatchUpVariant(): Boolean
+ suspend fun tryFallbackToAvcMovieVariant(requestVersion: Long, playbackUrl: String): Boolean
+ suspend fun tryRefreshXtreamPlaybackAfterAuthError(
+ error: PlayerError,
+ requestVersion: Long,
+ playbackUrl: String,
+ ): Boolean
+ fun recordMovieVariantFailureObservation(error: PlayerError)
+ fun updateDecoderModes(audioMode: DecoderMode, videoMode: DecoderMode)
+ fun setLastFailureReason(message: String?)
+ fun appendRecoveryAction(action: String)
+ fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction>
+ fun showPlayerNotice(
+ message: String,
+ recoveryType: PlayerRecoveryType,
+ actions: List<PlayerNoticeAction> = emptyList(),
+ isRetryNotice: Boolean = false,
+ )
+ fun markStreamFailure(streamUrl: String)
+ suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit>
+ fun logRepositoryFailure(operation: String, result: Result<Unit>)
+ fun fallbackToPreviousChannel(reason: String): Boolean
+ fun hasLastChannel(): Boolean
+}
+
+/** Owns the playback-error decision tree and its session-scoped recovery job. */
+class PlayerRecoveryExecutionCoordinator @Inject constructor() {
+ private var recoveryJob: Job? = null
+
+ internal fun cancel() {
+ recoveryJob?.cancel()
+ recoveryJob = null
+ }
+
+ internal fun handlePlaybackError(
+ request: PlayerRecoveryRequest,
+ sessionScope: CoroutineScope?,
+ port: PlayerRecoveryExecutionPort,
+ ): Job? {
+ val error = request.error
+ logInfo(
+ "handle-playback-error type=${error::class.java.simpleName} contentType=${request.contentType} " +
+ "hasChannel=${request.channel != null} requestVersion=${request.requestVersion} " +
+ "active=${port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)}"
+ )
+ cancel()
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return null
+
+ if (error is PlayerError.DecoderError && !port.recoveryState.retriedWithSoftwareDecoder) {
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return null
+ if (request.contentType == ContentType.LIVE) {
+ val currentLiveHlsSession = request.resolvedStreamInfo?.streamType == com.streamvault.domain.model.StreamType.HLS
+ if (currentLiveHlsSession) {
+ val channel = request.channel
+ if (channel != null && port.tryAlternateStream(channel, allowXtreamTsFallback = false)) {
+ return null
+ }
+ logWarning(
+ "Decoder error on live HLS. Keeping hardware path to match Sparkle-like playback on ${port.appPackageName}."
+ )
+ }
+ }
+ port.recoveryState.retriedWithSoftwareDecoder = true
+ logWarning("Decoder error detected. Retrying with software decoder mode.")
+ port.playerEngine.setDecoderModes(
+ audioMode = DecoderMode.SOFTWARE,
+ videoMode = DecoderMode.SOFTWARE
+ )
+ port.updateDecoderModes(
+ audioMode = DecoderMode.SOFTWARE,
+ videoMode = DecoderMode.SOFTWARE
+ )
+ port.setLastFailureReason(error.message)
+ port.appendRecoveryAction("Switched to software decoder")
+ port.playerEngine.play()
+ port.showPlayerNotice(
+ message = "Retrying with software decoding for this stream.",
+ recoveryType = PlayerRecoveryType.DECODER,
+ actions = port.buildRecoveryActions(PlayerRecoveryType.DECODER)
+ )
+ return null
+ }
+
+ port.recordMovieVariantFailureObservation(error)
+ if (
+ error is PlayerError.DecoderError &&
+ port.recoveryState.retriedWithSoftwareDecoder &&
+ request.contentType == ContentType.LIVE
+ ) {
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return null
+ val channel = request.channel ?: return null
+ if (port.tryAlternateStream(channel)) {
+ port.appendRecoveryAction("Trying alternate stream format after decoder error")
+ port.showPlayerNotice(
+ message = "Trying alternate stream format for ${channel.name}.",
+ recoveryType = PlayerRecoveryType.DECODER,
+ actions = port.buildRecoveryActions(PlayerRecoveryType.DECODER),
+ isRetryNotice = true
+ )
+ return null
+ }
+ }
+
+ recoveryJob = sessionScope?.launch {
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return@launch
+ if (
+ error is PlayerError.DecoderError &&
+ request.contentType == ContentType.MOVIE &&
+ !port.recoveryState.retriedWithAvcMovieVariant &&
+ port.tryFallbackToAvcMovieVariant(request.requestVersion, request.playbackUrl)
+ ) {
+ return@launch
+ }
+ if (port.tryRefreshXtreamPlaybackAfterAuthError(error, request.requestVersion, request.playbackUrl)) {
+ return@launch
+ }
+
+ val recoveryType = classifyPlaybackError(error)
+ val channel = request.channel
+ logInfo(
+ "recovery-dispatch type=$recoveryType live=${request.contentType == ContentType.LIVE} " +
+ "hasChannel=${channel != null}"
+ )
+
+ if (recoveryType == PlayerRecoveryType.DRM) {
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return@launch
+ port.showPlayerNotice(
+ message = "This channel requires DRM support that is not available. " +
+ "Your subscription may not include this content.",
+ recoveryType = PlayerRecoveryType.DRM,
+ actions = port.buildRecoveryActions(PlayerRecoveryType.DRM)
+ )
+ return@launch
+ }
+
+ if (request.contentType != ContentType.LIVE || channel == null) {
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return@launch
+ port.showPlayerNotice(
+ message = resolvePlaybackErrorMessage(error),
+ recoveryType = recoveryType,
+ actions = port.buildRecoveryActions(recoveryType)
+ )
+ return@launch
+ }
+
+ if (request.isCatchUp) {
+ port.markStreamFailure(request.currentStreamUrl)
+ port.setLastFailureReason(error.message)
+
+ val switched = when (recoveryType) {
+ PlayerRecoveryType.NETWORK,
+ PlayerRecoveryType.SOURCE,
+ PlayerRecoveryType.BUFFER_TIMEOUT -> port.tryNextCatchUpVariant()
+ else -> false
+ }
+
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return@launch
+ if (switched) {
+ port.appendRecoveryAction("Trying alternate catch-up URL")
+ port.showPlayerNotice(
+ message = "Trying another replay path for ${channel.name}.",
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = port.buildRecoveryActions(PlayerRecoveryType.CATCH_UP),
+ isRetryNotice = true
+ )
+ return@launch
+ }
+
+ port.showPlayerNotice(
+ message = resolveCatchUpFailureMessage(
+ channel = channel,
+ archiveRequested = true,
+ programHasArchive = request.currentProgramHasArchive
+ ),
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = port.buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ return@launch
+ }
+
+ port.markStreamFailure(request.currentStreamUrl)
+ port.setLastFailureReason(error.message)
+ port.logRepositoryFailure(
+ operation = "Increment channel error count",
+ result = port.incrementChannelErrorCount(channel.id)
+ )
+
+ val switched = when (recoveryType) {
+ PlayerRecoveryType.NETWORK,
+ PlayerRecoveryType.SOURCE,
+ PlayerRecoveryType.BUFFER_TIMEOUT -> port.tryAlternateStream(
+ channel = channel,
+ preferXtreamTsFallback = recoveryType == PlayerRecoveryType.SOURCE,
+ allowXtreamTsFallback = !request.livePlaybackReady
+ )
+ else -> false
+ }
+
+ if (!port.isActivePlaybackSession(request.requestVersion, request.playbackUrl)) return@launch
+ if (switched) {
+ port.appendRecoveryAction("Trying alternate stream")
+ port.showPlayerNotice(
+ message = "Trying an alternate stream for ${channel.name}.",
+ recoveryType = recoveryType,
+ actions = port.buildRecoveryActions(recoveryType),
+ isRetryNotice = true
+ )
+ return@launch
+ }
+ logWarning(
+ "recovery-no-switch type=$recoveryType hasLastChannel=${port.hasLastChannel()}"
+ )
+
+ if (port.fallbackToPreviousChannel("Recovery path exhausted for ${recoveryType.name.lowercase()}")) {
+ port.appendRecoveryAction("Returned to last channel")
+ port.showPlayerNotice(
+ message = "Playback failed on this stream. Returned to the last channel.",
+ recoveryType = recoveryType,
+ actions = port.buildRecoveryActions(recoveryType)
+ )
+ } else {
+ port.showPlayerNotice(
+ message = resolvePlaybackErrorMessage(error),
+ recoveryType = recoveryType,
+ actions = port.buildRecoveryActions(recoveryType)
+ )
+ }
+ }
+ return recoveryJob
+ }
+
+ private fun logInfo(message: String) {
+ runCatching { Log.i("PlayerVM", message) }
+ }
+
+ private fun logWarning(message: String) {
+ runCatching { Log.w("PlayerVM", message) }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapter.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapter.kt
new file mode 100644
index 00000000..63eda9f3
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapter.kt
@@ -0,0 +1,99 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.Result
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerError
+
+/**
+ * Bridges recovery execution to the active player runtime without retaining the ViewModel.
+ * Every callback is supplied by the composition root and is scoped to the current runtime.
+ */
+internal class PlayerRecoveryExecutionPortAdapter(
+ override val appPackageName: String,
+ private val engineCoordinator: PlayerEngineCoordinator,
+ override val recoveryState: PlayerRecoveryCoordinator,
+ private val isActivePlaybackSession: (Long, String) -> Boolean,
+ private val tryAlternateStream: (Channel, Boolean, Boolean) -> Boolean,
+ private val tryNextCatchUpVariant: () -> Boolean,
+ private val tryFallbackToAvcMovieVariant: suspend (Long, String) -> Boolean,
+ private val tryRefreshXtreamPlaybackAfterAuthError: suspend (PlayerError, Long, String) -> Boolean,
+ private val recordMovieVariantFailureObservation: (PlayerError) -> Unit,
+ private val updateDecoderModes: (DecoderMode, DecoderMode) -> Unit,
+ private val setLastFailureReason: (String?) -> Unit,
+ private val appendRecoveryAction: (String) -> Unit,
+ private val buildRecoveryActions: (PlayerRecoveryType) -> List<PlayerNoticeAction>,
+ private val showPlayerNotice: (String, PlayerRecoveryType, List<PlayerNoticeAction>, Boolean) -> Unit,
+ private val markStreamFailure: (String) -> Unit,
+ private val incrementChannelErrorCount: suspend (Long) -> Result<Unit>,
+ private val logRepositoryFailure: (String, Result<Unit>) -> Unit,
+ private val fallbackToPreviousChannel: (String) -> Boolean,
+ private val hasLastChannel: () -> Boolean,
+) : PlayerRecoveryExecutionPort {
+ override val playerEngine: PlayerEngine
+ get() = engineCoordinator.currentEngine
+
+ override fun isActivePlaybackSession(requestVersion: Long, playbackUrl: String): Boolean =
+ isActivePlaybackSession.invoke(requestVersion, playbackUrl)
+
+ override fun tryAlternateStream(
+ channel: Channel,
+ preferXtreamTsFallback: Boolean,
+ allowXtreamTsFallback: Boolean,
+ ): Boolean = tryAlternateStream.invoke(channel, preferXtreamTsFallback, allowXtreamTsFallback)
+
+ override fun tryNextCatchUpVariant(): Boolean = tryNextCatchUpVariant.invoke()
+
+ override suspend fun tryFallbackToAvcMovieVariant(requestVersion: Long, playbackUrl: String): Boolean =
+ tryFallbackToAvcMovieVariant.invoke(requestVersion, playbackUrl)
+
+ override suspend fun tryRefreshXtreamPlaybackAfterAuthError(
+ error: PlayerError,
+ requestVersion: Long,
+ playbackUrl: String,
+ ): Boolean = tryRefreshXtreamPlaybackAfterAuthError.invoke(error, requestVersion, playbackUrl)
+
+ override fun recordMovieVariantFailureObservation(error: PlayerError) {
+ recordMovieVariantFailureObservation.invoke(error)
+ }
+
+ override fun updateDecoderModes(audioMode: DecoderMode, videoMode: DecoderMode) {
+ updateDecoderModes.invoke(audioMode, videoMode)
+ }
+
+ override fun setLastFailureReason(message: String?) {
+ setLastFailureReason.invoke(message)
+ }
+
+ override fun appendRecoveryAction(action: String) {
+ appendRecoveryAction.invoke(action)
+ }
+
+ override fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> =
+ buildRecoveryActions.invoke(recoveryType)
+
+ override fun showPlayerNotice(
+ message: String,
+ recoveryType: PlayerRecoveryType,
+ actions: List<PlayerNoticeAction>,
+ isRetryNotice: Boolean,
+ ) {
+ showPlayerNotice.invoke(message, recoveryType, actions, isRetryNotice)
+ }
+
+ override fun markStreamFailure(streamUrl: String) {
+ markStreamFailure.invoke(streamUrl)
+ }
+
+ override suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> =
+ incrementChannelErrorCount.invoke(channelId)
+
+ override fun logRepositoryFailure(operation: String, result: Result<Unit>) {
+ logRepositoryFailure.invoke(operation, result)
+ }
+
+ override fun fallbackToPreviousChannel(reason: String): Boolean = fallbackToPreviousChannel.invoke(reason)
+
+ override fun hasLastChannel(): Boolean = hasLastChannel.invoke()
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicy.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicy.kt
new file mode 100644
index 00000000..e4e99ddf
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicy.kt
@@ -0,0 +1,39 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import java.util.Locale
+
+/** Pure recovery decisions shared by notices, retry handling, and preload protection. */
+internal object PlayerRecoveryPolicy {
+ fun buildActions(
+ hasAlternateStream: Boolean,
+ hasLastChannel: Boolean,
+ shouldOfferGuide: Boolean
+ ): List<PlayerNoticeAction> = buildList {
+ add(PlayerNoticeAction.RETRY)
+ if (hasAlternateStream) add(PlayerNoticeAction.ALTERNATE_STREAM)
+ if (hasLastChannel) add(PlayerNoticeAction.LAST_CHANNEL)
+ if (shouldOfferGuide) add(PlayerNoticeAction.OPEN_GUIDE)
+ }
+
+ fun shouldAttemptProviderAuthRetry(
+ providerType: ProviderType,
+ contentType: ContentType
+ ): Boolean = contentType == ContentType.LIVE &&
+ (providerType == ProviderType.XTREAM_CODES || providerType == ProviderType.STALKER_PORTAL)
+
+ fun shouldCooldownLivePreloadAfterError(message: String?): Boolean {
+ val normalized = message.orEmpty().lowercase(Locale.ROOT)
+ return "401" in normalized ||
+ "403" in normalized ||
+ "429" in normalized ||
+ "509" in normalized ||
+ "forbidden" in normalized ||
+ "unauthorized" in normalized ||
+ "too many" in normalized ||
+ "max connection" in normalized ||
+ "provider limit" in normalized ||
+ "connection limit" in normalized
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt
index 4c07f240..b22e1fdf 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerSleepTimerActions.kt
@@ -80,11 +80,11 @@ internal fun PlayerViewModel.applyDefaultPlaybackTimersIfNeeded() {
sleepTimerExitEmitted = false
viewModelScope.launch {
val stopMinutes = sanitizePlaybackTimerMinutes(
- preferencesRepository.defaultStopPlaybackTimerMinutes.first(),
+ playerPreferencesCoordinator.defaultStopPlaybackTimerMinutes.first(),
PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES
)
val idleMinutes = sanitizePlaybackTimerMinutes(
- preferencesRepository.defaultIdleStandbyTimerMinutes.first(),
+ playerPreferencesCoordinator.defaultIdleStandbyTimerMinutes.first(),
PlayerViewModel.PLAYBACK_TIMER_PRESETS_MINUTES
)
if (!playbackTimerDefaultsApplied || _sleepTimerUiState.value.stopTimerActive || _sleepTimerUiState.value.idleTimerActive) {
@@ -154,4 +154,4 @@ internal fun PlayerViewModel.expirePlaybackTimer() {
idleStandbyTimerEndsAtMs = 0L
_sleepTimerUiState.value = SleepTimerUiState()
_sleepTimerExitEvent.value += 1
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerThumbnailCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerThumbnailCoordinator.kt
new file mode 100644
index 00000000..9a284a55
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerThumbnailCoordinator.kt
@@ -0,0 +1,19 @@
+package com.streamvault.app.ui.screens.player
+
+import android.graphics.Bitmap
+import javax.inject.Inject
+
+/** Feature boundary for seek-frame extraction and its shared cache. */
+class PlayerThumbnailCoordinator @Inject constructor(
+ private val provider: SeekThumbnailProvider
+) {
+ internal fun supportsFrameExtraction(streamUrl: String): Boolean =
+ provider.supportsFrameExtraction(streamUrl)
+
+ internal suspend fun loadFrame(streamUrl: String, positionMs: Long): Bitmap? =
+ provider.loadFrame(streamUrl, positionMs)
+
+ internal fun clearCache() {
+ provider.clearCache()
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinator.kt
new file mode 100644
index 00000000..869f6a9c
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinator.kt
@@ -0,0 +1,61 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.player.timeshift.TimeshiftConfig
+import javax.inject.Inject
+
+/** Owns the decision to attach or detach the local live-rewind source. */
+class PlayerTimeshiftCoordinator @Inject constructor(
+ private val playerEngineCoordinator: PlayerEngineCoordinator
+) {
+ internal data class Request(
+ val contentType: ContentType,
+ val enabled: Boolean,
+ val streamClassLabel: String,
+ val config: TimeshiftConfig,
+ val streamInfoOverride: StreamInfo?,
+ val currentResolvedStreamInfo: StreamInfo?,
+ val currentResolvedPlaybackUrl: String,
+ val currentStreamUrl: String?,
+ val playbackTitle: String,
+ val currentTitle: String,
+ val channelKey: String?
+ )
+
+ internal fun startOrStop(
+ request: Request,
+ onUnavailable: () -> Unit,
+ onPreparing: () -> Unit
+ ) {
+ val engine = playerEngineCoordinator.currentEngine
+ if (request.contentType != ContentType.LIVE || !request.enabled) {
+ engine.stopLiveTimeshift()
+ return
+ }
+ if (!shouldStartLiveTimeshiftForStreamClass(request.streamClassLabel)) {
+ engine.stopLiveTimeshift()
+ return
+ }
+
+ val streamInfo = resolveTimeshiftStreamInfo(
+ streamInfoOverride = request.streamInfoOverride,
+ currentResolvedStreamInfo = request.currentResolvedStreamInfo,
+ currentResolvedPlaybackUrl = request.currentResolvedPlaybackUrl,
+ currentStreamUrl = request.currentStreamUrl,
+ playbackTitle = request.playbackTitle,
+ currentTitle = request.currentTitle
+ ) ?: run {
+ engine.stopLiveTimeshift()
+ onUnavailable()
+ return
+ }
+
+ onPreparing()
+ engine.startLiveTimeshift(
+ streamInfo = streamInfo,
+ channelKey = request.channelKey ?: streamInfo.url,
+ config = request.config
+ )
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTranslationCoordinator.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTranslationCoordinator.kt
new file mode 100644
index 00000000..c988bec6
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerTranslationCoordinator.kt
@@ -0,0 +1,49 @@
+package com.streamvault.app.ui.screens.player
+
+import com.streamvault.app.player.LiveTranslationClient
+import com.streamvault.app.player.LiveTranslationSession
+import com.streamvault.player.PlayerEngine
+import kotlinx.coroutines.CoroutineScope
+import okhttp3.OkHttpClient
+import javax.inject.Inject
+
+/** Owns the cancellable real-time translation session for the active playback. */
+class PlayerTranslationCoordinator @Inject constructor(
+ private val okHttpClient: OkHttpClient
+) {
+ private var session: LiveTranslationSession? = null
+
+ internal val isActive: Boolean
+ get() = session != null
+
+ internal fun start(
+ scope: CoroutineScope,
+ playerEngine: PlayerEngine,
+ endpoint: String,
+ logicalUrl: String,
+ providerId: Long,
+ contentId: Long,
+ onSourceLanguageDetected: (String) -> Unit,
+ onError: (String) -> Unit
+ ) {
+ stop()
+ LiveTranslationSession(
+ scope = scope,
+ playerEngine = playerEngine,
+ client = LiveTranslationClient(okHttpClient, endpoint),
+ logicalUrl = logicalUrl,
+ providerId = providerId,
+ contentId = contentId,
+ onSourceLanguageDetected = onSourceLanguageDetected,
+ onError = onError
+ ).also { nextSession ->
+ session = nextSession
+ nextSession.start()
+ }
+ }
+
+ internal fun stop() {
+ session?.stop()
+ session = null
+ }
+}
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 213537b8..5fcf6e71 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,25 +1,11 @@
package com.streamvault.app.ui.screens.player
-import android.os.Build
import android.os.SystemClock
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.app.cast.CastConnectionState
-import com.streamvault.app.cast.CastManager
-import com.streamvault.app.cast.CastMediaRequestFactory
-import com.streamvault.app.cast.CastPlaybackCoordinator
import com.streamvault.app.cast.CastPlaybackReportMode
-import com.streamvault.app.di.MainPlayerEngine
-import com.streamvault.app.player.LivePreviewHandoffManager
-import com.streamvault.app.player.LiveTranslationSession
-import com.streamvault.app.plugins.StreamVaultPluginManager
import com.streamvault.app.util.isPlaybackComplete
-import com.streamvault.app.tv.LauncherRecommendationsManager
-import com.streamvault.app.tv.WatchNextManager
-import com.streamvault.data.remote.stalker.StalkerUrlFactory
-import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
-import com.streamvault.data.security.CredentialDecryptionException
-import com.streamvault.domain.manager.RecordingManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ChannelNumberingMode
import com.streamvault.domain.model.CombinedCategory
@@ -28,32 +14,17 @@ import com.streamvault.domain.model.Program
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.Episode
-import com.streamvault.domain.model.Favorite
import com.streamvault.domain.model.LiveChannelObservedQuality
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.RecordingItem
import com.streamvault.domain.model.RecordingRecurrence
-import com.streamvault.domain.model.RecordingRequest
import com.streamvault.domain.model.RecordingStatus
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import com.streamvault.domain.model.StreamInfo
-import com.streamvault.domain.model.StreamType
import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.model.VideoFormat
-import com.streamvault.domain.usecase.GetCustomCategories
-import com.streamvault.domain.usecase.MarkAsWatched
-import com.streamvault.domain.usecase.ScheduleRecording
-import com.streamvault.domain.usecase.ScheduleRecordingCommand
-import com.streamvault.domain.repository.ChannelRepository
-import com.streamvault.domain.repository.CombinedM3uRepository
-import com.streamvault.domain.repository.EpgRepository
-import com.streamvault.domain.repository.MovieRepository
-import com.streamvault.domain.repository.PlaybackHistoryRepository
-import com.streamvault.domain.repository.SeriesRepository
-import com.streamvault.domain.repository.DownloadManager
-import com.streamvault.player.Media3PlayerEngine
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MAX_MS
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MIN_MS
import com.streamvault.player.PlaybackState
@@ -64,61 +35,44 @@ import com.streamvault.player.timeshift.LiveTimeshiftBackend
import com.streamvault.player.timeshift.LiveTimeshiftState
import com.streamvault.player.timeshift.LiveTimeshiftStatus
import com.streamvault.player.timeshift.TimeshiftConfig
-import com.streamvault.player.playback.applyUnsafeTlsBypass
-import com.streamvault.player.playback.applyPlaybackTransportPolicy
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-import kotlinx.coroutines.Dispatchers
import android.content.Context
import javax.inject.Inject
-import java.net.InetSocketAddress
-import java.net.Proxy
-import okhttp3.OkHttpClient
-import okhttp3.Request
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class PlayerViewModel @Inject constructor(
@ApplicationContext
internal val appContext: Context,
- @param:MainPlayerEngine
- private val mainPlayerEngine: PlayerEngine,
- internal val epgRepository: EpgRepository,
- internal val channelRepository: ChannelRepository,
- internal val movieRepository: MovieRepository,
- internal val seriesRepository: SeriesRepository,
- internal val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
- internal val playbackHistoryRepository: PlaybackHistoryRepository,
- internal val providerRepository: com.streamvault.domain.repository.ProviderRepository,
- internal val combinedM3uRepository: CombinedM3uRepository,
- internal val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
- internal val getCustomCategories: GetCustomCategories,
- internal val markAsWatched: MarkAsWatched,
- internal val scheduleRecordingUseCase: ScheduleRecording,
- internal val recordingManager: RecordingManager,
- internal val watchNextManager: WatchNextManager,
- internal val launcherRecommendationsManager: LauncherRecommendationsManager,
- internal val castManager: CastManager,
- internal val castMediaRequestFactory: CastMediaRequestFactory,
- internal val castPlaybackCoordinator: CastPlaybackCoordinator,
- internal val pluginManager: StreamVaultPluginManager,
- internal val xtreamStreamUrlResolver: XtreamStreamUrlResolver,
- internal val seekThumbnailProvider: SeekThumbnailProvider,
- internal val livePreviewHandoffManager: LivePreviewHandoffManager,
- private val downloadManager: DownloadManager,
- internal val okHttpClient: OkHttpClient,
+ internal val playerEngineCoordinator: PlayerEngineCoordinator,
+ internal val playerPreparationCoordinator: PlayerPreparationCoordinator,
+ internal val playerTimeshiftCoordinator: PlayerTimeshiftCoordinator,
+ internal val epgCoordinator: PlayerEpgCoordinator,
+ internal val guideTimelineCoordinator: PlayerGuideTimelineCoordinator,
+ internal val playerChannelCoordinator: PlayerChannelCoordinator,
+ internal val playerPlaylistCoordinator: PlayerPlaylistCoordinator,
+ internal val playbackHistoryCoordinator: PlayerHistoryCoordinator,
+ internal val playerProviderCoordinator: PlayerProviderCoordinator,
+ internal val playerPreferencesCoordinator: PlayerPreferencesCoordinator,
+ internal val playerPreviewCoordinator: PlayerPreviewCoordinator,
+ internal val playerThumbnailCoordinator: PlayerThumbnailCoordinator,
+ internal val playerRecordingCoordinator: PlayerRecordingCoordinator,
+ internal val playerCastCoordinator: PlayerCastCoordinator,
+ internal val playerTranslationCoordinator: PlayerTranslationCoordinator,
+ internal val playerContentResolver: PlayerContentResolver,
+ internal val playerPlaybackContextCoordinator: PlayerPlaybackContextCoordinator,
+ internal val playerRecoveryCoordinator: PlayerRecoveryCoordinator,
+ internal val playerRecoveryExecutionCoordinator: PlayerRecoveryExecutionCoordinator,
) : ViewModel() {
companion object {
- private const val MAX_PROGRAM_HISTORY_ITEMS = 18
- private const val MAX_UPCOMING_PROGRAM_ITEMS = 24
- private const val PLAYER_EPG_REFRESH_INTERVAL_MS = 30_000L
private const val MIN_WATCHED_FOR_AUTO_PLAY_MS = 5_000L
private const val AUTO_PLAY_COUNTDOWN_SECONDS = 10
private const val TOKEN_RENEWAL_LEAD_MS = 60_000L
@@ -129,8 +83,8 @@ class PlayerViewModel @Inject constructor(
internal const val TIMER_TICK_MS = 1_000L
}
- private val activePlayerEngineFlow = MutableStateFlow(mainPlayerEngine)
- val activePlayerEngine: StateFlow<PlayerEngine> = activePlayerEngineFlow.asStateFlow()
+ private val activePlayerEngineFlow = playerEngineCoordinator.activeEngine
+ val activePlayerEngine: StateFlow<PlayerEngine> = activePlayerEngineFlow
val playerEngine: PlayerEngine
get() = activePlayerEngineFlow.value
@@ -143,17 +97,10 @@ class PlayerViewModel @Inject constructor(
internal val showZapOverlayFlow = MutableStateFlow(false)
val showZapOverlay: StateFlow<Boolean> = showZapOverlayFlow.asStateFlow()
- private val _currentProgram = MutableStateFlow<Program?>(null)
- val currentProgram: StateFlow<Program?> = _currentProgram.asStateFlow()
-
- private val _nextProgram = MutableStateFlow<Program?>(null)
- val nextProgram: StateFlow<Program?> = _nextProgram.asStateFlow()
-
- private val _programHistory = MutableStateFlow<List<Program>>(emptyList())
- val programHistory: StateFlow<List<Program>> = _programHistory.asStateFlow()
-
- private val _upcomingPrograms = MutableStateFlow<List<Program>>(emptyList())
- val upcomingPrograms: StateFlow<List<Program>> = _upcomingPrograms.asStateFlow()
+ val currentProgram: StateFlow<Program?> = guideTimelineCoordinator.currentProgram
+ val nextProgram: StateFlow<Program?> = guideTimelineCoordinator.nextProgram
+ val programHistory: StateFlow<List<Program>> = guideTimelineCoordinator.programHistory
+ val upcomingPrograms: StateFlow<List<Program>> = guideTimelineCoordinator.upcomingPrograms
internal val currentChannelFlow = MutableStateFlow<com.streamvault.domain.model.Channel?>(null)
val currentChannel: StateFlow<com.streamvault.domain.model.Channel?> = currentChannelFlow.asStateFlow()
@@ -240,7 +187,7 @@ class PlayerViewModel @Inject constructor(
val sleepTimerUiState: StateFlow<SleepTimerUiState> = _sleepTimerUiState.asStateFlow()
internal val _sleepTimerExitEvent = MutableStateFlow(0)
val sleepTimerExitEvent: StateFlow<Int> = _sleepTimerExitEvent.asStateFlow()
- val remoteShortcutPreferences = preferencesRepository.remoteShortcutPreferences
+ val remoteShortcutPreferences = playerPreferencesCoordinator.remoteShortcutPreferences
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), com.streamvault.domain.model.RemoteShortcutPreferences())
private val _playerPreferencesUiState = MutableStateFlow(PlayerPreferencesUiState())
val playerPreferencesUiState: StateFlow<PlayerPreferencesUiState> = _playerPreferencesUiState.asStateFlow()
@@ -259,40 +206,93 @@ class PlayerViewModel @Inject constructor(
internal var numericInputFeedbackJob: Job? = null
internal var playerNoticeHideJob: Job? = null
internal var mutePersistJob: Job? = null
- private var recoveryJob: Job? = null
internal var numericInputBuffer: String = ""
- internal val triedAlternativeStreams = mutableSetOf<String>()
- internal val failedStreamsThisSession = mutableMapOf<String, Int>()
- internal val livePreloadCooldownProviderIds = mutableSetOf<Long>()
- internal var hasRetriedWithSoftwareDecoder = false
- internal var hasRetriedWithAvcMovieVariant = false
- internal var hasRetriedXtreamAuthRefresh = false
internal val probePassedPlaybackKeys = mutableSetOf<String>()
private val notifiedRecordingFailureIds = mutableSetOf<String>()
internal val livePlaybackRecordCoordinator =
- LivePlaybackRecordCoordinator(playbackHistoryRepository::recordPlayback)
+ LivePlaybackRecordCoordinator(playbackHistoryCoordinator::recordPlayback)
private var currentStreamClassLabel: String = "Primary"
internal var lastRecordedVariantObservationSignature: String? = null
internal var lastRecordedVodVariantObservationSignature: String? = null
- internal val playbackSessionCoordinator = PlaybackSessionCoordinator()
+ internal val playbackSessionCoordinator = PlaybackSessionCoordinator(viewModelScope)
+ private val playerRecoveryExecutionPort = PlayerRecoveryExecutionPortAdapter(
+ appPackageName = appContext.packageName,
+ engineCoordinator = playerEngineCoordinator,
+ recoveryState = playerRecoveryCoordinator,
+ isActivePlaybackSession = { requestVersion, playbackUrl ->
+ isActivePlaybackSession(requestVersion, playbackUrl)
+ },
+ tryAlternateStream = { channel, preferXtreamTsFallback, allowXtreamTsFallback ->
+ tryAlternateStreamInternal(
+ channel = channel,
+ preferXtreamTsFallback = preferXtreamTsFallback,
+ allowXtreamTsFallback = allowXtreamTsFallback
+ )
+ },
+ tryNextCatchUpVariant = { tryNextCatchUpVariantInternal() },
+ tryFallbackToAvcMovieVariant = { requestVersion, playbackUrl ->
+ tryFallbackToAvcMovieVariant(requestVersion, playbackUrl)
+ },
+ tryRefreshXtreamPlaybackAfterAuthError = { error, requestVersion, playbackUrl ->
+ tryRefreshXtreamPlaybackAfterAuthError(error, requestVersion, playbackUrl)
+ },
+ recordMovieVariantFailureObservation = { error ->
+ recordMovieVariantFailureObservation(error)
+ },
+ updateDecoderModes = { audioMode, videoMode -> updateDecoderModes(audioMode, videoMode) },
+ setLastFailureReason = { message -> setLastFailureReason(message) },
+ appendRecoveryAction = { action -> appendRecoveryAction(action) },
+ buildRecoveryActions = { recoveryType -> buildRecoveryActions(recoveryType) },
+ showPlayerNotice = { message, recoveryType, actions, isRetryNotice ->
+ showPlayerNotice(
+ message = message,
+ recoveryType = recoveryType,
+ actions = actions,
+ isRetryNotice = isRetryNotice
+ )
+ },
+ markStreamFailure = { streamUrl -> markStreamFailure(streamUrl) },
+ incrementChannelErrorCount = { channelId ->
+ playerChannelCoordinator.incrementChannelErrorCount(channelId)
+ },
+ logRepositoryFailure = { operation, result -> logRepositoryFailure(operation, result) },
+ fallbackToPreviousChannel = { reason -> fallbackToPreviousChannel(reason) },
+ hasLastChannel = { hasLastChannel() }
+ )
internal val prepareRequestVersion: Long
get() = playbackSessionCoordinator.currentId
internal var readySideEffectsRequestVersion: Long? = null
- internal var currentArtworkUrl: String? = null
- internal var currentResolvedPlaybackUrl: String = ""
+ internal var currentArtworkUrl: String?
+ get() = playerPlaybackContextCoordinator.currentArtworkUrl
set(value) {
- field = value
+ playerPlaybackContextCoordinator.currentArtworkUrl = value
+ }
+ internal var currentResolvedPlaybackUrl: String
+ get() = playerPlaybackContextCoordinator.currentResolvedPlaybackUrl
+ set(value) {
+ playerPlaybackContextCoordinator.currentResolvedPlaybackUrl = value
_externalPlaybackUrl.value = value.trim()
}
- internal var currentResolvedStreamInfo: StreamInfo? = null
- internal var pendingCatchUpUrls: List<String> = emptyList()
+ internal var currentResolvedStreamInfo: StreamInfo?
+ get() = playerPlaybackContextCoordinator.currentResolvedStreamInfo
+ set(value) {
+ playerPlaybackContextCoordinator.currentResolvedStreamInfo = value
+ }
+ internal fun clearResolvedStream() {
+ playerPlaybackContextCoordinator.clearResolvedStream()
+ _externalPlaybackUrl.value = ""
+ }
+ internal var pendingCatchUpUrls: List<String>
+ get() = playerPlaybackContextCoordinator.pendingCatchUpUrls
+ set(value) {
+ playerPlaybackContextCoordinator.pendingCatchUpUrls = value
+ }
internal var livePlaybackReadyForCurrentSession: Boolean = false
internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP
set(value) {
field = value
rebuildChannelNumberIndex()
}
- internal var activeEpgRequestKey: EpgRequestKey? = null
internal var playerControlsTimeoutMs: Long = 5_000L
internal var liveOverlayTimeoutMs: Long = 4_000L
internal var playerNoticeTimeoutMs: Long = 6_000L
@@ -331,12 +331,28 @@ class PlayerViewModel @Inject constructor(
internal var currentChannelIndex = -1
internal var previousChannelIndex = -1
internal var currentCategoryId: Long = -1
- internal var currentProviderId: Long = -1L
+ internal var currentProviderId: Long
+ get() = playerPlaybackContextCoordinator.currentProviderId
+ set(value) {
+ playerPlaybackContextCoordinator.currentProviderId = value
+ }
internal var currentCombinedProfileId: Long? = null
internal var currentCombinedSourceFilterProviderId: Long? = null
- internal var currentContentId: Long = -1L
- internal var currentContentType: ContentType = ContentType.LIVE
- internal var currentTitle: String = ""
+ internal var currentContentId: Long
+ get() = playerPlaybackContextCoordinator.currentContentId
+ set(value) {
+ playerPlaybackContextCoordinator.currentContentId = value
+ }
+ internal var currentContentType: ContentType
+ get() = playerPlaybackContextCoordinator.currentContentType
+ set(value) {
+ playerPlaybackContextCoordinator.currentContentType = value
+ }
+ internal var currentTitle: String
+ get() = playerPlaybackContextCoordinator.currentTitle
+ set(value) {
+ playerPlaybackContextCoordinator.currentTitle = value
+ }
internal var currentSeriesId: Long? = null
internal var currentSeasonNumber: Int? = null
internal var currentEpisodeNumber: Int? = null
@@ -346,7 +362,6 @@ class PlayerViewModel @Inject constructor(
internal var combinedCategoriesById: Map<Long, CombinedCategory> = emptyMap()
private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLE
- internal var epgJob: Job? = null
internal var playlistJob: Job? = null
internal var recentChannelsJob: Job? = null
internal var lastVisitedCategoryJob: Job? = null
@@ -383,23 +398,12 @@ class PlayerViewModel @Inject constructor(
val liveTranslationActive: StateFlow<Boolean> = _liveTranslationActive.asStateFlow()
internal val _liveTranslationDetectedLanguage = MutableStateFlow<String?>(null)
val liveTranslationDetectedLanguage: StateFlow<String?> = _liveTranslationDetectedLanguage.asStateFlow()
- internal var liveTranslationSession: LiveTranslationSession? = null
internal var castPlaybackReportMode: CastPlaybackReportMode = CastPlaybackReportMode.NONE
private var downloadPlaybackSlotActive = false
private var currentPlaybackUsesDownloadSlot = false
private var externalProviderPlaybackHold = false
- val castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState
-
- private fun setActivePlayerEngine(engine: PlayerEngine) {
- if (activePlayerEngineFlow.value === engine) return
- // Media3 session IDs must be globally unique. Release the outgoing engine's
- // MediaSession before the incoming engine's session is created by the combine
- // flow at the bottom of init. Mirrors the explicit release done in the forward
- // handoff path (mainPlayerEngine.setMediaSessionEnabled(false)) for the reverse.
- activePlayerEngineFlow.value.setMediaSessionEnabled(false)
- activePlayerEngineFlow.value = engine
- }
+ val castConnectionState: StateFlow<CastConnectionState> = playerCastCoordinator.connectionState
private fun <T> activeEngineState(
initialValue: T,
@@ -444,45 +448,41 @@ class PlayerViewModel @Inject constructor(
}
private fun maybeStartLiveTimeshift(streamInfoOverride: StreamInfo? = null) {
- if (currentContentType != ContentType.LIVE || !timeshiftConfig.enabled) {
- playerEngine.stopLiveTimeshift()
- return
- }
- if (!shouldStartLiveTimeshiftForStreamClass(currentStreamClassLabel)) {
- playerEngine.stopLiveTimeshift()
- return
- }
- val streamInfo = resolveTimeshiftStreamInfo(
- streamInfoOverride = streamInfoOverride,
- currentResolvedStreamInfo = currentResolvedStreamInfo,
- currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
- currentStreamUrl = currentStreamUrl,
- playbackTitle = playbackTitleFlow.value,
- currentTitle = currentTitle
- ) ?: run {
- playerEngine.stopLiveTimeshift()
- _timeshiftUiState.update {
- it.copy(
- available = false,
- enabledForSession = timeshiftConfig.enabled,
- statusMessage = "Local live rewind is unavailable for this stream."
- )
+ playerTimeshiftCoordinator.startOrStop(
+ request = PlayerTimeshiftCoordinator.Request(
+ contentType = currentContentType,
+ enabled = timeshiftConfig.enabled,
+ streamClassLabel = currentStreamClassLabel,
+ config = timeshiftConfig,
+ streamInfoOverride = streamInfoOverride,
+ currentResolvedStreamInfo = currentResolvedStreamInfo,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ currentStreamUrl = currentStreamUrl,
+ playbackTitle = playbackTitleFlow.value,
+ currentTitle = currentTitle,
+ channelKey = currentChannel.value?.id?.toString()
+ ?: currentContentId.takeIf { it > 0L }?.toString()
+ ),
+ onUnavailable = {
+ _timeshiftUiState.update {
+ it.copy(
+ available = false,
+ enabledForSession = timeshiftConfig.enabled,
+ statusMessage = "Local live rewind is unavailable for this stream."
+ )
+ }
+ },
+ onPreparing = {
+ _timeshiftUiState.update {
+ it.copy(
+ available = true,
+ enabledForSession = true,
+ statusMessage = "Preparing local live rewind…",
+ bufferDepthMs = timeshiftConfig.depthMs
+ )
+ }
}
- return
- }
- val fallbackUrl = streamInfo.url
- val channelKey = currentChannel.value?.id?.toString()
- ?: currentContentId.takeIf { it > 0L }?.toString()
- ?: fallbackUrl
- _timeshiftUiState.update {
- it.copy(
- available = true,
- enabledForSession = true,
- statusMessage = "Preparing local live rewind…",
- bufferDepthMs = timeshiftConfig.depthMs
- )
- }
- playerEngine.startLiveTimeshift(streamInfo, channelKey, timeshiftConfig)
+ )
}
init {
@@ -511,7 +511,7 @@ class PlayerViewModel @Inject constructor(
if (channel.errorCount > 0) {
logRepositoryFailure(
operation = "Reset channel error count",
- result = channelRepository.resetChannelErrorCount(channel.id)
+ result = playerChannelCoordinator.resetChannelErrorCount(channel.id)
)
}
}
@@ -537,7 +537,7 @@ class PlayerViewModel @Inject constructor(
}
}
viewModelScope.launch {
- recordingManager.observeRecordingItems().collect { items ->
+ playerRecordingCoordinator.observeRecordingItems().collect { items ->
handleRecordingStateChanges(previousItems = _recordingItems.value, newItems = items)
_recordingItems.value = items
refreshCurrentChannelRecording(items)
@@ -545,9 +545,9 @@ class PlayerViewModel @Inject constructor(
}
viewModelScope.launch {
combine(
- preferencesRepository.playerSubtitleTextScale,
- preferencesRepository.playerSubtitleTextColor,
- preferencesRepository.playerSubtitleBackgroundColor
+ playerPreferencesCoordinator.playerSubtitleTextScale,
+ playerPreferencesCoordinator.playerSubtitleTextColor,
+ playerPreferencesCoordinator.playerSubtitleBackgroundColor
) { textScale, textColor, backgroundColor ->
PlayerSubtitleStyle(
textScale = textScale,
@@ -558,16 +558,16 @@ class PlayerViewModel @Inject constructor(
.collect { (engine, style) -> engine.setSubtitleStyle(style) }
}
viewModelScope.launch {
- preferencesRepository.playerLiveTranslationEnabled.collect {
+ playerPreferencesCoordinator.playerLiveTranslationEnabled.collect {
refreshLiveTranslationAvailability()
}
}
viewModelScope.launch {
combine(
- preferencesRepository.playerControlsTimeoutSeconds,
- preferencesRepository.playerLiveOverlayTimeoutSeconds,
- preferencesRepository.playerNoticeTimeoutSeconds,
- preferencesRepository.playerDiagnosticsTimeoutSeconds
+ playerPreferencesCoordinator.playerControlsTimeoutSeconds,
+ playerPreferencesCoordinator.playerLiveOverlayTimeoutSeconds,
+ playerPreferencesCoordinator.playerNoticeTimeoutSeconds,
+ playerPreferencesCoordinator.playerDiagnosticsTimeoutSeconds
) { controlsSeconds, liveOverlaySeconds, noticeSeconds, diagnosticsSeconds ->
PlayerUiTimeouts(
controlsMs = controlsSeconds * 1000L,
@@ -583,31 +583,31 @@ class PlayerViewModel @Inject constructor(
}
}
viewModelScope.launch {
- preferencesRepository.zapAutoRevert.collect { zapAutoRevertEnabled = it }
+ playerPreferencesCoordinator.zapAutoRevert.collect { zapAutoRevertEnabled = it }
}
viewModelScope.launch {
- preferencesRepository.autoPlayNextEpisode.collect { autoPlayNextEpisodeEnabled = it }
+ playerPreferencesCoordinator.autoPlayNextEpisode.collect { autoPlayNextEpisodeEnabled = it }
}
viewModelScope.launch {
- preferencesRepository.parentalControlLevel.collect { parentalControlLevelFlow.value = it }
+ playerPreferencesCoordinator.parentalControlLevel.collect { parentalControlLevelFlow.value = it }
}
viewModelScope.launch {
- preferencesRepository.defaultStopPlaybackTimerMinutes.collect {
+ playerPreferencesCoordinator.defaultStopPlaybackTimerMinutes.collect {
defaultStopPlaybackTimerMinutes = sanitizePlaybackTimerMinutes(it, PLAYBACK_TIMER_PRESETS_MINUTES)
}
}
viewModelScope.launch {
- preferencesRepository.defaultIdleStandbyTimerMinutes.collect {
+ playerPreferencesCoordinator.defaultIdleStandbyTimerMinutes.collect {
defaultIdleStandbyTimerMinutes = sanitizePlaybackTimerMinutes(it, PLAYBACK_TIMER_PRESETS_MINUTES)
}
}
viewModelScope.launch {
- preferencesRepository.playerMediaSessionEnabled
+ playerPreferencesCoordinator.playerMediaSessionEnabled
.combine(activePlayerEngineFlow) { enabled, engine -> engine to enabled }
.collect { (engine, enabled) -> engine.setMediaSessionEnabled(enabled) }
}
viewModelScope.launch {
- preferencesRepository.playerFastRetryOnTransientFailures
+ playerPreferencesCoordinator.playerFastRetryOnTransientFailures
.combine(activePlayerEngineFlow) { enabled, engine -> engine to enabled }
.collect { (engine, enabled) -> engine.setFastRetryOnTransientFailures(enabled) }
}
@@ -625,12 +625,12 @@ class PlayerViewModel @Inject constructor(
if (channelId == null) {
flowOf(null)
} else {
- preferencesRepository.observeAudioVideoOffsetForChannel(channelId)
+ playerPreferencesCoordinator.observeAudioVideoOffsetForChannel(channelId)
}
}
combine(
- preferencesRepository.playerAudioVideoOffsetMs,
+ playerPreferencesCoordinator.playerAudioVideoOffsetMs,
channelOffsetFlow,
audioVideoOffsetPreviewMs,
activePlayerEngineFlow.flatMapLatest { it.audioVideoSyncEnabled },
@@ -661,9 +661,9 @@ class PlayerViewModel @Inject constructor(
}
viewModelScope.launch {
combine(
- preferencesRepository.playerTimeshiftEnabled,
- preferencesRepository.playerTimeshiftDepthMinutes,
- preferencesRepository.playerTimeshiftBackend
+ playerPreferencesCoordinator.playerTimeshiftEnabled,
+ playerPreferencesCoordinator.playerTimeshiftDepthMinutes,
+ playerPreferencesCoordinator.playerTimeshiftBackend
) { enabled, depthMinutes, backendPreference ->
TimeshiftConfig(
enabled = enabled,
@@ -685,15 +685,15 @@ class PlayerViewModel @Inject constructor(
activePlayerEngineFlow.flatMapLatest { it.timeshiftState }.collect(::applyTimeshiftState)
}
viewModelScope.launch {
- preferencesRepository.playerExternalPlaybackMode.collect { mode ->
+ playerPreferencesCoordinator.playerExternalPlaybackMode.collect { mode ->
_playerPreferencesUiState.value = PlayerPreferencesUiState(
externalPlaybackMode = mode
)
}
}
viewModelScope.launch {
- preferencesRepository.playerAudioDecoderMode
- .combine(preferencesRepository.playerVideoDecoderMode) { audioMode, videoMode ->
+ playerPreferencesCoordinator.playerAudioDecoderMode
+ .combine(playerPreferencesCoordinator.playerVideoDecoderMode) { audioMode, videoMode ->
audioMode to videoMode
}
.combine(activePlayerEngineFlow) { modes, engine -> engine to modes }
@@ -701,7 +701,7 @@ class PlayerViewModel @Inject constructor(
val (audioMode, videoMode) = modes
preferredAudioDecoderMode = audioMode
preferredVideoDecoderMode = videoMode
- if (!hasRetriedWithSoftwareDecoder) {
+ if (!playerRecoveryCoordinator.retriedWithSoftwareDecoder) {
engine.setDecoderModes(audioMode = audioMode, videoMode = videoMode)
if (engine === playerEngine) {
updateDecoderModes(audioMode = audioMode, videoMode = videoMode)
@@ -710,28 +710,28 @@ class PlayerViewModel @Inject constructor(
}
}
viewModelScope.launch {
- preferencesRepository.playerPlaybackBufferMode
+ playerPreferencesCoordinator.playerPlaybackBufferMode
.combine(activePlayerEngineFlow) { mode, engine -> engine to mode }
.collect { (engine, mode) ->
engine.setPlaybackBufferMode(mode)
}
}
viewModelScope.launch {
- preferencesRepository.playerAudioOutputPreference
+ playerPreferencesCoordinator.playerAudioOutputPreference
.combine(activePlayerEngineFlow) { preference, engine -> engine to preference }
.collect { (engine, preference) ->
engine.setAudioOutputPreference(preference)
}
}
viewModelScope.launch {
- preferencesRepository.playerCompatibilityMemoryEnabled
+ playerPreferencesCoordinator.playerCompatibilityMemoryEnabled
.combine(activePlayerEngineFlow) { enabled, engine -> engine to enabled }
.collect { (engine, enabled) ->
engine.setCompatibilityMemoryEnabled(enabled)
}
}
viewModelScope.launch {
- preferencesRepository.playerSurfaceMode
+ playerPreferencesCoordinator.playerSurfaceMode
.combine(activePlayerEngineFlow) { mode, engine -> engine to mode }
.collect { (engine, mode) ->
preferredSurfaceMode = mode
@@ -739,7 +739,7 @@ class PlayerViewModel @Inject constructor(
}
}
viewModelScope.launch {
- preferencesRepository.playerVodHttpProtocolMode
+ playerPreferencesCoordinator.playerVodHttpProtocolMode
.combine(activePlayerEngineFlow) { mode, engine -> engine to mode }
.collect { (engine, mode) ->
engine.setVodHttpProtocolMode(mode)
@@ -793,196 +793,22 @@ class PlayerViewModel @Inject constructor(
currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
currentStreamUrl = currentStreamUrl
)
- android.util.Log.i(
- "PlayerVM",
- "handle-playback-error type=${error::class.java.simpleName} contentType=$currentContentType " +
- "hasChannel=${currentChannelFlow.value != null} requestVersion=$requestVersion " +
- "active=${isActivePlaybackSession(requestVersion, playbackUrl)}"
+ playerRecoveryExecutionCoordinator.handlePlaybackError(
+ request = PlayerRecoveryRequest(
+ error = error,
+ requestVersion = requestVersion,
+ playbackUrl = playbackUrl,
+ contentType = currentContentType,
+ currentStreamUrl = currentStreamUrl,
+ resolvedStreamInfo = currentResolvedStreamInfo,
+ channel = currentChannelFlow.value?.sanitizedForPlayer(),
+ isCatchUp = isCatchUpPlayback(),
+ currentProgramHasArchive = currentProgram.value?.hasArchive == true,
+ livePlaybackReady = livePlaybackReadyForCurrentSession
+ ),
+ sessionScope = playbackSessionScope(requestVersion),
+ port = playerRecoveryExecutionPort
)
- recoveryJob?.cancel()
- if (error is PlayerError.DecoderError && !hasRetriedWithSoftwareDecoder) {
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
- if (currentContentType == ContentType.LIVE) {
- val currentLiveHlsSession = currentResolvedStreamInfo?.streamType == StreamType.HLS
- if (currentLiveHlsSession) {
- val channel = currentChannelFlow.value?.sanitizedForPlayer()
- if (channel != null &&
- tryAlternateStreamInternal(
- channel = channel,
- preferXtreamTsFallback = false,
- allowXtreamTsFallback = false
- )
- ) {
- return
- }
- android.util.Log.w(
- "PlayerVM",
- "Decoder error on live HLS. Keeping hardware path to match Sparkle-like playback on ${appContext.packageName}."
- )
- }
- }
- hasRetriedWithSoftwareDecoder = true
- android.util.Log.w("PlayerVM", "Decoder error detected. Retrying with software decoder mode.")
- playerEngine.setDecoderModes(
- audioMode = DecoderMode.SOFTWARE,
- videoMode = DecoderMode.SOFTWARE
- )
- updateDecoderModes(
- audioMode = DecoderMode.SOFTWARE,
- videoMode = DecoderMode.SOFTWARE
- )
- setLastFailureReason(error.message)
- appendRecoveryAction("Switched to software decoder")
- playerEngine.play()
- showPlayerNotice(
- message = "Retrying with software decoding for this stream.",
- recoveryType = PlayerRecoveryType.DECODER,
- actions = buildRecoveryActions(PlayerRecoveryType.DECODER)
- )
- return
- }
- recordMovieVariantFailureObservation(error)
- // After software decoder retry fails, also try an alternate stream format
- // (e.g. HLS→MPEG-TS or MPEG-TS→HLS) before giving up.
- if (error is PlayerError.DecoderError && hasRetriedWithSoftwareDecoder && currentContentType == ContentType.LIVE) {
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
- val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return
- val switched = tryAlternateStreamInternal(channel)
- if (switched) {
- appendRecoveryAction("Trying alternate stream format after decoder error")
- showPlayerNotice(
- message = "Trying alternate stream format for ${channel.name}.",
- recoveryType = PlayerRecoveryType.DECODER,
- actions = buildRecoveryActions(PlayerRecoveryType.DECODER),
- isRetryNotice = true
- )
- return
- }
- }
- recoveryJob = viewModelScope.launch {
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
- if (error is PlayerError.DecoderError && currentContentType == ContentType.MOVIE && !hasRetriedWithAvcMovieVariant) {
- if (tryFallbackToAvcMovieVariant(requestVersion, playbackUrl)) {
- return@launch
- }
- }
- if (tryRefreshXtreamPlaybackAfterAuthError(error, requestVersion, playbackUrl)) {
- return@launch
- }
-
- val recoveryType = classifyPlaybackError(error)
- val channel = currentChannelFlow.value?.sanitizedForPlayer()
- android.util.Log.i(
- "PlayerVM",
- "recovery-dispatch type=$recoveryType live=${currentContentType == ContentType.LIVE} " +
- "hasChannel=${channel != null}"
- )
-
- if (recoveryType == PlayerRecoveryType.DRM) {
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
- showPlayerNotice(
- message = "This channel requires DRM support that is not available. " +
- "Your subscription may not include this content.",
- recoveryType = PlayerRecoveryType.DRM,
- actions = buildRecoveryActions(PlayerRecoveryType.DRM)
- )
- return@launch
- }
-
- if (currentContentType != ContentType.LIVE || channel == null) {
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
- showPlayerNotice(
- message = resolvePlaybackErrorMessage(error),
- recoveryType = recoveryType,
- actions = buildRecoveryActions(recoveryType)
- )
- return@launch
- }
-
- if (isCatchUpPlayback()) {
- markStreamFailure(currentStreamUrl)
- setLastFailureReason(error.message)
-
- val switched = when (recoveryType) {
- PlayerRecoveryType.NETWORK,
- PlayerRecoveryType.SOURCE,
- PlayerRecoveryType.BUFFER_TIMEOUT -> tryNextCatchUpVariantInternal()
- else -> false
- }
-
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
- if (switched) {
- appendRecoveryAction("Trying alternate catch-up URL")
- showPlayerNotice(
- message = "Trying another replay path for ${channel.name}.",
- recoveryType = PlayerRecoveryType.CATCH_UP,
- actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP),
- isRetryNotice = true
- )
- return@launch
- }
-
- showPlayerNotice(
- message = resolveCatchUpFailureMessage(
- channel = channel,
- archiveRequested = true,
- programHasArchive = _currentProgram.value?.hasArchive == true
- ),
- recoveryType = PlayerRecoveryType.CATCH_UP,
- actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
- )
- return@launch
- }
-
- markStreamFailure(currentStreamUrl)
- setLastFailureReason(error.message)
- logRepositoryFailure(
- operation = "Increment channel error count",
- result = channelRepository.incrementChannelErrorCount(channel.id)
- )
-
- val switched = when (recoveryType) {
- PlayerRecoveryType.NETWORK,
- PlayerRecoveryType.SOURCE,
- PlayerRecoveryType.BUFFER_TIMEOUT -> tryAlternateStreamInternal(
- channel = channel,
- preferXtreamTsFallback = recoveryType == PlayerRecoveryType.SOURCE,
- allowXtreamTsFallback = !livePlaybackReadyForCurrentSession
- )
- else -> false
- }
-
- if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
- if (switched) {
- appendRecoveryAction("Trying alternate stream")
- showPlayerNotice(
- message = "Trying an alternate stream for ${channel.name}.",
- recoveryType = recoveryType,
- actions = buildRecoveryActions(recoveryType),
- isRetryNotice = true
- )
- return@launch
- }
- android.util.Log.w(
- "PlayerVM",
- "recovery-no-switch type=$recoveryType hasLastChannel=${hasLastChannel()}"
- )
-
- if (fallbackToPreviousChannel("Recovery path exhausted for ${recoveryType.name.lowercase()}")) {
- appendRecoveryAction("Returned to last channel")
- showPlayerNotice(
- message = "Playback failed on this stream. Returned to the last channel.",
- recoveryType = recoveryType,
- actions = buildRecoveryActions(recoveryType)
- )
- } else {
- showPlayerNotice(
- message = resolvePlaybackErrorMessage(error),
- recoveryType = recoveryType,
- actions = buildRecoveryActions(recoveryType)
- )
- }
- }
}
internal fun refreshCurrentChannelRecording(items: List<RecordingItem> = _recordingItems.value) {
@@ -1045,23 +871,38 @@ class PlayerViewModel @Inject constructor(
val audioVideoSyncEnabled: StateFlow<Boolean> = activeEngineState(false) { it.audioVideoSyncEnabled }
val preventStandbyDuringPlayback: StateFlow<Boolean> by lazy(LazyThreadSafetyMode.NONE) {
- preferencesRepository.preventStandbyDuringPlayback
+ playerPreferencesCoordinator.preventStandbyDuringPlayback
.stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), true)
}
internal fun beginPlaybackSession(): Long {
- recoveryJob?.cancel()
+ val sessionId = playbackSessionCoordinator.begin().id
+ playerRecoveryCoordinator.beginSession(sessionId)
+ playerRecoveryExecutionCoordinator.cancel()
thumbnailPreloadJob?.cancel()
+ tokenRenewalJob?.cancel()
+ zapBufferWatchdogJob?.cancel()
stopLiveTranslationSession()
- hasRetriedXtreamAuthRefresh = false
lastRecordedVariantObservationSignature = null
lastRecordedVodVariantObservationSignature = null
livePlaybackReadyForCurrentSession = false
readySideEffectsRequestVersion = null
playerEngine.setScrubbingMode(false)
- return playbackSessionCoordinator.begin().id
+ return sessionId
}
+ /**
+ * Launches work owned by a playback session. UI-only jobs should continue to use
+ * [viewModelScope]; preparation, recovery, renewal, and other session work belongs here.
+ */
+ internal fun launchPlaybackSession(
+ requestVersion: Long = prepareRequestVersion,
+ block: suspend () -> Unit
+ ): Job? = playbackSessionCoordinator.launch(requestVersion, block)
+
+ internal fun playbackSessionScope(requestVersion: Long = prepareRequestVersion): CoroutineScope? =
+ playbackSessionCoordinator.scope(requestVersion)
+
internal fun clearSeriesEpisodeContext() {
currentSeriesId = null
currentSeasonNumber = null
@@ -1081,7 +922,7 @@ class PlayerViewModel @Inject constructor(
seasonNumber: Int?,
episodeNumber: Int?
): Episode? {
- return when (val result = seriesRepository.getSeriesDetails(providerId, seriesId)) {
+ return when (val result = playerContentResolver.getSeriesDetails(providerId, seriesId)) {
is Result.Success -> {
if (!isActivePlaybackSession(requestVersion)) return null
val series = result.data.sanitizedForPlayer()
@@ -1162,7 +1003,6 @@ class PlayerViewModel @Inject constructor(
) {
val normalizedChannelId = epgChannelId?.trim()?.takeIf { it.isNotEmpty() }
if (providerId <= 0L || (internalChannelId <= 0L && normalizedChannelId == null && streamId <= 0L)) {
- activeEpgRequestKey = null
fetchEpg(providerId = -1L, internalChannelId = 0L, epgChannelId = null)
return
}
@@ -1173,8 +1013,6 @@ class PlayerViewModel @Inject constructor(
epgChannelId = normalizedChannelId,
streamId = streamId.takeIf { it > 0L } ?: 0L
)
- if (key == activeEpgRequestKey) return
- activeEpgRequestKey = key
fetchEpg(
providerId = key.providerId,
internalChannelId = key.internalChannelId,
@@ -1183,109 +1021,6 @@ class PlayerViewModel @Inject constructor(
)
}
- private suspend fun applyPlaybackPreferences() {
- playerEngine.setMuted(preferencesRepository.playerMuted.first())
- playerEngine.setPlaybackSpeed(
- if (currentContentType == ContentType.LIVE) {
- 1f
- } else {
- preferencesRepository.playerPlaybackSpeed.first()
- }
- )
- playerEngine.setPreferredAudioLanguage(
- resolvePreferredAudioLanguage(
- preferredAudioLanguage = preferencesRepository.preferredAudioLanguage.first(),
- appLanguage = preferencesRepository.appLanguage.first()
- )
- )
- playerEngine.setNetworkQualityPreferences(
- wifiMaxHeight = preferencesRepository.playerWifiMaxVideoHeight.first(),
- ethernetMaxHeight = preferencesRepository.playerEthernetMaxVideoHeight.first()
- )
- playerEngine.setSurfaceMode(preferencesRepository.playerSurfaceMode.first())
- playerEngine.setPlaybackBufferMode(preferencesRepository.playerPlaybackBufferMode.first())
- playerEngine.setVodHttpProtocolMode(preferencesRepository.playerVodHttpProtocolMode.first())
- playerEngine.setFastRetryOnTransientFailures(preferencesRepository.playerFastRetryOnTransientFailures.first())
- playerEngine.setAudioVideoOffsetMs(_audioVideoOffsetUiState.value.effectiveOffsetMs)
- }
-
- private suspend fun tryAdoptPreviewHandoff(
- requestVersion: Long,
- internalChannelId: Long,
- providerId: Long
- ): Boolean {
- if (currentContentType != ContentType.LIVE) return false
-
- val session = livePreviewHandoffManager.consumeFullscreenHandoff(
- channelId = internalChannelId,
- providerId = providerId.takeIf { it > 0L }
- ) ?: return false
-
- if (shouldBypassPreviewHandoffForFireTvLiveHls(session.streamInfo)) {
- android.util.Log.i(
- "PlayerVM",
- "Skipping preview handoff for Fire TV live HLS; fullscreen will prepare a fresh session."
- )
- livePreviewHandoffManager.clear(session.engine)
- session.engine.release()
- return false
- }
-
- val adoptedEngine = session.engine
- return runCatching {
- // Detach the Home preview surface before Player binds its own.
- adoptedEngine.clearRenderBinding()
- // Media3 requires a globally unique session ID. Release the main engine's
- // session before the adopted live engine enables its own replacement.
- mainPlayerEngine.setMediaSessionEnabled(false)
- setActivePlayerEngine(adoptedEngine)
- (adoptedEngine as? Media3PlayerEngine)?.let {
- it.bypassAudioFocus = false
- it.enableMediaSession = preferencesRepository.playerMediaSessionEnabled.first()
- it.constrainResolutionForMultiView = false
- }
- applyPlaybackPreferences()
- if (!isActivePlaybackSession(requestVersion)) {
- setActivePlayerEngine(mainPlayerEngine)
- adoptedEngine.release()
- false
- } else {
- currentResolvedPlaybackUrl = session.streamInfo.url
- currentResolvedStreamInfo = session.streamInfo
- readySideEffectsRequestVersion = requestVersion
- probePassedPlaybackKeys.add(
- resolvePlaybackProbeCacheKey(
- currentStreamUrl = currentStreamUrl,
- url = session.streamInfo.url
- )
- )
- adoptedEngine.resetLiveHandoffGrace()
- // Keep the already-playing preview session intact. Re-preparing on the
- // fullscreen transition can renegotiate the stream and strand HLS live
- // playback in buffering even though preview was already stable.
- playerEngine.play()
- startTokenRenewalMonitoring(session.streamInfo.expirationTime)
- maybeStartLiveTimeshift(session.streamInfo)
- true
- }
- }.getOrElse {
- livePreviewHandoffManager.clear(adoptedEngine)
- if (playerEngine === adoptedEngine) {
- setActivePlayerEngine(mainPlayerEngine)
- }
- adoptedEngine.release()
- false
- }
- }
-
- private fun shouldBypassPreviewHandoffForFireTvLiveHls(streamInfo: StreamInfo): Boolean {
- val isAmazonMediaTek = Build.MANUFACTURER.equals("Amazon", ignoreCase = true) &&
- Build.HARDWARE.orEmpty().startsWith("mt", ignoreCase = true)
- val isHls = streamInfo.streamType == StreamType.HLS ||
- streamInfo.url.substringBefore('?').endsWith(".m3u8", ignoreCase = true)
- return isAmazonMediaTek && isHls
- }
-
internal suspend fun preparePlayer(
streamInfo: com.streamvault.domain.model.StreamInfo,
requestVersion: Long,
@@ -1294,141 +1029,44 @@ class PlayerViewModel @Inject constructor(
): Boolean {
if (!isActivePlaybackSession(requestVersion)) return false
- // Fast-path expiry check: if the stream URL already carries an expiration timestamp
- // that is in the past, skip the network probe entirely and surface a clear message.
- val expiry = streamInfo.expirationTime
- if (expiry != null && expiry > 0L && expiry < System.currentTimeMillis()) {
+ val preparationResult = playerPreparationCoordinator.prepare(
+ request = PlayerPreparationCoordinator.Request(
+ streamInfo = streamInfo,
+ contentType = currentContentType,
+ providerId = currentProviderId,
+ currentStreamUrl = currentStreamUrl,
+ probePassedPlaybackKeys = probePassedPlaybackKeys.toSet(),
+ probeBeforePlayback = probeBeforePlayback,
+ audioVideoOffsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs
+ ),
+ isCurrent = { isActivePlaybackSession(requestVersion) }
+ ) ?: return false
+
+ if (preparationResult is PlayerPreparationCoordinator.Result.Failure) {
if (!isActivePlaybackSession(requestVersion)) return false
- val expiryMessage = "This stream's subscription has expired. " +
- "Please renew your subscription with the provider."
- setLastFailureReason(expiryMessage)
+ setLastFailureReason(preparationResult.message)
if (showFailureNotice) {
showPlayerNotice(
- message = expiryMessage,
- recoveryType = PlayerRecoveryType.SOURCE,
- actions = buildRecoveryActions(PlayerRecoveryType.SOURCE)
+ message = preparationResult.message,
+ recoveryType = preparationResult.recoveryType,
+ actions = buildRecoveryActions(preparationResult.recoveryType)
)
}
return false
}
- var preparedStreamInfo = streamInfo
- when (val pluginPrepareResult = pluginManager.preparePlaybackStreamInfo(streamInfo)) {
- is Result.Error -> {
- if (!isActivePlaybackSession(requestVersion)) return false
- setLastFailureReason(pluginPrepareResult.message)
- if (showFailureNotice) {
- showPlayerNotice(
- message = pluginPrepareResult.message,
- recoveryType = PlayerRecoveryType.NETWORK,
- actions = buildRecoveryActions(PlayerRecoveryType.NETWORK)
- )
- }
- return false
- }
- Result.Loading -> Unit
- is Result.Success -> preparedStreamInfo = pluginPrepareResult.data
- }
-
- if (probeBeforePlayback) {
- probePlaybackUrl(preparedStreamInfo)?.let { failure ->
- if (!isActivePlaybackSession(requestVersion)) return false
- setLastFailureReason(failure.message)
- if (showFailureNotice) {
- showPlayerNotice(
- message = failure.message,
- recoveryType = failure.recoveryType,
- actions = buildRecoveryActions(failure.recoveryType)
- )
- }
- return false
- }
- probePassedPlaybackKeys.add(
- resolvePlaybackProbeCacheKey(
- currentStreamUrl = currentStreamUrl,
- url = streamInfo.url
- )
- )
- }
- applyPlaybackPreferences()
+ val success = preparationResult as PlayerPreparationCoordinator.Result.Success
+ success.probeCacheKey?.let(probePassedPlaybackKeys::add)
if (!isActivePlaybackSession(requestVersion)) return false
- currentResolvedPlaybackUrl = preparedStreamInfo.url
- currentResolvedStreamInfo = preparedStreamInfo
+ currentResolvedPlaybackUrl = success.streamInfo.url
+ currentResolvedStreamInfo = success.streamInfo
readySideEffectsRequestVersion = requestVersion
- playerEngine.prepare(preparedStreamInfo)
refreshLiveTranslationAvailability()
- startTokenRenewalMonitoring(preparedStreamInfo.expirationTime)
- maybeStartLiveTimeshift(preparedStreamInfo)
+ startTokenRenewalMonitoring(success.streamInfo.expirationTime)
+ maybeStartLiveTimeshift(success.streamInfo)
return true
}
- private suspend fun probePlaybackUrl(streamInfo: com.streamvault.domain.model.StreamInfo): PlaybackProbeFailure? {
- val url = streamInfo.url
- if (!shouldProbePlaybackUrl(url)) return null
-
- return runCatching {
- withContext(Dispatchers.IO) {
- val request = Request.Builder()
- .url(url)
- .get()
- .header("Range", "bytes=0-0")
- .apply {
- streamInfo.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }
- streamInfo.headers.forEach { (name, value) ->
- header(name, value)
- }
- }
- .build()
- val probeClient = if (
- streamInfo.playbackTransportPolicy != null ||
- streamInfo.allowInvalidSsl ||
- streamInfo.proxyHost.isNotBlank()
- ) {
- okHttpClient.newBuilder()
- .apply {
- val transportPolicy = streamInfo.playbackTransportPolicy
- if (transportPolicy != null) {
- applyPlaybackTransportPolicy(transportPolicy)
- } else if (streamInfo.allowInvalidSsl) {
- applyUnsafeTlsBypass()
- }
- streamInfo.httpProxy()?.let { proxy(it) }
- }
- .build()
- } else {
- okHttpClient
- }
- probeClient.newCall(request).execute().use { response ->
- resolvePlaybackProbeFailure(response.code)
- }
- }
- }.getOrNull()
- }
-
- private suspend fun shouldProbePlaybackUrl(url: String): Boolean {
- if (!url.startsWith("http://") && !url.startsWith("https://")) return false
- val providerId = currentProviderId.takeIf { it > 0L } ?: return false
- val provider = providerRepository.getProvider(providerId) ?: return false
- val cacheKey = resolvePlaybackProbeCacheKey(
- currentStreamUrl = currentStreamUrl,
- url = url
- )
- if (provider.type != com.streamvault.domain.model.ProviderType.STALKER_PORTAL && cacheKey in probePassedPlaybackKeys) {
- return false
- }
- return (
- provider.type == com.streamvault.domain.model.ProviderType.XTREAM_CODES ||
- provider.type == com.streamvault.domain.model.ProviderType.STALKER_PORTAL
- ) &&
- (xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) || xtreamStreamUrlResolver.isInternalStreamUrl(url))
- }
-
- private fun StreamInfo.httpProxy(): Proxy? {
- val host = proxyHost.trim().takeIf { it.isNotBlank() } ?: return null
- val port = proxyPort ?: return null
- return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
- }
-
fun prepare(
streamUrl: String,
epgChannelId: String?,
@@ -1484,16 +1122,37 @@ class PlayerViewModel @Inject constructor(
)
if (!hasArchiveRequest) {
- viewModelScope.launch {
- if (tryAdoptPreviewHandoff(requestVersion, internalChannelId, providerId)) {
+ playbackSessionScope(requestVersion)?.launch {
+ if (playerPreviewCoordinator.tryAdoptFullscreenHandoff(
+ channelId = internalChannelId,
+ providerId = providerId,
+ contentType = currentContentType,
+ audioVideoOffsetMs = _audioVideoOffsetUiState.value.effectiveOffsetMs,
+ isCurrent = { isActivePlaybackSession(requestVersion) },
+ onAdopted = { streamInfo ->
+ currentResolvedPlaybackUrl = streamInfo.url
+ currentResolvedStreamInfo = streamInfo
+ readySideEffectsRequestVersion = requestVersion
+ probePassedPlaybackKeys.add(
+ resolvePlaybackProbeCacheKey(
+ currentStreamUrl = currentStreamUrl,
+ url = streamInfo.url
+ )
+ )
+ },
+ onStarted = { streamInfo ->
+ startTokenRenewalMonitoring(streamInfo.expirationTime)
+ maybeStartLiveTimeshift(streamInfo)
+ }
+ )) {
return@launch
}
var playbackLogicalUrl = streamUrl
var playbackContentId = internalChannelId
if (currentContentType == ContentType.SERIES_EPISODE && providerId > 0 && currentSeriesId != null) {
- val providerType = providerRepository.getProvider(providerId)?.type
+ val providerType = playerProviderCoordinator.getProvider(providerId)?.type
val shouldAwaitRefreshedEpisode = providerType == ProviderType.STALKER_PORTAL ||
- StalkerUrlFactory.isInternalStreamUrl(streamUrl)
+ playerContentResolver.isInternalStreamUrl(streamUrl)
if (shouldAwaitRefreshedEpisode) {
val resolvedEpisode = loadSeriesEpisodeContext(
requestVersion = requestVersion,
@@ -1523,17 +1182,19 @@ class PlayerViewModel @Inject constructor(
}
}
}
- val streamInfo = resolvePlaybackStreamInfo(
+ val resolution = resolvePlaybackStreamResolution(
playbackLogicalUrl,
playbackContentId,
providerId,
currentContentType
)
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ val streamInfo = resolution.streamInfo
if (streamInfo == null) {
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
+ resolution.failureMessage?.let(::setLastFailureReason)
_playbackResolutionUiState.value = PlaybackResolutionUiState.Failure(
- lastResolutionFailureMessage?.takeIf { it.isNotBlank() }
+ resolution.failureMessage
?: "No playable stream URL was available."
)
return@launch
@@ -1548,7 +1209,7 @@ class PlayerViewModel @Inject constructor(
// Doing this after preparePlayer ensures pause() acts on the live player instance,
// not a stale one that may have already been replaced by prepareInternal().
if (showResumePrompt && currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {
- val history = playbackHistoryRepository.getPlaybackHistory(
+ val history = playbackHistoryCoordinator.getPlaybackHistory(
contentId = currentContentId,
contentType = currentContentType,
providerId = currentProviderId,
@@ -1574,8 +1235,8 @@ class PlayerViewModel @Inject constructor(
openChannelInfoOverlay()
if (providerId > 0) {
- viewModelScope.launch {
- providerRepository.getProvider(providerId)?.let { provider ->
+ playbackSessionScope(requestVersion)?.launch {
+ playerProviderCoordinator.getProvider(providerId)?.let { provider ->
_playerDiagnostics.update {
it.copy(
providerName = provider.name,
@@ -1645,14 +1306,14 @@ class PlayerViewModel @Inject constructor(
}
val requestVersion = prepareRequestVersion
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val identity = resolveSeriesEpisodeIdentity(
providerId = providerId,
internalChannelId = internalChannelId,
seriesId = normalizedSeriesId,
seasonNumber = seasonNumber,
episodeNumber = episodeNumber,
- lookupEpisode = seriesRepository::getEpisodeById
+ lookupEpisode = playerContentResolver::getEpisodeById
) ?: return@launch
if (
identity.seriesId == currentSeriesId &&
@@ -1673,28 +1334,23 @@ class PlayerViewModel @Inject constructor(
}
internal fun applyProgramTimeline(programs: List<Program>, now: Long) {
- val timeline = buildProgramTimeline(
+ guideTimelineCoordinator.apply(
programs = programs,
now = now,
- channel = currentChannelFlow.value,
- maxHistoryItems = MAX_PROGRAM_HISTORY_ITEMS,
- maxUpcomingItems = MAX_UPCOMING_PROGRAM_ITEMS
+ channel = currentChannelFlow.value
)
- _currentProgram.value = timeline.currentProgram
- _nextProgram.value = timeline.nextProgram
- _programHistory.value = timeline.programHistory
- _upcomingPrograms.value = timeline.upcomingPrograms
}
internal fun clearEpgState() {
- _currentProgram.value = null
- _nextProgram.value = null
- _programHistory.value = emptyList()
- _upcomingPrograms.value = emptyList()
+ guideTimelineCoordinator.clear()
}
// Store current URL to find index later
- internal var currentStreamUrl: String = ""
+ internal var currentStreamUrl: String
+ get() = playerPlaybackContextCoordinator.currentStreamUrl
+ set(value) {
+ playerPlaybackContextCoordinator.currentStreamUrl = value
+ }
private fun resolveCurrentLiveChannelIndex(): Int {
currentChannelIndex = resolveLiveChannelIndex(
@@ -1716,8 +1372,7 @@ class PlayerViewModel @Inject constructor(
}
internal fun markStreamFailure(streamUrl: String) {
- if (streamUrl.isBlank()) return
- failedStreamsThisSession[streamUrl] = (failedStreamsThisSession[streamUrl] ?: 0) + 1
+ playerRecoveryCoordinator.markStreamFailure(streamUrl)
}
internal fun updateDecoderModes(audioMode: DecoderMode, videoMode: DecoderMode) {
@@ -1755,32 +1410,37 @@ class PlayerViewModel @Inject constructor(
}
}
- private var lastResolutionFailureMessage: String? = null
-
- internal suspend fun resolvePlaybackStreamInfo(
+ internal suspend fun resolvePlaybackStreamResolution(
logicalUrl: String,
internalContentId: Long,
providerId: Long,
contentType: ContentType
- ): com.streamvault.domain.model.StreamInfo? {
- val resolution = resolvePlayerPlaybackStreamInfo(
+ ): PlayerPlaybackStreamResolution = playerContentResolver.resolvePlaybackStream(
logicalUrl = logicalUrl,
internalContentId = internalContentId,
providerId = providerId,
contentType = contentType,
currentTitle = currentTitle,
currentSeries = currentSeries.value,
- currentEpisode = currentEpisode.value,
- channelRepository = channelRepository,
- movieRepository = movieRepository,
- seriesRepository = seriesRepository,
- xtreamStreamUrlResolver = xtreamStreamUrlResolver
+ currentEpisode = currentEpisode.value
)
- val credentialMessage = resolution.credentialFailureMessage
- lastResolutionFailureMessage = credentialMessage
- ?: resolution.resolutionFailureMessage?.takeIf { it.isNotBlank() }
- if (credentialMessage != null) {
- setLastFailureReason(credentialMessage)
+
+ internal suspend fun resolvePlaybackStreamInfo(
+ logicalUrl: String,
+ internalContentId: Long,
+ providerId: Long,
+ contentType: ContentType
+ ): com.streamvault.domain.model.StreamInfo? {
+ val resolution = resolvePlaybackStreamResolution(
+ logicalUrl = logicalUrl,
+ internalContentId = internalContentId,
+ providerId = providerId,
+ contentType = contentType
+ )
+ resolution.failureMessage?.let { failureMessage ->
+ setLastFailureReason(failureMessage)
+ }
+ if (resolution.streamInfo == null) {
return null
}
return resolution.streamInfo
@@ -1801,6 +1461,6 @@ class PlayerViewModel @Inject constructor(
override fun onCleared() {
playbackSessionCoordinator.invalidate()
super.onCleared()
- cleanupAfterCleared(mainPlayerEngine)
+ cleanupAfterCleared(playerEngineCoordinator.mainEngine)
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
index 139ee04e..c7763563 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
@@ -31,7 +31,7 @@ fun PlayerViewModel.castCurrentMedia(onRouteSelectionRequired: () -> Unit) {
}
}
- when (castPlaybackCoordinator.startCasting(request)) {
+ when (playerCastCoordinator.startCasting(request)) {
CastStartResult.STARTED -> {
castPlaybackReportMode = CastPlaybackReportMode.SUCCESS_AND_FAILURE
showPlayerNotice(
@@ -66,7 +66,7 @@ fun PlayerViewModel.castCurrentMedia(onRouteSelectionRequired: () -> Unit) {
internal fun PlayerViewModel.observeCastPlaybackEvents() {
viewModelScope.launch {
- castPlaybackCoordinator.playbackEvents.collect { event ->
+ playerCastCoordinator.playbackEvents.collect { event ->
handleCastPlaybackEvent(event)
}
}
@@ -95,7 +95,7 @@ private fun PlayerViewModel.handleCastPlaybackEvent(event: CastPlaybackEvent) {
}
fun PlayerViewModel.stopCasting() {
- castManager.stopCasting()
+ playerCastCoordinator.stopCasting()
showPlayerNotice(
message = appContext.getString(R.string.cast_disconnected),
recoveryType = PlayerRecoveryType.NETWORK
@@ -110,7 +110,7 @@ fun PlayerViewModel.startManualRecording() {
}
viewModelScope.launch {
val now = System.currentTimeMillis()
- val result = recordingManager.startManualRecording(
+ val result = playerRecordingCoordinator.startManualRecording(
RecordingRequest(
providerId = currentProviderId,
channelId = channel.id,
@@ -143,7 +143,7 @@ fun PlayerViewModel.scheduleWeeklyRecording() {
private fun PlayerViewModel.scheduleRecordingInternal(recurrence: RecordingRecurrence) {
viewModelScope.launch {
- val result = scheduleRecordingUseCase(
+ val result = playerRecordingCoordinator.scheduleRecording(
ScheduleRecordingCommand(
contentType = currentContentType,
providerId = currentProviderId,
@@ -172,7 +172,7 @@ private fun PlayerViewModel.scheduleRecordingInternal(recurrence: RecordingRecur
fun PlayerViewModel.stopCurrentRecording() {
val recording = currentChannelRecording.value ?: return
viewModelScope.launch {
- val result = recordingManager.stopRecording(recording.id)
+ val result = playerRecordingCoordinator.stopRecording(recording.id)
if (result is Result.Error) {
showPlayerNotice(message = result.message)
} else {
@@ -194,13 +194,13 @@ internal suspend fun PlayerViewModel.buildCastRequestResult(): PlayerCastRequest
)
// Use preferStableUrl = true for Cast: the credential-based portal URL
// does not expire, unlike the tokenized direct-source CDN URL.
- val streamInfo = channelRepository.getStreamInfo(channel, preferStableUrl = true)
+ val streamInfo = playerChannelCoordinator.getStreamInfo(channel, preferStableUrl = true)
.getOrNull()
?: return PlayerCastRequestResult.Failure(
toPlayerCastMessage(CastMediaRequestUnsupportedReason.STREAM_UNAVAILABLE)
)
toPlayerCastRequestResult(
- castMediaRequestFactory.buildFromStreamInfo(
+ playerCastCoordinator.buildFromStreamInfo(
streamInfo = streamInfo,
title = mediaTitle.value ?: channel.name,
subtitle = currentProgram.value?.title,
@@ -213,8 +213,8 @@ internal suspend fun PlayerViewModel.buildCastRequestResult(): PlayerCastRequest
ContentType.MOVIE,
ContentType.VOD -> {
- val movie = movieRepository.getMovie(currentContentId)
- val repositoryStreamInfo = movie?.let { movieRepository.getStreamInfo(it).getOrNull() }
+ val movie = playerContentResolver.getMovie(currentContentId)
+ val repositoryStreamInfo = movie?.let { playerContentResolver.getMovieStreamInfo(it).getOrNull() }
val streamInfo = selectPreferredVodCastStreamInfo(
activeStreamInfo = currentResolvedStreamInfo.takeIf { currentContentType == ContentType.MOVIE },
activePlaybackUrl = currentResolvedPlaybackUrl,
@@ -222,7 +222,7 @@ internal suspend fun PlayerViewModel.buildCastRequestResult(): PlayerCastRequest
)
?: return directCastRequest()
toPlayerCastRequestResult(
- castMediaRequestFactory.buildFromStreamInfo(
+ playerCastCoordinator.buildFromStreamInfo(
streamInfo = streamInfo,
title = currentTitle.ifBlank { movie?.name.orEmpty() },
subtitle = movie?.genre,
@@ -239,18 +239,11 @@ internal suspend fun PlayerViewModel.buildCastRequestResult(): PlayerCastRequest
}
private suspend fun PlayerViewModel.buildSeriesCastRequestResult(): PlayerCastRequestResult {
- val resolution = resolvePlayerPlaybackStreamInfo(
+ val resolution = resolvePlaybackStreamResolution(
logicalUrl = currentStreamUrl,
internalContentId = currentStableEpisodeId?.takeIf { it > 0L } ?: currentContentId,
providerId = currentProviderId,
contentType = currentContentType,
- currentTitle = currentTitle,
- currentSeries = currentSeries.value,
- currentEpisode = currentEpisode.value,
- channelRepository = channelRepository,
- movieRepository = movieRepository,
- seriesRepository = seriesRepository,
- xtreamStreamUrlResolver = xtreamStreamUrlResolver
)
resolution.credentialFailureMessage?.let { message ->
return PlayerCastRequestResult.Failure(message)
@@ -276,7 +269,7 @@ private suspend fun PlayerViewModel.buildSeriesCastRequestResult(): PlayerCastRe
currentTitle.ifBlank { episode?.let(::buildEpisodePlaybackTitle).orEmpty() }
}
return toPlayerCastRequestResult(
- castMediaRequestFactory.buildFromStreamInfo(
+ playerCastCoordinator.buildFromStreamInfo(
streamInfo = streamInfo,
title = castTitle,
subtitle = episode?.title,
@@ -293,7 +286,7 @@ internal fun PlayerViewModel.directCastRequest(): PlayerCastRequestResult {
toPlayerCastMessage(CastMediaRequestUnsupportedReason.EMPTY_URL)
)
return toPlayerCastRequestResult(
- castMediaRequestFactory.buildFromStreamInfo(
+ playerCastCoordinator.buildFromStreamInfo(
streamInfo = StreamInfo(url = url),
title = currentTitle,
subtitle = null,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
index 56c8cc49..0ba5fd8b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
@@ -281,8 +281,7 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =
stopLiveTimeshift = playerEngine::stopLiveTimeshift,
clearPreload = { playerEngine.preload(null) }
)
- currentResolvedPlaybackUrl = ""
- currentResolvedStreamInfo = null
+ clearResolvedStream()
val channel = channelList[index]
currentChannelIndex = index
currentContentId = channel.id
@@ -304,7 +303,7 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =
// like normal playback (matching the smooth pro-mode preview).
playerEngine.setScrubbingMode(false)
- viewModelScope.launch {
+ playbackSessionScope(requestVersion)?.launch {
val streamInfo = resolvePlaybackStreamInfo(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)
?: return@launch
if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch
@@ -332,8 +331,8 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =
showControlsFlow.value = false
openChannelInfoOverlay()
- triedAlternativeStreams.clear()
- triedAlternativeStreams.add(channel.streamUrl)
+ playerRecoveryCoordinator.clearStreamAttempts()
+ playerRecoveryCoordinator.markStreamAttempt(channel.streamUrl)
if (currentContentType == ContentType.LIVE && !isAutoFallback) scheduleZapBufferWatchdog(index)
}
@@ -345,13 +344,13 @@ internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {
playerEngine.preload(null)
return
}
- viewModelScope.launch {
- val provider = providerRepository.getProvider(nextChannel.providerId)
+ playbackSessionScope()?.launch {
+ val provider = playerProviderCoordinator.getProvider(nextChannel.providerId)
if (!shouldPreloadAdjacentChannel(
streamUrl = nextChannel.streamUrl,
providerType = provider?.type,
maxConnections = provider?.maxConnections ?: 1,
- preloadCoolingDown = nextChannel.providerId in livePreloadCooldownProviderIds
+ preloadCoolingDown = playerRecoveryCoordinator.isLivePreloadCoolingDown(nextChannel.providerId)
)
) {
playerEngine.preload(null)
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinatorTest.kt
new file mode 100644
index 00000000..5b3eeb12
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlaybackSessionCoordinatorTest.kt
@@ -0,0 +1,69 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class PlaybackSessionCoordinatorTest {
+
+ @Test
+ fun `begin cancels the previous session scope`() = runTest {
+ val coordinator = PlaybackSessionCoordinator(this)
+ val first = coordinator.begin()
+ val firstJob = coordinator.launch(first.id) {
+ awaitCancellation()
+ }
+
+ val second = coordinator.begin()
+ advanceUntilIdle()
+
+ assertThat(firstJob).isNotNull()
+ assertThat(firstJob?.isCancelled).isTrue()
+ assertThat(coordinator.isCurrent(first.id)).isFalse()
+ assertThat(coordinator.isCurrent(second.id)).isTrue()
+
+ coordinator.invalidate()
+ }
+
+ @Test
+ fun `stale session cannot launch new work`() = runTest {
+ val coordinator = PlaybackSessionCoordinator(this)
+ val first = coordinator.begin()
+ val second = coordinator.begin()
+ var executions = 0
+
+ val staleJob = coordinator.launch(first.id) {
+ executions++
+ }
+ val activeJob = coordinator.launch(second.id) {
+ executions++
+ }
+ advanceUntilIdle()
+
+ assertThat(staleJob).isNull()
+ assertThat(activeJob).isNotNull()
+ assertThat(executions).isEqualTo(1)
+
+ coordinator.invalidate()
+ }
+
+ @Test
+ fun `invalidate cancels active session and clears current identity`() = runTest {
+ val coordinator = PlaybackSessionCoordinator(this)
+ val session = coordinator.begin()
+ val job = coordinator.launch(session.id) {
+ awaitCancellation()
+ }
+
+ coordinator.invalidate()
+ advanceUntilIdle()
+
+ assertThat(job?.isCancelled).isTrue()
+ assertThat(coordinator.currentId).isEqualTo(0L)
+ assertThat(coordinator.isCurrent(session.id)).isFalse()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt
index 95bc19a3..9e8b94b9 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt
@@ -55,6 +55,17 @@ class PlayerContentResolutionSupportTest {
assertThat(shouldStartLiveTimeshiftForStreamClass("Primary")).isTrue()
}
+ @Test
+ fun `playback stream resolution keeps its failure message with the result`() {
+ val resolution = PlayerPlaybackStreamResolution(
+ streamInfo = null,
+ resolutionFailureMessage = "The provider returned no playable stream."
+ )
+
+ assertThat(resolution.failureMessage)
+ .isEqualTo("The provider returned no playable stream.")
+ }
+
@Test
fun `resolvePlayerPlaybackStreamInfo uses current episode playback identity`() = runBlocking {
val episode = episode(id = 21L, stableEpisodeId = 321L)
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinatorTest.kt
new file mode 100644
index 00000000..1ccc5eea
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEngineCoordinatorTest.kt
@@ -0,0 +1,33 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.player.PlayerEngine
+import org.junit.Test
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
+
+class PlayerEngineCoordinatorTest {
+
+ @Test
+ fun `switching engines disables the outgoing media session`() {
+ val mainEngine = mock<PlayerEngine>()
+ val nextEngine = mock<PlayerEngine>()
+ val coordinator = PlayerEngineCoordinator(mainEngine)
+
+ coordinator.switchTo(nextEngine)
+
+ assertThat(coordinator.currentEngine).isSameInstanceAs(nextEngine)
+ verify(mainEngine).setMediaSessionEnabled(false)
+ }
+
+ @Test
+ fun `switching to the current engine is a no-op`() {
+ val mainEngine = mock<PlayerEngine>()
+ val coordinator = PlayerEngineCoordinator(mainEngine)
+
+ coordinator.switchTo(mainEngine)
+
+ assertThat(coordinator.currentEngine).isSameInstanceAs(mainEngine)
+ verify(mainEngine, org.mockito.kotlin.never()).setMediaSessionEnabled(false)
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinatorTest.kt
new file mode 100644
index 00000000..7b6b22f5
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerEpgCoordinatorTest.kt
@@ -0,0 +1,215 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.ProviderRepository
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.kotlin.eq
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class PlayerEpgCoordinatorTest {
+
+ @Test
+ fun `request publishes local programs and cancellation stops refresh`() = runTest {
+ val epgRepository = mock<EpgRepository>()
+ val providerRepository = mock<ProviderRepository>()
+ val program = Program(channelId = "epg-1", title = "Now", startTime = 1L, endTime = 2L)
+ whenever(
+ epgRepository.getResolvedProgramsForPlaybackChannel(
+ providerId = eq(7L),
+ internalChannelId = eq(42L),
+ epgChannelId = eq("epg-1"),
+ streamId = eq(99L),
+ startTime = org.mockito.kotlin.any(),
+ endTime = org.mockito.kotlin.any()
+ )
+ ).thenReturn(listOf(program))
+ val coordinator = PlayerEpgCoordinator(epgRepository, providerRepository)
+ val received = mutableListOf<List<Program>>()
+
+ coordinator.request(
+ scope = this,
+ sessionId = 1L,
+ requestKey = EpgRequestKey(7L, 42L, "epg-1", 99L),
+ onPrograms = { programs, _ -> received += programs },
+ onClear = {}
+ )
+ runCurrent()
+ coordinator.cancel()
+
+ assertThat(received).containsExactly(listOf(program))
+ }
+
+ @Test
+ fun `empty local guide falls back to provider-native programs`() = runTest {
+ val epgRepository = mock<EpgRepository>()
+ val providerRepository = mock<ProviderRepository>()
+ val program = Program(channelId = "epg-1", title = "Remote", startTime = 3L, endTime = 4L)
+ whenever(
+ epgRepository.getResolvedProgramsForPlaybackChannel(
+ providerId = eq(7L),
+ internalChannelId = eq(42L),
+ epgChannelId = eq("epg-1"),
+ streamId = eq(99L),
+ startTime = org.mockito.kotlin.any(),
+ endTime = org.mockito.kotlin.any()
+ )
+ ).thenReturn(emptyList())
+ whenever(
+ providerRepository.getProgramsForLiveStream(
+ providerId = 7L,
+ streamId = 99L,
+ epgChannelId = "epg-1",
+ limit = 12
+ )
+ ).thenReturn(Result.Success(listOf(program)))
+ val coordinator = PlayerEpgCoordinator(epgRepository, providerRepository)
+ val received = mutableListOf<List<Program>>()
+
+ coordinator.request(
+ scope = this,
+ sessionId = 1L,
+ requestKey = EpgRequestKey(7L, 42L, "epg-1", 99L),
+ onPrograms = { programs, _ -> received += programs },
+ onClear = {}
+ )
+ runCurrent()
+ coordinator.cancel()
+
+ assertThat(received).containsExactly(listOf(program))
+ }
+
+ @Test
+ fun `same request key from a newer session rejects stale results`() = runTest {
+ val firstRequestStarted = CompletableDeferred<Unit>()
+ val releaseFirstRequest = CompletableDeferred<Unit>()
+ val providerRepository = mock<ProviderRepository>()
+ val staleProgram = Program(channelId = "epg-1", title = "Stale", startTime = 1L, endTime = 2L)
+ val currentProgram = Program(channelId = "epg-1", title = "Current", startTime = 3L, endTime = 4L)
+ val epgRepository = object : EpgRepository {
+ private var requestCount = 0
+
+ override suspend fun getResolvedProgramsForPlaybackChannel(
+ providerId: Long,
+ internalChannelId: Long,
+ epgChannelId: String?,
+ streamId: Long,
+ startTime: Long,
+ endTime: Long
+ ): List<Program> {
+ return if (requestCount++ == 0) {
+ firstRequestStarted.complete(Unit)
+ withContext(NonCancellable) { releaseFirstRequest.await() }
+ listOf(staleProgram)
+ } else {
+ listOf(currentProgram)
+ }
+ }
+
+ override fun getProgramsForChannel(
+ providerId: Long,
+ channelId: String,
+ startTime: Long,
+ endTime: Long
+ ): Flow<List<Program>> = emptyFlow()
+
+ override fun getProgramsForChannels(
+ providerId: Long,
+ channelIds: List<String>,
+ startTime: Long,
+ endTime: Long
+ ): Flow<Map<String, List<Program>>> = emptyFlow()
+
+ override suspend fun getProgramsForChannelsSnapshot(
+ providerId: Long,
+ channelIds: List<String>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>> = emptyMap()
+
+ override fun getProgramsByCategory(
+ providerId: Long,
+ categoryId: Long,
+ startTime: Long,
+ endTime: Long
+ ): Flow<List<Program>> = emptyFlow()
+
+ override fun searchPrograms(
+ providerId: Long,
+ query: String,
+ startTime: Long,
+ endTime: Long,
+ categoryId: Long?,
+ limit: Int
+ ): Flow<List<Program>> = emptyFlow()
+
+ override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> = flowOf(null)
+
+ override fun getNowPlayingForChannels(
+ providerId: Long,
+ channelIds: List<String>
+ ): Flow<Map<String, Program?>> = flowOf(emptyMap())
+
+ override suspend fun getNowPlayingForChannelsSnapshot(
+ providerId: Long,
+ channelIds: List<String>
+ ): Map<String, Program?> = emptyMap()
+
+ override fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>> =
+ flowOf(null to null)
+
+ override suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit> = Result.Success(Unit)
+
+ override suspend fun clearOldPrograms(beforeTime: Long) = Unit
+
+ override fun onProviderDeleted(providerId: Long) = Unit
+
+ override suspend fun getResolvedProgramsForChannels(
+ providerId: Long,
+ channelIds: List<Long>,
+ startTime: Long,
+ endTime: Long
+ ): Map<String, List<Program>> = emptyMap()
+ }
+ val coordinator = PlayerEpgCoordinator(epgRepository, providerRepository)
+ val received = mutableListOf<List<Program>>()
+ val requestKey = EpgRequestKey(7L, 42L, "epg-1", 99L)
+
+ coordinator.request(
+ scope = this,
+ sessionId = 1L,
+ requestKey = requestKey,
+ onPrograms = { programs, _ -> received += programs },
+ onClear = {}
+ )
+ runCurrent()
+ firstRequestStarted.await()
+
+ coordinator.request(
+ scope = this,
+ sessionId = 2L,
+ requestKey = requestKey,
+ onPrograms = { programs, _ -> received += programs },
+ onClear = {}
+ )
+ runCurrent()
+ releaseFirstRequest.complete(Unit)
+ runCurrent()
+ coordinator.cancel()
+
+ assertThat(received).containsExactly(listOf(currentProgram))
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinatorTest.kt
new file mode 100644
index 00000000..6c1c99fe
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerGuideTimelineCoordinatorTest.kt
@@ -0,0 +1,43 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Program
+import org.junit.Test
+
+class PlayerGuideTimelineCoordinatorTest {
+
+ @Test
+ fun `apply publishes current next history and upcoming slices`() {
+ val coordinator = PlayerGuideTimelineCoordinator()
+ val programs = listOf(
+ Program(channelId = "channel", title = "Past", startTime = 0L, endTime = 10L),
+ Program(channelId = "channel", title = "Now", startTime = 10L, endTime = 30L),
+ Program(channelId = "channel", title = "Next", startTime = 30L, endTime = 50L)
+ )
+
+ coordinator.apply(programs, now = 20L, channel = null)
+
+ assertThat(coordinator.currentProgram.value?.title).isEqualTo("Now")
+ assertThat(coordinator.nextProgram.value?.title).isEqualTo("Next")
+ assertThat(coordinator.programHistory.value).isEmpty()
+ assertThat(coordinator.upcomingPrograms.value.map { it.title })
+ .containsExactly("Now", "Next")
+ .inOrder()
+ }
+
+ @Test
+ fun `clear removes the previous timeline`() {
+ val coordinator = PlayerGuideTimelineCoordinator()
+ coordinator.apply(
+ programs = listOf(Program(channelId = "channel", title = "Now", startTime = 0L, endTime = 10L)),
+ now = 1L,
+ channel = null
+ )
+
+ coordinator.clear()
+
+ assertThat(coordinator.currentProgram.value).isNull()
+ assertThat(coordinator.programHistory.value).isEmpty()
+ assertThat(coordinator.upcomingPrograms.value).isEmpty()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinatorTest.kt
new file mode 100644
index 00000000..2ea39a2c
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerPlaybackContextCoordinatorTest.kt
@@ -0,0 +1,30 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StreamInfo
+import org.junit.Test
+
+class PlayerPlaybackContextCoordinatorTest {
+
+ @Test
+ fun `resolved stream can be cleared without losing logical playback identity`() {
+ val coordinator = PlayerPlaybackContextCoordinator()
+ coordinator.currentContentId = 42L
+ coordinator.currentContentType = ContentType.LIVE
+ coordinator.currentStreamUrl = "https://example.test/logical"
+ coordinator.currentResolvedPlaybackUrl = "https://example.test/resolved"
+ coordinator.currentResolvedStreamInfo = StreamInfo(
+ url = coordinator.currentResolvedPlaybackUrl,
+ title = "Example"
+ )
+
+ coordinator.clearResolvedStream()
+
+ assertThat(coordinator.currentContentId).isEqualTo(42L)
+ assertThat(coordinator.currentContentType).isEqualTo(ContentType.LIVE)
+ assertThat(coordinator.currentStreamUrl).isEqualTo("https://example.test/logical")
+ assertThat(coordinator.currentResolvedPlaybackUrl).isEmpty()
+ assertThat(coordinator.currentResolvedStreamInfo).isNull()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinatorTest.kt
new file mode 100644
index 00000000..dfae6712
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerProviderCoordinatorTest.kt
@@ -0,0 +1,37 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.security.CredentialDecryptionException
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.ProviderRepository
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+
+class PlayerProviderCoordinatorTest {
+
+ @Test
+ fun `catch-up credential failures become domain errors`() = runTest {
+ val repository = mock<ProviderRepository>()
+ whenever(repository.buildCatchUpUrls(any(), any(), any(), any()))
+ .thenThrow(CredentialDecryptionException("credentials unavailable"))
+
+ val result = PlayerProviderCoordinator(repository).buildCatchUpUrls(1L, 2L, 3L, 4L)
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).message).isEqualTo("credentials unavailable")
+ }
+
+ @Test
+ fun `catch-up urls remain domain successes`() = runTest {
+ val repository = mock<ProviderRepository>()
+ whenever(repository.buildCatchUpUrls(any(), any(), any(), any()))
+ .thenReturn(listOf("https://example.test/catchup"))
+
+ val result = PlayerProviderCoordinator(repository).buildCatchUpUrls(1L, 2L, 3L, 4L)
+
+ assertThat(result).isEqualTo(Result.Success(listOf("https://example.test/catchup")))
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinatorTest.kt
new file mode 100644
index 00000000..26ace2e9
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryCoordinatorTest.kt
@@ -0,0 +1,140 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.LiveChannelVariant
+import org.junit.Test
+
+class PlayerRecoveryCoordinatorTest {
+
+ @Test
+ fun `new playback session resets retry guards but retains provider cooldown`() {
+ val coordinator = PlayerRecoveryCoordinator()
+
+ coordinator.beginSession(1L)
+ coordinator.retriedWithSoftwareDecoder = true
+ coordinator.retriedWithAvcMovieVariant = true
+ coordinator.markXtreamAuthRefreshRetried()
+ assertThat(coordinator.markLivePreloadCoolingDown(42L)).isTrue()
+
+ coordinator.beginSession(2L)
+
+ assertThat(coordinator.retriedWithSoftwareDecoder).isFalse()
+ assertThat(coordinator.retriedWithAvcMovieVariant).isFalse()
+ assertThat(coordinator.canRetryXtreamAuthRefresh()).isTrue()
+ assertThat(coordinator.isLivePreloadCoolingDown(42L)).isTrue()
+ }
+
+ @Test
+ fun `new playback session retains stream attempt history`() {
+ val coordinator = PlayerRecoveryCoordinator()
+
+ coordinator.beginSession(1L)
+ coordinator.markStreamAttempt("https://example.test/primary")
+ coordinator.markStreamFailure("https://example.test/primary")
+
+ coordinator.beginSession(2L)
+
+ assertThat(coordinator.streamAttemptSnapshot())
+ .containsExactly("https://example.test/primary")
+ assertThat(coordinator.failedStreamSnapshot())
+ .containsExactly("https://example.test/primary", 1)
+ }
+
+ @Test
+ fun `multi-step live recovery does not revisit earlier variants`() {
+ val primaryUrl = "https://example.test/primary.m3u8"
+ val firstAlternateUrl = "https://example.test/alternate-a.m3u8"
+ val secondAlternateUrl = "https://example.test/alternate-b.m3u8"
+ val channel = Channel(
+ id = 1L,
+ name = "Live",
+ streamUrl = primaryUrl,
+ selectedVariantId = 1L,
+ variants = listOf(
+ LiveChannelVariant(
+ rawChannelId = 2L,
+ logicalGroupId = "live",
+ providerId = 1L,
+ originalName = "Alternate A",
+ canonicalName = "Live",
+ streamUrl = firstAlternateUrl
+ ),
+ LiveChannelVariant(
+ rawChannelId = 3L,
+ logicalGroupId = "live",
+ providerId = 1L,
+ originalName = "Alternate B",
+ canonicalName = "Live",
+ streamUrl = secondAlternateUrl
+ )
+ )
+ )
+ val coordinator = PlayerRecoveryCoordinator()
+
+ coordinator.beginSession(1L)
+ coordinator.markStreamAttempt(primaryUrl)
+ val firstCandidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 1L,
+ currentStreamUrl = primaryUrl,
+ currentResolvedPlaybackUrl = primaryUrl,
+ triedAlternativeStreams = coordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = coordinator.failedStreamSnapshot(),
+ preferXtreamTsFallback = false,
+ allowXtreamTsFallback = false
+ )
+ assertThat(firstCandidate?.url).isEqualTo(firstAlternateUrl)
+
+ coordinator.markStreamAttempt(firstAlternateUrl)
+ coordinator.beginSession(2L)
+ val secondCandidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 2L,
+ currentStreamUrl = firstAlternateUrl,
+ currentResolvedPlaybackUrl = firstAlternateUrl,
+ triedAlternativeStreams = coordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = coordinator.failedStreamSnapshot(),
+ preferXtreamTsFallback = false,
+ allowXtreamTsFallback = false
+ )
+ assertThat(secondCandidate?.url).isEqualTo(secondAlternateUrl)
+
+ coordinator.markStreamAttempt(secondAlternateUrl)
+ coordinator.beginSession(3L)
+ val nextCandidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 3L,
+ currentStreamUrl = secondAlternateUrl,
+ currentResolvedPlaybackUrl = secondAlternateUrl,
+ triedAlternativeStreams = coordinator.streamAttemptSnapshot(),
+ failedStreamsThisSession = coordinator.failedStreamSnapshot(),
+ preferXtreamTsFallback = false,
+ allowXtreamTsFallback = false
+ )
+
+ assertThat(nextCandidate).isNull()
+ }
+
+ @Test
+ fun `explicit root playback reset clears stream attempt history`() {
+ val coordinator = PlayerRecoveryCoordinator()
+
+ coordinator.beginSession(1L)
+ coordinator.markStreamAttempt("https://example.test/old.m3u8")
+ coordinator.markStreamFailure("https://example.test/old.m3u8")
+
+ coordinator.clearStreamAttempts()
+
+ assertThat(coordinator.streamAttemptSnapshot()).isEmpty()
+ assertThat(coordinator.failedStreamSnapshot()).isEmpty()
+ }
+
+ @Test
+ fun `preload cooldown is idempotent`() {
+ val coordinator = PlayerRecoveryCoordinator()
+
+ assertThat(coordinator.markLivePreloadCoolingDown(7L)).isTrue()
+ assertThat(coordinator.markLivePreloadCoolingDown(7L)).isFalse()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinatorTest.kt
new file mode 100644
index 00000000..7a38b491
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionCoordinatorTest.kt
@@ -0,0 +1,123 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.Result
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerError
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
+
+class PlayerRecoveryExecutionCoordinatorTest {
+
+ @Test
+ fun `stale playback errors are ignored`() = runTest {
+ val port = RecordingRecoveryPort().apply { active = false }
+ val coordinator = PlayerRecoveryExecutionCoordinator()
+
+ val job = coordinator.handlePlaybackError(
+ request = request(PlayerError.SourceError("source failed")),
+ sessionScope = this,
+ port = port
+ )
+
+ assertThat(job).isNull()
+ assertThat(port.notices).isEmpty()
+ }
+
+ @Test
+ fun `first decoder failure switches to software and publishes retry notice`() = runTest {
+ val port = RecordingRecoveryPort()
+ val coordinator = PlayerRecoveryExecutionCoordinator()
+
+ coordinator.handlePlaybackError(
+ request = request(PlayerError.DecoderError("decoder failed")),
+ sessionScope = this,
+ port = port
+ )
+ advanceUntilIdle()
+
+ assertThat(port.recoveryState.retriedWithSoftwareDecoder).isTrue()
+ assertThat(port.notices.single().recoveryType).isEqualTo(PlayerRecoveryType.DECODER)
+ assertThat(port.notices.single().message).contains("software")
+ verify(port.playerEngine).setDecoderModes(DecoderMode.SOFTWARE, DecoderMode.SOFTWARE)
+ verify(port.playerEngine).play()
+ }
+
+ private fun request(error: PlayerError) = PlayerRecoveryRequest(
+ error = error,
+ requestVersion = 1L,
+ playbackUrl = "https://example.test/live.m3u8",
+ contentType = ContentType.MOVIE,
+ currentStreamUrl = "https://example.test/live.m3u8",
+ resolvedStreamInfo = null,
+ channel = null,
+ isCatchUp = false,
+ currentProgramHasArchive = false,
+ livePlaybackReady = false
+ )
+
+ private class RecordingRecoveryPort : PlayerRecoveryExecutionPort {
+ override val appPackageName: String = "com.streamvault.test"
+ override val playerEngine: PlayerEngine = mock()
+ override val recoveryState = PlayerRecoveryCoordinator()
+ var active = true
+ val notices = mutableListOf<Notice>()
+
+ override fun isActivePlaybackSession(requestVersion: Long, playbackUrl: String): Boolean = active
+
+ override fun tryAlternateStream(
+ channel: com.streamvault.domain.model.Channel,
+ preferXtreamTsFallback: Boolean,
+ allowXtreamTsFallback: Boolean
+ ): Boolean = false
+
+ override fun tryNextCatchUpVariant(): Boolean = false
+
+ override suspend fun tryFallbackToAvcMovieVariant(requestVersion: Long, playbackUrl: String): Boolean = false
+
+ override suspend fun tryRefreshXtreamPlaybackAfterAuthError(
+ error: PlayerError,
+ requestVersion: Long,
+ playbackUrl: String
+ ): Boolean = false
+
+ override fun recordMovieVariantFailureObservation(error: PlayerError) = Unit
+
+ override fun updateDecoderModes(audioMode: DecoderMode, videoMode: DecoderMode) = Unit
+
+ override fun setLastFailureReason(message: String?) = Unit
+
+ override fun appendRecoveryAction(action: String) = Unit
+
+ override fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> = emptyList()
+
+ override fun showPlayerNotice(
+ message: String,
+ recoveryType: PlayerRecoveryType,
+ actions: List<PlayerNoticeAction>,
+ isRetryNotice: Boolean
+ ) {
+ notices += Notice(message, recoveryType)
+ }
+
+ override fun markStreamFailure(streamUrl: String) = Unit
+
+ override suspend fun incrementChannelErrorCount(channelId: Long): Result<Unit> = Result.Success(Unit)
+
+ override fun logRepositoryFailure(operation: String, result: Result<Unit>) = Unit
+
+ override fun fallbackToPreviousChannel(reason: String): Boolean = false
+
+ override fun hasLastChannel(): Boolean = false
+ }
+
+ private data class Notice(
+ val message: String,
+ val recoveryType: PlayerRecoveryType
+ )
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapterTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapterTest.kt
new file mode 100644
index 00000000..b8db7277
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryExecutionPortAdapterTest.kt
@@ -0,0 +1,50 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.DecoderMode
+import com.streamvault.domain.model.Result
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerError
+import org.junit.Test
+import org.mockito.kotlin.mock
+
+class PlayerRecoveryExecutionPortAdapterTest {
+
+ @Test
+ fun `player engine resolves from the current engine coordinator`() {
+ val mainEngine = mock<PlayerEngine>()
+ val adoptedEngine = mock<PlayerEngine>()
+ val engineCoordinator = PlayerEngineCoordinator(mainEngine)
+ val adapter = adapter(engineCoordinator)
+
+ assertThat(adapter.playerEngine).isSameInstanceAs(mainEngine)
+
+ engineCoordinator.switchTo(adoptedEngine)
+
+ assertThat(adapter.playerEngine).isSameInstanceAs(adoptedEngine)
+ }
+
+ private fun adapter(
+ engineCoordinator: PlayerEngineCoordinator
+ ): PlayerRecoveryExecutionPortAdapter = PlayerRecoveryExecutionPortAdapter(
+ appPackageName = "com.streamvault.test",
+ engineCoordinator = engineCoordinator,
+ recoveryState = PlayerRecoveryCoordinator(),
+ isActivePlaybackSession = { _, _ -> true },
+ tryAlternateStream = { _, _, _ -> false },
+ tryNextCatchUpVariant = { false },
+ tryFallbackToAvcMovieVariant = { _, _ -> false },
+ tryRefreshXtreamPlaybackAfterAuthError = { _, _, _ -> false },
+ recordMovieVariantFailureObservation = { _: PlayerError -> },
+ updateDecoderModes = { _: DecoderMode, _: DecoderMode -> },
+ setLastFailureReason = { _: String? -> },
+ appendRecoveryAction = { _: String -> },
+ buildRecoveryActions = { _: PlayerRecoveryType -> emptyList() },
+ showPlayerNotice = { _: String, _: PlayerRecoveryType, _: List<PlayerNoticeAction>, _: Boolean -> },
+ markStreamFailure = { _: String -> },
+ incrementChannelErrorCount = { _: Long -> Result.Success(Unit) },
+ logRepositoryFailure = { _: String, _: Result<Unit> -> },
+ fallbackToPreviousChannel = { _: String -> false },
+ hasLastChannel = { false }
+ )
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicyTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicyTest.kt
new file mode 100644
index 00000000..e778ca4c
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerRecoveryPolicyTest.kt
@@ -0,0 +1,55 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderType
+import org.junit.Test
+
+class PlayerRecoveryPolicyTest {
+
+ @Test
+ fun `recovery actions preserve retry alternate previous and guide order`() {
+ assertThat(
+ PlayerRecoveryPolicy.buildActions(
+ hasAlternateStream = true,
+ hasLastChannel = true,
+ shouldOfferGuide = true
+ )
+ ).containsExactly(
+ PlayerNoticeAction.RETRY,
+ PlayerNoticeAction.ALTERNATE_STREAM,
+ PlayerNoticeAction.LAST_CHANNEL,
+ PlayerNoticeAction.OPEN_GUIDE
+ ).inOrder()
+ }
+
+ @Test
+ fun `provider auth retry only applies to live Xtream and Stalker sessions`() {
+ assertThat(
+ PlayerRecoveryPolicy.shouldAttemptProviderAuthRetry(
+ ProviderType.XTREAM_CODES,
+ ContentType.LIVE
+ )
+ ).isTrue()
+ assertThat(
+ PlayerRecoveryPolicy.shouldAttemptProviderAuthRetry(
+ ProviderType.M3U,
+ ContentType.LIVE
+ )
+ ).isFalse()
+ assertThat(
+ PlayerRecoveryPolicy.shouldAttemptProviderAuthRetry(
+ ProviderType.XTREAM_CODES,
+ ContentType.MOVIE
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `provider limit messages disable preload`() {
+ assertThat(PlayerRecoveryPolicy.shouldCooldownLivePreloadAfterError("HTTP 429"))
+ .isTrue()
+ assertThat(PlayerRecoveryPolicy.shouldCooldownLivePreloadAfterError("decoder failed"))
+ .isFalse()
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinatorTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinatorTest.kt
new file mode 100644
index 00000000..ad61910b
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerTimeshiftCoordinatorTest.kt
@@ -0,0 +1,119 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.timeshift.TimeshiftConfig
+import org.junit.Test
+import org.mockito.kotlin.never
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
+
+class PlayerTimeshiftCoordinatorTest {
+
+ @Test
+ fun `live stream starts rewind with resolved channel key`() {
+ val engine = mock<PlayerEngine>()
+ val coordinator = PlayerTimeshiftCoordinator(PlayerEngineCoordinator(engine))
+ val streamInfo = StreamInfo(url = "https://provider.example/live.m3u8")
+ var preparing = false
+
+ coordinator.startOrStop(
+ request = PlayerTimeshiftCoordinator.Request(
+ contentType = ContentType.LIVE,
+ enabled = true,
+ streamClassLabel = "Live",
+ config = TimeshiftConfig(enabled = true),
+ streamInfoOverride = streamInfo,
+ currentResolvedStreamInfo = null,
+ currentResolvedPlaybackUrl = "",
+ currentStreamUrl = null,
+ playbackTitle = "Channel",
+ currentTitle = "Channel",
+ channelKey = "channel-42"
+ ),
+ onUnavailable = {},
+ onPreparing = { preparing = true }
+ )
+
+ assertThat(preparing).isTrue()
+ verify(engine).startLiveTimeshift(
+ streamInfo.copy(title = "Channel"),
+ "channel-42",
+ TimeshiftConfig(enabled = true)
+ )
+ verify(engine, never()).stopLiveTimeshift()
+ }
+
+ @Test
+ fun `catch up stream is detached without starting rewind`() {
+ val engine = mock<PlayerEngine>()
+ val coordinator = PlayerTimeshiftCoordinator(PlayerEngineCoordinator(engine))
+
+ coordinator.startOrStop(
+ request = PlayerTimeshiftCoordinator.Request(
+ contentType = ContentType.LIVE,
+ enabled = true,
+ streamClassLabel = "Catch-up",
+ config = TimeshiftConfig(enabled = true),
+ streamInfoOverride = StreamInfo(url = "https://provider.example/live.m3u8"),
+ currentResolvedStreamInfo = null,
+ currentResolvedPlaybackUrl = "",
+ currentStreamUrl = null,
+ playbackTitle = "Channel",
+ currentTitle = "Channel",
+ channelKey = "channel-42"
+ ),
+ onUnavailable = {},
+ onPreparing = {}
+ )
+
+ verify(engine).stopLiveTimeshift()
+ verify(engine, never()).startLiveTimeshift(
+ org.mockito.kotlin.any(),
+ org.mockito.kotlin.any(),
+ org.mockito.kotlin.any()
+ )
+ }
+
+ @Test
+ fun `live stream starts rewind on the engine adopted after coordinator creation`() {
+ val mainEngine = mock<PlayerEngine>()
+ val adoptedEngine = mock<PlayerEngine>()
+ val engineCoordinator = PlayerEngineCoordinator(mainEngine)
+ val coordinator = PlayerTimeshiftCoordinator(engineCoordinator)
+ val streamInfo = StreamInfo(url = "https://provider.example/live.m3u8")
+
+ engineCoordinator.switchTo(adoptedEngine)
+
+ coordinator.startOrStop(
+ request = PlayerTimeshiftCoordinator.Request(
+ contentType = ContentType.LIVE,
+ enabled = true,
+ streamClassLabel = "Live",
+ config = TimeshiftConfig(enabled = true),
+ streamInfoOverride = streamInfo,
+ currentResolvedStreamInfo = null,
+ currentResolvedPlaybackUrl = "",
+ currentStreamUrl = null,
+ playbackTitle = "Channel",
+ currentTitle = "Channel",
+ channelKey = "channel-42"
+ ),
+ onUnavailable = {},
+ onPreparing = {}
+ )
+
+ verify(adoptedEngine).startLiveTimeshift(
+ streamInfo.copy(title = "Channel"),
+ "channel-42",
+ TimeshiftConfig(enabled = true)
+ )
+ verify(mainEngine, never()).startLiveTimeshift(
+ org.mockito.kotlin.any(),
+ org.mockito.kotlin.any(),
+ org.mockito.kotlin.any()
+ )
+ }
+}
diff --git a/docs/IPTV_CODE_REVIEW.md b/docs/IPTV_CODE_REVIEW.md
index 95bd6290..efab569a 100644
--- a/docs/IPTV_CODE_REVIEW.md
+++ b/docs/IPTV_CODE_REVIEW.md
@@ -102,7 +102,7 @@ The former monolithic `IptvProvider` contract has been removed. The domain now d
| Plugin-based | Android service discovery and Messenger protocol in `StreamVaultPluginManager` | Plugin catalogs are imported/mapped into an M3U provider record rather than represented as a provider capability | Playback delegates through the plugin manager or the mapped M3U path depending on manifest action | No first-class provider EPG contract identified |
| Recordings/local output | `RecordingManagerImpl`, Room recording entities, alarms, foreground service/capture engine | Local database/files/document URIs, reconciled on launch and periodically | Local `RecordingItem` enters player/navigation as content | EPG is used to schedule/name recordings; recordings do not supply EPG |
-The registry is now the shared execution boundary for synchronization, detail hydration, guide lookup, playback, catch-up, recording-source resolution, and setup. Remaining coordinator decomposition and Stalker playback side-effect removal belong to ARCH-003/ARCH-004 in WP5.
+The registry is now the shared execution boundary for synchronization, detail hydration, guide lookup, playback, catch-up, recording-source resolution, and setup. Remaining coordinator decomposition belongs to ARCH-003; playback side-effect removal was addressed under ARCH-004.
### Current provider boundary (2026-08-11)
@@ -174,10 +174,10 @@ App update checking starts from `StreamVaultApp` and stores cached release metad
| ARCH-001 | Implemented in code; API 25 migration evidence pending (2026-08-11) | High | Explicit provider capabilities and complete typed registries now drive synchronization and runtime provider execution. | Architectural |
| ARCH-002 | Implemented in code; API 25 migration evidence pending (2026-08-11) | High | Stable provider identity, typed encrypted configuration/runtime storage, and generation-bound Stalker learning replace the authoritative union row. | Architectural |
| ARCH-003 | Implemented in code; device validation pending (2026-08-12) | High | Provider plans, activation receipts, durable continuation scheduling, state publication, index execution, and workflow admission are separated; the remaining `SyncManager` compatibility façade is approximately 2,451 lines. | Architectural |
-| ARCH-004 | Implemented and verified (2026-08-13) | Medium | Provider-neutral playback resolution is split from generation-fenced observation persistence. | Architectural |
-| ARCH-005 | Architectural concern | High | `PlayerViewModel` is a 25+ dependency feature orchestrator that crosses domain/data/player boundaries. | Architectural |
-| ARCH-006 | Implemented and verified (2026-08-13) | High | Plugin discovery is bounded/cancellable and plugins have stable first-class source identity with lifecycle repair. | Local + architectural |
-| ARCH-007 | Implemented and device-verified (2026-08-13) | Medium | Migrations are version-grouped behind a complete registry and every exported historical schema reaches v75. | Architectural |
+| ARCH-004 | **Resolved and verified (2026-08-13)** | Medium | Provider-neutral playback resolution is split from generation-fenced observation persistence. | Architectural |
+| ARCH-005 | **Resolved in code; live/device validation pending (2026-08-13)** | High | Playback session lifetime, engine handoff, content/provider resolution, recovery execution/state, EPG, and playback context now have explicit feature-owned boundaries; remaining shared ViewModel state is staged for follow-up isolation. | Architectural |
+| ARCH-006 | **Resolved in code; IPC lifecycle evidence pending (2026-08-13)** | High | Plugin discovery is bounded/cancellable and plugins have stable first-class source identity with lifecycle repair. | Local + architectural |
+| ARCH-007 | **Resolved and device-verified (2026-08-13)** | Medium | Migrations are version-grouped behind a complete registry and every exported historical schema reaches v75. | Architectural |
| ARCH-008 | Resolved in code; device validation pending | Medium | Startup launches several overlapping background pipelines with independent work identities and state stores. | Architectural |
## Detailed Phase 1 findings
@@ -237,11 +237,11 @@ App update checking starts from `StreamVaultApp` and stores cached release metad
- `SyncStatusPublicationCoordinator` now owns provider metadata/status publication, state/progress session fencing, aggregate state exposure, and partial-summary count/staleness policy. `SyncStatusPublicationCoordinatorTest` covers partial preservation, successful publication, and stale-session fencing.
- `XtreamIncrementalIndexExecutor` now owns full-stream indexing, category-slice fallback, priority-category ordering, cursor continuation, durable job updates, metadata publication, and follow-up scheduling. `XtreamIncrementalIndexOperationsAdapter` keeps that executor at one dependency while existing fetch/DAO helpers remain behind the compatibility façade.
- `StalkerIncrementalIndexExecutor` now owns the summary-category and wildcard page loops, parallel-fetch downgrade, retry/anomaly handling, page checkpoint progression, partial-result state selection, and catalog commit handoff. `StalkerIncrementalIndexOperationsAdapter` keeps the executor at one dependency while the remaining low-level recovery/checkpoint helpers are still exposed by the compatibility façade.
-- Focused coordinator, activation-policy, state-machine, lock, cursor, recovery, and architecture tests pass. `CatalogSyncEquivalenceIntegrationTest` runs the production streaming M3U importer and Room DAOs to prove full import converges with separate Live/Movie repair activation. `ProviderWorkManagerSerializationTest` enqueues the real provider, Xtream-index, Stalker-index, and EPG worker APIs and verifies one provider-scoped WorkManager chain. These instrumentation tests compile; execution remains pending because no device or emulator is connected.
+- Focused coordinator, activation-policy, state-machine, lock, cursor, recovery, and architecture tests pass. `CatalogSyncEquivalenceIntegrationTest` runs the production streaming M3U importer and Room DAOs to prove full import converges with separate Live/Movie repair activation. `ProviderWorkManagerSerializationTest` enqueues the real provider, Xtream-index, Stalker-index, and EPG worker APIs and verifies one provider-scoped WorkManager chain. These instrumentation tests compile; their provider/workflow execution remains pending. A connected TV emulator is available and has been used for the migration and live-playback gates documented below.
### ARCH-004 — Playback resolver has contradictory provider dispatch and hidden side effects
-- **Classification:** Implemented and verified (2026-08-13)
+- **Classification:** **Resolved and verified (2026-08-13)**
- **Severity:** Medium
- **Where:** `data/.../remote/xtream/XtreamStreamUrlResolver.kt:45-227`, especially `resolveWithMetadata`; Stalker provider cache and learning helpers in the same class.
- **Current behavior:** A class named `XtreamStreamUrlResolver` resolves Xtream, Stalker, M3U, and Jellyfin. In its exhaustive provider `when`, `ProviderType.M3U` is handled at lines 217-224 and then listed again with Jellyfin at lines 225-226. Kotlin accepts this, and the forced data-module compile passed, but the second M3U label contradicts the preceding pass-through behavior. The resolver also decrypts provider state, constructs/caches a full `StalkerProvider`, authenticates/resolves a link, and persists learned Stalker playback behavior.
@@ -254,7 +254,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad
### ARCH-005 — `PlayerViewModel` crosses every layer and is a feature-level god object
-- **Classification:** Architectural concern
+- **Classification:** **Resolved in code; live/device validation pending (2026-08-13)**
- **Severity:** High
- **Where:** `app/.../ui/screens/player/PlayerViewModel.kt:88-118` and the many `Player*Actions.kt`/`Player*Support.kt` extensions; direct imports of `SyncManager`, `StalkerUrlFactory`, `XtreamStreamUrlResolver`, `PreferencesRepository`, `OkHttpClient`, and concrete Media3 types.
- **Current behavior:** The ViewModel has more than 25 constructor dependencies spanning repositories, recording, TV recommendations, cast, plugins, URL resolution, synchronization, raw HTTP, preferences, and playback. Its behavior is distributed across dozens of extension files that share `internal` mutable state. It coordinates live/VOD/series resolution, EPG, history, autoplay, token renewal, alternate streams, recovery, timeshift, cast, recording, downloads, plugins, diagnostics, and UI notices.
@@ -266,7 +266,7 @@ App update checking starts from `StreamVaultApp` and stores cached release metad
### ARCH-006 — Plugin discovery blocks callers and plugins are not first-class providers
-- **Classification:** Implemented and verified (2026-08-13)
+- **Classification:** **Resolved in code; IPC lifecycle evidence pending (2026-08-13)**
- **Severity:** High
- **Where:** `app/.../plugins/StreamVaultPluginManager.kt`, especially `resolvePlugin`, `readManifestFromService`, `refreshTvInputCatalogInBackground`, and provider mapping/import methods.
- **Current behavior:** Discovery resolves each service and uses `runBlocking(Dispatchers.IO)` for status and manifest Messenger calls with 2.5s and 3s timeouts. These calls are sequential per plugin and are invoked from non-suspending discovery helpers. Background TV refresh creates an unowned `CoroutineScope(Dispatchers.IO)`. Plugin catalog identity is persisted as a mapping to an M3U provider, so plugin lifecycle and provider lifecycle are coupled indirectly by names/IDs and preferences.
@@ -276,10 +276,11 @@ App update checking starts from `StreamVaultApp` and stores cached release metad
- **Fix scope:** Local for blocking calls/scope; architectural for provider modeling.
- **Required tests:** Main-thread discovery test; multiple slow/dead plugin services; timeout/cancellation; uninstall during import; duplicate manifest IDs; mapping cleanup and TV catalog consistency; process death during catalog import.
- **Implementation (2026-08-13):** Discovery is suspending, concurrent per service, bounded by request and global timeouts, cancellation-safe, and exposes per-component loading/partial/timeout/error state. Application-owned `PluginWorkCoordinator` replaces ad-hoc scopes. Plugins implement the domain `ProviderSourceRegistry` as first-class `PluginProviderSource` values with package/service/manifest identity, capabilities, enabled state, and an explicitly labeled backing storage representation. Enable/disable mutations are serialized and checkpointed before IPC; startup and package broadcasts replay interrupted import/removal work, repair missing ownership, and remove providers only when their exact Android service component is absent.
+- **Closure status:** The implementation is resolved and the available unit/build/device checks pass. A third-party plugin service is not installed in the emulator, so bind/response cancellation, disconnect, loser-unbind, and package replace/reinstall integration evidence remains pending.
### ARCH-007 — Database definition and migration history are too concentrated to audit safely
-- **Classification:** Implemented and device-verified (2026-08-13)
+- **Classification:** **Resolved and device-verified (2026-08-13)**
- **Severity:** Medium
- **Where:** `data/.../local/StreamVaultDatabase.kt` and generated `data/schemas`.
- **Current behavior:** One multi-thousand-line Room database class declares a large entity set and a long sequence of handwritten migrations. The forced compile emitted dozens of migration override warnings and two warnings about inferred intersection types in migration code, in addition to schema-related warning noise.
@@ -397,7 +398,7 @@ Phase 2 should review these files/modules first, in this order:
| WORK-001 | Local database maintenance is incorrectly gated on connectivity | Resolved (2026-08-01) | Medium |
| WORK-002 | Recording reconciliation retries every error without classification/cap | Resolved (2026-07-29) | Medium |
| UPDATE-001 | Failed automatic update checks suppress another attempt for 24 hours | Resolved (2026-07-29) | Medium |
-| MEMORY-001 | Process-lifetime maps grow with provider/category/host/media identities | Implemented and verified (2026-08-13) | Medium |
+| MEMORY-001 | Process-lifetime maps grow with provider/category/host/media identities | **Resolved and verified (2026-08-13)** | Medium |
| PERSIST-001 | The central preferences DataStore has no explicit corruption recovery | Implemented; boundary verification pending (2026-07-30) | Medium |
| TEST-001 | The player suite asserts the opposite MPEG-TS extractor policy from production | Resolved (2026-07-26) | Medium |
@@ -567,7 +568,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl
### MEMORY-001 — Process-lifetime maps grow with provider/category/host/media identities
-- **Classification:** Implemented and verified (2026-08-13)
+- **Classification:** **Resolved and verified (2026-08-13)**
- **Severity:** Medium
- **Where:** `PlayerDataSourceFactoryProvider.clientsByKey:42-78`; `PlayerAddressHealthStore`; `Media3PlayerEngine.promotedLiveHlsBufferReasonsByMediaId:225,1764`; `AudioCompatibilityMemoryStore`; movie/series category caches and locks; `EpgSourceRepositoryImpl.sourceRefreshMutexes:81,218`; URL resolver Stalker-provider registry.
- **Current behavior:** Singleton/long-lived maps, sets, and per-media preference keys have no maximum, comprehensive TTL sweep, or deletion hook. Keys are data/network driven; player client keys include address/proxy variations. `SyncManager.onProviderDeleted` does not invalidate these other registries.
@@ -576,7 +577,7 @@ The urgent shared fixes are cancellation-safe HTTP, recording/timeshift lifecycl
- **Recommended correction:** Set ownership/bounds for every registry: provider-delete invalidation, LRU/TTL with proactive sweep, removal of unused mutexes, and a small fixed set of client profiles. Version/cap persisted compatibility memory.
- **Fix scope:** Shared cache policy plus local hooks.
- **Required tests:** 100,000 unique keys remain within fixed bounds; delete/re-add; TTL without same-key lookup; concurrent eviction/use; active calls survive client policy.
-- **Implementation (2026-08-13):** Added shared bounded/expiring cache, bounded-key-set, and idle self-releasing keyed-mutex policies. Applied fixed limits/TTL or lifecycle removal to player clients, address health, promoted-HLS reasons, versioned audio compatibility memory, movie/series/EPG locks and in-flight sets, sync/work locks, Stalker resolver/auth/URL/identity caches, and provider deletion hooks. Stress tests exercise 100,000 unique keys, TTL sweeping without same-key access, delete/re-add, eviction during active use, and lock replacement safety; evicting a client reference does not cancel an already active OkHttp call.
+- **Implementation (2026-08-13):** Added shared bounded/expiring cache, bounded-key-set, and idle self-releasing keyed-mutex policies. Applied fixed limits/TTL or lifecycle removal to player clients, TV-input playback clients, address health, promoted-HLS reasons, versioned audio compatibility memory, movie/series/EPG locks and in-flight sets, sync/work locks, Stalker resolver/auth/URL/identity caches, and provider deletion hooks. Stress tests exercise 100,000 unique keys, TTL sweeping without same-key access, delete/re-add, eviction during active use, and lock replacement safety; evicting a client reference does not cancel an already active OkHttp call.
### PERSIST-001 — The central preferences DataStore has no explicit corruption recovery
@@ -1518,7 +1519,14 @@ This batch does not require the large architecture split and creates the safety
- Parsed every Phase 1–5 summary and assigned all 56 stable IDs exactly once: 5 + 8 + 14 + 10 + 7 + 8 + 2 + 2 = 56.
- Severity totals reconcile to 35 High and 21 Medium.
- No code or build configuration changed in Phase 6. Only this Markdown report changed, so `graphify update .`, application builds, and emulator validation were not required for this consolidation step.
-- **Review status:** all six planned phases are complete. Implementation and remediation remain future work.
+- **Review status:** all six planned phases are complete. ARCH-004, ARCH-007, and MEMORY-001 are resolved and verified; ARCH-006 is resolved in code, with third-party plugin IPC lifecycle integration evidence still pending.
+
+### Dirty-tree closure update (2026-08-13)
+
+- **ARCH-004 — Resolved and verified:** provider-neutral playback routing and separate generation-fenced observation persistence are implemented; resolver/provider tests and the full JVM suites pass.
+- **ARCH-006 — Resolved in code; evidence caveat retained:** discovery, lifecycle ownership, stable source identity, mutation checkpoints, duplicate-ID handling, and UI owner-keying are implemented. The emulator has no third-party plugin service, so IPC disconnect/cancellation and package replace/reinstall integration tests remain unexecuted.
+- **ARCH-007 — Resolved and device-verified:** the production migration registry is contiguous through v75, and the connected migration suite passes all 37 tests for exported origins v1 and v3–v74 (v2 was never exported).
+- **MEMORY-001 — Resolved and verified:** process-lifetime registries now have explicit bounds/expiry or lifecycle invalidation, including TV-input playback clients; stress and full JVM suites pass.
### ARCH-003 implementation status addendum (2026-08-12)
@@ -1538,4 +1546,22 @@ Production M3U, Jellyfin, Xtream, and Stalker executors now report accepted stag
`SyncCoordinator` validates receipts and owns continuation handoff to `ProviderContinuationScheduler`; provider executors no longer construct or enqueue durable work. Catalog plans consume request snapshots through one delegate instead of re-projecting compatibility providers or bypassing the delegate for selected providers. App startup, Home, Dashboard, Settings, and Player no longer inject the concrete `SyncManager`; they consume lifecycle, command, or state ports, and the unused Player dependency was removed.
-`CatalogSyncEquivalenceIntegrationTest` exercises the real streaming M3U importer, staging tables, activation transactions, and production Room DAOs for a full import versus separate Live/Movie repairs. `ProviderWorkManagerSerializationTest` exercises the real enqueue functions for provider refresh, Xtream index, Stalker index, and background EPG and verifies that they occupy one provider-scoped serial chain. Both Android fixtures compile. The complete JVM validation now passes 981 data tests, 279 app tests, and 196 player tests with zero failures/errors/skips and rebuilds the debug APK. One initial aggregate run saw three `StalkerTransportFactoryTest` MockWebServer timeouts; the class passed immediately in isolation and the complete rerun passed. Device/emulator execution of the Room/WorkManager instrumentation tests is the remaining ARCH-003 closure evidence; `adb` finds no connected device and no emulator/AVD is installed here.
+`CatalogSyncEquivalenceIntegrationTest` exercises the real streaming M3U importer, staging tables, activation transactions, and production Room DAOs for a full import versus separate Live/Movie repairs. `ProviderWorkManagerSerializationTest` exercises the real enqueue functions for provider refresh, Xtream index, Stalker index, and background EPG and verifies that they occupy one provider-scoped serial chain. Both Android fixtures compile. The complete JVM validation now passes 983 data tests, 279 app tests, and 196 player tests with zero failures/errors/skips and rebuilds the debug APK. One initial aggregate run saw three `StalkerTransportFactoryTest` MockWebServer timeouts; the class passed immediately in isolation and the complete rerun passed. Device execution of these ARCH-003 provider/workflow fixtures remains the closure evidence still pending; the connected TV emulator was used for the 37-test migration gate and live-playback validation.
+
+### ARCH-005 decomposition slice (2026-08-13)
+
+Playback session lifetime is now owned by `PlaybackSessionCoordinator`, which creates parent-scope-owned session jobs and rejects stale session events. Player responsibilities are split behind feature-owned collaborators for engine switching, preparation, content/provider resolution, channel and playlist access, provider catch-up, preferences, EPG, guide timeline, history, recording, cast, translation, preview handoff, thumbnails, timeshift, and recovery state. `PlayerViewModel` no longer injects the concrete channel/movie/series/favorites/history/recording/cast/preferences repositories, raw HTTP client, or provider URL resolver; those implementation dependencies are isolated behind the player collaborators. Retry guards and provider preload cooldowns are also session-aware through `PlayerRecoveryCoordinator`.
+
+The provider-backed playback stream implementation now lives in `PlayerContentResolver`; its support file contains only playback models and pure helpers. Catch-up credential-decryption failures are translated to domain `Result` values by `PlayerProviderCoordinator`, keeping provider-specific exceptions out of playback actions.
+
+Playback-error execution is now owned by `PlayerRecoveryExecutionCoordinator`. The ViewModel snapshots session context and delegates through `PlayerRecoveryExecutionPort`; decoder retry, AVC fallback, provider-auth refresh, catch-up/alternate-stream recovery, failure accounting, notices, and previous-channel fallback are no longer implemented in the ViewModel method. Stale requests are rejected before a recovery job is scheduled, with focused tests for stale-event suppression and decoder retry.
+
+Preview/fullscreen engine handoff is now owned by `PlayerPreviewCoordinator`, including the Fire TV HLS bypass, MediaSession switching, preparation policy, adopted-engine lifecycle, and handoff-grace reset. The ViewModel retains only session-currentness and playback-state projection callbacks.
+
+Recovery attempt tracking is now owned by `PlayerRecoveryCoordinator`; alternate-stream attempts and failure counts are retained across the session IDs used for recovery transitions, explicitly cleared for root playback changes, and exposed to recovery selection only as snapshots.
+
+The mutable playback identity is now owned by `PlayerPlaybackContextCoordinator`; the ViewModel exposes compatibility accessors while preparation, recovery, and zap actions share one typed context owner for logical/resolved URLs and content identity.
+
+The recovery execution port no longer retains `PlayerViewModel`; `PlayerRecoveryExecutionPortAdapter` is an explicit runtime bridge assembled from engine, session, recovery-action, and UI projection callbacks.
+
+Focused session, engine, EPG, guide, timeshift, recovery-policy, and recovery-state tests pass, as do `:app:compileDebugKotlin`, `:app:compileDebugUnitTestKotlin`, and `:app:testDebugUnitTest`. ARCH-005 is marked **resolved in code**; the decomposition remains staged for follow-up isolation of shared ViewModel state and callback-heavy seams, while live-playback/device evidence remains the final closure gate.