StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Enhance catch-up support and subtitle management
David Nashash9edb18660998
diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex 9bcbbbd1..1334f167 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -508,7 +508,10 @@ class RecordingManagerImpl @Inject constructor(override suspend fun setScheduleEnabled(recordingId: String, enabled: Boolean): Result<Unit> = withContext(Dispatchers.IO) {if (enabled && !alarmScheduler.canScheduleExactAlarms()) {- return@withContext Result.error(RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ return@withContext Result.error(+ RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE,+ exactRecordingAlarmAccessException()+ )}val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")@@ -1338,10 +1341,15 @@ class RecordingManagerImpl @Inject constructor(private fun ensureExactRecordingAlarmsAvailableOrThrow() {if (!alarmScheduler.canScheduleExactAlarms()) {- throw com.streamvault.domain.model.ExactRecordingAlarmAccessException(RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ throw exactRecordingAlarmAccessException()}}+ private fun exactRecordingAlarmAccessException() =+ com.streamvault.domain.model.ExactRecordingAlarmAccessException(+ RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE+ )+private suspend fun scheduleStartAlarmOrFail(recordingId: String, whenMs: Long) {when (val result = alarmScheduler.scheduleStart(recordingId, whenMs)) {is Result.Success -> Unitdiff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.ktindex 68bf4f63..c9441d45 100644--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt@@ -224,7 +224,7 @@ class M3uParser {catchUp = extinf.catchUp?.takeIf(String::isNotBlank)?: extinf.catchUpType?.takeIf(String::isNotBlank),catchUpDays = extinf.catchUpDays?.toIntOrNull()?.takeIf { it in 0..365 }- ?: extinf.timeshift?.toIntOrNull()?.takeIf { it in 0..365 },+ ?: extinf.timeshift?.toIntOrNull()?.takeIf { it in 1..365 },catchUpSource = extinf.catchUpSource,timeshift = extinf.timeshift,url = url,@@ -238,14 +238,15 @@ class M3uParser {?.trim()?.lowercase()?.takeIf(String::isNotBlank)- ?: extinf.timeshift?.takeIf(String::isNotBlank)?.let { "shift" },+ ?: extinf.timeshift?.toIntOrNull()?.takeIf { it > 0 }?.let { "shift" },catchUpCorrectionSeconds = parseCatchUpCorrectionSeconds(extinf.catchUpCorrection)?: globalCatchUpCorrectionSeconds)}private fun M3uEntry.supportsCatchUp(): Boolean {- return !catchUpType.isNullOrBlank() || !catchUpSource.isNullOrBlank() || !timeshift.isNullOrBlank()+ return !catchUpType.isNullOrBlank() || !catchUpSource.isNullOrBlank() ||+ (timeshift?.toIntOrNull() ?: 0) > 0}private fun parseCatchUpCorrectionSeconds(value: String?): Int? {diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.ktindex f7f1441e..d1ba68fd 100644--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt@@ -82,7 +82,8 @@ class ChannelRepositoryImpl @Inject constructor(val labelMode: GroupedChannelLabelMode,val preferenceMode: LiveVariantPreferenceMode,val preferredVariants: Map<String, Long>,- val observedQualities: Map<Long, LiveChannelObservedQuality>+ val observedQualities: Map<Long, LiveChannelObservedQuality>,+ val catchUpFallbackAvailable: Boolean)private val channelNumberComparator = compareBy<Channel>(@@ -269,7 +270,7 @@ class ChannelRepositoryImpl @Inject constructor(val settings = currentPresentationSettings()val observation = settings.observedQualities[channelId]if (settings.groupingMode == LiveChannelGroupingMode.RAW_VARIANTS || entity.logicalGroupId.isBlank()) {- return entity.toPresentedRawChannel(observation, stalkerPortalUrl)+ return entity.toPresentedRawChannel(observation, stalkerPortalUrl, settings.catchUpFallbackAvailable)}val groupedEntities = channelDao.getByLogicalGroupId(entity.providerId, entity.logicalGroupId).ifEmpty { listOf(entity) }@@ -429,9 +430,10 @@ class ChannelRepositoryImpl @Inject constructor(preferencesRepository.liveChannelNumberingMode,preferencesRepository.liveChannelGroupingMode,preferencesRepository.groupedChannelLabelMode,- preferencesRepository.liveVariantPreferenceMode- ) { numberingMode, groupingMode, labelMode, preferenceMode ->- arrayOf(numberingMode, groupingMode, labelMode, preferenceMode)+ preferencesRepository.liveVariantPreferenceMode,+ preferencesRepository.m3uCatchUpQueryFormat+ ) { numberingMode, groupingMode, labelMode, preferenceMode, catchUpQueryFormat ->+ arrayOf(numberingMode, groupingMode, labelMode, preferenceMode, catchUpQueryFormat)},preferencesRepository.liveVariantSelections,preferencesRepository.liveVariantObservations@@ -442,7 +444,8 @@ class ChannelRepositoryImpl @Inject constructor(labelMode = settingsArray[2] as GroupedChannelLabelMode,preferenceMode = settingsArray[3] as LiveVariantPreferenceMode,preferredVariants = preferredVariants,- observedQualities = observedQualities+ observedQualities = observedQualities,+ catchUpFallbackAvailable = (settingsArray[4] as String).isNotBlank())}@@ -487,7 +490,8 @@ class ChannelRepositoryImpl @Inject constructor(rawById[rawId]?.let { entity ->entity.toPresentedRawChannel(settings.observedQualities[rawId],- stalkerPortalUrlForProvider(entity.providerId)+ stalkerPortalUrlForProvider(entity.providerId),+ settings.catchUpFallbackAvailable)}}@@ -523,7 +527,8 @@ class ChannelRepositoryImpl @Inject constructor(entities.map { entity ->entity.toPresentedRawChannel(settings.observedQualities[entity.id],- portalRootForProvider(entity.providerId)+ portalRootForProvider(entity.providerId),+ settings.catchUpFallbackAvailable)}} else {@@ -599,6 +604,7 @@ class ChannelRepositoryImpl @Inject constructor(catchUpSource = selectedVariant.catchUpSource,catchUpType = selectedVariant.catchUpType,catchUpCorrectionSeconds = selectedVariant.catchUpCorrectionSeconds,+ catchUpFallbackAvailable = settings.catchUpFallbackAvailable,providerId = representative.providerId,isAdult = representative.isAdult,isUserProtected = representative.isUserProtected,@@ -913,7 +919,8 @@ class ChannelRepositoryImpl @Inject constructor(private fun ChannelBrowseEntity.toPresentedRawChannel(observedQuality: LiveChannelObservedQuality?,- stalkerPortalUrl: String?+ stalkerPortalUrl: String?,+ catchUpFallbackAvailable: Boolean): Channel {val variant = toVariant(observedQuality)return Channel(@@ -933,6 +940,7 @@ class ChannelRepositoryImpl @Inject constructor(catchUpSource = catchUpSource,catchUpType = catchUpType,catchUpCorrectionSeconds = catchUpCorrectionSeconds,+ catchUpFallbackAvailable = catchUpFallbackAvailable,providerId = providerId,isAdult = isAdult,isUserProtected = isUserProtected,diff --git a/data/src/main/java/com/streamvault/data/repository/M3uCatchUpUrlBuilder.kt b/data/src/main/java/com/streamvault/data/repository/M3uCatchUpUrlBuilder.ktindex c0b358b1..c5ea1583 100644--- a/data/src/main/java/com/streamvault/data/repository/M3uCatchUpUrlBuilder.kt+++ b/data/src/main/java/com/streamvault/data/repository/M3uCatchUpUrlBuilder.kt@@ -1,14 +1,22 @@package com.streamvault.data.repositoryimport java.net.URI+import java.net.URLEncoder+import java.text.SimpleDateFormatimport java.time.Instantimport java.time.ZoneOffsetimport java.time.format.DateTimeFormatter+import java.util.Dateimport java.util.Locale+import java.util.TimeZoneimport com.streamvault.domain.provider.DEFAULT_M3U_CATCH_UP_QUERY_FORMATprivate val catchUpToken = Regex("\\$\\{([^{}]+)\\}|\\{([^{}]+)\\}")-private val compactJavaDateFormat = Regex("yyyyMMdd(?:HHmmss)?")+private val legacyCatchUpToken = Regex("\\$\\{\\((b|e)\\)([^}]+?)(?::(utc))?\\}")+private val javaDatePatternRun = Regex("([yMLwdDFuHkKhmsS])\\1+")++private const val DATE_LETTERS = "YmdHMS"+private const val MILLIS_PER_SECOND = 1_000Linternal fun buildM3uCatchUpUrls(source: String?,@@ -24,45 +32,58 @@ internal fun buildM3uCatchUpUrls(val template = source?.trim().orEmpty()val mode = catchUpType?.trim()?.lowercase(Locale.ROOT).orEmpty()if (template.hasCatchUpIdPlaceholder()) return emptyList()- val now = System.currentTimeMillis() / 1_000L+ val now = System.currentTimeMillis() / MILLIS_PER_SECONDval correctedStart = start + correctionSecondsval correctedEnd = maxOf(correctedStart + 1L, end + correctionSeconds)val correctedNow = now + correctionSecondsval fullSource = template.takeIf(::hasUrlScheme)- val candidate = when {- fullSource != null -> expandCatchUpTemplate(- fullSource,- correctedStart,- correctedEnd,- correctedNow,- correctionSeconds+ val candidates = when {+ fullSource != null -> listOf(+ expandCatchUpTemplate(+ fullSource,+ correctedStart,+ correctedEnd,+ correctedNow,+ correctionSeconds+ )+ )+ template.isNotBlank() && liveUrl.isNotBlank() && mode in APPEND_MODES -> listOf(+ appendCatchUpSource(+ liveUrl,+ expandCatchUpTemplate(template, correctedStart, correctedEnd, correctedNow, correctionSeconds)+ ))- template.isNotBlank() && liveUrl.isNotBlank() && mode in APPEND_MODES ->- appendCatchUpSource(liveUrl, expandCatchUpTemplate(template, correctedStart, correctedEnd, correctedNow, correctionSeconds))mode in SHIFT_MODES && liveUrl.isNotBlank() -> {val shiftSource = template.ifBlank { "?utc={utc}&lutc={lutc}" }- appendCatchUpSource(liveUrl, expandCatchUpTemplate(shiftSource, correctedStart, correctedEnd, correctedNow, correctionSeconds))+ listOf(+ appendCatchUpSource(+ liveUrl,+ expandCatchUpTemplate(shiftSource, correctedStart, correctedEnd, correctedNow, correctionSeconds)+ )+ )}- mode in APPEND_MODES && liveUrl.isNotBlank() -> {+ mode in APPEND_MODES && liveUrl.isNotBlank() -> listOfNotNull(fallbackTemplate.takeIf(String::isNotBlank)?.let { queryFormat ->appendCatchUpSource(liveUrl,expandCatchUpTemplate(queryFormat, correctedStart, correctedEnd, correctedNow, correctionSeconds))}- }- mode in FLUSSONIC_MODES && liveUrl.isNotBlank() ->- buildFlussonicCatchUpUrl(liveUrl, correctedStart, now)+ )+ mode.isFlussonicMode() && liveUrl.isNotBlank() -> listOfNotNull(+ buildFlussonicCatchUpUrl(liveUrl, correctedStart, correctedEnd)+ )mode in XTREAM_MODES && liveUrl.isNotBlank() ->- buildXtreamCatchUpUrl(liveUrl, correctedStart, correctedEnd)- else -> null+ buildXtreamCatchUpUrls(liveUrl, correctedStart, correctedEnd)+ else -> emptyList()}- return listOfNotNull(candidate?.takeIf(String::isNotBlank)).distinct()+ return candidates.filter(String::isNotBlank).distinct()}private fun String.hasCatchUpIdPlaceholder(): Boolean = catchUpToken.findAll(this).any { match ->- (match.groups[1]?.value ?: match.groups[2]?.value).equals("catchup-id", ignoreCase = true)+ val specifier = match.groups[1]?.value ?: match.groups[2]?.value.orEmpty()+ specifier.substringBefore(':').trim().equals("catchup-id", ignoreCase = true)}private fun expandCatchUpTemplate(@@ -74,53 +95,89 @@ private fun expandCatchUpTemplate(): String {val durationSeconds = (end - start).coerceAtLeast(1L)val durationMinutes = (durationSeconds / 60L).coerceAtLeast(1L)- return catchUpToken.replace(template) { match ->- val rawSpecifier = match.groups[1]?.value ?: match.groups[2]?.value.orEmpty()- val specifier = rawSpecifier.trim()- if (specifier == "YmdHis") {- return@replace formatTimestamp(start, "yyyyMMddHHmmss")+ val expandedLegacy = legacyCatchUpToken.replace(template) { match ->+ val seconds = if (match.groupValues[1] == "b") start else end+ val format = match.groupValues[2]+ if (format.equals("timestamp", ignoreCase = true)) {+ seconds.toString()+ } else {+ formatDateToken(seconds, format) ?: match.value}- if (specifier in setOf("Y", "m", "d", "H", "M", "S")) {- return@replace formatTimestamp(start, specifier)+ }+ return catchUpToken.replace(expandedLegacy) { match ->+ val specifier = (match.groups[1]?.value ?: match.groups[2]?.value.orEmpty()).trim()+ if (specifier.isEmpty()) {+ return@replace match.value}val name = specifier.substringBefore(':').lowercase(Locale.ROOT)val format = specifier.substringAfter(':', "")- when (name) {- "utc", "start" -> formatTimestamp(start, format)- "utcend", "end" -> formatTimestamp(end, format)- "lutc", "now", "timestamp" -> formatTimestamp(now, format)- "duration" -> {- val divisor = format.toLongOrNull()?.takeIf { it > 0L } ?: 1L- (durationSeconds / divisor).toString()+ val instant = when (name) {+ "utc", "start", "start-timestamp", "utcstart" -> start+ "utcend", "end", "stop", "end-timestamp" -> end+ "lutc", "now", "timenow", "currenttime", "timestamp" -> now+ else -> null+ }+ if (instant != null) {+ return@replace if (format.isBlank()) {+ instant.toString()+ } else {+ formatDateToken(instant, format) ?: match.value}+ }+ when (name) {+ "duration" -> formatDivided(durationSeconds, format) ?: match.value"duration_seconds" -> durationSeconds.toString()"duration_minutes" -> durationMinutes.toString()- "offset" -> {- val divisor = format.toLongOrNull()?.takeIf { it > 0L } ?: 1L- ((now - start).coerceAtLeast(0L) / divisor).toString()- }- else -> match.value+ "offset" -> formatDivided((now - start).coerceAtLeast(0L), format) ?: match.value+ else -> formatDateToken(start, specifier) ?: match.value}}}-private fun formatTimestamp(epochSeconds: Long, format: String): String {- if (format.isBlank()) return epochSeconds.toString()- val date = Instant.ofEpochSecond(epochSeconds).atZone(ZoneOffset.UTC)- if (compactJavaDateFormat.matches(format)) {- return runCatching { date.format(DateTimeFormatter.ofPattern(format, Locale.ROOT)) }- .getOrDefault(epochSeconds.toString())+private fun formatDivided(seconds: Long, divisorText: String): String? = if (divisorText.isBlank()) {+ seconds.toString()+} else {+ divisorText.toLongOrNull()?.takeIf { it > 0L }?.let { divisor -> (seconds / divisor).toString() }+}++private fun formatDateToken(epochSeconds: Long, format: String): String? {+ if (format.isBlank()) return null+ if (format.equals("YmdHis", ignoreCase = true)) {+ return formatDateLetters(epochSeconds, "YmdHMS")+ }+ if (format.contains('y') || javaDatePatternRun.containsMatchIn(format)) {+ return runCatching {+ SimpleDateFormat(format, Locale.US).apply {+ timeZone = TimeZone.getTimeZone("UTC")+ }.format(Date(epochSeconds * MILLIS_PER_SECOND))+ }.getOrNull()+ }+ return format.takeIf(::isDateLetterFormat)?.let { formatDateLetters(epochSeconds, it) }+}++private fun isDateLetterFormat(format: String): Boolean {+ var hasDateLetter = false+ format.forEach { character ->+ if (!character.isLetter()) return@forEach+ if (character !in DATE_LETTERS) return false+ hasDateLetter = true}+ return hasDateLetter+}++private fun formatDateLetters(epochSeconds: Long, format: String): String {+ val date = Instant.ofEpochSecond(epochSeconds).atZone(ZoneOffset.UTC)+ fun two(value: Int) = value.toString().padStart(2, '0')return buildString(format.length) {format.forEach { character ->append(when (character) {'Y' -> date.format(DateTimeFormatter.ofPattern("yyyy", Locale.ROOT))- 'm' -> date.format(DateTimeFormatter.ofPattern("MM", Locale.ROOT))- 'd' -> date.format(DateTimeFormatter.ofPattern("dd", Locale.ROOT))- 'H' -> date.format(DateTimeFormatter.ofPattern("HH", Locale.ROOT))- 'M' -> date.format(DateTimeFormatter.ofPattern("mm", Locale.ROOT))- 'S' -> date.format(DateTimeFormatter.ofPattern("ss", Locale.ROOT))+ 'm' -> two(date.monthValue)+ 'd' -> two(date.dayOfMonth)+ 'H' -> two(date.hour)+ 'M' -> two(date.minute)+ 'S' -> two(date.second)else -> character})@@ -146,27 +203,47 @@ private fun appendCatchUpSource(baseUrl: String, source: String): String {return appended + fragment}-private fun buildFlussonicCatchUpUrl(liveUrl: String, start: Long, now: Long): String? {+private fun buildFlussonicCatchUpUrl(liveUrl: String, start: Long, end: Long): String? {val uri = runCatching { URI(liveUrl) }.getOrNull() ?: return nullif (uri.rawAuthority.isNullOrBlank()) return nullval path = uri.rawPath?.takeIf(String::isNotBlank) ?: return nullval lastSegment = path.substringAfterLast('/')- val isHls = lastSegment.endsWith(".m3u8", ignoreCase = true)- val extension = lastSegment.substringAfterLast('.', "ts").takeIf { it.isNotBlank() } ?: "ts"- val streamPath = when {- lastSegment.equals("index.m3u8", ignoreCase = true) -> path.substringBeforeLast('/')- lastSegment.equals("index.ts", ignoreCase = true) -> path.substringBeforeLast('/')- else -> path.substringBeforeLast('/').trimEnd('/') + "/" + lastSegment.substringBeforeLast('.', lastSegment)- }.trimEnd('/')- val archiveName = if (isHls) {- "timeshift_rel-${(now - start).coerceAtLeast(0L)}.m3u8"- } else {- "timeshift_abs-$start.$extension"+ val prefix = path.substringBeforeLast('/', "")+ val durationSeconds = (end - start).coerceAtLeast(1L)+ val archiveName = when {+ lastSegment.endsWith(".m3u8", ignoreCase = true) -> "timeshift_abs-$start.m3u8"+ lastSegment.equals("mpegts", ignoreCase = true) ||+ lastSegment.endsWith(".ts", ignoreCase = true) -> "archive-$start-$durationSeconds.ts"+ else -> return null}- return rebuildUri(uri, "$streamPath/$archiveName")+ val archivePath = prefix.trimEnd('/') + "/" + archiveName+ return rebuildUri(uri, archivePath)}-private fun buildXtreamCatchUpUrl(liveUrl: String, start: Long, end: Long): String? {+private data class XtreamLiveUrlParts(+ val uri: URI,+ val username: String,+ val password: String,+ val streamId: String,+ val extension: String,+ val prefixSegments: List<String>+)++private fun buildXtreamCatchUpUrls(liveUrl: String, start: Long, end: Long): List<String> {+ val parts = parseXtreamLiveUrl(liveUrl) ?: return emptyList()+ val durationMinutes = ((end - start) / 60L).coerceAtLeast(1L)+ val startText = Instant.ofEpochSecond(start)+ .atZone(ZoneOffset.UTC)+ .format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH-mm", Locale.ROOT))+ val path = (parts.prefixSegments ++ listOf("timeshift", parts.username, parts.password, durationMinutes.toString(), startText, "${parts.streamId}.${parts.extension}"))+ .joinToString(separator = "/", prefix = "/")+ val pathUrl = rebuildUri(parts.uri, path)+ val phpUrl = buildXtreamPhpUrl(parts, startText, durationMinutes)+ return listOf(phpUrl, pathUrl).distinct()+}++private fun parseXtreamLiveUrl(liveUrl: String): XtreamLiveUrlParts? {val uri = runCatching { URI(liveUrl) }.getOrNull() ?: return nullif (uri.rawAuthority.isNullOrBlank()) return nullval pathSegments = uri.rawPath.orEmpty().split('/').filter(String::isNotBlank)@@ -182,15 +259,35 @@ private fun buildXtreamCatchUpUrl(liveUrl: String, start: Long, end: Long): Striif (streamId.isBlank()) return nullval extension = streamToken.substringAfterLast('.', "ts").takeIf(String::isNotBlank) ?: "ts"val prefix = pathSegments.take(if (liveIndex >= 0) liveIndex else credentialIndex)- val durationMinutes = ((end - start) / 60L).coerceAtLeast(1L)- val startText = Instant.ofEpochSecond(start)- .atZone(ZoneOffset.UTC)- .format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH-mm", Locale.ROOT))- val catchUpPath = (prefix + listOf("timeshift", username, password, durationMinutes.toString(), startText, "$streamId.$extension"))- .joinToString(separator = "/", prefix = "/")- return rebuildUri(uri, catchUpPath)+ return XtreamLiveUrlParts(uri, username, password, streamId, extension, prefix)+}++private fun buildXtreamPhpUrl(+ parts: XtreamLiveUrlParts,+ startText: String,+ durationMinutes: Long+): String {+ val scriptPath = if (parts.prefixSegments.isEmpty()) {+ "/streaming/timeshift.php"+ } else {+ "/" + parts.prefixSegments.joinToString("/") + "/streaming/timeshift.php"+ }+ val query = listOf(+ "username" to encodeQueryValue(parts.username),+ "password" to encodeQueryValue(parts.password),+ "stream" to encodeQueryValue(parts.streamId),+ "start" to startText,+ "duration" to durationMinutes.toString()+ ).joinToString("&") { (key, value) -> "$key=$value" }+ return buildString {+ append(parts.uri.scheme).append("://").append(parts.uri.rawAuthority)+ append(scriptPath).append('?').append(query)+ }}+private fun encodeQueryValue(value: String): String =+ URLEncoder.encode(value, Charsets.UTF_8.name())+private fun rebuildUri(uri: URI, path: String): String = buildString {append(uri.scheme).append("://").append(uri.rawAuthority).append(path)uri.rawQuery?.let { append('?').append(it) }@@ -200,7 +297,8 @@ private fun rebuildUri(uri: URI, path: String): String = buildString {private fun hasUrlScheme(value: String): Boolean =Regex("^[A-Za-z][A-Za-z0-9+.-]*://").containsMatchIn(value)+private fun String.isFlussonicMode(): Boolean = this == "fs" || startsWith("flussonic")+private val APPEND_MODES = setOf("", "default", "append")private val SHIFT_MODES = setOf("shift", "timeshift")-private val FLUSSONIC_MODES = setOf("fs", "flussonic")private val XTREAM_MODES = setOf("xc", "xc60", "xtream", "xtream-codes")diff --git a/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.ktindex a1704000..9b30d3c7 100644--- a/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImpl.kt@@ -177,9 +177,22 @@ class OpenSubtitlesRepositoryImpl @Inject constructor()if (!legacyCacheFile.isFile || legacyCacheFile.length() <= 0L) return@withContext null- runCatching { legacyCacheFile.copyTo(destination, overwrite = true) }+ val migrated = runCatching { legacyCacheFile.copyTo(destination, overwrite = true) }.getOrNull()?.takeIf { it.isFile && it.length() > 0L }+ if (migrated != null) {+ runCatching { legacyCacheFile.delete() }+ }+ migrated+ }++ override suspend fun deleteCachedSubtitle(downloadId: String) = withContext(Dispatchers.IO) {+ val fileId = downloadId.toLongOrNull()?.takeIf { it > 0L } ?: return@withContext+ runCatching { subtitleCacheFile(fileId).delete() }+ runCatching {+ File(context.cacheDir, "subtitles/opensubtitles/$fileId.srt").delete()+ }+ Unit}private suspend fun <T> requestWithOptionalSession(diff --git a/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.ktindex abec9a31..51901e5b 100644--- a/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/RecordingManagerImplTest.kt@@ -131,6 +131,19 @@ class RecordingManagerImplTest {verify(recordingServiceLauncher, never()).startCapture(any(), any())}+ @Test+ fun `enabling a schedule without exact alarm access returns a typed error`() = runBlocking {+ whenever(alarmScheduler.canScheduleExactAlarms()).thenReturn(false)++ val result = createManager().setScheduleEnabled("recording-1", enabled = true)++ assertThat((result as Result.Error).message)+ .isEqualTo(RecordingAlarmScheduler.EXACT_ALARM_PERMISSION_MESSAGE)+ assertThat(result.exception).isInstanceOf(ExactRecordingAlarmAccessException::class.java)+ verify(recordingRunDao, never()).getById(any())+ Unit+ }+@Testfun `startManualRecording routes capture through foreground service`() = runBlocking {val request = recordingRequest()diff --git a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.ktindex 06e378df..327eaaec 100644--- a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt+++ b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt@@ -447,6 +447,22 @@ class M3uParserTest {assertThat(channels.map { it.catchUpCorrectionSeconds }).containsExactly(-9_000, -9_000).inOrder()}+ @Test+ fun `zero legacy timeshift is not advertised as catch-up`() {+ val channels = parser.parseToChannels(+ """+ #EXTM3U+ #EXTINF:-1 timeshift="0",No Archive+ https://stream.example.com/no-archive.ts+ """.trimIndent().byteInputStream(),+ providerId = 9L+ )++ assertThat(channels.single().catchUpSupported).isFalse()+ assertThat(channels.single().catchUpType).isNull()+ assertThat(channels.single().catchUpDays).isEqualTo(0)+ }+@Testfun `parseToChannels_marksCatchUpSupported_whenOnlyCatchUpSourceExists`() {val channels = parser.parseToChannels(diff --git a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.ktindex 9300f236..b689cbf8 100644--- a/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ChannelRepositoryImplTest.kt@@ -64,6 +64,7 @@ class ChannelRepositoryImplTest {whenever(preferencesRepository.liveVariantPreferenceMode).thenReturn(flowOf(LiveVariantPreferenceMode.BALANCED))whenever(preferencesRepository.liveVariantSelections).thenReturn(flowOf(emptyMap()))whenever(preferencesRepository.liveVariantObservations).thenReturn(flowOf(emptyMap()))+ whenever(preferencesRepository.m3uCatchUpQueryFormat).thenReturn(flowOf("?utc={utc}"))whenever(preferencesRepository.hideDecorativeLiveRows).thenReturn(flowOf(true))whenever(preferencesRepository.getHiddenChannelIds(any())).thenReturn(flowOf(emptySet()))whenever(providerSnapshotDao.getConfigSync(any())).thenReturn(null)@@ -572,6 +573,34 @@ class ChannelRepositoryImplTest {).inOrder()}+ @Test+ fun `presented channels expose whether the catch-up fallback is configured`() = runTest {+ whenever(preferencesRepository.liveChannelGroupingMode).thenReturn(+ flowOf(LiveChannelGroupingMode.RAW_VARIANTS)+ )+ whenever(preferencesRepository.m3uCatchUpQueryFormat).thenReturn(flowOf(""))+ whenever(channelDao.getByIds(listOf(42L))).thenReturn(+ flowOf(+ listOf(+ ChannelBrowseEntity(+ id = 42L,+ streamId = 42L,+ name = "Fallback Channel",+ streamUrl = "https://stream/42.ts",+ number = 1,+ catchUpSupported = true,+ catchUpType = "append",+ providerId = 7L+ )+ )+ )+ )++ val result = createRepository().getChannelsByIds(listOf(42L)).first()++ assertThat(result.single().catchUpFallbackAvailable).isFalse()+ }+@Testfun `getChannel reads updated stalker portal config after an edit`() = runTest {whenever(channelDao.getBrowseById(536L)).thenReturn(diff --git a/data/src/test/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImplTest.ktnew file mode 100644index 00000000..7660fca2--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/OpenSubtitlesRepositoryImplTest.kt@@ -0,0 +1,64 @@+package com.streamvault.data.repository++import android.content.Context+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.remote.subtitle.OpenSubtitlesApi+import com.streamvault.data.remote.subtitle.OpenSubtitlesSessionStore+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.kotlin.mock+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class OpenSubtitlesRepositoryImplTest {+ private lateinit var context: Context+ private lateinit var repository: OpenSubtitlesRepositoryImpl+ private lateinit var durableDirectory: File+ private lateinit var legacyDirectory: File++ @Before+ fun setUp() {+ context = RuntimeEnvironment.getApplication()+ repository = OpenSubtitlesRepositoryImpl(+ context = context,+ api = mock<OpenSubtitlesApi>(),+ sessionStore = mock<OpenSubtitlesSessionStore>(),+ )+ durableDirectory = File(context.filesDir, "subtitles/opensubtitles").apply { mkdirs() }+ legacyDirectory = File(context.cacheDir, "subtitles/opensubtitles").apply { mkdirs() }+ }++ @After+ fun tearDown() {+ durableDirectory.deleteRecursively()+ legacyDirectory.deleteRecursively()+ }++ @Test+ fun `legacy cache file is moved to durable storage and removed`() = runBlocking {+ val legacy = File(legacyDirectory, "123.srt").apply { writeText("subtitle") }++ val cached = repository.cachedSubtitleFile("123")++ assertThat(cached).isNotNull()+ assertThat(cached!!.readText()).isEqualTo("subtitle")+ assertThat(cached.parentFile).isEqualTo(durableDirectory)+ assertThat(legacy.exists()).isFalse()+ }++ @Test+ fun `delete removes both durable and legacy cached files`() = runBlocking {+ val durable = File(durableDirectory, "456.srt").apply { writeText("subtitle") }+ val legacy = File(legacyDirectory, "456.srt").apply { writeText("subtitle") }++ repository.deleteCachedSubtitle("456")++ assertThat(durable.exists()).isFalse()+ assertThat(legacy.exists()).isFalse()+ }+}diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryCatchUpTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryCatchUpTest.ktindex 3719d89e..e40ee7d2 100644--- a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryCatchUpTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryCatchUpTest.kt@@ -98,24 +98,39 @@ class ProviderRepositoryCatchUpTest {}@Test- fun `Flussonic HLS mode builds a relative timeshift path`() {- val now = System.currentTimeMillis() / 1_000L+ fun `Flussonic HLS mode builds an absolute timeshift path and applies correction`() {val urls = buildM3uCatchUpUrls(source = null,streamUrl = "https://flussonic.example.com/news/index.m3u8?token=abc",catchUpType = "fs",- start = now - 3_600L,- end = now - 1_800L,+ start = 1_710_000_000L,+ end = 1_710_003_600L,+ correctionSeconds = 1_800+ )++ assertThat(urls).containsExactly(+ "https://flussonic.example.com/news/timeshift_abs-1710001800.m3u8?token=abc"+ )+ }++ @Test+ fun `Flussonic MPEG-TS mode builds a duration archive path`() {+ val urls = buildM3uCatchUpUrls(+ source = null,+ streamUrl = "https://flussonic.example.com/news/mpegts?token=abc",+ catchUpType = "flussonic-ts",+ start = 1_710_000_000L,+ end = 1_710_003_600L,correctionSeconds = 0)- assertThat(urls).hasSize(1)- assertThat(urls.single()).contains("/news/timeshift_rel-")- assertThat(urls.single()).endsWith(".m3u8?token=abc")+ assertThat(urls).containsExactly(+ "https://flussonic.example.com/news/archive-1710000000-3600.ts?token=abc"+ )}@Test- fun `Xtream mode builds its timeshift endpoint from the live URL`() {+ fun `Xtream mode builds both timeshift endpoint forms`() {val urls = buildM3uCatchUpUrls(source = null,streamUrl = "https://xc.example.com:8080/live/user/pass/42.ts",@@ -126,10 +141,57 @@ class ProviderRepositoryCatchUpTest {)assertThat(urls).containsExactly(+ "https://xc.example.com:8080/streaming/timeshift.php?username=user&password=pass&stream=42&start=2024-03-09:16-00&duration=60","https://xc.example.com:8080/timeshift/user/pass/60/2024-03-09:16-00/42.ts"+ ).inOrder()+ }++ @Test+ fun `legacy date placeholders expand to stable values`() {+ val urls = buildM3uCatchUpUrls(+ source = "https://archive.example.com/{Ymd}/{YmdHis}/{utc:yyyy-MM-dd}/{utc:Ymd-H-M}",+ streamUrl = "https://live.example.com/channel.ts",+ catchUpType = "default",+ start = 1_710_000_000L,+ end = 1_710_003_600L,+ correctionSeconds = 0+ )++ assertThat(urls).containsExactly(+ "https://archive.example.com/20240309/20240309160000/2024-03-09/20240309-16-00")}+ @Test+ fun `legacy start and end placeholders expand`() {+ val urls = buildM3uCatchUpUrls(+ source = "https://archive.example.com/${'$'}{(b)yyyyMMddHHmmss}-${'$'}{(e)yyyyMMddHHmmss}/${'$'}{(b)timestamp}-${'$'}{(e)timestamp}",+ streamUrl = "https://live.example.com/channel.ts",+ catchUpType = "default",+ start = 1_710_000_000L,+ end = 1_710_003_600L,+ correctionSeconds = 0+ )++ assertThat(urls).containsExactly(+ "https://archive.example.com/20240309160000-20240309170000/1710000000-1710003600"+ )+ }++ @Test+ fun `unknown placeholders are left untouched`() {+ val urls = buildM3uCatchUpUrls(+ source = "https://archive.example.com/{unknown}/{utc:unknown}",+ streamUrl = "https://live.example.com/channel.ts",+ catchUpType = "default",+ start = 1_710_000_000L,+ end = 1_710_003_600L,+ correctionSeconds = 0+ )++ assertThat(urls).containsExactly("https://archive.example.com/{unknown}/{utc:unknown}")+ }+@Testfun `unknown mode without a template does not create a candidate`() {val urls = buildM3uCatchUpUrls(@@ -157,4 +219,18 @@ class ProviderRepositoryCatchUpTest {assertThat(urls).isEmpty()}++ @Test+ fun `formatted catchup id templates do not return unresolved replay URLs`() {+ val urls = buildM3uCatchUpUrls(+ source = "https://archive.example.com/program/{catchup-id:raw}.m3u8",+ streamUrl = "https://live.example.com/channel.ts",+ catchUpType = "vod",+ start = 1_710_000_000L,+ end = 1_710_003_600L,+ correctionSeconds = 0+ )++ assertThat(urls).isEmpty()+ }}diff --git a/docs/CATCH_UP_SUPPORT_REVIEW.md b/docs/CATCH_UP_SUPPORT_REVIEW.mddeleted file mode 100644index 15b46088..00000000--- a/docs/CATCH_UP_SUPPORT_REVIEW.md+++ /dev/null@@ -1,56 +0,0 @@-# Catch-up Support Findings and Plan--**Review date:** 2026-10-30-**Status:** The implementation plan is complete. Provider-backed archive playback remains an environment-dependent smoke check.--## Findings--### The archive playback flow exists--Choosing a guide programme sends its start and end times to the provider repository. The repository builds replay URL candidates, which then use the normal player recovery path. The existing flow is programme based; there is no guide-free timestamp entry flow.--### Xtream and Stalker use provider-specific replay paths--- Xtream reads its archive flag and window and builds timeshift URLs.-- Stalker builds archive requests from its internal stream token and the selected programme interval.-- Stalker still requires a provider-marked archive programme when it has no reported archive window.--### M3U metadata and URL modes were incomplete--The parser read catch-up attributes, but the channel and sync persistence path dropped the mode and correction value. Numeric legacy `timeshift` values were not used as the archive window. URL generation expanded only a full source template, so it missed append/default query formats, SIPTV shift requests, Flussonic paths, and Xtream-style paths.--The default and append modes also need a provider-specific query format when a playlist does not include `catchup-source`. A fixed UTC query cannot fit every provider.--### Unknown windows blocked some advertised archives--An M3U or Xtream channel with an explicit replay mechanism and no reported day count could not play an ordinary past guide entry unless the entry itself carried an archive flag.--## Implementation completed--- Preserve M3U catch-up mode and correction seconds through parsing, channel models, sync staging, projections, and Room persistence. The database is version 90 with a migration from version 89.-- Parse `catchup` and `catchup-type`, numeric legacy `timeshift`, and channel-level or playlist-level correction values.-- Build and expand full templates, append/default query fragments, SIPTV shift, Flussonic, and Xtream-style paths. Support programme start/end, current time, date, duration, and offset tokens, while applying catch-up correction.-- Add an editable M3U fallback query format in Live TV settings. It defaults to `?utc={utc}&lutc={lutc}`, is used only when an entry has no source template, can be left blank to disable the fallback, and is included in settings backup and restore.-- Localize the new setting in all 38 advertised locales.-- Allow completed M3U and Xtream programmes when an explicit replay mechanism exists but the provider window is unknown. Keep Stalker’s provider-marked archive rule.-- Include M3U replay metadata in sync fingerprints so playlist changes are applied.-- Avoid offering unresolved `{catchup-id}` templates. Programme identifiers are not currently mapped from guide data.--## Decisions--- A single editable fallback query format is sufficient for this pass. Per-channel `catchup-source` values take precedence. A provider that needs another format can set the global fallback or supply its own source.-- Manual timestamp entry is a separate UI feature and is out of scope for programme-based archive playback.-- `catchup=vod` templates that require `{catchup-id}` are unsupported until the programme-specific identifier is parsed and persisted end to end.--## Validation completed--- Focused domain/data tests passed for archive eligibility, M3U parsing, configured query expansion, append/shift/Flussonic/Xtream URL construction, M3U capability-adapter URL generation, repository request wiring, preference persistence, backup classification, and sync-stage metadata/fingerprint propagation.-- Room migration instrumentation passed on the `Television_1080p` Android 16 emulator. It migrated a version 89 database containing provider, channel, and staged channel rows to version 90 and verified the new metadata columns and retained rows.-- `:feature:settings:testDebugUnitTest` passed.-- `:app:compileDebugKotlin` passed.-- XML resource validation found all three new keys in the default resources and each of the 37 translated locale directories.-- `git diff --check` passed.--## Provider playback smoke check--No provider credentials or working M3U archive fixture were available in this environment, so an actual provider response and decoded archive playback were not verified. The local tests verify the final candidate URLs and the app’s adapter/repository metadata flow, but they cannot confirm that a particular provider accepts those URLs. Run one archive programme against a known-good M3U provider before claiming provider-specific playback compatibility.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex bf859772..757d4f6a 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -21,7 +21,8 @@ All notable product changes are recorded in this document.### Fixed- Fixed Hardware Only video decoding being overridden after live TV stalls; recovery now preserves explicit audio and video decoder settings and excludes software video decoders in Hardware Only mode.- Fixed channel numbers appearing in Guide Favorites views and selected-channel details when Live TV numbering is set to Hidden.-- Fixed external subtitles disappearing after playback retries or when replaying a movie: attached subtitles are restored with the rebuilt source, and downloaded OpenSubtitles files are kept in durable app storage and remembered for that movie.+- Fixed external subtitles disappearing after playback retries, reconnects, buffering, or when replaying a movie: attached subtitles are restored with the rebuilt source, downloaded OpenSubtitles files are kept in durable app storage and remembered for that movie, and replaced subtitle files are cleaned up.+- Fixed M3U catch-up URL generation for legacy date placeholders and additional provider path/query styles, and stopped offering archive playback when the configured fallback cannot build a URL.- Fixed the player showing a generic recording error when Android alarm access is missing; it now explains how to enable access and retry.- Fixed the temporary torrent cache clear action to confirm when the cache was cleared successfully.- Fixed deleted downloads leaving partial files behind after earlier failed attempts.diff --git a/domain/src/main/java/com/streamvault/domain/model/Channel.kt b/domain/src/main/java/com/streamvault/domain/model/Channel.ktindex 5d9f71b4..41e571b7 100644--- a/domain/src/main/java/com/streamvault/domain/model/Channel.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Channel.kt@@ -15,6 +15,7 @@ data class Channel(val catchUpSupported: Boolean = false,val catchUpDays: Int = 0,val catchUpSource: String? = null,+ val catchUpFallbackAvailable: Boolean = true,val providerId: Long = 0,val currentProgram: Program? = null,val nextProgram: Program? = null,diff --git a/domain/src/main/java/com/streamvault/domain/playback/ArchivePlayback.kt b/domain/src/main/java/com/streamvault/domain/playback/ArchivePlayback.ktindex 4e1d65a1..82fe2bea 100644--- a/domain/src/main/java/com/streamvault/domain/playback/ArchivePlayback.kt+++ b/domain/src/main/java/com/streamvault/domain/playback/ArchivePlayback.kt@@ -37,9 +37,14 @@ fun Channel.archivePlaybackCapability(): ArchivePlaybackCapability {val needsUnmappedCatchUpId = Regex("\\$?\\{catchup-id}", RegexOption.IGNORE_CASE).containsMatchIn(source)val hasM3uTemplate = source.isNotBlank() && !needsUnmappedCatchUpId &&!normalizedSource.startsWith(STALKER_INTERNAL_PREFIX)- val hasM3uAutoMode = normalizedType in setOf(- "default", "append", "shift", "timeshift", "fs", "flussonic", "xc", "xc60", "xtream", "xtream-codes"- ) && !stream.startsWith(STALKER_INTERNAL_PREFIX)+ val needsConfiguredFallback = source.isBlank() && normalizedType in setOf("default", "append")+ val isFlussonicMode = normalizedType == "fs" || normalizedType.startsWith("flussonic")+ val hasM3uAutoMode = (+ normalizedType in setOf(+ "default", "append", "shift", "timeshift", "xc", "xc60", "xtream", "xtream-codes"+ ) || isFlussonicMode+ ) && !stream.startsWith(STALKER_INTERNAL_PREFIX) && !needsUnmappedCatchUpId &&+ (!needsConfiguredFallback || catchUpFallbackAvailable)val windowDays = catchUpDays.takeIf { it > 0 }return when {diff --git a/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.ktindex 1b9a32ab..5c0a7b01 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ExternalSubtitleRepository.kt@@ -24,4 +24,6 @@ interface ExternalSubtitleRepository {suspend fun downloadToCache(subtitle: ExternalSubtitle): Result<File>suspend fun cachedSubtitleFile(downloadId: String): File? = null++ suspend fun deleteCachedSubtitle(downloadId: String) = Unit}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt b/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.ktindex a7ae085d..ccf6e4cc 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/DownloadExternalSubtitle.kt@@ -14,4 +14,8 @@ class DownloadExternalSubtitle @Inject constructor(suspend fun cachedSubtitleFile(downloadId: String): File? =repository.cachedSubtitleFile(downloadId)++ suspend fun deleteCachedSubtitle(downloadId: String) {+ repository.deleteCachedSubtitle(downloadId)+ }}diff --git a/domain/src/test/java/com/streamvault/domain/playback/ArchivePlaybackTest.kt b/domain/src/test/java/com/streamvault/domain/playback/ArchivePlaybackTest.ktindex 57fdeee1..878c79e4 100644--- a/domain/src/test/java/com/streamvault/domain/playback/ArchivePlaybackTest.kt+++ b/domain/src/test/java/com/streamvault/domain/playback/ArchivePlaybackTest.kt@@ -178,6 +178,75 @@ class ArchivePlaybackTest {assertThat(channel.isArchivePlayable(program, now)).isFalse()}+ @Test+ fun `auto mode is not offered for a template that still needs a programme identifier`() {+ val now = 5 * 86_400_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ streamUrl = "https://live.example.com/channel.m3u8",+ catchUpSupported = true,+ catchUpSource = "https://archive.example.com/program/{catchup-id}.m3u8",+ catchUpType = "append"+ )+ val program = Program(+ channelId = "news",+ title = "Replay with identifier",+ startTime = now - 60_000L,+ endTime = now - 30_000L+ )++ assertThat(channel.archivePlaybackCapability().canBuildReplayCandidate).isFalse()+ assertThat(channel.isArchivePlayable(program, now)).isFalse()+ }++ @Test+ fun `source-less append is not offered when the fallback format is disabled`() {+ val now = 5 * 86_400_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ streamUrl = "https://live.example.com/news.ts",+ catchUpSupported = true,+ catchUpType = "append",+ catchUpFallbackAvailable = false+ )+ val program = Program(+ channelId = "news",+ title = "Unmarked Bulletin",+ startTime = now - 60_000L,+ endTime = now - 30_000L+ )++ assertThat(channel.archivePlaybackCapability().canBuildReplayCandidate).isFalse()+ assertThat(channel.isArchivePlayable(program, now)).isFalse()+ }++ @Test+ fun `source-less append is offered when the fallback format is configured`() {+ val now = 5 * 86_400_000L+ val channel = Channel(+ id = 42L,+ name = "News",+ providerId = 7L,+ streamUrl = "https://live.example.com/news.ts",+ catchUpSupported = true,+ catchUpType = "append",+ catchUpFallbackAvailable = true+ )+ val program = Program(+ channelId = "news",+ title = "Unmarked Bulletin",+ startTime = now - 60_000L,+ endTime = now - 30_000L+ )++ assertThat(channel.archivePlaybackCapability().canBuildReplayCandidate).isTrue()+ assertThat(channel.isArchivePlayable(program, now)).isTrue()+ }+@Testfun `unknown M3U catch-up window allows completed guide programme`() {val now = 5 * 86_400_000Ldiff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.ktindex b4275a2b..1c5c3251 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerExternalSubtitleActions.kt@@ -185,6 +185,7 @@ internal fun PlayerViewModel.downloadExternalSubtitle(subtitleId: String) {try {when (val result = downloadExternalSubtitleUseCase(subtitle)) {is Result.Success -> {+ val previousDownloadId = activeVodTrackPreferences?.subtitle?.externalSubtitleDownloadIdif (currentContentType == ContentType.MOVIE || currentContentType == ContentType.VOD) {val updatedPreferences = (activeVodTrackPreferences ?: VodTrackPreferences()).copy(subtitle = VodTrackPreference(@@ -197,6 +198,16 @@ internal fun PlayerViewModel.downloadExternalSubtitle(subtitleId: String) {playerEngine.setVodTrackPreferences(updatedPreferences)}playerEngine.addExternalSubtitle(Uri.fromFile(result.data), subtitle.language)+ if ((currentContentType == ContentType.MOVIE || currentContentType == ContentType.VOD) &&+ previousDownloadId != null && previousDownloadId != subtitle.downloadId+ ) {+ try {+ downloadExternalSubtitleUseCase.deleteCachedSubtitle(previousDownloadId)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ }+ }externalSubtitleSearchStateFlow.update {it.copy(downloadingSubtitleId = null, appliedSubtitleName = subtitle.displayLanguage)}@@ -219,7 +230,11 @@ internal suspend fun PlayerViewModel.restoreRememberedOpenSubtitle() {if (currentContentType != ContentType.MOVIE && currentContentType != ContentType.VOD) returnval preference = activeVodTrackPreferences?.subtitle ?: returnval downloadId = preference.externalSubtitleDownloadId ?: return- val cachedFile = downloadExternalSubtitleUseCase.cachedSubtitleFile(downloadId) ?: return+ val cachedFile = downloadExternalSubtitleUseCase.cachedSubtitleFile(downloadId)+ if (cachedFile == null) {+ clearRememberedOpenSubtitleForCurrentContent()+ return+ }playerEngine.addExternalSubtitle(subtitleUri = Uri.fromFile(cachedFile),language = preference.language?.takeIf { it.isNotBlank() } ?: "und",@@ -228,6 +243,17 @@ internal suspend fun PlayerViewModel.restoreRememberedOpenSubtitle() {)}+internal suspend fun PlayerViewModel.withoutMissingRememberedOpenSubtitle(+ preferences: VodTrackPreferences?+): VodTrackPreferences? {+ val subtitle = preferences?.subtitle ?: return preferences+ val downloadId = subtitle.externalSubtitleDownloadId ?: return preferences+ if (downloadExternalSubtitleUseCase.cachedSubtitleFile(downloadId) != null) return preferences+ val updated = preferences.copy(subtitle = null)+ persistVodTrackPreferences(updated, persistGlobal = false)+ return updated+}+internal fun PlayerViewModel.cancelExternalSubtitleSearch() {externalSubtitleSearchJob?.cancel()externalSubtitleDownloadJob?.cancel()diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.ktindex b9335fb5..3bdd4c3c 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt@@ -18,6 +18,7 @@ import com.streamvault.player.SUBTITLE_OFFSET_MIN_MSimport com.streamvault.player.PlaybackStateimport com.streamvault.player.PlayerErrorimport com.streamvault.player.SubtitleTrackSource+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.update@@ -45,8 +46,8 @@ fun PlayerViewModel.selectSubtitleTrack(trackId: String?) {playerEngine.selectSubtitleTrack(trackId)val current = activeVodTrackPreferences ?: VodTrackPreferences()- val rememberedDownloadId = current.subtitle- ?.externalSubtitleDownloadId+ val previousDownloadId = current.subtitle?.externalSubtitleDownloadId+ val rememberedDownloadId = previousDownloadId?.takeIf { selectedTrack?.subtitleSource == SubtitleTrackSource.ONLINE }val subtitlePreference = when {trackId == null -> VodTrackPreference(disabled = true)@@ -63,6 +64,16 @@ fun PlayerViewModel.selectSubtitleTrack(trackId: String?) {subtitle = subtitlePreference))+ if (previousDownloadId != null && rememberedDownloadId == null) {+ viewModelScope.launch {+ try {+ downloadExternalSubtitleUseCase.deleteCachedSubtitle(previousDownloadId)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ }+ }+ }}private fun com.streamvault.player.PlayerTrack.toVodTrackPreference() = VodTrackPreference(@@ -98,11 +109,21 @@ internal fun PlayerViewModel.persistVodTrackPreferences(internal fun PlayerViewModel.clearRememberedOpenSubtitleForCurrentContent() {val current = activeVodTrackPreferences ?: return- if (current.subtitle?.externalSubtitleDownloadId == null) return+ val downloadId = current.subtitle?.externalSubtitleDownloadId ?: return+ val updated = current.copy(subtitle = null)persistVodTrackPreferences(- updated = current.copy(subtitle = null),+ updated = updated,persistGlobal = false)+ playerEngine.setVodTrackPreferences(updated)+ viewModelScope.launch {+ try {+ downloadExternalSubtitleUseCase.deleteCachedSubtitle(downloadId)+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (_: Exception) {+ }+ }}fun PlayerViewModel.selectVideoQuality(trackId: String): Boolean {diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.ktindex 6026f9b3..67ec2245 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt@@ -1544,6 +1544,7 @@ class PlayerViewModel @Inject constructor(seriesId = currentSeriesId)}+ activeVodTrackPreferences = withoutMissingRememberedOpenSubtitle(activeVodTrackPreferences)val preparationResult = playerPreparationCoordinator.prepare(request = PlayerPreparationCoordinator.Request(diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex d86a767e..b2bdda9d 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -1200,7 +1200,10 @@ class Media3PlayerEngine @Inject constructor(}override fun selectSubtitleTrack(trackId: String?) {- if (activeExternalSubtitle?.trackId != trackId) {+ val selectedSource = trackId?.let { id ->+ trackController.availableSubtitleTracks.value.firstOrNull { it.id == id }?.subtitleSource+ }+ if (trackId == null || selectedSource != activeExternalSubtitle?.source) {activeExternalSubtitle = null}exoPlayer?.let { trackController.selectSubtitleTrack(it, trackId) }diff --git a/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.ktindex efc315e4..d7b72202 100644--- a/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt+++ b/player/src/main/java/com/streamvault/player/tracks/PlayerTrackController.kt@@ -129,25 +129,20 @@ class PlayerTrackController(}preferences.subtitle?.let { preference ->- if (preference.externalSubtitleDownloadId != null) {- builder- .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)- .clearOverridesOfType(C.TRACK_TYPE_TEXT)+ val selected = resolvePreferredPlayerTrack(preference, _availableSubtitleTracks.value)+ val waitingForExternal = preference.externalSubtitleDownloadId != null &&+ preference.trackId.isNullOrBlank()+ builder.clearOverridesOfType(C.TRACK_TYPE_TEXT)+ if (preference.disabled || waitingForExternal || selected == null) {+ builder.setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)_availableSubtitleTracks.update { tracks -> tracks.map { it.copy(isSelected = false) } }} else {- val selected = resolvePreferredPlayerTrack(preference, _availableSubtitleTracks.value)- builder.clearOverridesOfType(C.TRACK_TYPE_TEXT)- if (preference.disabled || selected == null) {- builder.setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)- _availableSubtitleTracks.update { tracks -> tracks.map { it.copy(isSelected = false) } }- } else {- findOverride(player.currentTracks, C.TRACK_TYPE_TEXT, selected.id)?.let { override ->- builder- .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)- .setOverrideForType(override)- _availableSubtitleTracks.update { tracks ->- tracks.map { track -> track.copy(isSelected = track.id == selected.id) }- }+ findOverride(player.currentTracks, C.TRACK_TYPE_TEXT, selected.id)?.let { override ->+ builder+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)+ .setOverrideForType(override)+ _availableSubtitleTracks.update { tracks ->+ tracks.map { track -> track.copy(isSelected = track.id == selected.id) }}}}diff --git a/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerExternalSubtitleAutoSelectTest.kt b/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerExternalSubtitleAutoSelectTest.ktindex 8410782f..24432820 100644--- a/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerExternalSubtitleAutoSelectTest.kt+++ b/player/src/test/java/com/streamvault/player/tracks/PlayerTrackControllerExternalSubtitleAutoSelectTest.kt@@ -12,6 +12,7 @@ import com.google.common.truth.Truth.assertThatimport com.streamvault.domain.settings.VodTrackPreferenceimport com.streamvault.domain.settings.VodTrackPreferencesimport com.streamvault.player.DEVICE_SUBTITLE_TRACK_ID+import com.streamvault.player.ONLINE_SUBTITLE_TRACK_IDimport com.streamvault.player.SubtitleTrackSourceimport java.lang.reflect.Proxyimport org.junit.Test@@ -45,10 +46,31 @@ class PlayerTrackControllerExternalSubtitleAutoSelectTest {))+ private val onlineGroup = TrackGroup(+ "online-subtitle",+ Format.Builder()+ .setId(ONLINE_SUBTITLE_TRACK_ID)+ .setSampleMimeType(MimeTypes.APPLICATION_SUBRIP)+ .setLanguage("en")+ .setLabel("downloaded.srt")+ .build()+ )+ private val onlineTracks = Tracks(+ listOf(+ Tracks.Group(+ onlineGroup,+ /* adaptiveSupported= */ false,+ /* trackSupport= */ intArrayOf(C.FORMAT_HANDLED),+ /* trackSelected= */ booleanArrayOf(false)+ )+ )+ )++ private var currentTracks: Tracks = tracksprivate var parameters = TrackSelectionParameters.Builder(context).build()private val player = Proxy.newProxyInstance(ExoPlayer::class.java.classLoader, arrayOf(ExoPlayer::class.java)) { _, method, args ->when (method.name) {- "getCurrentTracks" -> tracks+ "getCurrentTracks" -> currentTracks"getTrackSelectionParameters" -> parameters"setTrackSelectionParameters" -> {parameters = args!![0] as TrackSelectionParameters@@ -115,4 +137,35 @@ class PlayerTrackControllerExternalSubtitleAutoSelectTest {assertThat(parameters.overrides).isEmpty()}++ @Test+ fun `remembered online subtitle survives a later tracks changed pass`() {+ currentTracks = onlineTracks+ controller.onTracksChanged(onlineTracks)+ val onlineTrackId = controller.availableSubtitleTracks.value.single().id+ controller.setVodTrackPreferences(+ player,+ VodTrackPreferences(+ subtitle = VodTrackPreference(+ trackId = onlineTrackId,+ language = "en",+ label = "downloaded.srt",+ externalSubtitleDownloadId = "12345"+ )+ )+ )+ controller.requestExternalSubtitleAutoSelect(SubtitleTrackSource.ONLINE)++ controller.applyVodTrackPreferences(player)+ controller.applyPendingExternalSubtitleAutoSelect(player)++ assertThat(parameters.overrides[onlineGroup]?.trackIndices).containsExactly(0)++ controller.onTracksChanged(onlineTracks)+ controller.applyVodTrackPreferences(player)+ controller.applyPendingExternalSubtitleAutoSelect(player)++ assertThat(parameters.overrides[onlineGroup]?.trackIndices).containsExactly(0)+ assertThat(parameters.disabledTrackTypes).doesNotContain(C.TRACK_TYPE_TEXT)+ }}