DefaultMpvPlayer.kt
vendor/kmp-mpv/kmp-mpv/src/commonMain/kotlin/io/github/kmpmpv/DefaultMpvPlayer.kt
1package io.github.kmpmpv23import io.github.kmpmpv.internal.MpvEngine4import io.github.kmpmpv.internal.NativeEventId5import io.github.kmpmpv.internal.RawMpvEvent6import kotlinx.coroutines.CancellationException7import kotlinx.coroutines.CoroutineDispatcher8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.Job11import kotlinx.coroutines.NonCancellable12import kotlinx.coroutines.SupervisorJob13import kotlinx.coroutines.cancel14import kotlinx.coroutines.cancelAndJoin15import kotlinx.coroutines.channels.BufferOverflow16import kotlinx.coroutines.delay17import kotlinx.coroutines.ensureActive18import kotlinx.coroutines.currentCoroutineContext19import kotlinx.coroutines.flow.MutableSharedFlow20import kotlinx.coroutines.flow.MutableStateFlow21import kotlinx.coroutines.flow.SharedFlow22import kotlinx.coroutines.flow.StateFlow23import kotlinx.coroutines.flow.asSharedFlow24import kotlinx.coroutines.flow.asStateFlow25import kotlinx.coroutines.launch26import kotlinx.coroutines.sync.Mutex27import kotlinx.coroutines.sync.withLock28import kotlinx.coroutines.withContext29import kotlinx.coroutines.yield3031internal class DefaultMpvPlayer(32 private val engine: MpvEngine,33 private val configuration: MpvConfiguration,34 private val dispatcher: CoroutineDispatcher = Dispatchers.Default,35) : MpvPlayer {36 private val engineMutex = Mutex()37 private val lifecycleMutex = Mutex()38 private val scope = CoroutineScope(SupervisorJob() + dispatcher)39 private val mutableEvents = MutableSharedFlow<MpvEvent>(40 extraBufferCapacity = configuration.eventBufferCapacity,41 onBufferOverflow = BufferOverflow.DROP_OLDEST,42 )43 private val mutableState = MutableStateFlow(MpvPlaybackState())44 private var released = false45 private var engineClosed = false46 private var nextObservationId = USER_OBSERVATION_START4748 override val events: SharedFlow<MpvEvent> = mutableEvents.asSharedFlow()49 override val state: StateFlow<MpvPlaybackState> = mutableState.asStateFlow()5051 private val eventJob: Job5253 init {54 try {55 INTERNAL_PROPERTIES.forEachIndexed { index, property ->56 val result = engine.observeProperty(57 INTERNAL_OBSERVATION_START + index,58 property.first,59 property.second,60 )61 checkError(result, "observe property '${property.first}'")62 }63 eventJob = scope.launch { eventLoop() }64 } catch (failure: Throwable) {65 scope.cancel()66 engine.close()67 throw failure68 }69 }7071 override suspend fun load(path: String, mode: MpvLoadMode) {72 require(path.isNotBlank()) { "path must not be blank" }73 command("loadfile", path, mode.commandValue)74 }7576 override suspend fun play() {77 setProperty("pause", MpvValue.Flag(false))78 }7980 override suspend fun pause() {81 setProperty("pause", MpvValue.Flag(true))82 }8384 override suspend fun togglePause() {85 command("cycle", "pause")86 }8788 override suspend fun stop() {89 command("stop")90 }9192 override suspend fun seek(seconds: Double, mode: MpvSeekMode) {93 require(seconds.isFinite()) { "seconds must be finite" }94 command("seek", seconds.toString(), mode.commandValue)95 }9697 override suspend fun command(vararg arguments: String) {98 require(arguments.isNotEmpty()) { "an mpv command needs at least one argument" }99 require(arguments.none(String::isEmpty)) { "mpv command arguments must not be empty" }100 withEngine { checkError(it.command(arguments.toList()), "execute '${arguments.first()}'") }101 }102103 override suspend fun getProperty(name: String, format: MpvFormat): MpvValue {104 requirePropertyName(name)105 require(format != MpvFormat.None) { "None is not a readable property format" }106 return withEngine { native ->107 val result = native.getProperty(name, format)108 checkError(result.errorCode, "read property '$name'")109 result.value ?: MpvValue.None110 }111 }112113 override suspend fun setProperty(name: String, value: MpvValue) {114 requirePropertyName(name)115 require(value != MpvValue.None) { "None cannot be written as a property value" }116 withEngine { checkError(it.setProperty(name, value), "write property '$name'") }117 }118119 override suspend fun getStringProperty(name: String): String? =120 (getProperty(name, MpvFormat.String) as? MpvValue.Text)?.value121122 override suspend fun getBooleanProperty(name: String): Boolean? =123 (getProperty(name, MpvFormat.Flag) as? MpvValue.Flag)?.value124125 override suspend fun getLongProperty(name: String): Long? =126 (getProperty(name, MpvFormat.Int64) as? MpvValue.Integer)?.value127128 override suspend fun getDoubleProperty(name: String): Double? =129 (getProperty(name, MpvFormat.Double) as? MpvValue.Decimal)?.value130131 override suspend fun observeProperty(name: String, format: MpvFormat): Long {132 requirePropertyName(name)133 require(format != MpvFormat.None) { "None is not an observable property format" }134 return withEngine { native ->135 val id = nextObservationId++136 checkError(native.observeProperty(id, name, format), "observe property '$name'")137 id138 }139 }140141 override suspend fun unobserveProperty(observationId: Long) {142 require(observationId >= USER_OBSERVATION_START) { "cannot remove an internal observation" }143 withEngine { checkError(it.unobserveProperty(observationId), "remove observation $observationId") }144 }145146 override suspend fun requestLogMessages(level: MpvLogLevel) {147 withEngine { checkError(it.requestLogMessages(level.mpvName), "request log messages") }148 }149150 override suspend fun attachRenderTarget(target: MpvRenderTarget) {151 withEngine { checkError(it.attachRenderTarget(target), "attach render target") }152 }153154 override suspend fun detachRenderTarget() {155 withEngine { checkError(it.detachRenderTarget(), "detach render target") }156 }157158 override suspend fun updateRenderTargetSize(width: Int, height: Int) {159 require(width > 0 && height > 0) { "render target dimensions must be positive" }160 withEngine { checkError(it.updateRenderTargetSize(width, height), "update render target size") }161 }162163 override suspend fun renderSoftwareFrame(width: Int, height: Int): MpvSoftwareFrame {164 require(width > 0 && height > 0) { "software frame dimensions must be positive" }165 val stride = (width.toLong() * 4 + 63) / 64 * 64166 require(stride <= configuration.maxSoftwareFrameBytes / height.toLong()) {167 "software frame exceeds maxSoftwareFrameBytes (${configuration.maxSoftwareFrameBytes})"168 }169 return withEngine { native ->170 val result = native.renderSoftwareFrame(width, height)171 checkError(result.errorCode, "render a software frame")172 val frame = checkNotNull(result.value) { "libmpv returned no software frame" }173 MpvSoftwareFrame(width, height, frame.strideBytes, frame.pixels)174 }175 }176177 override suspend fun release(): Unit = withContext(dispatcher + NonCancellable) {178 lifecycleMutex.withLock {179 if (engineClosed) return@withLock180 released = true181 try {182 engine.wakeup()183 } finally {184 try {185 eventJob.cancelAndJoin()186 engineMutex.withLock { engine.close(); engineClosed = true }187 } finally {188 mutableState.value = MpvPlaybackState(status = MpvPlaybackStatus.Released)189 scope.cancel()190 }191 }192 }193 }194195 private suspend fun <T> withEngine(block: (MpvEngine) -> T): T = withContext(dispatcher) {196 lifecycleMutex.withLock {197 ensureNotReleased()198 engine.wakeup()199 engineMutex.withLock { block(engine) }200 }201 }202203 private suspend fun eventLoop() {204 try {205 var eventsSinceYield = 0206 while (true) {207 currentCoroutineContext().ensureActive()208 val event = engineMutex.withLock {209 engine.waitEvent(configuration.eventPollTimeoutSeconds)210 }211 if (event.eventId == NativeEventId.NONE) {212 delay(1)213 continue214 }215 handleEvent(event)216 if (event.eventId == NativeEventId.SHUTDOWN) break217 if (++eventsSinceYield == 32) {218 eventsSinceYield = 0219 yield()220 }221 }222 } catch (cancelled: CancellationException) {223 throw cancelled224 } catch (failure: Throwable) {225 val message = failure.message ?: failure::class.simpleName ?: "mpv event loop failed"226 mutableState.value = mutableState.value.copy(227 status = MpvPlaybackStatus.Error,228 lastError = message,229 )230 mutableEvents.tryEmit(231 MpvEvent.LogMessage("kmp-mpv", MpvLogLevel.Error, message),232 )233 }234 }235236 private fun handleEvent(raw: RawMpvEvent) {237 val event = raw.toPublicEvent(engine::errorString)238 if (event != null) mutableEvents.tryEmit(event)239240 when (raw.eventId) {241 NativeEventId.SHUTDOWN -> updateStatus(MpvPlaybackStatus.Released)242 NativeEventId.START_FILE -> updateStatus(MpvPlaybackStatus.Loading)243 NativeEventId.FILE_LOADED -> {244 mutableState.value = mutableState.value.copy(245 status = if (mutableState.value.paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing,246 lastError = null,247 )248 }249 NativeEventId.SEEK -> mutableState.value = mutableState.value.copy(seeking = true)250 NativeEventId.PLAYBACK_RESTART -> {251 mutableState.value = mutableState.value.copy(252 seeking = false,253 status = if (mutableState.value.paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing,254 )255 }256 NativeEventId.END_FILE -> {257 val failed = raw.endReason == 4 || raw.endError < 0258 mutableState.value = mutableState.value.copy(259 status = if (failed) MpvPlaybackStatus.Error else MpvPlaybackStatus.Ended,260 seeking = false,261 lastError = raw.endError.takeIf { it < 0 }?.let(engine::errorString),262 )263 }264 NativeEventId.PROPERTY_CHANGE -> updateStateFromProperty(raw.propertyName, raw.propertyValue)265 }266 }267268 private fun updateStateFromProperty(name: String?, value: MpvValue) {269 val current = mutableState.value270 mutableState.value = when (name) {271 "pause" -> {272 val paused = (value as? MpvValue.Flag)?.value ?: current.paused273 current.copy(274 paused = paused,275 status = when (current.status) {276 MpvPlaybackStatus.Playing,277 MpvPlaybackStatus.Paused,278 -> if (paused) MpvPlaybackStatus.Paused else MpvPlaybackStatus.Playing279 else -> current.status280 },281 )282 }283 "path" -> current.copy(mediaPath = (value as? MpvValue.Text)?.value)284 "media-title" -> current.copy(mediaTitle = (value as? MpvValue.Text)?.value)285 "time-pos" -> current.copy(positionSeconds = (value as? MpvValue.Decimal)?.value ?: 0.0)286 "duration" -> current.copy(durationSeconds = (value as? MpvValue.Decimal)?.value)287 "seekable" -> current.copy(seekable = (value as? MpvValue.Flag)?.value ?: false)288 "volume" -> current.copy(volume = (value as? MpvValue.Decimal)?.value ?: current.volume)289 "mute" -> current.copy(muted = (value as? MpvValue.Flag)?.value ?: current.muted)290 "speed" -> current.copy(speed = (value as? MpvValue.Decimal)?.value ?: current.speed)291 "video-params/w" -> current.copy(videoWidth = (value as? MpvValue.Integer)?.value)292 "video-params/h" -> current.copy(videoHeight = (value as? MpvValue.Integer)?.value)293 else -> current294 }295 }296297 private fun updateStatus(status: MpvPlaybackStatus) {298 mutableState.value = mutableState.value.copy(status = status)299 }300301 private fun ensureNotReleased() {302 check(!released) { "MpvPlayer has been released" }303 }304305 private fun checkError(errorCode: Int, action: String) {306 if (errorCode < 0) throw MpvException(errorCode, "Failed to $action: ${engine.errorString(errorCode)}")307 }308309 private fun requirePropertyName(name: String) {310 require(name.isNotBlank()) { "property name must not be blank" }311 }312313 private companion object {314 const val INTERNAL_OBSERVATION_START = 1L315 const val USER_OBSERVATION_START = 10_000L316317 val INTERNAL_PROPERTIES = listOf(318 "pause" to MpvFormat.Flag,319 "path" to MpvFormat.String,320 "media-title" to MpvFormat.String,321 "time-pos" to MpvFormat.Double,322 "duration" to MpvFormat.Double,323 "seekable" to MpvFormat.Flag,324 "volume" to MpvFormat.Double,325 "mute" to MpvFormat.Flag,326 "speed" to MpvFormat.Double,327 "video-params/w" to MpvFormat.Int64,328 "video-params/h" to MpvFormat.Int64,329 )330 }331}332333private fun RawMpvEvent.toPublicEvent(errorString: (Int) -> String): MpvEvent? = when (eventId) {334 NativeEventId.NONE -> null335 NativeEventId.SHUTDOWN -> MpvEvent.Lifecycle(MpvLifecycleEvent.Shutdown)336 NativeEventId.START_FILE -> MpvEvent.Lifecycle(MpvLifecycleEvent.StartFile)337 NativeEventId.FILE_LOADED -> MpvEvent.Lifecycle(MpvLifecycleEvent.FileLoaded)338 NativeEventId.VIDEO_RECONFIG -> MpvEvent.Lifecycle(MpvLifecycleEvent.VideoReconfigured)339 NativeEventId.AUDIO_RECONFIG -> MpvEvent.Lifecycle(MpvLifecycleEvent.AudioReconfigured)340 NativeEventId.SEEK -> MpvEvent.Lifecycle(MpvLifecycleEvent.Seek)341 NativeEventId.PLAYBACK_RESTART -> MpvEvent.Lifecycle(MpvLifecycleEvent.PlaybackRestart)342 NativeEventId.PROPERTY_CHANGE -> MpvEvent.PropertyChanged(343 replyUserData,344 propertyName.orEmpty(),345 propertyValue,346 )347 NativeEventId.LOG_MESSAGE -> MpvEvent.LogMessage(348 logPrefix.orEmpty(),349 logLevel.toLogLevel(),350 logText.orEmpty(),351 )352 NativeEventId.END_FILE -> MpvEvent.EndFile(353 reason = when (endReason) {354 0 -> MpvEndFileReason.Eof355 2 -> MpvEndFileReason.Stop356 3 -> MpvEndFileReason.Quit357 4 -> MpvEndFileReason.Error358 5 -> MpvEndFileReason.Redirect359 else -> MpvEndFileReason.Unknown360 },361 errorCode = endError,362 errorMessage = endError.takeIf { it < 0 }?.let(errorString),363 )364 NativeEventId.CLIENT_MESSAGE -> MpvEvent.ClientMessage(clientArguments)365 NativeEventId.GET_PROPERTY_REPLY -> reply(MpvReplyKind.GetProperty, errorString)366 NativeEventId.SET_PROPERTY_REPLY -> reply(MpvReplyKind.SetProperty, errorString)367 NativeEventId.COMMAND_REPLY -> reply(MpvReplyKind.Command, errorString)368 NativeEventId.QUEUE_OVERFLOW -> MpvEvent.QueueOverflow369 else -> MpvEvent.Unknown(eventId)370}371372private fun RawMpvEvent.reply(kind: MpvReplyKind, errorString: (Int) -> String): MpvEvent.Reply =373 MpvEvent.Reply(374 kind = kind,375 requestId = replyUserData,376 errorCode = errorCode,377 errorMessage = errorCode.takeIf { it < 0 }?.let(errorString),378 )379380private fun Int.toLogLevel(): MpvLogLevel = when (this) {381 10 -> MpvLogLevel.Fatal382 20 -> MpvLogLevel.Error383 30 -> MpvLogLevel.Warn384 40 -> MpvLogLevel.Info385 50 -> MpvLogLevel.Verbose386 60 -> MpvLogLevel.Debug387 70 -> MpvLogLevel.Trace388 else -> MpvLogLevel.None389}390