package eu.friedcutlet.yokan.services.media.player import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import eu.friedcutlet.yokan.database.DbAudioChannel import eu.friedcutlet.yokan.database.DbDebandingType import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.redactUrlForLog import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.withTimeoutOrNull import io.github.kdroidfilter.composemediaplayer.SubtitleTrack data class MediaPlayerConfiguration( val useLibass: Boolean = true, val useMpvConfig: Boolean = true, val mpvConfigDirectory: String = "", val hwdecMode: String = "auto", val enableHardwareAcceleration: Boolean? = null, val enableGpuNext: Boolean = false, val debandingType: DbDebandingType = DbDebandingType.None, val useYuv420p: Boolean = false, val audioPreferredLanguages: String? = null, val enableAudioPitchCorrection: Boolean? = null, val audioChannels: DbAudioChannel = DbAudioChannel.AutoSafe, val volumeBoostCap: Int? = null, /** Embedded-track subtitle priority (mpv `slang`); external tracks use [preferredSubtitle]. */ val subtitleLanguages: List = emptyList(), ) { companion object { fun from(settings: DbSettings, cacheRoot: String): MediaPlayerConfiguration = MediaPlayerConfiguration( useLibass = settings.useLibass, useMpvConfig = settings.useMpvConfig, mpvConfigDirectory = "${cacheRoot.trimEnd('/')}/mpv", hwdecMode = settings.hwdecMode, enableHardwareAcceleration = settings.enableHardwareAcceleration, enableGpuNext = settings.enableGpuNext, debandingType = settings.debandingType, useYuv420p = settings.useYuv420p, audioPreferredLanguages = settings.audioPreferredLanguages, enableAudioPitchCorrection = settings.enableAudioPitchCorrection, audioChannels = settings.audioChannels, volumeBoostCap = settings.volumeBoostCap, subtitleLanguages = settings.features.player.subtitleLanguages, ) } internal fun mpvOptions(): Map = buildMap { put("keep-open", "yes") put("load-stats-overlay", "yes") put("sub-ass", if (useLibass) "yes" else "no") put("hwdec", if (enableHardwareAcceleration == false) "no" else hwdecMode.ifBlank { "auto" }) put("audio-pitch-correction", if (enableAudioPitchCorrection != false) "yes" else "no") put("volume-max", ((volumeBoostCap ?: 30).coerceIn(0, 200) + 100).toString()) val videoFilters = buildList { if (useYuv420p) add("format=yuv420p") if (debandingType == DbDebandingType.Cpu) add("gradfun=radius=12") } if (videoFilters.isNotEmpty()) put("vf", videoFilters.joinToString(",")) if (debandingType == DbDebandingType.Gpu) put("deband", "yes") audioPreferredLanguages?.trim()?.takeIf(String::isNotEmpty)?.let { put("alang", it) } if (subtitleLanguages.isNotEmpty()) put("slang", subtitleLanguages.joinToString(",")) if (audioChannels == DbAudioChannel.ReverseStereo) { put("af", audioChannels.mpvName) } else { put("audio-channels", audioChannels.mpvName) } if (useMpvConfig && mpvConfigDirectory.isNotBlank()) { put("config", "yes") put("config-dir", mpvConfigDirectory) } else { put("config", "no") } } } data class MpvBridgeEvent(val name: String, val value: String) enum class MpvVideoFit(val label: String) { Contain("Fit"), Cover("Crop"), Original("100%"), } /** * Media engine handle. Each platform's actual factory picks the best * backend. libmpv is primary on Android, iOS devices, macOS and Windows. The * previous ComposeMediaPlayer path remains as a fallback for iOS simulators * and Linux machines where the distribution libmpv package is unavailable. */ interface MediaPlayerController { val isMpvBackend: Boolean get() = false val mpvBridgeEvents: Flow get() = emptyFlow() fun load(url: String, headers: Map = emptyMap(), initialPositionMs: Long = 0L) fun play() fun pause() fun seekTo(positionMs: Long) fun setPlaybackSpeed(speed: Float) /** Queues a raw libmpv command. Returns false on the compatibility backend. */ fun executeMpvCommand(vararg arguments: String): Boolean = false /** Await the native command call and join cleanup on expiry. Script/background work has its own lifetime. */ suspend fun executeMpvCommandAndJoin(vararg arguments: String): Boolean = false fun release() /** Await controller work, surface finalizers and native release. */ suspend fun releaseAndJoin() { release() } /** Current position in milliseconds (best-effort; 0 if not started or unsupported). */ fun currentPositionMs(): Long /** Total duration in milliseconds; 0 if unknown. */ fun durationMs(): Long /** True when the engine is currently playing. */ fun isPlaying(): Boolean /** The current stream's playback failure (observable Compose state); null while healthy. */ val playbackError: String? get() = null /** Selects an external subtitle file as the primary track; null disables subtitles. */ fun selectSubtitleTrack(file: String?, title: String? = null): Boolean = if (file.isNullOrBlank()) { executeMpvCommand("set", "sid", "no") } else { executeMpvCommand("sub-add", file, "select", title.orEmpty(), title.orEmpty()) } /** Shows a second external subtitle file alongside the primary one; null hides it. */ fun selectSecondarySubtitle(file: String?, title: String? = null): Boolean = false fun setSecondarySubtitleDelay(milliseconds: Int): Boolean = executeMpvCommand("set", "secondary-sub-delay", (milliseconds / 1000.0).toString()) /** Output volume in percent, 0..100. */ fun setVolume(percent: Int): Boolean = executeMpvCommand("set", "volume", percent.coerceIn(0, 100).toString()) } internal enum class PlaybackAction { Play, Pause, Stop, } internal data class MediaRequest( val id: Long, val url: String, val originalUrl: String, val headers: Map, val proxied: Boolean, val initialPositionMs: Long, ) internal data class PlaybackCommand( val id: Long, val action: PlaybackAction, ) internal data class SeekCommand( val id: Long, val positionMs: Long, ) internal class PendingSeekState { private var requestedGeneration = 0L private var dispatchedGeneration = 0L private var positionMs = 0L fun request(positionMs: Long) { requestedGeneration += 1L this.positionMs = positionMs.coerceAtLeast(0L) } fun pendingPositionMs(): Long? = positionMs.takeIf { requestedGeneration > dispatchedGeneration } fun markDispatched() { dispatchedGeneration = requestedGeneration } fun reset() { dispatchedGeneration = requestedGeneration positionMs = 0L } } internal class InitialPlaybackState { var autoplayRequested: Boolean = false private set var mediaPrepared by mutableStateOf(false) private set fun beginPreparation() { autoplayRequested = false mediaPrepared = false } fun requestPlay() { autoplayRequested = true } fun requestPause() { autoplayRequested = false } fun finishPreparation(): Boolean { mediaPrepared = true return autoplayRequested } fun reset() { autoplayRequested = false mediaPrepared = false } } internal suspend fun awaitInitialMediaDuration( durationMs: () -> Long?, isUsable: () -> Boolean, hasError: () -> Boolean, requireDuration: Boolean, readinessGraceMs: Long = 250L, timeoutMs: Long = 5_000L, pollIntervalMs: Long = 16L, ): Long? = withTimeoutOrNull(timeoutMs) { var resolvedDurationMs = 0L var waiting = true while (waiting) { val knownDurationMs = durationMs()?.takeIf { it > 0L } when { knownDurationMs != null -> { resolvedDurationMs = knownDurationMs waiting = false } hasError() -> waiting = false !requireDuration && isUsable() -> { delay(readinessGraceMs) val settledDurationMs = durationMs()?.takeIf { it > 0L } if (settledDurationMs != null) { resolvedDurationMs = settledDurationMs waiting = false } else if (hasError() || (!requireDuration && isUsable())) { waiting = false } } else -> delay(pollIntervalMs) } } resolvedDurationMs }?.takeIf { it > 0L } internal fun parsePlaybackPositionMs(positionText: String): Long { val parts = positionText.trim().split(':') if (parts.size !in 2..3) return 0L val values = parts.map { it.toLongOrNull() ?: return 0L } val hours = if (values.size == 3) values[0] else 0L val minutes = values[values.size - 2] val seconds = values.last() if (hours < 0L || minutes !in 0L..59L || seconds !in 0L..59L) return 0L return ((hours * 60L + minutes) * 60L + seconds) * 1000L } internal class ComposeMediaPlayerController( private val streamProxy: MediaStreamProxy, ) : MediaPlayerController { internal val surfaces = PlayerSurfaceResources() internal var mediaRequest by mutableStateOf(null) private set internal var playbackCommand by mutableStateOf(null) private set internal var seekCommand by mutableStateOf(null) private set internal var speed by mutableStateOf(1.0f) private set internal var released by mutableStateOf(false) private set /** compose-mediaplayer draws these with its own cue layer; the secondary one is offset by [secondaryDelayMs]. */ internal var subtitle by mutableStateOf(null) private set internal var secondarySubtitle by mutableStateOf(null) private set internal var secondaryDelayMs by mutableIntStateOf(0) private set internal var volume by mutableFloatStateOf(1f) private set internal var error by mutableStateOf(null) override val playbackError: String? get() = error private val initialPlaybackState = InitialPlaybackState() internal val autoplayRequested: Boolean get() = initialPlaybackState.autoplayRequested internal val mediaPrepared: Boolean get() = initialPlaybackState.mediaPrepared internal fun finishMediaPreparation(): Boolean = !released && initialPlaybackState.finishPreparation() private val pendingSeekState = PendingSeekState() internal fun pendingSeekPositionMs(): Long? = pendingSeekState.pendingPositionMs() internal fun markPendingSeekDispatched() = pendingSeekState.markDispatched() private var nextCommandId = 0L // Observable Compose state so reads in @Composable callers subscribe and // recompose as playback progresses. The Surface composable writes to these // every time the underlying VideoPlayerState ticks. private var cachedPositionMs by mutableLongStateOf(0L) private var cachedDurationMs by mutableLongStateOf(0L) private var cachedIsPlaying by mutableStateOf(false) // kdroidfilter compose-mediaplayer 0.7.11 has two unit bugs in its Linux // backend that don't match its KDoc: // • `metadata.duration` is raw GStreamer nanoseconds, not milliseconds // • `sliderPos` ranges 0..1000, not 0..1 // Android/iOS backends do follow the docs. Auto-detect once per session // by sniffing the first sane value we see, then reuse for `seekTo` math. internal var durationScaleToMs: Long = 1L private set internal var sliderScale: Float = 1f private set override fun load(url: String, headers: Map, initialPositionMs: Long) { if (released) return initialPlaybackState.beginPreparation() pendingSeekState.reset() val playableUrl = if (headers.isNotEmpty()) streamProxy.proxyUrl(url, headers) else url val proxied = playableUrl != url val startPositionMs = initialPositionMs.coerceAtLeast(0L) AppLogger.info( "[player] load request url=${redactUrlForLog(url)} headers=${headers.size} startPositionMs=$startPositionMs" + if (proxied) " proxy=${redactUrlForLog(playableUrl)}" else "", ) error = null subtitle = null secondarySubtitle = null mediaRequest = MediaRequest(nextId(), playableUrl, url, headers, proxied, startPositionMs) } override fun selectSubtitleTrack(file: String?, title: String?): Boolean { if (released) return false subtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) } return true } override fun selectSecondarySubtitle(file: String?, title: String?): Boolean { if (released) return false secondarySubtitle = file?.takeIf(String::isNotBlank)?.let { SubtitleTrack(title.orEmpty(), "", it) } return true } override fun setSecondarySubtitleDelay(milliseconds: Int): Boolean { if (released) return false secondaryDelayMs = milliseconds return true } override fun setVolume(percent: Int): Boolean { if (released) return false volume = percent.coerceIn(0, 100) / 100f return true } override fun play() { if (released) return initialPlaybackState.requestPlay() AppLogger.info("[player] play request") playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Play) } override fun pause() { if (released) return initialPlaybackState.requestPause() AppLogger.info("[player] pause request") playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Pause) } override fun seekTo(positionMs: Long) { if (released) return val targetMs = positionMs.coerceAtLeast(0L) pendingSeekState.request(targetMs) AppLogger.info("[player] seek request positionMs=$targetMs") seekCommand = SeekCommand(nextId(), targetMs) } override fun setPlaybackSpeed(speed: Float) { if (released) return val nextSpeed = speed.coerceIn(0.25f, 4.0f) if (this.speed != nextSpeed) AppLogger.info("[player] speed request speed=$nextSpeed") this.speed = nextSpeed } override fun release() { if (released) return AppLogger.info("[player] release request") released = true surfaces.retire() initialPlaybackState.reset() pendingSeekState.reset() mediaRequest = null playbackCommand = PlaybackCommand(nextId(), PlaybackAction.Stop) cachedPositionMs = 0L cachedDurationMs = 0L cachedIsPlaying = false } override suspend fun releaseAndJoin() { release() surfaces.closeAndJoin() } override fun currentPositionMs(): Long = cachedPositionMs override fun durationMs(): Long = cachedDurationMs override fun isPlaying(): Boolean = cachedIsPlaying internal fun updateSnapshot(rawDuration: Long, rawSlider: Float, positionText: String, isPlaying: Boolean) { if (released) return // Anything > 24h has to be the nanosecond bug — no manga episode is // a day long. Lock the scale on first detection so it stays stable // even if the player briefly reports 0. if (durationScaleToMs == 1L && rawDuration > 24L * 3600L * 1000L) { durationScaleToMs = 1_000_000L } val durationMs = if (rawDuration > 0L) rawDuration / durationScaleToMs else 0L if (sliderScale == 1f && rawSlider > 1.5f) { sliderScale = 1000f } val normalizedSlider = (rawSlider / sliderScale).coerceIn(0f, 1f) cachedDurationMs = durationMs cachedPositionMs = if (durationMs > 0L) { (normalizedSlider * durationMs).toLong() } else { parsePlaybackPositionMs(positionText) } cachedIsPlaying = isPlaying } private fun nextId(): Long = ++nextCommandId } fun createComposeMediaPlayerController(streamProxy: MediaStreamProxy): MediaPlayerController = ComposeMediaPlayerController(streamProxy) /** * Platform factory; mpv is primary and ComposeMediaPlayer is the compatibility fallback. * [streamProxy] serves streams that need request headers the backend can't send itself. */ expect fun createMediaPlayerController( configuration: MediaPlayerConfiguration, streamProxy: MediaStreamProxy, ): MediaPlayerController