MediaPlayer.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MediaPlayer.kt
1package eu.friedcutlet.yokan.services.media.player23import androidx.compose.runtime.getValue4import androidx.compose.runtime.mutableFloatStateOf5import androidx.compose.runtime.mutableIntStateOf6import androidx.compose.runtime.mutableLongStateOf7import androidx.compose.runtime.mutableStateOf8import androidx.compose.runtime.setValue9import eu.friedcutlet.yokan.database.DbAudioChannel10import eu.friedcutlet.yokan.database.DbDebandingType11import eu.friedcutlet.yokan.database.DbSettings12import eu.friedcutlet.yokan.services.logging.AppLogger13import eu.friedcutlet.yokan.services.logging.redactUrlForLog14import kotlinx.coroutines.delay15import kotlinx.coroutines.flow.Flow16import kotlinx.coroutines.flow.emptyFlow17import kotlinx.coroutines.withTimeoutOrNull18import io.github.kdroidfilter.composemediaplayer.SubtitleTrack1920data class MediaPlayerConfiguration(21 val useLibass: Boolean = true,22 val useMpvConfig: Boolean = true,23 val mpvConfigDirectory: String = "",24 val hwdecMode: String = "auto",25 val enableHardwareAcceleration: Boolean? = null,26 val enableGpuNext: Boolean = false,27 val debandingType: DbDebandingType = DbDebandingType.None,28 val useYuv420p: Boolean = false,29 val audioPreferredLanguages: String? = null,30 val enableAudioPitchCorrection: Boolean? = null,31 val audioChannels: DbAudioChannel = DbAudioChannel.AutoSafe,32 val volumeBoostCap: Int? = null,33 /** Embedded-track subtitle priority (mpv `slang`); external tracks use [preferredSubtitle]. */34 val subtitleLanguages: List<String> = emptyList(),35) {36 companion object {37 fun from(settings: DbSettings, cacheRoot: String): MediaPlayerConfiguration =38 MediaPlayerConfiguration(39 useLibass = settings.useLibass,40 useMpvConfig = settings.useMpvConfig,41 mpvConfigDirectory = "${cacheRoot.trimEnd('/')}/mpv",42 hwdecMode = settings.hwdecMode,43 enableHardwareAcceleration = settings.enableHardwareAcceleration,44 enableGpuNext = settings.enableGpuNext,45 debandingType = settings.debandingType,46 useYuv420p = settings.useYuv420p,47 audioPreferredLanguages = settings.audioPreferredLanguages,48 enableAudioPitchCorrection = settings.enableAudioPitchCorrection,49 audioChannels = settings.audioChannels,50 volumeBoostCap = settings.volumeBoostCap,51 subtitleLanguages = settings.features.player.subtitleLanguages,52 )53 }5455 internal fun mpvOptions(): Map<String, String> = buildMap {56 put("keep-open", "yes")57 put("load-stats-overlay", "yes")58 put("sub-ass", if (useLibass) "yes" else "no")59 put("hwdec", if (enableHardwareAcceleration == false) "no" else hwdecMode.ifBlank { "auto" })60 put("audio-pitch-correction", if (enableAudioPitchCorrection != false) "yes" else "no")61 put("volume-max", ((volumeBoostCap ?: 30).coerceIn(0, 200) + 100).toString())6263 val videoFilters = buildList {64 if (useYuv420p) add("format=yuv420p")65 if (debandingType == DbDebandingType.Cpu) add("gradfun=radius=12")66 }67 if (videoFilters.isNotEmpty()) put("vf", videoFilters.joinToString(","))68 if (debandingType == DbDebandingType.Gpu) put("deband", "yes")69 audioPreferredLanguages?.trim()?.takeIf(String::isNotEmpty)?.let { put("alang", it) }70 if (subtitleLanguages.isNotEmpty()) put("slang", subtitleLanguages.joinToString(","))71 if (audioChannels == DbAudioChannel.ReverseStereo) {72 put("af", audioChannels.mpvName)73 } else {74 put("audio-channels", audioChannels.mpvName)75 }76 if (useMpvConfig && mpvConfigDirectory.isNotBlank()) {77 put("config", "yes")78 put("config-dir", mpvConfigDirectory)79 } else {80 put("config", "no")81 }82 }83}8485data class MpvBridgeEvent(val name: String, val value: String)8687enum class MpvVideoFit(val label: String) {88 Contain("Fit"),89 Cover("Crop"),90 Original("100%"),91}9293/**94 * Media engine handle. Each platform's actual factory picks the best95 * backend. libmpv is primary on Android, iOS devices, macOS and Windows. The96 * previous ComposeMediaPlayer path remains as a fallback for iOS simulators97 * and Linux machines where the distribution libmpv package is unavailable.98 */99interface MediaPlayerController {100 val isMpvBackend: Boolean get() = false101 val mpvBridgeEvents: Flow<MpvBridgeEvent> get() = emptyFlow()102103 fun load(url: String, headers: Map<String, String> = emptyMap(), initialPositionMs: Long = 0L)104 fun play()105 fun pause()106 fun seekTo(positionMs: Long)107 fun setPlaybackSpeed(speed: Float)108 /** Queues a raw libmpv command. Returns false on the compatibility backend. */109 fun executeMpvCommand(vararg arguments: String): Boolean = false110 /** Await the native command call and join cleanup on expiry. Script/background work has its own lifetime. */111 suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean = false112 fun release()113 /** Await controller work, surface finalizers and native release. */114 suspend fun releaseAndJoin() { release() }115116 /** Current position in milliseconds (best-effort; 0 if not started or unsupported). */117 fun currentPositionMs(): Long118 /** Total duration in milliseconds; 0 if unknown. */119 fun durationMs(): Long120 /** True when the engine is currently playing. */121 fun isPlaying(): Boolean122123 /** The current stream's playback failure (observable Compose state); null while healthy. */124 val playbackError: String? get() = null125126 /** Selects an external subtitle file as the primary track; null disables subtitles. */127 fun selectSubtitleTrack(file: String?, title: String? = null): Boolean =128 if (file.isNullOrBlank()) {129 executeMpvCommand("set", "sid", "no")130 } else {131 executeMpvCommand("sub-add", file, "select", title.orEmpty(), title.orEmpty())132 }133134 /** Shows a second external subtitle file alongside the primary one; null hides it. */135 fun selectSecondarySubtitle(file: String?, title: String? = null): Boolean = false136137 fun setSecondarySubtitleDelay(milliseconds: Int): Boolean =138 executeMpvCommand("set", "secondary-sub-delay", (milliseconds / 1000.0).toString())139140 /** Output volume in percent, 0..100. */141 fun setVolume(percent: Int): Boolean = executeMpvCommand("set", "volume", percent.coerceIn(0, 100).toString())142}143144145internal enum class PlaybackAction {146 Play,147 Pause,148 Stop,149}150151internal data class MediaRequest(152 val id: Long,153 val url: String,154 val originalUrl: String,155 val headers: Map<String, String>,156 val proxied: Boolean,157 val initialPositionMs: Long,158)159160internal data class PlaybackCommand(161 val id: Long,162 val action: PlaybackAction,163)164165internal data class SeekCommand(166 val id: Long,167 val positionMs: Long,168)169internal class PendingSeekState {170 private var requestedGeneration = 0L171 private var dispatchedGeneration = 0L172 private var positionMs = 0L173174 fun request(positionMs: Long) {175 requestedGeneration += 1L176 this.positionMs = positionMs.coerceAtLeast(0L)177 }178179 fun pendingPositionMs(): Long? =180 positionMs.takeIf { requestedGeneration > dispatchedGeneration }181182 fun markDispatched() {183 dispatchedGeneration = requestedGeneration184 }185186 fun reset() {187 dispatchedGeneration = requestedGeneration188 positionMs = 0L189 }190}191192193internal class InitialPlaybackState {194 var autoplayRequested: Boolean = false195 private set196 var mediaPrepared by mutableStateOf(false)197 private set198199 fun beginPreparation() {200 autoplayRequested = false201 mediaPrepared = false202 }203204 fun requestPlay() {205 autoplayRequested = true206 }207208 fun requestPause() {209 autoplayRequested = false210 }211212 fun finishPreparation(): Boolean {213 mediaPrepared = true214 return autoplayRequested215 }216217 fun reset() {218 autoplayRequested = false219 mediaPrepared = false220 }221}222223internal suspend fun awaitInitialMediaDuration(224 durationMs: () -> Long?,225 isUsable: () -> Boolean,226 hasError: () -> Boolean,227 requireDuration: Boolean,228 readinessGraceMs: Long = 250L,229 timeoutMs: Long = 5_000L,230 pollIntervalMs: Long = 16L,231): Long? = withTimeoutOrNull<Long>(timeoutMs) {232 var resolvedDurationMs = 0L233 var waiting = true234 while (waiting) {235 val knownDurationMs = durationMs()?.takeIf { it > 0L }236 when {237 knownDurationMs != null -> {238 resolvedDurationMs = knownDurationMs239 waiting = false240 }241 hasError() -> waiting = false242 !requireDuration && isUsable() -> {243 delay(readinessGraceMs)244 val settledDurationMs = durationMs()?.takeIf { it > 0L }245 if (settledDurationMs != null) {246 resolvedDurationMs = settledDurationMs247 waiting = false248 } else if (hasError() || (!requireDuration && isUsable())) {249 waiting = false250 }251 }252 else -> delay(pollIntervalMs)253 }254 }255 resolvedDurationMs256}?.takeIf { it > 0L }257258internal fun parsePlaybackPositionMs(positionText: String): Long {259 val parts = positionText.trim().split(':')260 if (parts.size !in 2..3) return 0L261 val values = parts.map { it.toLongOrNull() ?: return 0L }262 val hours = if (values.size == 3) values[0] else 0L263 val minutes = values[values.size - 2]264 val seconds = values.last()265 if (hours < 0L || minutes !in 0L..59L || seconds !in 0L..59L) return 0L266 return ((hours * 60L + minutes) * 60L + seconds) * 1000L267}268269internal class ComposeMediaPlayerController(270 private val streamProxy: MediaStreamProxy,271) : MediaPlayerController {272 internal val surfaces = PlayerSurfaceResources()273 internal var mediaRequest by mutableStateOf<MediaRequest?>(null)274 private set275 internal var playbackCommand by mutableStateOf<PlaybackCommand?>(null)276 private set277 internal var seekCommand by mutableStateOf<SeekCommand?>(null)278 private set279 internal var speed by mutableStateOf(1.0f)280 private set281 internal var released by mutableStateOf(false)282 private set283 /** compose-mediaplayer draws these with its own cue layer; the secondary one is offset by [secondaryDelayMs]. */284 internal var subtitle by mutableStateOf<SubtitleTrack?>(null)285 private set286 internal var secondarySubtitle by mutableStateOf<SubtitleTrack?>(null)287 private set288 internal var secondaryDelayMs by mutableIntStateOf(0)289 private set290 internal var volume by mutableFloatStateOf(1f)291 private set292 internal var error by mutableStateOf<String?>(null)293 override val playbackError: String? get() = error294 private val initialPlaybackState = InitialPlaybackState()295 internal val autoplayRequested: Boolean get() = initialPlaybackState.autoplayRequested296 internal val mediaPrepared: Boolean get() = initialPlaybackState.mediaPrepared297 internal fun finishMediaPreparation(): Boolean = !released && initialPlaybackState.finishPreparation()298 private val pendingSeekState = PendingSeekState()299 internal fun pendingSeekPositionMs(): Long? = pendingSeekState.pendingPositionMs()300 internal fun markPendingSeekDispatched() = pendingSeekState.markDispatched()301302 private var nextCommandId = 0L303 // Observable Compose state so reads in @Composable callers subscribe and304 // recompose as playback progresses. The Surface composable writes to these305 // every time the underlying VideoPlayerState ticks.306 private var cachedPositionMs by mutableLongStateOf(0L)307 private var cachedDurationMs by mutableLongStateOf(0L)308 private var cachedIsPlaying by mutableStateOf(false)309 // kdroidfilter compose-mediaplayer 0.7.11 has two unit bugs in its Linux310 // backend that don't match its KDoc:311 // • `metadata.duration` is raw GStreamer nanoseconds, not milliseconds312 // • `sliderPos` ranges 0..1000, not 0..1313 // Android/iOS backends do follow the docs. Auto-detect once per session314 // by sniffing the first sane value we see, then reuse for `seekTo` math.315 internal var durationScaleToMs: Long = 1L316 private set317 internal var sliderScale: Float = 1f318 private set319320 override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) {321 if (released) return322 initialPlaybackState.beginPreparation()323 pendingSeekState.reset()324 val playableUrl = if (headers.isNotEmpty()) streamProxy.proxyUrl(url, headers) else url325 val proxied = playableUrl != url326 val startPositionMs = initialPositionMs.coerceAtLeast(0L)327 AppLogger.info(328 "[player] load request url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" +329 if (proxied) " proxy=${redactUrlForLog(playableUrl)}" else "",330 )331 error = null332 subtitle = null333 secondarySubtitle = null334 mediaRequest = MediaRequest(nextId(), playableUrl, url, headers, proxied, startPositionMs)335 }336337 override fun selectSubtitleTrack(file: String?, title: String?): Boolean {338 if (released) return false339 subtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) }340 return true341 }342343 override fun selectSecondarySubtitle(file: String?, title: String?): Boolean {344 if (released) return false345 secondarySubtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) }346 return true347 }348349 override fun setSecondarySubtitleDelay(milliseconds: Int): Boolean {350 if (released) return false351 secondaryDelayMs = milliseconds352 return true353 }354355 override fun setVolume(percent: Int): Boolean {356 if (released) return false357 volume = percent.coerceIn(0, 100) / 100f358 return true359 }360361 override fun play() {362 if (released) return363 initialPlaybackState.requestPlay()364 AppLogger.info("[player] play request")365 playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Play)366 }367368 override fun pause() {369 if (released) return370 initialPlaybackState.requestPause()371 AppLogger.info("[player] pause request")372 playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Pause)373 }374375 override fun seekTo(positionMs: Long) {376 if (released) return377 val targetMs = positionMs.coerceAtLeast(0L)378 pendingSeekState.request(targetMs)379 AppLogger.info("[player] seek request positionMs=$targetMs")380 seekCommand = SeekCommand(nextId(), targetMs)381 }382383 override fun setPlaybackSpeed(speed: Float) {384 if (released) return385 val nextSpeed = speed.coerceIn(0.25f, 4.0f)386 if (this.speed != nextSpeed) AppLogger.info("[player] speed request speed=$nextSpeed")387 this.speed = nextSpeed388 }389390 override fun release() {391 if (released) return392 AppLogger.info("[player] release request")393 released = true394 surfaces.retire()395 initialPlaybackState.reset()396 pendingSeekState.reset()397 mediaRequest = null398 playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Stop)399 cachedPositionMs = 0L400 cachedDurationMs = 0L401 cachedIsPlaying = false402 }403404 override suspend fun releaseAndJoin() {405 release()406 surfaces.closeAndJoin()407 }408409 override fun currentPositionMs(): Long = cachedPositionMs410411 override fun durationMs(): Long = cachedDurationMs412413 override fun isPlaying(): Boolean = cachedIsPlaying414415 internal fun updateSnapshot(rawDuration: Long, rawSlider: Float, positionText: String, isPlaying: Boolean) {416 if (released) return417 // Anything > 24h has to be the nanosecond bug — no manga episode is418 // a day long. Lock the scale on first detection so it stays stable419 // even if the player briefly reports 0.420 if (durationScaleToMs == 1L && rawDuration > 24L * 3600L * 1000L) {421 durationScaleToMs = 1_000_000L422 }423 val durationMs = if (rawDuration > 0L) rawDuration / durationScaleToMs else 0L424425 if (sliderScale == 1f && rawSlider > 1.5f) {426 sliderScale = 1000f427 }428 val normalizedSlider = (rawSlider / sliderScale).coerceIn(0f, 1f)429430 cachedDurationMs = durationMs431 cachedPositionMs = if (durationMs > 0L) {432 (normalizedSlider * durationMs).toLong()433 } else {434 parsePlaybackPositionMs(positionText)435 }436 cachedIsPlaying = isPlaying437 }438439 private fun nextId(): Long = ++nextCommandId440}441442fun createComposeMediaPlayerController(streamProxy: MediaStreamProxy): MediaPlayerController =443 ComposeMediaPlayerController(streamProxy)444445/**446 * Platform factory; mpv is primary and ComposeMediaPlayer is the compatibility fallback.447 * [streamProxy] serves streams that need request headers the backend can't send itself.448 */449expect fun createMediaPlayerController(450 configuration: MediaPlayerConfiguration,451 streamProxy: MediaStreamProxy,452): MediaPlayerController453