package eu.friedcutlet.yokan.services.media.cast import eu.friedcutlet.yokan.services.logging.AppLogger import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.put internal const val CAST_CONNECT_TIMEOUT_MS = 15_000L private const val TICK_MS = 1_000L private const val HEARTBEAT_TICKS = 5 private const val MAX_MISSED_HEARTBEATS = 3 /** * One CASTV2 session over [transport]: CONNECT → LAUNCH Default Media Receiver → CONNECT to its transportId → media * commands. Not thread-safe: every call must run on [scope]'s dispatcher, which must be single-threaded. * Failures are thrown from suspend calls and surfaced as [CastStatus.error]; nothing is retried. */ internal class CastSession( private val device: CastDevice, private val transport: CastTransport, private val scope: CoroutineScope, ) { private val reader = CastFrameReader(transport) private val writeLock = Mutex() private val launched = CompletableDeferred() private val mediaSessionId = MutableStateFlow(null) private val _status = MutableStateFlow(null) val status: StateFlow = _status.asStateFlow() private var requestId = 0 private var transportId: String? = null private var appSessionId: String? = null private var currentItemId: Int? = null private var itemIds = emptyList() private var itemIdsRequested = false private var style = CastTextStyle() private var missedHeartbeats = 0 private var closed = false private val jobs = mutableListOf() private fun nextId() = ++requestId suspend fun connect() { jobs += scope.launch { readLoop() } try { withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) { send(NS_CONNECTION, RECEIVER_ID, castJson("CONNECT")) send(NS_RECEIVER, RECEIVER_ID, castJson("LAUNCH", nextId()) { put("appId", DEFAULT_MEDIA_RECEIVER_APP_ID) }) launched.await() send(NS_CONNECTION, checkNotNull(transportId), castJson("CONNECT")) } ?: error("Timed out connecting to ${device.name}") } catch (e: Throwable) { close() throw e } _status.value = CastStatus(device) jobs += scope.launch { tickLoop() } } suspend fun loadQueue( items: List, startIndex: Int, startPositionMs: Long, style: CastTextStyle, activeSubtitleIndex: Int?, ) { require(startIndex in items.indices) { "Start index $startIndex outside queue of ${items.size}" } this.style = style itemIds = emptyList() currentItemId = null itemIdsRequested = false _status.update { it?.copy( queue = items, currentIndex = startIndex, positionMs = startPositionMs, durationMs = 0, playing = false, buffering = true, finished = false, error = null, ) } send(NS_MEDIA, connectedTransportId(), queueLoadJson(nextId(), items, startIndex, startPositionMs, style, activeSubtitleIndex)) } suspend fun append(items: List) { if (items.isEmpty()) return // The media session id arrives with the first MEDIA_STATUS after QUEUE_LOAD. val sessionId = withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) { mediaSessionId.filterNotNull().first() } ?: error("No media loaded on ${device.name}") send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_INSERT", nextId(), sessionId) { put("items", queueItemsJson(items, style)) }) _status.update { it?.copy(queue = it.queue + items, finished = false) } } suspend fun play() = mediaCommand("PLAY") suspend fun pause() = mediaCommand("PAUSE") suspend fun seekTo(positionMs: Long) = mediaCommand("SEEK") { put("currentTime", positionMs / 1000.0) } suspend fun next() = mediaCommand("QUEUE_UPDATE") { put("jump", 1) } suspend fun previous() = mediaCommand("QUEUE_UPDATE") { put("jump", -1) } suspend fun jumpTo(index: Int) { val itemId = itemIds.getOrNull(index) val current = _status.value?.currentIndex ?: -1 when { itemId != null -> mediaCommand("QUEUE_UPDATE") { put("currentItemId", itemId) } current >= 0 -> mediaCommand("QUEUE_UPDATE") { put("jump", index - current) } } } suspend fun disconnect() { try { if (!closed) { appSessionId?.let { send(NS_RECEIVER, RECEIVER_ID, castJson("STOP", nextId()) { put("sessionId", it) }) } transportId?.let { send(NS_CONNECTION, it, castJson("CLOSE")) } send(NS_CONNECTION, RECEIVER_ID, castJson("CLOSE")) } } catch (e: CancellationException) { throw e } catch (e: Throwable) { AppLogger.warn("Cast: stopping receiver on ${device.name} failed: ${e.message}") } finally { close() _status.value = null } } fun close() { closed = true launched.cancel() jobs.forEach { it.cancel() } transport.close() } /** No media session means there is nothing to control yet. */ private suspend fun mediaCommand(type: String, extra: JsonObjectBuilder.() -> Unit = {}) { val sessionId = mediaSessionId.value ?: return send(NS_MEDIA, connectedTransportId(), castJson(type, nextId(), sessionId, extra)) } private fun connectedTransportId() = checkNotNull(transportId.takeIf { !closed }) { "Not connected to ${device.name}" } private suspend fun send(namespace: String, destination: String, payload: String) { val frame = CastMessage(SENDER_ID, destination, namespace, payload).toFrame() try { writeLock.withLock { transport.write(frame) } } catch (e: CancellationException) { throw e } catch (e: Throwable) { fail("Lost connection to ${device.name}: ${e.message}", e) throw e } } private fun fail(message: String, cause: Throwable?) { if (closed) return AppLogger.warn("Cast: $message") launched.completeExceptionally(IllegalStateException(message, cause)) _status.update { it?.copy(playing = false, buffering = false, error = message) } close() } private suspend fun readLoop() { try { while (true) handle(reader.next()) } catch (e: CancellationException) { throw e } catch (e: Throwable) { fail("Lost connection to ${device.name}: ${e.message}", e) } } /** Polls media status each second while playing (receivers only push on state changes) and pings every 5s. */ private suspend fun tickLoop() { var tick = 0 try { while (true) { delay(TICK_MS) if (++tick % HEARTBEAT_TICKS == 0) { if (++missedHeartbeats > MAX_MISSED_HEARTBEATS) { fail("${device.name} stopped responding", null) return } send(NS_HEARTBEAT, RECEIVER_ID, castJson("PING")) } val sessionId = mediaSessionId.value if (sessionId != null && _status.value?.playing == true) { send(NS_MEDIA, connectedTransportId(), castJson("GET_STATUS", nextId(), sessionId)) } } } catch (e: CancellationException) { throw e } catch (_: Throwable) { // send() already failed the session. } } private suspend fun handle(message: CastMessage) { missedHeartbeats = 0 val json = try { Json.parseToJsonElement(message.payload) as? JsonObject } catch (_: IllegalArgumentException) { null } ?: return when (json.string("type")) { "PING" -> send(NS_HEARTBEAT, message.sourceId, castJson("PONG")) "CLOSE" -> if (message.sourceId == transportId || message.sourceId == RECEIVER_ID) { fail("${device.name} closed the Cast session", null) } "RECEIVER_STATUS" -> receiverStatus(json) "LAUNCH_ERROR" -> launched.completeExceptionally( IllegalStateException("${device.name} refused to launch the media receiver: ${json.string("reason")}"), ) "MEDIA_STATUS" -> mediaStatus(json) "QUEUE_ITEM_IDS" -> { itemIds = (json["itemIds"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.intOrNull }.orEmpty() itemIdsRequested = false _status.update { status -> status?.copy(currentIndex = currentItemId?.let(itemIds::indexOf) ?: status.currentIndex) } } "LOAD_FAILED", "INVALID_REQUEST", "INVALID_PLAYER_STATE" -> { val reason = json.string("reason")?.let { " ($it)" }.orEmpty() _status.update { it?.copy(buffering = false, error = "Cast device rejected the request: ${json.string("type")}$reason") } } } } private fun receiverStatus(json: JsonObject) { val applications = ((json["status"] as? JsonObject)?.get("applications") as? JsonArray).orEmpty() val app = applications.firstNotNullOfOrNull { entry -> (entry as? JsonObject)?.takeIf { it.string("appId") == DEFAULT_MEDIA_RECEIVER_APP_ID } } if (app == null) { // Before launch completes the receiver may still report its idle backdrop app. if (transportId != null) fail("Media receiver on ${device.name} was stopped", null) return } val id = app.string("transportId") ?: return appSessionId = app.string("sessionId") if (transportId == null) { transportId = id launched.complete(Unit) } } private suspend fun mediaStatus(json: JsonObject) { val entry = (json["status"] as? JsonArray)?.firstOrNull() as? JsonObject mediaSessionId.value = entry?.int("mediaSessionId") entry?.int("currentItemId")?.let { currentItemId = it } val queueSize = _status.value?.queue?.size ?: 0 // Receivers may send only a window of items; only a complete list maps positions to queue indexes. (entry?.get("items") as? JsonArray) ?.mapNotNull { (it as? JsonObject)?.int("itemId") } ?.takeIf { it.size == queueSize } ?.let { itemIds = it } _status.update { it?.withMediaStatus(entry, itemIds) } val sessionId = mediaSessionId.value val itemId = currentItemId if (sessionId != null && itemId != null && itemId !in itemIds && !itemIdsRequested) { itemIdsRequested = true send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_GET_ITEM_IDS", nextId(), sessionId)) } } }