Skip to content

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

Improve live playback recovery diagnostics

Basri Kahveci873086e13031
diff --git a/AGENTS.md b/AGENTS.md
index f449b672..37db04e4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,3 +7,85 @@ Rules:
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
+
+## StreamVault emulator orientation
+
+When starting the emulator with StreamVault, always ensure the visible device frame
+and the app orientation are aligned before playback debugging. The known-good
+orientation from the debugging session is the emulator in landscape with the app
+upright at Android `ROTATION_270`.
+
+Use:
+
+```bash
+adb shell cmd window set-ignore-orientation-request true
+adb shell cmd window user-rotation lock 3
+```
+
+Verify with:
+
+```bash
+adb shell dumpsys window displays | rg "cur=|mRotation=|mUserRotationMode|mUserRotation=|mCurrentRotation|mDisplayRotation|ignoreOrientationRequest"
+```
+
+Expected state:
+- `cur=2340x1080 app=2340x1080`
+- `mDisplayRotation=ROTATION_270`
+- `mRotation=3`
+- `mUserRotationMode=USER_ROTATION_LOCKED`
+- `mUserRotation=ROTATION_270`
+- `ignoreOrientationRequest=true`
+
+Do not treat `cur=2340x1080 app=2340x1080` alone as sufficient; the app can
+still be sideways or upside down if the emulator frame and Android rotation are
+not aligned. If the phone frame is portrait while the app is upright, rotate the
+emulator frame with `adb emu rotate`, then reapply the `ROTATION_270` lock above.
+
+## Live TV playback validation
+
+For live TV playback bugs, do not validate with a single screenshot, a short
+visual check, build success, install success, or launch success. Use frequent
+screenshots and log evidence from the emulator.
+
+Use a 2-second screenshot cadence for live TV stuckness checks. Capture long
+enough to pass the historical stuck window: at least 45 screenshots for roughly
+90 seconds, and prefer 61 screenshots for roughly 2 minutes when validating a
+fix that previously failed around the one-minute mark.
+
+Example:
+
+```bash
+mkdir -p /private/tmp/streamvault_live_validation
+for i in $(seq -w 0 60); do
+ adb exec-out screencap -p > /private/tmp/streamvault_live_validation/freq_${i}.png
+ stat -f "freq_${i} %z" /private/tmp/streamvault_live_validation/freq_${i}.png
+ sleep 2
+done
+```
+
+After capture, confirm frame progression with hashes:
+
+```bash
+shasum -a 256 /private/tmp/streamvault_live_validation/freq_*.png | awk '{print $1}' | sort | uniq | wc -l
+```
+
+Then confirm the player is still healthy:
+
+```bash
+adb shell dumpsys media_session | awk '/package=com.streamvault.app/{seen=1} seen && /metadata:/{print; getline; print; getline; print} seen && /state=PlaybackState/{print; exit}'
+adb logcat -d -v time > /private/tmp/streamvault_live_validation.log
+rg -n "fatal-error|live-recovery selected|live-recovery no-candidate|prepare resolvedStreamType=MPEG_TS_LIVE|source-malformed live-ts-fallback|Player stuck|state=ERROR" /private/tmp/streamvault_live_validation.log
+rg -n "retry category=|first-frame-success|prepare resolvedStreamType=HLS|read-progress streamType=HLS" /private/tmp/streamvault_live_validation.log | tail -80
+```
+
+A passing validation needs:
+- screenshots that keep changing through the full capture window
+- media session still in `PLAYING` with `error=null`
+- no fatal player error, no stuck-player timeout, and no unintended MPEG-TS
+ fallback
+- sanitized log evidence showing HLS prepare/read/first-frame or recovery
+ behavior
+
+Validate more than one live channel when the bug is reported as affecting live
+TV generally. Record the channel names, screenshot count, interval, unique hash
+count, media-session result, and log findings in the final report.
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3b505cc5..223a1f03 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -120,6 +120,12 @@
android:launchMode="singleTask"
android:theme="@style/Theme.StreamVault" />
+ <activity
+ android:name=".diagnostics.ExternalPlayerProbeActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:theme="@style/Theme.StreamVault" />
+
<service
android:name=".tvinput.StreamVaultTvInputService"
android:exported="true"
diff --git a/app/src/main/java/com/streamvault/app/diagnostics/ExternalPlayerProbeActivity.kt b/app/src/main/java/com/streamvault/app/diagnostics/ExternalPlayerProbeActivity.kt
new file mode 100644
index 00000000..f841febb
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/diagnostics/ExternalPlayerProbeActivity.kt
@@ -0,0 +1,96 @@
+package com.streamvault.app.diagnostics
+
+import android.content.Intent
+import android.os.Bundle
+import android.util.Log
+import androidx.activity.ComponentActivity
+import androidx.core.net.toUri
+import androidx.lifecycle.lifecycleScope
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.ChannelRepository
+import dagger.hilt.android.AndroidEntryPoint
+import javax.inject.Inject
+import kotlinx.coroutines.launch
+
+@AndroidEntryPoint
+class ExternalPlayerProbeActivity : ComponentActivity() {
+ @Inject
+ lateinit var channelRepository: ChannelRepository
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ lifecycleScope.launch {
+ launchExternalPlayer()
+ finish()
+ }
+ }
+
+ private suspend fun launchExternalPlayer() {
+ val channelId = intent.getLongExtra(EXTRA_CHANNEL_ID, -1L)
+ if (channelId <= 0L) {
+ Log.w(TAG, "external-player-probe missing channel id")
+ return
+ }
+
+ val channel = channelRepository.getChannel(channelId)
+ if (channel == null) {
+ Log.w(TAG, "external-player-probe channel not found channelId=$channelId")
+ return
+ }
+
+ val streamInfo = when (val result = channelRepository.getStreamInfo(channel)) {
+ is Result.Success -> result.data
+ is Result.Error -> {
+ Log.w(TAG, "external-player-probe resolve failed channelId=$channelId")
+ return
+ }
+ Result.Loading -> return
+ }
+
+ val url = if (intent.getBooleanExtra(EXTRA_FORCE_TS, false)) {
+ toMpegTsUrl(streamInfo.url)
+ } else {
+ streamInfo.url
+ }
+ val playerPackage = intent.getStringExtra(EXTRA_PLAYER_PACKAGE)
+ ?.takeIf(String::isNotBlank)
+ ?: DEFAULT_PLAYER_PACKAGE
+ val launchIntent = Intent(Intent.ACTION_VIEW)
+ .setDataAndType(url.toUri(), "video/*")
+ .setPackage(playerPackage)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+ runCatching { startActivity(launchIntent) }
+ .onSuccess {
+ Log.i(
+ TAG,
+ "external-player-probe launched channelId=$channelId " +
+ "playerPackage=$playerPackage forceTs=${intent.getBooleanExtra(EXTRA_FORCE_TS, false)}"
+ )
+ }
+ .onFailure { error ->
+ Log.w(TAG, "external-player-probe launch failed channelId=$channelId error=${error::class.java.simpleName}")
+ }
+ }
+
+ private fun toMpegTsUrl(url: String): String {
+ val queryStart = url.indexOf('?')
+ val base = if (queryStart >= 0) url.substring(0, queryStart) else url
+ val query = if (queryStart >= 0) url.substring(queryStart) else ""
+ return if (base.endsWith(HLS_EXTENSION, ignoreCase = true)) {
+ base.dropLast(HLS_EXTENSION.length) + MPEG_TS_EXTENSION + query
+ } else {
+ url
+ }
+ }
+
+ companion object {
+ const val EXTRA_CHANNEL_ID = "channel_id"
+ const val EXTRA_PLAYER_PACKAGE = "player_package"
+ const val EXTRA_FORCE_TS = "force_ts"
+ private const val DEFAULT_PLAYER_PACKAGE = "org.videolan.vlc"
+ private const val HLS_EXTENSION = ".m3u8"
+ private const val MPEG_TS_EXTENSION = ".ts"
+ private const val TAG = "ExternalPlayerProbe"
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
index d6253509..8daf8ea6 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamActions.kt
@@ -3,7 +3,6 @@ package com.streamvault.app.ui.screens.player
import androidx.lifecycle.viewModelScope
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.model.LiveChannelVariant
import kotlinx.coroutines.launch
fun PlayerViewModel.hasAlternateStream(): Boolean {
@@ -12,13 +11,15 @@ fun PlayerViewModel.hasAlternateStream(): Boolean {
}
if (currentContentType != ContentType.LIVE) return false
val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return false
- return nextLiveVariant(channel) != null ||
- selectNextAlternateUrl(
- candidateUrls = channel.alternativeStreams,
- currentStreamUrl = currentStreamUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession
- ) != null
+ return selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
+ currentStreamUrl = currentStreamUrl,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession,
+ preferXtreamTsFallback = false
+ ) != null
}
fun PlayerViewModel.tryAlternateStream(): Boolean {
@@ -30,9 +31,40 @@ fun PlayerViewModel.tryAlternateStream(): Boolean {
return tryAlternateStreamInternal(channel)
}
-internal fun PlayerViewModel.tryAlternateStreamInternal(channel: Channel): Boolean {
- nextLiveVariant(channel)?.let { nextVariant ->
- val updatedChannel = channel.withSelectedVariant(nextVariant.rawChannelId)?.sanitizedForPlayer() ?: return@let
+internal fun PlayerViewModel.tryAlternateStreamInternal(
+ channel: Channel,
+ preferXtreamTsFallback: Boolean = false,
+ allowXtreamTsFallback: Boolean = true
+): Boolean {
+ val candidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
+ currentStreamUrl = currentStreamUrl,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession,
+ preferXtreamTsFallback = preferXtreamTsFallback,
+ allowXtreamTsFallback = allowXtreamTsFallback
+ ) ?: run {
+ android.util.Log.w(
+ "PlayerVM",
+ "live-recovery no-candidate preferTsFallback=$preferXtreamTsFallback " +
+ "allowTsFallback=$allowXtreamTsFallback " +
+ "hasResolvedUrl=${currentResolvedPlaybackUrl.isNotBlank()} " +
+ "alternates=${channel.alternativeStreams.size} variants=${channel.variants.size}"
+ )
+ return false
+ }
+ android.util.Log.i(
+ "PlayerVM",
+ "live-recovery selected=${candidate.kind} preferTsFallback=$preferXtreamTsFallback " +
+ "allowTsFallback=$allowXtreamTsFallback"
+ )
+
+ if (candidate.kind == LiveRecoveryCandidateKind.VARIANT) {
+ val nextVariant = candidate.variant ?: return false
+ val updatedChannel = channel.withSelectedVariant(nextVariant.rawChannelId)?.sanitizedForPlayer()
+ ?: return false
val requestVersion = beginPlaybackSession()
triedAlternativeStreams.add(nextVariant.streamUrl)
currentContentId = updatedChannel.id
@@ -81,17 +113,17 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(channel: Channel): Boole
return true
}
- val nextStream = selectNextAlternateUrl(
- candidateUrls = channel.alternativeStreams,
- currentStreamUrl = currentStreamUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession
- ) ?: return false
-
val requestVersion = beginPlaybackSession()
+ val nextStream = candidate.url
triedAlternativeStreams.add(nextStream)
currentStreamUrl = nextStream
- updateStreamClass("Alternate")
+ updateStreamClass(
+ when (candidate.kind) {
+ LiveRecoveryCandidateKind.XTREAM_TS_FALLBACK -> "MPEG-TS fallback"
+ LiveRecoveryCandidateKind.ALTERNATE -> "Alternate"
+ LiveRecoveryCandidateKind.VARIANT -> "Variant"
+ }
+ )
viewModelScope.launch {
val streamInfo = resolvePlaybackStreamInfo(nextStream, channel.id, channel.providerId, ContentType.LIVE)
?: return@launch
@@ -102,16 +134,6 @@ internal fun PlayerViewModel.tryAlternateStreamInternal(channel: Channel): Boole
return true
}
-private fun PlayerViewModel.nextLiveVariant(channel: Channel): LiveChannelVariant? {
- return selectNextLiveVariant(
- variants = channel.variants,
- currentVariantId = channel.selectedVariantId.takeIf { it > 0 } ?: channel.id,
- currentStreamUrl = currentStreamUrl,
- triedAlternativeStreams = triedAlternativeStreams,
- failedStreamsThisSession = failedStreamsThisSession
- )
-}
-
internal fun PlayerViewModel.isCatchUpPlayback(): Boolean = isCatchUpPlayback.value
private fun PlayerViewModel.nextCatchUpVariant(): String? {
@@ -143,4 +165,4 @@ internal fun PlayerViewModel.tryNextCatchUpVariantInternal(): Boolean {
playerEngine.play()
}
return true
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
index 779fa93c..f49d2f3d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupport.kt
@@ -1,6 +1,23 @@
package com.streamvault.app.ui.screens.player
+import com.streamvault.data.remote.xtream.XtreamStreamKind
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
+import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.LiveChannelVariant
+import java.net.URI
+import java.util.Locale
+
+internal enum class LiveRecoveryCandidateKind {
+ VARIANT,
+ XTREAM_TS_FALLBACK,
+ ALTERNATE
+}
+
+internal data class LiveRecoveryCandidate(
+ val url: String,
+ val kind: LiveRecoveryCandidateKind,
+ val variant: LiveChannelVariant? = null
+)
internal fun buildPlayerRecoveryActions(
hasAlternateStream: Boolean,
@@ -54,4 +71,125 @@ internal fun selectNextLiveVariant(
variant.streamUrl != currentStreamUrl &&
variant.streamUrl !in triedAlternativeStreams
}
-}
\ No newline at end of file
+}
+
+internal fun selectNextLiveRecoveryCandidate(
+ channel: Channel,
+ currentVariantId: Long,
+ currentStreamUrl: String,
+ currentResolvedPlaybackUrl: String,
+ triedAlternativeStreams: Set<String>,
+ failedStreamsThisSession: Map<String, Int>,
+ preferXtreamTsFallback: Boolean,
+ allowXtreamTsFallback: Boolean = true
+): LiveRecoveryCandidate? {
+ val nextVariant = selectNextLiveVariant(
+ variants = channel.variants,
+ currentVariantId = currentVariantId,
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ )?.let { variant ->
+ LiveRecoveryCandidate(
+ url = variant.streamUrl,
+ kind = LiveRecoveryCandidateKind.VARIANT,
+ variant = variant
+ )
+ }
+ val xtreamTsFallback = if (allowXtreamTsFallback) {
+ selectXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = currentStreamUrl,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ )?.let { fallbackUrl ->
+ LiveRecoveryCandidate(
+ url = fallbackUrl,
+ kind = LiveRecoveryCandidateKind.XTREAM_TS_FALLBACK
+ )
+ }
+ } else {
+ null
+ }
+ val alternate = selectNextAlternateUrl(
+ candidateUrls = channel.alternativeStreams.filter { it != xtreamTsFallback?.url },
+ currentStreamUrl = currentStreamUrl,
+ triedAlternativeStreams = triedAlternativeStreams,
+ failedStreamsThisSession = failedStreamsThisSession
+ )?.let { alternateUrl ->
+ LiveRecoveryCandidate(
+ url = alternateUrl,
+ kind = LiveRecoveryCandidateKind.ALTERNATE
+ )
+ }
+
+ return if (preferXtreamTsFallback) {
+ xtreamTsFallback ?: nextVariant ?: alternate
+ } else {
+ nextVariant ?: xtreamTsFallback ?: alternate
+ }
+}
+
+internal fun buildXtreamLiveTsFallbackUrl(
+ channel: Channel,
+ currentStreamUrl: String,
+ currentResolvedPlaybackUrl: String
+): String? {
+ val token = XtreamUrlFactory.parseInternalStreamUrl(currentStreamUrl)
+ if (token != null && token.kind != XtreamStreamKind.LIVE) return null
+
+ val currentLooksLikeHls = token?.containerExtension == "m3u8" ||
+ currentStreamUrl.contains("ext=m3u8", ignoreCase = true) ||
+ currentResolvedPlaybackUrl.contains("ext=m3u8", ignoreCase = true) ||
+ currentResolvedPlaybackUrl.lowercase(Locale.ROOT).substringBefore('?').endsWith(".m3u8")
+ if (!currentLooksLikeHls) return null
+
+ val providerId = token?.providerId ?: channel.providerId
+ val streamId = token?.streamId
+ ?: channel.streamId.takeIf { it > 0L }
+ ?: extractXtreamLiveStreamId(currentResolvedPlaybackUrl)
+ ?: return null
+ if (providerId <= 0L || streamId <= 0L) return null
+
+ return XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.LIVE,
+ streamId = streamId,
+ containerExtension = "ts"
+ )
+}
+
+internal fun selectXtreamLiveTsFallbackUrl(
+ channel: Channel,
+ currentStreamUrl: String,
+ currentResolvedPlaybackUrl: String,
+ triedAlternativeStreams: Set<String>,
+ failedStreamsThisSession: Map<String, Int>
+): String? {
+ val fallbackUrl = buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = currentStreamUrl,
+ currentResolvedPlaybackUrl = currentResolvedPlaybackUrl
+ ) ?: return null
+ return fallbackUrl.takeIf {
+ it != currentStreamUrl &&
+ it !in triedAlternativeStreams &&
+ (failedStreamsThisSession[it] ?: 0) == 0
+ }
+}
+
+private fun extractXtreamLiveStreamId(url: String): Long? {
+ val pathSegments = runCatching { URI(url).path }
+ .getOrNull()
+ ?.trim('/')
+ ?.split('/')
+ ?.filter { it.isNotBlank() }
+ .orEmpty()
+ val liveIndex = pathSegments.indexOfFirst { it.equals("live", ignoreCase = true) }
+ if (liveIndex < 0) return null
+ val fileSegment = pathSegments.getOrNull(liveIndex + 3) ?: return null
+ return fileSegment.substringBefore('?')
+ .substringBeforeLast('.', missingDelimiterValue = fileSegment)
+ .toLongOrNull()
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
index 5aed5ce3..3f54399d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
@@ -26,6 +26,18 @@ internal data class PlayerPlaybackStreamResolution(
val credentialFailureMessage: String? = null
)
+internal fun shouldUseStoredLiveStreamInfo(
+ logicalUrl: String,
+ storedStreamUrl: String
+): Boolean {
+ val requestedUrl = logicalUrl.trim()
+ val storedUrl = storedStreamUrl.trim()
+ return requestedUrl.isBlank() || requestedUrl == storedUrl
+}
+
+internal fun shouldStartLiveTimeshiftForStreamClass(streamClassLabel: String): Boolean =
+ streamClassLabel != "Catch-up" && streamClassLabel != "MPEG-TS fallback"
+
internal fun buildSeriesEpisodeResolution(
series: Series,
episodeId: Long,
@@ -75,10 +87,12 @@ internal suspend fun resolvePlayerPlaybackStreamInfo(
channelRepository.getChannel(internalContentId)?.let { channel ->
fallbackStreamId = channel.streamId.takeIf { it > 0L }
?: channel.epgChannelId?.toLongOrNull()
- channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
- return PlayerPlaybackStreamResolution(
- streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
- )
+ if (shouldUseStoredLiveStreamInfo(logicalUrl, channel.streamUrl)) {
+ channelRepository.getStreamInfo(channel).getOrNull()?.let { resolved ->
+ return PlayerPlaybackStreamResolution(
+ streamInfo = resolved.copy(title = resolved.title ?: currentTitle)
+ )
+ }
}
}
}
@@ -157,4 +171,4 @@ internal suspend fun resolvePlayerPlaybackStreamInfo(
)
}
)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 5eb96f50..f749bb44 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
@@ -246,6 +246,7 @@ class PlayerViewModel @Inject constructor(
internal var currentResolvedPlaybackUrl: String = ""
internal var currentResolvedStreamInfo: StreamInfo? = null
internal var pendingCatchUpUrls: List<String> = emptyList()
+ internal var livePlaybackReadyForCurrentSession: Boolean = false
internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP
set(value) {
field = value
@@ -394,7 +395,7 @@ class PlayerViewModel @Inject constructor(
playerEngine.stopLiveTimeshift()
return
}
- if (currentStreamClassLabel == "Catch-up") {
+ if (!shouldStartLiveTimeshiftForStreamClass(currentStreamClassLabel)) {
playerEngine.stopLiveTimeshift()
return
}
@@ -450,6 +451,7 @@ class PlayerViewModel @Inject constructor(
zapBufferWatchdogJob?.cancel()
dismissRecoveredNoticeIfPresent()
if (currentContentType == ContentType.LIVE) {
+ livePlaybackReadyForCurrentSession = true
recordActiveLivePlayback()
currentChannelFlow.value?.sanitizedForPlayer()?.let { channel ->
if (channel.errorCount > 0) {
@@ -702,6 +704,12 @@ class PlayerViewModel @Inject constructor(
currentResolvedPlaybackUrl = currentResolvedPlaybackUrl,
currentStreamUrl = currentStreamUrl
)
+ android.util.Log.i(
+ "PlayerVM",
+ "handle-playback-error type=${error::class.java.simpleName} contentType=$currentContentType " +
+ "hasChannel=${currentChannelFlow.value != null} requestVersion=$requestVersion " +
+ "active=${isActivePlaybackSession(requestVersion, playbackUrl)}"
+ )
recoveryJob?.cancel()
if (error is PlayerError.DecoderError && !hasRetriedWithSoftwareDecoder) {
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return
@@ -727,6 +735,11 @@ class PlayerViewModel @Inject constructor(
val recoveryType = classifyPlaybackError(error)
val channel = currentChannelFlow.value?.sanitizedForPlayer()
+ android.util.Log.i(
+ "PlayerVM",
+ "recovery-dispatch type=$recoveryType live=${currentContentType == ContentType.LIVE} " +
+ "hasChannel=${channel != null}"
+ )
if (recoveryType == PlayerRecoveryType.DRM) {
if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@launch
@@ -794,7 +807,11 @@ class PlayerViewModel @Inject constructor(
val switched = when (recoveryType) {
PlayerRecoveryType.NETWORK,
PlayerRecoveryType.SOURCE,
- PlayerRecoveryType.BUFFER_TIMEOUT -> tryAlternateStreamInternal(channel)
+ PlayerRecoveryType.BUFFER_TIMEOUT -> tryAlternateStreamInternal(
+ channel = channel,
+ preferXtreamTsFallback = recoveryType == PlayerRecoveryType.SOURCE,
+ allowXtreamTsFallback = !livePlaybackReadyForCurrentSession
+ )
else -> false
}
@@ -809,6 +826,10 @@ class PlayerViewModel @Inject constructor(
)
return@launch
}
+ android.util.Log.w(
+ "PlayerVM",
+ "recovery-no-switch type=$recoveryType hasLastChannel=${hasLastChannel()}"
+ )
if (fallbackToPreviousChannel("Recovery path exhausted for ${recoveryType.name.lowercase()}")) {
appendRecoveryAction("Returned to last channel")
@@ -896,6 +917,7 @@ class PlayerViewModel @Inject constructor(
thumbnailPreloadJob?.cancel()
hasRetriedXtreamAuthRefresh = false
lastRecordedVariantObservationSignature = null
+ livePlaybackReadyForCurrentSession = false
readySideEffectsRequestVersion = null
playerEngine.setScrubbingMode(false)
return ++prepareRequestVersion
@@ -1086,13 +1108,11 @@ class PlayerViewModel @Inject constructor(
url = session.streamInfo.url
)
)
- // Re-prime the adopted engine against the fullscreen surface path.
- // Preview-to-fullscreen handoff can temporarily leave the reused live
- // player with an audio-only pipeline until the new render view binds.
- // Refreshing the current live media source makes the handoff more
- // robust without re-resolving provider URLs or abandoning the adopted
- // engine instance.
- playerEngine.renewStreamUrl(session.streamInfo)
+ // Re-prime the adopted engine against the fullscreen surface path at
+ // the live edge. Renewing in-place preserves the preview timeline
+ // position, which can strand HLS live playback in buffering after the
+ // fullscreen surface binds.
+ playerEngine.prepare(session.streamInfo)
playerEngine.play()
startTokenRenewalMonitoring(session.streamInfo.expirationTime)
maybeStartLiveTimeshift(session.streamInfo)
@@ -1169,6 +1189,7 @@ class PlayerViewModel @Inject constructor(
readySideEffectsRequestVersion = requestVersion
playerEngine.prepare(preparedStreamInfo)
startTokenRenewalMonitoring(preparedStreamInfo.expirationTime)
+ maybeStartLiveTimeshift(preparedStreamInfo)
return true
}
@@ -1340,8 +1361,6 @@ class PlayerViewModel @Inject constructor(
}
}
}
-
- maybeStartLiveTimeshift(streamInfo)
}
}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupportTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupportTest.kt
new file mode 100644
index 00000000..a00f6076
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerAlternateStreamSupportTest.kt
@@ -0,0 +1,290 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.remote.xtream.XtreamStreamKind
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.LiveChannelVariant
+import org.junit.Test
+
+class PlayerAlternateStreamSupportTest {
+ @Test
+ fun buildXtreamLiveTsFallbackUrl_convertsLiveHlsInternalUrlToTs() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 61351)
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+
+ val fallbackUrl = buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8"
+ )
+
+ assertThat(fallbackUrl).isEqualTo(
+ XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+ )
+ }
+
+ @Test
+ fun buildXtreamLiveTsFallbackUrl_usesChannelIdentifiersForResolvedHlsUrl() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 61351)
+
+ val fallbackUrl = buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = "http://example.test/live/user/pass/61351.m3u8",
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8?token=abc"
+ )
+
+ assertThat(fallbackUrl).isEqualTo(
+ XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+ )
+ }
+
+ @Test
+ fun buildXtreamLiveTsFallbackUrl_extractsStreamIdFromResolvedLivePath() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 0)
+
+ val fallbackUrl = buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = "https://example.test/live/user/pass/61351.m3u8",
+ currentResolvedPlaybackUrl = "https://example.test/proxy/live/user/pass/61351.m3u8?token=abc"
+ )
+
+ assertThat(fallbackUrl).isEqualTo(
+ XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+ )
+ }
+
+ @Test
+ fun buildXtreamLiveTsFallbackUrl_ignoresNonLiveInternalUrl() {
+ val channel = Channel(id = 10, name = "Movie", providerId = 7, streamId = 61351)
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.MOVIE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+
+ assertThat(
+ buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/movie/user/pass/61351.m3u8"
+ )
+ ).isNull()
+ }
+
+ @Test
+ fun buildXtreamLiveTsFallbackUrl_ignoresAlreadyTsLiveUrl() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 61351)
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+
+ assertThat(
+ buildXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.ts"
+ )
+ ).isNull()
+ }
+
+ @Test
+ fun selectXtreamLiveTsFallbackUrl_skipsTriedFallback() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 61351)
+ val fallbackUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+
+ assertThat(
+ selectXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = "xtream://7/live/61351?ext=m3u8",
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8",
+ triedAlternativeStreams = setOf(fallbackUrl),
+ failedStreamsThisSession = emptyMap()
+ )
+ ).isNull()
+ }
+
+ @Test
+ fun selectXtreamLiveTsFallbackUrl_skipsFailedFallback() {
+ val channel = Channel(id = 10, name = "Live", providerId = 7, streamId = 61351)
+ val fallbackUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+
+ assertThat(
+ selectXtreamLiveTsFallbackUrl(
+ channel = channel,
+ currentStreamUrl = "xtream://7/live/61351?ext=m3u8",
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8",
+ triedAlternativeStreams = emptySet(),
+ failedStreamsThisSession = mapOf(fallbackUrl to 1)
+ )
+ ).isNull()
+ }
+
+ @Test
+ fun selectNextLiveRecoveryCandidate_prefersTsFallbackBeforeVariantsWhenRequested() {
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+ val variantUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61352,
+ containerExtension = "m3u8"
+ )
+ val channel = Channel(
+ id = 10,
+ name = "Live",
+ providerId = 7,
+ streamId = 61351,
+ streamUrl = currentUrl,
+ selectedVariantId = 10,
+ variants = listOf(
+ LiveChannelVariant(
+ rawChannelId = 11,
+ logicalGroupId = "live",
+ providerId = 7,
+ originalName = "Live HD",
+ canonicalName = "Live",
+ streamUrl = variantUrl,
+ streamId = 61352
+ )
+ )
+ )
+
+ val candidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 10,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8",
+ triedAlternativeStreams = emptySet(),
+ failedStreamsThisSession = emptyMap(),
+ preferXtreamTsFallback = true
+ )
+
+ assertThat(candidate?.kind).isEqualTo(LiveRecoveryCandidateKind.XTREAM_TS_FALLBACK)
+ assertThat(candidate?.url).isEqualTo(
+ XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+ )
+ }
+
+ @Test
+ fun selectNextLiveRecoveryCandidate_skipsTsFallbackWhenDisallowed() {
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+ val channel = Channel(
+ id = 10,
+ name = "Live",
+ providerId = 7,
+ streamId = 61351,
+ streamUrl = currentUrl,
+ selectedVariantId = 10
+ )
+
+ val candidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 10,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8",
+ triedAlternativeStreams = emptySet(),
+ failedStreamsThisSession = emptyMap(),
+ preferXtreamTsFallback = true,
+ allowXtreamTsFallback = false
+ )
+
+ assertThat(candidate).isNull()
+ }
+
+ @Test
+ fun selectNextLiveRecoveryCandidate_keepsVariantPreferenceByDefault() {
+ val currentUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+ val variantUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61352,
+ containerExtension = "m3u8"
+ )
+ val channel = Channel(
+ id = 10,
+ name = "Live",
+ providerId = 7,
+ streamId = 61351,
+ streamUrl = currentUrl,
+ selectedVariantId = 10,
+ variants = listOf(
+ LiveChannelVariant(
+ rawChannelId = 11,
+ logicalGroupId = "live",
+ providerId = 7,
+ originalName = "Live HD",
+ canonicalName = "Live",
+ streamUrl = variantUrl,
+ streamId = 61352
+ )
+ )
+ )
+
+ val candidate = selectNextLiveRecoveryCandidate(
+ channel = channel,
+ currentVariantId = 10,
+ currentStreamUrl = currentUrl,
+ currentResolvedPlaybackUrl = "http://example.test/live/user/pass/61351.m3u8",
+ triedAlternativeStreams = emptySet(),
+ failedStreamsThisSession = emptyMap(),
+ preferXtreamTsFallback = false
+ )
+
+ assertThat(candidate?.kind).isEqualTo(LiveRecoveryCandidateKind.VARIANT)
+ assertThat(candidate?.url).isEqualTo(variantUrl)
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt
new file mode 100644
index 00000000..9b89f54e
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupportTest.kt
@@ -0,0 +1,58 @@
+package com.streamvault.app.ui.screens.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.remote.xtream.XtreamStreamKind
+import com.streamvault.data.remote.xtream.XtreamUrlFactory
+import org.junit.Test
+
+class PlayerContentResolutionSupportTest {
+ @Test
+ fun shouldUseStoredLiveStreamInfo_usesStoredInfoForPrimaryLiveUrl() {
+ val primaryUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+
+ assertThat(
+ shouldUseStoredLiveStreamInfo(
+ logicalUrl = primaryUrl,
+ storedStreamUrl = primaryUrl
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun shouldUseStoredLiveStreamInfo_bypassesStoredInfoForTransportFallback() {
+ val primaryUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "m3u8"
+ )
+ val fallbackUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = 7,
+ kind = XtreamStreamKind.LIVE,
+ streamId = 61351,
+ containerExtension = "ts"
+ )
+
+ assertThat(
+ shouldUseStoredLiveStreamInfo(
+ logicalUrl = fallbackUrl,
+ storedStreamUrl = primaryUrl
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun shouldStartLiveTimeshiftForStreamClass_skipsMpegTsFallback() {
+ assertThat(shouldStartLiveTimeshiftForStreamClass("MPEG-TS fallback")).isFalse()
+ }
+
+ @Test
+ fun shouldStartLiveTimeshiftForStreamClass_allowsPrimaryLivePlayback() {
+ assertThat(shouldStartLiveTimeshiftForStreamClass("Primary")).isTrue()
+ }
+}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 4a37209e..c08a2807 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -60,9 +60,19 @@ import com.streamvault.player.playback.PreloadCoordinator
import com.streamvault.player.playback.ResolvedStreamType
import com.streamvault.player.playback.resolveRetryAttemptAfterPlaybackStarted
import com.streamvault.player.playback.resolveRetryAttemptAfterReady
+import com.streamvault.player.playback.resolveRetryAttemptForCategory
import com.streamvault.player.playback.resolveRetrySeekPositionMs
import com.streamvault.player.playback.StreamTypeResolver
import com.streamvault.player.playback.VideoStallDetector
+import com.streamvault.player.playback.buildLiveTsFallbackStreamInfo
+import com.streamvault.player.playback.hasEffectivePlaybackStarted
+import com.streamvault.player.playback.shouldFallbackMalformedHlsToLiveTs
+import com.streamvault.player.playback.shouldFallbackStalledHlsToLiveTs
+import com.streamvault.player.playback.shouldPreservePlaybackStateForRetry
+import com.streamvault.player.playback.shouldRecoverFrameSilentReadyStalls
+import com.streamvault.player.playback.shouldRecoverPositionAdvancingReadyStalls
+import com.streamvault.player.playback.shouldRecoverReadyStalls
+import com.streamvault.player.playback.shouldReconnectLiveStall
import com.streamvault.player.stats.PlayerStatsCollector
import com.streamvault.player.timeshift.DefaultLiveTimeshiftManager
import com.streamvault.player.timeshift.LiveTimeshiftBackend
@@ -82,6 +92,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -174,12 +185,15 @@ class Media3PlayerEngine @Inject constructor(
private var currentRetryPolicy: PlayerRetryPolicy? = null
private var currentRetryContext: PlaybackRetryContext? = null
private var playbackStarted = false
+ private var liveBufferingRecoveryArmed = false
private var hasRenderedFirstVideoFrame = false
private var prepareStartMs = 0L
private var retryAttempt = 0
+ private var lastRetryCategory: PlaybackErrorCategory? = null
private var retryJob: Job? = null
private var retryGeneration = 0L
private var currentBufferIsLive: Boolean? = null
+ private var currentBufferPolicyLabel: String? = null
private var audioCodecUnsupportedReported = false
private var lastSupportErrorMessage: String? = null
@@ -198,7 +212,11 @@ class Media3PlayerEngine @Inject constructor(
private val _videoFormat = MutableStateFlow(VideoFormat(0, 0))
override val videoFormat: StateFlow<VideoFormat> = _videoFormat.asStateFlow()
- private val _error = MutableSharedFlow<PlayerError?>(replay = 1)
+ private val _error = MutableSharedFlow<PlayerError?>(
+ replay = 1,
+ extraBufferCapacity = 8,
+ onBufferOverflow = BufferOverflow.DROP_OLDEST
+ )
override val error: Flow<PlayerError?> = _error.asSharedFlow()
private val _retryStatus = MutableStateFlow<PlayerRetryStatus?>(null)
@@ -295,12 +313,22 @@ class Media3PlayerEngine @Inject constructor(
while (true) {
delay(1_000L)
val stats = _playerStats.value
+ val liveStream = isCurrentStreamLive()
+ val liveBufferingRecoveryEligible = liveStream &&
+ (playbackStarted || liveBufferingRecoveryArmed)
val stalled = videoStallDetector.shouldReportStall(
playbackState = _playbackState.value,
isPlaying = _isPlaying.value,
- playbackStarted = playbackStarted,
+ playbackStarted = playbackStarted || liveBufferingRecoveryArmed,
currentPositionMs = _currentPosition.value,
- bufferedDurationMs = stats.bufferedDurationMs
+ bufferedDurationMs = stats.bufferedDurationMs,
+ playWhenReady = exoPlayer?.playWhenReady == true,
+ recoverBufferingStalls = liveBufferingRecoveryEligible,
+ recoverReadyStalls = shouldRecoverReadyStalls(currentResolvedStreamType),
+ recoverPositionAdvancingReadyStalls =
+ shouldRecoverPositionAdvancingReadyStalls(currentResolvedStreamType),
+ recoverFrameSilentReadyStalls =
+ shouldRecoverFrameSilentReadyStalls(currentResolvedStreamType)
)
_playerStats.value = _playerStats.value.copy(
lastVideoFrameAgoMs = videoStallDetector.lastVideoFrameAgoMs(),
@@ -347,8 +375,10 @@ class Media3PlayerEngine @Inject constructor(
currentRetryContext = playbackPlan.retryContext
currentRetryPolicy = playbackPlan.retryPolicy
retryAttempt = 0
+ lastRetryCategory = null
_retryStatus.value = null
playbackStarted = false
+ liveBufferingRecoveryArmed = false
val mediaSource = mediaSourceFactory.create(
streamInfo = streamInfo,
@@ -745,8 +775,10 @@ class Media3PlayerEngine @Inject constructor(
currentRetryPolicy = null
currentRetryContext = null
playbackStarted = false
+ liveBufferingRecoveryArmed = false
hasRenderedFirstVideoFrame = false
retryAttempt = 0
+ lastRetryCategory = null
_retryStatus.value = null
_playbackState.value = PlaybackState.IDLE
_isPlaying.value = false
@@ -794,11 +826,17 @@ class Media3PlayerEngine @Inject constructor(
retryGeneration++
lastStreamInfo = streamInfo
val mediaId = mediaSourceFactory.mediaIdFor(streamInfo)
- if (!preserveRetryState || lastMediaId != mediaId) {
+ val mediaChanged = lastMediaId != mediaId
+ val shouldArmLiveBufferingRecovery = preserveRetryState &&
+ !mediaChanged &&
+ (playbackStarted || liveBufferingRecoveryArmed) &&
+ isCurrentStreamLive()
+ if (!preserveRetryState || mediaChanged) {
retryAttempt = 0
+ lastRetryCategory = null
_retryStatus.value = null
}
- if (lastMediaId != mediaId) {
+ if (mediaChanged) {
decoderPreferencePolicy.resetForMedia(mediaId)
sessionSurfaceModeOverride = null
textureViewSessionFallbackAttempted = false
@@ -807,6 +845,7 @@ class Media3PlayerEngine @Inject constructor(
}
lastMediaId = mediaId
playbackStarted = false
+ liveBufferingRecoveryArmed = shouldArmLiveBufferingRecovery
hasRenderedFirstVideoFrame = false
prepareStartMs = System.currentTimeMillis()
audioCodecUnsupportedReported = false
@@ -818,6 +857,7 @@ class Media3PlayerEngine @Inject constructor(
statsCollector.reset()
videoStallDetector.reset()
if (!preserveRetryState) {
+ liveBufferingRecoveryArmed = false
videoStallRecoveryAttempt = 0
videoStallSafeRecoveryPerformed = false
}
@@ -863,13 +903,19 @@ class Media3PlayerEngine @Inject constructor(
ResolvedStreamType.RTSP
)
val previousDecoderPolicy = activeDecoderPolicy
+ val nextBufferPolicy = PlaybackBufferPolicies.forPlayback(
+ resolvedStreamType = currentResolvedStreamType,
+ compatibilityMode = nextDecoderPolicy == ActiveDecoderPolicy.COMPATIBILITY
+ )
val needsRecreate = activeDecoderMode != preferredDecoderMode ||
previousDecoderPolicy != nextDecoderPolicy ||
isLiveBuffer != currentBufferIsLive ||
+ nextBufferPolicy.label != currentBufferPolicyLabel ||
requestedDecoderMode == DecoderMode.COMPATIBILITY
activeDecoderMode = preferredDecoderMode
activeDecoderPolicy = nextDecoderPolicy
currentBufferIsLive = isLiveBuffer
+ currentBufferPolicyLabel = nextBufferPolicy.label
updateRenderSurfaceForMode()
if (needsRecreate) {
recreatePlayer()
@@ -961,7 +1007,7 @@ class Media3PlayerEngine @Inject constructor(
private fun createPlayer(): ExoPlayer {
val renderersFactory = buildRenderersFactory()
val bufferPolicy = PlaybackBufferPolicies.forPlayback(
- isLive = currentBufferIsLive == true,
+ resolvedStreamType = currentResolvedStreamType,
compatibilityMode = activeDecoderPolicy == ActiveDecoderPolicy.COMPATIBILITY
)
val loadControl = DefaultLoadControl.Builder()
@@ -971,7 +1017,8 @@ class Media3PlayerEngine @Inject constructor(
bufferPolicy.playbackBufferMs,
bufferPolicy.rebufferMs
)
- .setPrioritizeTimeOverSizeThresholds(true)
+ .setTargetBufferBytes(bufferPolicy.targetBufferBytes)
+ .setPrioritizeTimeOverSizeThresholds(bufferPolicy.prioritizeTimeOverSizeThresholds)
.build()
val livePlaybackSpeedControl = DefaultLivePlaybackSpeedControl.Builder()
.setFallbackMinPlaybackSpeed(1.0f)
@@ -994,6 +1041,9 @@ class Media3PlayerEngine @Inject constructor(
.apply {
videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
playbackParameters = PlaybackParameters(_playbackSpeed.value)
+ setVideoFrameMetadataListener { presentationTimeUs, _, _, _ ->
+ videoStallDetector.onVideoFrameRendered((presentationTimeUs / 1_000L).coerceAtLeast(0L))
+ }
addAnalyticsListener(createAnalyticsListener())
addListener(createPlayerListener())
}
@@ -1207,6 +1257,7 @@ class Media3PlayerEngine @Inject constructor(
val ttff = System.currentTimeMillis() - prepareStartMs
_playerStats.value = _playerStats.value.copy(ttffMs = ttff)
}
+ videoStallDetector.onVideoFrameRendered(eventTime.currentPlaybackPositionMs)
markPlaybackStarted("first-frame-success")
}
}
@@ -1232,6 +1283,9 @@ class Media3PlayerEngine @Inject constructor(
currentAttempt = retryAttempt,
playbackStarted = playbackStarted
)
+ if (retryAttempt == 0) {
+ lastRetryCategory = null
+ }
if (isPlayingTimeshiftSnapshot && pendingTimeshiftSeekToEnd) {
pendingTimeshiftSeekToEnd = false
playerOrNull()?.duration?.takeIf { it > 0L && it != C.TIME_UNSET }?.let { duration ->
@@ -1379,7 +1433,11 @@ class Media3PlayerEngine @Inject constructor(
private fun markPlaybackStarted(reason: String) {
if (playbackStarted) return
playbackStarted = true
+ liveBufferingRecoveryArmed = false
retryAttempt = resolveRetryAttemptAfterPlaybackStarted(retryAttempt)
+ if (retryAttempt == 0) {
+ lastRetryCategory = null
+ }
Log.i(
TAG,
"$reason streamType=$currentResolvedStreamType timeoutProfile=$currentTimeoutProfile audioPath=$audioOutputPath compatibilitySource=$compatibilityDecisionSource target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}"
@@ -1477,22 +1535,61 @@ class Media3PlayerEngine @Inject constructor(
private fun handleVideoStall() {
val streamInfo = lastStreamInfo ?: return
videoStallCount++
- recordCompatibilityFailure("VIDEO_STALL")
_playerStats.value = _playerStats.value.copy(videoStallCount = videoStallCount)
val wasPlaying = exoPlayer?.playWhenReady ?: true
val seekPosition = exoPlayer?.currentPosition?.takeIf { it > 0L }
+ val nextRecoveryAttempt = videoStallRecoveryAttempt + 1
+ val liveReconnectionStall = shouldReconnectLiveStall(
+ playbackState = _playbackState.value,
+ resolvedStreamType = currentResolvedStreamType,
+ recoveryAttempt = nextRecoveryAttempt
+ )
Log.w(
TAG,
"video-stall count=$videoStallCount recovered=$videoStallSafeRecoveryPerformed decoder=$selectedVideoDecoderName policy=$activeDecoderPolicy surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
)
- if (!playbackStarted) {
+ if (!playbackStarted && !liveBufferingRecoveryArmed) {
Log.w(TAG, "video-stall ignored because playback has not started yet")
return
}
- videoStallRecoveryAttempt++
+ videoStallRecoveryAttempt = nextRecoveryAttempt
+ if (liveReconnectionStall) {
+ Log.w(TAG, "live-${_playbackState.value.name.lowercase()}-stall reconnect attempt=$videoStallRecoveryAttempt")
+ prepareInternal(
+ streamInfo = streamInfo,
+ preserveRetryState = true,
+ seekPositionMs = null,
+ autoPlay = wasPlaying
+ )
+ return
+ }
+
+ if (
+ shouldFallbackStalledHlsToLiveTs(
+ resolvedStreamType = currentResolvedStreamType,
+ recoveryAttempt = videoStallRecoveryAttempt
+ )
+ ) {
+ val fallbackStreamInfo = buildLiveTsFallbackStreamInfo(streamInfo)
+ if (fallbackStreamInfo != null) {
+ Log.w(
+ TAG,
+ "video-stall live-ts-fallback from=HLS attempt=$videoStallRecoveryAttempt target=${PlaybackLogSanitizer.sanitizeUrl(fallbackStreamInfo.url)}"
+ )
+ prepareInternal(
+ streamInfo = fallbackStreamInfo,
+ preserveRetryState = false,
+ seekPositionMs = null,
+ autoPlay = wasPlaying
+ )
+ return
+ }
+ }
+
+ recordCompatibilityFailure("VIDEO_STALL")
if (!videoStallSafeRecoveryPerformed) {
videoStallSafeRecoveryPerformed = true
Log.w(TAG, "video-stall safe reprepare attempt=$videoStallRecoveryAttempt")
@@ -1938,6 +2035,10 @@ class Media3PlayerEngine @Inject constructor(
val retryPolicy = currentRetryPolicy
val retryContext = currentRetryContext
val category = PlayerErrorClassifier.classify(error)
+ val effectivePlaybackStarted = hasEffectivePlaybackStarted(
+ playbackStarted = playbackStarted,
+ liveBufferingRecoveryArmed = liveBufferingRecoveryArmed
+ )
if (streamInfo == null || mediaId == null || retryPolicy == null || retryContext == null) {
_retryStatus.value = null
@@ -1960,8 +2061,35 @@ class Media3PlayerEngine @Inject constructor(
}
}
- val nextAttempt = retryAttempt + 1
- if (retryPolicy.shouldRetry(error, retryContext, playbackStarted, nextAttempt)) {
+ if (
+ shouldFallbackMalformedHlsToLiveTs(
+ category = category,
+ resolvedStreamType = currentResolvedStreamType,
+ playbackStarted = effectivePlaybackStarted
+ )
+ ) {
+ val fallbackStreamInfo = buildLiveTsFallbackStreamInfo(streamInfo)
+ if (fallbackStreamInfo != null) {
+ Log.w(
+ TAG,
+ "source-malformed live-ts-fallback from=HLS target=${PlaybackLogSanitizer.sanitizeUrl(fallbackStreamInfo.url)}"
+ )
+ prepareInternal(
+ fallbackStreamInfo,
+ preserveRetryState = false,
+ seekPositionMs = null,
+ autoPlay = true
+ )
+ return
+ }
+ }
+
+ val nextAttempt = resolveRetryAttemptForCategory(
+ currentAttempt = retryAttempt,
+ lastCategory = lastRetryCategory,
+ nextCategory = category
+ )
+ if (retryPolicy.shouldRetry(error, retryContext, effectivePlaybackStarted, nextAttempt)) {
val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)
val player = exoPlayer
val retrySeekPositionMs = resolveRetrySeekPositionMs(
@@ -1970,28 +2098,32 @@ class Media3PlayerEngine @Inject constructor(
currentPositionMs = player?.currentPosition,
durationMs = player?.duration,
isCurrentMediaItemLive = player?.isCurrentMediaItemLive == true,
- playbackStarted = playbackStarted
+ playbackStarted = effectivePlaybackStarted
)
// retryGeneration captured and checked on Main — safe with
// Dispatchers.Main.immediate. If the scope dispatcher is ever changed
// (e.g. in tests), convert retryGeneration to AtomicLong.
val scheduledRetryGeneration = retryGeneration
retryAttempt = nextAttempt
+ lastRetryCategory = category
_retryStatus.value = PlayerRetryStatus(
attempt = nextAttempt,
- maxAttempts = retryPolicy.maxAttempts(error, playbackStarted),
+ maxAttempts = retryPolicy.maxAttempts(error, effectivePlaybackStarted),
delayMs = delayMs
)
Log.w(
TAG,
- "retry category=$category attempt=$nextAttempt delayMs=$delayMs reason=${retryPolicy.retryReason(error)} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ "retry category=$category attempt=$nextAttempt delayMs=$delayMs reason=${retryPolicy.retryReason(error)} " +
+ "errorCode=${error.errorCodeName} causeChain=${formatErrorCauseChain(error)} " +
+ "target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
)
retryJob = scope.launch {
delay(delayMs)
if (
scheduledRetryGeneration != retryGeneration ||
lastMediaId != mediaId ||
- retryAttempt != nextAttempt
+ retryAttempt != nextAttempt ||
+ lastRetryCategory != category
) {
return@launch
}
@@ -2003,7 +2135,11 @@ class Media3PlayerEngine @Inject constructor(
}
prepareInternal(
streamInfo,
- preserveRetryState = category != PlaybackErrorCategory.LIVE_WINDOW,
+ preserveRetryState = shouldPreservePlaybackStateForRetry(
+ category = category,
+ playbackStarted = playbackStarted,
+ liveBufferingRecoveryArmed = liveBufferingRecoveryArmed
+ ),
seekPositionMs = retrySeekPositionMs,
autoPlay = true
)
@@ -2014,10 +2150,23 @@ class Media3PlayerEngine @Inject constructor(
_retryStatus.value = null
Log.e(
TAG,
- "fatal-error category=$category target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
+ "fatal-error category=$category reason=${retryPolicy.retryReason(error)} " +
+ "errorCode=${error.errorCodeName} causeChain=${formatErrorCauseChain(error)} " +
+ "target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}"
)
lastSupportErrorMessage = error.message
_error.tryEmit(PlayerError.fromException(error))
_playbackState.value = PlaybackState.ERROR
}
+
+ private fun formatErrorCauseChain(error: Throwable): String {
+ return generateSequence(error) { it.cause }
+ .take(6)
+ .joinToString(" <- ") { cause ->
+ val className = cause::class.java.simpleName.ifBlank { cause::class.java.name }
+ val message = PlaybackLogSanitizer.sanitizeMessage(cause.message)
+ "$className($message)"
+ }
+ .take(600)
+ }
}
diff --git a/player/src/main/java/com/streamvault/player/playback/LiveRetryStatePolicy.kt b/player/src/main/java/com/streamvault/player/playback/LiveRetryStatePolicy.kt
new file mode 100644
index 00000000..a6270dca
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/LiveRetryStatePolicy.kt
@@ -0,0 +1,17 @@
+package com.streamvault.player.playback
+
+internal fun shouldPreservePlaybackStateForRetry(
+ category: PlaybackErrorCategory,
+ playbackStarted: Boolean,
+ liveBufferingRecoveryArmed: Boolean
+): Boolean =
+ category != PlaybackErrorCategory.LIVE_WINDOW ||
+ hasEffectivePlaybackStarted(
+ playbackStarted = playbackStarted,
+ liveBufferingRecoveryArmed = liveBufferingRecoveryArmed
+ )
+
+internal fun hasEffectivePlaybackStarted(
+ playbackStarted: Boolean,
+ liveBufferingRecoveryArmed: Boolean
+): Boolean = playbackStarted || liveBufferingRecoveryArmed
diff --git a/player/src/main/java/com/streamvault/player/playback/LiveTsFallbackUrl.kt b/player/src/main/java/com/streamvault/player/playback/LiveTsFallbackUrl.kt
new file mode 100644
index 00000000..e6b037c8
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/LiveTsFallbackUrl.kt
@@ -0,0 +1,65 @@
+package com.streamvault.player.playback
+
+import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.StreamType
+import java.net.URI
+import java.util.Locale
+
+internal fun buildLiveTsFallbackStreamInfo(streamInfo: StreamInfo): StreamInfo? {
+ val fallbackUrl = buildLiveTsFallbackUrl(streamInfo.url) ?: return null
+ return streamInfo.copy(
+ url = fallbackUrl,
+ streamType = StreamType.MPEG_TS,
+ containerExtension = "ts"
+ )
+}
+
+internal fun shouldFallbackMalformedHlsToLiveTs(
+ category: PlaybackErrorCategory,
+ resolvedStreamType: ResolvedStreamType,
+ playbackStarted: Boolean
+): Boolean =
+ category == PlaybackErrorCategory.SOURCE_MALFORMED &&
+ resolvedStreamType == ResolvedStreamType.HLS &&
+ !playbackStarted
+
+internal fun shouldFallbackStalledHlsToLiveTs(
+ resolvedStreamType: ResolvedStreamType,
+ recoveryAttempt: Int
+): Boolean =
+ resolvedStreamType == ResolvedStreamType.HLS &&
+ recoveryAttempt >= 3
+
+internal fun buildLiveTsFallbackUrl(url: String): String? {
+ val uri = runCatching { URI(url) }.getOrNull() ?: return null
+ val path = uri.path.orEmpty()
+ if (!path.contains("/live/", ignoreCase = true)) return null
+
+ val query = uri.rawQuery.orEmpty()
+ val queryFallback = if (query.contains("ext=m3u8", ignoreCase = true)) {
+ val updated = Regex("""(?i)(^|&)ext=m3u8(?=&|$)""").replace(query) { match ->
+ "${match.groupValues[1]}ext=ts"
+ }
+ rebuildUri(uri, path = path, query = updated)
+ } else {
+ null
+ }
+ if (queryFallback != null) return queryFallback
+
+ if (!path.lowercase(Locale.ROOT).endsWith(".m3u8")) return null
+ return rebuildUri(
+ uri = uri,
+ path = path.dropLast(".m3u8".length) + ".ts",
+ query = uri.rawQuery
+ )
+}
+
+private fun rebuildUri(uri: URI, path: String, query: String?): String {
+ return URI(
+ uri.scheme,
+ uri.rawAuthority,
+ path,
+ query,
+ uri.rawFragment
+ ).toASCIIString()
+}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt
index 8dd025c2..d5aa3721 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt
@@ -5,10 +5,16 @@ internal data class PlaybackBufferPolicy(
val minBufferMs: Int,
val maxBufferMs: Int,
val playbackBufferMs: Int,
- val rebufferMs: Int
+ val rebufferMs: Int,
+ val targetBufferBytes: Int,
+ val prioritizeTimeOverSizeThresholds: Boolean
)
internal object PlaybackBufferPolicies {
+ private const val DEFAULT_TARGET_BUFFER_BYTES = -1
+ private const val MPEG_TS_LIVE_TARGET_BUFFER_BYTES = 16 * 1024 * 1024
+ private const val MPEG_TS_LIVE_MIN_BUFFER_MS = 5_000
+ private const val MPEG_TS_LIVE_MAX_BUFFER_MS = 10_000
private const val LIVE_MIN_BUFFER_MS = 8_000
private const val LIVE_MAX_BUFFER_MS = 30_000
private const val COMPAT_LIVE_MIN_BUFFER_MS = 15_000
@@ -20,12 +26,58 @@ internal object PlaybackBufferPolicies {
private const val VOD_PLAYBACK_BUFFER_MS = 8_000
private const val VOD_REBUFFER_MS = 18_000
- fun forPlayback(isLive: Boolean, compatibilityMode: Boolean): PlaybackBufferPolicy = when {
- compatibilityMode && isLive ->
- PlaybackBufferPolicy("compat-live", COMPAT_LIVE_MIN_BUFFER_MS, COMPAT_LIVE_MAX_BUFFER_MS, PLAYBACK_BUFFER_MS, REBUFFER_MS)
- isLive ->
- PlaybackBufferPolicy("stable-live", LIVE_MIN_BUFFER_MS, LIVE_MAX_BUFFER_MS, PLAYBACK_BUFFER_MS, REBUFFER_MS)
+ fun forPlayback(resolvedStreamType: ResolvedStreamType, compatibilityMode: Boolean): PlaybackBufferPolicy = when {
+ resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE ->
+ PlaybackBufferPolicy(
+ "mpeg-ts-live",
+ MPEG_TS_LIVE_MIN_BUFFER_MS,
+ MPEG_TS_LIVE_MAX_BUFFER_MS,
+ PLAYBACK_BUFFER_MS,
+ REBUFFER_MS,
+ MPEG_TS_LIVE_TARGET_BUFFER_BYTES,
+ prioritizeTimeOverSizeThresholds = true
+ )
+ compatibilityMode && resolvedStreamType.isLive ->
+ PlaybackBufferPolicy(
+ "compat-live",
+ COMPAT_LIVE_MIN_BUFFER_MS,
+ COMPAT_LIVE_MAX_BUFFER_MS,
+ PLAYBACK_BUFFER_MS,
+ REBUFFER_MS,
+ DEFAULT_TARGET_BUFFER_BYTES,
+ prioritizeTimeOverSizeThresholds = true
+ )
+ resolvedStreamType.isLive ->
+ PlaybackBufferPolicy(
+ "stable-live",
+ LIVE_MIN_BUFFER_MS,
+ LIVE_MAX_BUFFER_MS,
+ PLAYBACK_BUFFER_MS,
+ REBUFFER_MS,
+ DEFAULT_TARGET_BUFFER_BYTES,
+ prioritizeTimeOverSizeThresholds = true
+ )
else ->
- PlaybackBufferPolicy("stable-vod", VOD_MIN_BUFFER_MS, VOD_MAX_BUFFER_MS, VOD_PLAYBACK_BUFFER_MS, VOD_REBUFFER_MS)
+ PlaybackBufferPolicy(
+ "stable-vod",
+ VOD_MIN_BUFFER_MS,
+ VOD_MAX_BUFFER_MS,
+ VOD_PLAYBACK_BUFFER_MS,
+ VOD_REBUFFER_MS,
+ DEFAULT_TARGET_BUFFER_BYTES,
+ prioritizeTimeOverSizeThresholds = true
+ )
}
+
+ fun forPlayback(isLive: Boolean, compatibilityMode: Boolean): PlaybackBufferPolicy =
+ forPlayback(
+ resolvedStreamType = if (isLive) ResolvedStreamType.HLS else ResolvedStreamType.PROGRESSIVE,
+ compatibilityMode = compatibilityMode
+ )
+
+ private val ResolvedStreamType.isLive: Boolean
+ get() = this == ResolvedStreamType.HLS ||
+ this == ResolvedStreamType.SMOOTH_STREAMING ||
+ this == ResolvedStreamType.MPEG_TS_LIVE ||
+ this == ResolvedStreamType.RTSP
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
index ddd526e8..c262a7dc 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
@@ -21,12 +21,18 @@ internal object PlaybackLogSanitizer {
private fun sanitizePath(path: String): String = sanitizePathSegments(path).take(120)
private fun sanitizePathSegments(value: String): String {
- return credentialPathRegex.replace(value) { match ->
- "${match.groupValues[1]}${match.groupValues[2]}/<redacted>/<redacted>${match.groupValues[3]}"
+ return opaqueSegmentPathRegex.replace(
+ credentialPathRegex.replace(value) { match ->
+ "${match.groupValues[1]}${match.groupValues[2]}/<redacted>/<redacted>${match.groupValues[3]}"
+ }
+ ) { match ->
+ "${match.groupValues[1]}${match.groupValues[2]}/<redacted>${match.groupValues[3]}"
}
}
private val credentialQueryRegex = Regex("""([?&](?:username|password|token|auth)=)[^&#\s]+""", RegexOption.IGNORE_CASE)
private val credentialPathRegex =
Regex("""(/)(live|movie|series|timeshift|timeshifts)/[^/\s]+/[^/\s]+([^?\s#]*)""", RegexOption.IGNORE_CASE)
+ private val opaqueSegmentPathRegex =
+ Regex("""(/)(r)/[^/\s]+([^?\s#]*)""", RegexOption.IGNORE_CASE)
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicy.kt
new file mode 100644
index 00000000..4b0c78b7
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicy.kt
@@ -0,0 +1,29 @@
+package com.streamvault.player.playback
+
+import com.streamvault.player.PlaybackState
+
+internal fun shouldRecoverReadyStalls(resolvedStreamType: ResolvedStreamType): Boolean =
+ true
+
+internal fun shouldRecoverPositionAdvancingReadyStalls(resolvedStreamType: ResolvedStreamType): Boolean =
+ !resolvedStreamType.isLiveForStallRecovery
+
+internal fun shouldRecoverFrameSilentReadyStalls(resolvedStreamType: ResolvedStreamType): Boolean =
+ resolvedStreamType.isLiveForStallRecovery
+
+internal fun shouldReconnectLiveStall(
+ playbackState: PlaybackState,
+ resolvedStreamType: ResolvedStreamType,
+ recoveryAttempt: Int
+): Boolean =
+ recoveryAttempt == 1 &&
+ (
+ playbackState == PlaybackState.BUFFERING && resolvedStreamType.isLiveForStallRecovery ||
+ playbackState == PlaybackState.READY && resolvedStreamType.isLiveForStallRecovery
+ )
+
+private val ResolvedStreamType.isLiveForStallRecovery: Boolean
+ get() = this == ResolvedStreamType.HLS ||
+ this == ResolvedStreamType.SMOOTH_STREAMING ||
+ this == ResolvedStreamType.MPEG_TS_LIVE ||
+ this == ResolvedStreamType.RTSP
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
index f7a3b865..253b6111 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
@@ -14,6 +14,9 @@ import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.Protocol
+internal fun shouldUsePlatformHttpDataSource(resolvedStreamType: ResolvedStreamType): Boolean =
+ false
+
@UnstableApi
class PlayerDataSourceFactoryProvider(
private val context: Context,
@@ -64,7 +67,16 @@ class PlayerDataSourceFactoryProvider(
setDefaultRequestProperties(headers)
}
}
- val factory = DefaultDataSource.Factory(context, upstreamFactory)
+ val defaultFactory = DefaultDataSource.Factory(context, upstreamFactory)
+ val factory = if (shouldWrapDataSourceReadStats(resolvedStreamType)) {
+ PlayerDataSourceReadStatsFactory(
+ upstream = defaultFactory,
+ resolvedStreamType = resolvedStreamType,
+ initialTargetUrl = streamInfo.url
+ )
+ } else {
+ defaultFactory
+ }
return profile to factory
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt
new file mode 100644
index 00000000..4c550fb9
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt
@@ -0,0 +1,176 @@
+package com.streamvault.player.playback
+
+import android.net.Uri
+import android.os.SystemClock
+import android.util.Log
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.TransferListener
+import java.io.IOException
+
+@UnstableApi
+internal class PlayerDataSourceReadStatsFactory(
+ private val upstream: DataSource.Factory,
+ private val resolvedStreamType: ResolvedStreamType,
+ private val initialTargetUrl: String,
+ private val clockMs: () -> Long = SystemClock::elapsedRealtime
+) : DataSource.Factory {
+ override fun createDataSource(): DataSource =
+ PlayerDataSourceReadStatsDataSource(
+ upstream = upstream.createDataSource(),
+ resolvedStreamType = resolvedStreamType,
+ initialTargetUrl = initialTargetUrl,
+ clockMs = clockMs
+ )
+}
+
+internal fun shouldWrapDataSourceReadStats(resolvedStreamType: ResolvedStreamType): Boolean =
+ resolvedStreamType == ResolvedStreamType.HLS ||
+ resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE
+
+@UnstableApi
+private class PlayerDataSourceReadStatsDataSource(
+ private val upstream: DataSource,
+ private val resolvedStreamType: ResolvedStreamType,
+ initialTargetUrl: String,
+ private val clockMs: () -> Long
+) : DataSource {
+ private val tracker = PlayerDataSourceReadStatsTracker()
+ private var target = PlaybackLogSanitizer.sanitizeUrl(initialTargetUrl)
+ private var opened = false
+
+ override fun addTransferListener(transferListener: TransferListener) {
+ upstream.addTransferListener(transferListener)
+ }
+
+ @Throws(IOException::class)
+ override fun open(dataSpec: DataSpec): Long {
+ target = PlaybackLogSanitizer.sanitizeUrl(dataSpec.uri.toString())
+ val length = upstream.open(dataSpec)
+ tracker.open(clockMs())
+ opened = true
+ if (readStatsLoggingEnabled()) {
+ Log.d(
+ TAG,
+ "read-open streamType=$resolvedStreamType position=${dataSpec.position} length=$length target=$target"
+ )
+ }
+ return length
+ }
+
+ @Throws(IOException::class)
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
+ val bytesRead = upstream.read(buffer, offset, length)
+ if (bytesRead > 0 && readStatsLoggingEnabled()) {
+ tracker.recordRead(bytesRead, clockMs())?.let(::logProgress)
+ }
+ return bytesRead
+ }
+
+ override fun getUri(): Uri? = upstream.uri
+
+ override fun getResponseHeaders(): Map<String, List<String>> = upstream.responseHeaders
+
+ @Throws(IOException::class)
+ override fun close() {
+ try {
+ upstream.close()
+ } finally {
+ if (opened && readStatsLoggingEnabled()) {
+ logClose(tracker.snapshot(clockMs()))
+ }
+ opened = false
+ }
+ }
+
+ private fun logProgress(snapshot: PlayerDataSourceReadStatsSnapshot) {
+ Log.d(
+ TAG,
+ "read-progress streamType=$resolvedStreamType bytes=${snapshot.totalBytes} " +
+ "deltaBytes=${snapshot.deltaBytes} elapsedMs=${snapshot.elapsedMs} " +
+ "intervalMs=${snapshot.intervalMs} avgKbps=${snapshot.averageKbps} " +
+ "intervalKbps=${snapshot.intervalKbps} target=$target"
+ )
+ }
+
+ private fun logClose(snapshot: PlayerDataSourceReadStatsSnapshot) {
+ Log.d(
+ TAG,
+ "read-close streamType=$resolvedStreamType bytes=${snapshot.totalBytes} " +
+ "elapsedMs=${snapshot.elapsedMs} avgKbps=${snapshot.averageKbps} target=$target"
+ )
+ }
+
+ private fun readStatsLoggingEnabled(): Boolean = Log.isLoggable(TAG, Log.DEBUG)
+
+ private companion object {
+ const val TAG = "PlayerDataReadStats"
+ }
+}
+
+internal class PlayerDataSourceReadStatsTracker(
+ private val minLogIntervalMs: Long = MIN_LOG_INTERVAL_MS,
+ private val minLogDeltaBytes: Long = MIN_LOG_DELTA_BYTES
+) {
+ private var openedAtMs: Long = 0L
+ private var lastLogAtMs: Long = 0L
+ private var lastLogBytes: Long = 0L
+ private var totalBytes: Long = 0L
+
+ fun open(nowMs: Long) {
+ openedAtMs = nowMs
+ lastLogAtMs = nowMs
+ lastLogBytes = 0L
+ totalBytes = 0L
+ }
+
+ fun recordRead(bytesRead: Int, nowMs: Long): PlayerDataSourceReadStatsSnapshot? {
+ if (bytesRead <= 0) return null
+
+ totalBytes += bytesRead.toLong()
+ val intervalMs = nowMs - lastLogAtMs
+ val deltaBytes = totalBytes - lastLogBytes
+ if (intervalMs < minLogIntervalMs && deltaBytes < minLogDeltaBytes) {
+ return null
+ }
+
+ return snapshot(nowMs).also {
+ lastLogAtMs = nowMs
+ lastLogBytes = totalBytes
+ }
+ }
+
+ fun snapshot(nowMs: Long): PlayerDataSourceReadStatsSnapshot {
+ val elapsedMs = (nowMs - openedAtMs).coerceAtLeast(0L)
+ val intervalMs = (nowMs - lastLogAtMs).coerceAtLeast(0L)
+ val deltaBytes = totalBytes - lastLogBytes
+ return PlayerDataSourceReadStatsSnapshot(
+ totalBytes = totalBytes,
+ deltaBytes = deltaBytes,
+ elapsedMs = elapsedMs,
+ intervalMs = intervalMs,
+ averageKbps = bytesToKbps(totalBytes, elapsedMs),
+ intervalKbps = bytesToKbps(deltaBytes, intervalMs)
+ )
+ }
+
+ private fun bytesToKbps(bytes: Long, elapsedMs: Long): Long {
+ if (bytes <= 0L || elapsedMs <= 0L) return 0L
+ return (bytes * 8_000L) / elapsedMs / 1_000L
+ }
+
+ companion object {
+ const val MIN_LOG_INTERVAL_MS = 2_000L
+ const val MIN_LOG_DELTA_BYTES = 512L * 1024L
+ }
+}
+
+internal data class PlayerDataSourceReadStatsSnapshot(
+ val totalBytes: Long,
+ val deltaBytes: Long,
+ val elapsedMs: Long,
+ val intervalMs: Long,
+ val averageKbps: Long,
+ val intervalKbps: Long
+)
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
index a389e2b0..503ad634 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
@@ -1,3 +1,5 @@
+@file:androidx.media3.common.util.UnstableApi
+
package com.streamvault.player.playback
import android.net.Uri
@@ -9,6 +11,7 @@ import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.extractor.DefaultExtractorsFactory
+import androidx.media3.extractor.ts.TsExtractor
import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactory
import androidx.media3.exoplayer.dash.DashMediaSource
import androidx.media3.exoplayer.hls.HlsMediaSource
@@ -24,6 +27,26 @@ import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
import java.util.UUID
+/** Explicit CEA-608 and CEA-708 closed caption formats for MPEG-TS streams. */
+private val TS_SUBTITLE_FORMATS: List<Format> = listOf(
+ Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_CEA608).build(),
+ Format.Builder()
+ .setSampleMimeType(MimeTypes.APPLICATION_CEA708)
+ .setCodecs("cea-708")
+ .setAccessibilityChannel(1)
+ .build()
+)
+
+internal fun liveMpegTsExtractorsFactory(): DefaultExtractorsFactory =
+ DefaultExtractorsFactory()
+ .setTsExtractorMode(TsExtractor.MODE_HLS)
+ .setTsExtractorFlags(
+ DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS
+ or DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES
+ or DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM
+ )
+ .setTsSubtitleFormats(TS_SUBTITLE_FORMATS)
+
@UnstableApi
class PlayerMediaSourceFactory(
private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider
@@ -65,13 +88,7 @@ class PlayerMediaSourceFactory(
resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> ProgressiveMediaSource.Factory(
dataSourceFactory,
- DefaultExtractorsFactory()
- .setTsExtractorFlags(
- DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS
- or DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES
- or DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM
- )
- .setTsSubtitleFormats(TS_SUBTITLE_FORMATS)
+ liveMpegTsExtractorsFactory()
)
.setLoadErrorHandlingPolicy(retryPolicy)
.createMediaSource(mediaItem)
@@ -139,15 +156,5 @@ class PlayerMediaSourceFactory(
companion object {
private const val TAG = "PlayerMediaSourceFactory"
-
- /** Explicit CEA-608 and CEA-708 closed caption formats for MPEG-TS streams. */
- private val TS_SUBTITLE_FORMATS: List<Format> = listOf(
- Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_CEA608).build(),
- Format.Builder()
- .setSampleMimeType(MimeTypes.APPLICATION_CEA708)
- .setCodecs("cea-708")
- .setAccessibilityChannel(1)
- .build()
- )
}
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt
index c8197dcd..40471acb 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt
@@ -11,6 +11,7 @@ import java.net.SocketTimeoutException
import java.net.UnknownHostException
private const val LIVE_WINDOW_RETRY_DELAY_MS = 500L
+private const val LIVE_HLS_MALFORMED_RETRY_ATTEMPTS_AFTER_START = 12
data class PlaybackRetryContext(
val resolvedStreamType: ResolvedStreamType,
@@ -62,7 +63,24 @@ class PlayerRetryPolicy(
PlaybackErrorCategory.LIVE_WINDOW -> "refresh-live-window"
PlaybackErrorCategory.NETWORK -> "transient-network"
PlaybackErrorCategory.HTTP_SERVER -> "server-retryable"
- else -> "retryable-source"
+ PlaybackErrorCategory.SOURCE_MALFORMED ->
+ if (streamContext.resolvedStreamType == ResolvedStreamType.HLS) {
+ "malformed-live-hls-refresh"
+ } else {
+ "malformed-source"
+ }
+ PlaybackErrorCategory.HTTP_AUTH -> "terminal-auth"
+ PlaybackErrorCategory.SSL -> "terminal-tls"
+ PlaybackErrorCategory.CLEAR_TEXT_BLOCKED -> "terminal-cleartext"
+ PlaybackErrorCategory.DRM -> "terminal-drm"
+ PlaybackErrorCategory.DECODER -> "terminal-decoder"
+ PlaybackErrorCategory.FORMAT_UNSUPPORTED -> "format-unsupported"
+ PlaybackErrorCategory.UNKNOWN ->
+ if (streamContext.isLive) {
+ "retryable-live-unknown"
+ } else {
+ "retryable-source"
+ }
}
}
@@ -101,7 +119,8 @@ class PlayerRetryPolicy(
PlaybackErrorCategory.DECODER,
PlaybackErrorCategory.CLEAR_TEXT_BLOCKED,
PlaybackErrorCategory.SSL,
- PlaybackErrorCategory.HTTP_AUTH,
+ PlaybackErrorCategory.HTTP_AUTH -> 0
+
PlaybackErrorCategory.FORMAT_UNSUPPORTED -> if (playbackStarted) 1 else 0
PlaybackErrorCategory.LIVE_WINDOW -> 1
@@ -118,11 +137,16 @@ class PlayerRetryPolicy(
}
PlaybackErrorCategory.SOURCE_MALFORMED -> when {
+ streamContext.resolvedStreamType == ResolvedStreamType.HLS && playbackStarted ->
+ LIVE_HLS_MALFORMED_RETRY_ATTEMPTS_AFTER_START
+ playbackStarted -> 0
+ else -> 1
+ }
+ PlaybackErrorCategory.UNKNOWN -> when {
streamContext.isLive && playbackStarted -> 3
playbackStarted -> 0
else -> 1
}
- PlaybackErrorCategory.UNKNOWN -> if (playbackStarted) 0 else 1
}
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicy.kt
index b78717ca..f0e92603 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicy.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicy.kt
@@ -39,6 +39,16 @@ internal fun resolveRetryAttemptAfterPlaybackStarted(currentAttempt: Int): Int {
return 0
}
+internal fun resolveRetryAttemptForCategory(
+ currentAttempt: Int,
+ lastCategory: PlaybackErrorCategory?,
+ nextCategory: PlaybackErrorCategory
+): Int {
+ if (currentAttempt <= 0) return 1
+ if (lastCategory != nextCategory) return 1
+ return currentAttempt + 1
+}
+
private fun Long?.isFiniteMediaDuration(): Boolean {
return this != null && this != C.TIME_UNSET && this > 0L
}
diff --git a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
index 1c184ba1..e8f31109 100644
--- a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
+++ b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt
@@ -6,6 +6,7 @@ class VideoStallDetector(
private val nowMs: () -> Long = System::currentTimeMillis,
private val initialGraceMs: Long = 8_000L,
private val stallThresholdMs: Long = 5_000L,
+ private val bufferingStallThresholdMs: Long = 20_000L,
private val minPositionAdvanceMs: Long = 1_500L
) {
private var startedAtMs: Long = 0L
@@ -15,6 +16,7 @@ class VideoStallDetector(
private var lastPositionCheckMs: Long = 0L
private var stalled = false
+ @Synchronized
fun reset() {
val now = nowMs()
startedAtMs = now
@@ -25,6 +27,7 @@ class VideoStallDetector(
stalled = false
}
+ @Synchronized
fun onVideoFrameRendered(currentPositionMs: Long = 0L) {
if (lastFrameAtMs <= 0L) {
firstFramePositionMs = currentPositionMs.coerceAtLeast(0L)
@@ -33,27 +36,66 @@ class VideoStallDetector(
stalled = false
}
+ @Synchronized
fun lastVideoFrameAgoMs(): Long {
val frameAt = lastFrameAtMs
return if (frameAt <= 0L) 0L else (nowMs() - frameAt).coerceAtLeast(0L)
}
+ @Synchronized
fun shouldReportStall(
playbackState: PlaybackState,
isPlaying: Boolean,
playbackStarted: Boolean,
currentPositionMs: Long,
- bufferedDurationMs: Long
+ bufferedDurationMs: Long,
+ playWhenReady: Boolean = isPlaying,
+ recoverBufferingStalls: Boolean = false,
+ recoverReadyStalls: Boolean = true,
+ recoverPositionAdvancingReadyStalls: Boolean = true,
+ recoverFrameSilentReadyStalls: Boolean = false
): Boolean {
val now = nowMs()
- if (playbackState != PlaybackState.READY || !isPlaying || !playbackStarted || bufferedDurationMs <= 1_000L) {
+ val playbackRequested = isPlaying || playWhenReady
+ val canEvaluateReadyStall = recoverReadyStalls && playbackState == PlaybackState.READY
+ val canEvaluateBufferingStall = recoverBufferingStalls && playbackState == PlaybackState.BUFFERING
+ if ((!canEvaluateReadyStall && !canEvaluateBufferingStall) || !playbackRequested || !playbackStarted) {
lastPositionMs = currentPositionMs
lastPositionCheckMs = now
stalled = false
return false
}
- if (now - startedAtMs < initialGraceMs || lastFrameAtMs <= 0L) return false
- if (currentPositionMs - firstFramePositionMs < minPositionAdvanceMs) return false
+ if (now - startedAtMs < initialGraceMs) return false
+ if (canEvaluateBufferingStall) {
+ val frameSilent = if (lastFrameAtMs <= 0L) {
+ now - startedAtMs >= bufferingStallThresholdMs
+ } else {
+ now - lastFrameAtMs >= bufferingStallThresholdMs
+ }
+ if (frameSilent && !stalled) {
+ stalled = true
+ return true
+ }
+ if (!frameSilent) stalled = false
+ return false
+ }
+ if (lastFrameAtMs <= 0L) return false
+ val frameSilent = now - lastFrameAtMs >= stallThresholdMs
+ val requestedButNotAdvancing = playWhenReady && !isPlaying && frameSilent
+ val frameSilentReadyRecovery = recoverFrameSilentReadyStalls && frameSilent
+ if (!requestedButNotAdvancing && !frameSilentReadyRecovery && bufferedDurationMs <= 1_000L) {
+ lastPositionMs = currentPositionMs
+ lastPositionCheckMs = now
+ stalled = false
+ return false
+ }
+ if (
+ !requestedButNotAdvancing &&
+ !frameSilentReadyRecovery &&
+ currentPositionMs - firstFramePositionMs < minPositionAdvanceMs
+ ) {
+ return false
+ }
val positionAdvanced = currentPositionMs - lastPositionMs >= minPositionAdvanceMs
val checkWindowElapsed = now - lastPositionCheckMs >= minPositionAdvanceMs
@@ -62,8 +104,11 @@ class VideoStallDetector(
lastPositionCheckMs = now
}
- val frameSilent = now - lastFrameAtMs >= stallThresholdMs
- val nextStalled = positionAdvanced && frameSilent
+ val nextStalled = (
+ frameSilentReadyRecovery ||
+ requestedButNotAdvancing ||
+ recoverPositionAdvancingReadyStalls && positionAdvanced
+ ) && frameSilent
if (nextStalled && !stalled) {
stalled = true
return true
@@ -72,4 +117,3 @@ class VideoStallDetector(
return false
}
}
-
diff --git a/player/src/test/java/com/streamvault/player/playback/LiveRetryStatePolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveRetryStatePolicyTest.kt
new file mode 100644
index 00000000..93bbc31a
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/LiveRetryStatePolicyTest.kt
@@ -0,0 +1,50 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class LiveRetryStatePolicyTest {
+
+ @Test
+ fun `live window retry preserves started state after first frame`() {
+ assertThat(
+ shouldPreservePlaybackStateForRetry(
+ category = PlaybackErrorCategory.LIVE_WINDOW,
+ playbackStarted = true,
+ liveBufferingRecoveryArmed = false
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `armed live recovery counts as playback started for retry policy`() {
+ assertThat(
+ hasEffectivePlaybackStarted(
+ playbackStarted = false,
+ liveBufferingRecoveryArmed = true
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `live window retry before first frame keeps existing reset behavior`() {
+ assertThat(
+ shouldPreservePlaybackStateForRetry(
+ category = PlaybackErrorCategory.LIVE_WINDOW,
+ playbackStarted = false,
+ liveBufferingRecoveryArmed = false
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `non live window retry preserves existing retry state behavior`() {
+ assertThat(
+ shouldPreservePlaybackStateForRetry(
+ category = PlaybackErrorCategory.NETWORK,
+ playbackStarted = false,
+ liveBufferingRecoveryArmed = false
+ )
+ ).isTrue()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/LiveTsFallbackUrlTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveTsFallbackUrlTest.kt
new file mode 100644
index 00000000..0b74189a
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/LiveTsFallbackUrlTest.kt
@@ -0,0 +1,75 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class LiveTsFallbackUrlTest {
+
+ @Test
+ fun `live hls path is converted to transport stream path`() {
+ val fallback = buildLiveTsFallbackUrl("https://example.test/live/user/pass/61351.m3u8")
+
+ assertThat(fallback).isEqualTo("https://example.test/live/user/pass/61351.ts")
+ }
+
+ @Test
+ fun `live hls query extension is converted to transport stream query extension`() {
+ val fallback = buildLiveTsFallbackUrl("https://example.test/live/user/pass/61351?ext=m3u8")
+
+ assertThat(fallback).isEqualTo("https://example.test/live/user/pass/61351?ext=ts")
+ }
+
+ @Test
+ fun `non hls live url is not converted`() {
+ assertThat(buildLiveTsFallbackUrl("https://example.test/live/user/pass/61351.ts")).isNull()
+ }
+
+ @Test
+ fun `non live hls url is not converted`() {
+ assertThat(buildLiveTsFallbackUrl("https://example.test/movie/user/pass/61351.m3u8")).isNull()
+ }
+
+ @Test
+ fun `malformed hls can use transport stream fallback`() {
+ assertThat(
+ shouldFallbackMalformedHlsToLiveTs(
+ category = PlaybackErrorCategory.SOURCE_MALFORMED,
+ resolvedStreamType = ResolvedStreamType.HLS,
+ playbackStarted = false
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `malformed hls does not switch to transport stream after playback started`() {
+ assertThat(
+ shouldFallbackMalformedHlsToLiveTs(
+ category = PlaybackErrorCategory.SOURCE_MALFORMED,
+ resolvedStreamType = ResolvedStreamType.HLS,
+ playbackStarted = true
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `stalled hls can use transport stream fallback after bounded recoveries`() {
+ assertThat(
+ shouldFallbackStalledHlsToLiveTs(
+ resolvedStreamType = ResolvedStreamType.HLS,
+ recoveryAttempt = 3
+ )
+ ).isTrue()
+ assertThat(
+ shouldFallbackStalledHlsToLiveTs(
+ resolvedStreamType = ResolvedStreamType.HLS,
+ recoveryAttempt = 2
+ )
+ ).isFalse()
+ assertThat(
+ shouldFallbackStalledHlsToLiveTs(
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ recoveryAttempt = 3
+ )
+ ).isFalse()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt
index 907325a5..c7c59efa 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt
@@ -14,6 +14,8 @@ class PlaybackBufferPoliciesTest {
assertThat(policy.maxBufferMs).isEqualTo(30_000)
assertThat(policy.playbackBufferMs).isEqualTo(1_500)
assertThat(policy.rebufferMs).isEqualTo(5_000)
+ assertThat(policy.targetBufferBytes).isEqualTo(-1)
+ assertThat(policy.prioritizeTimeOverSizeThresholds).isTrue()
}
@Test
@@ -25,6 +27,24 @@ class PlaybackBufferPoliciesTest {
assertThat(policy.maxBufferMs).isEqualTo(45_000)
assertThat(policy.playbackBufferMs).isEqualTo(1_500)
assertThat(policy.rebufferMs).isEqualTo(5_000)
+ assertThat(policy.targetBufferBytes).isEqualTo(-1)
+ assertThat(policy.prioritizeTimeOverSizeThresholds).isTrue()
+ }
+
+ @Test
+ fun `mpeg ts live prioritizes playable time over byte target`() {
+ val policy = PlaybackBufferPolicies.forPlayback(
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ compatibilityMode = false
+ )
+
+ assertThat(policy.label).isEqualTo("mpeg-ts-live")
+ assertThat(policy.minBufferMs).isEqualTo(5_000)
+ assertThat(policy.maxBufferMs).isEqualTo(10_000)
+ assertThat(policy.playbackBufferMs).isEqualTo(1_500)
+ assertThat(policy.rebufferMs).isEqualTo(5_000)
+ assertThat(policy.targetBufferBytes).isEqualTo(16 * 1024 * 1024)
+ assertThat(policy.prioritizeTimeOverSizeThresholds).isTrue()
}
@Test
@@ -36,5 +56,7 @@ class PlaybackBufferPoliciesTest {
assertThat(policy.maxBufferMs).isEqualTo(240_000)
assertThat(policy.playbackBufferMs).isEqualTo(8_000)
assertThat(policy.rebufferMs).isEqualTo(18_000)
+ assertThat(policy.targetBufferBytes).isEqualTo(-1)
+ assertThat(policy.prioritizeTimeOverSizeThresholds).isTrue()
}
}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt
new file mode 100644
index 00000000..534859f3
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt
@@ -0,0 +1,34 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class PlaybackLogSanitizerTest {
+ @Test
+ fun `redacts live username and password path segments`() {
+ val sanitized = PlaybackLogSanitizer.sanitizeUrl(
+ "https://example.test/live/user-name/password-value/61351.m3u8"
+ )
+
+ assertThat(sanitized).isEqualTo("example.test/live/<redacted>/<redacted>/61351.m3u8")
+ }
+
+ @Test
+ fun `redacts opaque segment token path`() {
+ val sanitized = PlaybackLogSanitizer.sanitizeUrl(
+ "https://example.test/r/a4b5206dad97d1070000000000006eb4/61351_1429.ts"
+ )
+
+ assertThat(sanitized).isEqualTo("example.test/r/<redacted>/61351_1429.ts")
+ }
+
+ @Test
+ fun `redacts opaque segment token in messages`() {
+ val sanitized = PlaybackLogSanitizer.sanitizeMessage(
+ "read target=https://example.test/r/a4b5206dad97d1070000000000006eb4/61351_1429.ts"
+ )
+
+ assertThat(sanitized).doesNotContain("a4b5206dad97d1070000000000006eb4")
+ assertThat(sanitized).contains("/r/<redacted>/61351_1429.ts")
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt
new file mode 100644
index 00000000..9013a97c
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt
@@ -0,0 +1,59 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.player.PlaybackState
+import org.junit.Test
+
+class PlaybackStallRecoveryPolicyTest {
+ @Test
+ fun `ready stalls are recovered for live transport streams`() {
+ assertThat(shouldRecoverReadyStalls(ResolvedStreamType.MPEG_TS_LIVE)).isTrue()
+ }
+
+ @Test
+ fun `position advancing ready stalls are not recovered for live streams`() {
+ assertThat(shouldRecoverPositionAdvancingReadyStalls(ResolvedStreamType.MPEG_TS_LIVE)).isFalse()
+ assertThat(shouldRecoverPositionAdvancingReadyStalls(ResolvedStreamType.HLS)).isFalse()
+ assertThat(shouldRecoverPositionAdvancingReadyStalls(ResolvedStreamType.PROGRESSIVE)).isTrue()
+ }
+
+ @Test
+ fun `frame silent ready stalls are recovered for live streams`() {
+ assertThat(shouldRecoverFrameSilentReadyStalls(ResolvedStreamType.MPEG_TS_LIVE)).isTrue()
+ assertThat(shouldRecoverFrameSilentReadyStalls(ResolvedStreamType.HLS)).isTrue()
+ assertThat(shouldRecoverFrameSilentReadyStalls(ResolvedStreamType.PROGRESSIVE)).isFalse()
+ }
+
+ @Test
+ fun `live ready stalls reconnect the current stream`() {
+ assertThat(
+ shouldReconnectLiveStall(
+ playbackState = PlaybackState.READY,
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ recoveryAttempt = 1
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `live ready stalls stop reconnecting after first recovery attempt`() {
+ assertThat(
+ shouldReconnectLiveStall(
+ playbackState = PlaybackState.READY,
+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,
+ recoveryAttempt = 2
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `vod ready stalls do not reconnect as live streams`() {
+ assertThat(
+ shouldReconnectLiveStall(
+ playbackState = PlaybackState.READY,
+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,
+ recoveryAttempt = 1
+ )
+ ).isFalse()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt
new file mode 100644
index 00000000..1b2f112f
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt
@@ -0,0 +1,24 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class PlayerDataSourceFactoryProviderTest {
+ @Test
+ fun `mpeg ts live keeps okhttp data source`() {
+ assertThat(shouldUsePlatformHttpDataSource(ResolvedStreamType.MPEG_TS_LIVE)).isFalse()
+ }
+
+ @Test
+ fun `hls keeps okhttp data source`() {
+ assertThat(shouldUsePlatformHttpDataSource(ResolvedStreamType.HLS)).isFalse()
+ }
+
+ @Test
+ fun `read stats wrap only live stream types`() {
+ assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.HLS)).isTrue()
+ assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.MPEG_TS_LIVE)).isTrue()
+ assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.PROGRESSIVE)).isFalse()
+ assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.DASH)).isFalse()
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceReadStatsTrackerTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceReadStatsTrackerTest.kt
new file mode 100644
index 00000000..8cb6ac44
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceReadStatsTrackerTest.kt
@@ -0,0 +1,69 @@
+package com.streamvault.player.playback
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class PlayerDataSourceReadStatsTrackerTest {
+ @Test
+ fun `does not emit before thresholds`() {
+ val tracker = PlayerDataSourceReadStatsTracker(
+ minLogIntervalMs = 2_000,
+ minLogDeltaBytes = 1_000
+ )
+
+ tracker.open(nowMs = 100)
+
+ assertThat(tracker.recordRead(bytesRead = 400, nowMs = 500)).isNull()
+ }
+
+ @Test
+ fun `emits when byte threshold is reached`() {
+ val tracker = PlayerDataSourceReadStatsTracker(
+ minLogIntervalMs = 2_000,
+ minLogDeltaBytes = 1_000
+ )
+
+ tracker.open(nowMs = 100)
+ val snapshot = tracker.recordRead(bytesRead = 1_000, nowMs = 600)
+
+ assertThat(snapshot).isEqualTo(
+ PlayerDataSourceReadStatsSnapshot(
+ totalBytes = 1_000,
+ deltaBytes = 1_000,
+ elapsedMs = 500,
+ intervalMs = 500,
+ averageKbps = 16,
+ intervalKbps = 16
+ )
+ )
+ }
+
+ @Test
+ fun `emits when time threshold is reached`() {
+ val tracker = PlayerDataSourceReadStatsTracker(
+ minLogIntervalMs = 2_000,
+ minLogDeltaBytes = 1_000_000
+ )
+
+ tracker.open(nowMs = 100)
+ val snapshot = tracker.recordRead(bytesRead = 800, nowMs = 2_100)
+
+ assertThat(snapshot?.totalBytes).isEqualTo(800)
+ assertThat(snapshot?.elapsedMs).isEqualTo(2_000)
+ assertThat(snapshot?.averageKbps).isEqualTo(3)
+ }
+
+ @Test
+ fun `ignores non positive reads`() {
+ val tracker = PlayerDataSourceReadStatsTracker(
+ minLogIntervalMs = 1,
+ minLogDeltaBytes = 1
+ )
+
+ tracker.open(nowMs = 100)
+
+ assertThat(tracker.recordRead(bytesRead = 0, nowMs = 200)).isNull()
+ assertThat(tracker.recordRead(bytesRead = -1, nowMs = 300)).isNull()
+ assertThat(tracker.snapshot(nowMs = 300).totalBytes).isEqualTo(0)
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt
new file mode 100644
index 00000000..fae196fa
--- /dev/null
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt
@@ -0,0 +1,18 @@
+package com.streamvault.player.playback
+
+import androidx.media3.extractor.ts.TsExtractor
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class PlayerMediaSourceFactoryTest {
+
+ @Test
+ fun `live mpeg ts extractor uses hls mode to avoid finite progressive duration`() {
+ val factory = liveMpegTsExtractorsFactory()
+ val modeField = factory::class.java.getDeclaredField("tsMode").apply {
+ isAccessible = true
+ }
+
+ assertThat(modeField.getInt(factory)).isEqualTo(TsExtractor.MODE_HLS)
+ }
+}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt
index 62b37ea4..a8b836c8 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt
@@ -1,9 +1,12 @@
package com.streamvault.player.playback
+import android.os.Bundle
import androidx.media3.common.ParserException
+import androidx.media3.common.PlaybackException
import androidx.media3.exoplayer.source.BehindLiveWindowException
import com.google.common.truth.Truth.assertThat
import java.io.IOException
+import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
import org.junit.Test
@@ -39,24 +42,65 @@ class PlayerRetryPolicyTest {
.isFalse()
}
+ @Test
+ fun `auth failure after playback start stays terminal`() {
+ val error = IOException("HTTP 403")
+
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(0)
+ assertThat(policy.retryReason(error)).isEqualTo("terminal-auth")
+ }
+
@Test
fun `ssl error never retries`() {
assertThat(policy.shouldRetry(SSLHandshakeException("bad cert"), liveContext, playbackStarted = false, attempt = 1))
.isFalse()
}
+ @Test
+ fun `ssl failure after playback start stays terminal`() {
+ val error = SSLHandshakeException("certificate verify failed")
+
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(0)
+ assertThat(policy.retryReason(error)).isEqualTo("terminal-tls")
+ }
+
+ @Test
+ fun `cleartext failure after playback start stays terminal`() {
+ val error = IOException("cleartext traffic not permitted")
+
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(0)
+ assertThat(policy.retryReason(error)).isEqualTo("terminal-cleartext")
+ }
+
+ @Test
+ fun `drm failure after playback start stays terminal`() {
+ val error = TestPlaybackException(
+ "drm license failed",
+ PlaybackException.ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED
+ )
+
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(0)
+ assertThat(policy.retryReason(error)).isEqualTo("terminal-drm")
+ }
+
@Test
fun `behind live window retries once`() {
val error = BehindLiveWindowException()
assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 1)).isTrue()
assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 2)).isFalse()
assertThat(policy.retryDelayMs(error, 1)).isEqualTo(500L)
+ assertThat(policy.retryReason(error)).isEqualTo("refresh-live-window")
}
@Test
fun `decoder init failure does not go through network retry policy`() {
val error = IllegalStateException("decoder init failed")
assertThat(policy.shouldRetry(error, liveContext, playbackStarted = false, attempt = 1)).isFalse()
+ assertThat(policy.retryReason(error)).isEqualTo("terminal-decoder")
}
@Test
@@ -81,16 +125,24 @@ class PlayerRetryPolicyTest {
assertThat(progressivePolicy.shouldRetry(error, progressiveContext, playbackStarted = true, attempt = 3)).isTrue()
assertThat(progressivePolicy.shouldRetry(error, progressiveContext, playbackStarted = true, attempt = 4)).isFalse()
assertThat(progressivePolicy.maxAttempts(error, playbackStarted = true)).isEqualTo(3)
+ assertThat(progressivePolicy.retryReason(error)).isEqualTo("server-retryable")
+ }
+
+ @Test
+ fun `network errors keep transient retry reason`() {
+ val error = SocketTimeoutException("timed out")
+
+ assertThat(policy.retryReason(error)).isEqualTo("transient-network")
}
@Test
- fun `malformed live segment after playback start retries as transient source failure`() {
+ fun `malformed hls refresh after playback start retries before app recovery`() {
val error = ParserException.createForMalformedContainer("bad live segment", null)
assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isTrue()
- assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 2)).isTrue()
- assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 3)).isTrue()
- assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 4)).isFalse()
- assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(3)
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 12)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 13)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(12)
+ assertThat(policy.retryReason(error)).isEqualTo("malformed-live-hls-refresh")
}
@Test
@@ -98,4 +150,19 @@ class PlayerRetryPolicyTest {
val error = ParserException.createForMalformedContainer("bad movie segment", null)
assertThat(progressivePolicy.shouldRetry(error, progressiveContext, playbackStarted = true, attempt = 1)).isFalse()
}
+
+ @Test
+ fun `unknown live runtime error after playback start retries before surfacing`() {
+ val error = RuntimeException("Unexpected runtime error")
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 1)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 2)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 3)).isTrue()
+ assertThat(policy.shouldRetry(error, liveContext, playbackStarted = true, attempt = 4)).isFalse()
+ assertThat(policy.maxAttempts(error, playbackStarted = true)).isEqualTo(3)
+ }
+
+ private class TestPlaybackException(
+ message: String,
+ errorCode: Int
+ ) : PlaybackException(message, null, errorCode, Bundle.EMPTY, 0L)
}
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicyTest.kt
index 5d1101f9..8737d919 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicyTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerRetrySeekPositionPolicyTest.kt
@@ -102,4 +102,26 @@ class PlayerRetrySeekPositionPolicyTest {
assertThat(nextAttempt).isEqualTo(0)
}
+
+ @Test
+ fun `new retry category starts its own attempt budget`() {
+ val nextAttempt = resolveRetryAttemptForCategory(
+ currentAttempt = 1,
+ lastCategory = PlaybackErrorCategory.LIVE_WINDOW,
+ nextCategory = PlaybackErrorCategory.SOURCE_MALFORMED
+ )
+
+ assertThat(nextAttempt).isEqualTo(1)
+ }
+
+ @Test
+ fun `same retry category increments current attempt`() {
+ val nextAttempt = resolveRetryAttemptForCategory(
+ currentAttempt = 2,
+ lastCategory = PlaybackErrorCategory.SOURCE_MALFORMED,
+ nextCategory = PlaybackErrorCategory.SOURCE_MALFORMED
+ )
+
+ assertThat(nextAttempt).isEqualTo(3)
+ }
}
diff --git a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
index c4770883..0db689ba 100644
--- a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt
@@ -53,6 +53,26 @@ class VideoStallDetectorTest {
).isFalse()
}
+ @Test
+ fun `does not report ready stall when ready stall recovery is disabled`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = true,
+ playbackStarted = true,
+ currentPositionMs = 3_000L,
+ bufferedDurationMs = 5_000L,
+ recoverReadyStalls = false
+ )
+ ).isFalse()
+ }
+
@Test
fun `does not report while buffering paused or empty buffered`() {
val detector = detector()
@@ -67,6 +87,206 @@ class VideoStallDetectorTest {
assertThat(detector.shouldReportStall(PlaybackState.READY, true, true, 4_000L, 0L)).isFalse()
}
+ @Test
+ fun `reports live buffering recovery after prior playback started without new frame`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.BUFFERING,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 0L,
+ bufferedDurationMs = 0L,
+ recoverBufferingStalls = true
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `does not report live buffering recovery before grace period`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 3_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.BUFFERING,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 0L,
+ bufferedDurationMs = 0L,
+ recoverBufferingStalls = true
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `does not report live buffering recovery before buffering threshold`() {
+ val detector = VideoStallDetector(
+ nowMs = { nowMs },
+ initialGraceMs = 5_000L,
+ stallThresholdMs = 4_000L,
+ bufferingStallThresholdMs = 10_000L,
+ minPositionAdvanceMs = 1_000L
+ )
+ detector.reset()
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.BUFFERING,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 0L,
+ bufferedDurationMs = 0L,
+ recoverBufferingStalls = true
+ )
+ ).isFalse()
+
+ nowMs = 10_000L
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.BUFFERING,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 0L,
+ bufferedDurationMs = 0L,
+ recoverBufferingStalls = true
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `reports when playback is requested but exoplayer stops isPlaying updates`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 500L,
+ bufferedDurationMs = 5_000L
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `reports requested playback stall even when live buffer is empty`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 500L,
+ bufferedDurationMs = 0L
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `does not report position advancing ready stall when that recovery is disabled`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = true,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 3_000L,
+ bufferedDurationMs = 5_000L,
+ recoverPositionAdvancingReadyStalls = false
+ )
+ ).isFalse()
+ }
+
+ @Test
+ fun `reports requested playback stall when position advancing recovery is disabled`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = false,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 500L,
+ bufferedDurationMs = 5_000L,
+ recoverPositionAdvancingReadyStalls = false
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `reports live ready stall when frames stop and live position is not useful`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 0L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = true,
+ playWhenReady = true,
+ playbackStarted = true,
+ currentPositionMs = 0L,
+ bufferedDurationMs = 0L,
+ recoverPositionAdvancingReadyStalls = false,
+ recoverFrameSilentReadyStalls = true
+ )
+ ).isTrue()
+ }
+
+ @Test
+ fun `does not report when playback is not requested`() {
+ val detector = detector()
+ detector.reset()
+ nowMs = 1_000L
+ detector.onVideoFrameRendered(currentPositionMs = 500L)
+ nowMs = 9_000L
+
+ assertThat(
+ detector.shouldReportStall(
+ playbackState = PlaybackState.READY,
+ isPlaying = false,
+ playWhenReady = false,
+ playbackStarted = true,
+ currentPositionMs = 500L,
+ bufferedDurationMs = 5_000L
+ )
+ ).isFalse()
+ }
+
@Test
fun `new rendered frame clears stalled state`() {
val detector = detector()
@@ -105,7 +325,7 @@ class VideoStallDetectorTest {
nowMs = { nowMs },
initialGraceMs = 5_000L,
stallThresholdMs = 4_000L,
+ bufferingStallThresholdMs = 4_000L,
minPositionAdvanceMs = 1_000L
)
}
-