package eu.friedcutlet.yokan.services.media.player import kotlin.coroutines.CoroutineContext import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.redactUrlForLog import eu.friedcutlet.yokan.util.PlatformLock import io.github.kmpmpv.MpvConfiguration import io.github.kmpmpv.MpvEvent import io.github.kmpmpv.MpvFormat import io.github.kmpmpv.MpvPlaybackStatus import io.github.kmpmpv.MpvRenderTarget import io.github.kmpmpv.MpvPlayer import io.github.kmpmpv.MpvSoftwareFrame import io.github.kmpmpv.MpvValue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ensureActive import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.Job import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.dropWhile import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock internal class MpvMediaPlayerController( internal val player: MpvPlayer, private val streamProxy: MediaStreamProxy, private val dispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1), private val loadTimeoutMs: Long = 30_000L, ) : MediaPlayerController { // Preserve UI command order (load -> speed -> play, for example) while the // library independently serializes access to the native mpv handle. private val ownerJob = SupervisorJob() private val commandJob = SupervisorJob(ownerJob) private val scope = CoroutineScope(commandJob + dispatcher) private val releaseRequested = kotlinx.coroutines.CompletableDeferred() private val cleanup: kotlinx.coroutines.Deferred private val retirementLock = Mutex() private val surfaces = PlayerSurfaceResources() private val surfaceMutex = Mutex() private var surfaceTarget: Any? = null private var nativeReleased = false private val lifecycleLock = PlatformLock() private var seekJob: Job? = null private val commandMutex = Mutex() private var cachedPositionMs by mutableLongStateOf(0L) private var cachedDurationMs by mutableLongStateOf(0L) private var cachedIsPlaying by mutableStateOf(false) private var cachedError by mutableStateOf(null) private val mutableMpvBridgeEvents = MutableSharedFlow(extraBufferCapacity = 32) private var releasedState = false private val released: Boolean get() = lifecycleLock.withLock { releasedState } override val isMpvBackend: Boolean = true override val mpvBridgeEvents: Flow = mutableMpvBridgeEvents.asSharedFlow() init { require(loadTimeoutMs > 0) // Cleanup is an owned sibling: it must join command/observer finalizers before native release. cleanup = CoroutineScope(ownerJob + dispatcher).async(start = CoroutineStart.UNDISPATCHED) { releaseRequested.await() commandJob.join() releaseNative() } scope.launch { var lastLoggedError: String? = null player.state.collect { state -> lifecycleLock.withLock { if (releasedState) return@withLock cachedPositionMs = (state.positionSeconds * 1000.0).toLong().coerceAtLeast(0L) cachedDurationMs = ((state.durationSeconds ?: 0.0) * 1000.0).toLong().coerceAtLeast(0L) cachedIsPlaying = state.status == MpvPlaybackStatus.Playing && !state.paused if (state.status == MpvPlaybackStatus.Error) cachedError = state.lastError ?: "mpv playback failed" } if (state.lastError != lastLoggedError) { state.lastError?.let { AppLogger.error("[player] mpv error $it") } lastLoggedError = state.lastError } } } scope.launch { MpvBridgePropertyNames.forEach { property -> kotlinx.coroutines.currentCoroutineContext().ensureActive() runPlayerOperation("observe $property") { player.observeProperty(property, MpvFormat.String) } } player.events.collect { event -> val changed = event as? MpvEvent.PropertyChanged ?: return@collect if (changed.name !in MpvBridgePropertyNames) return@collect val text = when (val value = changed.value) { is MpvValue.Text -> value.value is MpvValue.Integer -> value.value.toString() is MpvValue.Decimal -> value.value.toString() is MpvValue.Flag -> value.value.toString() MpvValue.None -> "" } if (text.isBlank()) return@collect kotlinx.coroutines.currentCoroutineContext().ensureActive() if (released) return@collect mutableMpvBridgeEvents.emit(MpvBridgeEvent(changed.name.removePrefix("user-data/"), text)) runPlayerOperation("clear ${changed.name}") { player.setProperty(changed.name, MpvValue.Text("")) } } } } override fun load(url: String, headers: Map, initialPositionMs: Long) { if (released) return // mpv percent-decodes file:// URLs, so a local name containing e.g. "%20" would not open; give it the path. val playableUrl = if (headers.isNotEmpty()) { streamProxy.proxyUrl(url, headers) } else { url.removePrefix("file://") } val startPositionMs = initialPositionMs.coerceAtLeast(0L) lifecycleLock.withLock { cachedError = null } AppLogger.info( "[player] mpv load url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" + if (headers.isNotEmpty() && playableUrl != url) " proxy=${redactUrlForLog(playableUrl)}" else "", ) launchCommand("load") { val completed = withTimeoutOrNull(loadTimeoutMs) { coroutineScope { val loadFinished = async(start = CoroutineStart.UNDISPATCHED) { player.events .dropWhile { event -> event !is MpvEvent.Lifecycle || event.kind != io.github.kmpmpv.MpvLifecycleEvent.StartFile } .first { event -> event is MpvEvent.Lifecycle && event.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded || event is MpvEvent.EndFile } } player.pause() player.load(playableUrl) val terminalEvent = loadFinished.await() if ( terminalEvent is MpvEvent.Lifecycle && terminalEvent.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded && startPositionMs > 0L ) { player.seek(startPositionMs / 1000.0) } } true } if (completed == null) { AppLogger.error("[player] mpv load timed out after ${loadTimeoutMs}ms") lifecycleLock.withLock { if (!releasedState) cachedError = "Timed out loading the stream" } } } } override fun play() = launchCommand("play") { player.play() } override fun pause() = launchCommand("pause") { player.pause() } override fun seekTo(positionMs: Long) { lifecycleLock.withLock { if (releasedState) return@withLock // Scrubbing should not accumulate obsolete seek jobs behind an in-flight load. seekJob?.cancel() seekJob = scope.launch { commandMutex.withLock { kotlinx.coroutines.currentCoroutineContext().ensureActive() runPlayerOperation("seek") { player.seek(positionMs.coerceAtLeast(0L) / 1000.0) } } } } } override fun setPlaybackSpeed(speed: Float) = launchCommand("speed") { player.setProperty("speed", MpvValue.Decimal(speed.coerceIn(0.25f, 4.0f).toDouble())) } override fun executeMpvCommand(vararg arguments: String): Boolean { if (arguments.isEmpty()) return false return queueCommand(arguments.first()) { player.command(*arguments) } } override val playbackError: String? get() = cachedError /** External files need their track id, which mpv only exposes through `track-list`. */ override fun selectSecondarySubtitle(file: String?, title: String?): Boolean = queueCommand("secondary-sid") { if (file.isNullOrBlank()) { player.setProperty("secondary-sid", MpvValue.Text("no")) } else { player.command("sub-add", file, "auto", title.orEmpty()) val count = player.getLongProperty("track-list/count") ?: 0L val id = (count - 1 downTo 0L).firstNotNullOfOrNull { index -> player.getLongProperty("track-list/$index/id")?.takeIf { player.getStringProperty("track-list/$index/type") == "sub" && player.getStringProperty("track-list/$index/external-filename") == file } } if (id != null) player.setProperty("secondary-sid", MpvValue.Integer(id)) else AppLogger.warn("[player] secondary subtitle track was not added") } } override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean { val caller = requireNotNull(currentCoroutineContext()[Job]) caller.ensureActive() if (arguments.isEmpty()) return false val work = lifecycleLock.withLock { if (releasedState) return@withLock null scope.async { commandMutex.withLock { currentCoroutineContext().ensureActive() caller.ensureActive() if (released) throw CancellationException("Player controller is retired.") try { player.command(*arguments) currentCoroutineContext().ensureActive() caller.ensureActive() true } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { AppLogger.error("[player] mpv ${arguments.first()} failed: ${failure.message.orEmpty()}") false } } } } ?: return false return try { work.await() } finally { // Native calls may finish blocking work or non-cancelable finalizers after cancellation. withContext(NonCancellable) { work.cancelAndJoin() } caller.ensureActive() } } /** Own the complete UI render loop, including its pixel finalizer, before releasing libmpv. */ internal suspend fun withSoftwareRendering(use: suspend (MpvSoftwareRenderer) -> Unit) { val callerContext = currentCoroutineContext() val caller = requireNotNull(callerContext[Job]) caller.ensureActive() val work = lifecycleLock.withLock { if (releasedState) throw CancellationException("Player controller is retired.") // Keep canvas publication/cleanup on the captured UI context, with controller ownership. scope.async(callerContext.minusKey(Job)) { val renderJob = requireNotNull(currentCoroutineContext()[Job]) fun ensureCurrent() { renderJob.ensureActive() caller.ensureActive() if (released) throw CancellationException("Player controller is retired.") } ensureCurrent() val renderer = MpvSoftwareRenderer { width, height -> ensureCurrent() // Escaped callbacks cannot start untracked frame work in another coroutine. if (currentCoroutineContext()[Job] !== renderJob) { throw CancellationException("Software renderer belongs to its render loop.") } try { withContext(dispatcher) { ensureCurrent() player.renderSoftwareFrame(width, height) } } finally { // A late frame or native failure must become cancellation before UI handling. ensureCurrent() } } use(renderer) } } try { work.await() } finally { withContext(NonCancellable) { work.cancelAndJoin() } caller.ensureActive() } } internal fun bindNativeSurface(context: CoroutineContext, removeCallbacks: () -> Unit): MpvNativeSurfaceBinding? { val identity = Any() val resource = surfaces.register(context) { removeCallbacks() withContext(dispatcher) { surfaceMutex.withLock { if (surfaceTarget === identity) { player.detachRenderTarget() surfaceTarget = null } } } } ?: return null return MpvNativeSurfaceBinding(resource) { operation, current -> withContext(dispatcher) { surfaceMutex.withLock { current() operation() } } }.also { binding -> binding.attachTarget = { target -> // Record ownership before attachment so partial native failure still detaches on cleanup. surfaceTarget = identity player.attachRenderTarget(target) } binding.resizeTarget = { width, height -> if (surfaceTarget === identity) player.updateRenderTargetSize(width, height) } binding.detachTarget = { if (surfaceTarget === identity) { player.detachRenderTarget() surfaceTarget = null } } } } override fun release() { lifecycleLock.withLock { if (releasedState) return@withLock releasedState = true cachedPositionMs = 0L cachedDurationMs = 0L cachedIsPlaying = false seekJob = null } surfaces.retire() scope.cancel() releaseRequested.complete(Unit) } override suspend fun releaseAndJoin() { release() withContext(NonCancellable) { cleanup.join() releaseNative() // Retry failed immediate cleanup without reopening command admission. ownerJob.join() } } private suspend fun releaseNative() = withContext(NonCancellable) { retirementLock.withLock { if (!nativeReleased) { surfaces.closeAndJoin() player.release() nativeReleased = true ownerJob.complete() } } } override fun currentPositionMs(): Long = cachedPositionMs override fun durationMs(): Long = cachedDurationMs override fun isPlaying(): Boolean = cachedIsPlaying private fun launchCommand(name: String, command: suspend () -> Unit) { queueCommand(name, command) } private fun queueCommand(name: String, command: suspend () -> Unit): Boolean = lifecycleLock.withLock { if (releasedState) return@withLock false scope.launch { commandMutex.withLock command@{ kotlinx.coroutines.currentCoroutineContext().ensureActive() if (released) return@command runPlayerOperation(name, command) } } true } private suspend fun runPlayerOperation(name: String, command: suspend () -> Unit) { try { command() } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { AppLogger.error("[player] mpv $name failed: ${failure.message.orEmpty()}") } } } /** This capability expires when its render loop, UI caller or controller finishes. */ internal class MpvSoftwareRenderer internal constructor( private val render: suspend (Int, Int) -> MpvSoftwareFrame, ) { suspend fun renderFrame(width: Int, height: Int): MpvSoftwareFrame = render(width, height) } internal fun createMpvMediaPlayerController( configuration: MediaPlayerConfiguration, streamProxy: MediaStreamProxy, platformOptions: Map = emptyMap(), libraryPath: String? = null, ): MediaPlayerController = MpvMediaPlayerController( MpvPlayer.create( MpvConfiguration( libraryPath = libraryPath, options = MpvConfiguration.DefaultOptions + configuration.mpvOptions() + platformOptions, eventPollTimeoutSeconds = 0.01, ), ), streamProxy, )