HlsPlaylist.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylist.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DbPageUrl4import eu.friedcutlet.yokan.services.catchingNonCancellation5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpResponse7import eu.friedcutlet.yokan.services.http.HttpService8import eu.friedcutlet.yokan.util.PlatformLock9import io.ktor.http.URLBuilder10import io.ktor.http.takeFrom11import kotlinx.coroutines.coroutineScope12import kotlinx.coroutines.launch13import kotlinx.coroutines.sync.Semaphore14import kotlinx.coroutines.sync.withPermit15import kotlinx.coroutines.withContext16import kotlinx.coroutines.withTimeoutOrNull1718/**19 * [reference] from a playlist (absolute, protocol-relative, root-relative or relative) resolved against20 * [base]; null when either is not a URL. The base's query and fragment never carry over.21 */22internal fun resolveHlsUrl(base: String, reference: String): String? = runCatching {23 URLBuilder(base).apply {24 parameters.clear()25 fragment = ""26 }.takeFrom(reference).buildString()27}.getOrNull()2829/** The highest-BANDWIDTH variant of a master playlist resolved against [playlistUrl]; null for a media playlist. */30internal fun hlsBestVariantUrl(playlist: String, playlistUrl: String): String? {31 var bestBandwidth = -1L32 var bestUri: String? = null33 var bandwidth: Long? = null34 for (rawLine in playlist.lines()) {35 val line = rawLine.trim()36 if (line.startsWith("#EXT-X-STREAM-INF")) {37 bandwidth = hlsAttribute(line, "BANDWIDTH")?.toLongOrNull() ?: 0L38 } else if (bandwidth != null && line.isNotEmpty() && !line.startsWith("#")) {39 if (bandwidth > bestBandwidth) {40 bestBandwidth = bandwidth41 bestUri = line42 }43 bandwidth = null44 }45 }46 return bestUri?.let { resolveHlsUrl(playlistUrl, it) }47}4849/** Attribute [name] of an HLS tag line, unquoted; quoted values may contain commas. */50internal fun hlsAttribute(line: String, name: String): String? =51 Regex("""[:,]$name=("[^"]*"|[^,]*)""").find(line)?.groupValues?.get(1)?.removeSurrounding("\"")5253/** [line] with its `URI="…"` attribute pointing at [uri]. */54internal fun hlsWithUri(line: String, uri: String): String =55 line.replace(Regex("""URI="[^"]*"""")) { "URI=\"$uri\"" }5657/**58 * Saves an HLS stream as `<name>.m3u8` with its segments, keys and init maps rewritten to local files; a59 * master playlist is followed to its highest-bandwidth variant. Every file is retried and marked like a60 * page, so a restart only fetches what is missing. Null once saved, else the failing HTTP status.61 */62internal suspend fun PageTransfer.downloadHlsPlaylist(63 page: DbPageUrl,64 location: String,65 name: String,66 retries: Int,67 permits: Semaphore,68 onBytes: (Long) -> Unit,69 onTransfer: (Long) -> Unit,70): Int? {71 val headers = page.headers.orEmpty()72 var playlistUrl = page.url73 var response = http.fetchText(playlistUrl, headers) ?: return 074 if (response.isPlaylist()) {75 hlsBestVariantUrl(response.body, playlistUrl)?.let { variant ->76 playlistUrl = variant77 response = http.fetchText(variant, headers) ?: return 078 }79 }80 val playlist = response.body81 if (!response.isPlaylist() || playlist.lines().none { it.isNotBlank() && !it.trim().startsWith("#") }) {82 return response.statusCode83 }84 // Remote URL → local file name; keys and byte-range segments repeat the same URL.85 val localNames = mutableMapOf<String, String>()86 val rewritten = mutableListOf<String>()87 var segments = 088 for (rawLine in playlist.lines()) {89 val line = rawLine.trim()90 val tagUri = if (line.startsWith("#EXT-X-KEY") || line.startsWith("#EXT-X-MAP")) hlsAttribute(line, "URI") else null91 val reference = tagUri ?: line.takeUnless { it.isEmpty() || it.startsWith("#") }92 if (reference == null) {93 rewritten += line94 continue95 }96 val remote = resolveHlsUrl(playlistUrl, reference) ?: return 097 val localName = localNames[remote] ?: run {98 val fileName = when {99 tagUri == null -> "${name}_seg_${padIndex(segments++)}.ts"100 line.startsWith("#EXT-X-KEY") -> "${name}_key_${localNames.size}.key"101 else -> "${name}_map_${localNames.size}.mp4"102 }103 fileName.also { localNames[remote] = it }104 }105 rewritten += if (tagUri == null) localName else hlsWithUri(line, localName)106 }107 val pending = ArrayDeque(localNames.entries.toList())108 val progress = mutableMapOf<String, Long>()109 val failures = mutableListOf<Int>()110 // Guards pending, progress and failures across the parallel workers below.111 val lock = PlatformLock()112 coroutineScope {113 repeat(minOf(PAGE_PARALLELISM, pending.size)) {114 launch {115 while (true) {116 val resource = lock.withLock { pending.removeFirstOrNull() } ?: break117 val path = "$location/${resource.value}"118 val savedSize = withContext(ioDispatcher) {119 if (files.exists(path) && files.exists("$path.complete")) files.directorySize(path) else null120 }121 val update: (Long) -> Unit = { bytes ->122 lock.withLock {123 progress[resource.key] = bytes124 onTransfer(progress.values.sum())125 }126 }127 if (savedSize != null) {128 update(savedSize)129 } else {130 val status = permits.withPermit {131 attemptDownload(resource.key, headers, path, retries, onBytes = {}, onTransfer = update)132 }133 if (status != null) lock.withLock { failures += status }134 }135 }136 }137 }138 }139 failures.firstOrNull()?.let { return it }140 onBytes(lock.withLock { progress.values.sum() })141 withContext(ioDispatcher) {142 val playlistPath = "$location/$name.m3u8"143 files.writeBytesAsync(playlistPath, rewritten.joinToString("\n").encodeToByteArray())144 files.writeBytesAsync("$playlistPath.complete", ByteArray(0))145 }146 onBytes(playlist.length.toLong())147 return null148}149150private suspend fun HttpService.fetchText(url: String, headers: Map<String, String>): HttpResponse? =151 catchingNonCancellation {152 withTimeoutOrNull(DOWNLOAD_CONNECTION_TIMEOUT_MS) { request(HttpRequest(url = url, headers = headers)) }153 }.getOrNull()154155private fun HttpResponse.isPlaylist(): Boolean = statusCode in 200..299 && body.startsWith("#EXTM3U")156