PlaybackPolicies.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlaybackPolicies.kt
1package eu.friedcutlet.yokan.services.media.player23import eu.friedcutlet.yokan.database.DbVideo4import eu.friedcutlet.yokan.database.DbVideoTrack5import eu.friedcutlet.yokan.services.extensions.languageName6import kotlin.math.roundToInt78/** Range accepted by both player backends. */9val PlaybackSpeedRange: ClosedFloatingPointRange<Double> = 0.25..4.01011/** Parses a comma-separated preset list; null when empty or any value is invalid. */12fun parseSpeedPresets(text: String): List<Double>? {13 val values = text.split(',', ';', ' ').map(String::trim).filter(String::isNotEmpty).map { token ->14 token.removeSuffix("x").removePrefix("x").toDoubleOrNull()?.takeIf { it in PlaybackSpeedRange } ?: return null15 }16 return values.map { (it * 100).roundToInt() / 100.0 }.distinct().sorted().ifEmpty { null }17}1819/** Splits a comma-separated preference into its trimmed, non-empty terms. */20fun parseTermList(text: String): List<String> = text.split(',').map(String::trim).filter(String::isNotEmpty).distinct()2122/**23 * Auto-selected subtitle: blacklisted tracks are never chosen; the first [languages] entry that has24 * an allowed track wins, preferring whitelisted names. Without a language match the first allowed25 * track is used, as before languages were configurable.26 */27fun preferredSubtitle(28 tracks: List<DbVideoTrack>,29 languages: List<String>,30 whitelist: List<String> = emptyList(),31 blacklist: List<String> = emptyList(),32): DbVideoTrack? {33 val allowed = tracks.filter { track -> !track.file.isNullOrBlank() && blacklist.none { track.hasTerm(it) } }34 fun pick(candidates: List<DbVideoTrack>) =35 candidates.firstOrNull { track -> whitelist.any { track.hasTerm(it) } } ?: candidates.firstOrNull()36 return languages.firstNotNullOfOrNull { language -> pick(allowed.filter { it.isLanguage(language) }) } ?: pick(allowed)37}3839private fun DbVideoTrack.hasTerm(term: String): Boolean =40 label.orEmpty().contains(term, ignoreCase = true) || file.orEmpty().contains(term, ignoreCase = true)4142private fun DbVideoTrack.isLanguage(language: String): Boolean {43 val text = label.orEmpty().ifBlank { file.orEmpty() }44 val code = language.trim().lowercase()45 if (code.isEmpty()) return false46 val name = languageName(code).substringBefore(" (")47 return Regex("\\b${Regex.escape(code)}\\b", RegexOption.IGNORE_CASE).containsMatchIn(text) ||48 (name.length > 3 && text.contains(name, ignoreCase = true))49}5051/** The next stream to try after [failedUrls] failed; each stream is tried once, so failover terminates. */52fun nextFailoverVideo(videos: List<DbVideo>, failedUrls: Set<String>): DbVideo? = videos.firstOrNull { it.url !in failedUrls }5354/** A pending sleep timer: a wall-clock [deadlineMs], or the end of the current episode when null. */55data class SleepTimer(val deadlineMs: Long?)5657fun SleepTimer.isDue(nowMs: Long, positionMs: Long, durationMs: Long): Boolean =58 deadlineMs?.let { nowMs >= it } ?: (durationMs > 0L && positionMs >= durationMs - 500L)5960/** One seek-preview tile: [imageUrl] cropped to x/y/width/height (width 0 = whole image). */61data class SeekThumbnail(62 val startMs: Long,63 val endMs: Long,64 val imageUrl: String,65 val x: Int = 0,66 val y: Int = 0,67 val width: Int = 0,68 val height: Int = 0,69)7071/** Parses a WebVTT thumbnail track (`sprite.jpg#xywh=0,0,160,90` cues); relative URLs resolve against [baseUrl]. */72fun parseThumbnailVtt(content: String, baseUrl: String): List<SeekThumbnail> {73 val lines = content.replace("\r\n", "\n").replace('\r', '\n').lines()74 val result = mutableListOf<SeekThumbnail>()75 for ((index, line) in lines.withIndex()) {76 if ("-->" !in line) continue77 val start = parseVttTime(line.substringBefore("-->")) ?: continue78 val end = parseVttTime(line.substringAfter("-->").trim().substringBefore(' ')) ?: continue79 val target = lines.getOrNull(index + 1)?.trim().orEmpty()80 if (target.isEmpty()) continue81 val image = resolveUrl(baseUrl, target.substringBefore("#xywh="))82 val box = target.substringAfter("#xywh=", "").split(',').mapNotNull { it.trim().toIntOrNull() }83 result += if (box.size == 4 && box[2] > 0 && box[3] > 0 && box[0] >= 0 && box[1] >= 0) {84 SeekThumbnail(start, end, image, box[0], box[1], box[2], box[3])85 } else {86 SeekThumbnail(start, end, image)87 }88 }89 return result.sortedBy { it.startMs }90}9192/** The tile shown at [positionMs]: the last cue starting at or before it, within its end time. */93fun List<SeekThumbnail>.at(positionMs: Long): SeekThumbnail? {94 var low = 095 var high = lastIndex96 var found: SeekThumbnail? = null97 while (low <= high) {98 val mid = (low + high) ushr 199 if (this[mid].startMs <= positionMs) { found = this[mid]; low = mid + 1 } else high = mid - 1100 }101 return found?.takeIf { positionMs < it.endMs }102}103104private fun parseVttTime(text: String): Long? {105 val parts = text.trim().split(':')106 if (parts.size !in 2..3) return null107 val seconds = parts.last().replace(',', '.').toDoubleOrNull() ?: return null108 val minutes = parts[parts.size - 2].toLongOrNull() ?: return null109 val hours = if (parts.size == 3) parts[0].toLongOrNull() ?: return null else 0L110 return (hours * 3_600_000L) + (minutes * 60_000L) + (seconds * 1000).roundToInt()111}112113private fun resolveUrl(base: String, reference: String): String {114 if (Regex("^[a-zA-Z][a-zA-Z0-9+.-]*:").containsMatchIn(reference)) return reference115 val scheme = base.substringBefore("://", "")116 if (reference.startsWith("//")) return "${scheme.ifEmpty { "https" }}:$reference"117 val withoutQuery = base.substringBefore('?').substringBefore('#')118 if (reference.startsWith("/")) {119 val origin = if (scheme.isEmpty()) "" else "$scheme://" + withoutQuery.substringAfter("://").substringBefore('/')120 return origin + reference121 }122 val directory = withoutQuery.substringBeforeLast('/', "")123 return if (directory.isEmpty()) reference else "$directory/$reference"124}125