MpvFeatures.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/player/MpvFeatures.kt
1package eu.friedcutlet.yokan.services.media.player23import eu.friedcutlet.yokan.database.DbCustomButton4import eu.friedcutlet.yokan.domain.Chapter5import eu.friedcutlet.yokan.services.files.LocalFileService6import kotlinx.serialization.json.Json7import kotlinx.serialization.json.contentOrNull8import kotlinx.serialization.json.doubleOrNull9import kotlinx.serialization.json.jsonArray10import kotlinx.serialization.json.jsonObject11import kotlinx.serialization.json.jsonPrimitive1213data class MpvMenuAction(val label: String, val command: String)1415val MpvStatsActions: List<MpvMenuAction> = listOf(16 MpvMenuAction("Stats toggle", "stats/display-stats-toggle"),17 MpvMenuAction("Stats page 1", "stats/display-page-1"),18 MpvMenuAction("Stats page 2", "stats/display-page-2"),19 MpvMenuAction("Stats page 3", "stats/display-page-3"),20 MpvMenuAction("Stats page 4", "stats/display-page-4"),21 MpvMenuAction("Stats page 5", "stats/display-page-5"),22)2324val MpvShaderActions: List<MpvMenuAction> = listOf(25 MpvMenuAction("Anime4K: Mode A (Fast)", "set_anime_a"),26 MpvMenuAction("Anime4K: Mode B (Fast)", "set_anime_b"),27 MpvMenuAction("Anime4K: Mode C (Fast)", "set_anime_c"),28 MpvMenuAction("Anime4K: Mode A+A (Fast)", "set_anime_aa"),29 MpvMenuAction("Anime4K: Mode B+B (Fast)", "set_anime_bb"),30 MpvMenuAction("Anime4K: Mode C+A (Fast)", "set_anime_ca"),31 MpvMenuAction("Anime4K: Mode A (HQ)", "set_anime_hq_a"),32 MpvMenuAction("Anime4K: Mode B (HQ)", "set_anime_hq_b"),33 MpvMenuAction("Anime4K: Mode C (HQ)", "set_anime_hq_c"),34 MpvMenuAction("Anime4K: Mode A+A (HQ)", "set_anime_hq_aa"),35 MpvMenuAction("Anime4K: Mode B+B (HQ)", "set_anime_hq_bb"),36 MpvMenuAction("Anime4K: Mode C+A (HQ)", "set_anime_hq_ca"),37 MpvMenuAction("AMD FSR", "set_fsr"),38 MpvMenuAction("Luma Upscaling", "set_luma"),39 MpvMenuAction("Qualcomm Snapdragon GSR", "set_snapdragon"),40 MpvMenuAction("NVIDIA Image Scaling", "set_nvidia"),41 MpvMenuAction("Clear GLSL shaders", "clear_anime"),42)4344fun prepareMpvConfiguration(45 configuration: MediaPlayerConfiguration,46 files: LocalFileService,47 ensureCurrent: () -> Unit = {},48) {49 ensureCurrent()50 if (!configuration.useMpvConfig || configuration.mpvConfigDirectory.isBlank()) return51 val mpvConf = "${configuration.mpvConfigDirectory}/mpv.conf"52 val inputConf = "${configuration.mpvConfigDirectory}/input.conf"53 val hasMpvConf = files.exists(mpvConf)54 ensureCurrent()55 if (!hasMpvConf) files.writeBytes(mpvConf, DefaultMpvConf.encodeToByteArray())56 ensureCurrent()57 val hasInputConf = files.exists(inputConf)58 ensureCurrent()59 if (!hasInputConf) files.writeBytes(inputConf, DefaultMpvInputConf.encodeToByteArray())60 ensureCurrent()61}6263fun MediaPlayerController.showMpvStats(binding: String): Boolean =64 executeMpvCommand("script-binding", binding)6566fun MediaPlayerController.selectMpvShader(scriptMessage: String): Boolean =67 executeMpvCommand("script-message", scriptMessage)6869fun MediaPlayerController.selectAudioTrack(file: String?, title: String? = null): Boolean =70 if (file.isNullOrBlank()) {71 executeMpvCommand("set", "aid", "no")72 } else {73 executeMpvCommand("audio-add", file, "select", title.orEmpty(), title.orEmpty())74 }7576fun MediaPlayerController.setSubtitleDelay(milliseconds: Int): Boolean =77 executeMpvCommand("set", "sub-delay", (milliseconds / 1000.0).toString())7879fun MediaPlayerController.setSubtitleSpeed(speed: Double): Boolean =80 executeMpvCommand("set", "sub-speed", speed.coerceIn(0.1, 10.0).toString())8182fun MediaPlayerController.setAudioDelay(milliseconds: Int): Boolean =83 executeMpvCommand("set", "audio-delay", (milliseconds / 1000.0).toString())8485fun MediaPlayerController.setMpvVideoFit(fit: MpvVideoFit): Boolean = when (fit) {86 MpvVideoFit.Contain -> {87 executeMpvCommand("set", "video-unscaled", "no") &&88 executeMpvCommand("set", "panscan", "0")89 }90 MpvVideoFit.Cover -> {91 executeMpvCommand("set", "video-unscaled", "no") &&92 executeMpvCommand("set", "panscan", "1")93 }94 MpvVideoFit.Original -> {95 executeMpvCommand("set", "panscan", "0") &&96 executeMpvCommand("set", "video-unscaled", "yes")97 }98}99100/** Explicit sync covers screenshot encoding/writing as well as native dispatch. */101suspend fun MediaPlayerController.takeMpvScreenshotAndJoin(path: String, includeSubtitles: Boolean = false): Boolean =102 executeMpvCommandAndJoin("sync", "screenshot-to-file", path, if (includeSubtitles) "subtitles" else "video")103104fun installMpvCustomButtons(105 controller: MediaPlayerController,106 buttons: List<DbCustomButton>,107 configuration: MediaPlayerConfiguration,108 files: LocalFileService,109 ensureCurrent: () -> Unit = {},110): Boolean {111 ensureCurrent()112 if (!controller.isMpvBackend || !configuration.useMpvConfig) return false113 val chapterScriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_chapter_titles.js"114 files.writeBytes(chapterScriptPath, ChapterTitlesJavaScript.encodeToByteArray())115 ensureCurrent()116 val chapterScriptLoaded = controller.executeMpvCommand("load-script", chapterScriptPath)117 ensureCurrent()118 if (buttons.isEmpty()) return chapterScriptLoaded119 val primary = buttons.firstOrNull(DbCustomButton::isFavourite) ?: buttons.first()120 val scriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_custom_buttons.js"121 files.writeBytes(scriptPath, buildMpvCustomButtonsScript(buttons, primary.id).encodeToByteArray())122 ensureCurrent()123 val customScriptLoaded = controller.executeMpvCommand("load-script", scriptPath)124 ensureCurrent()125 return customScriptLoaded && chapterScriptLoaded126}127128internal fun buildMpvCustomButtonsScript(buttons: List<DbCustomButton>, primaryId: Long): String = buildString {129 appendLine(AniyomiJavaScriptBridge)130 buttons.forEach { button ->131 appendLine(button.startupCode(primaryId))132 appendLine("function button_${button.id}() {")133 appendLine(button.pressCode(primaryId).prependIndent(" "))134 appendLine("}")135 appendLine("mp.register_script_message('call_button_${button.id}', button_${button.id});")136 appendLine("function button_${button.id}_long() {")137 appendLine(button.longPressCode(primaryId).prependIndent(" "))138 appendLine("}")139 appendLine("mp.register_script_message('call_button_${button.id}_long', button_${button.id}_long);")140 }141}142143val DefaultMpvConf: String = """144# Generated mpv defaults. Lines starting with # are ignored.145profile=gpu-hq146keep-open=yes147load-stats-overlay=yes148""".trimIndent()149150val DefaultMpvInputConf: String = """151# Generated input bindings.152SPACE cycle pause153RIGHT seek 10154LEFT seek -10155""".trimIndent()156157private val AniyomiJavaScriptBridge = """158var aniyomi = {};159aniyomi.show_text = function(text) { mp.set_property('user-data/aniyomi/show_text', String(text)); };160aniyomi.hide_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'hide'); };161aniyomi.show_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'show'); };162aniyomi.toggle_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'toggle'); };163aniyomi.show_subtitle_settings = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_settings'); };164aniyomi.show_subtitle_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_delay'); };165aniyomi.show_audio_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'audio_delay'); };166aniyomi.show_video_filters = function() { mp.set_property('user-data/aniyomi/show_panel', 'video_filters'); };167aniyomi.show_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'show'); };168aniyomi.hide_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'hide'); };169aniyomi.toggle_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'toggle'); };170aniyomi.set_button_title = function(text) { mp.set_property('user-data/aniyomi/set_button_title', String(text)); };171aniyomi.reset_button_title = function() { mp.set_property('user-data/aniyomi/reset_button_title', 'unused'); };172aniyomi.hide_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'hide'); };173aniyomi.show_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'show'); };174aniyomi.toggle_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'toggle'); };175aniyomi.previous_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'p'); };176aniyomi.next_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'n'); };177aniyomi.pause = function() { mp.set_property('user-data/aniyomi/pause', 'pause'); };178aniyomi.unpause = function() { mp.set_property('user-data/aniyomi/pause', 'unpause'); };179aniyomi.pauseunpause = function() { mp.set_property('user-data/aniyomi/pause', 'pauseunpause'); };180aniyomi.seek_by = function(value) { mp.set_property('user-data/aniyomi/seek_by', String(value)); };181aniyomi.seek_to = function(value) { mp.set_property('user-data/aniyomi/seek_to', String(value)); };182aniyomi.seek_by_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_by_with_text', value + '|' + text); };183aniyomi.seek_to_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_to_with_text', value + '|' + text); };184aniyomi.int_picker = function(title, nameFormat, start, stop, step, property) {185 mp.set_property('user-data/aniyomi/launch_int_picker', [title, nameFormat, start, stop, step, property].join('|'));186};187aniyomi.left_seek_by = function(value) { aniyomi.seek_by(-value); };188aniyomi.right_seek_by = function(value) { aniyomi.seek_by(value); };189""".trimIndent()190191private val ChapterTitlesJavaScript = """192function publishChapterTitles() {193 var count = mp.get_property_number('chapter-list/count', 0);194 var chapters = [];195 for (var index = 0; index < count; index++) {196 chapters.push({197 title: mp.get_property_native('chapter-list/' + index + '/title') || ('Chapter ' + (index + 1)),198 timestamp: mp.get_property_native('chapter-list/' + index + '/time') || 0199 });200 }201 mp.set_property('user-data/mangayomi/chapter_titles', mp.utils.format_json(chapters));202}203204function publishCurrentChapter(name, value) {205 if (value !== undefined && value !== null) {206 mp.set_property_number('user-data/mangayomi/current_chapter', Math.max(value, 0));207 }208}209210mp.register_event('file-loaded', publishChapterTitles);211mp.observe_property('chapter', 'number', publishCurrentChapter);212""".trimIndent()213214/** Player sheet pages the mpv scripts can open. */215internal enum class MpvPanel { Video, Subtitles, Audio }216217/** A typed request from the in-player mpv scripts, decoded from an [MpvBridgeEvent]. */218internal sealed interface PlayerBridgeCommand {219 data class ShowText(val text: String) : PlayerBridgeCommand220 /** [visible] null toggles the chrome. */221 data class SetUiVisible(val visible: Boolean?) : PlayerBridgeCommand222 data class ShowPanel(val panel: MpvPanel) : PlayerBridgeCommand223 data class SetButtonTitle(val title: String) : PlayerBridgeCommand224 data object ResetButtonTitle : PlayerBridgeCommand225 /** [visible] null toggles the custom button. */226 data class SetButtonVisible(val visible: Boolean?) : PlayerBridgeCommand227 data class SwitchEpisode(val offset: Int) : PlayerBridgeCommand228 /** [paused] null toggles playback. */229 data class SetPaused(val paused: Boolean?) : PlayerBridgeCommand230 /** Seeks by [seconds] from the current position when [relative], otherwise to [seconds]; [text] is shown alongside. */231 data class Seek(val seconds: Long, val relative: Boolean, val text: String? = null) : PlayerBridgeCommand232 data class LaunchIntPicker(val request: MpvIntPickerRequest) : PlayerBridgeCommand233 data class ChapterTitles(val marks: List<MpvChapterMark>) : PlayerBridgeCommand234 data class CurrentChapter(val index: Int) : PlayerBridgeCommand235 data class SelectedShader(val label: String) : PlayerBridgeCommand236}237238/** Every bridge property the scripts write, as `user-data/<key>`; the mpv backend observes exactly these. */239private enum class MpvBridgeName(val key: String) {240 ShowText("aniyomi/show_text"),241 ToggleUi("aniyomi/toggle_ui"),242 ShowPanel("aniyomi/show_panel"),243 SoftwareKeyboard("aniyomi/software_keyboard"),244 SetButtonTitle("aniyomi/set_button_title"),245 ResetButtonTitle("aniyomi/reset_button_title"),246 ToggleButton("aniyomi/toggle_button"),247 SwitchEpisode("aniyomi/switch_episode"),248 Pause("aniyomi/pause"),249 SeekBy("aniyomi/seek_by"),250 SeekTo("aniyomi/seek_to"),251 SeekByWithText("aniyomi/seek_by_with_text"),252 SeekToWithText("aniyomi/seek_to_with_text"),253 LaunchIntPicker("aniyomi/launch_int_picker"),254 ChapterTitles("mangayomi/chapter_titles"),255 CurrentChapter("mangayomi/current_chapter"),256 SelectedShader("mangayomi/selected_shader"),257}258259private val MpvBridgeNamesByKey = MpvBridgeName.entries.associateBy(MpvBridgeName::key)260261internal val MpvBridgePropertyNames: Set<String> = MpvBridgeName.entries.mapTo(HashSet()) { "user-data/${it.key}" }262263/** Null for unknown names, malformed values, and requests the player has no surface for (software keyboard). */264internal fun MpvBridgeEvent.toCommand(): PlayerBridgeCommand? = when (MpvBridgeNamesByKey[name] ?: return null) {265 MpvBridgeName.ShowText -> PlayerBridgeCommand.ShowText(value)266 MpvBridgeName.ToggleUi -> PlayerBridgeCommand.SetUiVisible(parseVisibility(value))267 MpvBridgeName.ShowPanel -> PlayerBridgeCommand.ShowPanel(268 when (value) {269 "subtitle_settings", "subtitle_delay" -> MpvPanel.Subtitles270 "audio_delay" -> MpvPanel.Audio271 else -> MpvPanel.Video272 },273 )274 MpvBridgeName.SoftwareKeyboard -> null275 MpvBridgeName.SetButtonTitle -> PlayerBridgeCommand.SetButtonTitle(value)276 MpvBridgeName.ResetButtonTitle -> PlayerBridgeCommand.ResetButtonTitle277 MpvBridgeName.ToggleButton -> PlayerBridgeCommand.SetButtonVisible(parseVisibility(value))278 MpvBridgeName.SwitchEpisode -> PlayerBridgeCommand.SwitchEpisode(if (value == "p") -1 else 1)279 MpvBridgeName.Pause -> PlayerBridgeCommand.SetPaused(280 when (value) {281 "pause" -> true282 "unpause" -> false283 else -> null284 },285 )286 MpvBridgeName.SeekBy -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = true) }287 MpvBridgeName.SeekTo -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = false) }288 MpvBridgeName.SeekByWithText -> parseSeekWithText(value, relative = true)289 MpvBridgeName.SeekToWithText -> parseSeekWithText(value, relative = false)290 MpvBridgeName.LaunchIntPicker -> MpvIntPickerRequest.parse(value)?.let(PlayerBridgeCommand::LaunchIntPicker)291 MpvBridgeName.ChapterTitles -> PlayerBridgeCommand.ChapterTitles(MpvChapterMark.parseList(value))292 MpvBridgeName.CurrentChapter -> PlayerBridgeCommand.CurrentChapter(value.toDoubleOrNull()?.toInt()?.coerceAtLeast(0) ?: 0)293 MpvBridgeName.SelectedShader -> PlayerBridgeCommand.SelectedShader(value)294}295296private fun parseVisibility(value: String): Boolean? = when (value) {297 "show" -> true298 "hide" -> false299 else -> null300}301302private fun parseSeconds(value: String): Long? = value.trim().trim('"').toDoubleOrNull()?.toLong()303304/** `seconds|text`: an unparsable position still shows the text. */305private fun parseSeekWithText(value: String, relative: Boolean): PlayerBridgeCommand? {306 val pieces = value.split('|', limit = 2)307 val text = pieces.getOrNull(1)308 val seconds = parseSeconds(pieces.first()) ?: return text?.let(PlayerBridgeCommand::ShowText)309 return PlayerBridgeCommand.Seek(seconds, relative, text)310}311312/** `title|valueFormat|start|stop|step|property`, as written by `aniyomi.int_picker`. */313internal data class MpvIntPickerRequest(314 val title: String,315 val valueFormat: String,316 val start: Int,317 val stop: Int,318 val step: Int,319 val property: String,320) {321 companion object {322 fun parse(value: String): MpvIntPickerRequest? {323 val pieces = value.split('|')324 if (pieces.size < 6) return null325 val start = pieces[2].toIntOrNull() ?: return null326 val stop = pieces[3].toIntOrNull() ?: return null327 val step = pieces[4].toIntOrNull()?.takeIf { it > 0 } ?: return null328 if (stop <= start || pieces[5].isBlank()) return null329 return MpvIntPickerRequest(330 title = pieces[0],331 valueFormat = pieces[1],332 start = start,333 stop = stop,334 step = step,335 property = pieces[5],336 )337 }338 }339}340341internal data class MpvChapterMark(val title: String, val positionMs: Long) {342 companion object {343 /** The JSON array published by the chapter-titles script; malformed input yields no marks. */344 fun parseList(value: String): List<MpvChapterMark> = runCatching {345 Json.parseToJsonElement(value).jsonArray.mapNotNull { element ->346 val objectValue = element.jsonObject347 val timestampSeconds = objectValue["timestamp"]?.jsonPrimitive?.doubleOrNull348 ?: return@mapNotNull null349 MpvChapterMark(350 title = objectValue["title"]?.jsonPrimitive?.contentOrNull.orEmpty().ifBlank { "Chapter" },351 positionMs = (timestampSeconds * 1000.0).toLong().coerceAtLeast(0L),352 )353 }354 }.getOrDefault(emptyList())355 }356}357