package eu.friedcutlet.yokan.services.media.player import io.github.kmpmpv.MpvRenderTarget import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.updateAndGet /** Surface callbacks expire by identity and generation; all native work and detachment are joined. */ internal class MpvNativeSurfaceBinding( private val resource: PlayerSurfaceResources.Resource, private val serialized: suspend (suspend () -> Unit, () -> Unit) -> Unit, ) { internal var attachTarget: suspend (MpvRenderTarget) -> Unit = {} internal var resizeTarget: suspend (Int, Int) -> Unit = { _, _ -> } internal var detachTarget: suspend () -> Unit = {} private val generation = MutableStateFlow(0L) fun attach(target: MpvRenderTarget, width: Int, height: Int): Boolean { val captured = generation.updateAndGet { it + 1L } return resource.launch { current -> serialized({ if (generation.value == captured) { attachTarget(target) current() if (generation.value == captured && width > 0 && height > 0) resizeTarget(width, height) } }, current) } } fun resize(width: Int, height: Int): Boolean { if (width <= 0 || height <= 0) return false val captured = generation.value return resource.launch { current -> serialized({ if (generation.value == captured) resizeTarget(width, height) }, current) } } fun detach(): Boolean { val captured = generation.updateAndGet { it + 1L } return resource.launch { current -> serialized({ if (generation.value == captured) detachTarget() }, current) } } fun retire() { generation.updateAndGet { it + 1L }; resource.retire() } suspend fun closeAndJoin() { retire(); resource.closeAndJoin() } }