package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.redactUrlForLog import eu.friedcutlet.yokan.services.http.ProfileHttpEngine import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.plugins.HttpTimeout import io.ktor.client.request.headers import io.ktor.client.request.prepareRequest import io.ktor.client.statement.bodyAsChannel import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.utils.io.jvm.javaio.toInputStream import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.InputStream import java.io.OutputStream import java.net.InetAddress import java.net.ServerSocket import java.net.Socket import java.net.URI import java.util.Locale import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.concurrent.RejectedExecutionException import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong import kotlin.concurrent.thread import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext class JvmMediaStreamProxy internal constructor(engine: HttpClientEngine) : MediaStreamProxy { constructor() : this(OkHttp.create()) private val workerJob = SupervisorJob() private val transport = ProfileHttpEngine(engine, workerJob) private val retirementLock = Mutex() private val http = HttpClient(transport) { expectSuccess = false followRedirects = true install(HttpTimeout) { connectTimeoutMillis = 15_000L requestTimeoutMillis = 60_000L socketTimeoutMillis = 45_000L } } private val entries = ConcurrentHashMap() private val entryIds = mutableMapOf() private val clients = ConcurrentHashMap.newKeySet() private val workers = ThreadPoolExecutor( 4, 16, 30L, TimeUnit.SECONDS, ArrayBlockingQueue(32), { task -> Thread(task, "yokan-media-stream-proxy-client").apply { isDaemon = true } }, ).apply { allowCoreThreadTimeOut(true) } private var stopped = false private var lastCleanupMs = 0L private val nextId = AtomicLong() private val running = AtomicBoolean(false) private val lock = Any() private var acceptThread: Thread? = null @Volatile private var serverSocket: ServerSocket? = null @Volatile private var port: Int = 0 override fun proxyUrl(url: String, headers: Map): String { if (headers.isEmpty()) return synchronized(lock) { check(!stopped) { "Media stream proxy has been stopped" } url } ensureStarted() val id = register(url, headers) // ExoPlayer's DefaultMediaSourceFactory picks Progressive vs HLS vs // DASH by URL extension (no Content-Type sniff happens before the // factory pick). Without an extension hint the player treats /media/1 // as opaque bytes and rejects an HLS playlist with "no extractor // could read the stream". Embedding the upstream's extension in the // proxy URL fixes the auto-detection. val localUrl = localUrlForId(id, extensionHint(url)) AppLogger.info("[player-proxy] registered id=$id target=${redactUrlForLog(url)} headers=${headers.size}") return localUrl } private fun retire() { synchronized(lock) { if (stopped) return stopped = true running.set(false) runCatching { serverSocket?.close() } serverSocket = null clients.forEach { runCatching { it.close() } } clients.clear() entries.clear() entryIds.clear() } workerJob.cancel() workers.shutdownNow() } /** Legacy immediate shutdown; session retirement uses the awaited path below. */ override fun stop() { retire() transport.close() http.close() } override suspend fun closeAndJoin() = retirementLock.withLock { withContext(NonCancellable) { retire() workerJob.cancelAndJoin() // Ktor response producers can outlive execute() and its blocking worker. transport.closeAndJoin() withContext(Dispatchers.IO) { synchronized(lock) { acceptThread }?.join() while (!workers.awaitTermination(1, TimeUnit.SECONDS)) { /* await owned threads */ } } http.coroutineContext[Job]?.cancelAndJoin() http.close() } } private fun ensureStarted() { if (running.get()) return synchronized(lock) { check(!stopped) { "Media stream proxy has been stopped" } if (running.get()) return val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")) serverSocket = socket port = socket.localPort running.set(true) acceptThread = thread(name = "yokan-media-stream-proxy", isDaemon = true) { acceptLoop(socket) } AppLogger.info("[player-proxy] listening on 127.0.0.1:$port") } } private fun acceptLoop(socket: ServerSocket) { while (running.get()) { val client = runCatching { socket.accept() } .onFailure { error -> if (running.get()) AppLogger.warn("[player-proxy] accept failed: ${error.message.orEmpty()}") } .getOrNull() ?: if (socket.isClosed) return else continue synchronized(lock) { if (!running.get()) { client.close() return } clients.add(client) try { workers.execute { try { handleClient(client) } catch (_: java.io.IOException) { // Disconnects and stop() closing an idle socket are normal. } finally { clients.remove(client) runCatching { client.close() } } } } catch (_: RejectedExecutionException) { clients.remove(client) client.close() } } } } private fun handleClient(socket: Socket) { socket.soTimeout = 30_000 socket.use { client -> val input = BufferedInputStream(client.getInputStream()) // BufferedOutputStream is NOT auto-flushed when the socket closes; // without an explicit flush GStreamer's hlsdemux sees a truncated // response and bails with "Stream doesn't contain enough data". val output = BufferedOutputStream(client.getOutputStream()) try { val request = readHttpRequest(input) ?: run { writeError(output, 400, "Bad Request") return@use } if (request.method == "OPTIONS") { writeResponseHeaders(output, 204, emptyMap(), 0) return@use } // Strip query string and the optional extension hint we // append in proxyUrl / localUrl when registering. The first // dot in /media/. is always the extension boundary. val rawPath = request.path.removePrefix("/media/").substringBefore('?') val id = (if ('.' in rawPath) rawPath.substringBeforeLast('.') else rawPath) .takeIf { it.isNotBlank() } val entry = id?.let(entries::get) if (entry == null) { writeError(output, 404, "Unknown media proxy entry") return@use } entry.lastAccessMs.set(System.currentTimeMillis()) proxy(entry, request, output) } finally { runCatching { output.flush() } } } } private fun proxy(entry: ProxyEntry, request: ProxyRequest, output: OutputStream) { runCatching { runBlocking(workerJob) { val playlistRequest = isPlaylist(entry.url, "") http.prepareRequest(entry.url) { method = if (request.method == "HEAD") HttpMethod.Head else HttpMethod.Get headers { request.headers.forEach { (name, value) -> val rangeHeader = name.equals("Range", ignoreCase = true) || name.equals("If-Range", ignoreCase = true) if (shouldForwardRequestHeader(name) && !(playlistRequest && rangeHeader)) { append(name, value) } } entry.headers.forEach { (name, value) -> if (name.isNotBlank()) { remove(name) append(name, value) } } } }.execute { response -> val status = response.status.value val responseHeaders = response.headers.entries() .associate { (name, values) -> name to values.joinToString(",") } val contentType = response.headers[HttpHeaders.ContentType].orEmpty() val body = if (request.method == "HEAD") null else response.bodyAsChannel().toInputStream() if (isPlaylist(entry.url, contentType)) { val raw = body?.use { it.readBytes() }?.decodeToString().orEmpty() // Strip UTF-8 BOM + leading whitespace — GStreamer's typefind // only recognizes the playlist when the first bytes are `#EXTM3U`. val text = raw.removePrefix("").trimStart() val rewritten = rewritePlaylist(text, entry.url, entry.headers).encodeToByteArray() val headers = responseHeaders .filterKeys { shouldForwardResponseHeader(it) && !it.equals("Content-Length", ignoreCase = true) && !it.equals("Content-Range", ignoreCase = true) && !it.equals("Accept-Ranges", ignoreCase = true) } .toMutableMap() headers["Content-Type"] = "application/vnd.apple.mpegurl" headers["Content-Length"] = rewritten.size.toString() writeResponseHeaders(output, status, headers, rewritten.size) if (request.method != "HEAD") output.write(rewritten) output.flush() AppLogger.info( "[player-proxy] playlist proxied status=$status " + "target=${redactUrlForLog(entry.url)} bytes=${rewritten.size}", ) } else { val headers = responseHeaders.filterKeys(::shouldForwardResponseHeader) writeResponseHeaders(output, status, headers, null) body?.use { it.copyTo(output) } output.flush() AppLogger.info("[player-proxy] stream proxied status=$status target=${redactUrlForLog(entry.url)}") } } } }.onFailure { error -> if (error is CancellationException || !running.get()) return@onFailure // Broken pipe = client closed first (seeking, switching streams, // player error). Anything else is worth surfacing. val isBrokenPipe = error is java.io.IOException && error.message.orEmpty().contains("broken pipe", ignoreCase = true) if (isBrokenPipe) { AppLogger.info("[player-proxy] client disconnected target=${redactUrlForLog(entry.url)}") } else { AppLogger.error("[player-proxy] request failed target=${redactUrlForLog(entry.url)}: ${error.message.orEmpty()}") runCatching { writeError(output, 502, "Media proxy request failed") } } } } private fun rewritePlaylist(body: String, baseUrl: String, headers: Map): String { val base = runCatching { URI(baseUrl) }.getOrNull() ?: return body return body.lineSequence().joinToString("\n") { line -> val tagLine = uriAttributeRegex.replace(line) { match -> val raw = match.groupValues[1] val resolved = resolvePlaylistUrl(base, raw) if (shouldProxyUrl(resolved)) "URI=\"${localUrl(resolved, headers)}\"" else match.value } val trimmed = tagLine.trim() when { trimmed.isBlank() || trimmed.startsWith("#") -> tagLine else -> resolvePlaylistUrl(base, trimmed).let { resolved -> if (shouldProxyUrl(resolved)) localUrl(resolved, headers) else tagLine } } } } private fun resolvePlaylistUrl(base: URI, value: String): String = runCatching { base.resolve(value).toString() }.getOrDefault(value) private fun shouldProxyUrl(url: String): Boolean = url.startsWith("http://", ignoreCase = true) || url.startsWith("https://", ignoreCase = true) private fun localUrl(url: String, headers: Map): String { val id = register(url, headers) return localUrlForId(id, extensionHint(url)) } private fun localUrlForId(id: String, ext: String = ""): String { val suffix = if (ext.isNotBlank()) ".$ext" else "" return "http://127.0.0.1:$port/media/$id$suffix" } /** * Picks the canonical file extension off the upstream URL so the proxy * URL we hand the player carries the same hint. Container types that * ExoPlayer / GStreamer / AVPlayer dispatch on by extension only need * to be enumerated here; everything else degrades to the legacy "no * suffix" form, which is fine for direct MP4 / WebM byte streams. */ private fun extensionHint(url: String): String { val cleanPath = url.substringBefore('?').lowercase() return when { cleanPath.endsWith(".m3u8") -> "m3u8" cleanPath.endsWith(".m3u") -> "m3u" cleanPath.endsWith(".mpd") -> "mpd" cleanPath.endsWith(".mp4") -> "mp4" cleanPath.endsWith(".m4s") -> "m4s" cleanPath.endsWith(".mkv") -> "mkv" cleanPath.endsWith(".webm") -> "webm" cleanPath.endsWith(".ts") -> "ts" cleanPath.endsWith(".aac") -> "aac" cleanPath.endsWith(".vtt") -> "vtt" else -> "" } } private fun register(url: String, headers: Map): String = synchronized(lock) { check(!stopped) { "Media stream proxy has been stopped" } val now = System.currentTimeMillis() cleanupIfNeeded(now) val key = ProxyKey(url, headers.toMap()) entryIds[key]?.let { id -> entries[id]?.let { entry -> entry.lastAccessMs.set(now) return@synchronized id } } val id = nextId.incrementAndGet().toString() entries[id] = ProxyEntry(url, key.headers, AtomicLong(now)) entryIds[key] = id id } // Live playlists repeatedly name the same segments. Reuse those registrations, and // scan for expired entries at most once a minute rather than on every segment. private fun cleanupIfNeeded(now: Long) { if (now - lastCleanupMs < 60_000L) return lastCleanupMs = now val cutoff = now - 30 * 60 * 1_000L val iterator = entryIds.iterator() while (iterator.hasNext()) { val (_, id) = iterator.next() val entry = entries[id] if (entry == null || entry.lastAccessMs.get() < cutoff) { entries.remove(id) iterator.remove() } } } private data class ProxyKey(val url: String, val headers: Map) private fun readHttpRequest(input: InputStream): ProxyRequest? { val requestLine = readLine(input)?.takeIf { it.isNotBlank() } ?: return null val parts = requestLine.split(' ') if (parts.size < 2) return null val headers = linkedMapOf() while (true) { val line = readLine(input) ?: return null if (line.isBlank()) break val separator = line.indexOf(':') if (separator > 0) { headers[line.take(separator).trim()] = line.drop(separator + 1).trim() } } return ProxyRequest( method = parts[0].uppercase(Locale.US), path = parts[1], headers = headers, ) } private fun readLine(input: InputStream): String? { val bytes = java.io.ByteArrayOutputStream() while (true) { val next = input.read() if (next < 0) return if (bytes.size() == 0) null else bytes.toByteArray().decodeToString() if (next == '\n'.code) break if (next != '\r'.code) bytes.write(next) if (bytes.size() > 16_384) return null } return bytes.toByteArray().decodeToString() } private fun isPlaylist(url: String, contentType: String): Boolean { val lowerType = contentType.lowercase() val lowerUrl = url.substringBefore("?").lowercase() return "mpegurl" in lowerType || lowerUrl.endsWith(".m3u8") } private fun shouldForwardRequestHeader(name: String): Boolean = when (name.lowercase()) { "host", "connection", "proxy-connection", "content-length", "accept-encoding" -> false else -> true } private fun shouldForwardResponseHeader(name: String): Boolean = when (name.lowercase()) { "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "content-encoding" -> false else -> true } private fun writeError(output: OutputStream, status: Int, message: String) { val body = message.encodeToByteArray() writeResponseHeaders( output = output, status = status, headers = mapOf("Content-Type" to "text/plain; charset=utf-8", "Content-Length" to body.size.toString()), contentLength = body.size, ) output.write(body) } private fun writeResponseHeaders( output: OutputStream, status: Int, headers: Map, contentLength: Int?, ) { output.writeAscii("HTTP/1.1 $status ${reasonPhrase(status)}\r\n") output.writeAscii("Connection: close\r\n") output.writeAscii("Access-Control-Allow-Origin: *\r\n") val hasLength = headers.keys.any { it.equals("Content-Length", ignoreCase = true) } if (contentLength != null && !hasLength) output.writeAscii("Content-Length: $contentLength\r\n") headers.forEach { (name, value) -> if (name.isNotBlank() && value.isNotBlank()) output.writeAscii("$name: $value\r\n") } output.writeAscii("\r\n") } private fun OutputStream.writeAscii(value: String) { write(value.encodeToByteArray()) } private fun reasonPhrase(status: Int): String = when (status) { 200 -> "OK" 204 -> "No Content" 206 -> "Partial Content" 400 -> "Bad Request" 404 -> "Not Found" 500 -> "Internal Server Error" 502 -> "Bad Gateway" else -> "Status" } private data class ProxyEntry( val url: String, val headers: Map, val lastAccessMs: AtomicLong, ) private data class ProxyRequest( val method: String, val path: String, val headers: Map, ) private companion object { val uriAttributeRegex = Regex("URI=\"([^\"]+)\"") } }