Yokan / rebuild
Course 1 8624561

JvmMediaStreamProxy.kt

composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/player/JvmMediaStreamProxy.kt

implementation492 lines
1package eu.friedcutlet.yokan.services.media.player23import eu.friedcutlet.yokan.services.logging.AppLogger4import eu.friedcutlet.yokan.services.logging.redactUrlForLog5import eu.friedcutlet.yokan.services.http.ProfileHttpEngine6import io.ktor.client.HttpClient7import io.ktor.client.engine.HttpClientEngine8import io.ktor.client.engine.okhttp.OkHttp9import io.ktor.client.plugins.HttpTimeout10import io.ktor.client.request.headers11import io.ktor.client.request.prepareRequest12import io.ktor.client.statement.bodyAsChannel13import io.ktor.http.HttpHeaders14import io.ktor.http.HttpMethod15import io.ktor.utils.io.jvm.javaio.toInputStream16import java.io.BufferedInputStream17import java.io.BufferedOutputStream18import java.io.InputStream19import java.io.OutputStream20import java.net.InetAddress21import java.net.ServerSocket22import java.net.Socket23import java.net.URI24import java.util.Locale25import java.util.concurrent.ConcurrentHashMap26import java.util.concurrent.ArrayBlockingQueue27import java.util.concurrent.ThreadPoolExecutor28import java.util.concurrent.TimeUnit29import java.util.concurrent.RejectedExecutionException30import java.util.concurrent.atomic.AtomicBoolean31import java.util.concurrent.atomic.AtomicLong32import kotlin.concurrent.thread33import kotlinx.coroutines.CancellationException34import kotlinx.coroutines.Dispatchers35import kotlinx.coroutines.Job36import kotlinx.coroutines.NonCancellable37import kotlinx.coroutines.SupervisorJob38import kotlinx.coroutines.cancelAndJoin39import kotlinx.coroutines.runBlocking40import kotlinx.coroutines.sync.Mutex41import kotlinx.coroutines.sync.withLock42import kotlinx.coroutines.withContext4344class JvmMediaStreamProxy internal constructor(engine: HttpClientEngine) : MediaStreamProxy {45    constructor() : this(OkHttp.create())4647    private val workerJob = SupervisorJob()48    private val transport = ProfileHttpEngine(engine, workerJob)49    private val retirementLock = Mutex()50    private val http = HttpClient(transport) {51        expectSuccess = false52        followRedirects = true53        install(HttpTimeout) {54            connectTimeoutMillis = 15_000L55            requestTimeoutMillis = 60_000L56            socketTimeoutMillis = 45_000L57        }58    }59    private val entries = ConcurrentHashMap<String, ProxyEntry>()60    private val entryIds = mutableMapOf<ProxyKey, String>()61    private val clients = ConcurrentHashMap.newKeySet<Socket>()62    private val workers = ThreadPoolExecutor(63        4, 16, 30L, TimeUnit.SECONDS, ArrayBlockingQueue(32),64        { task -> Thread(task, "yokan-media-stream-proxy-client").apply { isDaemon = true } },65    ).apply { allowCoreThreadTimeOut(true) }66    private var stopped = false67    private var lastCleanupMs = 0L68    private val nextId = AtomicLong()69    private val running = AtomicBoolean(false)70    private val lock = Any()71    private var acceptThread: Thread? = null7273    @Volatile74    private var serverSocket: ServerSocket? = null7576    @Volatile77    private var port: Int = 07879    override fun proxyUrl(url: String, headers: Map<String, String>): String {80        if (headers.isEmpty()) return synchronized(lock) {81            check(!stopped) { "Media stream proxy has been stopped" }82            url83        }84        ensureStarted()85        val id = register(url, headers)86        // ExoPlayer's DefaultMediaSourceFactory picks Progressive vs HLS vs87        // DASH by URL extension (no Content-Type sniff happens before the88        // factory pick). Without an extension hint the player treats /media/189        // as opaque bytes and rejects an HLS playlist with "no extractor90        // could read the stream". Embedding the upstream's extension in the91        // proxy URL fixes the auto-detection.92        val localUrl = localUrlForId(id, extensionHint(url))93        AppLogger.info("[player-proxy] registered id=$id target=${redactUrlForLog(url)} headers=${headers.size}")94        return localUrl95    }9697    private fun retire() {98        synchronized(lock) {99            if (stopped) return100            stopped = true101            running.set(false)102            runCatching { serverSocket?.close() }103            serverSocket = null104            clients.forEach { runCatching { it.close() } }105            clients.clear()106            entries.clear()107            entryIds.clear()108        }109        workerJob.cancel()110        workers.shutdownNow()111    }112113    /** Legacy immediate shutdown; session retirement uses the awaited path below. */114    override fun stop() {115        retire()116        transport.close()117        http.close()118    }119120    override suspend fun closeAndJoin() = retirementLock.withLock {121        withContext(NonCancellable) {122            retire()123            workerJob.cancelAndJoin()124            // Ktor response producers can outlive execute() and its blocking worker.125            transport.closeAndJoin()126            withContext(Dispatchers.IO) {127                synchronized(lock) { acceptThread }?.join()128                while (!workers.awaitTermination(1, TimeUnit.SECONDS)) { /* await owned threads */ }129            }130            http.coroutineContext[Job]?.cancelAndJoin()131            http.close()132        }133    }134135    private fun ensureStarted() {136        if (running.get()) return137        synchronized(lock) {138            check(!stopped) { "Media stream proxy has been stopped" }139            if (running.get()) return140            val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))141            serverSocket = socket142            port = socket.localPort143            running.set(true)144            acceptThread = thread(name = "yokan-media-stream-proxy", isDaemon = true) { acceptLoop(socket) }145            AppLogger.info("[player-proxy] listening on 127.0.0.1:$port")146        }147    }148149    private fun acceptLoop(socket: ServerSocket) {150        while (running.get()) {151            val client = runCatching { socket.accept() }152                .onFailure { error ->153                    if (running.get()) AppLogger.warn("[player-proxy] accept failed: ${error.message.orEmpty()}")154                }155                .getOrNull() ?: if (socket.isClosed) return else continue156            synchronized(lock) {157                if (!running.get()) {158                    client.close()159                    return160                }161                clients.add(client)162                try {163                    workers.execute {164                        try {165                            handleClient(client)166                        } catch (_: java.io.IOException) {167                            // Disconnects and stop() closing an idle socket are normal.168                        } finally {169                            clients.remove(client)170                            runCatching { client.close() }171                        }172                    }173                } catch (_: RejectedExecutionException) {174                    clients.remove(client)175                    client.close()176                }177            }178        }179    }180181    private fun handleClient(socket: Socket) {182        socket.soTimeout = 30_000183        socket.use { client ->184            val input = BufferedInputStream(client.getInputStream())185            // BufferedOutputStream is NOT auto-flushed when the socket closes;186            // without an explicit flush GStreamer's hlsdemux sees a truncated187            // response and bails with "Stream doesn't contain enough data".188            val output = BufferedOutputStream(client.getOutputStream())189            try {190                val request = readHttpRequest(input) ?: run {191                    writeError(output, 400, "Bad Request")192                    return@use193                }194                if (request.method == "OPTIONS") {195                    writeResponseHeaders(output, 204, emptyMap(), 0)196                    return@use197                }198                // Strip query string and the optional extension hint we199                // append in proxyUrl / localUrl when registering. The first200                // dot in /media/<id>.<ext> is always the extension boundary.201                val rawPath = request.path.removePrefix("/media/").substringBefore('?')202                val id = (if ('.' in rawPath) rawPath.substringBeforeLast('.') else rawPath)203                    .takeIf { it.isNotBlank() }204                val entry = id?.let(entries::get)205                if (entry == null) {206                    writeError(output, 404, "Unknown media proxy entry")207                    return@use208                }209                entry.lastAccessMs.set(System.currentTimeMillis())210                proxy(entry, request, output)211            } finally {212                runCatching { output.flush() }213            }214        }215    }216217    private fun proxy(entry: ProxyEntry, request: ProxyRequest, output: OutputStream) {218        runCatching {219            runBlocking(workerJob) {220                val playlistRequest = isPlaylist(entry.url, "")221                http.prepareRequest(entry.url) {222                    method = if (request.method == "HEAD") HttpMethod.Head else HttpMethod.Get223                    headers {224                        request.headers.forEach { (name, value) ->225                            val rangeHeader = name.equals("Range", ignoreCase = true) ||226                                name.equals("If-Range", ignoreCase = true)227                            if (shouldForwardRequestHeader(name) && !(playlistRequest && rangeHeader)) {228                                append(name, value)229                            }230                        }231                        entry.headers.forEach { (name, value) ->232                            if (name.isNotBlank()) {233                                remove(name)234                                append(name, value)235                            }236                        }237                    }238                }.execute { response ->239                    val status = response.status.value240                    val responseHeaders = response.headers.entries()241                        .associate { (name, values) -> name to values.joinToString(",") }242                    val contentType = response.headers[HttpHeaders.ContentType].orEmpty()243                    val body = if (request.method == "HEAD") null else response.bodyAsChannel().toInputStream()244                    if (isPlaylist(entry.url, contentType)) {245                        val raw = body?.use { it.readBytes() }?.decodeToString().orEmpty()246                        // Strip UTF-8 BOM + leading whitespace — GStreamer's typefind247                        // only recognizes the playlist when the first bytes are `#EXTM3U`.248                        val text = raw.removePrefix("").trimStart()249                        val rewritten = rewritePlaylist(text, entry.url, entry.headers).encodeToByteArray()250                        val headers = responseHeaders251                            .filterKeys {252                                shouldForwardResponseHeader(it) &&253                                    !it.equals("Content-Length", ignoreCase = true) &&254                                    !it.equals("Content-Range", ignoreCase = true) &&255                                    !it.equals("Accept-Ranges", ignoreCase = true)256                            }257                            .toMutableMap()258                        headers["Content-Type"] = "application/vnd.apple.mpegurl"259                        headers["Content-Length"] = rewritten.size.toString()260                        writeResponseHeaders(output, status, headers, rewritten.size)261                        if (request.method != "HEAD") output.write(rewritten)262                        output.flush()263                        AppLogger.info(264                            "[player-proxy] playlist proxied status=$status " +265                                "target=${redactUrlForLog(entry.url)} bytes=${rewritten.size}",266                        )267                    } else {268                        val headers = responseHeaders.filterKeys(::shouldForwardResponseHeader)269                        writeResponseHeaders(output, status, headers, null)270                        body?.use { it.copyTo(output) }271                        output.flush()272                        AppLogger.info("[player-proxy] stream proxied status=$status target=${redactUrlForLog(entry.url)}")273                    }274                }275            }276        }.onFailure { error ->277            if (error is CancellationException || !running.get()) return@onFailure278            // Broken pipe = client closed first (seeking, switching streams,279            // player error). Anything else is worth surfacing.280            val isBrokenPipe = error is java.io.IOException &&281                error.message.orEmpty().contains("broken pipe", ignoreCase = true)282            if (isBrokenPipe) {283                AppLogger.info("[player-proxy] client disconnected target=${redactUrlForLog(entry.url)}")284            } else {285                AppLogger.error("[player-proxy] request failed target=${redactUrlForLog(entry.url)}: ${error.message.orEmpty()}")286                runCatching { writeError(output, 502, "Media proxy request failed") }287            }288        }289    }290291    private fun rewritePlaylist(body: String, baseUrl: String, headers: Map<String, String>): String {292        val base = runCatching { URI(baseUrl) }.getOrNull() ?: return body293        return body.lineSequence().joinToString("\n") { line ->294            val tagLine = uriAttributeRegex.replace(line) { match ->295                val raw = match.groupValues[1]296                val resolved = resolvePlaylistUrl(base, raw)297                if (shouldProxyUrl(resolved)) "URI=\"${localUrl(resolved, headers)}\"" else match.value298            }299            val trimmed = tagLine.trim()300            when {301                trimmed.isBlank() || trimmed.startsWith("#") -> tagLine302                else -> resolvePlaylistUrl(base, trimmed).let { resolved ->303                    if (shouldProxyUrl(resolved)) localUrl(resolved, headers) else tagLine304                }305            }306        }307    }308309    private fun resolvePlaylistUrl(base: URI, value: String): String =310        runCatching { base.resolve(value).toString() }.getOrDefault(value)311312    private fun shouldProxyUrl(url: String): Boolean =313        url.startsWith("http://", ignoreCase = true) || url.startsWith("https://", ignoreCase = true)314315    private fun localUrl(url: String, headers: Map<String, String>): String {316        val id = register(url, headers)317        return localUrlForId(id, extensionHint(url))318    }319320    private fun localUrlForId(id: String, ext: String = ""): String {321        val suffix = if (ext.isNotBlank()) ".$ext" else ""322        return "http://127.0.0.1:$port/media/$id$suffix"323    }324325    /**326     * Picks the canonical file extension off the upstream URL so the proxy327     * URL we hand the player carries the same hint. Container types that328     * ExoPlayer / GStreamer / AVPlayer dispatch on by extension only need329     * to be enumerated here; everything else degrades to the legacy "no330     * suffix" form, which is fine for direct MP4 / WebM byte streams.331     */332    private fun extensionHint(url: String): String {333        val cleanPath = url.substringBefore('?').lowercase()334        return when {335            cleanPath.endsWith(".m3u8") -> "m3u8"336            cleanPath.endsWith(".m3u") -> "m3u"337            cleanPath.endsWith(".mpd") -> "mpd"338            cleanPath.endsWith(".mp4") -> "mp4"339            cleanPath.endsWith(".m4s") -> "m4s"340            cleanPath.endsWith(".mkv") -> "mkv"341            cleanPath.endsWith(".webm") -> "webm"342            cleanPath.endsWith(".ts") -> "ts"343            cleanPath.endsWith(".aac") -> "aac"344            cleanPath.endsWith(".vtt") -> "vtt"345            else -> ""346        }347    }348349    private fun register(url: String, headers: Map<String, String>): String = synchronized(lock) {350        check(!stopped) { "Media stream proxy has been stopped" }351        val now = System.currentTimeMillis()352        cleanupIfNeeded(now)353        val key = ProxyKey(url, headers.toMap())354        entryIds[key]?.let { id ->355            entries[id]?.let { entry ->356                entry.lastAccessMs.set(now)357                return@synchronized id358            }359        }360        val id = nextId.incrementAndGet().toString()361        entries[id] = ProxyEntry(url, key.headers, AtomicLong(now))362        entryIds[key] = id363        id364    }365366    // Live playlists repeatedly name the same segments. Reuse those registrations, and367    // scan for expired entries at most once a minute rather than on every segment.368    private fun cleanupIfNeeded(now: Long) {369        if (now - lastCleanupMs < 60_000L) return370        lastCleanupMs = now371        val cutoff = now - 30 * 60 * 1_000L372        val iterator = entryIds.iterator()373        while (iterator.hasNext()) {374            val (_, id) = iterator.next()375            val entry = entries[id]376            if (entry == null || entry.lastAccessMs.get() < cutoff) {377                entries.remove(id)378                iterator.remove()379            }380        }381    }382383    private data class ProxyKey(val url: String, val headers: Map<String, String>)384385    private fun readHttpRequest(input: InputStream): ProxyRequest? {386        val requestLine = readLine(input)?.takeIf { it.isNotBlank() } ?: return null387        val parts = requestLine.split(' ')388        if (parts.size < 2) return null389        val headers = linkedMapOf<String, String>()390        while (true) {391            val line = readLine(input) ?: return null392            if (line.isBlank()) break393            val separator = line.indexOf(':')394            if (separator > 0) {395                headers[line.take(separator).trim()] = line.drop(separator + 1).trim()396            }397        }398        return ProxyRequest(399            method = parts[0].uppercase(Locale.US),400            path = parts[1],401            headers = headers,402        )403    }404405    private fun readLine(input: InputStream): String? {406        val bytes = java.io.ByteArrayOutputStream()407        while (true) {408            val next = input.read()409            if (next < 0) return if (bytes.size() == 0) null else bytes.toByteArray().decodeToString()410            if (next == '\n'.code) break411            if (next != '\r'.code) bytes.write(next)412            if (bytes.size() > 16_384) return null413        }414        return bytes.toByteArray().decodeToString()415    }416417    private fun isPlaylist(url: String, contentType: String): Boolean {418        val lowerType = contentType.lowercase()419        val lowerUrl = url.substringBefore("?").lowercase()420        return "mpegurl" in lowerType || lowerUrl.endsWith(".m3u8")421    }422423    private fun shouldForwardRequestHeader(name: String): Boolean = when (name.lowercase()) {424        "host", "connection", "proxy-connection", "content-length", "accept-encoding" -> false425        else -> true426    }427428    private fun shouldForwardResponseHeader(name: String): Boolean = when (name.lowercase()) {429        "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",430        "transfer-encoding", "upgrade", "content-encoding" -> false431        else -> true432    }433434    private fun writeError(output: OutputStream, status: Int, message: String) {435        val body = message.encodeToByteArray()436        writeResponseHeaders(437            output = output,438            status = status,439            headers = mapOf("Content-Type" to "text/plain; charset=utf-8", "Content-Length" to body.size.toString()),440            contentLength = body.size,441        )442        output.write(body)443    }444445    private fun writeResponseHeaders(446        output: OutputStream,447        status: Int,448        headers: Map<String, String>,449        contentLength: Int?,450    ) {451        output.writeAscii("HTTP/1.1 $status ${reasonPhrase(status)}\r\n")452        output.writeAscii("Connection: close\r\n")453        output.writeAscii("Access-Control-Allow-Origin: *\r\n")454        val hasLength = headers.keys.any { it.equals("Content-Length", ignoreCase = true) }455        if (contentLength != null && !hasLength) output.writeAscii("Content-Length: $contentLength\r\n")456        headers.forEach { (name, value) ->457            if (name.isNotBlank() && value.isNotBlank()) output.writeAscii("$name: $value\r\n")458        }459        output.writeAscii("\r\n")460    }461462    private fun OutputStream.writeAscii(value: String) {463        write(value.encodeToByteArray())464    }465466    private fun reasonPhrase(status: Int): String = when (status) {467        200 -> "OK"468        204 -> "No Content"469        206 -> "Partial Content"470        400 -> "Bad Request"471        404 -> "Not Found"472        500 -> "Internal Server Error"473        502 -> "Bad Gateway"474        else -> "Status"475    }476477    private data class ProxyEntry(478        val url: String,479        val headers: Map<String, String>,480        val lastAccessMs: AtomicLong,481    )482483    private data class ProxyRequest(484        val method: String,485        val path: String,486        val headers: Map<String, String>,487    )488489    private companion object {490        val uriAttributeRegex = Regex("URI=\"([^\"]+)\"")491    }492}493

Search chapters, reference and source filenames.