-
Notifications
You must be signed in to change notification settings - Fork 0
/
MediaPlayer.android.kt
302 lines (270 loc) · 11.9 KB
/
MediaPlayer.android.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package moe.styx.styx2m.player
import Styx_m.styx_m.BuildConfig
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import dev.jdtech.mpv.MPVLib
import io.github.xxfast.kstore.extensions.getOrEmpty
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import moe.styx.common.compose.files.Storage
import moe.styx.common.compose.files.getCurrentAndCollectFlow
import moe.styx.common.compose.http.login
import moe.styx.common.compose.utils.MpvPreferences
import moe.styx.common.compose.utils.ServerStatus
import moe.styx.common.data.MediaEntry
import moe.styx.common.extension.eqI
import moe.styx.common.json
import moe.styx.common.util.Log
actual class MediaPlayer actual constructor(initialEntryID: String, startAt: Long) : AMediaPlayer(initialEntryID, startAt) {
val observer by lazy {
object : MPVLib.EventObserver {
override fun event(@MPVLib.Event eventID: Int) {
val scope = CoroutineScope(Dispatchers.Main)
when (eventID) {
MPVLib.MPV_EVENT_SEEK -> {
scope.launch { playbackStatus.emit(PlaybackStatus.Seeking) }
}
MPVLib.MPV_EVENT_START_FILE -> {
if (!playerInitialized) {
initialCommands.forEach {
MPVLib.command(it)
}
}
}
MPVLib.MPV_EVENT_PLAYBACK_RESTART -> {
if (!playerInitialized) {
playerInitialized = true
MPVLib.setPropertyBoolean("pause", false)
}
}
else -> Unit
}
}
override fun eventProperty(p0: String) {}
override fun eventProperty(property: String, value: Long) {
val scope = CoroutineScope(Dispatchers.Main)
when (property) {
"time-pos" -> scope.launch { progress.emit(value) }
"duration" -> scope.launch { fileLength.emit(value) }
"demuxer-cache-time" -> scope.launch { cacheEnd.emit(value) }
else -> Log.d("MPV") { "Long property changed - $property: $value" }
}
}
override fun eventProperty(property: String, value: Double) {
when (property) {
"percent-pos" -> {
playbackPercent = value.toFloat()
}
else -> Log.d("MPV") { "Double property changed - $property: $value" }
}
}
override fun eventProperty(property: String, value: Boolean) {
val scope = CoroutineScope(Dispatchers.Main)
when (property) {
"pause" -> {
isPaused = value
if (playbackStatus.value !is PlaybackStatus.Buffering) {
scope.launch { if (value) playbackStatus.emit(PlaybackStatus.Paused) else playbackStatus.emit(PlaybackStatus.Playing) }
}
}
"paused-for-cache" -> {
if (playerInitialized)
scope.launch { if (value) playbackStatus.emit(PlaybackStatus.Buffering) else playbackStatus.emit(PlaybackStatus.Playing) }
}
"seeking" -> {
if (playbackStatus.value !is PlaybackStatus.Buffering) {
scope.launch {
if (value) playbackStatus.emit(PlaybackStatus.Seeking)
else playbackStatus.emit(if (isPaused) PlaybackStatus.Paused else PlaybackStatus.Playing)
}
}
}
else -> Log.d("MPV") { "Bool property changed - $property: $value" }
}
}
override fun eventProperty(property: String, value: String) {
val scope = CoroutineScope(Dispatchers.Main)
when (property) {
"media-title" -> scope.launch { mediaTitle.emit(value) }
"track-list" -> {
scope.launch {
runCatching {
trackList.emit(json.decodeFromString(value))
}.onFailure {
Log.e("MPV", it) { "Failed to parse track-list!" }
}
}
}
"chapter-list" -> {
scope.launch {
runCatching {
chapters.emit(json.decodeFromString(value))
}
}
}
else -> Log.d("MPV") { "String property changed - $property: $value" }
}
}
}
}
var playerInitialized = false
var libWasLoaded = false
var initialCommands: List<Array<String>> = emptyList()
override fun setPlaying(playing: Boolean) {
if (playerInitialized) {
MPVLib.setPropertyBoolean("pause", !playing)
}
}
override fun seek(position: Long) {
if (playerInitialized) {
MPVLib.command(arrayOf("set", "time-pos", "$position"))
}
}
override fun setSubtitleTrack(id: Int) {
if (playerInitialized && (playbackStatus.value in arrayOf(PlaybackStatus.Playing, PlaybackStatus.Paused))) {
MPVLib.command(arrayOf("set", "sub", "$id"))
}
}
override fun setAudioTrack(id: Int) {
if (playerInitialized && (playbackStatus.value in arrayOf(PlaybackStatus.Playing, PlaybackStatus.Paused))) {
MPVLib.command(arrayOf("set", "audio", "$id"))
}
}
override fun internalPlayEntry(mediaEntry: MediaEntry, scope: CoroutineScope) {
if (!playerInitialized)
return
MPVLib.command(arrayOf("set", "start", "0"))
initialCommands = emptyList()
scope.launch { currentEntry.emit(mediaEntry.GUID) }
}
@Composable
override fun PlayerComponent() {
val context = LocalContext.current
val entryList by Storage.stores.entryStore.getCurrentAndCollectFlow()
val curEntryID by this.currentEntry.collectAsState()
initialCommands = listOf(
arrayOf("set", "start", "$startAt"),
)
if (!playerInitialized && !libWasLoaded) {
MPVLib.create(context)
setMPVOptions()
MPVLib.init()
initObservers()
libWasLoaded = true
}
AndroidView(factory = { ctx ->
val view = SurfaceView(ctx)
view.holder.addCallback(surfaceHolder)
view
}, Modifier.fillMaxSize())
LaunchedEffect(curEntryID) {
val downloaded = Storage.stores.downloadedStore.getOrEmpty().find { it.entryID eqI curEntryID }
val currentEntry = entryList.find { it.GUID eqI curEntryID }
if ((ServerStatus.lastKnown == ServerStatus.UNKNOWN || login == null) && downloaded == null) {
MPVLib.command(
arrayOf(
"show-text",
"You do not have this episode downloaded and are not logged in.\nOr don't have a working connection...",
"5000"
)
)
return@LaunchedEffect
}
if (currentEntry != null) {
if (downloaded != null) {
MPVLib.command(arrayOf("loadfile", downloaded.path, "replace"))
} else {
MPVLib.command(arrayOf("loadfile", "${BuildConfig.BASE_URL}/watch/${currentEntry.GUID}?token=${login?.watchToken}", "replace"))
}
}
}
}
override fun releasePlayer() {
runCatching {
MPVLib.removeObserver(observer)
MPVLib.destroy()
}
}
private val surfaceHolder: SurfaceHolder.Callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
MPVLib.attachSurface(holder.surface)
MPVLib.setOptionString("force-window", "yes")
MPVLib.setOptionString("vo", MpvPreferences.getOrDefault().videoOutputDriver)
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int,
) {
MPVLib.setPropertyString("android-surface-size", "${width}x$height")
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
MPVLib.setOptionString("vo", "null")
MPVLib.setOptionString("force-window", "no")
MPVLib.detachSurface()
}
}
}
private fun MediaPlayer.initObservers() {
MPVLib.addObserver(observer)
arrayOf(
Property("track-list", MPVLib.MPV_FORMAT_STRING),
Property("chapter-list", MPVLib.MPV_FORMAT_STRING),
Property("paused-for-cache", MPVLib.MPV_FORMAT_FLAG),
Property("eof-reached", MPVLib.MPV_FORMAT_FLAG),
Property("seekable", MPVLib.MPV_FORMAT_FLAG),
Property("time-pos", MPVLib.MPV_FORMAT_INT64),
Property("percent-pos", MPVLib.MPV_FORMAT_DOUBLE),
Property("duration", MPVLib.MPV_FORMAT_INT64),
Property("pause", MPVLib.MPV_FORMAT_FLAG),
Property("seeking", MPVLib.MPV_FORMAT_FLAG),
Property("demuxer-cache-time", MPVLib.MPV_FORMAT_INT64),
Property("media-title", MPVLib.MPV_FORMAT_STRING)
).forEach { (name, format) ->
MPVLib.observeProperty(name, format)
}
}
private fun MediaPlayer.setMPVOptions() {
val pref = MpvPreferences.getOrDefault()
MPVLib.setOptionString("config", "no")
MPVLib.setOptionString("profile", pref.getPlatformProfile())
if (pref.profile == "normal") {
MPVLib.setOptionString("scale", "catmull_rom")
MPVLib.setOptionString("cscale", "bilinear")
MPVLib.setOptionString("dscale", "bilinear")
}
MPVLib.setOptionString("gpu-api", pref.gpuAPI)
MPVLib.setOptionString("gpu-context", "android")
MPVLib.setOptionString("opengl-es", "yes")
MPVLib.setOptionString("tls-verify", "no")
MPVLib.setOptionString("blend-subtitles", "yes")
MPVLib.setOptionString("cache", "yes")
MPVLib.setOptionString("demuxer-max-bytes", "50MiB")
MPVLib.setOptionString("demuxer-max-back-bytes", "32MiB")
MPVLib.setOptionString("force-window", "no")
MPVLib.setOptionString("keep-open", "always")
MPVLib.setOptionString("ytdl", "no")
MPVLib.setOptionString("save-position-on-quit", "no")
MPVLib.setOptionString("sub-font-provider", "none")
MPVLib.setOptionString("hwdec", if (pref.hwDecoding) (if (pref.alternativeHwDecode) "mediacodec" else "mediacodec-copy") else "no")
MPVLib.setOptionString("hwdec-codecs", "h264,hevc,mpeg4,mpeg2video,vp8,vp9,av1")
MPVLib.setOptionString("deband", if (pref.deband) "yes" else "no")
MPVLib.setOptionString("deband-iterations", pref.debandIterations)
MPVLib.setOptionString("dither-depth", if (pref.dither10bit) "10" else "8")
MPVLib.setOptionString("slang", pref.getSlangArg())
MPVLib.setOptionString("alang", pref.getAlangArg())
if (this.startAt != 0L) {
MPVLib.setOptionString("start", "$startAt")
}
}
data class Property(val name: String, @MPVLib.Format val format: Int)