package tv.tivilux.nativeplayer.ui.components import android.os.SystemClock import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.lifecycle.Lifecycle import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.media3.common.MediaItem import androidx.media3.common.PlaybackException import androidx.media3.common.Player import androidx.media3.common.Timeline import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.analytics.AnalyticsListener import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.isActive import kotlinx.coroutines.delay import java.util.UUID import tv.tivilux.nativeplayer.data.LiveRecoveryPolicy import tv.tivilux.nativeplayer.data.LiveStreamTrace /** One recovery owner for the existing shared player; never runs for VOD or MultiView. */ @androidx.annotation.OptIn(UnstableApi::class) @Composable internal fun rememberLivePlaybackSessionStatus( player: ExoPlayer, url: String?, candidates: List, autoPlay: Boolean, diagnosticChannelKey: String, diagnosticChannelName: String, ): String? { val lifecycle = LocalLifecycleOwner.current.lifecycle var status by remember(player, url) { mutableStateOf(null) } LaunchedEffect(player, url, autoPlay, lifecycle) { if (url.isNullOrBlank()) return@LaunchedEffect // One cancellable tune/recovery job. ON_STOP cancels it; foreground return // starts only this effect's latest URL. Guide/fullscreen keeps the same effect. lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { val sessionContext = currentCoroutineContext() val sessionId = UUID.randomUUID().toString() var attempt = 0L var ownedMediaId: String? = null var failure = false val eventWindow = Timeline.Window() val listener = object : AnalyticsListener { override fun onPlayerError(eventTime: AnalyticsListener.EventTime, error: PlaybackException) { if (!sessionContext.isActive || ownedMediaId == null) return val timeline = eventTime.timeline if (eventTime.windowIndex !in 0 until timeline.windowCount) return val eventId = timeline.getWindow(eventTime.windowIndex, eventWindow).mediaItem.mediaId if (eventId == ownedMediaId && player.currentMediaItem?.mediaId == ownedMediaId) { failure = true } } } player.addAnalyticsListener(listener) try { val sources = if (url in candidates) candidates.dropWhile { it != url } else listOf(url) var sourceIndex = sources.indexOf(player.currentMediaItem?.localConfiguration?.uri?.toString()) .coerceAtLeast(0) var currentSource = sources[sourceIndex] suspend fun prepareFresh(): Boolean { sessionContext.ensureActive() try { // Invalidate callbacks before requesting Media3 loader/source teardown. // Teardown is asynchronous inside Media3; a fixed sleep cannot acknowledge it. ownedMediaId?.let { LiveStreamTrace.ending(it) } ownedMediaId = null player.playWhenReady = false player.stop() player.clearMediaItems() } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { failure = true return false } return try { sessionContext.ensureActive() ownedMediaId = "$sessionId:${++attempt}" val format = if (android.net.Uri.parse(currentSource).path?.endsWith(".m3u8", true) == true) "HLS" else "TS/OTHER" LiveStreamTrace.begin(ownedMediaId!!, format, diagnosticChannelKey, diagnosticChannelName) player.setMediaItem(MediaItem.Builder().setUri(currentSource).setMediaId(ownedMediaId!!).build()) player.prepare() player.playWhenReady = autoPlay failure = false true } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { // Missing/unsupported source factories and malformed provider URLs must not escape. failure = true false } } // Initial preparation waits for foreground; channel changes cancel this effect immediately. while (!lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) delay(250) if (!prepareFresh() && sourceIndex < sources.lastIndex) { sourceIndex++ currentSource = sources[sourceIndex] prepareFresh() } val policy = LiveRecoveryPolicy(SystemClock.elapsedRealtime()) var lastPosition = player.currentPosition var lastFrames = -1 var firstSample = true var reconnectStarted = 0L while (true) { delay(1_000) sessionContext.ensureActive() // Another owner clearing/replacing this player must never revive this session. if (ownedMediaId != null && player.currentMediaItem?.mediaId != ownedMediaId) return@repeatOnLifecycle val now = SystemClock.elapsedRealtime() val foreground = lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) val active = foreground && autoPlay && player.playWhenReady && player.playbackSuppressionReason == Player.PLAYBACK_SUPPRESSION_REASON_NONE && (player.playbackState != Player.STATE_IDLE || failure || player.playerError != null) val counters = player.videoDecoderCounters counters?.ensureUpdated() val frames = counters?.renderedOutputBufferCount ?: -1 val position = player.currentPosition // Video frames catch frozen video while audio/position continues. Audio-only feeds use time. val hasVideo = player.videoFormat != null && frames >= 0 val progressed = !firstSample && player.playbackState == Player.STATE_READY && (if (hasVideo) frames > lastFrames else position > lastPosition) firstSample = false lastFrames = frames lastPosition = position if (progressed && active && player.playerError == null) { failure = false status = null reconnectStarted = 0L } if (!active) { status = null; reconnectStarted = 0L } val action = policy.sample(now, active, progressed, failure || player.playerError != null) if (action > 0) { status = "Reconnecting..." reconnectStarted = now try { val hls = android.net.Uri.parse(currentSource).path?.endsWith(".m3u8", true) == true if (hls && sourceIndex < sources.lastIndex) { sourceIndex++ currentSource = sources[sourceIndex] prepareFresh() } else when (action) { 1 -> { if (player.playerError != null || player.playbackState == Player.STATE_IDLE) { player.prepare() player.playWhenReady = true failure = false } else if (player.isCurrentMediaItemSeekable) { // Flush/retry at the current position first; live-edge seek is stage two. player.seekTo(player.currentPosition) player.playWhenReady = true } else { // prepare() is a no-op for a frozen READY progressive/TS source. // Unseekable live streams need a fresh loader on this same player. prepareFresh() } } 2 -> { if (player.isCurrentMediaItemLive && player.isCurrentMediaItemSeekable) { player.seekToDefaultPosition() player.prepare() player.playWhenReady = true failure = false } else prepareFresh() } else -> prepareFresh() } } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { failure = true } } if (policy.isExhausted() && reconnectStarted > 0L && now - reconnectStarted >= 20_000L) { status = "Stream unavailable — change channel to retry" } } } finally { // A cancelled owner may finish after a newer effect has started. Its // cleanup must never stop that newer owner's MediaItem. player.removeAnalyticsListener(listener) val stillOwnsMedia = ownedMediaId != null && player.currentMediaItem?.mediaId == ownedMediaId ownedMediaId?.let { LiveStreamTrace.ending(it) } ownedMediaId = null if (stillOwnsMedia) { player.playWhenReady = false player.stop() player.clearMediaItems() } } } } return status }