forked from doublesymmetry/react-native-track-player
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMusicService.kt
1213 lines (1073 loc) · 45.4 KB
/
MusicService.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.doublesymmetry.trackplayer.service
import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.Bitmap
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.view.KeyEvent
import androidx.annotation.MainThread
import androidx.annotation.OptIn
import androidx.core.app.NotificationCompat
import androidx.media.utils.MediaConstants
import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.CacheBitmapLoader
import androidx.media3.session.LibraryResult
import androidx.media3.common.MediaItem
import androidx.media3.common.util.BitmapLoader
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.CommandButton
import androidx.media3.session.MediaSession
import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionCommands
import androidx.media3.session.SessionResult
import com.lovegaoshi.kotlinaudio.models.*
import com.lovegaoshi.kotlinaudio.player.QueuedAudioPlayer
import com.doublesymmetry.trackplayer.HeadlessJsMediaService
import com.doublesymmetry.trackplayer.extensions.NumberExt.Companion.toMilliseconds
import com.doublesymmetry.trackplayer.extensions.NumberExt.Companion.toSeconds
import com.doublesymmetry.trackplayer.extensions.asLibState
import com.doublesymmetry.trackplayer.extensions.find
import com.doublesymmetry.trackplayer.model.MetadataAdapter
import com.doublesymmetry.trackplayer.model.PlaybackMetadata
import com.doublesymmetry.trackplayer.model.Track
import com.doublesymmetry.trackplayer.model.TrackAudioItem
import com.doublesymmetry.trackplayer.module.MusicEvents
import com.doublesymmetry.trackplayer.module.MusicEvents.Companion.METADATA_PAYLOAD_KEY
import com.doublesymmetry.trackplayer.R as TrackPlayerR
import com.doublesymmetry.trackplayer.utils.BundleUtils
import com.doublesymmetry.trackplayer.utils.BundleUtils.setRating
import com.doublesymmetry.trackplayer.utils.CoilBitmapLoader
import com.doublesymmetry.trackplayer.utils.buildMediaItem
import com.facebook.react.bridge.Arguments
import com.facebook.react.jstasks.HeadlessJsTaskConfig
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.flow
import timber.log.Timber
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess
@OptIn(UnstableApi::class)
@MainThread
class MusicService : HeadlessJsMediaService() {
private lateinit var player: QueuedAudioPlayer
private val binder = MusicBinder()
private val scope = MainScope()
private lateinit var fakePlayer: ExoPlayer
private lateinit var mediaSession: MediaLibrarySession
private var progressUpdateJob: Job? = null
var mediaTree: Map<String, List<MediaItem>> = HashMap()
var mediaTreeStyle: List<Int> = listOf(
MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM,
MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM)
private var sessionCommands: SessionCommands? = null
private var playerCommands: Player.Commands? = null
private var customLayout: List<CommandButton> = listOf()
private var lastWake: Long = 0
var onStartCommandIntentValid: Boolean = true
fun crossFadePrepare(previous: Boolean = false) { player.crossFadePrepare(previous) }
fun switchExoPlayer(
fadeDuration: Long = 2500,
fadeInterval: Long = 20,
fadeToVolume: Float = 1f
) {
player.switchExoPlayer(
fadeDuration = fadeDuration,
fadeInterval = fadeInterval,
fadeToVolume = fadeToVolume)
emitPlaybackTrackChangedEvents(null, null, 0.0)
}
fun acquireWakeLock() { acquireWakeLockNow(this) }
fun abandonWakeLock() { sWakeLock?.release() }
fun getBitmapLoader(): BitmapLoader {
return mediaSession.bitmapLoader
}
fun getCurrentBitmap(): ListenableFuture<Bitmap>? {
return player.exoPlayer.currentMediaItem?.mediaMetadata?.let {
mediaSession.bitmapLoader.loadBitmapFromMetadata(
it
)
}
}
@ExperimentalCoroutinesApi
override fun onCreate() {
Timber.plant(Timber.DebugTree())
Timber.tag("APM").d("RNTP musicservice created.")
fakePlayer = ExoPlayer.Builder(this).build()
val openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
// Add the Uri data so apps can identify that it was a notification click
data = Uri.parse("trackplayer://notification.click")
action = Intent.ACTION_VIEW
}
mediaSession = MediaLibrarySession.Builder(this, fakePlayer, APMMediaSessionCallback() )
.setBitmapLoader(CacheBitmapLoader(CoilBitmapLoader(this)))
// https://github.com/androidx/media/issues/1218
.setSessionActivity(PendingIntent.getActivity(this, 0, openAppIntent, getPendingIntentFlags()))
.build()
super.onCreate()
}
/**
* Use [appKilledPlaybackBehavior] instead.
*/
@Deprecated("This will be removed soon")
var stoppingAppPausesPlayback = true
private set
enum class AppKilledPlaybackBehavior(val string: String) {
CONTINUE_PLAYBACK("continue-playback"),
PAUSE_PLAYBACK("pause-playback"),
STOP_PLAYBACK_AND_REMOVE_NOTIFICATION("stop-playback-and-remove-notification")
}
private var appKilledPlaybackBehavior = AppKilledPlaybackBehavior.STOP_PLAYBACK_AND_REMOVE_NOTIFICATION
private var stopForegroundGracePeriod: Int = DEFAULT_STOP_FOREGROUND_GRACE_PERIOD
val tracks: List<Track>
get() = player.items.map { (it as TrackAudioItem).track }
val currentTrack: Track
get() {
return try {
(player.currentItem as TrackAudioItem).track
} catch (e: Exception) {
Track(this, Bundle(), 0)
}
}
val state
get() = player.playerState
val playbackError
get() = player.playbackError
val event
get() = player.playerEventHolder
var playWhenReady: Boolean
get() = player.playWhenReady
set(value) {
player.playWhenReady = value
}
private var latestOptions: Bundle? = null
private var compactCapabilities: List<Capability> = emptyList()
private var commandStarted = false
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
onStartCommandIntentValid = intent != null
Timber.tag("APM").d("onStartCommand: ${intent?.action}, ${intent?.`package`}")
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
// HACK: this is not supposed to be here. I definitely screwed up. but Why?
onMediaKeyEvent(intent)
}
// HACK: Why is onPlay triggering onStartCommand??
if (!commandStarted) {
commandStarted = true
super.onStartCommand(intent, flags, startId)
}
return START_STICKY
}
@MainThread
fun setupPlayer(playerOptions: Bundle?) {
if (this::player.isInitialized) {
print("Player was initialized. Prevent re-initializing again")
return
}
Timber.tag("APM").d("RNTP musicservice set up")
val mPlayerOptions = PlayerOptions(
crossfade = playerOptions?.getBoolean(CROSSFADE, false) ?: false,
cacheSize = playerOptions?.getDouble(MAX_CACHE_SIZE_KEY)?.toLong() ?: 0,
audioContentType = when(playerOptions?.getString(ANDROID_AUDIO_CONTENT_TYPE)) {
"music" -> C.AUDIO_CONTENT_TYPE_MUSIC
"speech" -> C.AUDIO_CONTENT_TYPE_SPEECH
"sonification" -> C.AUDIO_CONTENT_TYPE_SONIFICATION
"movie" -> C.AUDIO_CONTENT_TYPE_MOVIE
"unknown" -> C.AUDIO_CONTENT_TYPE_UNKNOWN
else -> C.AUDIO_CONTENT_TYPE_MUSIC
},
wakeMode = playerOptions?.getInt(WAKE_MODE, 0) ?: 0,
handleAudioBecomingNoisy = playerOptions?.getBoolean(HANDLE_NOISY, true) ?: true,
alwaysShowNext = playerOptions?.getBoolean(ALWAYS_SHOW_NEXT, true) ?: true,
handleAudioFocus = playerOptions?.getBoolean(AUTO_HANDLE_INTERRUPTIONS) ?: true,
bufferOptions = BufferOptions(
playerOptions?.getDouble(MIN_BUFFER_KEY)?.toMilliseconds()?.toInt(),
playerOptions?.getDouble(MAX_BUFFER_KEY)?.toMilliseconds()?.toInt(),
playerOptions?.getDouble(PLAY_BUFFER_KEY)?.toMilliseconds()?.toInt(),
playerOptions?.getDouble(BACK_BUFFER_KEY)?.toMilliseconds()?.toInt(),
),
skipSilence = playerOptions?.getBoolean(SKIP_SILENCE) ?: false
)
player = QueuedAudioPlayer(this@MusicService, mPlayerOptions)
fakePlayer.release()
mediaSession.player = player.player
observeEvents()
}
@MainThread
fun updateOptions(options: Bundle) {
latestOptions = options
val androidOptions = options.getBundle(ANDROID_OPTIONS_KEY)
if (androidOptions?.containsKey(PARSE_EMBEDDED_ARTWORK) == true) {
player.parseEmbeddedArtwork = androidOptions.getBoolean(PARSE_EMBEDDED_ARTWORK)
}
if (androidOptions?.containsKey(AUDIO_OFFLOAD_KEY) == true) {
player.setAudioOffload(androidOptions.getBoolean(AUDIO_OFFLOAD_KEY))
}
if (androidOptions?.containsKey(SKIP_SILENCE) == true) {
player.skipSilence = androidOptions.getBoolean(SKIP_SILENCE)
}
appKilledPlaybackBehavior =
AppKilledPlaybackBehavior::string.find(androidOptions?.getString(APP_KILLED_PLAYBACK_BEHAVIOR_KEY)) ?:
AppKilledPlaybackBehavior.CONTINUE_PLAYBACK
BundleUtils.getIntOrNull(androidOptions, STOP_FOREGROUND_GRACE_PERIOD_KEY)?.let { stopForegroundGracePeriod = it }
// TODO: This handles a deprecated flag. Should be removed soon.
options.getBoolean(STOPPING_APP_PAUSES_PLAYBACK_KEY).let {
stoppingAppPausesPlayback = options.getBoolean(STOPPING_APP_PAUSES_PLAYBACK_KEY)
if (stoppingAppPausesPlayback) {
appKilledPlaybackBehavior = AppKilledPlaybackBehavior.PAUSE_PLAYBACK
}
}
player.alwaysPauseOnInterruption = androidOptions?.getBoolean(PAUSE_ON_INTERRUPTION_KEY) ?: false
player.shuffleMode = androidOptions?.getBoolean(SHUFFLE_KEY) ?: false
// setup progress update events if configured
progressUpdateJob?.cancel()
val updateInterval = BundleUtils.getDoubleOrNull(options, PROGRESS_UPDATE_EVENT_INTERVAL_KEY)
if (updateInterval != null && updateInterval > 0) {
progressUpdateJob = scope.launch {
progressUpdateEventFlow(updateInterval).collect { emit(MusicEvents.PLAYBACK_PROGRESS_UPDATED, it) }
}
}
val capabilities = options.getIntegerArrayList("capabilities")?.map { Capability.entries[it] } ?: emptyList()
var notificationCapabilities = options.getIntegerArrayList("notificationCapabilities")?.map { Capability.entries[it] } ?: emptyList()
compactCapabilities = options.getIntegerArrayList("compactCapabilities")?.map { Capability.entries[it] } ?: emptyList()
val customActions = options.getBundle(CUSTOM_ACTIONS_KEY)
val customActionsList = customActions?.getStringArrayList(CUSTOM_ACTIONS_LIST_KEY)
if (notificationCapabilities.isEmpty()) notificationCapabilities = capabilities
val playerCommandsBuilder = Player.Commands.Builder().addAll(
// HACK: without COMMAND_GET_CURRENT_MEDIA_ITEM, notification cannot be created
Player.COMMAND_GET_CURRENT_MEDIA_ITEM,
Player.COMMAND_GET_TRACKS,
Player.COMMAND_GET_TIMELINE,
Player.COMMAND_GET_METADATA,
Player.COMMAND_GET_AUDIO_ATTRIBUTES,
Player.COMMAND_GET_VOLUME,
Player.COMMAND_GET_DEVICE_VOLUME,
Player.COMMAND_GET_TEXT,
Player.COMMAND_SEEK_TO_MEDIA_ITEM,
Player.COMMAND_SET_MEDIA_ITEM,
Player.COMMAND_PREPARE,
Player.COMMAND_RELEASE,
)
notificationCapabilities.forEach {
when (it) {
Capability.PLAY, Capability.PAUSE -> {
playerCommandsBuilder.add(Player.COMMAND_PLAY_PAUSE)
}
Capability.STOP -> {
playerCommandsBuilder.add(Player.COMMAND_STOP)
}
Capability.SKIP_TO_NEXT -> {
playerCommandsBuilder.add(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)
playerCommandsBuilder.add(Player.COMMAND_SEEK_TO_NEXT)
}
Capability.SKIP_TO_PREVIOUS -> {
playerCommandsBuilder.add(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM)
playerCommandsBuilder.add(Player.COMMAND_SEEK_TO_PREVIOUS)
}
Capability.JUMP_FORWARD -> {
playerCommandsBuilder.add(Player.COMMAND_SEEK_FORWARD)
}
Capability.JUMP_BACKWARD -> {
playerCommandsBuilder.add(Player.COMMAND_SEEK_BACK)
}
Capability.SEEK_TO -> {
playerCommandsBuilder.add(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)
}
else -> { }
}
}
customLayout = customActionsList?.map {
v -> CustomButton(
displayName = v,
sessionCommand = v,
iconRes = BundleUtils.getCustomIcon(
this,
customActions,
v,
TrackPlayerR.drawable.ifl_24px
)
).commandButton
} ?: ImmutableList.of()
val sessionCommandsBuilder = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS.buildUpon()
customLayout.forEach {
v ->
v.sessionCommand?.let { sessionCommandsBuilder.add(it) }
}
sessionCommands = sessionCommandsBuilder.build()
playerCommands = playerCommandsBuilder.build()
if (mediaSession.mediaNotificationControllerInfo != null) {
// https://github.com/androidx/media/blob/c35a9d62baec57118ea898e271ac66819399649b/demos/session_service/src/main/java/androidx/media3/demo/session/DemoMediaLibrarySessionCallback.kt#L107
mediaSession.setCustomLayout(
mediaSession.mediaNotificationControllerInfo!!,
customLayout
)
mediaSession.setAvailableCommands(
mediaSession.mediaNotificationControllerInfo!!,
sessionCommands!!,
playerCommands!!
)
}
}
@MainThread
private fun progressUpdateEventFlow(interval: Double) = flow {
while (true) {
if (player.isPlaying) {
val bundle = progressUpdateEvent()
emit(bundle)
}
delay((interval * 1000).toLong())
}
}
@MainThread
private suspend fun progressUpdateEvent(): Bundle {
return withContext(Dispatchers.Main) {
Bundle().apply {
putDouble(POSITION_KEY, player.position.toSeconds())
putDouble(DURATION_KEY, player.duration.toSeconds())
putDouble(BUFFERED_POSITION_KEY, player.bufferedPosition.toSeconds())
putInt(TRACK_KEY, player.currentIndex)
}
}
}
@MainThread
fun add(track: Track) {
add(listOf(track))
}
@MainThread
fun add(tracks: List<Track>) {
val items = tracks.map { it.toAudioItem() }
player.add(items)
}
@MainThread
fun add(tracks: List<Track>, atIndex: Int) {
val items = tracks.map { it.toAudioItem() }
player.add(items, atIndex)
}
@MainThread
fun load(track: Track) {
player.load(track.toAudioItem())
}
@MainThread
fun move(fromIndex: Int, toIndex: Int) {
player.move(fromIndex, toIndex);
}
@MainThread
fun remove(index: Int) {
remove(listOf(index))
}
@MainThread
fun remove(indexes: List<Int>) {
player.remove(indexes)
}
@MainThread
fun clear() {
player.clear()
}
@MainThread
fun play() {
player.play()
}
@MainThread
fun pause() {
player.pause()
}
@MainThread
fun stop() {
player.stop()
}
@MainThread
fun removeUpcomingTracks() {
player.removeUpcomingItems()
}
@MainThread
fun removePreviousTracks() {
player.removePreviousItems()
}
@MainThread
fun skip(index: Int) {
player.jumpToItem(index)
}
@MainThread
fun skipToNext() {
player.next()
}
@MainThread
fun skipToPrevious() {
player.previous()
}
@MainThread
fun seekTo(seconds: Float) {
player.seek((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
}
@MainThread
fun seekBy(offset: Float) {
player.seekBy((offset.toLong()), TimeUnit.SECONDS)
}
@MainThread
fun retry() {
player.prepare()
}
@MainThread
fun getCurrentTrackIndex(): Int = player.currentIndex
@MainThread
fun getRate(): Float = player.playbackSpeed
@MainThread
fun setRate(value: Float) {
player.playbackSpeed = value
}
@MainThread
fun getRepeatMode(): RepeatMode = player.repeatMode
@MainThread
fun setRepeatMode(value: RepeatMode) {
player.repeatMode = value
}
@MainThread
fun getVolume(): Float = player.volume
@MainThread
fun setVolume(value: Float) {
player.volume = value
}
@MainThread
fun setAnimatedVolume(value: Float, duration: Long = 500L, interval: Long = 20L, emitEventMsg: String = ""): Deferred<Unit> {
val eventMsgBundle = Bundle()
eventMsgBundle.putString(DATA_KEY, emitEventMsg)
return player.fadeVolume(value, duration, interval) {
emit(
MusicEvents.PLAYBACK_ANIMATED_VOLUME_CHANGED,
eventMsgBundle
)
}
}
fun fadeOutPause (duration: Long = 500L, interval: Long = 20L) {
player.fadeVolume(0f, duration, interval) {
player.pause()
}
}
fun fadeOutNext (duration: Long = 500L, interval: Long = 20L, toVolume: Float = 1f) {
player.fadeVolume(0f, duration, interval) {
player.next()
player.fadeVolume(toVolume, duration, interval)
}
}
fun fadeOutPrevious (duration: Long = 500L, interval: Long = 20L, toVolume: Float = 1f) {
player.fadeVolume(0f, duration, interval) {
player.previous()
player.fadeVolume(toVolume, duration, interval)
}
}
fun fadeOutJump (index: Int, duration: Long = 500L, interval: Long = 20L, toVolume: Float = 1f) {
player.fadeVolume(0f, duration, interval) {
player.jumpToItem(index)
player.fadeVolume(toVolume, duration, interval)
}
}
@MainThread
fun getDurationInSeconds(): Double = player.duration.toSeconds()
@MainThread
fun getPositionInSeconds(): Double = player.position.toSeconds()
@MainThread
fun getBufferedPositionInSeconds(): Double = player.bufferedPosition.toSeconds()
@MainThread
fun getPlayerStateBundle(state: AudioPlayerState): Bundle {
val bundle = Bundle()
bundle.putString(STATE_KEY, state.asLibState.state)
if (state == AudioPlayerState.ERROR) {
bundle.putBundle(ERROR_KEY, getPlaybackErrorBundle())
}
return bundle
}
@MainThread
fun updateMetadataForTrack(index: Int, track: Track) {
player.replaceItem(index, track.toAudioItem())
}
@MainThread
fun updateNowPlayingMetadata(track: Track) {
updateMetadataForTrack(player.currentIndex, track)
}
@MainThread
fun clearNotificationMetadata() {
}
private fun emitPlaybackTrackChangedEvents(
index: Int?,
previousIndex: Int?,
oldPosition: Double
) {
val a = Bundle()
a.putDouble(POSITION_KEY, oldPosition)
if (index != null) {
a.putInt(NEXT_TRACK_KEY, index)
}
if (previousIndex != null) {
a.putInt(TRACK_KEY, previousIndex)
}
emit(MusicEvents.PLAYBACK_TRACK_CHANGED, a)
val b = Bundle()
b.putDouble("lastPosition", oldPosition)
if (tracks.isNotEmpty()) {
b.putInt("index", player.currentIndex)
b.putBundle("track", tracks[player.currentIndex].originalItem)
if (previousIndex != null) {
b.putInt("lastIndex", previousIndex)
b.putBundle("lastTrack", tracks[previousIndex].originalItem)
}
}
emit(MusicEvents.PLAYBACK_ACTIVE_TRACK_CHANGED, b)
}
private fun emitQueueEndedEvent() {
val bundle = Bundle()
bundle.putInt(TRACK_KEY, player.currentIndex)
bundle.putDouble(POSITION_KEY, player.position.toSeconds())
emit(MusicEvents.PLAYBACK_QUEUE_ENDED, bundle)
}
@Suppress("DEPRECATION")
fun isForegroundService(): Boolean {
val manager = baseContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (MusicService::class.java.name == service.service.className) {
return service.foreground
}
}
Timber.e("isForegroundService found no matching service")
return false
}
@MainThread
private fun observeEvents() {
scope.launch {
event.stateChange.collect {
emit(MusicEvents.PLAYBACK_STATE, getPlayerStateBundle(it))
if (it == AudioPlayerState.ENDED && player.nextItem == null) {
emitQueueEndedEvent()
}
}
}
scope.launch {
event.audioItemTransition.collect {
if (it !is AudioItemTransitionReason.REPEAT) {
emitPlaybackTrackChangedEvents(
player.currentIndex,
player.previousIndex,
(it?.oldPosition ?: 0).toSeconds()
)
}
}
}
scope.launch {
event.onAudioFocusChanged.collect {
Bundle().apply {
putBoolean(IS_FOCUS_LOSS_PERMANENT_KEY, it.isFocusLostPermanently)
putBoolean(IS_PAUSED_KEY, it.isPaused)
emit(MusicEvents.BUTTON_DUCK, this)
}
}
}
scope.launch {
event.onPlayerActionTriggeredExternally.collect {
when (it) {
is MediaSessionCallback.RATING -> {
Bundle().apply {
setRating(this, "rating", it.rating)
emit(MusicEvents.BUTTON_SET_RATING, this)
}
}
is MediaSessionCallback.SEEK -> {
Bundle().apply {
putDouble("position", it.positionMs.toSeconds())
emit(MusicEvents.BUTTON_SEEK_TO, this)
}
}
MediaSessionCallback.PLAY -> emit(MusicEvents.BUTTON_PLAY)
MediaSessionCallback.PAUSE -> emit(MusicEvents.BUTTON_PAUSE)
MediaSessionCallback.NEXT -> emit(MusicEvents.BUTTON_SKIP_NEXT)
MediaSessionCallback.PREVIOUS -> emit(MusicEvents.BUTTON_SKIP_PREVIOUS)
MediaSessionCallback.STOP -> emit(MusicEvents.BUTTON_STOP)
MediaSessionCallback.FORWARD -> {
Bundle().apply {
val interval = latestOptions?.getDouble(FORWARD_JUMP_INTERVAL_KEY, DEFAULT_JUMP_INTERVAL) ?:
DEFAULT_JUMP_INTERVAL
putInt("interval", interval.toInt())
emit(MusicEvents.BUTTON_JUMP_FORWARD, this)
}
}
MediaSessionCallback.REWIND -> {
Bundle().apply {
val interval = latestOptions?.getDouble(BACKWARD_JUMP_INTERVAL_KEY, DEFAULT_JUMP_INTERVAL) ?:
DEFAULT_JUMP_INTERVAL
putInt("interval", interval.toInt())
emit(MusicEvents.BUTTON_JUMP_BACKWARD, this)
}
}
is MediaSessionCallback.CUSTOMACTION -> {
Bundle().apply {
putString("customAction", it.customAction)
emit(MusicEvents.BUTTON_CUSTOM_ACTION, this)
}
}
}
}
}
scope.launch {
event.onTimedMetadata.collect {
val data = MetadataAdapter.fromMetadata(it)
val bundle = Bundle().apply {
putParcelableArrayList(METADATA_PAYLOAD_KEY, ArrayList(data))
}
emit(MusicEvents.METADATA_TIMED_RECEIVED, bundle)
// TODO: Handle the different types of metadata and publish to new events
val metadata = PlaybackMetadata.fromId3Metadata(it)
?: PlaybackMetadata.fromIcy(it)
?: PlaybackMetadata.fromVorbisComment(it)
?: PlaybackMetadata.fromQuickTime(it)
if (metadata != null) {
Bundle().apply {
putString("source", metadata.source)
putString("title", metadata.title)
putString("url", metadata.url)
putString("artist", metadata.artist)
putString("album", metadata.album)
putString("date", metadata.date)
putString("genre", metadata.genre)
emit(MusicEvents.PLAYBACK_METADATA, this)
}
}
}
}
scope.launch {
event.onCommonMetadata.collect {
val data = MetadataAdapter.fromMediaMetadata(it)
val bundle = Bundle().apply {
putBundle(METADATA_PAYLOAD_KEY, data)
}
emit(MusicEvents.METADATA_COMMON_RECEIVED, bundle)
}
}
scope.launch {
event.playWhenReadyChange.collect {
Bundle().apply {
putBoolean("playWhenReady", it.playWhenReady)
emit(MusicEvents.PLAYBACK_PLAY_WHEN_READY_CHANGED, this)
}
}
}
scope.launch {
event.playbackError.collect {
emit(MusicEvents.PLAYBACK_ERROR, getPlaybackErrorBundle())
}
}
}
private fun getPlaybackErrorBundle(): Bundle {
val bundle = Bundle()
val error = playbackError
if (error?.message != null) {
bundle.putString("message", error.message)
}
if (error?.code != null) {
bundle.putString("code", "android-" + error.code)
}
return bundle
}
@SuppressLint("VisibleForTests")
@MainThread
fun emit(event: String, data: Bundle? = null) {
reactContext?.emitDeviceEvent(event, data?.let { Arguments.fromBundle(it) })
}
@SuppressLint("VisibleForTests")
@MainThread
private fun emitList(event: String, data: List<Bundle> = emptyList()) {
val payload = Arguments.createArray()
data.forEach { payload.pushMap(Arguments.fromBundle(it)) }
reactContext?.emitDeviceEvent(event, payload)
}
override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig {
return HeadlessJsTaskConfig(TASK_KEY, Arguments.createMap(), 0, true)
}
@MainThread
override fun onBind(intent: Intent?): IBinder? {
val intentAction = intent?.action
Timber.tag("APM").d("onbind: $intentAction")
return if (intentAction != null) {
super.onBind(intent)
} else {
binder
}
}
override fun onUnbind(intent: Intent?): Boolean {
Timber.tag("APM").d("unbind: ${intent?.action}")
return super.onUnbind(intent)
}
override fun onUpdateNotification(session: MediaSession, startInForegroundRequired: Boolean) {
// https://github.com/androidx/media/issues/843#issuecomment-1860555950
super.onUpdateNotification(session, true)
}
@MainThread
override fun onTaskRemoved(rootIntent: Intent?) {
onUnbind(rootIntent)
Timber
.tag("APM")
.d("onTaskRemoved: ${::player.isInitialized}, $appKilledPlaybackBehavior")
if (!::player.isInitialized) {
mediaSession.release()
return
}
when (appKilledPlaybackBehavior) {
AppKilledPlaybackBehavior.PAUSE_PLAYBACK -> player.pause()
AppKilledPlaybackBehavior.STOP_PLAYBACK_AND_REMOVE_NOTIFICATION -> {
Timber.tag("APM").d("onTaskRemoved: Killing service")
mediaSession.release()
player.clear()
player.stop()
// HACK: the service first stops, then starts, then call onTaskRemove. Why system
// registers the service being restarted?
player.destroy()
scope.cancel()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(STOP_FOREGROUND_REMOVE)
} else {
@Suppress("DEPRECATION")
stopForeground(true)
}
onDestroy()
// https://github.com/androidx/media/issues/27#issuecomment-1456042326
stopSelf()
exitProcess(0)
}
else -> {}
}
}
@SuppressLint("VisibleForTests")
private fun selfWake(clientPackageName: String): Boolean {
val reactActivity = reactContext?.currentActivity
if (
// HACK: validate reactActivity is present; if not, send wake intent
(reactActivity == null || reactActivity.isDestroyed)
&& Settings.canDrawOverlays(this)
) {
val currentTime = System.currentTimeMillis()
if (currentTime - lastWake < 100000) {
return false
}
lastWake = currentTime
val activityIntent = packageManager.getLaunchIntentForPackage(packageName)
activityIntent!!.data = Uri.parse("trackplayer://service-bound")
activityIntent.action = Intent.ACTION_VIEW
activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
var activityOptions = ActivityOptions.makeBasic()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
activityOptions = activityOptions.setPendingIntentBackgroundActivityStartMode(
ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED)
}
this.startActivity(activityIntent, activityOptions.toBundle())
return true
}
return false
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession {
Timber.tag("APM").d("onGetSession: ${controllerInfo.packageName}")
return mediaSession
}
fun notifyChildrenChanged() {
mediaSession.connectedControllers.forEach {
controller ->
mediaTree.forEach {
it -> mediaSession.notifyChildrenChanged(controller, it.key, it.value.size, null)
}
}
}
@MainThread
override fun onHeadlessJsTaskFinish(taskId: Int) {
// This is empty so ReactNative doesn't kill this service
}
@MainThread
override fun onDestroy() {
Timber.tag("APM").d("RNTP service is destroyed.")
if (::player.isInitialized) {
mediaSession.release()
player.destroy()
}
progressUpdateJob?.cancel()
super.onDestroy()
}
fun onMediaKeyEvent(intent: Intent?): Boolean? {
val keyEvent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent?.getParcelableExtra(Intent.EXTRA_KEY_EVENT, KeyEvent::class.java)
} else {
intent?.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
}
if (keyEvent?.action == KeyEvent.ACTION_DOWN) {
return when (keyEvent.keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
emit(MusicEvents.BUTTON_PLAY_PAUSE)
true
}
KeyEvent.KEYCODE_MEDIA_STOP -> {
emit(MusicEvents.BUTTON_STOP)
true
}
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
emit(MusicEvents.BUTTON_PAUSE)
true
}
KeyEvent.KEYCODE_MEDIA_PLAY -> {
emit(MusicEvents.BUTTON_PLAY)
true
}
KeyEvent.KEYCODE_MEDIA_NEXT -> {
emit(MusicEvents.BUTTON_SKIP_NEXT)
true
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
emit(MusicEvents.BUTTON_SKIP_PREVIOUS)
true
}
KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD, KeyEvent.KEYCODE_MEDIA_STEP_FORWARD -> {
emit(MusicEvents.BUTTON_JUMP_FORWARD)
true
}
KeyEvent.KEYCODE_MEDIA_REWIND, KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD, KeyEvent.KEYCODE_MEDIA_STEP_BACKWARD -> {
emit(MusicEvents.BUTTON_JUMP_BACKWARD)
true
}
else -> null
}
}
return null
}
@MainThread
inner class MusicBinder : Binder() {
val service = this@MusicService
}
private inner class APMMediaSessionCallback: MediaLibrarySession.Callback {
// HACK: I'm sure most of the callbacks were not implemented correctly.
// ATM I only care that andorid auto still functions.
private val rootItem = buildMediaItem(title = "root", mediaId = AA_ROOT_KEY, isPlayable = false)
private val forYouItem = buildMediaItem(title = "For You", mediaId = AA_FOR_YOU_KEY, isPlayable = false)
override fun onDisconnected(
session: MediaSession,
controller: MediaSession.ControllerInfo
) {
emit(MusicEvents.CONNECTOR_DISCONNECTED, Bundle().apply {
putString("package", controller.packageName)
})
super.onDisconnected(session, controller)
}
// Configure commands available to the controller in onConnect()
@OptIn(UnstableApi::class)
override fun onConnect(
session: MediaSession,
controller: MediaSession.ControllerInfo
): MediaSession.ConnectionResult {
Timber.tag("APM").d("connection via: ${controller.packageName}")
val isMediaNotificationController = session.isMediaNotificationController(controller)
val isAutomotiveController = session.isAutomotiveController(controller)
val isAutoCompanionController = session.isAutoCompanionController(controller)
emit(MusicEvents.CONNECTOR_CONNECTED, Bundle().apply {
putString("package", controller.packageName)
putBoolean("isMediaNotificationController", isMediaNotificationController)
putBoolean("isAutomotiveController", isAutomotiveController)
putBoolean("isAutoCompanionController", isAutoCompanionController)
})
if (controller.packageName in arrayOf(
"com.android.systemui",
// https://github.com/googlesamples/android-media-controller
"com.example.android.mediacontroller",
// Android Auto
"com.google.android.projection.gearhead"