PlaylistManager.kt 27 KB
Newer Older
Geoffrey Métais's avatar
Geoffrey Métais committed
1
2
package org.videolan.vlc.media

3
import android.arch.lifecycle.MutableLiveData
Geoffrey Métais's avatar
Geoffrey Métais committed
4
5
6
7
import android.content.Intent
import android.net.Uri
import android.support.annotation.MainThread
import android.support.v4.content.LocalBroadcastManager
8
import android.support.v4.media.session.PlaybackStateCompat
9
import android.support.v7.preference.PreferenceManager
Geoffrey Métais's avatar
Geoffrey Métais committed
10
11
12
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
13
14
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.CoroutineStart
Geoffrey Métais's avatar
Geoffrey Métais committed
15
import kotlinx.coroutines.experimental.android.UI
16
17
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.withContext
Geoffrey Métais's avatar
Geoffrey Métais committed
18
19
import org.videolan.libvlc.Media
import org.videolan.libvlc.MediaPlayer
20
import org.videolan.libvlc.RendererItem
Geoffrey Métais's avatar
Geoffrey Métais committed
21
22
import org.videolan.medialibrary.Medialibrary
import org.videolan.medialibrary.media.MediaWrapper
23
24
25
26
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.PlaybackService
import org.videolan.vlc.R
import org.videolan.vlc.VLCApplication
Geoffrey Métais's avatar
Geoffrey Métais committed
27
28
29
30
31
32
import org.videolan.vlc.gui.preferences.PreferencesActivity
import org.videolan.vlc.gui.preferences.PreferencesFragment
import org.videolan.vlc.gui.video.VideoPlayerActivity
import org.videolan.vlc.util.*
import java.util.*

Geoffrey Métais's avatar
Geoffrey Métais committed
33
34
35
private const val TAG = "VLC/PlaylistManager"
private const val PREVIOUS_LIMIT_DELAY = 5000L
private const val AUDIO_REPEAT_MODE_KEY = "audio_repeat_mode"
Geoffrey Métais's avatar
Geoffrey Métais committed
36
37
38

class PlaylistManager(val service: PlaybackService) : MediaWrapperList.EventListener, Media.EventListener {

39
40
    companion object {
        val showAudioPlayer = MutableLiveData<Boolean>().apply { value = false }
41
42
        private val mediaList = MediaWrapperList()
        fun hasMedia() = mediaList.size() != 0
43
44
    }

Geoffrey Métais's avatar
Geoffrey Métais committed
45
46
    private val medialibrary by lazy(LazyThreadSafetyMode.NONE) { Medialibrary.getInstance() }
    val player by lazy(LazyThreadSafetyMode.NONE) { PlayerController() }
47
    private val settings by lazy(LazyThreadSafetyMode.NONE) { PreferenceManager.getDefaultSharedPreferences(service) }
Geoffrey Métais's avatar
Geoffrey Métais committed
48
49
50
51
52
53
54
55
    private val ctx by lazy(LazyThreadSafetyMode.NONE) { VLCApplication.getAppContext() }
    var currentIndex = -1
    private var nextIndex = -1
    private var prevIndex = -1
    private var previous = Stack<Int>()
    var repeating = Constants.REPEAT_NONE
    var shuffling = false
    var videoBackground = false
56
        private set
Geoffrey Métais's avatar
Geoffrey Métais committed
57
58
59
60
61
    var isBenchmark = false
    var isHardware = false
    private var parsed = false
    var savedTime = 0L
    private var random = Random(System.currentTimeMillis())
62
    private var newMedia = false
63
64
    @Volatile
    private var expanding = false
Geoffrey Métais's avatar
Geoffrey Métais committed
65
66
67
68
69
70
71
72
73

    fun hasCurrentMedia() = isValidPosition(currentIndex)

    fun hasPlaylist() = mediaList.size() > 1

    fun canShuffle() = mediaList.size() > 2

    fun isValidPosition(position: Int) = position in 0 until mediaList.size()

74
75
76
77
    init {
        if (settings.getBoolean("audio_save_repeat", false)) repeating = settings.getInt(AUDIO_REPEAT_MODE_KEY, Constants.REPEAT_NONE)
    }

Geoffrey Métais's avatar
Geoffrey Métais committed
78
79
80
81
82
83
84
85
86
87
88
    /**
     * Loads a selection of files (a non-user-supplied collection of media)
     * into the primary or "currently playing" playlist.
     *
     * @param mediaPathList A list of locations to load
     * @param position The position to start playing at
     */
    @MainThread
    fun loadLocations(mediaPathList: List<String>, position: Int) {
        val mediaList = ArrayList<MediaWrapper>()

89
        for (location in mediaPathList) {
Geoffrey Métais's avatar
Geoffrey Métais committed
90
            var mediaWrapper = medialibrary.getMedia(location)
91
            if (mediaWrapper === null) {
Geoffrey Métais's avatar
Geoffrey Métais committed
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
                if (!location.validateLocation()) {
                    Log.w(TAG, "Invalid location " + location)
                    service.showToast(service.resources.getString(R.string.invalid_location, location), Toast.LENGTH_SHORT)
                    continue
                }
                Log.v(TAG, "Creating on-the-fly Media object for " + location)
                mediaWrapper = MediaWrapper(Uri.parse(location))
            }
            mediaList.add(mediaWrapper)
        }
        load(mediaList, position)
    }

    fun load(list: List<MediaWrapper>, position: Int) {
        mediaList.removeEventListener(this)
        mediaList.clear()
        previous.clear()
        for (media in list) mediaList.add(media)
        if (!hasMedia()) {
            Log.w(TAG, "Warning: empty media list, nothing to play !")
            return
        }
        currentIndex = if (isValidPosition(position)) position else 0

        // Add handler after loading the list
        mediaList.addEventListener(this)
        playIndex(position)
        onPlaylistLoaded()
    }

    @Volatile
    private var loadingLastPlaylist = false
124
    fun loadLastPlaylist(type: Int = Constants.PLAYLIST_TYPE_AUDIO) : Boolean {
125
        if (loadingLastPlaylist) return true
Geoffrey Métais's avatar
Geoffrey Métais committed
126
        loadingLastPlaylist = true
127
128
129
130
131
132
133
134
135
136
137
        val audio = type == Constants.PLAYLIST_TYPE_AUDIO
        val currentMedia = settings.getString(if (audio) "current_song" else "current_media", "")
        if (currentMedia.isEmpty()) {
            loadingLastPlaylist = false
            return false
        }
        val locations = settings.getString(if (audio) "audio_list" else "media_list", "").split(" ".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
        if (Util.isArrayEmpty(locations)) {
            loadingLastPlaylist = false
            return false
        }
Geoffrey Métais's avatar
Geoffrey Métais committed
138
        launch(UI, CoroutineStart.UNDISPATCHED) {
139
            val playList = withContext(CommonPool) {
140
                locations.map { Uri.decode(it) }.mapTo(ArrayList(locations.size)) { MediaWrapper(Uri.parse(it)) }
141
            }
Geoffrey Métais's avatar
Geoffrey Métais committed
142
143
            // load playlist
            shuffling = settings.getBoolean(if (audio) "audio_shuffling" else "media_shuffling", false)
144
            repeating = settings.getInt(if (audio) "audio_repeating" else "media_repeating", Constants.REPEAT_NONE)
Geoffrey Métais's avatar
Geoffrey Métais committed
145
146
147
148
149
150
151
152
153
154
155
156
            val position = settings.getInt(if (audio) "position_in_audio_list" else "position_in_media_list", 0)
            savedTime = settings.getLong(if (audio) "position_in_song" else "position_in_media", -1)
            if (!audio) {
                if (position < playList.size && settings.getBoolean(PreferencesActivity.VIDEO_PAUSED, false)) {
                    playList[position].addFlags(MediaWrapper.MEDIA_PAUSED)
                }
                val rate = settings.getFloat(PreferencesActivity.VIDEO_SPEED, player.getRate())
                if (rate != 1.0f) player.setRate(rate, false)
            }
            load(playList, position)
            loadingLastPlaylist = false
        }
157
        return true
Geoffrey Métais's avatar
Geoffrey Métais committed
158
159
160
161
    }

    private fun onPlaylistLoaded() {
        service.onPlaylistLoaded()
162
163
        launch(UI, CoroutineStart.UNDISPATCHED) {
            determinePrevAndNextIndices()
164
            launch(VLCIO) { mediaList.updateWithMLMeta() }
165
        }
Geoffrey Métais's avatar
Geoffrey Métais committed
166
167
    }

Geoffrey Métais's avatar
Geoffrey Métais committed
168
169
170
    fun play() {
        if (hasMedia()) player.play()
    }
Geoffrey Métais's avatar
Geoffrey Métais committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184

    fun pause() {
        if (player.pause()) savePosition()
    }

    @MainThread
    fun next() {
        val size = mediaList.size()
        previous.push(currentIndex)
        currentIndex = nextIndex
        if (size == 0 || currentIndex < 0 || currentIndex >= size) {
            Log.w(TAG, "Warning: invalid next index, aborted !")
            //Close video player if started
            LocalBroadcastManager.getInstance(ctx).sendBroadcast(Intent(Constants.EXIT_PLAYER))
185
            stop()
Geoffrey Métais's avatar
Geoffrey Métais committed
186
187
188
189
190
191
192
            return
        }
        videoBackground = !player.isVideoPlaying() && player.canSwitchToVideo()
        playIndex(currentIndex)
    }

    fun stop(systemExit: Boolean = false) {
193
194
195
196
        if (hasCurrentMedia()) {
            savePosition()
            saveMediaMeta()
        }
Geoffrey Métais's avatar
Geoffrey Métais committed
197
198
199
200
201
        player.releaseMedia()
        mediaList.removeEventListener(this)
        previous.clear()
        currentIndex = -1
        mediaList.clear()
202
        if (systemExit) player.release()
Geoffrey Métais's avatar
Geoffrey Métais committed
203
        else player.restart()
204
        showAudioPlayer.value = false
205
        service.onPlaybackStopped(systemExit)
Geoffrey Métais's avatar
Geoffrey Métais committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    }

    @MainThread
    fun previous(force : Boolean) {
        if (hasPrevious() && currentIndex > 0 &&
                (force || !player.seekable || player.getTime() < PREVIOUS_LIMIT_DELAY)) {
            val size = mediaList.size()
            currentIndex = prevIndex
            if (previous.size > 0) previous.pop()
            if (size == 0 || prevIndex < 0 || currentIndex >= size) {
                Log.w(TAG, "Warning: invalid previous index, aborted !")
                player.stop()
                return
            }
            playIndex(currentIndex)
        } else player.setPosition(0F)
    }

    fun shuffle() {
        if (shuffling) previous.clear()
        shuffling = !shuffling
        savePosition()
228
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
229
230
231
232
    }

    fun setRepeatType(repeatType: Int) {
        repeating = repeatType
233
        if (isAudioList() && settings.getBoolean("audio_save_repeat", false))
Geoffrey Métais's avatar
Geoffrey Métais committed
234
235
            settings.edit().putInt(AUDIO_REPEAT_MODE_KEY, repeating).apply()
        savePosition()
236
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
237
238
    }

239
240
241
242
243
    fun setRenderer(item: RendererItem?) {
        player.setRenderer(item)
        showAudioPlayer.value = player.playbackState != PlaybackStateCompat.STATE_STOPPED && (item !== null || !player.isVideoPlaying())
    }

Geoffrey Métais's avatar
Geoffrey Métais committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    fun playIndex(index: Int, flags: Int = 0) {
        if (mediaList.size() == 0) {
            Log.w(TAG, "Warning: empty media list, nothing to play !")
            return
        }
        currentIndex = if (isValidPosition(index)) {
            index
        } else {
            Log.w(TAG, "Warning: index $index out of bounds")
            0
        }

        val mw = mediaList.getMedia(index) ?: return
        val isVideoPlaying = mw.type == MediaWrapper.TYPE_VIDEO && player.isVideoPlaying()
        if (!videoBackground && isVideoPlaying) mw.addFlags(MediaWrapper.MEDIA_VIDEO)
        if (videoBackground) mw.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
        parsed = false
        player.switchToVideo = false
        if (TextUtils.equals(mw.uri.scheme, "content")) MediaUtils.retrieveMediaTitle(mw)

264
265
266
        launch(UI, CoroutineStart.UNDISPATCHED) {
            if (mw.hasFlag(MediaWrapper.MEDIA_FORCE_AUDIO) && player.getAudioTracksCount() == 0) {
                determinePrevAndNextIndices(true)
267
                skipMedia()
268
269
            } else if (mw.type != MediaWrapper.TYPE_VIDEO || isVideoPlaying || player.hasRenderer
                    || mw.hasFlag(MediaWrapper.MEDIA_FORCE_AUDIO)) {
270
271
272
273
274
275
                val uri = FileUtils.getUri(mw.uri)
                if (uri == null) {
                    skipMedia()
                    return@launch
                }
                val media = Media(VLCInstance.get(), uri)
276
                setStartTime(media, mw)
277
278
279
280
281
282
283
284
285
                VLCOptions.setMediaOptions(media, ctx, flags or mw.flags)
                /* keeping only video during benchmark */
                if (isBenchmark) {
                    media.addOption(":no-audio")
                    media.addOption(":no-spu")
                    if (isHardware) {
                        media.addOption(":codec=mediacodec_ndk,mediacodec_jni,none")
                        isHardware = false
                    }
Geoffrey Métais's avatar
Geoffrey Métais committed
286
                }
287
                media.setEventListener(this@PlaylistManager)
288
                player.setSlaves(media, mw)
289
290
291
292
293
294
295
296
297
                player.startPlayback(media, mediaplayerEventListener)
                media.release()
                determinePrevAndNextIndices()
                service.onNewPlayback(mw)
                if (settings.getBoolean(PreferencesFragment.PLAYBACK_HISTORY, true)) launch {
                    var id = mw.id
                    if (id == 0L) {
                        var internalMedia = medialibrary.findMedia(mw)
                        if (internalMedia != null && internalMedia.id != 0L)
Geoffrey Métais's avatar
Geoffrey Métais committed
298
                            id = internalMedia.id
299
                        else {
300
                            internalMedia = medialibrary.addMedia(Uri.decode(mw.uri.toString()))
301
302
303
                            if (internalMedia != null)
                                id = internalMedia.id
                        }
Geoffrey Métais's avatar
Geoffrey Métais committed
304
                    }
305
                    medialibrary.increasePlayCount(id)
Geoffrey Métais's avatar
Geoffrey Métais committed
306
                }
307
308
                saveCurrentMedia()
                newMedia = true
309
310
311
            } else { //Start VideoPlayer for first video, it will trigger playIndex when ready.
                player.stop()
                VideoPlayerActivity.startOpened(ctx, mw.uri, currentIndex)
Geoffrey Métais's avatar
Geoffrey Métais committed
312
313
314
315
            }
        }
    }

316
317
318
319
320
    private fun skipMedia() {
        if (currentIndex != nextIndex) next()
        else stop(false)
    }

Geoffrey Métais's avatar
Geoffrey Métais committed
321
322
323
324
325
326
327
328
329
    fun onServiceDestroyed() {
        player.release()
    }

    @MainThread
    fun switchToVideo(): Boolean {
        val media = getCurrentMedia()
        if (media === null || media.hasFlag(MediaWrapper.MEDIA_FORCE_AUDIO) || !player.canSwitchToVideo())
            return false
330
        val hasRenderer = player.hasRenderer
Geoffrey Métais's avatar
Geoffrey Métais committed
331
        videoBackground = false
332
        if (player.isVideoPlaying() && !hasRenderer) {//Player is already running, just send it an intent
Geoffrey Métais's avatar
Geoffrey Métais committed
333
334
335
336
            player.setVideoTrackEnabled(true)
            LocalBroadcastManager.getInstance(service).sendBroadcast(
                    VideoPlayerActivity.getIntent(Constants.PLAY_FROM_SERVICE,
                            media, false, currentIndex))
337
        } else if (!player.switchToVideo) { //Start the video player
338
            VideoPlayerActivity.startOpened(VLCApplication.getAppContext(), media.uri, currentIndex)
339
            if (!hasRenderer) player.switchToVideo = true
Geoffrey Métais's avatar
Geoffrey Métais committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        }
        return true
    }

    fun setVideoTrackEnabled(enabled: Boolean) {
        if (!hasMedia() || !player.isPlaying()) return
        if (enabled) getCurrentMedia()?.addFlags(MediaWrapper.MEDIA_VIDEO)
        else getCurrentMedia()?.removeFlags(MediaWrapper.MEDIA_VIDEO)
        player.setVideoTrackEnabled(enabled)
    }

    fun hasPrevious() = prevIndex != -1

    fun hasNext() = nextIndex != -1

    override fun onItemAdded(index: Int, mrl: String?) {
        if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemAdded")
357
358
359
360
361
362
        if (currentIndex >= index && !expanding) ++currentIndex
        launch(UI, CoroutineStart.UNDISPATCHED) {
            determinePrevAndNextIndices()
            executeUpdate()
            saveMediaList()
        }
Geoffrey Métais's avatar
Geoffrey Métais committed
363
364
365
366
    }

    override fun onItemRemoved(index: Int, mrl: String?) {
        if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemDeleted")
367
        val currentRemoved = currentIndex == index
368
369
370
        if (currentIndex >= index && !expanding) --currentIndex
        launch(UI, CoroutineStart.UNDISPATCHED) {
            determinePrevAndNextIndices()
371
            if (currentRemoved && !expanding) {
372
373
374
375
376
                when {
                    nextIndex != -1 -> next()
                    currentIndex != -1 -> playIndex(currentIndex, 0)
                    else -> stop()
                }
Geoffrey Métais's avatar
Geoffrey Métais committed
377
            }
378
379
            executeUpdate()
            saveMediaList()
Geoffrey Métais's avatar
Geoffrey Métais committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
        }
    }

    private fun executeUpdate() {
        service.executeUpdate()
    }

    fun saveMediaMeta() {
        val media = medialibrary.findMedia(getCurrentMedia())
        if (media === null || media.id == 0L) return
        val canSwitchToVideo = player.canSwitchToVideo()
        if (media.type == MediaWrapper.TYPE_VIDEO || canSwitchToVideo || media.isPodcast) {
            //Save progress
            val time = player.getTime()
Geoffrey Métais's avatar
Geoffrey Métais committed
394
            val length = player.length
Geoffrey Métais's avatar
Geoffrey Métais committed
395
396
397
398
399
400
401
402
            var progress = time / length.toFloat()
            if (progress > 0.95f || length - time < 10000) {
                //increase seen counter if more than 95% of the media have been seen
                //and reset progress to 0
                media.setLongMeta(MediaWrapper.META_SEEN, ++media.seen)
                progress = 0f
            }
            media.time = if (progress == 0f) 0L else time
403
            media.setLongMeta(MediaWrapper.META_PROGRESS, media.time)
Geoffrey Métais's avatar
Geoffrey Métais committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
        }
        if (canSwitchToVideo) {
            //Save audio delay
            if (settings.getBoolean("save_individual_audio_delay", false))
                media.setLongMeta(MediaWrapper.META_AUDIODELAY, player.getAudioDelay())
            media.setLongMeta(MediaWrapper.META_SUBTITLE_DELAY, player.getSpuDelay())
            media.setLongMeta(MediaWrapper.META_SUBTITLE_TRACK, player.getSpuTrack().toLong())
        }
    }

    private fun loadMediaMeta(media: MediaWrapper) {
        if (media.id == 0L) return
        if (player.canSwitchToVideo()) {
            if (settings.getBoolean("save_individual_audio_delay", false))
                player.setAudioDelay(media.getMetaLong(MediaWrapper.META_AUDIODELAY))
            player.setSpuTrack(media.getMetaLong(MediaWrapper.META_SUBTITLE_TRACK).toInt())
            player.setSpuDelay(media.getMetaLong(MediaWrapper.META_SUBTITLE_DELAY))
        }
    }

    @Synchronized
425
    private fun saveCurrentMedia() {
Geoffrey Métais's avatar
Geoffrey Métais committed
426
        settings.edit()
427
                .putString(if (isAudioList()) "current_song" else "current_media", mediaList.getMRL(Math.max(currentIndex, 0)))
Geoffrey Métais's avatar
Geoffrey Métais committed
428
429
430
431
432
                .apply()
    }

    @Synchronized
    private fun saveMediaList() {
433
        if (getCurrentMedia() === null) return
Geoffrey Métais's avatar
Geoffrey Métais committed
434
        val locations = StringBuilder()
435
        for (mw in mediaList.all) locations.append(" ").append(Uri.encode(Uri.decode(mw.uri.toString())))
Geoffrey Métais's avatar
Geoffrey Métais committed
436
437
        //We save a concatenated String because putStringSet is APIv11.
        settings.edit()
438
                .putString(if (!isAudioList()) "media_list" else "audio_list", locations.toString().trim { it <= ' ' })
Geoffrey Métais's avatar
Geoffrey Métais committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
                .apply()
    }

    override fun onItemMoved(indexBefore: Int, indexAfter: Int, mrl: String?) {
        if (BuildConfig.DEBUG) Log.i(TAG, "CustomMediaListItemMoved")
        if (currentIndex == indexBefore) {
            currentIndex = indexAfter
            if (indexAfter > indexBefore)
                --currentIndex
        } else if (currentIndex in indexAfter..(indexBefore - 1))
            ++currentIndex
        else if (currentIndex in (indexBefore + 1)..(indexAfter - 1))
            --currentIndex

        // If we are in random mode, we completely reset the stored previous track
        // as their indices changed.
        previous.clear()
456
457
458
459
460
        launch(UI, CoroutineStart.UNDISPATCHED) {
            determinePrevAndNextIndices()
            executeUpdate()
            saveMediaList()
        }
Geoffrey Métais's avatar
Geoffrey Métais committed
461
462
    }

463
    private suspend fun determinePrevAndNextIndices(expand: Boolean = false) {
Geoffrey Métais's avatar
Geoffrey Métais committed
464
465
        val media = getCurrentMedia()
        if (expand && media !== null) {
466
            expanding = true
Geoffrey Métais's avatar
Geoffrey Métais committed
467
            nextIndex = expand(media.type == MediaWrapper.TYPE_STREAM)
468
            expanding = false
Geoffrey Métais's avatar
Geoffrey Métais committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
        } else {
            nextIndex = -1
        }
        prevIndex = -1

        if (nextIndex == -1) {
            // No subitems; play the next item.
            val size = mediaList.size()
            shuffling = shuffling and (size > 2)

            // Repeating once doesn't change the index
            if (repeating == Constants.REPEAT_ONE) {
                nextIndex = currentIndex
                prevIndex = nextIndex
            } else {
                if (shuffling) {
                    if (!previous.isEmpty()) {
                        prevIndex = previous.peek()
                        while (!isValidPosition(prevIndex)) {
                            previous.removeAt(previous.size - 1)
                            if (previous.isEmpty()) {
                                prevIndex = -1
                                break
                            }
                            prevIndex = previous.peek()
                        }
                    }
                    // If we've played all songs already in shuffle, then either
                    // reshuffle or stop (depending on RepeatType).
                    if (previous.size + 1 == size) {
                        if (repeating == Constants.REPEAT_NONE) {
                            nextIndex = -1
                            return
                        } else {
                            previous.clear()
                            random = Random(System.currentTimeMillis())
                        }
                    }
                    random = Random(System.currentTimeMillis())
                    // Find a new index not in previous.
                    do {
                        nextIndex = random.nextInt(size)
                    } while (nextIndex == currentIndex || previous.contains(nextIndex))

                } else {
                    // normal playback
                    if (currentIndex > 0)
                        prevIndex = currentIndex - 1
                    nextIndex = when {
                        currentIndex + 1 < size -> currentIndex + 1
                        repeating == Constants.REPEAT_NONE -> -1
                        else -> 0
                    }
                }
            }
        }
    }

    /**
     * Expand the current media.
     * @return the index of the media was expanded, and -1 if no media was expanded
     */
    @MainThread
532
    private suspend fun expand(updateHistory: Boolean): Int {
533
        val index = currentIndex
534
        val ml = player.expand()
Geoffrey Métais's avatar
Geoffrey Métais committed
535
536
        var ret = -1

537
        if (ml != null && ml.count > 0) {
538
            val mrl = if (updateHistory) getCurrentMedia()?.location else null
539
            mediaList.remove(index)
Geoffrey Métais's avatar
Geoffrey Métais committed
540
541
542
            for (i in ml.count - 1 downTo 0) {
                val child = ml.getMediaAt(i)
                child.parse()
543
                mediaList.insert(index, MediaWrapper(child))
Geoffrey Métais's avatar
Geoffrey Métais committed
544
545
                child.release()
            }
546
            if (mrl !== null && ml.count == 1) medialibrary.addToHistory(mrl, getCurrentMedia()!!.title)
547
            ret = index
Geoffrey Métais's avatar
Geoffrey Métais committed
548
        }
549
        ml?.release()
Geoffrey Métais's avatar
Geoffrey Métais committed
550
551
552
553
554
555
556
557
558
559
560
        return ret
    }

    fun getCurrentMedia() = mediaList.getMedia(currentIndex)

    fun getPrevMedia() = if (isValidPosition(prevIndex)) mediaList.getMedia(prevIndex) else null

    fun getNextMedia() = if (isValidPosition(nextIndex)) mediaList.getMedia(nextIndex) else null

    fun getMedia(position: Int) = mediaList.getMedia(position)

561
562
563
    private suspend fun setStartTime(media: Media, mw: MediaWrapper) {
        if (savedTime <= 0L ) {
            if (mw.time >= 0L) savedTime = mw.time
564
            else if (mw.time == 0L && mw.type == MediaWrapper.TYPE_VIDEO || mw.isPodcast) savedTime = withContext(VLCIO) { medialibrary.findMedia(mw).getMetaLong(MediaWrapper.META_PROGRESS) }
565

Geoffrey Métais's avatar
Geoffrey Métais committed
566
        }
567
568
569
570
        if (savedTime <= 0L) return
        val mediaLength = mw.length
        if (mediaLength > 0 && savedTime < 0.95 * mediaLength) media.addOption(":start-time=${savedTime/1000L}")
        savedTime = 0L
Geoffrey Métais's avatar
Geoffrey Métais committed
571
572
573
574
575
576
    }

    @Synchronized
    private fun savePosition(reset: Boolean = false) {
        if (!hasMedia()) return
        val editor = settings.edit()
577
        val audio = isAudioList()
Geoffrey Métais's avatar
Geoffrey Métais committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
        editor.putBoolean(if (audio) "audio_shuffling" else "media_shuffling", shuffling)
        editor.putInt(if (audio) "audio_repeating" else "media_repeating", repeating)
        editor.putInt(if (audio) "position_in_audio_list" else "position_in_media_list", if (reset) 0 else currentIndex)
        editor.putLong(if (audio) "position_in_song" else "position_in_media", if (reset) 0L else player.getTime())
        if (!audio) {
            editor.putBoolean(PreferencesActivity.VIDEO_PAUSED, !player.isPlaying())
            editor.putFloat(PreferencesActivity.VIDEO_SPEED, player.getRate())
        }
        editor.apply()
    }

    /**
     * Append to the current existing playlist
     */
    fun append(list: List<MediaWrapper>) {
        if (!hasCurrentMedia()) {
            load(list, 0)
            return
        }
        for (media in list) mediaList.add(media)
    }

    /**
     * Insert into the current existing playlist
     */

    fun insertNext(list: List<MediaWrapper>) {
        if (!hasCurrentMedia()) {
            load(list, 0)
            return
        }

        val startIndex = currentIndex + 1

612
        for ((index, mw) in list.withIndex()) mediaList.insert(startIndex + index, mw)
Geoffrey Métais's avatar
Geoffrey Métais committed
613
614
615
616
617
618
619
    }

    /**
     * Move an item inside the playlist.
     */
    fun moveItem(positionStart: Int, positionEnd: Int) {
        mediaList.move(positionStart, positionEnd)
620
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
621
622
623
624
    }

    fun insertItem(position: Int, mw: MediaWrapper) {
        mediaList.insert(position, mw)
625
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
626
627
628
629
630
    }


    fun remove(position: Int) {
        mediaList.remove(position)
631
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
632
633
634
635
    }

    fun removeLocation(location: String) {
        mediaList.remove(location)
636
        launch(UI, CoroutineStart.UNDISPATCHED) { determinePrevAndNextIndices() }
Geoffrey Métais's avatar
Geoffrey Métais committed
637
638
639
640
    }

    fun getMediaListSize()= mediaList.size()

641
    fun getMediaList(): MutableList<MediaWrapper> = mediaList.all
Geoffrey Métais's avatar
Geoffrey Métais committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672

    override fun onEvent(event: Media.Event) {
        var update = true
        when (event.type) {
            Media.Event.MetaChanged -> {
                /* Update Meta if file is already parsed */
                if (parsed && player.updateCurrentMeta(event.metaId, getCurrentMedia())) service.executeUpdate()
                if (BuildConfig.DEBUG) Log.i(MediaDatabase.TAG, "Media.Event.MetaChanged: " + event.metaId)
            }
            Media.Event.ParsedChanged -> {
                if (BuildConfig.DEBUG) Log.i(MediaDatabase.TAG, "Media.Event.ParsedChanged")
                player.updateCurrentMeta(-1, getCurrentMedia())
                parsed = true
            }
            else -> update = false
        }
        if (update) {
            service.onMediaEvent(event)
            if (parsed) service.showNotification()
        }
    }

    private val mediaplayerEventListener = MediaPlayer.EventListener { event ->
        when (event.type) {
            MediaPlayer.Event.Playing -> {
                medialibrary.pauseBackgroundOperations()
                videoBackground = false
                val mw = medialibrary.findMedia(getCurrentMedia())
                if (newMedia) {
                    loadMediaMeta(mw)
                    if (mw.type == MediaWrapper.TYPE_STREAM) medialibrary.addToHistory(mw.location, mw.title)
673
674
675
                    saveMediaList()
                    savePosition(true)
                    saveCurrentMedia()
676
                    newMedia = false
677
                    if (player.hasRenderer|| !player.isVideoPlaying()) showAudioPlayer.value = true
Geoffrey Métais's avatar
Geoffrey Métais committed
678
679
680
681
682
                }
            }
            MediaPlayer.Event.Paused -> medialibrary.resumeBackgroundOperations()
            MediaPlayer.Event.EndReached -> {
                saveMediaMeta()
683
                if (isBenchmark) player.setPreviousStats()
684
685
686
687
688
                launch(UI, CoroutineStart.UNDISPATCHED) {
                    determinePrevAndNextIndices(true)
                    if (nextIndex == -1) savePosition(true)
                    next()
                }
Geoffrey Métais's avatar
Geoffrey Métais committed
689
            }
Geoffrey Métais's avatar
Geoffrey Métais committed
690
691
            MediaPlayer.Event.EncounteredError -> {
                service.showToast(service.getString(
692
693
                        R.string.invalid_location,
                        getCurrentMedia()?.getLocation() ?: ""), Toast.LENGTH_SHORT)
694
                if (currentIndex != nextIndex) next() else stop(true)
Geoffrey Métais's avatar
Geoffrey Métais committed
695
            }
Geoffrey Métais's avatar
Geoffrey Métais committed
696
697
698
        }
        service.onMediaPlayerEvent(event)
    }
Geoffrey Métais's avatar
Geoffrey Métais committed
699

700
    private fun isAudioList() = !player.canSwitchToVideo() && mediaList.isAudioList
Geoffrey Métais's avatar
Geoffrey Métais committed
701
}