NetworkCastController.kt
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/cast/NetworkCastController.kt
1package eu.friedcutlet.yokan.services.media.cast23import eu.friedcutlet.yokan.services.logging.AppLogger4import kotlinx.coroutines.CancellationException5import kotlinx.coroutines.CoroutineScope6import kotlinx.coroutines.Dispatchers7import kotlinx.coroutines.ExperimentalCoroutinesApi8import kotlinx.coroutines.Job9import kotlinx.coroutines.SupervisorJob10import kotlinx.coroutines.cancel11import kotlinx.coroutines.flow.Flow12import kotlinx.coroutines.flow.MutableStateFlow13import kotlinx.coroutines.flow.SharingStarted14import kotlinx.coroutines.flow.StateFlow15import kotlinx.coroutines.flow.asStateFlow16import kotlinx.coroutines.flow.catch17import kotlinx.coroutines.flow.flatMapLatest18import kotlinx.coroutines.flow.flowOf19import kotlinx.coroutines.flow.stateIn20import kotlinx.coroutines.launch21import kotlinx.coroutines.withContext2223/**24 * Native CASTV2 sender shared by Android, desktop and iOS: platform code supplies only device discovery and the25 * TLS byte stream. Android deliberately uses this instead of the proprietary Google Cast SDK, so there is no26 * Play Services dependency and one code path to maintain.27 */28@OptIn(ExperimentalCoroutinesApi::class)29internal class NetworkCastController(30 parentScope: CoroutineScope,31 private val discover: () -> Flow<List<CastDevice>>,32 private val openTransport: suspend (CastDevice) -> CastTransport,33) : CastController {34 // CastSession is single-threaded by contract; every session call is confined here.35 private val dispatcher = Dispatchers.Default.limitedParallelism(1)36 private val scope = CoroutineScope(parentScope.coroutineContext + SupervisorJob(parentScope.coroutineContext[Job]) + dispatcher)37 private val session = MutableStateFlow<CastSession?>(null)38 private val _devices = MutableStateFlow(emptyList<CastDevice>())39 private var discoveryJob: Job? = null4041 override val isSupported: StateFlow<Boolean> = MutableStateFlow(true).asStateFlow()42 override val usesSystemPicker = false43 override val devices: StateFlow<List<CastDevice>> = _devices.asStateFlow()44 override val status: StateFlow<CastStatus?> =45 session.flatMapLatest { it?.status ?: flowOf(null) }.stateIn(scope, SharingStarted.Eagerly, null)4647 override fun startDiscovery() {48 scope.launch {49 if (discoveryJob?.isActive == true) return@launch50 discoveryJob = scope.launch {51 discover()52 .catch { AppLogger.warn("Cast discovery failed: ${it.message}") }53 .collect { _devices.value = it }54 }55 }56 }5758 override fun stopDiscovery() {59 scope.launch {60 discoveryJob?.cancel()61 discoveryJob = null62 }63 }6465 override suspend fun connect(device: CastDevice?) = withContext(dispatcher) {66 requireNotNull(device) { "Choose a Cast device" }67 session.value?.disconnect()68 session.value = null69 val next = CastSession(device, openTransport(device), scope)70 next.connect()71 session.value = next72 }7374 override suspend fun loadQueue(75 items: List<CastMedia>,76 startIndex: Int,77 startPositionMs: Long,78 style: CastTextStyle,79 activeSubtitleIndex: Int?,80 ) = withContext(dispatcher) {81 connected().loadQueue(items, startIndex, startPositionMs, style, activeSubtitleIndex)82 }8384 override suspend fun append(items: List<CastMedia>) = withContext(dispatcher) { connected().append(items) }8586 override fun play() = command { it.play() }87 override fun pause() = command { it.pause() }88 override fun seekTo(positionMs: Long) = command { it.seekTo(positionMs) }89 override fun next() = command { it.next() }90 override fun previous() = command { it.previous() }91 override fun jumpTo(index: Int) = command { it.jumpTo(index) }9293 override suspend fun disconnect() = withContext(dispatcher) {94 session.value?.disconnect()95 session.value = null96 }9798 override fun close() {99 session.value?.close()100 session.value = null101 scope.cancel()102 }103104 private fun connected() = checkNotNull(session.value) { "No Cast session" }105106 /** Commands run in call order on the confined dispatcher; failures already land in [CastStatus.error]. */107 private fun command(block: suspend (CastSession) -> Unit) {108 scope.launch {109 val current = session.value ?: return@launch110 try {111 block(current)112 } catch (e: CancellationException) {113 throw e114 } catch (e: Throwable) {115 AppLogger.warn("Cast command failed: ${e.message}")116 }117 }118 }119}120