Skip to content

Commit 4323f76

Browse files
committed
Improved application start
1 parent cbefbbb commit 4323f76

File tree

1 file changed

+145
-118
lines changed

1 file changed

+145
-118
lines changed

composeApp/src/androidMain/kotlin/it/fast4x/riplay/service/PlayerService.kt

Lines changed: 145 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ class PlayerService : Service(),
275275

276276
private var isPersistentQueueEnabled = false
277277
private var isResumePlaybackOnStart = false
278+
278279
//private var isclosebackgroundPlayerEnabled = false
279280
private var closeServiceAfterMinutes by mutableStateOf(DurationInMinutes.Disabled)
280281
private var closeServiceWhenPlayerPausedAfterMinutes by mutableStateOf(DurationInMinutes.Disabled)
@@ -328,8 +329,10 @@ class PlayerService : Service(),
328329
private val _internalOnlinePlayer = MutableStateFlow<YouTubePlayer?>(null)
329330
val internalOnlinePlayer: StateFlow<YouTubePlayer?> = _internalOnlinePlayer
330331

331-
private val _internalOnlinePlayerState = MutableStateFlow<PlayerConstants.PlayerState>(PlayerConstants.PlayerState.UNSTARTED)
332-
val internalOnlinePlayerState: StateFlow<PlayerConstants.PlayerState> = _internalOnlinePlayerState
332+
private val _internalOnlinePlayerState =
333+
MutableStateFlow<PlayerConstants.PlayerState>(PlayerConstants.PlayerState.UNSTARTED)
334+
val internalOnlinePlayerState: StateFlow<PlayerConstants.PlayerState> =
335+
_internalOnlinePlayerState
333336

334337
private val _internalOnlineBufferedFraction = MutableStateFlow(0f)
335338
val internalOnlineBufferedFraction: StateFlow<Float> = _internalOnlineBufferedFraction
@@ -381,6 +384,7 @@ class PlayerService : Service(),
381384

382385
private var noisyReceiver: NoisyAudioReceiver? = null
383386
private var bluetoothReceiver: BluetoothConnectReceiver? = null
387+
384388
//private lateinit var audioFocusHelper: AudioFocusHelper
385389
private var hasAudioFocus = false
386390

@@ -431,66 +435,39 @@ class PlayerService : Service(),
431435
super.onCreate()
432436

433437
createNotificationChannel()
434-
startForeground()
435-
436-
/**
437-
* Online initialization
438-
*/
439438

439+
//connectivityManager = getSystemService()!!
440440

441+
// INITIALIZATION
441442
preferences.registerOnSharedPreferenceChangeListener(this)
443+
initializeLocalPlayer()
444+
initializeVariables()
445+
initializeOnlinePlayer()
446+
initializeUnifiedMediaSession()
442447

443-
//val preferences = preferences
444-
isPersistentQueueEnabled = preferences.getBoolean(persistentQueueKey, true)
445-
isResumePlaybackOnStart = preferences.getBoolean(resumePlaybackOnStartKey, false)
446-
isShowingThumbnailInLockscreen =
447-
preferences.getBoolean(isShowingThumbnailInLockscreenKey, false)
448-
medleyDuration = preferences.getFloat(playbackDurationKey, 0f)
449-
450-
player = ExoPlayer.Builder(this)
451-
.setMediaSourceFactory(createMediaSourceFactory())
452-
.setRenderersFactory(createRendersFactory())
453-
.setHandleAudioBecomingNoisy(true)
454-
.setWakeMode(C.WAKE_MODE_LOCAL)
455-
.setAudioAttributes(
456-
AudioAttributes.Builder()
457-
.setUsage(C.USAGE_MEDIA)
458-
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
459-
.build(),
460-
isHandleAudioFocusEnabled()
461-
)
462-
//.setUsePlatformDiagnostics(false)
463-
.setSeekBackIncrementMs(5000)
464-
.setSeekForwardIncrementMs(5000)
465-
// .setLoadControl(
466-
// DefaultLoadControl.Builder()
467-
// .setBufferDurationsMs(
468-
// DefaultLoadControl.DEFAULT_MIN_BUFFER_MS, // 50000
469-
// DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, // 50000
470-
// 5000,
471-
// 10000
472-
// ).build()
473-
// )
474-
.build()
475-
.apply {
476-
addListener(this@PlayerService)
477-
sleepTimerListener = SleepTimerListener(coroutineScope, this)
478-
addListener(sleepTimerListener)
479-
addAnalyticsListener(PlaybackStatsListener(false, this@PlayerService))
480-
}
481-
482-
player.repeatMode = preferences.getEnum(queueLoopTypeKey, QueueLoopType.Default).type
483-
484-
player.skipSilenceEnabled = preferences.getBoolean(skipSilenceKey, false)
485-
player.pauseAtEndOfMediaItems = true
486-
487-
audioVolumeObserver = AudioVolumeObserver(this)
488-
audioVolumeObserver.register(AudioManager.STREAM_MUSIC, this)
448+
startForeground()
489449

490-
equalizerHelper = EqualizerHelper(this)
491-
equalizerHelper.setup(0)
450+
initializeBitmapProvider()
451+
initializeAudioVolumeObserver()
452+
initializeAudioEqualizer()
453+
initializeLegacyNotificationActionReceiver()
454+
initializePositionObserver()
455+
initializeBluetoothConnect()
456+
initializeNormalizeVolume()
457+
initializeBassBoost()
458+
initializeReverb()
459+
initializeSensorListener()
460+
initializeSongCoverInLockScreen()
461+
initializeMedleyMode()
462+
initializePlaybackParameters()
463+
initializeNoisyReceiver()
464+
initializeAudioManager()
465+
//initializeAudioFocusHelper()
466+
//initializeTelephonyManager(true)
492467

493-
//connectivityManager = getSystemService()!!
468+
initializeRiTune()
469+
initializeDiscordPresence()
470+
// INITIALIZATION
494471

495472
coroutineScope.launch {
496473
withContext(Dispatchers.Main) {
@@ -543,7 +520,7 @@ class PlayerService : Service(),
543520
var currentMediaId = song.id
544521

545522
if (lastOnlineMediaId != currentMediaId) {
546-
if(onlineListenedDurationMs > 0) incrementOnlineListenedPlaytimeMs()
523+
if (onlineListenedDurationMs > 0) incrementOnlineListenedPlaytimeMs()
547524
delay(200)
548525
onlineListenedDurationMs = 0L
549526
lastOnlineMediaId = currentMediaId
@@ -564,13 +541,15 @@ class PlayerService : Service(),
564541
?.let {
565542
Timber.d("PlayerService onCreate update currentSong onlinemetadata it $it")
566543
try {
567-
Database.upsert(Format(
568-
songId = currentMediaId,
569-
contentLength = it.videoDetails?.lengthSeconds?.toLong(),
570-
loudnessDb = it.playerConfig?.audioConfig?.loudnessDb
571-
?: it.playerConfig?.audioConfig?.perceptualLoudnessDb?.toFloat(),
572-
playbackUrl = it.playbackTracking?.videostatsPlaybackUrl?.baseUrl
573-
))
544+
Database.upsert(
545+
Format(
546+
songId = currentMediaId,
547+
contentLength = it.videoDetails?.lengthSeconds?.toLong(),
548+
loudnessDb = it.playerConfig?.audioConfig?.loudnessDb
549+
?: it.playerConfig?.audioConfig?.perceptualLoudnessDb?.toFloat(),
550+
playbackUrl = it.playbackTracking?.videostatsPlaybackUrl?.baseUrl
551+
)
552+
)
574553
} catch (e: Exception) {
575554
Timber.e("PlayerService onCreate update currentSong exception ${e.stackTraceToString()}")
576555
}
@@ -579,30 +558,6 @@ class PlayerService : Service(),
579558
}
580559
}
581560

582-
initializeVariables()
583-
584-
initializeLegacyNotificationActionReceiver()
585-
initializeUnifiedMediaSession()
586-
initializeBitmapProvider()
587-
initializeOnlinePlayer()
588-
589-
initializePositionObserver()
590-
initializeBluetoothConnect()
591-
initializeNormalizeVolume()
592-
initializeBassBoost()
593-
initializeReverb()
594-
initializeSensorListener()
595-
initializeSongCoverInLockScreen()
596-
initializeMedleyMode()
597-
initializePlaybackParameters()
598-
initializeNoisyReceiver()
599-
initializeAudioManager()
600-
//initializeAudioFocusHelper()
601-
//initializeTelephonyManager(true)
602-
603-
initializeRiTune()
604-
initializeDiscordPresence()
605-
606561
globalQueue.linkController(binder)
607562

608563
coroutineScope.launch(Dispatchers.Default) {
@@ -642,7 +597,14 @@ class PlayerService : Service(),
642597

643598
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
644599
startForeground()
645-
Timber.d("PlayerService onStartCommand action ${intent?.action} enable ${intent?.getBooleanExtra(EXTRA_ENABLE_LISTENER, false)}")
600+
Timber.d(
601+
"PlayerService onStartCommand action ${intent?.action} enable ${
602+
intent?.getBooleanExtra(
603+
EXTRA_ENABLE_LISTENER,
604+
false
605+
)
606+
}"
607+
)
646608
/*
647609
when (intent?.action) {
648610
ACTION_UPDATE_PHONE_LISTENER -> {
@@ -656,28 +618,35 @@ class PlayerService : Service(),
656618
}
657619

658620
private fun startForeground() {
659-
runCatching {
660-
notification().let {
661-
ServiceCompat.startForeground(
662-
this@PlayerService,
663-
NOTIFICATION_ID,
664-
it,
665-
if (isAtLeastAndroid11) {
666-
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
667-
} else {
668-
0
669-
}
670-
)
671-
}
672-
}.onFailure {
673-
Timber.e("PlayerService oncreate startForeground ${it.stackTraceToString()}")
674-
stopSelf()
675-
SmartMessage("Error starting service, maybe permission denied?", context = this)
621+
//runCatching {
622+
notification().let {
623+
ServiceCompat.startForeground(
624+
this@PlayerService,
625+
NOTIFICATION_ID,
626+
it,
627+
if (isAtLeastAndroid11) {
628+
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
629+
} else {
630+
0
631+
}
632+
)
676633
}
634+
// }.onFailure {
635+
// Timber.e("PlayerService oncreate startForeground ${it.stackTraceToString()}")
636+
// stopSelf()
637+
// SmartMessage("Error starting service, maybe permission denied?", context = this)
638+
// }
677639
}
678640

679641
private fun initializeVariables() {
680642

643+
//val preferences = preferences
644+
isPersistentQueueEnabled = preferences.getBoolean(persistentQueueKey, true)
645+
isResumePlaybackOnStart = preferences.getBoolean(resumePlaybackOnStartKey, false)
646+
isShowingThumbnailInLockscreen =
647+
preferences.getBoolean(isShowingThumbnailInLockscreenKey, false)
648+
medleyDuration = preferences.getFloat(playbackDurationKey, 0f)
649+
681650
_internalOnlinePlayerView.value = LayoutInflater.from(appContext())
682651
.inflate(R.layout.youtube_player, null, false) as YouTubePlayerView
683652

@@ -688,28 +657,31 @@ class PlayerService : Service(),
688657
currentMediaItemState.value = player.currentMediaItem
689658

690659
//isclosebackgroundPlayerEnabled = preferences.getBoolean(closebackgroundPlayerKey, false)
691-
closeServiceAfterMinutes = preferences.getEnum(closePlayerServiceAfterMinutesKey, DurationInMinutes.Disabled)
660+
closeServiceAfterMinutes =
661+
preferences.getEnum(closePlayerServiceAfterMinutesKey, DurationInMinutes.Disabled)
692662
closeServiceWhenPlayerPausedAfterMinutes = preferences.getEnum(
693-
closePlayerServiceWhenPausedAfterMinutesKey, DurationInMinutes.Disabled)
663+
closePlayerServiceWhenPausedAfterMinutesKey, DurationInMinutes.Disabled
664+
)
694665
}
695666

696667
private fun initializePlaybackParameters() {
697668
when (localMediaItem?.isLocal) {
698669
false -> {
699670
val playbackSpeed = preferences.getFloat(playbackSpeedKey, 1f)
700671
val onlinePlabackRate = when {
701-
(playbackSpeed.toDouble() in 0.0..0.25) -> PlayerConstants.PlaybackRate.RATE_0_25
702-
(playbackSpeed.toDouble() in 0.26..0.5) -> PlayerConstants.PlaybackRate.RATE_0_5
703-
(playbackSpeed.toDouble() in 0.51..0.75) -> PlayerConstants.PlaybackRate.RATE_0_75
704-
(playbackSpeed.toDouble() in 0.76..1.0) -> PlayerConstants.PlaybackRate.RATE_1
705-
(playbackSpeed.toDouble() in 1.01..1.25) -> PlayerConstants.PlaybackRate.RATE_1_25
706-
(playbackSpeed.toDouble() in 1.26..1.5) -> PlayerConstants.PlaybackRate.RATE_1_5
707-
(playbackSpeed.toDouble() in 1.51..1.75) -> PlayerConstants.PlaybackRate.RATE_1_75
672+
(playbackSpeed.toDouble() in 0.0..0.25) -> PlayerConstants.PlaybackRate.RATE_0_25
673+
(playbackSpeed.toDouble() in 0.26..0.5) -> PlayerConstants.PlaybackRate.RATE_0_5
674+
(playbackSpeed.toDouble() in 0.51..0.75) -> PlayerConstants.PlaybackRate.RATE_0_75
675+
(playbackSpeed.toDouble() in 0.76..1.0) -> PlayerConstants.PlaybackRate.RATE_1
676+
(playbackSpeed.toDouble() in 1.01..1.25) -> PlayerConstants.PlaybackRate.RATE_1_25
677+
(playbackSpeed.toDouble() in 1.26..1.5) -> PlayerConstants.PlaybackRate.RATE_1_5
678+
(playbackSpeed.toDouble() in 1.51..1.75) -> PlayerConstants.PlaybackRate.RATE_1_75
708679
(playbackSpeed.toDouble() > 1.76) -> PlayerConstants.PlaybackRate.RATE_2
709680
else -> PlayerConstants.PlaybackRate.RATE_1
710681
}
711682
_internalOnlinePlayer.value?.setPlaybackRate(onlinePlabackRate)
712683
}
684+
713685
else -> {
714686
player.playbackParameters = PlaybackParameters(
715687
preferences.getFloat(playbackSpeedKey, 1f),
@@ -766,7 +738,9 @@ class PlayerService : Service(),
766738
while (medleyDuration > 0) {
767739
withContext(Dispatchers.Main) {
768740
Timber.d("PlayerService initializeMedleyMode medleyDuration $medleyDuration player.isPlaying ${player.isPlaying} internalOnlinePlayerState ${_internalOnlinePlayerState.value == PlayerConstants.PlayerState.PLAYING}")
769-
val seconds = if (localMediaItem?.isLocal == true) player.currentPosition.div(1000).toInt() else currentSecond.value.toInt()
741+
val seconds =
742+
if (localMediaItem?.isLocal == true) player.currentPosition.div(1000)
743+
.toInt() else currentSecond.value.toInt()
770744
if (medleyDuration.toInt() <= seconds) {
771745
//delay(1.seconds * (medleyDuration.toInt() + 2))
772746
//handleSkipToNext()
@@ -946,10 +920,13 @@ class PlayerService : Service(),
946920
}
947921

948922
private fun resumePlaybackOnStart() {
949-
if(!isPersistentQueueEnabled && !isResumePlaybackOnStart) return
923+
if (!isPersistentQueueEnabled && !isResumePlaybackOnStart) return
950924

951925
when (player.currentMediaItem?.isLocal) {
952-
true -> { if (!player.isPlaying) player.play() }
926+
true -> {
927+
if (!player.isPlaying) player.play()
928+
}
929+
953930
else -> {}
954931
}
955932

@@ -1006,6 +983,46 @@ class PlayerService : Service(),
1006983
initializeOnlinePlayer()
1007984
}
1008985

986+
private fun initializeLocalPlayer() {
987+
player = ExoPlayer.Builder(this)
988+
.setMediaSourceFactory(createMediaSourceFactory())
989+
.setRenderersFactory(createRendersFactory())
990+
.setHandleAudioBecomingNoisy(true)
991+
.setWakeMode(C.WAKE_MODE_LOCAL)
992+
.setAudioAttributes(
993+
AudioAttributes.Builder()
994+
.setUsage(C.USAGE_MEDIA)
995+
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
996+
.build(),
997+
isHandleAudioFocusEnabled()
998+
)
999+
//.setUsePlatformDiagnostics(false)
1000+
.setSeekBackIncrementMs(5000)
1001+
.setSeekForwardIncrementMs(5000)
1002+
// .setLoadControl(
1003+
// DefaultLoadControl.Builder()
1004+
// .setBufferDurationsMs(
1005+
// DefaultLoadControl.DEFAULT_MIN_BUFFER_MS, // 50000
1006+
// DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, // 50000
1007+
// 5000,
1008+
// 10000
1009+
// ).build()
1010+
// )
1011+
.build()
1012+
.apply {
1013+
addListener(this@PlayerService)
1014+
sleepTimerListener = SleepTimerListener(coroutineScope, this)
1015+
addListener(sleepTimerListener)
1016+
addAnalyticsListener(PlaybackStatsListener(false, this@PlayerService))
1017+
}
1018+
1019+
player.repeatMode = preferences.getEnum(queueLoopTypeKey, QueueLoopType.Default).type
1020+
1021+
player.skipSilenceEnabled = preferences.getBoolean(skipSilenceKey, false)
1022+
player.pauseAtEndOfMediaItems = true
1023+
}
1024+
1025+
10091026
private fun initializeOnlinePlayer() {
10101027

10111028
_internalOnlinePlayerView.value.apply {
@@ -1263,6 +1280,16 @@ class PlayerService : Service(),
12631280

12641281
}
12651282

1283+
private fun initializeAudioVolumeObserver() {
1284+
audioVolumeObserver = AudioVolumeObserver(this)
1285+
audioVolumeObserver.register(AudioManager.STREAM_MUSIC, this)
1286+
}
1287+
1288+
private fun initializeAudioEqualizer() {
1289+
equalizerHelper = EqualizerHelper(this)
1290+
equalizerHelper.setup(0)
1291+
}
1292+
12661293
private fun initializeLegacyNotificationActionReceiver() {
12671294

12681295
legacyNotificationActionReceiver = LegacyNotificationActionReceiver()

0 commit comments

Comments
 (0)