package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.DbVideoTrack import eu.friedcutlet.yokan.services.extensions.languageName import kotlin.math.roundToInt /** Range accepted by both player backends. */ val PlaybackSpeedRange: ClosedFloatingPointRange = 0.25..4.0 /** Parses a comma-separated preset list; null when empty or any value is invalid. */ fun parseSpeedPresets(text: String): List? { val values = text.split(',', ';', ' ').map(String::trim).filter(String::isNotEmpty).map { token -> token.removeSuffix("x").removePrefix("x").toDoubleOrNull()?.takeIf { it in PlaybackSpeedRange } ?: return null } return values.map { (it * 100).roundToInt() / 100.0 }.distinct().sorted().ifEmpty { null } } /** Splits a comma-separated preference into its trimmed, non-empty terms. */ fun parseTermList(text: String): List = text.split(',').map(String::trim).filter(String::isNotEmpty).distinct() /** * Auto-selected subtitle: blacklisted tracks are never chosen; the first [languages] entry that has * an allowed track wins, preferring whitelisted names. Without a language match the first allowed * track is used, as before languages were configurable. */ fun preferredSubtitle( tracks: List, languages: List, whitelist: List = emptyList(), blacklist: List = emptyList(), ): DbVideoTrack? { val allowed = tracks.filter { track -> !track.file.isNullOrBlank() && blacklist.none { track.hasTerm(it) } } fun pick(candidates: List) = candidates.firstOrNull { track -> whitelist.any { track.hasTerm(it) } } ?: candidates.firstOrNull() return languages.firstNotNullOfOrNull { language -> pick(allowed.filter { it.isLanguage(language) }) } ?: pick(allowed) } private fun DbVideoTrack.hasTerm(term: String): Boolean = label.orEmpty().contains(term, ignoreCase = true) || file.orEmpty().contains(term, ignoreCase = true) private fun DbVideoTrack.isLanguage(language: String): Boolean { val text = label.orEmpty().ifBlank { file.orEmpty() } val code = language.trim().lowercase() if (code.isEmpty()) return false val name = languageName(code).substringBefore(" (") return Regex("\\b${Regex.escape(code)}\\b", RegexOption.IGNORE_CASE).containsMatchIn(text) || (name.length > 3 && text.contains(name, ignoreCase = true)) } /** The next stream to try after [failedUrls] failed; each stream is tried once, so failover terminates. */ fun nextFailoverVideo(videos: List, failedUrls: Set): DbVideo? = videos.firstOrNull { it.url !in failedUrls } /** A pending sleep timer: a wall-clock [deadlineMs], or the end of the current episode when null. */ data class SleepTimer(val deadlineMs: Long?) fun SleepTimer.isDue(nowMs: Long, positionMs: Long, durationMs: Long): Boolean = deadlineMs?.let { nowMs >= it } ?: (durationMs > 0L && positionMs >= durationMs - 500L) /** One seek-preview tile: [imageUrl] cropped to x/y/width/height (width 0 = whole image). */ data class SeekThumbnail( val startMs: Long, val endMs: Long, val imageUrl: String, val x: Int = 0, val y: Int = 0, val width: Int = 0, val height: Int = 0, ) /** Parses a WebVTT thumbnail track (`sprite.jpg#xywh=0,0,160,90` cues); relative URLs resolve against [baseUrl]. */ fun parseThumbnailVtt(content: String, baseUrl: String): List { val lines = content.replace("\r\n", "\n").replace('\r', '\n').lines() val result = mutableListOf() for ((index, line) in lines.withIndex()) { if ("-->" !in line) continue val start = parseVttTime(line.substringBefore("-->")) ?: continue val end = parseVttTime(line.substringAfter("-->").trim().substringBefore(' ')) ?: continue val target = lines.getOrNull(index + 1)?.trim().orEmpty() if (target.isEmpty()) continue val image = resolveUrl(baseUrl, target.substringBefore("#xywh=")) val box = target.substringAfter("#xywh=", "").split(',').mapNotNull { it.trim().toIntOrNull() } result += if (box.size == 4 && box[2] > 0 && box[3] > 0 && box[0] >= 0 && box[1] >= 0) { SeekThumbnail(start, end, image, box[0], box[1], box[2], box[3]) } else { SeekThumbnail(start, end, image) } } return result.sortedBy { it.startMs } } /** The tile shown at [positionMs]: the last cue starting at or before it, within its end time. */ fun List.at(positionMs: Long): SeekThumbnail? { var low = 0 var high = lastIndex var found: SeekThumbnail? = null while (low <= high) { val mid = (low + high) ushr 1 if (this[mid].startMs <= positionMs) { found = this[mid]; low = mid + 1 } else high = mid - 1 } return found?.takeIf { positionMs < it.endMs } } private fun parseVttTime(text: String): Long? { val parts = text.trim().split(':') if (parts.size !in 2..3) return null val seconds = parts.last().replace(',', '.').toDoubleOrNull() ?: return null val minutes = parts[parts.size - 2].toLongOrNull() ?: return null val hours = if (parts.size == 3) parts[0].toLongOrNull() ?: return null else 0L return (hours * 3_600_000L) + (minutes * 60_000L) + (seconds * 1000).roundToInt() } private fun resolveUrl(base: String, reference: String): String { if (Regex("^[a-zA-Z][a-zA-Z0-9+.-]*:").containsMatchIn(reference)) return reference val scheme = base.substringBefore("://", "") if (reference.startsWith("//")) return "${scheme.ifEmpty { "https" }}:$reference" val withoutQuery = base.substringBefore('?').substringBefore('#') if (reference.startsWith("/")) { val origin = if (scheme.isEmpty()) "" else "$scheme://" + withoutQuery.substringAfter("://").substringBefore('/') return origin + reference } val directory = withoutQuery.substringBeforeLast('/', "") return if (directory.isEmpty()) reference else "$directory/$reference" }