Yokan / rebuild
Course 1 8624561

CastProtocol.kt

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

implementation275 lines
1package eu.friedcutlet.yokan.services.media.cast23import kotlinx.serialization.json.JsonArray4import kotlinx.serialization.json.JsonObject5import kotlinx.serialization.json.JsonObjectBuilder6import kotlinx.serialization.json.JsonPrimitive7import kotlinx.serialization.json.add8import kotlinx.serialization.json.buildJsonArray9import kotlinx.serialization.json.buildJsonObject10import kotlinx.serialization.json.doubleOrNull11import kotlinx.serialization.json.intOrNull12import kotlinx.serialization.json.put13import kotlinx.serialization.json.putJsonArray14import kotlinx.serialization.json.putJsonObject1516// CASTV2: TLS on port 8009 carrying length-prefixed CastMessage protobufs with JSON payloads.1718internal const val DEFAULT_MEDIA_RECEIVER_APP_ID = "CC1AD845"19internal const val NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection"20internal const val NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat"21internal const val NS_RECEIVER = "urn:x-cast:com.google.cast.receiver"22internal const val NS_MEDIA = "urn:x-cast:com.google.cast.media"23internal const val SENDER_ID = "sender-0"24internal const val RECEIVER_ID = "receiver-0"2526/** Receivers reject messages above 64 KiB, so anything larger is a corrupt stream. */27private const val MAX_FRAME_BYTES = 64 * 10242829/** Byte stream to a receiver (TLS socket on port 8009). */30internal interface CastTransport {31    /** Writes one length-prefixed frame. */32    suspend fun write(frame: ByteArray)33    /** Returns the next non-empty chunk of the stream (frame boundaries are not preserved); throws at end of stream. */34    suspend fun read(): ByteArray35    fun close()36}3738/** STRING-payload CastMessage; device-auth BINARY payloads are not used by this client. */39internal data class CastMessage(40    val sourceId: String,41    val destinationId: String,42    val namespace: String,43    val payload: String,44)4546/** Encodes as a 4-byte big-endian length followed by the protobuf (fields 1..6 in order). */47internal fun CastMessage.toFrame(): ByteArray {48    val strings = arrayOf(sourceId, destinationId, namespace, payload).map { it.encodeToByteArray() }49    val bodySize = 4 + strings.sumOf { 1 + varintSize(it.size) + it.size }50    val out = ByteArray(4 + bodySize)51    var p = 052    fun byte(value: Int) { out[p++] = value.toByte() }53    fun string(field: Int, bytes: ByteArray) {54        byte(field shl 3 or 2)55        var n = bytes.size56        while (n >= 0x80) { byte((n and 0x7F) or 0x80); n = n ushr 7 }57        byte(n)58        bytes.copyInto(out, p)59        p += bytes.size60    }61    for (shift in intArrayOf(24, 16, 8, 0)) byte(bodySize ushr shift)62    byte(0x08); byte(0) // protocol_version = CASTV2_1_063    string(2, strings[0])64    string(3, strings[1])65    string(4, strings[2])66    byte(0x28); byte(0) // payload_type = STRING67    string(6, strings[3])68    return out69}7071private fun varintSize(value: Int): Int {72    var n = value ushr 773    var size = 174    while (n != 0) { n = n ushr 7; size++ }75    return size76}7778internal fun decodeCastMessage(bytes: ByteArray, start: Int = 0, end: Int = bytes.size): CastMessage {79    var p = start80    fun varint(): Long {81        var result = 0L82        var shift = 083        while (true) {84            check(p < end && shift < 64) { "Truncated Cast message" }85            val b = bytes[p++].toInt()86            result = result or ((b and 0x7F).toLong() shl shift)87            if ((b and 0x80) == 0) return result88            shift += 789        }90    }91    var source: String? = null92    var destination: String? = null93    var namespace: String? = null94    var payload = ""95    while (p < end) {96        val key = varint().toInt()97        when (key and 7) {98            0 -> varint()99            1 -> p += 8100            5 -> p += 4101            2 -> {102                val length = varint()103                check(length in 0..(end - p).toLong()) { "Truncated Cast message" }104                val valueEnd = p + length.toInt()105                when (key ushr 3) {106                    2 -> source = bytes.decodeToString(p, valueEnd)107                    3 -> destination = bytes.decodeToString(p, valueEnd)108                    4 -> namespace = bytes.decodeToString(p, valueEnd)109                    6 -> payload = bytes.decodeToString(p, valueEnd)110                }111                p = valueEnd112            }113            else -> error("Unsupported protobuf wire type ${key and 7}")114        }115        check(p <= end) { "Truncated Cast message" }116    }117    return CastMessage(118        checkNotNull(source) { "Cast message without source" },119        checkNotNull(destination) { "Cast message without destination" },120        checkNotNull(namespace) { "Cast message without namespace" },121        payload,122    )123}124125/** Reassembles frames from arbitrarily split transport chunks. */126internal class CastFrameReader(private val transport: CastTransport) {127    private var buffer = ByteArray(0)128129    suspend fun next(): CastMessage {130        while (true) {131            if (buffer.size >= 4) {132                val length = ((buffer[0].toInt() and 0xFF) shl 24) or ((buffer[1].toInt() and 0xFF) shl 16) or133                    ((buffer[2].toInt() and 0xFF) shl 8) or (buffer[3].toInt() and 0xFF)134                check(length in 0..MAX_FRAME_BYTES) { "Invalid Cast frame length $length" }135                if (buffer.size >= 4 + length) {136                    val message = decodeCastMessage(buffer, 4, 4 + length)137                    buffer = buffer.copyOfRange(4 + length, buffer.size)138                    return message139                }140            }141            buffer += transport.read()142        }143    }144}145146/** `{"type":type,"requestId":…,"mediaSessionId":…, …extra}`; ids are omitted when null. */147internal fun castJson(148    type: String,149    requestId: Int? = null,150    mediaSessionId: Int? = null,151    extra: JsonObjectBuilder.() -> Unit = {},152): String = buildJsonObject {153    put("type", type)154    requestId?.let { put("requestId", it) }155    mediaSessionId?.let { put("mediaSessionId", it) }156    extra()157}.toString()158159internal fun queueLoadJson(160    requestId: Int,161    items: List<CastMedia>,162    startIndex: Int,163    startPositionMs: Long,164    style: CastTextStyle,165    activeSubtitleIndex: Int?,166): String = castJson("QUEUE_LOAD", requestId) {167    put("items", queueItemsJson(items, style, startIndex, startPositionMs, activeSubtitleIndex))168    put("startIndex", startIndex)169    put("repeatMode", "REPEAT_OFF")170}171172/** QueueItem objects; the start item carries the resume position and active subtitle. */173internal fun queueItemsJson(174    items: List<CastMedia>,175    style: CastTextStyle,176    startIndex: Int = -1,177    startPositionMs: Long = 0,178    activeSubtitleIndex: Int? = null,179): JsonArray = buildJsonArray {180    items.forEachIndexed { index, media ->181        val start = index == startIndex182        // Track ids are 1-based subtitle indexes so the active index maps without a lookup table.183        val tracks = media.subtitles.withIndex().filter { isWebVtt(it.value.url) }184        add(buildJsonObject {185            putJsonObject("media") {186                put("contentId", media.url)187                put("contentUrl", media.url)188                put("streamType", "BUFFERED")189                put("contentType", media.contentType ?: guessContentType(media.url))190                putJsonObject("metadata") {191                    put("metadataType", 0)192                    put("title", media.title)193                    media.subtitle?.let { put("subtitle", it) }194                    media.posterUrl?.let { url -> putJsonArray("images") { add(buildJsonObject { put("url", url) }) } }195                }196                putJsonArray("tracks") {197                    tracks.forEach { (i, subtitle) ->198                        add(buildJsonObject {199                            put("trackId", i + 1)200                            put("type", "TEXT")201                            put("trackContentId", subtitle.url)202                            put("trackContentType", "text/vtt")203                            put("subtype", "SUBTITLES")204                            put("name", subtitle.label)205                            subtitle.language?.let { put("language", it) }206                        })207                    }208                }209                putJsonObject("textTrackStyle") {210                    put("foregroundColor", castColor(style.foregroundArgb))211                    put("edgeType", if ((style.edgeArgb ushr 24) == 0) "NONE" else "OUTLINE")212                    put("edgeColor", castColor(style.edgeArgb))213                    put("backgroundColor", castColor(style.backgroundArgb))214                    put("fontScale", style.fontScale)215                    put("fontStyle", when {216                        style.bold && style.italic -> "BOLD_ITALIC"217                        style.bold -> "BOLD"218                        style.italic -> "ITALIC"219                        else -> "NORMAL"220                    })221                }222            }223            put("autoplay", true)224            if (start) {225                put("startTime", startPositionMs / 1000.0)226                activeSubtitleIndex227                    ?.takeIf { active -> tracks.any { it.index == active } }228                    ?.let { putJsonArray("activeTrackIds") { add(it + 1) } }229            }230        })231    }232}233234/** The Default Media Receiver only renders WebVTT side-loaded text tracks. */235private fun isWebVtt(url: String) = url.substringBefore('#').substringBefore('?').endsWith(".vtt", ignoreCase = true)236237private fun guessContentType(url: String): String {238    val path = url.substringBefore('#').substringBefore('?').lowercase()239    return when {240        path.endsWith(".m3u8") -> "application/x-mpegURL"241        path.endsWith(".mpd") -> "application/dash+xml"242        path.endsWith(".webm") -> "video/webm"243        else -> "video/mp4"244    }245}246247/** ARGB int → Cast `#RRGGBBAA`. */248internal fun castColor(argb: Int): String =249    "#" + ((argb shl 8) or (argb ushr 24)).toUInt().toString(16).padStart(8, '0').uppercase()250251internal fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content252internal fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull253internal fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.doubleOrNull254255/**256 * Applies one MEDIA_STATUS `status[]` entry (null when the receiver has no media session) to the previous status.257 * [itemIds] are the receiver's queue item ids in queue order, so their positions index [CastStatus.queue].258 */259internal fun CastStatus.withMediaStatus(entry: JsonObject?, itemIds: List<Int>): CastStatus {260    if (entry == null) return copy(playing = false, buffering = false)261    val state = entry.string("playerState")262    val idleReason = entry.string("idleReason")263    val index = entry.int("currentItemId")?.let(itemIds::indexOf) ?: currentIndex264    val duration = (entry["media"] as? JsonObject)?.double("duration")265    val idle = state == "IDLE"266    return copy(267        playing = state == "PLAYING",268        buffering = state == "BUFFERING" || state == "LOADING",269        positionMs = entry.double("currentTime")?.let { (it * 1000).toLong() } ?: positionMs,270        durationMs = duration?.let { (it * 1000).toLong() } ?: if (index == currentIndex) durationMs else 0,271        currentIndex = index,272        finished = idle && idleReason == "FINISHED" && (index == -1 || index == queue.lastIndex),273        error = if (idle && idleReason == "ERROR") "Cast device could not play this media" else error.takeIf { idle },274    )275}276

Search chapters, reference and source filenames.