--- build72/app/build.gradle.kts +++ build73/app/build.gradle.kts @@ -12,8 +12,8 @@ applicationId = "tv.tivilux.nativeplayer" minSdk = 23 targetSdk = 35 - versionCode = 72 - versionName = "0.4.56" + versionCode = 73 + versionName = "0.4.57" buildConfigField("String", "DEFAULT_SERVER_URL", "\"http://xtreamview.net\"") buildConfigField("String", "UPDATE_MANIFEST_URL", "\"https://play.theappdrop.store/tivilux-updates/latest.json\"") --- build72/app/src/main/java/tv/tivilux/nativeplayer/ui/TiviLuxApp.kt +++ build73/app/src/main/java/tv/tivilux/nativeplayer/ui/TiviLuxApp.kt @@ -126,13 +126,15 @@ // Never allow Live/VOD audio to survive after TiviLux leaves the foreground. // MainActivity removes the task for an explicit HOME/app-switch. This observer is - // the playback safety net: ON_STOP pauses both shared players immediately, before + // the playback safety net: ON_STOP stops/clears Live TV and pauses VOD immediately, before // Compose disposal/release finishes tearing the Activity down. HOME then removes // the task, which disposes and releases the players completely. DisposableEffect(lifecycleOwner, sharedLivePlayer, sharedVodPlayer) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_STOP) { - sharedLivePlayer.pause() + sharedLivePlayer.playWhenReady = false + sharedLivePlayer.stop() + sharedLivePlayer.clearMediaItems() sharedVodPlayer.pause() } } --- build72/app/src/main/java/tv/tivilux/nativeplayer/ui/components/LivePlaybackSession.kt +++ build73/app/src/main/java/tv/tivilux/nativeplayer/ui/components/LivePlaybackSession.kt @@ -2,20 +2,27 @@ import android.os.SystemClock import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf 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 /** One recovery owner for the existing shared player; never runs for VOD or MultiView. */ @@ -29,132 +36,159 @@ ): String? { val lifecycle = LocalLifecycleOwner.current.lifecycle var status by remember(player, url) { mutableStateOf(null) } - // PlaybackException callbacks and synchronous media-source creation failures share one budget. - val failure = remember(player, url) { mutableStateOf(false) } - DisposableEffect(player, url) { - val listener = object : Player.Listener { - override fun onPlayerError(error: PlaybackException) { failure.value = true } - } - player.addListener(listener) - onDispose { player.removeListener(listener) } - } - LaunchedEffect(player, url, autoPlay, lifecycle) { if (url.isNullOrBlank()) return@LaunchedEffect - 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 { - val outgoingSource = player.currentMediaItem?.localConfiguration?.uri?.toString() + // 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 { - // Hard handoff: stop consumption first and remove the old MediaItem so Media3 - // releases its MediaSource/DataSource before the replacement can be prepared. - player.playWhenReady = false - player.stop() - player.clearMediaItems() - } catch (_: Exception) { - failure.value = true - return false - } - // Keep this cancellable delay OUTSIDE the broad media-source catch. If another channel - // is selected during the drain window, LaunchedEffect cancellation must win immediately - // so this stale tune can never continue on and reopen an intermediate channel. - if (!outgoingSource.isNullOrBlank() && outgoingSource != currentSource) { - delay(180L) - } - return try { - player.setMediaItem(MediaItem.fromUri(currentSource)) - player.prepare() - player.playWhenReady = autoPlay - failure.value = false - true - } catch (_: Exception) { - // Missing/unsupported source factories and malformed provider URLs must not escape. - failure.value = true - false - } - } - // Initial preparation waits for foreground; channel changes cancel this effect immediately. - while (!lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) delay(250) - if (player.currentMediaItem?.localConfiguration?.uri?.toString() != currentSource) { - if (!prepareFresh() && sources.size > 1) { - sourceIndex++ - currentSource = sources[sourceIndex] - prepareFresh() - } - } else if (player.playbackState == Player.STATE_IDLE) { - prepareFresh() - } - val policy = LiveRecoveryPolicy(SystemClock.elapsedRealtime()) - var lastPosition = player.currentPosition - var lastFrames = -1 - var firstSample = true - var reconnectStarted = 0L - while (true) { - delay(1_000) - 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.value || 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.value = false - status = null - reconnectStarted = 0L - } - if (!active) { status = null; reconnectStarted = 0L } - val action = policy.sample(now, active, progressed, failure.value || 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.value = 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. + 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 = 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}" + 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() } - } - 2 -> { - if (player.isCurrentMediaItemLive && player.isCurrentMediaItemSeekable) { - player.seekToDefaultPosition() - player.prepare() - player.playWhenReady = true - failure.value = false - } else prepareFresh() - } - else -> prepareFresh() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { failure = true } } - } catch (_: Exception) { failure.value = true } - } - if (policy.isExhausted() && reconnectStarted > 0L && now - reconnectStarted >= 20_000L) { - status = "Stream unavailable — change channel to retry" + 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 = null + if (stillOwnsMedia) { + player.playWhenReady = false + player.stop() + player.clearMediaItems() + } } } } --- build72/latest.json +++ build73/latest.json @@ -1,13 +1,13 @@ { - "versionCode": 72, - "versionName": "0.4.56", - "apkUrl": "https://play.theappdrop.store/tivilux-updates/TiviLux-Native-v0.4.56.apk", + "versionCode": 73, + "versionName": "0.4.57", + "apkUrl": "https://play.theappdrop.store/tivilux-updates/TiviLux-Native-v0.4.57.apk", "required": false, "sha256": "", "notes": [ - "Fixed old Live TV provider sessions lingering after channel changes", - "Live channel switches now stop and clear the outgoing Media3 source before opening the replacement stream", - "Rapid tune changes cancel stale intermediate handoffs while retaining the same single shared ExoPlayer", - "Preserves HLS recovery, Guide/fullscreen playback, Sports, Favorites, profiles and Settings" + "Live TV tune/recovery work now ends with its owning playback session", + "Removed the fixed 180 ms channel-switch delay", + "Live TV stops and clears media when backgrounded; obsolete error callbacks are filtered", + "Existing buffer, HLS, decoder and HTTP tuning retained" ] } --- build72/updates/latest.json +++ build73/updates/latest.json @@ -1,13 +1,13 @@ { - "versionCode": 72, - "versionName": "0.4.56", - "apkUrl": "https://play.theappdrop.store/tivilux-updates/TiviLux-Native-v0.4.56.apk", + "versionCode": 73, + "versionName": "0.4.57", + "apkUrl": "https://play.theappdrop.store/tivilux-updates/TiviLux-Native-v0.4.57.apk", "required": false, "sha256": "", "notes": [ - "Fixed old Live TV provider sessions lingering after channel changes", - "Live channel switches now stop and clear the outgoing Media3 source before opening the replacement stream", - "Rapid tune changes cancel stale intermediate handoffs while retaining the same single shared ExoPlayer", - "Preserves HLS recovery, Guide/fullscreen playback, Sports, Favorites, profiles and Settings" + "Live TV tune/recovery work now ends with its owning playback session", + "Removed the fixed 180 ms channel-switch delay", + "Live TV stops and clears media when backgrounded; obsolete error callbacks are filtered", + "Existing buffer, HLS, decoder and HTTP tuning retained" ] }