package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlin.coroutines.CoroutineContext /** Controller-owned surface lifetimes, retained until cleanup succeeds. */ internal class PlayerSurfaceResources { private val lock = PlatformLock() private val closeMutex = Mutex() private var retired = false private val resources = mutableSetOf() fun register(context: CoroutineContext, cleanup: suspend () -> Unit): Resource? = lock.withLock { if (retired) return@withLock null Resource(context, cleanup).also { resources += it } } fun retire() { val captured = lock.withLock { retired = true; resources.toList() } captured.forEach { it.retire() } } suspend fun closeAndJoin() = withContext(NonCancellable) { retire() closeMutex.withLock { val captured = lock.withLock { resources.toList() } captured.forEach { it.closeAndJoin() } } } internal inner class Resource(private val context: CoroutineContext, private val finalize: suspend () -> Unit) { private val available = MutableStateFlow(true) private val owner = SupervisorJob() private val workJob = SupervisorJob(owner) private val scope = CoroutineScope(context.minusKey(Job) + workJob) private val signal = CompletableDeferred() private val cleanupMutex = Mutex() private var complete = false private val cleanup = CoroutineScope(context.minusKey(Job) + owner).async(start = CoroutineStart.UNDISPATCHED) { signal.await() workJob.join() finalizeOnce() } init { owner.invokeOnCompletion { lock.withLock { resources.remove(this@Resource) } } } val isAvailable: Boolean get() = available.value && workJob.isActive fun ensureOpen() { workJob.ensureActive() if (!available.value) throw CancellationException("Player surface is retired.") } fun retire() { available.value = false workJob.cancel() signal.complete(Unit) } suspend fun runOwned(action: suspend (() -> Unit) -> T): T { val callerContext = currentCoroutineContext() val caller = requireNotNull(callerContext[Job]) caller.ensureActive(); ensureOpen() val work = scope.async(callerContext.minusKey(Job)) { val job = requireNotNull(currentCoroutineContext()[Job]) val current = { job.ensureActive(); caller.ensureActive(); ensureOpen() } current() try { action(current).also { current() } } finally { current() } } return try { work.await() } finally { withContext(NonCancellable) { work.cancelAndJoin() } caller.ensureActive() } } fun launch(action: suspend (() -> Unit) -> Unit): Boolean { if (!isAvailable) return false scope.launch { val job = requireNotNull(currentCoroutineContext()[Job]) val current = { job.ensureActive(); ensureOpen() } try { current(); action(current); current() } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { current() AppLogger.error("[player] surface operation failed: ${failure.message.orEmpty()}") } } return true } suspend fun closeAndJoin() = withContext(NonCancellable) { retire() cleanup.join() finalizeOnce() owner.complete() owner.join() } private suspend fun finalizeOnce() = withContext(context.minusKey(Job) + NonCancellable) { cleanupMutex.withLock { if (!complete) { finalize() complete = true owner.complete() } } } } }