ProfilePlayerServices.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/ProfilePlayerServices.kt
1package eu.friedcutlet.yokan.services.media.player23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.database.DbCustomButton5import eu.friedcutlet.yokan.database.DbSettings6import eu.friedcutlet.yokan.services.files.LocalFileService7import eu.friedcutlet.yokan.services.media.AniSkipMarker8import eu.friedcutlet.yokan.services.media.AniSkipService9import eu.friedcutlet.yokan.services.runJoined10import eu.friedcutlet.yokan.util.PlatformLock11import eu.friedcutlet.yokan.util.nowMillis12import kotlinx.coroutines.CancellationException13import kotlinx.coroutines.CoroutineDispatcher14import kotlinx.coroutines.CoroutineScope15import kotlinx.coroutines.Dispatchers16import kotlinx.coroutines.Job17import kotlinx.coroutines.NonCancellable18import kotlinx.coroutines.SupervisorJob19import kotlinx.coroutines.currentCoroutineContext20import kotlinx.coroutines.ensureActive21import kotlinx.coroutines.flow.MutableStateFlow22import kotlinx.coroutines.flow.updateAndGet23import kotlinx.coroutines.flow.collect24import kotlinx.coroutines.withContext25import kotlinx.coroutines.sync.Mutex26import kotlinx.coroutines.sync.withLock2728/** Player auxiliary requests retain one session's files, AniSkip transport and stream proxy. */29class ProfilePlayerServices internal constructor(30 val profileId: ProfileId,31 private val files: LocalFileService,32 private val aniSkip: AniSkipService,33 private val proxy: MediaStreamProxy,34 ownerScope: CoroutineScope,35 private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default,36 private val controllerFactory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController,37 private val isOwnerOpen: () -> Boolean = { true },38) {39 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])40 private val job = SupervisorJob(ownerJob)41 private val scope = CoroutineScope(ownerScope.coroutineContext + job)42 private val proxyGate = PlatformLock()43 private val cacheRoot = files.cacheRoot.trimEnd('/')44 private val screenshotId = MutableStateFlow(0L)45 private val controllerCleanupLock = Mutex()46 private val failedControllers = mutableSetOf<MediaPlayerController>()47 internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen()48 /** Session-wide so the timer keeps running when the player moves to another episode. */49 val sleepTimer = MutableStateFlow<SleepTimer?>(null)5051 private fun ensureOpen() {52 ownerJob.ensureActive()53 job.ensureActive()54 if (!isOwnerOpen()) throw CancellationException("Player services owner is retiring.")55 }5657 internal fun reader(): Reader {58 ensureOpen()59 return Reader().also { if (!isAvailable) { it.retire(); ensureOpen() } }60 }6162 internal suspend fun closeAndJoin() {63 job.cancel()64 withContext(NonCancellable) {65 job.join()66 retryControllerCleanup()67 // Synchronous proxy registration can come from a native player thread.68 // Drain that gate before the session releases its captured native proxy.69 withContext(fileDispatcher) { proxyGate.withLock { } }70 }71 }7273 private suspend fun retryControllerCleanup() = withContext(NonCancellable) {74 controllerCleanupLock.withLock {75 failedControllers.toList().forEach { controller ->76 controller.releaseAndJoin()77 failedControllers.remove(controller)78 }79 }80 }8182 internal inner class Reader {83 private val readerJob = SupervisorJob(job)84 private val readerScope = CoroutineScope(scope.coroutineContext + readerJob)85 val isAvailable: Boolean get() = readerJob.isActive && this@ProfilePlayerServices.isAvailable8687 fun ensureOpen() { readerJob.ensureActive(); this@ProfilePlayerServices.ensureOpen() }88 fun retire() { readerJob.cancel() }89 suspend fun closeAndJoin() {90 retire()91 withContext(NonCancellable) { readerJob.join(); retryControllerCleanup() }92 }9394 /** Retiring a reader's proxy handle never stops the session's shared proxy. */95 val streamProxy: MediaStreamProxy = object : MediaStreamProxy {96 override fun proxyUrl(url: String, headers: Map<String, String>): String = proxyGate.withLock {97 ensureOpen()98 try { proxy.proxyUrl(url, headers) }99 finally { ensureOpen() }100 }101 override fun stop() = retire()102 }103104 fun configuration(settings: DbSettings): MediaPlayerConfiguration {105 ensureOpen()106 return MediaPlayerConfiguration.from(settings, cacheRoot).also { ensureOpen() }107 }108109 private fun validate(configuration: MediaPlayerConfiguration) {110 ensureOpen()111 require(configuration.mpvConfigDirectory == "$cacheRoot/mpv") { "Player configuration belongs to another file root." }112 }113114 private suspend fun <T> runOwned(action: suspend (() -> Unit) -> T): T {115 val caller = requireNotNull(currentCoroutineContext()[Job])116 try {117 return readerScope.runJoined(admit = { ensureOpen() }) { call ->118 val current = { call.ensureActive(); caller.ensureActive(); ensureOpen() }119 current()120 action(current).also { current() }121 }122 } finally {123 caller.ensureActive(); ensureOpen()124 }125 }126127 suspend fun prepareConfiguration(configuration: MediaPlayerConfiguration) = runOwned { current ->128 validate(configuration)129 withContext(fileDispatcher) { prepareMpvConfiguration(configuration, files, current) }130 }131132 /** The callback owns the controller's active lifetime; expiry joins allocation and native cleanup. */133 suspend fun withController(configuration: MediaPlayerConfiguration, use: suspend (MediaPlayerController) -> Unit) =134 runOwned { current ->135 validate(configuration)136 retryControllerCleanup()137 var created: MediaPlayerController? = null138 try {139 withContext(fileDispatcher) {140 current()141 // Capture inside the dispatcher block: prompt cancellation must not lose a late allocation.142 created = controllerFactory(configuration, streamProxy)143 }144 current()145 use(checkNotNull(created))146 } finally {147 created?.let { controller -> withContext(NonCancellable) {148 try { controller.releaseAndJoin() }149 catch (failure: Throwable) {150 controllerCleanupLock.withLock { failedControllers += controller }151 throw failure152 }153 } }154 }155 }156157 suspend fun installCustomButtons(158 controller: MediaPlayerController,159 buttons: List<DbCustomButton>,160 configuration: MediaPlayerConfiguration,161 ): Boolean = runOwned { current ->162 validate(configuration)163 withContext(fileDispatcher) { installMpvCustomButtons(controller, buttons, configuration, files, current) }164 }165166 suspend fun markers(malId: Long, episode: Int, episodeLengthSeconds: Int): List<AniSkipMarker> =167 runOwned { current ->168 aniSkip.markers(malId, episode, episodeLengthSeconds).also { current() }169 }170171 /** Collection belongs to this reader; delivery retains the caller's UI context. */172 suspend fun collectBridgeEvents(controller: MediaPlayerController, onEvent: suspend (MpvBridgeEvent) -> Unit) {173 val deliveryContext = currentCoroutineContext().minusKey(Job)174 runOwned { current ->175 controller.mpvBridgeEvents.collect { event ->176 current()177 withContext(deliveryContext) { current(); onEvent(event) }178 }179 }180 }181182 /** Publish the path only after native capture completes; expiry joins capture before removing its file. */183 suspend fun requestScreenshot(184 controller: MediaPlayerController,185 mangaName: String,186 chapterName: String,187 includeSubtitles: Boolean = false,188 ): String? =189 runOwned { current -> withContext(fileDispatcher) {190 current()191 val timestamp = nowMillis()192 val fileName = "$mangaName-$chapterName"193 .replace(Regex("[^A-Za-z0-9._-]+"), "-").trim('-').take(80)194 .ifBlank { "screenshot" }195 val id = screenshotId.updateAndGet { it + 1 }196 val path = "$cacheRoot/screenshots/$fileName-$timestamp-$id.png"197 var completed = false198 try {199 files.writeBytes(path, ByteArray(0))200 current()201 val captured = controller.takeMpvScreenshotAndJoin(path, includeSubtitles)202 current()203 completed = captured204 if (completed) path else null205 } finally {206 if (!completed) withContext(NonCancellable) { files.deleteRecursively(path) }207 }208 } }209 }210}211