package eu.friedcutlet.yokan.services.media.cast import java.io.EOFException import java.net.DatagramPacket import java.net.InetAddress import java.net.InetSocketAddress import java.net.MulticastSocket import java.net.SocketTimeoutException import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocket import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager import kotlin.time.Duration.Companion.seconds import kotlin.time.TimeMark import kotlin.time.TimeSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext actual fun createCastController(scope: CoroutineScope): CastController = NetworkCastController(scope, ::discoverCastDevices, ::openCastSocket) /** Holds whatever the platform needs to receive multicast while discovering; returns the release action. */ internal expect fun holdCastMulticastLock(): () -> Unit private val MDNS_GROUP: InetAddress = InetAddress.getByName("224.0.0.251") private const val MDNS_PORT = 5353 private val QUERY_INTERVAL = 3.seconds private val DEVICE_EXPIRY = 30.seconds /** * Re-sends the `_googlecast._tcp` PTR query every 3s from an ephemeral port, so responders answer by unicast * (RFC 6762 ยง6.7 legacy queries) and port 5353 never has to be shared with the OS responder. * Devices not heard from for 30s are dropped. */ internal fun discoverCastDevices(): Flow> = flow { val release = holdCastMulticastLock() try { MulticastSocket().use { socket -> socket.timeToLive = 255 socket.soTimeout = 1000 val query = castMdnsQuery() val buffer = ByteArray(9000) val packet = DatagramPacket(buffer, buffer.size) val seen = linkedMapOf>() var lastQuery: TimeMark? = null while (true) { currentCoroutineContext().ensureActive() if (lastQuery == null || lastQuery.elapsedNow() >= QUERY_INTERVAL) { socket.send(DatagramPacket(query, query.size, MDNS_GROUP, MDNS_PORT)) lastQuery = TimeSource.Monotonic.markNow() } try { packet.setLength(buffer.size) socket.receive(packet) val now = TimeSource.Monotonic.markNow() parseCastMdnsResponse(buffer.copyOf(packet.length), packet.address.hostAddress.orEmpty()) .forEach { seen[it.id] = it to now } } catch (_: SocketTimeoutException) { // Wake up to re-query, expire devices and observe cancellation. } seen.values.removeAll { it.second.elapsedNow() > DEVICE_EXPIRY } emit(seen.values.map { it.first }.sortedBy { it.name.lowercase() }) } } } finally { release() } }.flowOn(Dispatchers.IO).distinctUntilChanged() private class SocketCastTransport(private val socket: SSLSocket) : CastTransport { private val input = socket.inputStream private val output = socket.outputStream private val buffer = ByteArray(16 * 1024) override suspend fun write(frame: ByteArray) = withContext(Dispatchers.IO) { output.write(frame) output.flush() } // Blocking read; close() unblocks it with a SocketException. override suspend fun read(): ByteArray = withContext(Dispatchers.IO) { val count = input.read(buffer) if (count < 0) throw EOFException("Cast device closed the connection") buffer.copyOf(count) } override fun close() = socket.close() } private suspend fun openCastSocket(device: CastDevice): CastTransport = withContext(Dispatchers.IO) { val context = SSLContext.getInstance("TLS").apply { init(null, arrayOf(AcceptReceiverCertificate), null) } // A plain SSLSocket performs no hostname verification (no endpoint identification algorithm is set), // which is required: receivers are addressed by LAN IP, not by a name on their certificate. val socket = context.socketFactory.createSocket() as SSLSocket try { socket.connect(InetSocketAddress(device.host, device.port), CAST_CONNECT_TIMEOUT_MS.toInt()) socket.soTimeout = CAST_CONNECT_TIMEOUT_MS.toInt() socket.startHandshake() socket.soTimeout = 0 SocketCastTransport(socket) } catch (e: Throwable) { socket.close() throw e } } /** * Chromecast receivers present a self-signed per-device TLS certificate (authenticity is proven separately by * Google's device-auth challenge, which this client does not implement), so platform trust stores always reject * it. Installed only on the Cast socket's own SSLContext; no other connection is affected. */ private object AcceptReceiverCertificate : X509TrustManager { override fun checkClientTrusted(chain: Array?, authType: String?) = Unit override fun checkServerTrusted(chain: Array?, authType: String?) = Unit override fun getAcceptedIssuers(): Array = emptyArray() }