package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.services.files.LocalFileService import kotlinx.serialization.json.Json import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive data class MpvMenuAction(val label: String, val command: String) val MpvStatsActions: List = listOf( MpvMenuAction("Stats toggle", "stats/display-stats-toggle"), MpvMenuAction("Stats page 1", "stats/display-page-1"), MpvMenuAction("Stats page 2", "stats/display-page-2"), MpvMenuAction("Stats page 3", "stats/display-page-3"), MpvMenuAction("Stats page 4", "stats/display-page-4"), MpvMenuAction("Stats page 5", "stats/display-page-5"), ) val MpvShaderActions: List = listOf( MpvMenuAction("Anime4K: Mode A (Fast)", "set_anime_a"), MpvMenuAction("Anime4K: Mode B (Fast)", "set_anime_b"), MpvMenuAction("Anime4K: Mode C (Fast)", "set_anime_c"), MpvMenuAction("Anime4K: Mode A+A (Fast)", "set_anime_aa"), MpvMenuAction("Anime4K: Mode B+B (Fast)", "set_anime_bb"), MpvMenuAction("Anime4K: Mode C+A (Fast)", "set_anime_ca"), MpvMenuAction("Anime4K: Mode A (HQ)", "set_anime_hq_a"), MpvMenuAction("Anime4K: Mode B (HQ)", "set_anime_hq_b"), MpvMenuAction("Anime4K: Mode C (HQ)", "set_anime_hq_c"), MpvMenuAction("Anime4K: Mode A+A (HQ)", "set_anime_hq_aa"), MpvMenuAction("Anime4K: Mode B+B (HQ)", "set_anime_hq_bb"), MpvMenuAction("Anime4K: Mode C+A (HQ)", "set_anime_hq_ca"), MpvMenuAction("AMD FSR", "set_fsr"), MpvMenuAction("Luma Upscaling", "set_luma"), MpvMenuAction("Qualcomm Snapdragon GSR", "set_snapdragon"), MpvMenuAction("NVIDIA Image Scaling", "set_nvidia"), MpvMenuAction("Clear GLSL shaders", "clear_anime"), ) fun prepareMpvConfiguration( configuration: MediaPlayerConfiguration, files: LocalFileService, ensureCurrent: () -> Unit = {}, ) { ensureCurrent() if (!configuration.useMpvConfig || configuration.mpvConfigDirectory.isBlank()) return val mpvConf = "${configuration.mpvConfigDirectory}/mpv.conf" val inputConf = "${configuration.mpvConfigDirectory}/input.conf" val hasMpvConf = files.exists(mpvConf) ensureCurrent() if (!hasMpvConf) files.writeBytes(mpvConf, DefaultMpvConf.encodeToByteArray()) ensureCurrent() val hasInputConf = files.exists(inputConf) ensureCurrent() if (!hasInputConf) files.writeBytes(inputConf, DefaultMpvInputConf.encodeToByteArray()) ensureCurrent() } fun MediaPlayerController.showMpvStats(binding: String): Boolean = executeMpvCommand("script-binding", binding) fun MediaPlayerController.selectMpvShader(scriptMessage: String): Boolean = executeMpvCommand("script-message", scriptMessage) fun MediaPlayerController.selectAudioTrack(file: String?, title: String? = null): Boolean = if (file.isNullOrBlank()) { executeMpvCommand("set", "aid", "no") } else { executeMpvCommand("audio-add", file, "select", title.orEmpty(), title.orEmpty()) } fun MediaPlayerController.setSubtitleDelay(milliseconds: Int): Boolean = executeMpvCommand("set", "sub-delay", (milliseconds / 1000.0).toString()) fun MediaPlayerController.setSubtitleSpeed(speed: Double): Boolean = executeMpvCommand("set", "sub-speed", speed.coerceIn(0.1, 10.0).toString()) fun MediaPlayerController.setAudioDelay(milliseconds: Int): Boolean = executeMpvCommand("set", "audio-delay", (milliseconds / 1000.0).toString()) fun MediaPlayerController.setMpvVideoFit(fit: MpvVideoFit): Boolean = when (fit) { MpvVideoFit.Contain -> { executeMpvCommand("set", "video-unscaled", "no") && executeMpvCommand("set", "panscan", "0") } MpvVideoFit.Cover -> { executeMpvCommand("set", "video-unscaled", "no") && executeMpvCommand("set", "panscan", "1") } MpvVideoFit.Original -> { executeMpvCommand("set", "panscan", "0") && executeMpvCommand("set", "video-unscaled", "yes") } } /** Explicit sync covers screenshot encoding/writing as well as native dispatch. */ suspend fun MediaPlayerController.takeMpvScreenshotAndJoin(path: String, includeSubtitles: Boolean = false): Boolean = executeMpvCommandAndJoin("sync", "screenshot-to-file", path, if (includeSubtitles) "subtitles" else "video") fun installMpvCustomButtons( controller: MediaPlayerController, buttons: List, configuration: MediaPlayerConfiguration, files: LocalFileService, ensureCurrent: () -> Unit = {}, ): Boolean { ensureCurrent() if (!controller.isMpvBackend || !configuration.useMpvConfig) return false val chapterScriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_chapter_titles.js" files.writeBytes(chapterScriptPath, ChapterTitlesJavaScript.encodeToByteArray()) ensureCurrent() val chapterScriptLoaded = controller.executeMpvCommand("load-script", chapterScriptPath) ensureCurrent() if (buttons.isEmpty()) return chapterScriptLoaded val primary = buttons.firstOrNull(DbCustomButton::isFavourite) ?: buttons.first() val scriptPath = "${configuration.mpvConfigDirectory}/scripts/yokan_custom_buttons.js" files.writeBytes(scriptPath, buildMpvCustomButtonsScript(buttons, primary.id).encodeToByteArray()) ensureCurrent() val customScriptLoaded = controller.executeMpvCommand("load-script", scriptPath) ensureCurrent() return customScriptLoaded && chapterScriptLoaded } internal fun buildMpvCustomButtonsScript(buttons: List, primaryId: Long): String = buildString { appendLine(AniyomiJavaScriptBridge) buttons.forEach { button -> appendLine(button.startupCode(primaryId)) appendLine("function button_${button.id}() {") appendLine(button.pressCode(primaryId).prependIndent(" ")) appendLine("}") appendLine("mp.register_script_message('call_button_${button.id}', button_${button.id});") appendLine("function button_${button.id}_long() {") appendLine(button.longPressCode(primaryId).prependIndent(" ")) appendLine("}") appendLine("mp.register_script_message('call_button_${button.id}_long', button_${button.id}_long);") } } val DefaultMpvConf: String = """ # Generated mpv defaults. Lines starting with # are ignored. profile=gpu-hq keep-open=yes load-stats-overlay=yes """.trimIndent() val DefaultMpvInputConf: String = """ # Generated input bindings. SPACE cycle pause RIGHT seek 10 LEFT seek -10 """.trimIndent() private val AniyomiJavaScriptBridge = """ var aniyomi = {}; aniyomi.show_text = function(text) { mp.set_property('user-data/aniyomi/show_text', String(text)); }; aniyomi.hide_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'hide'); }; aniyomi.show_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'show'); }; aniyomi.toggle_ui = function() { mp.set_property('user-data/aniyomi/toggle_ui', 'toggle'); }; aniyomi.show_subtitle_settings = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_settings'); }; aniyomi.show_subtitle_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'subtitle_delay'); }; aniyomi.show_audio_delay = function() { mp.set_property('user-data/aniyomi/show_panel', 'audio_delay'); }; aniyomi.show_video_filters = function() { mp.set_property('user-data/aniyomi/show_panel', 'video_filters'); }; aniyomi.show_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'show'); }; aniyomi.hide_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'hide'); }; aniyomi.toggle_software_keyboard = function() { mp.set_property('user-data/aniyomi/software_keyboard', 'toggle'); }; aniyomi.set_button_title = function(text) { mp.set_property('user-data/aniyomi/set_button_title', String(text)); }; aniyomi.reset_button_title = function() { mp.set_property('user-data/aniyomi/reset_button_title', 'unused'); }; aniyomi.hide_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'hide'); }; aniyomi.show_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'show'); }; aniyomi.toggle_button = function() { mp.set_property('user-data/aniyomi/toggle_button', 'toggle'); }; aniyomi.previous_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'p'); }; aniyomi.next_episode = function() { mp.set_property('user-data/aniyomi/switch_episode', 'n'); }; aniyomi.pause = function() { mp.set_property('user-data/aniyomi/pause', 'pause'); }; aniyomi.unpause = function() { mp.set_property('user-data/aniyomi/pause', 'unpause'); }; aniyomi.pauseunpause = function() { mp.set_property('user-data/aniyomi/pause', 'pauseunpause'); }; aniyomi.seek_by = function(value) { mp.set_property('user-data/aniyomi/seek_by', String(value)); }; aniyomi.seek_to = function(value) { mp.set_property('user-data/aniyomi/seek_to', String(value)); }; aniyomi.seek_by_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_by_with_text', value + '|' + text); }; aniyomi.seek_to_with_text = function(value, text) { mp.set_property('user-data/aniyomi/seek_to_with_text', value + '|' + text); }; aniyomi.int_picker = function(title, nameFormat, start, stop, step, property) { mp.set_property('user-data/aniyomi/launch_int_picker', [title, nameFormat, start, stop, step, property].join('|')); }; aniyomi.left_seek_by = function(value) { aniyomi.seek_by(-value); }; aniyomi.right_seek_by = function(value) { aniyomi.seek_by(value); }; """.trimIndent() private val ChapterTitlesJavaScript = """ function publishChapterTitles() { var count = mp.get_property_number('chapter-list/count', 0); var chapters = []; for (var index = 0; index < count; index++) { chapters.push({ title: mp.get_property_native('chapter-list/' + index + '/title') || ('Chapter ' + (index + 1)), timestamp: mp.get_property_native('chapter-list/' + index + '/time') || 0 }); } mp.set_property('user-data/mangayomi/chapter_titles', mp.utils.format_json(chapters)); } function publishCurrentChapter(name, value) { if (value !== undefined && value !== null) { mp.set_property_number('user-data/mangayomi/current_chapter', Math.max(value, 0)); } } mp.register_event('file-loaded', publishChapterTitles); mp.observe_property('chapter', 'number', publishCurrentChapter); """.trimIndent() /** Player sheet pages the mpv scripts can open. */ internal enum class MpvPanel { Video, Subtitles, Audio } /** A typed request from the in-player mpv scripts, decoded from an [MpvBridgeEvent]. */ internal sealed interface PlayerBridgeCommand { data class ShowText(val text: String) : PlayerBridgeCommand /** [visible] null toggles the chrome. */ data class SetUiVisible(val visible: Boolean?) : PlayerBridgeCommand data class ShowPanel(val panel: MpvPanel) : PlayerBridgeCommand data class SetButtonTitle(val title: String) : PlayerBridgeCommand data object ResetButtonTitle : PlayerBridgeCommand /** [visible] null toggles the custom button. */ data class SetButtonVisible(val visible: Boolean?) : PlayerBridgeCommand data class SwitchEpisode(val offset: Int) : PlayerBridgeCommand /** [paused] null toggles playback. */ data class SetPaused(val paused: Boolean?) : PlayerBridgeCommand /** Seeks by [seconds] from the current position when [relative], otherwise to [seconds]; [text] is shown alongside. */ data class Seek(val seconds: Long, val relative: Boolean, val text: String? = null) : PlayerBridgeCommand data class LaunchIntPicker(val request: MpvIntPickerRequest) : PlayerBridgeCommand data class ChapterTitles(val marks: List) : PlayerBridgeCommand data class CurrentChapter(val index: Int) : PlayerBridgeCommand data class SelectedShader(val label: String) : PlayerBridgeCommand } /** Every bridge property the scripts write, as `user-data/`; the mpv backend observes exactly these. */ private enum class MpvBridgeName(val key: String) { ShowText("aniyomi/show_text"), ToggleUi("aniyomi/toggle_ui"), ShowPanel("aniyomi/show_panel"), SoftwareKeyboard("aniyomi/software_keyboard"), SetButtonTitle("aniyomi/set_button_title"), ResetButtonTitle("aniyomi/reset_button_title"), ToggleButton("aniyomi/toggle_button"), SwitchEpisode("aniyomi/switch_episode"), Pause("aniyomi/pause"), SeekBy("aniyomi/seek_by"), SeekTo("aniyomi/seek_to"), SeekByWithText("aniyomi/seek_by_with_text"), SeekToWithText("aniyomi/seek_to_with_text"), LaunchIntPicker("aniyomi/launch_int_picker"), ChapterTitles("mangayomi/chapter_titles"), CurrentChapter("mangayomi/current_chapter"), SelectedShader("mangayomi/selected_shader"), } private val MpvBridgeNamesByKey = MpvBridgeName.entries.associateBy(MpvBridgeName::key) internal val MpvBridgePropertyNames: Set = MpvBridgeName.entries.mapTo(HashSet()) { "user-data/${it.key}" } /** Null for unknown names, malformed values, and requests the player has no surface for (software keyboard). */ internal fun MpvBridgeEvent.toCommand(): PlayerBridgeCommand? = when (MpvBridgeNamesByKey[name] ?: return null) { MpvBridgeName.ShowText -> PlayerBridgeCommand.ShowText(value) MpvBridgeName.ToggleUi -> PlayerBridgeCommand.SetUiVisible(parseVisibility(value)) MpvBridgeName.ShowPanel -> PlayerBridgeCommand.ShowPanel( when (value) { "subtitle_settings", "subtitle_delay" -> MpvPanel.Subtitles "audio_delay" -> MpvPanel.Audio else -> MpvPanel.Video }, ) MpvBridgeName.SoftwareKeyboard -> null MpvBridgeName.SetButtonTitle -> PlayerBridgeCommand.SetButtonTitle(value) MpvBridgeName.ResetButtonTitle -> PlayerBridgeCommand.ResetButtonTitle MpvBridgeName.ToggleButton -> PlayerBridgeCommand.SetButtonVisible(parseVisibility(value)) MpvBridgeName.SwitchEpisode -> PlayerBridgeCommand.SwitchEpisode(if (value == "p") -1 else 1) MpvBridgeName.Pause -> PlayerBridgeCommand.SetPaused( when (value) { "pause" -> true "unpause" -> false else -> null }, ) MpvBridgeName.SeekBy -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = true) } MpvBridgeName.SeekTo -> parseSeconds(value)?.let { PlayerBridgeCommand.Seek(it, relative = false) } MpvBridgeName.SeekByWithText -> parseSeekWithText(value, relative = true) MpvBridgeName.SeekToWithText -> parseSeekWithText(value, relative = false) MpvBridgeName.LaunchIntPicker -> MpvIntPickerRequest.parse(value)?.let(PlayerBridgeCommand::LaunchIntPicker) MpvBridgeName.ChapterTitles -> PlayerBridgeCommand.ChapterTitles(MpvChapterMark.parseList(value)) MpvBridgeName.CurrentChapter -> PlayerBridgeCommand.CurrentChapter(value.toDoubleOrNull()?.toInt()?.coerceAtLeast(0) ?: 0) MpvBridgeName.SelectedShader -> PlayerBridgeCommand.SelectedShader(value) } private fun parseVisibility(value: String): Boolean? = when (value) { "show" -> true "hide" -> false else -> null } private fun parseSeconds(value: String): Long? = value.trim().trim('"').toDoubleOrNull()?.toLong() /** `seconds|text`: an unparsable position still shows the text. */ private fun parseSeekWithText(value: String, relative: Boolean): PlayerBridgeCommand? { val pieces = value.split('|', limit = 2) val text = pieces.getOrNull(1) val seconds = parseSeconds(pieces.first()) ?: return text?.let(PlayerBridgeCommand::ShowText) return PlayerBridgeCommand.Seek(seconds, relative, text) } /** `title|valueFormat|start|stop|step|property`, as written by `aniyomi.int_picker`. */ internal data class MpvIntPickerRequest( val title: String, val valueFormat: String, val start: Int, val stop: Int, val step: Int, val property: String, ) { companion object { fun parse(value: String): MpvIntPickerRequest? { val pieces = value.split('|') if (pieces.size < 6) return null val start = pieces[2].toIntOrNull() ?: return null val stop = pieces[3].toIntOrNull() ?: return null val step = pieces[4].toIntOrNull()?.takeIf { it > 0 } ?: return null if (stop <= start || pieces[5].isBlank()) return null return MpvIntPickerRequest( title = pieces[0], valueFormat = pieces[1], start = start, stop = stop, step = step, property = pieces[5], ) } } } internal data class MpvChapterMark(val title: String, val positionMs: Long) { companion object { /** The JSON array published by the chapter-titles script; malformed input yields no marks. */ fun parseList(value: String): List = runCatching { Json.parseToJsonElement(value).jsonArray.mapNotNull { element -> val objectValue = element.jsonObject val timestampSeconds = objectValue["timestamp"]?.jsonPrimitive?.doubleOrNull ?: return@mapNotNull null MpvChapterMark( title = objectValue["title"]?.jsonPrimitive?.contentOrNull.orEmpty().ifBlank { "Chapter" }, positionMs = (timestampSeconds * 1000.0).toLong().coerceAtLeast(0L), ) } }.getOrDefault(emptyList()) } }