package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.media.AniSkipMarker import eu.friedcutlet.yokan.services.media.AniSkipService import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.updateAndGet import kotlinx.coroutines.flow.collect import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** Player auxiliary requests retain one session's files, AniSkip transport and stream proxy. */ class ProfilePlayerServices internal constructor( val profileId: ProfileId, private val files: LocalFileService, private val aniSkip: AniSkipService, private val proxy: MediaStreamProxy, ownerScope: CoroutineScope, private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default, private val controllerFactory: (MediaPlayerConfiguration, MediaStreamProxy) -> MediaPlayerController = ::createMediaPlayerController, private val isOwnerOpen: () -> Boolean = { true }, ) { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) private val job = SupervisorJob(ownerJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) private val proxyGate = PlatformLock() private val cacheRoot = files.cacheRoot.trimEnd('/') private val screenshotId = MutableStateFlow(0L) private val controllerCleanupLock = Mutex() private val failedControllers = mutableSetOf() internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen() /** Session-wide so the timer keeps running when the player moves to another episode. */ val sleepTimer = MutableStateFlow(null) private fun ensureOpen() { ownerJob.ensureActive() job.ensureActive() if (!isOwnerOpen()) throw CancellationException("Player services owner is retiring.") } internal fun reader(): Reader { ensureOpen() return Reader().also { if (!isAvailable) { it.retire(); ensureOpen() } } } internal suspend fun closeAndJoin() { job.cancel() withContext(NonCancellable) { job.join() retryControllerCleanup() // Synchronous proxy registration can come from a native player thread. // Drain that gate before the session releases its captured native proxy. withContext(fileDispatcher) { proxyGate.withLock { } } } } private suspend fun retryControllerCleanup() = withContext(NonCancellable) { controllerCleanupLock.withLock { failedControllers.toList().forEach { controller -> controller.releaseAndJoin() failedControllers.remove(controller) } } } internal inner class Reader { private val readerJob = SupervisorJob(job) private val readerScope = CoroutineScope(scope.coroutineContext + readerJob) val isAvailable: Boolean get() = readerJob.isActive && this@ProfilePlayerServices.isAvailable fun ensureOpen() { readerJob.ensureActive(); this@ProfilePlayerServices.ensureOpen() } fun retire() { readerJob.cancel() } suspend fun closeAndJoin() { retire() withContext(NonCancellable) { readerJob.join(); retryControllerCleanup() } } /** Retiring a reader's proxy handle never stops the session's shared proxy. */ val streamProxy: MediaStreamProxy = object : MediaStreamProxy { override fun proxyUrl(url: String, headers: Map): String = proxyGate.withLock { ensureOpen() try { proxy.proxyUrl(url, headers) } finally { ensureOpen() } } override fun stop() = retire() } fun configuration(settings: DbSettings): MediaPlayerConfiguration { ensureOpen() return MediaPlayerConfiguration.from(settings, cacheRoot).also { ensureOpen() } } private fun validate(configuration: MediaPlayerConfiguration) { ensureOpen() require(configuration.mpvConfigDirectory == "$cacheRoot/mpv") { "Player configuration belongs to another file root." } } private suspend fun runOwned(action: suspend (() -> Unit) -> T): T { val caller = requireNotNull(currentCoroutineContext()[Job]) try { return readerScope.runJoined(admit = { ensureOpen() }) { call -> val current = { call.ensureActive(); caller.ensureActive(); ensureOpen() } current() action(current).also { current() } } } finally { caller.ensureActive(); ensureOpen() } } suspend fun prepareConfiguration(configuration: MediaPlayerConfiguration) = runOwned { current -> validate(configuration) withContext(fileDispatcher) { prepareMpvConfiguration(configuration, files, current) } } /** The callback owns the controller's active lifetime; expiry joins allocation and native cleanup. */ suspend fun withController(configuration: MediaPlayerConfiguration, use: suspend (MediaPlayerController) -> Unit) = runOwned { current -> validate(configuration) retryControllerCleanup() var created: MediaPlayerController? = null try { withContext(fileDispatcher) { current() // Capture inside the dispatcher block: prompt cancellation must not lose a late allocation. created = controllerFactory(configuration, streamProxy) } current() use(checkNotNull(created)) } finally { created?.let { controller -> withContext(NonCancellable) { try { controller.releaseAndJoin() } catch (failure: Throwable) { controllerCleanupLock.withLock { failedControllers += controller } throw failure } } } } } suspend fun installCustomButtons( controller: MediaPlayerController, buttons: List, configuration: MediaPlayerConfiguration, ): Boolean = runOwned { current -> validate(configuration) withContext(fileDispatcher) { installMpvCustomButtons(controller, buttons, configuration, files, current) } } suspend fun markers(malId: Long, episode: Int, episodeLengthSeconds: Int): List = runOwned { current -> aniSkip.markers(malId, episode, episodeLengthSeconds).also { current() } } /** Collection belongs to this reader; delivery retains the caller's UI context. */ suspend fun collectBridgeEvents(controller: MediaPlayerController, onEvent: suspend (MpvBridgeEvent) -> Unit) { val deliveryContext = currentCoroutineContext().minusKey(Job) runOwned { current -> controller.mpvBridgeEvents.collect { event -> current() withContext(deliveryContext) { current(); onEvent(event) } } } } /** Publish the path only after native capture completes; expiry joins capture before removing its file. */ suspend fun requestScreenshot( controller: MediaPlayerController, mangaName: String, chapterName: String, includeSubtitles: Boolean = false, ): String? = runOwned { current -> withContext(fileDispatcher) { current() val timestamp = nowMillis() val fileName = "$mangaName-$chapterName" .replace(Regex("[^A-Za-z0-9._-]+"), "-").trim('-').take(80) .ifBlank { "screenshot" } val id = screenshotId.updateAndGet { it + 1 } val path = "$cacheRoot/screenshots/$fileName-$timestamp-$id.png" var completed = false try { files.writeBytes(path, ByteArray(0)) current() val captured = controller.takeMpvScreenshotAndJoin(path, includeSubtitles) current() completed = captured if (completed) path else null } finally { if (!completed) withContext(NonCancellable) { files.deleteRecursively(path) } } } } } }