Yokan / rebuild
Course 1 8624561

CastSession.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastSession.kt

implementation278 lines
1package eu.friedcutlet.yokan.services.media.cast23import eu.friedcutlet.yokan.services.logging.AppLogger4import kotlinx.coroutines.CancellationException5import kotlinx.coroutines.CompletableDeferred6import kotlinx.coroutines.CoroutineScope7import kotlinx.coroutines.Job8import kotlinx.coroutines.delay9import kotlinx.coroutines.flow.MutableStateFlow10import kotlinx.coroutines.flow.StateFlow11import kotlinx.coroutines.flow.asStateFlow12import kotlinx.coroutines.flow.filterNotNull13import kotlinx.coroutines.flow.first14import kotlinx.coroutines.flow.update15import kotlinx.coroutines.launch16import kotlinx.coroutines.sync.Mutex17import kotlinx.coroutines.sync.withLock18import kotlinx.coroutines.withTimeoutOrNull19import kotlinx.serialization.json.Json20import kotlinx.serialization.json.JsonArray21import kotlinx.serialization.json.JsonObject22import kotlinx.serialization.json.JsonObjectBuilder23import kotlinx.serialization.json.JsonPrimitive24import kotlinx.serialization.json.intOrNull25import kotlinx.serialization.json.put2627internal const val CAST_CONNECT_TIMEOUT_MS = 15_000L28private const val TICK_MS = 1_000L29private const val HEARTBEAT_TICKS = 530private const val MAX_MISSED_HEARTBEATS = 33132/**33 * One CASTV2 session over [transport]: CONNECT → LAUNCH Default Media Receiver → CONNECT to its transportId → media34 * commands. Not thread-safe: every call must run on [scope]'s dispatcher, which must be single-threaded.35 * Failures are thrown from suspend calls and surfaced as [CastStatus.error]; nothing is retried.36 */37internal class CastSession(38    private val device: CastDevice,39    private val transport: CastTransport,40    private val scope: CoroutineScope,41) {42    private val reader = CastFrameReader(transport)43    private val writeLock = Mutex()44    private val launched = CompletableDeferred<Unit>()45    private val mediaSessionId = MutableStateFlow<Int?>(null)46    private val _status = MutableStateFlow<CastStatus?>(null)47    val status: StateFlow<CastStatus?> = _status.asStateFlow()4849    private var requestId = 050    private var transportId: String? = null51    private var appSessionId: String? = null52    private var currentItemId: Int? = null53    private var itemIds = emptyList<Int>()54    private var itemIdsRequested = false55    private var style = CastTextStyle()56    private var missedHeartbeats = 057    private var closed = false58    private val jobs = mutableListOf<Job>()5960    private fun nextId() = ++requestId6162    suspend fun connect() {63        jobs += scope.launch { readLoop() }64        try {65            withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) {66                send(NS_CONNECTION, RECEIVER_ID, castJson("CONNECT"))67                send(NS_RECEIVER, RECEIVER_ID, castJson("LAUNCH", nextId()) { put("appId", DEFAULT_MEDIA_RECEIVER_APP_ID) })68                launched.await()69                send(NS_CONNECTION, checkNotNull(transportId), castJson("CONNECT"))70            } ?: error("Timed out connecting to ${device.name}")71        } catch (e: Throwable) {72            close()73            throw e74        }75        _status.value = CastStatus(device)76        jobs += scope.launch { tickLoop() }77    }7879    suspend fun loadQueue(80        items: List<CastMedia>,81        startIndex: Int,82        startPositionMs: Long,83        style: CastTextStyle,84        activeSubtitleIndex: Int?,85    ) {86        require(startIndex in items.indices) { "Start index $startIndex outside queue of ${items.size}" }87        this.style = style88        itemIds = emptyList()89        currentItemId = null90        itemIdsRequested = false91        _status.update {92            it?.copy(93                queue = items, currentIndex = startIndex, positionMs = startPositionMs, durationMs = 0,94                playing = false, buffering = true, finished = false, error = null,95            )96        }97        send(NS_MEDIA, connectedTransportId(), queueLoadJson(nextId(), items, startIndex, startPositionMs, style, activeSubtitleIndex))98    }99100    suspend fun append(items: List<CastMedia>) {101        if (items.isEmpty()) return102        // The media session id arrives with the first MEDIA_STATUS after QUEUE_LOAD.103        val sessionId = withTimeoutOrNull(CAST_CONNECT_TIMEOUT_MS) { mediaSessionId.filterNotNull().first() }104            ?: error("No media loaded on ${device.name}")105        send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_INSERT", nextId(), sessionId) {106            put("items", queueItemsJson(items, style))107        })108        _status.update { it?.copy(queue = it.queue + items, finished = false) }109    }110111    suspend fun play() = mediaCommand("PLAY")112    suspend fun pause() = mediaCommand("PAUSE")113    suspend fun seekTo(positionMs: Long) = mediaCommand("SEEK") { put("currentTime", positionMs / 1000.0) }114    suspend fun next() = mediaCommand("QUEUE_UPDATE") { put("jump", 1) }115    suspend fun previous() = mediaCommand("QUEUE_UPDATE") { put("jump", -1) }116117    suspend fun jumpTo(index: Int) {118        val itemId = itemIds.getOrNull(index)119        val current = _status.value?.currentIndex ?: -1120        when {121            itemId != null -> mediaCommand("QUEUE_UPDATE") { put("currentItemId", itemId) }122            current >= 0 -> mediaCommand("QUEUE_UPDATE") { put("jump", index - current) }123        }124    }125126    suspend fun disconnect() {127        try {128            if (!closed) {129                appSessionId?.let { send(NS_RECEIVER, RECEIVER_ID, castJson("STOP", nextId()) { put("sessionId", it) }) }130                transportId?.let { send(NS_CONNECTION, it, castJson("CLOSE")) }131                send(NS_CONNECTION, RECEIVER_ID, castJson("CLOSE"))132            }133        } catch (e: CancellationException) {134            throw e135        } catch (e: Throwable) {136            AppLogger.warn("Cast: stopping receiver on ${device.name} failed: ${e.message}")137        } finally {138            close()139            _status.value = null140        }141    }142143    fun close() {144        closed = true145        launched.cancel()146        jobs.forEach { it.cancel() }147        transport.close()148    }149150    /** No media session means there is nothing to control yet. */151    private suspend fun mediaCommand(type: String, extra: JsonObjectBuilder.() -> Unit = {}) {152        val sessionId = mediaSessionId.value ?: return153        send(NS_MEDIA, connectedTransportId(), castJson(type, nextId(), sessionId, extra))154    }155156    private fun connectedTransportId() = checkNotNull(transportId.takeIf { !closed }) { "Not connected to ${device.name}" }157158    private suspend fun send(namespace: String, destination: String, payload: String) {159        val frame = CastMessage(SENDER_ID, destination, namespace, payload).toFrame()160        try {161            writeLock.withLock { transport.write(frame) }162        } catch (e: CancellationException) {163            throw e164        } catch (e: Throwable) {165            fail("Lost connection to ${device.name}: ${e.message}", e)166            throw e167        }168    }169170    private fun fail(message: String, cause: Throwable?) {171        if (closed) return172        AppLogger.warn("Cast: $message")173        launched.completeExceptionally(IllegalStateException(message, cause))174        _status.update { it?.copy(playing = false, buffering = false, error = message) }175        close()176    }177178    private suspend fun readLoop() {179        try {180            while (true) handle(reader.next())181        } catch (e: CancellationException) {182            throw e183        } catch (e: Throwable) {184            fail("Lost connection to ${device.name}: ${e.message}", e)185        }186    }187188    /** Polls media status each second while playing (receivers only push on state changes) and pings every 5s. */189    private suspend fun tickLoop() {190        var tick = 0191        try {192            while (true) {193                delay(TICK_MS)194                if (++tick % HEARTBEAT_TICKS == 0) {195                    if (++missedHeartbeats > MAX_MISSED_HEARTBEATS) {196                        fail("${device.name} stopped responding", null)197                        return198                    }199                    send(NS_HEARTBEAT, RECEIVER_ID, castJson("PING"))200                }201                val sessionId = mediaSessionId.value202                if (sessionId != null && _status.value?.playing == true) {203                    send(NS_MEDIA, connectedTransportId(), castJson("GET_STATUS", nextId(), sessionId))204                }205            }206        } catch (e: CancellationException) {207            throw e208        } catch (_: Throwable) {209            // send() already failed the session.210        }211    }212213    private suspend fun handle(message: CastMessage) {214        missedHeartbeats = 0215        val json = try {216            Json.parseToJsonElement(message.payload) as? JsonObject217        } catch (_: IllegalArgumentException) {218            null219        } ?: return220        when (json.string("type")) {221            "PING" -> send(NS_HEARTBEAT, message.sourceId, castJson("PONG"))222            "CLOSE" -> if (message.sourceId == transportId || message.sourceId == RECEIVER_ID) {223                fail("${device.name} closed the Cast session", null)224            }225            "RECEIVER_STATUS" -> receiverStatus(json)226            "LAUNCH_ERROR" -> launched.completeExceptionally(227                IllegalStateException("${device.name} refused to launch the media receiver: ${json.string("reason")}"),228            )229            "MEDIA_STATUS" -> mediaStatus(json)230            "QUEUE_ITEM_IDS" -> {231                itemIds = (json["itemIds"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.intOrNull }.orEmpty()232                itemIdsRequested = false233                _status.update { status -> status?.copy(currentIndex = currentItemId?.let(itemIds::indexOf) ?: status.currentIndex) }234            }235            "LOAD_FAILED", "INVALID_REQUEST", "INVALID_PLAYER_STATE" -> {236                val reason = json.string("reason")?.let { " ($it)" }.orEmpty()237                _status.update { it?.copy(buffering = false, error = "Cast device rejected the request: ${json.string("type")}$reason") }238            }239        }240    }241242    private fun receiverStatus(json: JsonObject) {243        val applications = ((json["status"] as? JsonObject)?.get("applications") as? JsonArray).orEmpty()244        val app = applications.firstNotNullOfOrNull { entry ->245            (entry as? JsonObject)?.takeIf { it.string("appId") == DEFAULT_MEDIA_RECEIVER_APP_ID }246        }247        if (app == null) {248            // Before launch completes the receiver may still report its idle backdrop app.249            if (transportId != null) fail("Media receiver on ${device.name} was stopped", null)250            return251        }252        val id = app.string("transportId") ?: return253        appSessionId = app.string("sessionId")254        if (transportId == null) {255            transportId = id256            launched.complete(Unit)257        }258    }259260    private suspend fun mediaStatus(json: JsonObject) {261        val entry = (json["status"] as? JsonArray)?.firstOrNull() as? JsonObject262        mediaSessionId.value = entry?.int("mediaSessionId")263        entry?.int("currentItemId")?.let { currentItemId = it }264        val queueSize = _status.value?.queue?.size ?: 0265        // Receivers may send only a window of items; only a complete list maps positions to queue indexes.266        (entry?.get("items") as? JsonArray)267            ?.mapNotNull { (it as? JsonObject)?.int("itemId") }268            ?.takeIf { it.size == queueSize }269            ?.let { itemIds = it }270        _status.update { it?.withMediaStatus(entry, itemIds) }271        val sessionId = mediaSessionId.value272        val itemId = currentItemId273        if (sessionId != null && itemId != null && itemId !in itemIds && !itemIdsRequested) {274            itemIdsRequested = true275            send(NS_MEDIA, connectedTransportId(), castJson("QUEUE_GET_ITEM_IDS", nextId(), sessionId))276        }277    }278}279

Search chapters, reference and source filenames.