package eu.friedcutlet.yokan.services.media.cast import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject // CASTV2: TLS on port 8009 carrying length-prefixed CastMessage protobufs with JSON payloads. internal const val DEFAULT_MEDIA_RECEIVER_APP_ID = "CC1AD845" internal const val NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection" internal const val NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat" internal const val NS_RECEIVER = "urn:x-cast:com.google.cast.receiver" internal const val NS_MEDIA = "urn:x-cast:com.google.cast.media" internal const val SENDER_ID = "sender-0" internal const val RECEIVER_ID = "receiver-0" /** Receivers reject messages above 64 KiB, so anything larger is a corrupt stream. */ private const val MAX_FRAME_BYTES = 64 * 1024 /** Byte stream to a receiver (TLS socket on port 8009). */ internal interface CastTransport { /** Writes one length-prefixed frame. */ suspend fun write(frame: ByteArray) /** Returns the next non-empty chunk of the stream (frame boundaries are not preserved); throws at end of stream. */ suspend fun read(): ByteArray fun close() } /** STRING-payload CastMessage; device-auth BINARY payloads are not used by this client. */ internal data class CastMessage( val sourceId: String, val destinationId: String, val namespace: String, val payload: String, ) /** Encodes as a 4-byte big-endian length followed by the protobuf (fields 1..6 in order). */ internal fun CastMessage.toFrame(): ByteArray { val strings = arrayOf(sourceId, destinationId, namespace, payload).map { it.encodeToByteArray() } val bodySize = 4 + strings.sumOf { 1 + varintSize(it.size) + it.size } val out = ByteArray(4 + bodySize) var p = 0 fun byte(value: Int) { out[p++] = value.toByte() } fun string(field: Int, bytes: ByteArray) { byte(field shl 3 or 2) var n = bytes.size while (n >= 0x80) { byte((n and 0x7F) or 0x80); n = n ushr 7 } byte(n) bytes.copyInto(out, p) p += bytes.size } for (shift in intArrayOf(24, 16, 8, 0)) byte(bodySize ushr shift) byte(0x08); byte(0) // protocol_version = CASTV2_1_0 string(2, strings[0]) string(3, strings[1]) string(4, strings[2]) byte(0x28); byte(0) // payload_type = STRING string(6, strings[3]) return out } private fun varintSize(value: Int): Int { var n = value ushr 7 var size = 1 while (n != 0) { n = n ushr 7; size++ } return size } internal fun decodeCastMessage(bytes: ByteArray, start: Int = 0, end: Int = bytes.size): CastMessage { var p = start fun varint(): Long { var result = 0L var shift = 0 while (true) { check(p < end && shift < 64) { "Truncated Cast message" } val b = bytes[p++].toInt() result = result or ((b and 0x7F).toLong() shl shift) if ((b and 0x80) == 0) return result shift += 7 } } var source: String? = null var destination: String? = null var namespace: String? = null var payload = "" while (p < end) { val key = varint().toInt() when (key and 7) { 0 -> varint() 1 -> p += 8 5 -> p += 4 2 -> { val length = varint() check(length in 0..(end - p).toLong()) { "Truncated Cast message" } val valueEnd = p + length.toInt() when (key ushr 3) { 2 -> source = bytes.decodeToString(p, valueEnd) 3 -> destination = bytes.decodeToString(p, valueEnd) 4 -> namespace = bytes.decodeToString(p, valueEnd) 6 -> payload = bytes.decodeToString(p, valueEnd) } p = valueEnd } else -> error("Unsupported protobuf wire type ${key and 7}") } check(p <= end) { "Truncated Cast message" } } return CastMessage( checkNotNull(source) { "Cast message without source" }, checkNotNull(destination) { "Cast message without destination" }, checkNotNull(namespace) { "Cast message without namespace" }, payload, ) } /** Reassembles frames from arbitrarily split transport chunks. */ internal class CastFrameReader(private val transport: CastTransport) { private var buffer = ByteArray(0) suspend fun next(): CastMessage { while (true) { if (buffer.size >= 4) { val length = ((buffer[0].toInt() and 0xFF) shl 24) or ((buffer[1].toInt() and 0xFF) shl 16) or ((buffer[2].toInt() and 0xFF) shl 8) or (buffer[3].toInt() and 0xFF) check(length in 0..MAX_FRAME_BYTES) { "Invalid Cast frame length $length" } if (buffer.size >= 4 + length) { val message = decodeCastMessage(buffer, 4, 4 + length) buffer = buffer.copyOfRange(4 + length, buffer.size) return message } } buffer += transport.read() } } } /** `{"type":type,"requestId":…,"mediaSessionId":…, …extra}`; ids are omitted when null. */ internal fun castJson( type: String, requestId: Int? = null, mediaSessionId: Int? = null, extra: JsonObjectBuilder.() -> Unit = {}, ): String = buildJsonObject { put("type", type) requestId?.let { put("requestId", it) } mediaSessionId?.let { put("mediaSessionId", it) } extra() }.toString() internal fun queueLoadJson( requestId: Int, items: List, startIndex: Int, startPositionMs: Long, style: CastTextStyle, activeSubtitleIndex: Int?, ): String = castJson("QUEUE_LOAD", requestId) { put("items", queueItemsJson(items, style, startIndex, startPositionMs, activeSubtitleIndex)) put("startIndex", startIndex) put("repeatMode", "REPEAT_OFF") } /** QueueItem objects; the start item carries the resume position and active subtitle. */ internal fun queueItemsJson( items: List, style: CastTextStyle, startIndex: Int = -1, startPositionMs: Long = 0, activeSubtitleIndex: Int? = null, ): JsonArray = buildJsonArray { items.forEachIndexed { index, media -> val start = index == startIndex // Track ids are 1-based subtitle indexes so the active index maps without a lookup table. val tracks = media.subtitles.withIndex().filter { isWebVtt(it.value.url) } add(buildJsonObject { putJsonObject("media") { put("contentId", media.url) put("contentUrl", media.url) put("streamType", "BUFFERED") put("contentType", media.contentType ?: guessContentType(media.url)) putJsonObject("metadata") { put("metadataType", 0) put("title", media.title) media.subtitle?.let { put("subtitle", it) } media.posterUrl?.let { url -> putJsonArray("images") { add(buildJsonObject { put("url", url) }) } } } putJsonArray("tracks") { tracks.forEach { (i, subtitle) -> add(buildJsonObject { put("trackId", i + 1) put("type", "TEXT") put("trackContentId", subtitle.url) put("trackContentType", "text/vtt") put("subtype", "SUBTITLES") put("name", subtitle.label) subtitle.language?.let { put("language", it) } }) } } putJsonObject("textTrackStyle") { put("foregroundColor", castColor(style.foregroundArgb)) put("edgeType", if ((style.edgeArgb ushr 24) == 0) "NONE" else "OUTLINE") put("edgeColor", castColor(style.edgeArgb)) put("backgroundColor", castColor(style.backgroundArgb)) put("fontScale", style.fontScale) put("fontStyle", when { style.bold && style.italic -> "BOLD_ITALIC" style.bold -> "BOLD" style.italic -> "ITALIC" else -> "NORMAL" }) } } put("autoplay", true) if (start) { put("startTime", startPositionMs / 1000.0) activeSubtitleIndex ?.takeIf { active -> tracks.any { it.index == active } } ?.let { putJsonArray("activeTrackIds") { add(it + 1) } } } }) } } /** The Default Media Receiver only renders WebVTT side-loaded text tracks. */ private fun isWebVtt(url: String) = url.substringBefore('#').substringBefore('?').endsWith(".vtt", ignoreCase = true) private fun guessContentType(url: String): String { val path = url.substringBefore('#').substringBefore('?').lowercase() return when { path.endsWith(".m3u8") -> "application/x-mpegURL" path.endsWith(".mpd") -> "application/dash+xml" path.endsWith(".webm") -> "video/webm" else -> "video/mp4" } } /** ARGB int → Cast `#RRGGBBAA`. */ internal fun castColor(argb: Int): String = "#" + ((argb shl 8) or (argb ushr 24)).toUInt().toString(16).padStart(8, '0').uppercase() internal fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content internal fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull internal fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.doubleOrNull /** * Applies one MEDIA_STATUS `status[]` entry (null when the receiver has no media session) to the previous status. * [itemIds] are the receiver's queue item ids in queue order, so their positions index [CastStatus.queue]. */ internal fun CastStatus.withMediaStatus(entry: JsonObject?, itemIds: List): CastStatus { if (entry == null) return copy(playing = false, buffering = false) val state = entry.string("playerState") val idleReason = entry.string("idleReason") val index = entry.int("currentItemId")?.let(itemIds::indexOf) ?: currentIndex val duration = (entry["media"] as? JsonObject)?.double("duration") val idle = state == "IDLE" return copy( playing = state == "PLAYING", buffering = state == "BUFFERING" || state == "LOADING", positionMs = entry.double("currentTime")?.let { (it * 1000).toLong() } ?: positionMs, durationMs = duration?.let { (it * 1000).toLong() } ?: if (index == currentIndex) durationMs else 0, currentIndex = index, finished = idle && idleReason == "FINISHED" && (index == -1 || index == queue.lastIndex), error = if (idle && idleReason == "ERROR") "Cast device could not play this media" else error.takeIf { idle }, ) }