forked from mpv-android/mpv-android
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MPVView.kt
422 lines (347 loc) · 15.6 KB
/
MPVView.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package `is`.xyz.mpv
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import `is`.xyz.mpv.MPVLib.mpvFormat.*
import android.os.Build
import android.os.Environment
import android.preference.PreferenceManager
import android.view.*
import kotlin.math.abs
import kotlin.reflect.KProperty
internal class MPVView(context: Context, attrs: AttributeSet) : SurfaceView(context, attrs), SurfaceHolder.Callback {
fun initialize(configDir: String) {
MPVLib.create(this.context)
MPVLib.setOptionString("config", "yes")
MPVLib.setOptionString("config-dir", configDir)
initOptions() // do this before init() so user-supplied config can override our choices
MPVLib.init()
// certain options are hardcoded:
MPVLib.setOptionString("save-position-on-quit", "no")
MPVLib.setOptionString("force-window", "no")
holder.addCallback(this)
observeProperties()
}
private fun initOptions() {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.context)
// hwdec
val hwdec = if (sharedPreferences.getBoolean("hardware_decoding", true))
"mediacodec-copy"
else
"no"
// vo: set display fps as reported by android
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val disp = wm.defaultDisplay
val refreshRate = disp.mode.refreshRate
Log.v(TAG, "Display ${disp.displayId} reports FPS of $refreshRate")
MPVLib.setOptionString("override-display-fps", refreshRate.toString())
} else {
Log.v(TAG, "Android version too old, disabling refresh rate functionality " +
"(${Build.VERSION.SDK_INT} < ${Build.VERSION_CODES.M})")
}
// set non-complex options
data class Property(val preference_name: String, val mpv_option: String)
val opts = arrayOf(
Property("default_audio_language", "alang"),
Property("default_subtitle_language", "slang"),
// vo-related
Property("video_scale", "scale"),
Property("video_scale_param1", "scale-param1"),
Property("video_scale_param2", "scale-param2"),
Property("video_downscale", "dscale"),
Property("video_downscale_param1", "dscale-param1"),
Property("video_downscale_param2", "dscale-param2"),
Property("video_tscale", "tscale"),
Property("video_tscale_param1", "tscale-param1"),
Property("video_tscale_param2", "tscale-param2")
)
for ((preference_name, mpv_option) in opts) {
val preference = sharedPreferences.getString(preference_name, "")
if (!preference.isNullOrBlank())
MPVLib.setOptionString(mpv_option, preference)
}
// set more options
val debandMode = sharedPreferences.getString("video_debanding", "")
if (debandMode == "gradfun") {
// lower the default radius (16) to improve performance
MPVLib.setOptionString("vf", "gradfun=radius=12")
} else if (debandMode == "gpu") {
MPVLib.setOptionString("deband", "yes")
}
val vidsync = sharedPreferences.getString("video_sync", resources.getString(R.string.pref_video_interpolation_sync_default))
MPVLib.setOptionString("video-sync", vidsync!!)
if (sharedPreferences.getBoolean("video_interpolation", false))
MPVLib.setOptionString("interpolation", "yes")
if (sharedPreferences.getBoolean("gpudebug", false))
MPVLib.setOptionString("gpu-debug", "yes")
if (sharedPreferences.getBoolean("video_fastdecode", false)) {
MPVLib.setOptionString("vd-lavc-fast", "yes")
MPVLib.setOptionString("vd-lavc-skiploopfilter", "nonkey")
}
MPVLib.setOptionString("vo", "gpu")
MPVLib.setOptionString("gpu-context", "android")
MPVLib.setOptionString("hwdec", hwdec)
MPVLib.setOptionString("hwdec-codecs", "h264,hevc,mpeg4,mpeg2video,vp8,vp9")
MPVLib.setOptionString("ao", "audiotrack,opensles")
MPVLib.setOptionString("tls-verify", "yes")
MPVLib.setOptionString("tls-ca-file", "${this.context.filesDir.path}/cacert.pem")
MPVLib.setOptionString("input-default-bindings", "yes")
// Limit demuxer cache to 32 MiB, the default is too high for mobile devices
MPVLib.setOptionString("demuxer-max-bytes", "${32 * 1024 * 1024}")
MPVLib.setOptionString("demuxer-max-back-bytes", "${32 * 1024 * 1024}")
val screenshotDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
screenshotDir.mkdirs()
MPVLib.setOptionString("screenshot-directory", screenshotDir.path)
}
fun playFile(filePath: String) {
this.filePath = filePath
}
// Called when back button is pressed, or app is shutting down
fun destroy() {
// Disable surface callbacks to avoid using unintialized mpv state
holder.removeCallback(this)
MPVLib.destroy()
}
fun onPointerEvent(event: MotionEvent): Boolean {
assert (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER))
if (event.actionMasked == MotionEvent.ACTION_SCROLL) {
val h = event.getAxisValue(MotionEvent.AXIS_HSCROLL)
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (abs(h) > 0)
MPVLib.command(arrayOf("keypress", if (h < 0) "WHEEL_LEFT" else "WHEEL_RIGHT"))
if (abs(v) > 0)
MPVLib.command(arrayOf("keypress", if (v < 0) "WHEEL_DOWN" else "WHEEL_UP"))
return true
}
return false
}
fun onKey(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_MULTIPLE)
return false
if (KeyEvent.isModifierKey(event.keyCode))
return false
var mapped = KeyMapping.map.get(event.keyCode)
if (mapped == null) {
// Fallback to produced glyph
if (!event.isPrintingKey) {
if (event.repeatCount == 0)
Log.d(TAG, "Unmapped non-printable key ${event.keyCode}")
return false
}
val ch = event.unicodeChar
if (ch.and(KeyCharacterMap.COMBINING_ACCENT) != 0)
return false // dead key
mapped = ch.toChar().toString()
}
if (event.repeatCount > 0)
return true // eat event but ignore it, mpv has its own key repeat
val mod: MutableList<String> = mutableListOf()
event.isShiftPressed && mod.add("shift")
event.isCtrlPressed && mod.add("ctrl")
event.isAltPressed && mod.add("alt")
event.isMetaPressed && mod.add("meta")
val action = if (event.action == KeyEvent.ACTION_DOWN) "keydown" else "keyup"
mod.add(mapped)
MPVLib.command(arrayOf(action, mod.joinToString("+")))
return true
}
private fun observeProperties() {
// This observes all properties needed by MPVView or MPVActivity
data class Property(val name: String, val format: Int)
val p = arrayOf(
Property("time-pos", MPV_FORMAT_INT64),
Property("duration", MPV_FORMAT_INT64),
Property("pause", MPV_FORMAT_FLAG),
Property("track-list", MPV_FORMAT_NONE),
Property("video-params", MPV_FORMAT_NONE),
Property("playlist-pos", MPV_FORMAT_NONE),
Property("playlist-count", MPV_FORMAT_NONE),
Property("video-format", MPV_FORMAT_NONE),
Property("media-title", MPV_FORMAT_STRING),
Property("metadata/by-key/Artist", MPV_FORMAT_STRING),
Property("metadata/by-key/Album", MPV_FORMAT_STRING)
)
for ((name, format) in p)
MPVLib.observeProperty(name, format)
}
fun addObserver(o: MPVLib.EventObserver) {
MPVLib.addObserver(o)
}
fun removeObserver(o: MPVLib.EventObserver) {
MPVLib.removeObserver(o)
}
data class Track(val mpvId: Int, val name: String)
var tracks = mapOf<String, MutableList<Track>>(
"audio" to arrayListOf(),
"video" to arrayListOf(),
"sub" to arrayListOf())
fun loadTracks() {
for (list in tracks.values) {
list.clear()
// pseudo-track to allow disabling audio/subs
list.add(Track(-1, context.getString(R.string.track_off)))
}
val count = MPVLib.getPropertyInt("track-list/count")!!
// Note that because events are async, properties might disappear at any moment
// so use ?: continue instead of !!
for (i in 0 until count) {
val type = MPVLib.getPropertyString("track-list/$i/type") ?: continue
if (!tracks.containsKey(type)) {
Log.w(TAG, "Got unknown track type: $type")
continue
}
val mpvId = MPVLib.getPropertyInt("track-list/$i/id") ?: continue
val lang = MPVLib.getPropertyString("track-list/$i/lang")
val title = MPVLib.getPropertyString("track-list/$i/title")
val trackName = if (!lang.isNullOrEmpty() && !title.isNullOrEmpty())
context.getString(R.string.ui_track_title_lang, mpvId, title, lang)
else if (!lang.isNullOrEmpty() || !title.isNullOrEmpty())
context.getString(R.string.ui_track_text, mpvId, (lang ?: "") + (title ?: ""))
else
context.getString(R.string.ui_track, mpvId)
tracks.getValue(type).add(Track(
mpvId=mpvId,
name=trackName
))
}
}
data class PlaylistItem(val index: Int, val filename: String, val title: String?)
fun loadPlaylist(): MutableList<PlaylistItem> {
val playlist = mutableListOf<PlaylistItem>()
val count = MPVLib.getPropertyInt("playlist-count")!!
for (i in 0 until count) {
val filename = MPVLib.getPropertyString("playlist/$i/filename")!!
val title = MPVLib.getPropertyString("playlist/$i/title")
playlist.add(PlaylistItem(index=i, filename=filename, title=title))
}
return playlist
}
data class Chapter(val index: Int, val title: String?, val time: Double)
fun loadChapters(): MutableList<Chapter> {
val chapters = mutableListOf<Chapter>()
val count = MPVLib.getPropertyInt("chapter-list/count")!!
for (i in 0 until count) {
val title = MPVLib.getPropertyString("chapter-list/$i/title")
val time = MPVLib.getPropertyDouble("chapter-list/$i/time")!!
chapters.add(Chapter(
index=i,
title=title,
time=time
))
}
return chapters
}
private var filePath: String? = null
// Property getters/setters
var paused: Boolean?
get() = MPVLib.getPropertyBoolean("pause")
set(paused) = MPVLib.setPropertyBoolean("pause", paused!!)
val duration: Int?
get() = MPVLib.getPropertyInt("duration")
var timePos: Int?
get() = MPVLib.getPropertyInt("time-pos")
set(progress) = MPVLib.setPropertyInt("time-pos", progress!!)
val hwdecActive: Boolean
get() = (MPVLib.getPropertyString("hwdec-current") ?: "no") != "no"
var playbackSpeed: Double?
get() = MPVLib.getPropertyDouble("speed")
set(speed) = MPVLib.setPropertyDouble("speed", speed!!)
val filename: String?
get() = MPVLib.getPropertyString("filename")
val avsync: String?
get() = MPVLib.getPropertyString("avsync")
val decoderFrameDropCount: Int?
get() = MPVLib.getPropertyInt("decoder-frame-drop-count")
val frameDropCount: Int?
get() = MPVLib.getPropertyInt("frame-drop-count")
val containerFps: Double?
get() = MPVLib.getPropertyDouble("container-fps")
val estimatedVfFps: Double?
get() = MPVLib.getPropertyDouble("estimated-vf-fps")
val videoW: Int?
get() = MPVLib.getPropertyInt("video-params/w")
val videoH: Int?
get() = MPVLib.getPropertyInt("video-params/h")
val videoAspect: Double?
get() = MPVLib.getPropertyDouble("video-params/aspect")
val videoCodec: String?
get() = MPVLib.getPropertyString("video-codec")
val audioCodec: String?
get() = MPVLib.getPropertyString("audio-codec")
val audioSampleRate: Int?
get() = MPVLib.getPropertyInt("audio-params/samplerate")
val audioChannels: Int?
get() = MPVLib.getPropertyInt("audio-params/channel-count")
class TrackDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
val v = MPVLib.getPropertyString(property.name)
// we can get null here for "no" or other invalid value
return v?.toIntOrNull() ?: -1
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
if (value == -1)
MPVLib.setPropertyString(property.name, "no")
else
MPVLib.setPropertyInt(property.name, value)
}
}
var vid: Int by TrackDelegate()
var sid: Int by TrackDelegate()
var aid: Int by TrackDelegate()
// Commands
fun cyclePause() = MPVLib.command(arrayOf("cycle", "pause"))
fun cycleAudio() = MPVLib.command(arrayOf("cycle", "audio"))
fun cycleSub() = MPVLib.command(arrayOf("cycle", "sub"))
fun cycleHwdec() = MPVLib.command(arrayOf("cycle-values", "hwdec", "mediacodec-copy", "no"))
fun cycleSpeed() {
val speeds = arrayOf(0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0)
val currentSpeed = playbackSpeed ?: 1.0
val index = speeds.indexOfFirst { it > currentSpeed }
playbackSpeed = speeds[if (index == -1) 0 else index]
}
fun getRepeat(): Int {
return when (MPVLib.getPropertyString("loop-playlist") +
MPVLib.getPropertyString("loop-file")) {
"noinf" -> 2
"infno" -> 1
else -> 0
}
}
fun cycleRepeat() {
val state = getRepeat()
when (state) {
0, 1 -> {
MPVLib.setPropertyString("loop-playlist", if (state == 1) "no" else "inf")
MPVLib.setPropertyString("loop-file", if (state == 1) "inf" else "no")
}
2 -> MPVLib.setPropertyString("loop-file", "no")
}
}
// Surface callbacks
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
MPVLib.setPropertyString("android-surface-size", "${width}x$height")
}
override fun surfaceCreated(holder: SurfaceHolder) {
Log.w(TAG, "attaching surface")
MPVLib.attachSurface(holder.surface)
// This forces mpv to render subs/osd/whatever into our surface even if it would ordinarily not
MPVLib.setOptionString("force-window", "yes")
if (filePath != null) {
MPVLib.command(arrayOf("loadfile", filePath as String))
filePath = null
} else {
// We disable video output when the context disappears, enable it back
MPVLib.setPropertyString("vo", "gpu")
}
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.w(TAG, "detaching surface")
MPVLib.setPropertyString("vo", "null")
MPVLib.setOptionString("force-window", "no")
MPVLib.detachSurface()
}
companion object {
private const val TAG = "mpv"
}
}