MpvMediaPlayerController.kt
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvMediaPlayerController.kt
1package eu.friedcutlet.yokan.services.media.player23import kotlin.coroutines.CoroutineContext4import androidx.compose.runtime.getValue5import androidx.compose.runtime.mutableLongStateOf6import androidx.compose.runtime.mutableStateOf7import androidx.compose.runtime.setValue8import eu.friedcutlet.yokan.services.logging.AppLogger9import eu.friedcutlet.yokan.services.logging.redactUrlForLog10import eu.friedcutlet.yokan.util.PlatformLock11import io.github.kmpmpv.MpvConfiguration12import io.github.kmpmpv.MpvEvent13import io.github.kmpmpv.MpvFormat14import io.github.kmpmpv.MpvPlaybackStatus15import io.github.kmpmpv.MpvRenderTarget16import io.github.kmpmpv.MpvPlayer17import io.github.kmpmpv.MpvSoftwareFrame18import io.github.kmpmpv.MpvValue19import kotlinx.coroutines.CancellationException20import kotlinx.coroutines.CoroutineDispatcher21import kotlinx.coroutines.ensureActive22import kotlinx.coroutines.NonCancellable23import kotlinx.coroutines.Job24import kotlinx.coroutines.withContext25import kotlinx.coroutines.withTimeoutOrNull26import kotlinx.coroutines.CoroutineScope27import kotlinx.coroutines.CoroutineStart28import kotlinx.coroutines.Dispatchers29import kotlinx.coroutines.SupervisorJob30import kotlinx.coroutines.async31import kotlinx.coroutines.cancel32import kotlinx.coroutines.cancelAndJoin33import kotlinx.coroutines.currentCoroutineContext34import kotlinx.coroutines.coroutineScope35import kotlinx.coroutines.flow.Flow36import kotlinx.coroutines.flow.MutableSharedFlow37import kotlinx.coroutines.flow.asSharedFlow38import kotlinx.coroutines.flow.collect39import kotlinx.coroutines.flow.dropWhile40import kotlinx.coroutines.flow.first41import kotlinx.coroutines.launch42import kotlinx.coroutines.sync.Mutex43import kotlinx.coroutines.sync.withLock4445internal class MpvMediaPlayerController(46 internal val player: MpvPlayer,47 private val streamProxy: MediaStreamProxy,48 private val dispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1),49 private val loadTimeoutMs: Long = 30_000L,50) : MediaPlayerController {51 // Preserve UI command order (load -> speed -> play, for example) while the52 // library independently serializes access to the native mpv handle.53 private val ownerJob = SupervisorJob()54 private val commandJob = SupervisorJob(ownerJob)55 private val scope = CoroutineScope(commandJob + dispatcher)56 private val releaseRequested = kotlinx.coroutines.CompletableDeferred<Unit>()57 private val cleanup: kotlinx.coroutines.Deferred<Unit>58 private val retirementLock = Mutex()59 private val surfaces = PlayerSurfaceResources()60 private val surfaceMutex = Mutex()61 private var surfaceTarget: Any? = null62 private var nativeReleased = false63 private val lifecycleLock = PlatformLock()64 private var seekJob: Job? = null65 private val commandMutex = Mutex()66 private var cachedPositionMs by mutableLongStateOf(0L)67 private var cachedDurationMs by mutableLongStateOf(0L)68 private var cachedIsPlaying by mutableStateOf(false)69 private var cachedError by mutableStateOf<String?>(null)70 private val mutableMpvBridgeEvents = MutableSharedFlow<MpvBridgeEvent>(extraBufferCapacity = 32)71 private var releasedState = false72 private val released: Boolean get() = lifecycleLock.withLock { releasedState }7374 override val isMpvBackend: Boolean = true75 override val mpvBridgeEvents: Flow<MpvBridgeEvent> = mutableMpvBridgeEvents.asSharedFlow()7677 init {78 require(loadTimeoutMs > 0)79 // Cleanup is an owned sibling: it must join command/observer finalizers before native release.80 cleanup = CoroutineScope(ownerJob + dispatcher).async(start = CoroutineStart.UNDISPATCHED) {81 releaseRequested.await()82 commandJob.join()83 releaseNative()84 }85 scope.launch {86 var lastLoggedError: String? = null87 player.state.collect { state ->88 lifecycleLock.withLock {89 if (releasedState) return@withLock90 cachedPositionMs = (state.positionSeconds * 1000.0).toLong().coerceAtLeast(0L)91 cachedDurationMs = ((state.durationSeconds ?: 0.0) * 1000.0).toLong().coerceAtLeast(0L)92 cachedIsPlaying = state.status == MpvPlaybackStatus.Playing && !state.paused93 if (state.status == MpvPlaybackStatus.Error) cachedError = state.lastError ?: "mpv playback failed"94 }95 if (state.lastError != lastLoggedError) {96 state.lastError?.let { AppLogger.error("[player] mpv error $it") }97 lastLoggedError = state.lastError98 }99 }100 }101 scope.launch {102 MpvBridgePropertyNames.forEach { property ->103 kotlinx.coroutines.currentCoroutineContext().ensureActive()104 runPlayerOperation("observe $property") { player.observeProperty(property, MpvFormat.String) }105 }106 player.events.collect { event ->107 val changed = event as? MpvEvent.PropertyChanged ?: return@collect108 if (changed.name !in MpvBridgePropertyNames) return@collect109 val text = when (val value = changed.value) {110 is MpvValue.Text -> value.value111 is MpvValue.Integer -> value.value.toString()112 is MpvValue.Decimal -> value.value.toString()113 is MpvValue.Flag -> value.value.toString()114 MpvValue.None -> ""115 }116 if (text.isBlank()) return@collect117 kotlinx.coroutines.currentCoroutineContext().ensureActive()118 if (released) return@collect119 mutableMpvBridgeEvents.emit(MpvBridgeEvent(changed.name.removePrefix("user-data/"), text))120 runPlayerOperation("clear ${changed.name}") { player.setProperty(changed.name, MpvValue.Text("")) }121 }122 }123 }124125 override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) {126 if (released) return127 // mpv percent-decodes file:// URLs, so a local name containing e.g. "%20" would not open; give it the path.128 val playableUrl = if (headers.isNotEmpty()) {129 streamProxy.proxyUrl(url, headers)130 } else {131 url.removePrefix("file://")132 }133 val startPositionMs = initialPositionMs.coerceAtLeast(0L)134 lifecycleLock.withLock { cachedError = null }135 AppLogger.info(136 "[player] mpv load url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" +137 if (headers.isNotEmpty() && playableUrl != url) " proxy=${redactUrlForLog(playableUrl)}" else "",138 )139 launchCommand("load") {140 val completed = withTimeoutOrNull(loadTimeoutMs) {141 coroutineScope {142 val loadFinished = async(start = CoroutineStart.UNDISPATCHED) {143 player.events144 .dropWhile { event ->145 event !is MpvEvent.Lifecycle ||146 event.kind != io.github.kmpmpv.MpvLifecycleEvent.StartFile147 }148 .first { event ->149 event is MpvEvent.Lifecycle &&150 event.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded ||151 event is MpvEvent.EndFile152 }153 }154 player.pause()155 player.load(playableUrl)156 val terminalEvent = loadFinished.await()157 if (158 terminalEvent is MpvEvent.Lifecycle &&159 terminalEvent.kind == io.github.kmpmpv.MpvLifecycleEvent.FileLoaded &&160 startPositionMs > 0L161 ) {162 player.seek(startPositionMs / 1000.0)163 }164 }165 true166 }167 if (completed == null) {168 AppLogger.error("[player] mpv load timed out after ${loadTimeoutMs}ms")169 lifecycleLock.withLock { if (!releasedState) cachedError = "Timed out loading the stream" }170 }171 }172 }173174 override fun play() = launchCommand("play") { player.play() }175176 override fun pause() = launchCommand("pause") { player.pause() }177178 override fun seekTo(positionMs: Long) {179 lifecycleLock.withLock {180 if (releasedState) return@withLock181 // Scrubbing should not accumulate obsolete seek jobs behind an in-flight load.182 seekJob?.cancel()183 seekJob = scope.launch {184 commandMutex.withLock {185 kotlinx.coroutines.currentCoroutineContext().ensureActive()186 runPlayerOperation("seek") { player.seek(positionMs.coerceAtLeast(0L) / 1000.0) }187 }188 }189 }190 }191192 override fun setPlaybackSpeed(speed: Float) = launchCommand("speed") {193 player.setProperty("speed", MpvValue.Decimal(speed.coerceIn(0.25f, 4.0f).toDouble()))194 }195196 override fun executeMpvCommand(vararg arguments: String): Boolean {197 if (arguments.isEmpty()) return false198 return queueCommand(arguments.first()) { player.command(*arguments) }199 }200201 override val playbackError: String? get() = cachedError202203 /** External files need their track id, which mpv only exposes through `track-list`. */204 override fun selectSecondarySubtitle(file: String?, title: String?): Boolean = queueCommand("secondary-sid") {205 if (file.isNullOrBlank()) {206 player.setProperty("secondary-sid", MpvValue.Text("no"))207 } else {208 player.command("sub-add", file, "auto", title.orEmpty())209 val count = player.getLongProperty("track-list/count") ?: 0L210 val id = (count - 1 downTo 0L).firstNotNullOfOrNull { index ->211 player.getLongProperty("track-list/$index/id")?.takeIf {212 player.getStringProperty("track-list/$index/type") == "sub" &&213 player.getStringProperty("track-list/$index/external-filename") == file214 }215 }216 if (id != null) player.setProperty("secondary-sid", MpvValue.Integer(id))217 else AppLogger.warn("[player] secondary subtitle track was not added")218 }219 }220221 override suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean {222 val caller = requireNotNull(currentCoroutineContext()[Job])223 caller.ensureActive()224 if (arguments.isEmpty()) return false225 val work = lifecycleLock.withLock {226 if (releasedState) return@withLock null227 scope.async {228 commandMutex.withLock {229 currentCoroutineContext().ensureActive()230 caller.ensureActive()231 if (released) throw CancellationException("Player controller is retired.")232 try {233 player.command(*arguments)234 currentCoroutineContext().ensureActive()235 caller.ensureActive()236 true237 } catch (cancelled: CancellationException) {238 throw cancelled239 } catch (failure: Throwable) {240 AppLogger.error("[player] mpv ${arguments.first()} failed: ${failure.message.orEmpty()}")241 false242 }243 }244 }245 } ?: return false246 return try { work.await() }247 finally {248 // Native calls may finish blocking work or non-cancelable finalizers after cancellation.249 withContext(NonCancellable) { work.cancelAndJoin() }250 caller.ensureActive()251 }252 }253254 /** Own the complete UI render loop, including its pixel finalizer, before releasing libmpv. */255 internal suspend fun withSoftwareRendering(use: suspend (MpvSoftwareRenderer) -> Unit) {256 val callerContext = currentCoroutineContext()257 val caller = requireNotNull(callerContext[Job])258 caller.ensureActive()259 val work = lifecycleLock.withLock {260 if (releasedState) throw CancellationException("Player controller is retired.")261 // Keep canvas publication/cleanup on the captured UI context, with controller ownership.262 scope.async(callerContext.minusKey(Job)) {263 val renderJob = requireNotNull(currentCoroutineContext()[Job])264 fun ensureCurrent() {265 renderJob.ensureActive()266 caller.ensureActive()267 if (released) throw CancellationException("Player controller is retired.")268 }269 ensureCurrent()270 val renderer = MpvSoftwareRenderer { width, height ->271 ensureCurrent()272 // Escaped callbacks cannot start untracked frame work in another coroutine.273 if (currentCoroutineContext()[Job] !== renderJob) {274 throw CancellationException("Software renderer belongs to its render loop.")275 }276 try {277 withContext(dispatcher) {278 ensureCurrent()279 player.renderSoftwareFrame(width, height)280 }281 } finally {282 // A late frame or native failure must become cancellation before UI handling.283 ensureCurrent()284 }285 }286 use(renderer)287 }288 }289 try { work.await() }290 finally {291 withContext(NonCancellable) { work.cancelAndJoin() }292 caller.ensureActive()293 }294 }295296 internal fun bindNativeSurface(context: CoroutineContext, removeCallbacks: () -> Unit): MpvNativeSurfaceBinding? {297 val identity = Any()298 val resource = surfaces.register(context) {299 removeCallbacks()300 withContext(dispatcher) {301 surfaceMutex.withLock {302 if (surfaceTarget === identity) {303 player.detachRenderTarget()304 surfaceTarget = null305 }306 }307 }308 } ?: return null309 return MpvNativeSurfaceBinding(resource) { operation, current ->310 withContext(dispatcher) {311 surfaceMutex.withLock {312 current()313 operation()314 }315 }316 }.also { binding ->317 binding.attachTarget = { target ->318 // Record ownership before attachment so partial native failure still detaches on cleanup.319 surfaceTarget = identity320 player.attachRenderTarget(target)321 }322 binding.resizeTarget = { width, height ->323 if (surfaceTarget === identity) player.updateRenderTargetSize(width, height)324 }325 binding.detachTarget = {326 if (surfaceTarget === identity) {327 player.detachRenderTarget()328 surfaceTarget = null329 }330 }331 }332 }333334 override fun release() {335 lifecycleLock.withLock {336 if (releasedState) return@withLock337 releasedState = true338 cachedPositionMs = 0L339 cachedDurationMs = 0L340 cachedIsPlaying = false341 seekJob = null342 }343 surfaces.retire()344 scope.cancel()345 releaseRequested.complete(Unit)346 }347348 override suspend fun releaseAndJoin() {349 release()350 withContext(NonCancellable) {351 cleanup.join()352 releaseNative() // Retry failed immediate cleanup without reopening command admission.353 ownerJob.join()354 }355 }356357 private suspend fun releaseNative() = withContext(NonCancellable) {358 retirementLock.withLock {359 if (!nativeReleased) {360 surfaces.closeAndJoin()361 player.release()362 nativeReleased = true363 ownerJob.complete()364 }365 }366 }367368 override fun currentPositionMs(): Long = cachedPositionMs369370 override fun durationMs(): Long = cachedDurationMs371372 override fun isPlaying(): Boolean = cachedIsPlaying373374 private fun launchCommand(name: String, command: suspend () -> Unit) {375 queueCommand(name, command)376 }377378 private fun queueCommand(name: String, command: suspend () -> Unit): Boolean = lifecycleLock.withLock {379 if (releasedState) return@withLock false380 scope.launch {381 commandMutex.withLock command@{382 kotlinx.coroutines.currentCoroutineContext().ensureActive()383 if (released) return@command384 runPlayerOperation(name, command)385 }386 }387 true388 }389390 private suspend fun runPlayerOperation(name: String, command: suspend () -> Unit) {391 try {392 command()393 } catch (cancelled: CancellationException) {394 throw cancelled395 } catch (failure: Throwable) {396 AppLogger.error("[player] mpv $name failed: ${failure.message.orEmpty()}")397 }398 }399}400401/** This capability expires when its render loop, UI caller or controller finishes. */402internal class MpvSoftwareRenderer internal constructor(403 private val render: suspend (Int, Int) -> MpvSoftwareFrame,404) {405 suspend fun renderFrame(width: Int, height: Int): MpvSoftwareFrame = render(width, height)406}407408internal fun createMpvMediaPlayerController(409 configuration: MediaPlayerConfiguration,410 streamProxy: MediaStreamProxy,411 platformOptions: Map<String, String> = emptyMap(),412 libraryPath: String? = null,413): MediaPlayerController =414 MpvMediaPlayerController(415 MpvPlayer.create(416 MpvConfiguration(417 libraryPath = libraryPath,418 options = MpvConfiguration.DefaultOptions + configuration.mpvOptions() + platformOptions,419 eventPollTimeoutSeconds = 0.01,420 ),421 ),422 streamProxy,423 )424