Skip to content

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

fixed zapping connection issue

David Nashash3745e92146f3
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
index ca5daebf..65b4af13 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt
@@ -79,6 +79,16 @@ internal suspend fun <T> withScopedScrubbingMode(
}
}
+internal fun releaseOutgoingLiveZapPlayback(
+ stopPlayback: () -> Unit,
+ stopLiveTimeshift: () -> Unit,
+ clearPreload: () -> Unit
+) {
+ stopPlayback()
+ stopLiveTimeshift()
+ clearPreload()
+}
+
fun PlayerViewModel.playNext() {
clearNumericChannelInput()
if (channelList.isEmpty()) return
@@ -189,6 +199,11 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =
previousChannelIndex = currentChannelIndex
}
val requestVersion = beginPlaybackSession()
+ releaseOutgoingLiveZapPlayback(
+ stopPlayback = playerEngine::stop,
+ stopLiveTimeshift = playerEngine::stopLiveTimeshift,
+ clearPreload = { playerEngine.preload(null) }
+ )
val channel = channelList[index]
currentChannelIndex = index
currentContentId = channel.id
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt
index 640aceb0..20e2edc6 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerZapActionsTest.kt
@@ -52,4 +52,17 @@ class PlayerZapActionsTest {
assertThat(states).containsExactly(true, false).inOrder()
}
-}
\ No newline at end of file
+
+ @Test
+ fun `releaseOutgoingLiveZapPlayback closes active fetchers before clearing preload`() {
+ val calls = mutableListOf<String>()
+
+ releaseOutgoingLiveZapPlayback(
+ stopPlayback = { calls += "stopPlayback" },
+ stopLiveTimeshift = { calls += "stopLiveTimeshift" },
+ clearPreload = { calls += "clearPreload" }
+ )
+
+ assertThat(calls).containsExactly("stopPlayback", "stopLiveTimeshift", "clearPreload").inOrder()
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 4a37209e..2ba8b71c 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -24,6 +24,7 @@ import androidx.media3.exoplayer.analytics.AnalyticsListener
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.mediacodec.MediaCodecInfo
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
+import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
import androidx.media3.session.MediaSession
@@ -108,6 +109,12 @@ class Media3PlayerEngine @Inject constructor(
private const val KNOWN_BAD_FAILURE_THRESHOLD = 3
private const val MEDIA_SESSION_ID_PREFIX = "streamvault"
private val nextMediaSessionInstanceId = AtomicLong(1L)
+ private val LIVE_RESOLVED_STREAM_TYPES = setOf(
+ ResolvedStreamType.HLS,
+ ResolvedStreamType.SMOOTH_STREAMING,
+ ResolvedStreamType.MPEG_TS_LIVE,
+ ResolvedStreamType.RTSP
+ )
}
var constrainResolutionForMultiView: Boolean = false
@@ -339,6 +346,9 @@ class Media3PlayerEngine @Inject constructor(
preload = false,
playbackStarted = { playbackStarted }
)
+ val resumePositionMs = player.currentPosition.takeIf {
+ it > 0L && playbackPlan.resolvedStreamType !in LIVE_RESOLVED_STREAM_TYPES
+ }
lastStreamInfo = streamInfo
lastMediaId = mediaSourceFactory.mediaIdFor(streamInfo)
@@ -358,8 +368,9 @@ class Media3PlayerEngine @Inject constructor(
preload = false
).second
- player.setMediaSource(mediaSource, /* resetPosition= */ false)
+ replaceMediaSource(player, mediaSource, resetPosition = false, reason = "renew-url")
player.prepare()
+ resumePositionMs?.let(player::seekTo)
Log.i(
TAG,
@@ -382,8 +393,20 @@ class Media3PlayerEngine @Inject constructor(
override fun stop() {
retryJob?.cancel()
- exoPlayer?.stop()
+ retryJob = null
+ preloadCoordinator.invalidate("stop")
+ exoPlayer?.let { player ->
+ releaseCurrentMedia(player, reason = "stop")
+ }
+ playbackStarted = false
+ hasRenderedFirstVideoFrame = false
+ lastStreamInfo = null
+ lastMediaId = null
_playbackState.value = PlaybackState.IDLE
+ _isPlaying.value = false
+ _mediaTitle.value = null
+ statsCollector.stop()
+ statsCollector.reset()
audioFocusController.onPauseOrStop()
}
@@ -856,12 +879,7 @@ class Media3PlayerEngine @Inject constructor(
val nextDecoderPolicy = recoveryDecoderPolicyOverride ?: resolveActiveDecoderPolicy(
policyModeFor(requestedDecoderMode, preferredDecoderMode)
)
- val isLiveBuffer = currentResolvedStreamType in setOf(
- ResolvedStreamType.HLS,
- ResolvedStreamType.SMOOTH_STREAMING,
- ResolvedStreamType.MPEG_TS_LIVE,
- ResolvedStreamType.RTSP
- )
+ val isLiveBuffer = currentResolvedStreamType in LIVE_RESOLVED_STREAM_TYPES
val previousDecoderPolicy = activeDecoderPolicy
val needsRecreate = activeDecoderMode != preferredDecoderMode ||
previousDecoderPolicy != nextDecoderPolicy ||
@@ -900,16 +918,11 @@ class Media3PlayerEngine @Inject constructor(
preload = false
).second
preloadCoordinator.onPlaybackStarted(mediaId)
- player.setMediaSource(mediaSource)
+ replaceMediaSource(player, mediaSource, resetPosition = true, reason = "prepare")
player.prepare()
seekPositionMs?.takeIf { it > 0L }?.let(player::seekTo)
- val isLive = currentResolvedStreamType in setOf(
- ResolvedStreamType.HLS,
- ResolvedStreamType.SMOOTH_STREAMING,
- ResolvedStreamType.MPEG_TS_LIVE,
- ResolvedStreamType.RTSP
- )
+ val isLive = currentResolvedStreamType in LIVE_RESOLVED_STREAM_TYPES
val osContentType = if (isLive) {
android.media.AudioAttributes.CONTENT_TYPE_MUSIC
} else {
@@ -944,6 +957,24 @@ class Media3PlayerEngine @Inject constructor(
// The caller (prepareInternal) will create a fresh player and set it up fully.
}
+ private fun replaceMediaSource(
+ player: ExoPlayer,
+ mediaSource: MediaSource,
+ resetPosition: Boolean,
+ reason: String
+ ) {
+ releaseCurrentMedia(player, reason)
+ player.setMediaSource(mediaSource, resetPosition)
+ }
+
+ private fun releaseCurrentMedia(player: ExoPlayer, reason: String) {
+ if (player.mediaItemCount == 0 && player.playbackState == Player.STATE_IDLE) return
+ player.playWhenReady = false
+ player.stop()
+ player.clearMediaItems()
+ Log.i(TAG, "released current media reason=$reason")
+ }
+
private fun getOrCreatePlayer(): ExoPlayer {
check(!isDisposed) { "Cannot create a player after terminal release" }
return exoPlayer ?: createPlayer().also { player ->
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index a965a7ec..d2970629 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -64,6 +64,8 @@ interface PlayerEngine {
fun renewStreamUrl(streamInfo: StreamInfo)
fun play()
fun pause()
+
+ /** Stop playback and release the active media source/network connection. */
fun stop()
fun seekTo(positionMs: Long)
fun seekForward(ms: Long = 10_000)
diff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
index f13f277a..5b38c67d 100644
--- a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
@@ -32,6 +32,7 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
+import okhttp3.Response
internal interface LiveTimeshiftManager {
val state: StateFlow<LiveTimeshiftState>
@@ -281,11 +282,13 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
val effectiveDepthMs: Long = config.effectiveDepthMs(backend)
protected val sequence = AtomicLong(0L)
protected val stateStartMs = System.currentTimeMillis()
+ @Volatile private var activeCall: okhttp3.Call? = null
abstract suspend fun capture()
abstract suspend fun createSnapshot(): LiveTimeshiftSnapshot?
open suspend fun stop() {
+ activeCall?.cancel()
job?.cancel()
sessionDir.deleteRecursively()
}
@@ -295,6 +298,27 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
streamInfo.headers.forEach { (key, value) -> header(key, value) }
}.build()
+ protected fun trackCall(request: Request): okhttp3.Call {
+ val call = okHttpClient.newCall(request)
+ activeCall = call
+ return call
+ }
+
+ protected fun clearTrackedCall(call: okhttp3.Call) {
+ if (activeCall === call) {
+ activeCall = null
+ }
+ }
+
+ protected fun <T> executeRequest(request: Request, block: (Response) -> T): T {
+ val call = trackCall(request)
+ return try {
+ call.execute().use(block)
+ } finally {
+ clearTrackedCall(call)
+ }
+ }
+
protected fun updateWindow(windowDurationMs: Long, message: String? = null) {
val now = System.currentTimeMillis()
_state.value = _state.value.copy(
@@ -335,14 +359,8 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
private val chunks = ArrayDeque<ProgressiveChunk>()
private val chunkMutex = Mutex()
- @Volatile private var activeCall: okhttp3.Call? = null
private var runningChunkDurationMs = 0L
- override suspend fun stop() {
- activeCall?.cancel()
- super.stop()
- }
-
override suspend fun capture() {
var retryDelay = 1_000L
var retryCount = 0
@@ -350,30 +368,33 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
currentCoroutineContext().ensureActive()
try {
val request = makeRequest(streamInfo.url)
- val call = okHttpClient.newCall(request)
- activeCall = call
- call.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")
- retryDelay = 1_000L
- retryCount = 0
- input.use { source ->
- var current = createChunk()
- val buffer = ByteArray(PROGRESSIVE_READ_BUFFER_SIZE)
- while (true) {
- currentCoroutineContext().ensureActive()
- val read = source.read(buffer)
- if (read <= 0) break
- current.write(buffer, read)
- if (System.currentTimeMillis() - current.startedAtMs >= PROGRESSIVE_CHUNK_MS) {
+ val call = trackCall(request)
+ try {
+ call.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")
+ retryDelay = 1_000L
+ retryCount = 0
+ input.use { source ->
+ var current = createChunk()
+ val buffer = ByteArray(PROGRESSIVE_READ_BUFFER_SIZE)
+ while (true) {
+ 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)
- current = createChunk()
}
}
- if (current.bytesWritten > 0L) {
- finalizeChunk(current)
- }
}
+ } finally {
+ clearTrackedCall(call)
}
break // stream ended normally
} catch (t: Throwable) {
@@ -574,7 +595,7 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
}
private fun streamSegmentToDisk(url: String, target: File) {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("Timeshift segment failed with HTTP ${response.code}")
val body = response.body ?: throw IOException("Timeshift segment returned an empty body")
body.byteStream().use { input -> target.outputStream().use { output -> input.copyTo(output, bufferSize = PROGRESSIVE_READ_BUFFER_SIZE) } }
@@ -590,16 +611,16 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
}
private fun fetchText(url: String): String {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ return executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("Timeshift playlist failed with HTTP ${response.code}")
- return response.body?.string().orEmpty()
+ response.body?.string().orEmpty()
}
}
private fun fetchBytes(url: String): ByteArray {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ return executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("Timeshift segment failed with HTTP ${response.code}")
- return response.body?.bytes() ?: ByteArray(0)
+ response.body?.bytes() ?: ByteArray(0)
}
}
@@ -840,7 +861,7 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
}
private fun streamSegmentToDisk(url: String, target: File) {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("DASH segment fetch failed: HTTP ${response.code}")
val body = response.body ?: throw IOException("DASH segment returned empty body")
body.byteStream().use { input -> target.outputStream().use { out -> input.copyTo(out, bufferSize = PROGRESSIVE_READ_BUFFER_SIZE) } }
@@ -848,16 +869,16 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
}
private fun fetchText(url: String): String {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ return executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("MPD fetch failed: HTTP ${response.code}")
- return response.body?.string().orEmpty()
+ response.body?.string().orEmpty()
}
}
private fun fetchBytes(url: String): ByteArray {
- okHttpClient.newCall(makeRequest(url)).execute().use { response ->
+ return executeRequest(makeRequest(url)) { response ->
if (!response.isSuccessful) throw IOException("DASH segment fetch failed: HTTP ${response.code}")
- return response.body?.bytes() ?: ByteArray(0)
+ response.body?.bytes() ?: ByteArray(0)
}
}