PlayerSurfaceResources.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/PlayerSurfaceResources.kt
1package eu.friedcutlet.yokan.services.media.player23import eu.friedcutlet.yokan.services.logging.AppLogger4import eu.friedcutlet.yokan.util.PlatformLock5import kotlinx.coroutines.*6import kotlinx.coroutines.flow.MutableStateFlow7import kotlinx.coroutines.sync.Mutex8import kotlinx.coroutines.sync.withLock9import kotlin.coroutines.CoroutineContext1011/** Controller-owned surface lifetimes, retained until cleanup succeeds. */12internal class PlayerSurfaceResources {13 private val lock = PlatformLock()14 private val closeMutex = Mutex()15 private var retired = false16 private val resources = mutableSetOf<Resource>()17 fun register(context: CoroutineContext, cleanup: suspend () -> Unit): Resource? = lock.withLock {18 if (retired) return@withLock null19 Resource(context, cleanup).also { resources += it }20 }21 fun retire() {22 val captured = lock.withLock { retired = true; resources.toList() }23 captured.forEach { it.retire() }24 }25 suspend fun closeAndJoin() = withContext(NonCancellable) {26 retire()27 closeMutex.withLock {28 val captured = lock.withLock { resources.toList() }29 captured.forEach { it.closeAndJoin() }30 }31 }32 internal inner class Resource(private val context: CoroutineContext, private val finalize: suspend () -> Unit) {33 private val available = MutableStateFlow(true)34 private val owner = SupervisorJob()35 private val workJob = SupervisorJob(owner)36 private val scope = CoroutineScope(context.minusKey(Job) + workJob)37 private val signal = CompletableDeferred<Unit>()38 private val cleanupMutex = Mutex()39 private var complete = false40 private val cleanup = CoroutineScope(context.minusKey(Job) + owner).async(start = CoroutineStart.UNDISPATCHED) {41 signal.await()42 workJob.join()43 finalizeOnce()44 }45 init { owner.invokeOnCompletion { lock.withLock { resources.remove(this@Resource) } } }46 val isAvailable: Boolean get() = available.value && workJob.isActive47 fun ensureOpen() {48 workJob.ensureActive()49 if (!available.value) throw CancellationException("Player surface is retired.")50 }51 fun retire() {52 available.value = false53 workJob.cancel()54 signal.complete(Unit)55 }56 suspend fun <T> runOwned(action: suspend (() -> Unit) -> T): T {57 val callerContext = currentCoroutineContext()58 val caller = requireNotNull(callerContext[Job])59 caller.ensureActive(); ensureOpen()60 val work = scope.async(callerContext.minusKey(Job)) {61 val job = requireNotNull(currentCoroutineContext()[Job])62 val current = { job.ensureActive(); caller.ensureActive(); ensureOpen() }63 current()64 try { action(current).also { current() } }65 finally { current() }66 }67 return try { work.await() }68 finally {69 withContext(NonCancellable) { work.cancelAndJoin() }70 caller.ensureActive()71 }72 }73 fun launch(action: suspend (() -> Unit) -> Unit): Boolean {74 if (!isAvailable) return false75 scope.launch {76 val job = requireNotNull(currentCoroutineContext()[Job])77 val current = { job.ensureActive(); ensureOpen() }78 try { current(); action(current); current() }79 catch (cancelled: CancellationException) { throw cancelled }80 catch (failure: Throwable) {81 current()82 AppLogger.error("[player] surface operation failed: ${failure.message.orEmpty()}")83 }84 }85 return true86 }87 suspend fun closeAndJoin() = withContext(NonCancellable) {88 retire()89 cleanup.join()90 finalizeOnce()91 owner.complete()92 owner.join()93 }94 private suspend fun finalizeOnce() = withContext(context.minusKey(Job) + NonCancellable) {95 cleanupMutex.withLock {96 if (!complete) {97 finalize()98 complete = true99 owner.complete()100 }101 }102 }103 }104}105