StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
wip: progress on live pause and rewind
David Nashash3b09701f43b0
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex c375d6f9..75d78a19 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt@@ -191,12 +191,14 @@ fun PlayerScreen(val castConnectionState by viewModel.castConnectionState.collectAsStateWithLifecycle()val seekPreview by viewModel.seekPreview.collectAsStateWithLifecycle()val preventStandbyDuringPlayback by viewModel.preventStandbyDuringPlayback.collectAsStateWithLifecycle()+ val timeshiftUiState by viewModel.timeshiftUiState.collectAsStateWithLifecycle()var showTrackSelection by remember { mutableStateOf<TrackType?>(null) }var showSpeedSelection by remember { mutableStateOf(false) }var showProgramHistory by remember { mutableStateOf(false) }var showSplitDialog by remember { mutableStateOf(false) }var showEpisodePicker by remember { mutableStateOf(false) }+ var channelInfoSubPanelOpen by remember { mutableStateOf(false) }val focusRequester = remember { FocusRequester() }val channelListFocusRequester = remember { FocusRequester() }@@ -473,6 +475,9 @@ fun PlayerScreen(if (showTrackSelection != null || showSpeedSelection || showProgramHistory || showSplitDialog || showEpisodePicker) {return@onPreviewKeyEvent false}+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) {+ return@onPreviewKeyEvent false+ }when (event.nativeKeyEvent.keyCode) {KeyEvent.KEYCODE_DPAD_UP,@@ -588,6 +593,7 @@ fun PlayerScreen(if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent falseif (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay) return@onKeyEvent falseif (showControls && contentType != "LIVE") return@onKeyEvent false@@ -604,6 +610,7 @@ fun PlayerScreen(if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent falseif (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay) return@onKeyEvent falseif (showControls && contentType != "LIVE") return@onKeyEvent false@@ -629,6 +636,9 @@ fun PlayerScreen(true}KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) {+ true+ } elseif (contentType == "LIVE") {viewModel.playNext()true@@ -637,6 +647,9 @@ fun PlayerScreen(}}KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> {+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) {+ true+ } elseif (contentType == "LIVE") {viewModel.playPrevious()true@@ -645,6 +658,9 @@ fun PlayerScreen(}}KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {+ if (showChannelInfoOverlay && channelInfoSubPanelOpen) {+ true+ } elseif (contentType == "LIVE") {viewModel.zapToLastChannel()true@@ -831,6 +847,7 @@ fun PlayerScreen(isMuted = isMuted,playbackSpeed = playbackSpeed,mediaTitle = mediaTitle,+ timeshiftUiState = timeshiftUiState,playButtonFocusRequester = playButtonFocusRequester,quickActionsFocusRequester = quickActionsFocusRequester,modifier = Modifier.fillMaxSize(),@@ -858,6 +875,7 @@ fun PlayerScreen(isCastConnected = castConnectionState == CastConnectionState.CONNECTED,onCast = { viewModel.castCurrentMedia { mainActivity?.openCastRouteChooser() } },onStopCasting = viewModel::stopCasting,+ onSeekToLiveEdge = viewModel::seekToLiveEdge,onSeekToPosition = viewModel::seekTo,onSetScrubbingMode = viewModel::setScrubbingMode,seekPreview = seekPreview,@@ -1048,10 +1066,17 @@ fun PlayerScreen(currentRecordingStatus = currentChannelRecording?.status,onStartRecording = viewModel::startManualRecording,onStopRecording = viewModel::stopCurrentRecording,+ onScheduleRecording = viewModel::scheduleRecording,+ onScheduleDailyRecording = viewModel::scheduleDailyRecording,+ onScheduleWeeklyRecording = viewModel::scheduleWeeklyRecording,onRestartProgram = { viewModel.restartCurrentProgram() },+ onOpenArchive = { showProgramHistory = true },onToggleAspectRatio = { viewModel.toggleAspectRatio() },onToggleDiagnostics = { viewModel.toggleDiagnostics() },onTogglePlayPause = { if (isPlaying) viewModel.pause() else viewModel.play() },+ onSeekBackward = viewModel::seekBackward,+ onSeekForward = viewModel::seekForward,+ onSeekToLiveEdge = viewModel::seekToLiveEdge,isPlaying = isPlaying,currentAspectRatio = aspectRatio.modeName,isDiagnosticsEnabled = showDiagnostics,@@ -1067,7 +1092,9 @@ fun PlayerScreen(onEnterPictureInPicture = enterPictureInPicture,isCastConnected = castConnectionState == CastConnectionState.CONNECTED,onCast = { viewModel.castCurrentMedia { mainActivity?.openCastRouteChooser() } },- onStopCasting = viewModel::stopCasting+ onStopCasting = viewModel::stopCasting,+ timeshiftUiState = timeshiftUiState,+ onTransientPanelVisibilityChanged = { channelInfoSubPanelOpen = it })}}@@ -1112,6 +1139,7 @@ private fun PlayerControlsOverlayHost(isMuted: Boolean,playbackSpeed: Float,mediaTitle: String?,+ timeshiftUiState: PlayerTimeshiftUiState,playButtonFocusRequester: FocusRequester,quickActionsFocusRequester: FocusRequester,modifier: Modifier = Modifier,@@ -1139,6 +1167,7 @@ private fun PlayerControlsOverlayHost(isCastConnected: Boolean,onCast: () -> Unit,onStopCasting: () -> Unit,+ onSeekToLiveEdge: () -> Unit,onSeekToPosition: (Long) -> Unit,onSetScrubbingMode: (Boolean) -> Unit,seekPreview: SeekPreviewState,@@ -1166,6 +1195,7 @@ private fun PlayerControlsOverlayHost(isMuted = isMuted,playbackSpeed = playbackSpeed,mediaTitle = mediaTitle,+ timeshiftUiState = timeshiftUiState,playButtonFocusRequester = playButtonFocusRequester,quickActionsFocusRequester = quickActionsFocusRequester,modifier = modifier,@@ -1193,6 +1223,7 @@ private fun PlayerControlsOverlayHost(isCastConnected = isCastConnected,onCast = onCast,onStopCasting = onStopCasting,+ onSeekToLiveEdge = onSeekToLiveEdge,onSeekToPosition = onSeekToPosition,onSetScrubbingMode = onSetScrubbingMode,seekPreview = seekPreview,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.ktindex 02dba418..73930168 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@@ -28,6 +28,7 @@ import com.streamvault.domain.model.RecordingStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Series+import com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.model.VideoFormatimport com.streamvault.domain.usecase.GetCustomCategories@@ -43,6 +44,10 @@ import com.streamvault.player.PlaybackStateimport com.streamvault.player.PlayerEngineimport com.streamvault.player.PlayerErrorimport com.streamvault.player.PlayerSubtitleStyle+import com.streamvault.player.timeshift.LiveTimeshiftBackend+import com.streamvault.player.timeshift.LiveTimeshiftState+import com.streamvault.player.timeshift.LiveTimeshiftStatus+import com.streamvault.player.timeshift.TimeshiftConfigimport dagger.hilt.android.lifecycle.HiltViewModelimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.Job@@ -172,6 +177,8 @@ class PlayerViewModel @Inject constructor(val recordingItems: StateFlow<List<RecordingItem>> = _recordingItems.asStateFlow()private val currentChannelFlowRecording = MutableStateFlow<RecordingItem?>(null)val currentChannelRecording: StateFlow<RecordingItem?> = currentChannelFlowRecording.asStateFlow()+ private val _timeshiftUiState = MutableStateFlow(PlayerTimeshiftUiState())+ val timeshiftUiState: StateFlow<PlayerTimeshiftUiState> = _timeshiftUiState.asStateFlow()internal var channelInfoHideJob: Job? = nullinternal var liveOverlayHideJob: Job? = null@@ -199,6 +206,7 @@ class PlayerViewModel @Inject constructor(private var playerNoticeTimeoutMs: Long = 6_000Linternal var diagnosticsTimeoutMs: Long = 15_000Lprivate var preferredDecoderMode: DecoderMode = DecoderMode.AUTO+ private var timeshiftConfig: TimeshiftConfig = TimeshiftConfig()// Zapping stateinternal var channelList: List<com.streamvault.domain.model.Channel> = emptyList()@@ -238,6 +246,73 @@ class PlayerViewModel @Inject constructor(}}+ private fun applyTimeshiftState(state: LiveTimeshiftState) {+ val backendLabel = when (state.backend) {+ LiveTimeshiftBackend.DISK -> "Disk"+ LiveTimeshiftBackend.MEMORY -> "Memory"+ LiveTimeshiftBackend.NONE -> ""+ }+ val visibleForLiveUi = timeshiftConfig.enabled &&+ state.status != LiveTimeshiftStatus.DISABLED &&+ state.status != LiveTimeshiftStatus.UNSUPPORTED &&+ state.status != LiveTimeshiftStatus.FAILED+ _timeshiftUiState.value = PlayerTimeshiftUiState(+ available = visibleForLiveUi,+ enabledForSession = timeshiftConfig.enabled,+ backendLabel = backendLabel,+ bufferedBehindLiveMs = state.currentOffsetFromLiveMs,+ bufferDepthMs = state.bufferedDurationMs.takeIf { it > 0L } ?: timeshiftConfig.depthMs,+ canSeekToLive = state.canSeekToLive,+ statusMessage = state.message.orEmpty(),+ engineState = state+ )+ }++ private fun maybeStartLiveTimeshift(streamInfoOverride: StreamInfo? = null) {+ if (currentContentType != ContentType.LIVE || !timeshiftConfig.enabled) {+ playerEngine.stopLiveTimeshift()+ return+ }+ if (currentStreamClassLabel == "Catch-up") {+ playerEngine.stopLiveTimeshift()+ return+ }+ val resolvedCandidate = currentResolvedPlaybackUrl.safeTrimmedOrNull()+ val currentCandidate = currentStreamUrl.safeTrimmedOrNull()+ val fallbackUrl = resolvedCandidate ?: currentCandidate ?: run {+ playerEngine.stopLiveTimeshift()+ _timeshiftUiState.update {+ it.copy(+ available = false,+ enabledForSession = timeshiftConfig.enabled,+ statusMessage = "Local live rewind is unavailable for this stream."+ )+ }+ return+ }+ val streamInfo = streamInfoOverride ?: StreamInfo(+ url = fallbackUrl,+ title = playbackTitleFlow.value.ifBlank { currentTitle }+ )+ 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)+ }++ private fun String?.safeTrimmedOrNull(): String? {+ val value = this ?: return null+ return value.trim().takeIf { it.isNotEmpty() }+ }+init {viewModelScope.launch {playerEngine.error.collect { error ->@@ -317,6 +392,26 @@ class PlayerViewModel @Inject constructor(viewModelScope.launch {preferencesRepository.playerMediaSessionEnabled.collect(playerEngine::setMediaSessionEnabled)}+ viewModelScope.launch {+ combine(+ preferencesRepository.playerTimeshiftEnabled,+ preferencesRepository.playerTimeshiftDepthMinutes+ ) { enabled, depthMinutes ->+ TimeshiftConfig(enabled = enabled, depthMinutes = depthMinutes)+ }.collect { config ->+ timeshiftConfig = config+ _timeshiftUiState.update { current ->+ current.copy(+ enabledForSession = config.enabled,+ bufferDepthMs = config.depthMs+ )+ }+ maybeStartLiveTimeshift()+ }+ }+ viewModelScope.launch {+ playerEngine.timeshiftState.collect(::applyTimeshiftState)+ }viewModelScope.launch {preferencesRepository.playerDecoderMode.collect { mode ->preferredDecoderMode = mode@@ -902,6 +997,7 @@ class PlayerViewModel @Inject constructor(recentChannelsFlow.value = emptyList()lastVisitedCategoryJob?.cancel()_lastVisitedCategory.value = null+ playerEngine.stopLiveTimeshift()}hasRetriedWithSoftwareDecoder = falseplayerEngine.setDecoderMode(preferredDecoderMode)@@ -924,6 +1020,7 @@ class PlayerViewModel @Inject constructor(return@launch}if (!preparePlayer(streamInfo, requestVersion)) return@launch+ maybeStartLiveTimeshift(streamInfo)}}@@ -981,6 +1078,7 @@ class PlayerViewModel @Inject constructor(}if (currentContentType == ContentType.LIVE && hasArchiveRequest) {+ playerEngine.stopLiveTimeshift()viewModelScope.launch {val catchUpUrls = try {providerRepository.buildCatchUpUrls(@@ -1134,12 +1232,14 @@ class PlayerViewModel @Inject constructor(if (currentContentType != ContentType.LIVE) {viewModelScope.launch { persistPlaybackProgress() }}+ playerEngine.stopLiveTimeshift()}fun handOffPlaybackToMultiView() {if (currentContentType != ContentType.LIVE) {viewModelScope.launch { persistPlaybackProgress() }}+ playerEngine.stopLiveTimeshift()playerEngine.release()}@@ -1704,10 +1804,28 @@ class PlayerViewModel @Inject constructor(return false}- fun play() = playerEngine.play()- fun pause() = playerEngine.pause()+ fun play() {+ if (currentContentType == ContentType.LIVE &&+ timeshiftConfig.enabled &&+ timeshiftUiState.value.engineState.status == LiveTimeshiftStatus.PAUSED_BEHIND_LIVE+ ) {+ playerEngine.resumeTimeshift()+ } else {+ playerEngine.play()+ }+ }++ fun pause() {+ if (currentContentType == ContentType.LIVE && timeshiftConfig.enabled) {+ playerEngine.pauseTimeshift()+ } else {+ playerEngine.pause()+ }+ }+fun seekForward() = playerEngine.seekForward()fun seekBackward() = playerEngine.seekBackward()+ fun seekToLiveEdge() = playerEngine.seekToLiveEdge()fun playEpisode(episode: Episode, showResumePrompt: Boolean = true) {prepare(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.ktindex 90e8a710..f4567773 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt@@ -6,6 +6,7 @@ import com.streamvault.domain.model.ChannelQualityOptionimport com.streamvault.domain.model.Seasonimport com.streamvault.domain.model.Seriesimport com.streamvault.domain.model.DecoderMode+import com.streamvault.player.timeshift.LiveTimeshiftStateimport java.util.Localedata class ResumePromptState(@@ -50,6 +51,17 @@ data class PlayerDiagnosticsUiState(val troubleshootingHints: List<String> = emptyList())+data class PlayerTimeshiftUiState(+ val available: Boolean = false,+ val enabledForSession: Boolean = false,+ val backendLabel: String = "",+ val bufferedBehindLiveMs: Long = 0L,+ val bufferDepthMs: Long = 0L,+ val canSeekToLive: Boolean = false,+ val statusMessage: String = "",+ val engineState: LiveTimeshiftState = LiveTimeshiftState()+)+enum class PlayerRecoveryType {NETWORK,SOURCE,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.ktindex ae70ab47..effb50e2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt@@ -68,6 +68,7 @@ import com.streamvault.app.Rimport com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.screens.player.NumericChannelInputState+import com.streamvault.app.ui.screens.player.PlayerTimeshiftUiStateimport com.streamvault.app.ui.screens.player.SeekPreviewStateimport com.streamvault.app.ui.theme.ErrorColorimport com.streamvault.app.ui.theme.Primary@@ -108,6 +109,7 @@ fun PlayerControlsOverlay(isMuted: Boolean,playbackSpeed: Float = 1f,mediaTitle: String?,+ timeshiftUiState: PlayerTimeshiftUiState = PlayerTimeshiftUiState(),playButtonFocusRequester: FocusRequester,quickActionsFocusRequester: FocusRequester = FocusRequester(),onClose: () -> Unit,@@ -134,6 +136,7 @@ fun PlayerControlsOverlay(isCastConnected: Boolean = false,onCast: () -> Unit = {},onStopCasting: () -> Unit = {},+ onSeekToLiveEdge: () -> Unit = {},onSeekToPosition: (Long) -> Unit = {},onSetScrubbingMode: (Boolean) -> Unit = {},seekPreview: SeekPreviewState = SeekPreviewState(),@@ -190,6 +193,7 @@ fun PlayerControlsOverlay(isMuted = isMuted,playbackSpeed = playbackSpeed,mediaTitle = mediaTitle,+ timeshiftUiState = timeshiftUiState,playButtonFocusRequester = playButtonFocusRequester,quickActionsFocusRequester = quickActionsFocusRequester,modifier = Modifier.align(Alignment.BottomCenter),@@ -213,6 +217,7 @@ fun PlayerControlsOverlay(isCastConnected = isCastConnected,onCast = onCast,onStopCasting = onStopCasting,+ onSeekToLiveEdge = onSeekToLiveEdge,onTogglePlayPause = onTogglePlayPause,onSeekBackward = onSeekBackward,onSeekForward = onSeekForward,@@ -508,6 +513,7 @@ private fun PlayerBottomBar(isMuted: Boolean,playbackSpeed: Float,mediaTitle: String?,+ timeshiftUiState: PlayerTimeshiftUiState,playButtonFocusRequester: FocusRequester,quickActionsFocusRequester: FocusRequester,onRestartProgram: () -> Unit,@@ -530,6 +536,7 @@ private fun PlayerBottomBar(isCastConnected: Boolean,onCast: () -> Unit,onStopCasting: () -> Unit,+ onSeekToLiveEdge: () -> Unit,onTogglePlayPause: () -> Unit,onSeekBackward: () -> Unit,onSeekForward: () -> Unit,@@ -592,6 +599,7 @@ private fun PlayerBottomBar(currentRecordingStatus = currentRecordingStatus,isMuted = isMuted,mediaTitle = mediaTitle,+ timeshiftUiState = timeshiftUiState,playButtonFocusRequester = playButtonFocusRequester,quickActionsFocusRequester = quickActionsFocusRequester,onRestartProgram = onRestartProgram,@@ -611,6 +619,12 @@ private fun PlayerBottomBar(isCastConnected = isCastConnected,onCast = onCast,onStopCasting = onStopCasting+ ,+ isPlaying = isPlaying,+ onTogglePlayPause = onTogglePlayPause,+ onSeekBackward = onSeekBackward,+ onSeekForward = onSeekForward,+ onSeekToLiveEdge = onSeekToLiveEdge)} else {PlayerVodInfo(@@ -665,6 +679,7 @@ private fun PlayerLiveInfo(currentRecordingStatus: RecordingStatus?,isMuted: Boolean,mediaTitle: String?,+ timeshiftUiState: PlayerTimeshiftUiState,playButtonFocusRequester: FocusRequester,quickActionsFocusRequester: FocusRequester,onRestartProgram: () -> Unit,@@ -683,9 +698,18 @@ private fun PlayerLiveInfo(onToggleMute: () -> Unit,isCastConnected: Boolean,onCast: () -> Unit,- onStopCasting: () -> Unit+ onStopCasting: () -> Unit,+ isPlaying: Boolean,+ onTogglePlayPause: () -> Unit,+ onSeekBackward: () -> Unit,+ onSeekForward: () -> Unit,+ onSeekToLiveEdge: () -> Unit) {+ val showTimeshiftControls = timeshiftUiState.available && !isCastConnectedval primaryActions = buildList {+ if (showTimeshiftControls) {+ add(PlayerActionSpec(stringResource(R.string.player_jump_to_live), onSeekToLiveEdge))+ }add(PlayerActionSpec(stringResource(if (isMuted) R.string.player_unmute else R.string.player_mute),onToggleMute@@ -731,7 +755,14 @@ private fun PlayerLiveInfo(horizontalArrangement = Arrangement.spacedBy(8.dp),verticalArrangement = Arrangement.spacedBy(8.dp)) {- PlayerMetaPill(text = stringResource(R.string.player_live_now), accent = true)+ PlayerMetaPill(+ text = if (showTimeshiftControls) {+ stringResource(R.string.player_live_rewind_badge)+ } else {+ stringResource(R.string.player_live_now)+ },+ accent = true+ )PlayerMetaPill(text = stringResource(R.string.player_live_channel, displayChannelNumber))if (currentProgram?.hasArchive == true) {PlayerMetaPill(text = stringResource(R.string.player_archive_badge))@@ -739,6 +770,18 @@ private fun PlayerLiveInfo(if (isMuted) {PlayerMetaPill(text = stringResource(R.string.player_muted_badge))}+ if (showTimeshiftControls) {+ PlayerMetaPill(+ text = if (timeshiftUiState.bufferedBehindLiveMs > 1_000L) {+ stringResource(+ R.string.player_live_offset,+ formatDuration(timeshiftUiState.bufferedBehindLiveMs)+ )+ } else {+ stringResource(R.string.player_live_ready)+ }+ )+ }}Text(text = currentProgram?.title ?: mediaTitle ?: currentChannelName.orEmpty(),@@ -760,6 +803,100 @@ private fun PlayerLiveInfo(Spacer(modifier = Modifier.height(16.dp))+ if (showTimeshiftControls) {+ Surface(+ shape = RoundedCornerShape(20.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 14.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Surface(+ shape = RoundedCornerShape(999.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.24f))+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ PlayerTransportButton(+ label = "\u23EA",+ contentDescription = stringResource(R.string.player_rewind),+ onClick = onSeekBackward,+ modifier = Modifier.focusProperties { down = quickActionsFocusRequester }+ )+ TvClickableSurface(+ onClick = onTogglePlayPause,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(50)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.84f),+ focusedContainerColor = Primary+ ),+ modifier = Modifier+ .size(62.dp)+ .focusRequester(playButtonFocusRequester)+ .focusProperties { down = quickActionsFocusRequester }+ ) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {+ if (isPlaying) {+ Text(text = "II", style = MaterialTheme.typography.headlineMedium, color = Color.White)+ } else {+ Icon(+ imageVector = Icons.Default.PlayArrow,+ contentDescription = stringResource(R.string.player_play),+ tint = Color.White,+ modifier = Modifier.size(30.dp)+ )+ }+ }+ }+ PlayerTransportButton(+ label = "\u23E9",+ contentDescription = stringResource(R.string.player_forward),+ onClick = onSeekForward,+ modifier = Modifier.focusProperties { down = quickActionsFocusRequester }+ )+ }+ }+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ text = timeshiftUiState.statusMessage.ifBlank {+ if (timeshiftUiState.bufferDepthMs > 0L) {+ stringResource(R.string.player_live_timeshift_buffering)+ } else {+ stringResource(R.string.player_live_timeshift_ready)+ }+ },+ style = MaterialTheme.typography.labelLarge,+ color = Color.White+ )+ Text(+ text = if (timeshiftUiState.bufferedBehindLiveMs > 1_000L) {+ stringResource(R.string.player_live_offset, formatDuration(timeshiftUiState.bufferedBehindLiveMs))+ } else {+ stringResource(R.string.player_live_ready)+ },+ style = MaterialTheme.typography.labelMedium,+ color = Color.White.copy(alpha = 0.72f)+ )+ }+ if (timeshiftUiState.canSeekToLive) {+ PlayerQuickSettingsButton(+ text = stringResource(R.string.player_jump_to_live),+ onClick = onSeekToLiveEdge+ )+ }+ }+ }++ Spacer(modifier = Modifier.height(16.dp))+ }+val start = currentProgram?.startTime ?: 0Lval end = currentProgram?.endTime ?: 0Lif (start > 0 && end > 0) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.ktindex 02c7b911..9426ddaf 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt@@ -24,6 +24,7 @@ import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.width@@ -33,6 +34,8 @@ import androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.PlayArrowimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.derivedStateOf@@ -44,6 +47,7 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.graphics.Brush@@ -53,7 +57,6 @@ import androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflow-import androidx.compose.foundation.layout.offsetimport androidx.compose.ui.unit.LayoutDirectionimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.sp@@ -63,6 +66,7 @@ import androidx.tv.material3.ClickableSurfaceDefaultsimport androidx.tv.material3.Borderimport androidx.tv.material3.MaterialThemeimport androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaultsimport androidx.tv.material3.Textimport coil3.compose.AsyncImageimport com.streamvault.app.R@@ -72,6 +76,7 @@ import com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.screens.player.PlayerDiagnosticsUiState+import com.streamvault.app.ui.screens.player.PlayerTimeshiftUiStateimport com.streamvault.domain.model.RecordingStatusimport com.streamvault.app.ui.design.AppColors.Brand as Primaryimport com.streamvault.app.ui.design.AppColors.SurfaceElevated as SurfaceVariant@@ -80,6 +85,7 @@ import com.streamvault.app.ui.design.AppColors.TextTertiary as OnSurfaceDimimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Programimport com.streamvault.player.PlayerStats+import com.streamvault.player.timeshift.LiveTimeshiftStatusimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale@@ -172,10 +178,17 @@ fun ChannelInfoOverlay(currentRecordingStatus: RecordingStatus?,onStartRecording: () -> Unit,onStopRecording: () -> Unit,+ onScheduleRecording: () -> Unit,+ onScheduleDailyRecording: () -> Unit,+ onScheduleWeeklyRecording: () -> Unit,onRestartProgram: () -> Unit,+ onOpenArchive: () -> Unit,onToggleAspectRatio: () -> Unit,onToggleDiagnostics: () -> Unit,onTogglePlayPause: () -> Unit,+ onSeekBackward: () -> Unit,+ onSeekForward: () -> Unit,+ onSeekToLiveEdge: () -> Unit,isPlaying: Boolean,currentAspectRatio: String,isDiagnosticsEnabled: Boolean,@@ -191,11 +204,54 @@ fun ChannelInfoOverlay(onEnterPictureInPicture: () -> Unit = {},isCastConnected: Boolean = false,onCast: () -> Unit = {},- onStopCasting: () -> Unit = {}+ onStopCasting: () -> Unit = {},+ timeshiftUiState: PlayerTimeshiftUiState = PlayerTimeshiftUiState(),+ onTransientPanelVisibilityChanged: (Boolean) -> Unit = {}) {val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())+ val showTimeshiftControls = timeshiftUiState.available && !isCastConnected+ val hasCatchUpOptions = currentChannel?.catchUpSupported == true || currentProgram?.hasArchive == true+ var expandedPanel by remember { mutableStateOf<ChannelInfoPanel?>(null) }+ val recordButtonFocusRequester = remember { FocusRequester() }+ val catchUpButtonFocusRequester = remember { FocusRequester() }+ val liveDvrPanelFocusRequester = remember { FocusRequester() }+ val recordPanelFocusRequester = remember { FocusRequester() }+ val catchUpPanelFocusRequester = remember { FocusRequester() }- BackHandler { onDismiss() }+ fun handleMainActionFocus(ownerPanel: ChannelInfoPanel?) {+ onOverlayInteracted()+ if (expandedPanel != null && expandedPanel != ownerPanel) {+ expandedPanel = null+ }+ }++ fun togglePanel(panel: ChannelInfoPanel) {+ expandedPanel = if (expandedPanel == panel) null else panel+ }++ LaunchedEffect(showTimeshiftControls, hasCatchUpOptions) {+ expandedPanel = when (expandedPanel) {+ ChannelInfoPanel.LIVE_DVR -> expandedPanel.takeIf { showTimeshiftControls }+ ChannelInfoPanel.CATCH_UP -> expandedPanel.takeIf { hasCatchUpOptions }+ else -> expandedPanel+ }+ }++ LaunchedEffect(expandedPanel) {+ onTransientPanelVisibilityChanged(expandedPanel != null)+ }++ androidx.compose.runtime.DisposableEffect(Unit) {+ onDispose { onTransientPanelVisibilityChanged(false) }+ }++ BackHandler {+ if (expandedPanel != null) {+ expandedPanel = null+ } else {+ onDismiss()+ }+ }PlayerOverlayPanel(modifier = Modifier@@ -245,6 +301,23 @@ fun ChannelInfoOverlay(label = stringResource(R.string.player_live_channel, displayChannelNumber),containerColor = AppColors.BrandMuted)+ if (showTimeshiftControls) {+ StatusPill(+ label = stringResource(R.string.player_live_rewind_badge),+ containerColor = AppColors.SurfaceEmphasis+ )+ }+ if (currentRecordingStatus == RecordingStatus.RECORDING) {+ StatusPill(+ label = stringResource(R.string.player_recording_badge),+ containerColor = AppColors.Live+ )+ } else if (currentRecordingStatus == RecordingStatus.SCHEDULED) {+ StatusPill(+ label = stringResource(R.string.player_recording_scheduled_badge),+ containerColor = AppColors.BrandMuted+ )+ }if (currentChannel != null) {Text(text = currentChannel.name,@@ -352,6 +425,20 @@ fun ChannelInfoOverlay(}}+ if (showTimeshiftControls && expandedPanel == ChannelInfoPanel.LIVE_DVR) {+ CompactTimeshiftTransport(+ timeshiftUiState = timeshiftUiState,+ isPlaying = isPlaying,+ onOverlayInteracted = onOverlayInteracted,+ onTogglePlayPause = onTogglePlayPause,+ onSeekBackward = onSeekBackward,+ onSeekForward = onSeekForward,+ onSeekToLiveEdge = onSeekToLiveEdge,+ firstFocusRequester = liveDvrPanelFocusRequester,+ ownerFocusRequester = focusRequester+ )+ }+LazyRow(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.spacedBy(6.dp),@@ -360,30 +447,46 @@ fun ChannelInfoOverlay() {item {QuickActionButton(- icon = stringResource(R.string.player_action_playback),- label = if (isPlaying) stringResource(R.string.player_pause) else stringResource(R.string.player_play),+ icon = if (showTimeshiftControls) "DVR" else stringResource(R.string.player_action_playback),+ label = if (showTimeshiftControls) {+ stringResource(R.string.player_live_dvr_controls)+ } else if (isPlaying) {+ stringResource(R.string.player_pause)+ } else {+ stringResource(R.string.player_play)+ },onClick = {- onOverlayInteracted()- onTogglePlayPause()+ if (showTimeshiftControls) {+ togglePanel(ChannelInfoPanel.LIVE_DVR)+ } else {+ onTogglePlayPause()+ }},- onInteraction = onOverlayInteracted,+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.LIVE_DVR.takeIf { showTimeshiftControls }) },colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.20f),+ containerColor = if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {+ Primary.copy(alpha = 0.30f)+ } else {+ Primary.copy(alpha = 0.20f)+ },focusedContainerColor = Primary,pressedContainerColor = Primary.copy(alpha = 0.8f)),- modifier = Modifier.focusRequester(focusRequester)+ modifier = Modifier+ .focusRequester(focusRequester)+ .focusProperties {+ if (expandedPanel == ChannelInfoPanel.LIVE_DVR) {+ up = liveDvrPanelFocusRequester+ }+ })}item {QuickActionButton(icon = stringResource(R.string.player_action_mute),label = if (isMuted) stringResource(R.string.player_unmute) else stringResource(R.string.player_mute),- onClick = {- onOverlayInteracted()- onToggleMute()- },- onInteraction = onOverlayInteracted+ onClick = onToggleMute,+ onInteraction = { handleMainActionFocus(null) })}if (subtitleTrackCount > 0) {@@ -391,11 +494,8 @@ fun ChannelInfoOverlay(QuickActionButton(icon = stringResource(R.string.player_subs),label = stringResource(R.string.player_subs),- onClick = {- onOverlayInteracted()- onOpenSubtitleTracks()- },- onInteraction = onOverlayInteracted+ onClick = onOpenSubtitleTracks,+ onInteraction = { handleMainActionFocus(null) })}}@@ -404,11 +504,8 @@ fun ChannelInfoOverlay(QuickActionButton(icon = stringResource(R.string.player_action_quality),label = stringResource(R.string.player_quality_short),- onClick = {- onOverlayInteracted()- onOpenVideoTracks()- },- onInteraction = onOverlayInteracted+ onClick = onOpenVideoTracks,+ onInteraction = { handleMainActionFocus(null) })}}@@ -417,11 +514,8 @@ fun ChannelInfoOverlay(QuickActionButton(icon = stringResource(R.string.player_audio),label = stringResource(R.string.player_audio),- onClick = {- onOverlayInteracted()- onOpenAudioTracks()- },- onInteraction = onOverlayInteracted+ onClick = onOpenAudioTracks,+ onInteraction = { handleMainActionFocus(null) })}}@@ -430,10 +524,11 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_guide),label = stringResource(R.string.player_epg_short),onClick = {- onOverlayInteracted()+ expandedPanel = null+ onDismiss()onOpenFullEpg()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}item {@@ -441,11 +536,11 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_split),label = stringResource(R.string.player_multiview_short),onClick = {- onOverlayInteracted()+ expandedPanel = nullonDismiss()onOpenSplitScreen()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}item {@@ -453,10 +548,10 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_diagnostics),label = stringResource(R.string.player_stats),onClick = {- onOverlayInteracted()+ expandedPanel = nullonToggleDiagnostics()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}if (!lastVisitedCategoryName.isNullOrBlank()) {@@ -465,61 +560,50 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_group),label = lastVisitedCategoryName,onClick = {- onOverlayInteracted()+ expandedPanel = nullonOpenLastGroup()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}}item {QuickActionButton(- icon = if (currentRecordingStatus == RecordingStatus.RECORDING) {- stringResource(R.string.player_stop_recording)- } else {- stringResource(R.string.player_record)- },- label = if (currentRecordingStatus == RecordingStatus.RECORDING) {- stringResource(R.string.player_stop_recording)- } else {- stringResource(R.string.player_record)- },- onClick = {- onOverlayInteracted()- if (currentRecordingStatus == RecordingStatus.RECORDING) {- onStopRecording()- } else {- onStartRecording()+ icon = "REC",+ label = stringResource(R.string.player_record),+ onClick = { togglePanel(ChannelInfoPanel.RECORD) },+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.RECORD) },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (expandedPanel == ChannelInfoPanel.RECORD) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,+ focusedContainerColor = Primary.copy(alpha = 0.85f)+ ),+ modifier = Modifier+ .focusRequester(recordButtonFocusRequester)+ .focusProperties {+ if (expandedPanel == ChannelInfoPanel.RECORD) {+ up = recordPanelFocusRequester+ }}- },- onInteraction = onOverlayInteracted)}- if (currentChannel?.catchUpSupported == true) {+ if (hasCatchUpOptions) {item {QuickActionButton(- icon = stringResource(R.string.player_catchup_badge),- label = stringResource(R.string.player_archive),- onClick = {- onOverlayInteracted()- onDismiss()- onOpenFullEpg()- },- onInteraction = onOverlayInteracted- )- }- }- if (currentChannel?.catchUpSupported == true && currentProgram?.hasArchive == true) {- item {- QuickActionButton(- icon = stringResource(R.string.player_action_restart_short),- label = stringResource(R.string.player_restart),- onClick = {- onOverlayInteracted()- onRestartProgram()- onDismiss()- },- onInteraction = onOverlayInteracted+ icon = "C-UP",+ label = stringResource(R.string.player_catchup_badge),+ onClick = { togglePanel(ChannelInfoPanel.CATCH_UP) },+ onInteraction = { handleMainActionFocus(ChannelInfoPanel.CATCH_UP) },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (expandedPanel == ChannelInfoPanel.CATCH_UP) Primary.copy(alpha = 0.22f) else AppColors.SurfaceEmphasis,+ focusedContainerColor = Primary.copy(alpha = 0.85f)+ ),+ modifier = Modifier+ .focusRequester(catchUpButtonFocusRequester)+ .focusProperties {+ if (expandedPanel == ChannelInfoPanel.CATCH_UP) {+ up = catchUpPanelFocusRequester+ }+ })}}@@ -528,10 +612,10 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_cast),label = if (isCastConnected) stringResource(R.string.player_stop_casting) else stringResource(R.string.player_cast),onClick = {- onOverlayInteracted()+ expandedPanel = nullif (isCastConnected) onStopCasting() else onCast()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}item {@@ -539,10 +623,10 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_pip),label = stringResource(R.string.player_pip_short),onClick = {- onOverlayInteracted()+ expandedPanel = nullonEnterPictureInPicture()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}item {@@ -550,17 +634,440 @@ fun ChannelInfoOverlay(icon = stringResource(R.string.player_action_view),label = currentAspectRatio,onClick = {- onOverlayInteracted()+ expandedPanel = nullonToggleAspectRatio()},- onInteraction = onOverlayInteracted+ onInteraction = { handleMainActionFocus(null) })}}++ when (expandedPanel) {+ ChannelInfoPanel.RECORD -> {+ ChannelInfoActionMenuTray(+ title = stringResource(R.string.player_record_options),+ actions = buildList {+ if (currentRecordingStatus == RecordingStatus.RECORDING || currentRecordingStatus == RecordingStatus.SCHEDULED) {+ add(+ ChannelInfoMenuEntry(+ label = if (currentRecordingStatus == RecordingStatus.SCHEDULED) {+ stringResource(R.string.player_cancel_scheduled_recording)+ } else {+ stringResource(R.string.player_stop_recording)+ }+ ) {+ expandedPanel = null+ onStopRecording()+ }+ )+ } else {+ add(+ ChannelInfoMenuEntry(stringResource(R.string.player_record_now)) {+ expandedPanel = null+ onStartRecording()+ }+ )+ }+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_recording)) {+ expandedPanel = null+ onScheduleRecording()+ })+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_daily_recording)) {+ expandedPanel = null+ onScheduleDailyRecording()+ })+ add(ChannelInfoMenuEntry(stringResource(R.string.player_schedule_weekly_recording)) {+ expandedPanel = null+ onScheduleWeeklyRecording()+ })+ },+ onInteraction = onOverlayInteracted,+ firstActionFocusRequester = recordPanelFocusRequester,+ ownerFocusRequester = recordButtonFocusRequester+ )+ }++ ChannelInfoPanel.CATCH_UP -> {+ ChannelInfoActionMenuTray(+ title = stringResource(R.string.player_catchup_options),+ actions = buildList {+ if (currentProgram?.hasArchive == true) {+ add(ChannelInfoMenuEntry(stringResource(R.string.player_restart)) {+ expandedPanel = null+ onRestartProgram()+ onDismiss()+ })+ }+ if (currentChannel?.catchUpSupported == true) {+ add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_archive)) {+ expandedPanel = null+ onDismiss()+ onOpenArchive()+ })+ }+ add(ChannelInfoMenuEntry(stringResource(R.string.player_browse_guide_catchup)) {+ expandedPanel = null+ onDismiss()+ onOpenFullEpg()+ })+ },+ onInteraction = onOverlayInteracted,+ firstActionFocusRequester = catchUpPanelFocusRequester,+ ownerFocusRequester = catchUpButtonFocusRequester+ )+ }++ ChannelInfoPanel.LIVE_DVR,+ null -> Unit+ }}}}+private enum class ChannelInfoPanel {+ LIVE_DVR,+ RECORD,+ CATCH_UP+}++private data class ChannelInfoMenuEntry(+ val label: String,+ val onClick: () -> Unit+)++@Composable+private fun CompactTimeshiftTransport(+ timeshiftUiState: PlayerTimeshiftUiState,+ isPlaying: Boolean,+ onOverlayInteracted: () -> Unit,+ onTogglePlayPause: () -> Unit,+ onSeekBackward: () -> Unit,+ onSeekForward: () -> Unit,+ onSeekToLiveEdge: () -> Unit,+ firstFocusRequester: FocusRequester,+ ownerFocusRequester: FocusRequester+) {+ val transportReady = timeshiftUiState.bufferDepthMs > 1_000L &&+ timeshiftUiState.engineState.status != LiveTimeshiftStatus.PREPARING+ val behindLive = timeshiftUiState.bufferedBehindLiveMs.coerceAtLeast(0L)+ val bufferDepth = timeshiftUiState.bufferDepthMs.coerceAtLeast(0L)+ val liveProgress = if (bufferDepth > 0L) {+ ((bufferDepth - behindLive).toFloat() / bufferDepth.toFloat()).coerceIn(0f, 1f)+ } else {+ 1f+ }+ val statusLine = when {+ !transportReady -> timeshiftUiState.statusMessage.ifBlank {+ stringResource(R.string.player_live_timeshift_buffering)+ }+ behindLive > 1_000L -> stringResource(+ R.string.player_live_offset,+ formatTimeLabel(behindLive)+ )+ else -> stringResource(R.string.player_live_ready)+ }+ var lastTransportActionAtMs by remember { mutableStateOf(0L) }++ fun runTransportAction(enabled: Boolean, action: () -> Unit) {+ if (!enabled) return+ val now = System.currentTimeMillis()+ if (now - lastTransportActionAtMs < 240L) return+ lastTransportActionAtMs = now+ onOverlayInteracted()+ action()+ }++ Surface(+ shape = RoundedCornerShape(18.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Surface(+ shape = RoundedCornerShape(14.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 9.dp, vertical = 7.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = stringResource(R.string.player_live_rewind_badge),+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),+ color = Primary+ )+ Text(+ text = statusLine,+ style = MaterialTheme.typography.titleSmall.copy(fontSize = 20.sp),+ color = Color.White,+ fontWeight = FontWeight.Bold+ )+ Text(+ text = stringResource(+ R.string.player_live_buffer_depth,+ formatTimeLabel(bufferDepth)+ ),+ style = MaterialTheme.typography.labelMedium,+ color = Color.White.copy(alpha = 0.7f)+ )+ }+ }++ Row(+ modifier = Modifier.weight(1f),+ horizontalArrangement = Arrangement.End,+ verticalAlignment = Alignment.CenterVertically+ ) {+ CompactTransportButton(+ topLabel = stringResource(R.string.player_rewind),+ mainLabel = stringResource(R.string.player_seek_back_10),+ enabled = transportReady,+ onInteraction = onOverlayInteracted,+ onClick = { runTransportAction(transportReady, onSeekBackward) },+ modifier = Modifier+ .focusRequester(firstFocusRequester)+ .focusProperties { down = ownerFocusRequester }+ )+ Spacer(modifier = Modifier.width(8.dp))+ TvClickableSurface(+ onClick = { runTransportAction(transportReady, onTogglePlayPause) },+ enabled = transportReady,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.88f),+ focusedContainerColor = Primary,+ disabledContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier+ .size(52.dp)+ .focusProperties { down = ownerFocusRequester }+ ) {+ Box(+ modifier = Modifier.fillMaxSize(),+ contentAlignment = Alignment.Center+ ) {+ if (isPlaying) {+ Text(+ text = "II",+ style = MaterialTheme.typography.headlineSmall,+ color = Color.White+ )+ } else {+ androidx.tv.material3.Icon(+ imageVector = Icons.Default.PlayArrow,+ contentDescription = stringResource(R.string.player_play),+ tint = Color.White,+ modifier = Modifier.size(26.dp)+ )+ }+ }+ }+ Spacer(modifier = Modifier.width(8.dp))+ CompactTransportButton(+ topLabel = stringResource(R.string.player_forward),+ mainLabel = stringResource(R.string.player_seek_forward_10),+ enabled = transportReady && timeshiftUiState.canSeekToLive,+ onInteraction = onOverlayInteracted,+ onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekForward) },+ modifier = Modifier.focusProperties { down = ownerFocusRequester }+ )+ Spacer(modifier = Modifier.width(8.dp))+ CompactTransportButton(+ topLabel = stringResource(R.string.player_live_ready),+ mainLabel = stringResource(R.string.player_jump_to_live_short),+ enabled = transportReady && timeshiftUiState.canSeekToLive,+ highlighted = !timeshiftUiState.canSeekToLive,+ onInteraction = onOverlayInteracted,+ onClick = { runTransportAction(transportReady && timeshiftUiState.canSeekToLive, onSeekToLiveEdge) },+ modifier = Modifier.focusProperties { down = ownerFocusRequester }+ )+ }+ }++ androidx.compose.material3.LinearProgressIndicator(+ progress = { liveProgress },+ modifier = Modifier+ .fillMaxWidth()+ .height(4.dp)+ .clip(RoundedCornerShape(999.dp)),+ color = Primary,+ trackColor = Color.White.copy(alpha = 0.16f)+ )+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.player_live_buffer_start),+ style = MaterialTheme.typography.labelSmall,+ color = Color.White.copy(alpha = 0.52f)+ )+ Text(+ text = if (behindLive > 1_000L) {+ stringResource(R.string.player_live_offset, formatTimeLabel(behindLive))+ } else {+ stringResource(R.string.player_live_ready)+ },+ style = MaterialTheme.typography.labelSmall,+ color = Color.White.copy(alpha = 0.76f)+ )+ Text(+ text = stringResource(R.string.player_live_buffer_end),+ style = MaterialTheme.typography.labelSmall,+ color = Color.White.copy(alpha = 0.52f)+ )+ }+ }+ }+}++@Composable+private fun CompactTransportButton(+ topLabel: String,+ mainLabel: String,+ enabled: Boolean,+ highlighted: Boolean = false,+ onInteraction: () -> Unit,+ onClick: () -> Unit,+ modifier: Modifier = Modifier+) {+ TvClickableSurface(+ onClick = onClick,+ enabled = enabled,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (highlighted) {+ Primary.copy(alpha = 0.18f)+ } else {+ Color.White.copy(alpha = 0.08f)+ },+ focusedContainerColor = Primary.copy(alpha = 0.86f),+ disabledContainerColor = Color.White.copy(alpha = 0.04f)+ ),+ modifier = modifier+ .widthIn(min = 68.dp)+ .onFocusChanged {+ if (it.isFocused) onInteraction()+ }+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(1.dp)+ ) {+ Text(+ text = topLabel,+ style = MaterialTheme.typography.labelSmall.copy(fontSize = 10.sp),+ color = Color.White.copy(alpha = if (enabled) 0.72f else 0.32f)+ )+ Text(+ text = mainLabel,+ style = MaterialTheme.typography.titleSmall.copy(fontSize = 16.sp),+ color = if (enabled) Color.White else Color.White.copy(alpha = 0.32f),+ fontWeight = FontWeight.Bold+ )+ }+ }+}++@Composable+private fun ChannelInfoActionMenuTray(+ title: String,+ actions: List<ChannelInfoMenuEntry>,+ onInteraction: () -> Unit,+ firstActionFocusRequester: FocusRequester,+ ownerFocusRequester: FocusRequester+) {+ if (actions.isEmpty()) return++ Surface(+ shape = RoundedCornerShape(18.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.Black.copy(alpha = 0.22f))+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.labelLarge,+ color = Primary,+ fontWeight = FontWeight.Bold+ )+ LazyRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ itemsIndexed(actions) { index, action ->+ CompactMenuActionButton(+ text = action.label,+ onClick = action.onClick,+ onInteraction = onInteraction,+ modifier = (if (index == 0) Modifier.focusRequester(firstActionFocusRequester) else Modifier)+ .focusProperties { down = ownerFocusRequester }+ )+ }+ }+ }+ }+}++@Composable+private fun CompactMenuActionButton(+ text: String,+ onClick: () -> Unit,+ onInteraction: () -> Unit,+ modifier: Modifier = Modifier+) {+ TvClickableSurface(+ onClick = {+ onInteraction()+ onClick()+ },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Primary.copy(alpha = 0.88f)+ ),+ modifier = modifier+ .onFocusChanged {+ if (it.isFocused) onInteraction()+ }+ ) {+ Text(+ text = text,+ style = MaterialTheme.typography.bodyMedium,+ color = Color.White,+ fontWeight = FontWeight.Medium,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+}++private fun formatTimeLabel(ms: Long): String {+ val totalSeconds = (ms / 1_000L).coerceAtLeast(0L)+ val hours = totalSeconds / 3_600L+ val minutes = (totalSeconds % 3_600L) / 60L+ val seconds = totalSeconds % 60L+ return if (hours > 0L) {+ String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds)+ } else {+ String.format(Locale.getDefault(), "%d:%02d", minutes, seconds)+ }+}+@Composableprivate fun QuickActionButton(icon: String,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.ktindex 4fd7060e..dceb9aa1 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt@@ -167,6 +167,9 @@ fun SettingsScreen(val ethernetQualityLabel = remember(uiState.ethernetMaxVideoHeight, context) {formatQualityCapLabel(uiState.ethernetMaxVideoHeight, context.getString(R.string.settings_quality_cap_auto))}+ val timeshiftDepthLabel = remember(uiState.playerTimeshiftDepthMinutes, context) {+ formatTimeshiftDepthLabel(uiState.playerTimeshiftDepthMinutes, context)+ }val lastSpeedTestLabel = remember(uiState.lastSpeedTest) {uiState.lastSpeedTest?.let(::formatSpeedTestValueLabel)?: context.getString(R.string.settings_speed_test_not_run)@@ -211,6 +214,7 @@ fun SettingsScreen(var showGuideDefaultCategoryDialog by rememberSaveable { mutableStateOf(false) }var showPlaybackSpeedDialog by rememberSaveable { mutableStateOf(false) }var showDecoderModeDialog by rememberSaveable { mutableStateOf(false) }+ var showTimeshiftDepthDialog by rememberSaveable { mutableStateOf(false) }var showControlsTimeoutDialog by rememberSaveable { mutableStateOf(false) }var showLiveOverlayTimeoutDialog by rememberSaveable { mutableStateOf(false) }var showNoticeTimeoutDialog by rememberSaveable { mutableStateOf(false) }@@ -468,6 +472,45 @@ fun SettingsScreen(Switch(checked = uiState.playerMediaSessionEnabled, onCheckedChange = { viewModel.setPlayerMediaSessionEnabled(it) })}}+ HorizontalDivider(color = Color.White.copy(alpha = 0.07f), modifier = Modifier.padding(vertical = 4.dp))+ TvClickableSurface(+ onClick = { viewModel.setPlayerTimeshiftEnabled(!uiState.playerTimeshiftEnabled) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_live_timeshift), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_live_timeshift_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.playerTimeshiftEnabled, onCheckedChange = { viewModel.setPlayerTimeshiftEnabled(it) })+ }+ }+ ClickableSettingsRow(+ label = stringResource(R.string.settings_live_timeshift_depth),+ value = timeshiftDepthLabel,+ onClick = { showTimeshiftDepthDialog = true }+ )+ ClickableSettingsRow(+ label = stringResource(R.string.settings_live_timeshift_backend),+ value = stringResource(R.string.settings_live_timeshift_backend_value),+ onClick = {}+ )+ Text(+ text = stringResource(R.string.settings_live_timeshift_backend_subtitle),+ style = MaterialTheme.typography.bodySmall,+ color = OnBackground.copy(alpha = 0.6f),+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)+ )ClickableSettingsRow(label = stringResource(R.string.settings_decoder_mode),value = decoderModeLabel,@@ -1000,6 +1043,8 @@ fun SettingsScreen(onShowPlaybackSpeedDialogChange = { showPlaybackSpeedDialog = it },showDecoderModeDialog = showDecoderModeDialog,onShowDecoderModeDialogChange = { showDecoderModeDialog = it },+ showTimeshiftDepthDialog = showTimeshiftDepthDialog,+ onShowTimeshiftDepthDialogChange = { showTimeshiftDepthDialog = it },showControlsTimeoutDialog = showControlsTimeoutDialog,onShowControlsTimeoutDialogChange = { showControlsTimeoutDialog = it },showLiveOverlayTimeoutDialog = showLiveOverlayTimeoutDialog,@@ -1081,3 +1126,12 @@ private fun android.content.Context.findMainActivity(): MainActivity? {return null}+private fun formatTimeshiftDepthLabel(+ depthMinutes: Int,+ context: android.content.Context+): String = when (depthMinutes) {+ 15 -> context.getString(R.string.settings_live_timeshift_depth_15)+ 60 -> context.getString(R.string.settings_live_timeshift_depth_60)+ else -> context.getString(R.string.settings_live_timeshift_depth_30)+}+diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.ktindex 7ab8b9e8..9ff92af6 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt@@ -58,6 +58,8 @@ internal fun SettingsScreenDialogs(onShowPlaybackSpeedDialogChange: (Boolean) -> Unit,showDecoderModeDialog: Boolean,onShowDecoderModeDialogChange: (Boolean) -> Unit,+ showTimeshiftDepthDialog: Boolean,+ onShowTimeshiftDepthDialogChange: (Boolean) -> Unit,showControlsTimeoutDialog: Boolean,onShowControlsTimeoutDialogChange: (Boolean) -> Unit,showLiveOverlayTimeoutDialog: Boolean,@@ -281,6 +283,32 @@ internal fun SettingsScreenDialogs(}}+ if (showTimeshiftDepthDialog) {+ val depthOptions = remember(context) {+ listOf(+ 15 to context.getString(R.string.settings_live_timeshift_depth_15),+ 30 to context.getString(R.string.settings_live_timeshift_depth_30),+ 60 to context.getString(R.string.settings_live_timeshift_depth_60)+ )+ }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_live_timeshift_depth),+ onDismiss = { onShowTimeshiftDepthDialogChange(false) }+ ) {+ depthOptions.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.second,+ currentLevel = if (uiState.playerTimeshiftDepthMinutes == option.first) index else -1,+ onSelect = {+ viewModel.setPlayerTimeshiftDepthMinutes(option.first)+ onShowTimeshiftDepthDialogChange(false)+ }+ )+ }+ }+ }+if (showLiveTvFiltersDialog) {LiveTvQuickFiltersDialog(filters = uiState.liveTvCategoryFilters,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.ktindex e35671bd..6dbba56c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt@@ -60,6 +60,8 @@ internal fun observeSettingsPreferenceSnapshot(subtitleBackgroundColor = 0x80000000.toInt(),wifiMaxVideoHeight = null,ethernetMaxVideoHeight = null,+ playerTimeshiftEnabled = false,+ playerTimeshiftDepthMinutes = 30,lastSpeedTestMegabits = null,lastSpeedTestTimestamp = null,lastSpeedTestTransport = null,@@ -114,6 +116,10 @@ internal fun observeSettingsPreferenceSnapshot(snapshot.copy(wifiMaxVideoHeight = wifiMaxVideoHeight)}.combine(preferencesRepository.playerEthernetMaxVideoHeight) { snapshot, ethernetMaxVideoHeight ->snapshot.copy(ethernetMaxVideoHeight = ethernetMaxVideoHeight)+ }.combine(preferencesRepository.playerTimeshiftEnabled) { snapshot, enabled ->+ snapshot.copy(playerTimeshiftEnabled = enabled)+ }.combine(preferencesRepository.playerTimeshiftDepthMinutes) { snapshot, depthMinutes ->+ snapshot.copy(playerTimeshiftDepthMinutes = depthMinutes)}.combine(preferencesRepository.lastSpeedTestMegabits) { snapshot, lastSpeedTestMegabits ->snapshot.copy(lastSpeedTestMegabits = lastSpeedTestMegabits)}.combine(preferencesRepository.lastSpeedTestTimestamp) { snapshot, lastSpeedTestTimestamp ->@@ -188,6 +194,8 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencsubtitleBackgroundColor = snapshot.subtitleBackgroundColor,wifiMaxVideoHeight = snapshot.wifiMaxVideoHeight,ethernetMaxVideoHeight = snapshot.ethernetMaxVideoHeight,+ playerTimeshiftEnabled = snapshot.playerTimeshiftEnabled,+ playerTimeshiftDepthMinutes = snapshot.playerTimeshiftDepthMinutes,lastSpeedTest = snapshot.lastSpeedTestMegabits?.let {InternetSpeedTestUiModel(megabitsPerSecond = it,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex 9df2d398..a3795d8e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -420,6 +420,18 @@ class SettingsViewModel @Inject constructor(}}+ fun setPlayerTimeshiftEnabled(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setPlayerTimeshiftEnabled(enabled)+ }+ }++ fun setPlayerTimeshiftDepthMinutes(minutes: Int) {+ viewModelScope.launch {+ preferencesRepository.setPlayerTimeshiftDepthMinutes(minutes)+ }+ }+fun setPlayerDecoderMode(mode: DecoderMode) {viewModelScope.launch {preferencesRepository.setPlayerDecoderMode(mode)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.ktindex 5817e946..0c517d34 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt@@ -59,6 +59,8 @@ internal data class SettingsPreferenceSnapshot(val subtitleBackgroundColor: Int,val wifiMaxVideoHeight: Int?,val ethernetMaxVideoHeight: Int?,+ val playerTimeshiftEnabled: Boolean,+ val playerTimeshiftDepthMinutes: Int,val lastSpeedTestMegabits: Double?,val lastSpeedTestTimestamp: Long?,val lastSpeedTestTransport: String?,@@ -151,6 +153,8 @@ data class SettingsUiState(val subtitleBackgroundColor: Int = 0x80000000.toInt(),val wifiMaxVideoHeight: Int? = null,val ethernetMaxVideoHeight: Int? = null,+ val playerTimeshiftEnabled: Boolean = false,+ val playerTimeshiftDepthMinutes: Int = 30,val lastSpeedTest: InternetSpeedTestUiModel? = null,val isRunningInternetSpeedTest: Boolean = false,val backupPreview: BackupPreview? = null,diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 9b020a70..6ca8af34 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -340,6 +340,16 @@<string name="settings_default_playback_speed">Default Playback Speed</string><string name="settings_media_session">System Media Session</string><string name="settings_media_session_subtitle">Expose playback to Android system media controls. Disable this if playback crashes on a specific device when opening the player.</string>+ <string name="settings_live_timeshift">Enable Local Live Rewind</string>+ <string name="settings_live_timeshift_subtitle">Keep a temporary local buffer for pausing and rewinding live TV even when the provider has no catch-up support.</string>+ <string name="settings_live_timeshift_depth">Local Live Rewind Depth</string>+ <string name="settings_live_timeshift_backend">Live Rewind Backend</string>+ <string name="settings_live_timeshift_backend_value">Automatic</string>+ <string name="settings_live_timeshift_backend_subtitle">Prefers app storage for the local ring buffer and falls back to bounded memory when storage is unavailable.</string>+ <string name="settings_select_live_timeshift_depth">Select Local Live Rewind Depth</string>+ <string name="settings_live_timeshift_depth_15">15 minutes</string>+ <string name="settings_live_timeshift_depth_30">30 minutes</string>+ <string name="settings_live_timeshift_depth_60">60 minutes</string><string name="settings_player_controls_timeout">VOD Controls Auto-Hide</string><string name="settings_live_overlay_timeout">Live TV Overlays Auto-Hide</string><string name="settings_player_notice_timeout">Playback Notices Auto-Hide</string>@@ -835,14 +845,20 @@<string name="player_restart">Restart</string><string name="player_archive">Archive</string><string name="player_record">Record</string>+ <string name="player_record_now">Record now</string><string name="player_stop_recording">Stop Recording</string>+ <string name="player_cancel_scheduled_recording">Cancel Scheduled</string><string name="player_schedule_recording">Schedule</string><string name="player_schedule_daily_recording">Schedule Daily</string><string name="player_schedule_weekly_recording">Schedule Weekly</string>+ <string name="player_record_options">Recording</string>+ <string name="player_live_dvr_controls">Player</string><string name="player_recording_started">Recording started for %1$s.</string><string name="player_recording_stopped">Recording stopped.</string><string name="player_recording_scheduled">Recording scheduled for %1$s.</string><string name="player_recording_missing_context">Recording needs a valid live channel context.</string>+ <string name="player_recording_badge">Recording</string>+ <string name="player_recording_scheduled_badge">Scheduled</string><string name="player_subs">Subs</string><string name="player_audio">Audio</string><string name="player_action_mute">Mute</string>@@ -883,6 +899,9 @@<string name="player_last_group_hint">Jump back to the last live group you were browsing.</string><string name="player_archive_badge">Archive</string><string name="player_catchup_badge">Catch-up</string>+ <string name="player_catchup_options">Catch-up</string>+ <string name="player_browse_archive">Browse Archive</string>+ <string name="player_browse_guide_catchup">Browse Guide</string><string name="player_time_range_minutes">%1$s - %2$s | %3$d min</string><string name="player_next_label">Next:</string><string name="player_full_epg">Full EPG</string>@@ -1069,6 +1088,19 @@<string name="settings_category_controls_empty">No categories match this search.</string><string name="player_archive_title">Program Archive</string><string name="player_no_archive">No archived programs found</string>+ <string name="player_jump_to_live">Jump to Live</string>+ <string name="player_jump_to_live_short">LIVE</string>+ <string name="player_live_rewind_badge">LOCAL DVR</string>+ <string name="player_live_offset">%1$s behind live</string>+ <string name="player_live_ready">LIVE</string>+ <string name="player_live_buffer_depth">Buffer %1$s</string>+ <string name="player_live_buffer_start">Buffer start</string>+ <string name="player_live_buffer_end">Live edge</string>+ <string name="player_seek_back_10">-10s</string>+ <string name="player_seek_forward_10">+10s</string>+ <string name="player_live_timeshift_ready">Timeshift ready.</string>+ <string name="player_live_timeshift_buffering">Local live rewind is still buffering.</string>+ <string name="player_live_timeshift_failed">Local live rewind is unavailable for this stream.</string><string name="series_loading_details">Loading details...</string><string name="series_not_found">Series not found</string><string name="series_detail_back">Back to library</string>diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 8c28f583..360887df 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -94,6 +94,8 @@ class PreferencesRepository @Inject constructor(val PLAYER_DIAGNOSTICS_TIMEOUT_SECONDS = intPreferencesKey("player_diagnostics_timeout_seconds")val PLAYER_WIFI_MAX_VIDEO_HEIGHT = intPreferencesKey("player_wifi_max_video_height")val PLAYER_ETHERNET_MAX_VIDEO_HEIGHT = intPreferencesKey("player_ethernet_max_video_height")+ val PLAYER_TIMESHIFT_ENABLED = booleanPreferencesKey("player_timeshift_enabled")+ val PLAYER_TIMESHIFT_DEPTH_MINUTES = intPreferencesKey("player_timeshift_depth_minutes")val LAST_SPEED_TEST_MEGABITS = stringPreferencesKey("last_speed_test_megabits")val LAST_SPEED_TEST_TIMESTAMP = longPreferencesKey("last_speed_test_timestamp")val LAST_SPEED_TEST_TRANSPORT = stringPreferencesKey("last_speed_test_transport")@@ -238,6 +240,19 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.PLAYER_ETHERNET_MAX_VIDEO_HEIGHT]?.takeIf { it > 0 }}+ val playerTimeshiftEnabled: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.PLAYER_TIMESHIFT_ENABLED] ?: false+ }++ val playerTimeshiftDepthMinutes: Flow<Int> = context.dataStore.data.map { preferences ->+ when (preferences[PreferencesKeys.PLAYER_TIMESHIFT_DEPTH_MINUTES] ?: 30) {+ 15, 30, 60 -> preferences[PreferencesKeys.PLAYER_TIMESHIFT_DEPTH_MINUTES] ?: 30+ in Int.MIN_VALUE..22 -> 15+ in 23..45 -> 30+ else -> 60+ }+ }+val lastSpeedTestMegabits: Flow<Double?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.LAST_SPEED_TEST_MEGABITS]?.toDoubleOrNull()}@@ -588,6 +603,23 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun setPlayerTimeshiftEnabled(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.PLAYER_TIMESHIFT_ENABLED] = enabled+ }+ }++ suspend fun setPlayerTimeshiftDepthMinutes(minutes: Int) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.PLAYER_TIMESHIFT_DEPTH_MINUTES] = when (minutes) {+ 15, 30, 60 -> minutes+ in Int.MIN_VALUE..22 -> 15+ in 23..45 -> 30+ else -> 60+ }+ }+ }+suspend fun setLastSpeedTestResult(megabitsPerSecond: Double?,measuredAtMs: Long?,diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex 39709156..ded3b3f9 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -43,6 +43,11 @@ import com.streamvault.player.playback.PreloadCoordinatorimport com.streamvault.player.playback.ResolvedStreamTypeimport com.streamvault.player.playback.StreamTypeResolverimport com.streamvault.player.stats.PlayerStatsCollector+import com.streamvault.player.timeshift.DefaultLiveTimeshiftManager+import com.streamvault.player.timeshift.LiveTimeshiftBackend+import com.streamvault.player.timeshift.LiveTimeshiftState+import com.streamvault.player.timeshift.LiveTimeshiftStatus+import com.streamvault.player.timeshift.TimeshiftConfigimport com.streamvault.player.tracks.PlayerTrackControllerimport com.streamvault.player.ui.PlayerViewBinderimport com.streamvault.player.ui.SubtitleStyleController@@ -53,6 +58,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.MutableStateFlow@@ -70,6 +76,7 @@ class Media3PlayerEngine @Inject constructor(companion object {private const val TAG = "Media3PlayerEngine"+ private const val AUDIO_RENDERER_RECOVERY_COOLDOWN_MS = 15_000L}var constrainResolutionForMultiView: Boolean = false@@ -134,6 +141,10 @@ class Media3PlayerEngine @Inject constructor(private val _playbackSpeed = MutableStateFlow(1f)override val playbackSpeed: StateFlow<Float> = _playbackSpeed.asStateFlow()+ private val liveTimeshiftManager = DefaultLiveTimeshiftManager(context, okHttpClient)+ private val _timeshiftState = MutableStateFlow(LiveTimeshiftState())+ override val timeshiftState: StateFlow<LiveTimeshiftState> = _timeshiftState.asStateFlow()+private val _playerStats = MutableStateFlow(PlayerStats())override val playerStats: StateFlow<PlayerStats> = _playerStats.asStateFlow()@@ -170,6 +181,21 @@ class Media3PlayerEngine @Inject constructor(private val preloadCoordinator = PreloadCoordinator()private val compatibilityProfile: PlaybackCompatibilityProfile = DefaultPlaybackCompatibilityProfileprivate val decoderPreferencePolicy = DefaultDecoderPreferencePolicy()+ private var activeLiveTimeshiftStreamInfo: StreamInfo? = null+ private var activeLiveTimeshiftChannelKey: String? = null+ private var isPlayingTimeshiftSnapshot: Boolean = false+ private var pendingTimeshiftSeekMs: Long? = null+ private var pendingTimeshiftSeekToEnd: Boolean = false+ private var pendingTimeshiftAutoPlay: Boolean = false+ private var lastAudioRendererRecoveryAtMs: Long = 0L++ init {+ scope.launch {+ liveTimeshiftManager.state.collectLatest {+ syncTimeshiftState()+ }+ }+ }override fun prepare(streamInfo: StreamInfo) {prepareInternal(streamInfo = streamInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)@@ -178,6 +204,7 @@ class Media3PlayerEngine @Inject constructor(override fun play() {if (audioFocusController.requestAudioFocusIfNeeded()) {exoPlayer?.playWhenReady = true+ syncTimeshiftState()}}@@ -195,10 +222,26 @@ class Media3PlayerEngine @Inject constructor(}override fun seekTo(positionMs: Long) {+ if (activeLiveTimeshiftStreamInfo != null && !isPlayingTimeshiftSnapshot && _timeshiftState.value.supported) {+ switchToTimeshiftSnapshot(positionMs = positionMs.coerceAtLeast(0L), autoPlay = true)+ return+ }exoPlayer?.seekTo(positionMs)}override fun seekForward(ms: Long) {+ if (isPlayingTimeshiftSnapshot) {+ exoPlayer?.let { player ->+ val duration = player.duration+ val newPosition = if (duration != C.TIME_UNSET) {+ (player.currentPosition + ms).coerceAtMost(duration)+ } else {+ player.currentPosition + ms+ }+ player.seekTo(newPosition)+ }+ return+ }exoPlayer?.let { player ->val duration = player.durationval newPosition = if (duration != C.TIME_UNSET) {@@ -211,6 +254,12 @@ class Media3PlayerEngine @Inject constructor(}override fun seekBackward(ms: Long) {+ if (activeLiveTimeshiftStreamInfo != null && !isPlayingTimeshiftSnapshot && _timeshiftState.value.supported) {+ val liveEdge = _timeshiftState.value.liveEdgePositionMs+ val target = (liveEdge - ms).coerceAtLeast(0L)+ switchToTimeshiftSnapshot(positionMs = target, autoPlay = true)+ return+ }exoPlayer?.let { player ->player.seekTo((player.currentPosition - ms).coerceAtLeast(0L))}@@ -244,6 +293,61 @@ class Media3PlayerEngine @Inject constructor(exoPlayer?.playbackParameters = PlaybackParameters(clamped)}+ override fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {+ activeLiveTimeshiftStreamInfo = streamInfo+ activeLiveTimeshiftChannelKey = channelKey+ scope.launch {+ liveTimeshiftManager.startSession(streamInfo, channelKey, config)+ syncTimeshiftState()+ }+ }++ override fun stopLiveTimeshift() {+ val wasSnapshot = isPlayingTimeshiftSnapshot+ val liveInfo = activeLiveTimeshiftStreamInfo+ activeLiveTimeshiftStreamInfo = null+ activeLiveTimeshiftChannelKey = null+ isPlayingTimeshiftSnapshot = false+ pendingTimeshiftSeekMs = null+ pendingTimeshiftSeekToEnd = false+ pendingTimeshiftAutoPlay = false+ scope.launch {+ liveTimeshiftManager.stopSession()+ if (wasSnapshot && liveInfo != null) {+ prepareInternal(liveInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)+ }+ syncTimeshiftState()+ }+ }++ override fun seekToLiveEdge() {+ val liveInfo = activeLiveTimeshiftStreamInfo ?: return+ isPlayingTimeshiftSnapshot = false+ pendingTimeshiftSeekMs = null+ pendingTimeshiftSeekToEnd = false+ pendingTimeshiftAutoPlay = false+ prepareInternal(liveInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = true)+ syncTimeshiftState()+ }++ override fun pauseTimeshift() {+ if (activeLiveTimeshiftStreamInfo != null && !isPlayingTimeshiftSnapshot && _timeshiftState.value.supported) {+ switchToTimeshiftSnapshot(positionMs = null, autoPlay = false, seekToEnd = true)+ return+ }+ exoPlayer?.playWhenReady = false+ audioFocusController.onPauseOrStop()+ syncTimeshiftState()+ }++ override fun resumeTimeshift() {+ if (isPlayingTimeshiftSnapshot) {+ play()+ return+ }+ seekToLiveEdge()+ }+override fun setPreferredAudioLanguage(languageTag: String?) {trackController.setPreferredAudioLanguage(exoPlayer, languageTag)}@@ -319,6 +423,9 @@ class Media3PlayerEngine @Inject constructor(}override fun release() {+ scope.launch {+ liveTimeshiftManager.stopSession()+ }retryJob?.cancel()retryJob = nullpreloadCoordinator.release()@@ -341,6 +448,10 @@ class Media3PlayerEngine @Inject constructor(_mediaTitle.value = nulltrackController.resetSelections()statsCollector.reset()+ activeLiveTimeshiftStreamInfo = null+ activeLiveTimeshiftChannelKey = null+ isPlayingTimeshiftSnapshot = false+ _timeshiftState.value = LiveTimeshiftState()}private fun prepareInternal(@@ -536,6 +647,32 @@ class Media3PlayerEngine @Inject constructor(statsCollector.onAudioFormatChanged(format)}+ override fun onAudioUnderrun(+ eventTime: AnalyticsListener.EventTime,+ bufferSize: Int,+ bufferSizeMs: Long,+ elapsedSinceLastFeedMs: Long+ ) {+ Log.w(+ TAG,+ "audio-underrun bufferSize=$bufferSize bufferSizeMs=$bufferSizeMs elapsedSinceLastFeedMs=$elapsedSinceLastFeedMs"+ )+ }++ override fun onAudioSinkError(+ eventTime: AnalyticsListener.EventTime,+ audioSinkError: Exception+ ) {+ handleAudioRendererIssue(audioSinkError, "audio-sink")+ }++ override fun onAudioCodecError(+ eventTime: AnalyticsListener.EventTime,+ audioCodecError: Exception+ ) {+ handleAudioRendererIssue(audioCodecError, "audio-codec")+ }+override fun onDroppedVideoFrames(eventTime: AnalyticsListener.EventTime,droppedFrames: Int,@@ -579,10 +716,22 @@ class Media3PlayerEngine @Inject constructor(}if (_playbackState.value == PlaybackState.READY) {_retryStatus.value = null+ if (isPlayingTimeshiftSnapshot && pendingTimeshiftSeekToEnd) {+ pendingTimeshiftSeekToEnd = false+ playerOrNull()?.duration?.takeIf { it > 0L && it != C.TIME_UNSET }?.let { duration ->+ playerOrNull()?.seekTo(duration)+ }+ } else if (isPlayingTimeshiftSnapshot) {+ pendingTimeshiftSeekMs?.let { target ->+ pendingTimeshiftSeekMs = null+ playerOrNull()?.seekTo(target)+ }+ }}if (_playbackState.value == PlaybackState.READY && _isPlaying.value) {markPlaybackStarted("ready-while-playing")}+ syncTimeshiftState()}override fun onIsPlayingChanged(isPlaying: Boolean) {@@ -596,6 +745,7 @@ class Media3PlayerEngine @Inject constructor(} else {statsCollector.stop()}+ syncTimeshiftState()}override fun onPlayerError(error: PlaybackException) {@@ -608,6 +758,7 @@ class Media3PlayerEngine @Inject constructor(reason: Int) {_currentPosition.value = newPosition.positionMs+ syncTimeshiftState()}override fun onMediaMetadataChanged(metadata: androidx.media3.common.MediaMetadata) {@@ -620,6 +771,65 @@ class Media3PlayerEngine @Inject constructor(}}+ private fun playerOrNull(): ExoPlayer? = exoPlayer++ private fun switchToTimeshiftSnapshot(+ positionMs: Long?,+ autoPlay: Boolean,+ seekToEnd: Boolean = false+ ) {+ val liveInfo = activeLiveTimeshiftStreamInfo ?: return+ scope.launch {+ val snapshot = liveTimeshiftManager.createSnapshot() ?: run {+ syncTimeshiftState(messageOverride = "Local live rewind is still buffering.")+ return@launch+ }+ isPlayingTimeshiftSnapshot = true+ pendingTimeshiftSeekMs = positionMs+ pendingTimeshiftSeekToEnd = seekToEnd+ pendingTimeshiftAutoPlay = autoPlay+ val snapshotInfo = liveInfo.copy(url = snapshot.url, streamType = inferSnapshotStreamType(snapshot.url))+ prepareInternal(snapshotInfo, preserveRetryState = false, seekPositionMs = null, autoPlay = autoPlay)+ syncTimeshiftState()+ }+ }++ private fun inferSnapshotStreamType(url: String) = when {+ url.lowercase().endsWith(".m3u8") -> com.streamvault.domain.model.StreamType.HLS+ else -> com.streamvault.domain.model.StreamType.PROGRESSIVE+ }++ private fun syncTimeshiftState(messageOverride: String? = null) {+ val managerState = liveTimeshiftManager.state.value+ if (!managerState.enabled) {+ _timeshiftState.value = managerState+ return+ }+ val player = exoPlayer+ val duration = player?.duration?.takeIf { it != C.TIME_UNSET } ?: managerState.liveEdgePositionMs+ val currentPosition = player?.currentPosition ?: duration+ val offsetFromLive = when {+ isPlayingTimeshiftSnapshot -> (managerState.liveEdgePositionMs - currentPosition).coerceAtLeast(0L)+ else -> 0L+ }+ val status = when {+ managerState.status == LiveTimeshiftStatus.FAILED -> LiveTimeshiftStatus.FAILED+ !managerState.supported -> LiveTimeshiftStatus.UNSUPPORTED+ isPlayingTimeshiftSnapshot && _playbackState.value == PlaybackState.BUFFERING -> LiveTimeshiftStatus.BUFFERING+ isPlayingTimeshiftSnapshot && _isPlaying.value -> LiveTimeshiftStatus.PLAYING_BEHIND_LIVE+ isPlayingTimeshiftSnapshot -> LiveTimeshiftStatus.PAUSED_BEHIND_LIVE+ managerState.status == LiveTimeshiftStatus.PREPARING -> LiveTimeshiftStatus.PREPARING+ else -> LiveTimeshiftStatus.LIVE+ }+ _timeshiftState.value = managerState.copy(+ backend = if (managerState.backend == LiveTimeshiftBackend.NONE) managerState.backend else managerState.backend,+ status = status,+ liveEdgePositionMs = managerState.liveEdgePositionMs,+ currentOffsetFromLiveMs = offsetFromLive,+ message = messageOverride ?: managerState.message+ )+ }+private fun markPlaybackStarted(reason: String) {if (playbackStarted) returnplaybackStarted = true@@ -629,6 +839,48 @@ class Media3PlayerEngine @Inject constructor()}+ private fun handleAudioRendererIssue(error: Exception, source: String) {+ val streamInfo = lastStreamInfo+ if (streamInfo == null) {+ _error.tryEmit(PlayerError.DecoderError(error.message ?: "Audio playback failed."))+ return+ }++ val now = System.currentTimeMillis()+ if (now - lastAudioRendererRecoveryAtMs < AUDIO_RENDERER_RECOVERY_COOLDOWN_MS) {+ Log.e(+ TAG,+ "audio-renderer-failed source=$source target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"+ )+ _error.tryEmit(+ PlayerError.DecoderError(+ error.message ?: "Audio playback failed for this stream."+ )+ )+ return+ }++ lastAudioRendererRecoveryAtMs = now+ val wasPlaying = exoPlayer?.playWhenReady ?: true+ val seekPosition = exoPlayer?.currentPosition+ ?.takeIf { currentResolvedStreamType == ResolvedStreamType.PROGRESSIVE && it > 0L }++ Log.w(+ TAG,+ "audio-renderer-recover source=$source target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"+ )++ retryJob?.cancel()+ retryJob = null+ _retryStatus.value = null+ prepareInternal(+ streamInfo = streamInfo,+ preserveRetryState = false,+ seekPositionMs = seekPosition,+ autoPlay = wasPlaying+ )+ }+private fun handlePlaybackError(error: PlaybackException) {retryJob?.cancel()retryJob = nulldiff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex a70e39cd..e5ed6d35 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -9,6 +9,8 @@ import com.streamvault.domain.model.VideoFormatimport androidx.media3.common.PlaybackExceptionimport com.streamvault.player.playback.PlaybackErrorCategoryimport com.streamvault.player.playback.PlayerErrorClassifier+import com.streamvault.player.timeshift.LiveTimeshiftState+import com.streamvault.player.timeshift.TimeshiftConfigimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.StateFlow@@ -33,6 +35,7 @@ interface PlayerEngine {val availableSubtitleTracks: StateFlow<List<PlayerTrack>>val availableVideoTracks: StateFlow<List<PlayerTrack>>val playbackSpeed: StateFlow<Float>+ val timeshiftState: StateFlow<LiveTimeshiftState>/** In-stream metadata title (ICY / HLS). Null when the stream sends nothing. */val mediaTitle: StateFlow<String?>@@ -49,6 +52,11 @@ interface PlayerEngine {fun setVolume(volume: Float)fun setMuted(muted: Boolean)fun setPlaybackSpeed(speed: Float)+ fun startLiveTimeshift(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig)+ fun stopLiveTimeshift()+ fun seekToLiveEdge()+ fun pauseTimeshift()+ fun resumeTimeshift()fun setPreferredAudioLanguage(languageTag: String?)fun setSubtitleStyle(style: PlayerSubtitleStyle)fun setNetworkQualityPreferences(wifiMaxHeight: Int?, ethernetMaxHeight: Int?)diff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.ktnew file mode 100644index 00000000..d08f87ec--- /dev/null+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt@@ -0,0 +1,529 @@+package com.streamvault.player.timeshift++import android.content.Context+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import dagger.hilt.android.qualifiers.ApplicationContext+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.IOException+import java.net.URI+import java.util.Locale+import java.util.concurrent.atomic.AtomicLong+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActive+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request++internal interface LiveTimeshiftManager {+ val state: StateFlow<LiveTimeshiftState>+ suspend fun startSession(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig)+ suspend fun stopSession()+ suspend fun createSnapshot(): LiveTimeshiftSnapshot?+}++@Singleton+internal class DefaultLiveTimeshiftManager @Inject constructor(+ @param:ApplicationContext private val context: Context,+ private val okHttpClient: OkHttpClient+) : LiveTimeshiftManager {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val mutex = Mutex()+ private val _state = MutableStateFlow(LiveTimeshiftState())+ override val state: StateFlow<LiveTimeshiftState> = _state.asStateFlow()++ private var activeSession: Session? = null++ override suspend fun startSession(streamInfo: StreamInfo, channelKey: String, config: TimeshiftConfig) {+ withContext(Dispatchers.IO) {+ mutex.withLock {+ stopSessionLocked()+ if (!config.enabled) {+ _state.value = LiveTimeshiftState(enabled = false, status = LiveTimeshiftStatus.DISABLED)+ return@withLock+ }+ val support = determineSupport(streamInfo)+ if (!support.supported) {+ _state.value = LiveTimeshiftState(+ enabled = true,+ supported = false,+ status = LiveTimeshiftStatus.UNSUPPORTED,+ message = support.reason+ )+ return@withLock+ }+ val backend = chooseBackend()+ val sessionDir = File(context.cacheDir, "timeshift/${channelKey.hashCode()}-${System.currentTimeMillis()}").apply { mkdirs() }+ val session = when (support.streamType) {+ StreamType.HLS -> HlsSession(streamInfo, config, backend, sessionDir)+ StreamType.MPEG_TS,+ StreamType.PROGRESSIVE,+ StreamType.UNKNOWN -> ProgressiveSession(streamInfo, config, backend, sessionDir)+ StreamType.DASH,+ StreamType.RTSP -> null+ }+ if (session == null) {+ _state.value = LiveTimeshiftState(+ enabled = true,+ supported = false,+ status = LiveTimeshiftStatus.UNSUPPORTED,+ message = "This live stream type cannot use local rewind yet."+ )+ return@withLock+ }+ activeSession = session+ _state.value = LiveTimeshiftState(+ enabled = true,+ supported = true,+ backend = backend,+ status = LiveTimeshiftStatus.PREPARING,+ message = "Preparing local live rewind…"+ )+ session.job = scope.launch {+ try {+ session.capture()+ } catch (t: Throwable) {+ _state.value = _state.value.copy(+ enabled = true,+ supported = true,+ backend = session.backend,+ status = LiveTimeshiftStatus.FAILED,+ message = t.message ?: "Local live rewind failed."+ )+ }+ }+ }+ }+ }++ override suspend fun stopSession() {+ withContext(Dispatchers.IO) {+ mutex.withLock {+ stopSessionLocked()+ _state.value = LiveTimeshiftState(enabled = false, status = LiveTimeshiftStatus.DISABLED)+ }+ }+ }++ override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {+ return withContext(Dispatchers.IO) {+ mutex.withLock {+ activeSession?.createSnapshot()+ }+ }+ }++ private suspend fun stopSessionLocked() {+ activeSession?.stop()+ activeSession = null+ }++ private fun chooseBackend(): LiveTimeshiftBackend {+ return try {+ context.cacheDir?.takeIf { (it.exists() || it.mkdirs()) && it.canWrite() }+ ?.let { LiveTimeshiftBackend.DISK }+ ?: LiveTimeshiftBackend.MEMORY+ } catch (_: Throwable) {+ LiveTimeshiftBackend.MEMORY+ }+ }++ private fun determineSupport(streamInfo: StreamInfo): SupportResult {+ if (streamInfo.drmInfo != null) {+ return SupportResult(false, "DRM-protected streams cannot use local rewind yet.", streamInfo.streamType)+ }+ val type = inferType(streamInfo)+ return when (type) {+ StreamType.RTSP -> SupportResult(false, "RTSP streams cannot use local rewind yet.", type)+ StreamType.DASH -> SupportResult(false, "DASH local rewind is not available in this version.", type)+ else -> SupportResult(true, null, type)+ }+ }++ private fun inferType(streamInfo: StreamInfo): StreamType {+ if (streamInfo.streamType != StreamType.UNKNOWN) return streamInfo.streamType+ val url = streamInfo.url.lowercase(Locale.ROOT)+ return when {+ url.endsWith(".m3u8") -> StreamType.HLS+ url.endsWith(".mpd") -> StreamType.DASH+ url.endsWith(".ts") -> StreamType.MPEG_TS+ url.startsWith("rtsp") -> StreamType.RTSP+ else -> StreamType.PROGRESSIVE+ }+ }++ private inner class SupportResult(+ val supported: Boolean,+ val reason: String?,+ val streamType: StreamType+ )++ private abstract inner class Session(+ val streamInfo: StreamInfo,+ val config: TimeshiftConfig,+ val backend: LiveTimeshiftBackend,+ val sessionDir: File+ ) {+ var job: Job? = null+ protected val sequence = AtomicLong(0L)+ protected val stateStartMs = System.currentTimeMillis()++ abstract suspend fun capture()+ abstract suspend fun createSnapshot(): LiveTimeshiftSnapshot?++ open suspend fun stop() {+ job?.cancel()+ sessionDir.deleteRecursively()+ }++ protected fun makeRequest(url: String) = Request.Builder().url(url).apply {+ streamInfo.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }+ streamInfo.headers.forEach { (key, value) -> header(key, value) }+ }.build()++ protected fun updateWindow(windowDurationMs: Long, message: String? = null) {+ val now = System.currentTimeMillis()+ _state.value = _state.value.copy(+ enabled = true,+ supported = true,+ backend = backend,+ status = if (windowDurationMs > 0L) LiveTimeshiftStatus.LIVE else LiveTimeshiftStatus.PREPARING,+ bufferStartMs = (now - windowDurationMs).coerceAtLeast(0L),+ bufferEndMs = now,+ liveEdgePositionMs = windowDurationMs,+ bufferedDurationMs = windowDurationMs,+ currentOffsetFromLiveMs = 0L,+ message = message ?: if (windowDurationMs > 0L) "Local live rewind ready." else "Preparing local live rewind…"+ )+ }++ protected fun resolveRelativeUrl(baseUrl: String, value: String): String {+ return runCatching { URI(baseUrl).resolve(value).toString() }.getOrDefault(value)+ }+ }++ private inner class ProgressiveSession(+ streamInfo: StreamInfo,+ config: TimeshiftConfig,+ backend: LiveTimeshiftBackend,+ sessionDir: File+ ) : Session(streamInfo, config, backend, sessionDir) {++ private val chunks = ArrayDeque<ProgressiveChunk>()+ private val chunkMutex = Mutex()++ override suspend fun capture() {+ val request = makeRequest(streamInfo.url)+ okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Timeshift stream failed with HTTP ${response.code}")+ val input = response.body?.byteStream() ?: throw IOException("Timeshift stream returned an empty body")+ input.use { source ->+ var current = createChunk()+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ while (scope.isActive) {+ currentCoroutineContext().ensureActive()+ val read = source.read(buffer)+ if (read <= 0) break+ current.write(buffer, read)+ if (System.currentTimeMillis() - current.startedAtMs >= PROGRESSIVE_CHUNK_MS) {+ finalizeChunk(current)+ current = createChunk()+ }+ }+ if (current.bytesWritten > 0L) {+ finalizeChunk(current)+ }+ }+ }+ }++ override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {+ val snapshotDir = File(sessionDir, "snapshot-progressive").apply {+ deleteRecursively()+ mkdirs()+ }+ val snapshotFile = File(snapshotDir, "buffer.ts")+ val orderedChunks = chunkMutex.withLock { chunks.toList() }+ if (orderedChunks.isEmpty()) return null+ snapshotFile.outputStream().use { output ->+ orderedChunks.forEach { chunk ->+ when {+ chunk.file != null && chunk.file.exists() -> chunk.file.inputStream().use { it.copyTo(output) }+ chunk.payload != null -> output.write(chunk.payload)+ }+ }+ }+ val durationMs = orderedChunks.sumOf { it.durationMs }+ return LiveTimeshiftSnapshot(+ url = snapshotFile.toURI().toString(),+ durationMs = durationMs,+ backend = backend+ )+ }++ private fun createChunk(): ActiveProgressiveChunk {+ val id = sequence.incrementAndGet()+ val targetFile = if (backend == LiveTimeshiftBackend.DISK) {+ File(sessionDir, "chunk-$id.ts")+ } else {+ null+ }+ return ActiveProgressiveChunk(+ id = id,+ startedAtMs = System.currentTimeMillis(),+ file = targetFile,+ output = if (targetFile != null) targetFile.outputStream().buffered() else ByteArrayOutputStream()+ )+ }++ private suspend fun finalizeChunk(active: ActiveProgressiveChunk) {+ active.output.flush()+ active.output.close()+ val endedAtMs = System.currentTimeMillis()+ val chunk = ProgressiveChunk(+ id = active.id,+ startedAtMs = active.startedAtMs,+ endedAtMs = endedAtMs,+ durationMs = (endedAtMs - active.startedAtMs).coerceAtLeast(1L),+ file = active.file,+ payload = if (backend == LiveTimeshiftBackend.MEMORY) (active.output as ByteArrayOutputStream).toByteArray() else null+ )+ val windowDuration = chunkMutex.withLock {+ chunks += chunk+ pruneProgressiveChunksLocked()+ chunks.sumOf { it.durationMs }+ }+ updateWindow(windowDuration)+ }++ private fun ActiveProgressiveChunk.write(buffer: ByteArray, read: Int) {+ output.write(buffer, 0, read)+ bytesWritten += read+ }++ private fun pruneProgressiveChunksLocked() {+ var totalDurationMs = chunks.sumOf { it.durationMs }+ while (totalDurationMs > config.depthMs && chunks.isNotEmpty()) {+ val removed = chunks.removeFirst()+ removed.file?.delete()+ totalDurationMs -= removed.durationMs+ }+ }+ }++ private inner class HlsSession(+ streamInfo: StreamInfo,+ config: TimeshiftConfig,+ backend: LiveTimeshiftBackend,+ sessionDir: File+ ) : Session(streamInfo, config, backend, sessionDir) {++ private val segments = ArrayDeque<HlsSegmentSnapshot>()+ private val segmentMutex = Mutex()++ override suspend fun capture() {+ var currentPlaylistUrl = streamInfo.url+ val seenSegments = linkedSetOf<String>()+ while (scope.isActive) {+ currentCoroutineContext().ensureActive()+ val playlistText = fetchText(currentPlaylistUrl)+ val parsed = parsePlaylist(currentPlaylistUrl, playlistText)+ when (parsed) {+ is ParsedHlsPlaylist.Master -> currentPlaylistUrl = parsed.bestVariantUrl+ is ParsedHlsPlaylist.Media -> {+ parsed.segments.forEach { remoteSegment ->+ currentCoroutineContext().ensureActive()+ if (!seenSegments.add(remoteSegment.uri)) return@forEach+ val bytes = fetchBytes(remoteSegment.uri)+ val retained = retainHlsSegment(remoteSegment, bytes)+ val windowDuration = segmentMutex.withLock {+ segments += retained+ pruneHlsSegmentsLocked()+ segments.sumOf { it.durationMs }+ }+ updateWindow(windowDuration)+ }+ if (parsed.endList) break+ delay((parsed.targetDurationSeconds.coerceAtLeast(2) * 1000L) / 2L)+ }+ }+ }+ }++ override suspend fun createSnapshot(): LiveTimeshiftSnapshot? {+ val snapshotDir = File(sessionDir, "snapshot-hls").apply {+ deleteRecursively()+ mkdirs()+ }+ val snapshotSegments = segmentMutex.withLock { segments.toList() }+ if (snapshotSegments.isEmpty()) return null+ val playlist = File(snapshotDir, "index.m3u8")+ val targetDurationSeconds = snapshotSegments.maxOf { ((it.durationMs + 999L) / 1000L).toInt().coerceAtLeast(1) }+ val body = buildString {+ appendLine("#EXTM3U")+ appendLine("#EXT-X-VERSION:3")+ appendLine("#EXT-X-TARGETDURATION:$targetDurationSeconds")+ appendLine("#EXT-X-MEDIA-SEQUENCE:0")+ snapshotSegments.forEachIndexed { index, segment ->+ val fileName = "segment-$index.ts"+ val outputFile = File(snapshotDir, fileName)+ when {+ segment.file != null && segment.file.exists() -> segment.file.copyTo(outputFile, overwrite = true)+ segment.payload != null -> outputFile.writeBytes(segment.payload)+ }+ appendLine("#EXTINF:${"%.3f".format(Locale.US, segment.durationMs / 1000.0)},")+ appendLine(fileName)+ }+ appendLine("#EXT-X-ENDLIST")+ }+ playlist.writeText(body)+ return LiveTimeshiftSnapshot(+ url = playlist.toURI().toString(),+ durationMs = snapshotSegments.sumOf { it.durationMs },+ backend = backend+ )+ }++ private fun retainHlsSegment(remote: RemoteHlsSegment, bytes: ByteArray): HlsSegmentSnapshot {+ val id = sequence.incrementAndGet()+ return if (backend == LiveTimeshiftBackend.DISK) {+ val target = File(sessionDir, "segment-$id.ts").apply { writeBytes(bytes) }+ HlsSegmentSnapshot(remote.uri, remote.durationMs, target, null)+ } else {+ HlsSegmentSnapshot(remote.uri, remote.durationMs, null, bytes)+ }+ }++ private fun pruneHlsSegmentsLocked() {+ var totalDurationMs = segments.sumOf { it.durationMs }+ while (totalDurationMs > config.depthMs && segments.isNotEmpty()) {+ val removed = segments.removeFirst()+ removed.file?.delete()+ totalDurationMs -= removed.durationMs+ }+ }++ private fun fetchText(url: String): String {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Timeshift playlist failed with HTTP ${response.code}")+ return response.body?.string().orEmpty()+ }+ }++ private fun fetchBytes(url: String): ByteArray {+ okHttpClient.newCall(makeRequest(url)).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Timeshift segment failed with HTTP ${response.code}")+ return response.body?.bytes() ?: ByteArray(0)+ }+ }++ private fun parsePlaylist(baseUrl: String, rawText: String): ParsedHlsPlaylist {+ val lines = rawText.lineSequence().map(String::trim).filter { it.isNotEmpty() }.toList()+ if (lines.any { it.startsWith("#EXT-X-STREAM-INF", ignoreCase = true) }) {+ val variants = mutableListOf<Pair<Int, String>>()+ var pendingBandwidth = 0+ lines.forEachIndexed { index, line ->+ if (line.startsWith("#EXT-X-STREAM-INF", ignoreCase = true)) {+ pendingBandwidth = Regex("""BANDWIDTH=(\d+)""")+ .find(line)+ ?.groupValues+ ?.getOrNull(1)+ ?.toIntOrNull()+ ?: 0+ val next = lines.getOrNull(index + 1)?.takeIf { !it.startsWith("#") } ?: return@forEachIndexed+ variants += pendingBandwidth to resolveRelativeUrl(baseUrl, next)+ }+ }+ val bestVariantUrl = variants.maxByOrNull { it.first }?.second+ ?: throw IOException("No playable HLS variants were available.")+ return ParsedHlsPlaylist.Master(bestVariantUrl)+ }++ var targetDurationSeconds = 6+ var endList = false+ val segments = mutableListOf<RemoteHlsSegment>()+ var currentDurationMs = 6_000L+ lines.forEach { line ->+ when {+ line.startsWith("#EXT-X-TARGETDURATION", ignoreCase = true) -> {+ targetDurationSeconds = line.substringAfter(':', "6").toIntOrNull() ?: 6+ }+ line.startsWith("#EXTINF", ignoreCase = true) -> {+ currentDurationMs = ((line.substringAfter(':').substringBefore(',').toDoubleOrNull() ?: 6.0) * 1000.0).toLong()+ }+ line.startsWith("#EXT-X-ENDLIST", ignoreCase = true) -> endList = true+ line.startsWith("#") -> Unit+ else -> {+ segments += RemoteHlsSegment(+ uri = resolveRelativeUrl(baseUrl, line),+ durationMs = currentDurationMs.coerceAtLeast(1L)+ )+ }+ }+ }+ return ParsedHlsPlaylist.Media(+ targetDurationSeconds = targetDurationSeconds,+ endList = endList,+ segments = segments+ )+ }+ }++ private data class ProgressiveChunk(+ val id: Long,+ val startedAtMs: Long,+ val endedAtMs: Long,+ val durationMs: Long,+ val file: File?,+ val payload: ByteArray?+ )++ private data class ActiveProgressiveChunk(+ val id: Long,+ val startedAtMs: Long,+ val file: File?,+ val output: java.io.OutputStream,+ var bytesWritten: Long = 0L+ )++ private data class HlsSegmentSnapshot(+ val remoteUrl: String,+ val durationMs: Long,+ val file: File?,+ val payload: ByteArray?+ )++ private data class RemoteHlsSegment(+ val uri: String,+ val durationMs: Long+ )++ private sealed interface ParsedHlsPlaylist {+ data class Master(val bestVariantUrl: String) : ParsedHlsPlaylist+ data class Media(+ val targetDurationSeconds: Int,+ val endList: Boolean,+ val segments: List<RemoteHlsSegment>+ ) : ParsedHlsPlaylist+ }++ private companion object {+ private const val PROGRESSIVE_CHUNK_MS = 2_000L+ }+}diff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.ktnew file mode 100644index 00000000..a2b82a83--- /dev/null+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftModels.kt@@ -0,0 +1,47 @@+package com.streamvault.player.timeshift++data class TimeshiftConfig(+ val enabled: Boolean = false,+ val depthMinutes: Int = 30+) {+ val depthMs: Long = depthMinutes.coerceIn(15, 60) * 60_000L+}++enum class LiveTimeshiftBackend {+ NONE,+ DISK,+ MEMORY+}++enum class LiveTimeshiftStatus {+ DISABLED,+ UNSUPPORTED,+ PREPARING,+ LIVE,+ PAUSED_BEHIND_LIVE,+ PLAYING_BEHIND_LIVE,+ BUFFERING,+ FAILED+}++data class LiveTimeshiftState(+ val enabled: Boolean = false,+ val supported: Boolean = false,+ val backend: LiveTimeshiftBackend = LiveTimeshiftBackend.NONE,+ val status: LiveTimeshiftStatus = LiveTimeshiftStatus.DISABLED,+ val bufferStartMs: Long = 0L,+ val bufferEndMs: Long = 0L,+ val liveEdgePositionMs: Long = 0L,+ val currentOffsetFromLiveMs: Long = 0L,+ val bufferedDurationMs: Long = 0L,+ val message: String? = null+) {+ val canSeekToLive: Boolean = supported && currentOffsetFromLiveMs > 1_000L+ val isActive: Boolean = enabled && supported && status != LiveTimeshiftStatus.DISABLED && status != LiveTimeshiftStatus.UNSUPPORTED+}++internal data class LiveTimeshiftSnapshot(+ val url: String,+ val durationMs: Long,+ val backend: LiveTimeshiftBackend+)