-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerController.kt
More file actions
500 lines (432 loc) · 18.4 KB
/
PlayerController.kt
File metadata and controls
500 lines (432 loc) · 18.4 KB
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
package com.fourshil.musicya.player
import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.fourshil.musicya.data.model.Song
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
/**
* Central controller for music playback operations.
*
* Manages the connection to [MusicService] via Media3's [MediaController] and exposes
* playback state through Kotlin [StateFlow]s for reactive UI updates. Delegates specialized
* functionality to focused manager classes:
* - [SleepTimerManager] for sleep timer operations
* - [PlaybackSpeedManager] for playback speed control
*
* ## Usage
* Call [connect] early in the app lifecycle (typically from ViewModel init) to establish
* the MediaController connection. All playback operations are safe to call immediately;
* they will be queued until the controller is ready.
*
* @property context Application context for MediaController binding
* @property sleepTimerManager Manages sleep timer functionality
* @property speedManager Manages playback speed control
*/
@Singleton
class PlayerController @Inject constructor(
@ApplicationContext private val context: Context,
private val sleepTimerManager: SleepTimerManager,
private val speedManager: PlaybackSpeedManager,
private val crossfadeManager: CrossfadeManager
) {
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private var positionUpdateJob: Job? = null
private var controllerFuture: ListenableFuture<MediaController>? = null
// Playback state
private val _isPlaying = MutableStateFlow(false)
/** Whether playback is currently active */
val isPlaying: StateFlow<Boolean> = _isPlaying.asStateFlow()
private val _currentSong = MutableStateFlow<Song?>(null)
/** The currently playing song, or null if nothing is playing */
val currentSong: StateFlow<Song?> = _currentSong.asStateFlow()
private val _currentPosition = MutableStateFlow(0L)
/** Current playback position in milliseconds */
val currentPosition: StateFlow<Long> = _currentPosition.asStateFlow()
private val _duration = MutableStateFlow(0L)
/** Duration of the current track in milliseconds */
val duration: StateFlow<Long> = _duration.asStateFlow()
private val _shuffleEnabled = MutableStateFlow(false)
/** Whether shuffle mode is enabled */
val shuffleEnabled: StateFlow<Boolean> = _shuffleEnabled.asStateFlow()
private val _repeatMode = MutableStateFlow(Player.REPEAT_MODE_OFF)
/** Current repeat mode (OFF, ALL, or ONE) */
val repeatMode: StateFlow<Int> = _repeatMode.asStateFlow()
private val _queue = MutableStateFlow<List<Song>>(emptyList())
/** Current playback queue */
val queue: StateFlow<List<Song>> = _queue.asStateFlow()
private val _currentQueueIndex = MutableStateFlow(-1)
/** Current index in the playback queue */
val currentQueueIndex: StateFlow<Int> = _currentQueueIndex.asStateFlow()
// Track queue count to avoid unnecessary rebuilds
private var lastQueueCount = -1 // Use -1 to force initial update
private var lastFirstItemId: String? = null // Track first item to detect queue changes
// Track position update interval - use slower updates for MiniPlayer, faster for NowPlaying
private var positionUpdateInterval = 500L
// Delegated managers - expose their state flows
/** Remaining sleep timer time in milliseconds */
val sleepTimerRemaining: StateFlow<Long> = sleepTimerManager.remainingMs
/** Current playback speed (1.0 = normal) */
val playbackSpeed: StateFlow<Float> = speedManager.speed
// Crossfade setting
private val _crossfadeDuration = MutableStateFlow(0)
/** Crossfade duration in seconds (0 = disabled) */
val crossfadeDuration: StateFlow<Int> = _crossfadeDuration.asStateFlow()
/**
* The underlying MediaController, if connected and ready.
* Returns null if connection is pending or failed.
*/
val controller: MediaController?
get() = if (controllerFuture?.isDone == true) {
try { controllerFuture?.get() } catch (e: Exception) { null }
} else null
/**
* Establish connection to the MusicService.
* Safe to call multiple times; subsequent calls are no-ops.
*/
fun connect() {
if (controllerFuture != null) return
// Initialize managers with required dependencies
sleepTimerManager.initialize(scope) { controller?.pause() }
speedManager.initialize { speed -> controller?.setPlaybackSpeed(speed) }
val sessionToken = SessionToken(context, ComponentName(context, MusicService::class.java))
controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()
controllerFuture?.addListener({
val mediaController = controller ?: return@addListener
mediaController.addListener(object : Player.Listener {
override fun onIsPlayingChanged(isPlaying: Boolean) {
_isPlaying.value = isPlaying
if (isPlaying) startPositionUpdates() else stopPositionUpdates()
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
updateCurrentSong(mediaItem)
}
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_READY) {
_duration.value = mediaController.duration
}
}
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {
_shuffleEnabled.value = shuffleModeEnabled
}
override fun onRepeatModeChanged(repeatMode: Int) {
_repeatMode.value = repeatMode
}
override fun onTimelineChanged(timeline: androidx.media3.common.Timeline, reason: Int) {
updateQueue(mediaController)
}
})
// Sync initial state
_isPlaying.value = mediaController.isPlaying
_shuffleEnabled.value = mediaController.shuffleModeEnabled
_repeatMode.value = mediaController.repeatMode
updateCurrentSong(mediaController.currentMediaItem)
updateQueue(mediaController)
}, MoreExecutors.directExecutor())
}
private fun updateCurrentSong(mediaItem: MediaItem?) {
// Also update index
_currentQueueIndex.value = controller?.currentMediaItemIndex ?: -1
if (mediaItem == null) {
_currentSong.value = null
return
}
val meta = mediaItem.mediaMetadata
val albumId = meta.extras?.getLong("album_id") ?: 0L
_currentSong.value = Song(
id = mediaItem.mediaId.toLongOrNull() ?: 0,
title = meta.title?.toString() ?: "Unknown",
artist = meta.artist?.toString() ?: "Unknown Artist",
album = meta.albumTitle?.toString() ?: "Unknown Album",
albumId = albumId,
duration = controller?.duration ?: 0,
uri = mediaItem.localConfiguration?.uri ?: Uri.EMPTY,
path = meta.extras?.getString("path") ?: "",
dateAdded = 0,
size = 0
)
}
private fun updateQueue(controller: MediaController) {
val count = controller.mediaItemCount
val currentIndex = controller.currentMediaItemIndex
// Get first item ID to detect content changes (not just count changes)
val firstItemId = if (count > 0) controller.getMediaItemAt(0).mediaId else null
// Rebuild queue if count changed OR first item changed (different playlist)
if (count != lastQueueCount || firstItemId != lastFirstItemId) {
lastQueueCount = count
lastFirstItemId = firstItemId
val newQueue = ArrayList<Song>(count)
for (i in 0 until count) {
val item = controller.getMediaItemAt(i)
val meta = item.mediaMetadata
newQueue.add(
Song(
id = item.mediaId.toLongOrNull() ?: 0,
title = meta.title?.toString() ?: "Unknown",
artist = meta.artist?.toString() ?: "Unknown Artist",
album = meta.albumTitle?.toString() ?: "Unknown Album",
albumId = meta.extras?.getLong("album_id") ?: 0L,
duration = 0, // Duration not available in queue items usually
uri = item.localConfiguration?.uri ?: Uri.EMPTY,
path = meta.extras?.getString("path") ?: "",
dateAdded = 0,
size = 0
)
)
}
_queue.value = newQueue
}
_currentQueueIndex.value = currentIndex
}
// ============ Playback Control ============
/**
* Play a single song, replacing the current queue.
* @param song The song to play
*/
fun playSong(song: Song) {
// Reset queue tracking to force update
lastQueueCount = -1
lastFirstItemId = null
val ctrl = controller
if (ctrl == null) {
// Controller not ready, queue the operation
scope.launch {
// Wait for controller to be ready (max 3 seconds)
var attempts = 0
while (controller == null && attempts < 30) {
kotlinx.coroutines.delay(100)
attempts++
}
controller?.let { c ->
val mediaItem = buildMediaItem(song)
c.setMediaItem(mediaItem)
c.prepare()
c.play()
}
}
return
}
val mediaItem = buildMediaItem(song)
ctrl.setMediaItem(mediaItem)
ctrl.prepare()
ctrl.play()
}
/**
* Play a list of songs starting at a specific index.
* @param songs List of songs to play
* @param startIndex Index of the song to start with (default: 0)
*/
fun playSongs(songs: List<Song>, startIndex: Int = 0) {
if (songs.isEmpty()) return
// Reset queue tracking to force update
lastQueueCount = -1
lastFirstItemId = null
val ctrl = controller
if (ctrl == null) {
// Controller not ready, queue the operation
scope.launch {
// Wait for controller to be ready (max 3 seconds)
var attempts = 0
while (controller == null && attempts < 30) {
kotlinx.coroutines.delay(100)
attempts++
}
controller?.let { c ->
val mediaItems = songs.map { buildMediaItem(it) }
c.setMediaItems(mediaItems, startIndex, 0)
c.prepare()
c.play()
}
}
return
}
val mediaItems = songs.map { buildMediaItem(it) }
ctrl.setMediaItems(mediaItems, startIndex, 0)
ctrl.prepare()
ctrl.play()
}
private fun buildMediaItem(song: Song): MediaItem {
return MediaItem.Builder()
.setMediaId(song.id.toString())
.setUri(song.uri)
.setMediaMetadata(
MediaMetadata.Builder()
.setTitle(song.title)
.setArtist(song.artist)
.setAlbumTitle(song.album)
.setArtworkUri(song.albumArtUri)
.setExtras(Bundle().apply {
putLong("album_id", song.albumId)
putString("path", song.path)
})
.build()
)
.build()
}
/** Toggle between play and pause states */
fun togglePlayPause() {
controller?.let { if (it.isPlaying) it.pause() else it.play() }
}
/**
* Seek to a specific position in the current track.
* @param position Position in milliseconds
*/
fun seekTo(position: Long) {
controller?.seekTo(position)
_currentPosition.value = position
}
/** Get current playback position immediately (for one-time reads) */
fun getCurrentPosition(): Long = controller?.currentPosition ?: 0L
/**
* Start polling position updates for progress bar.
* @param fastUpdates If true, use faster update interval (for NowPlaying screen)
*/
fun startPositionUpdates(fastUpdates: Boolean = false) {
positionUpdateInterval = if (fastUpdates) 200L else 500L
if (positionUpdateJob?.isActive == true) {
// If already running, just update interval on next iteration
return
}
positionUpdateJob = scope.launch {
while (isActive) {
controller?.let {
_currentPosition.value = it.currentPosition
_duration.value = it.duration.coerceAtLeast(0L)
}
delay(positionUpdateInterval)
}
}
}
/** Stop polling position updates */
fun stopPositionUpdates() {
positionUpdateJob?.cancel()
positionUpdateJob = null
}
/** Skip to the next track */
fun skipToNext() = controller?.seekToNext()
/** Skip to the previous track */
fun skipToPrevious() = controller?.seekToPrevious()
/** Toggle shuffle mode on/off */
fun toggleShuffle() {
controller?.let { it.shuffleModeEnabled = !it.shuffleModeEnabled }
}
/** Cycle repeat mode: OFF → ALL → ONE → OFF */
fun toggleRepeat() {
controller?.let {
it.repeatMode = when (it.repeatMode) {
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
else -> Player.REPEAT_MODE_OFF
}
}
}
// ============ Queue Management ============
/**
* Insert a song to play after the current track.
* @param song The song to insert
*/
fun playNext(song: Song) {
val mediaItem = buildMediaItem(song)
controller?.let {
val nextIndex = it.currentMediaItemIndex + 1
it.addMediaItem(nextIndex, mediaItem)
}
}
/**
* Add a song to the end of the queue.
* @param song The song to add
*/
fun addToQueue(song: Song) = addToQueue(listOf(song))
/**
* Add multiple songs to the end of the queue.
* @param songs The songs to add
*/
fun addToQueue(songs: List<Song>) {
val mediaItems = songs.map { buildMediaItem(it) }
controller?.addMediaItems(mediaItems)
}
/**
* Get the current playback queue.
* @return List of songs in the queue
*/
fun getQueue(): List<Song> {
val ctrl = controller ?: return emptyList()
return (0 until ctrl.mediaItemCount).map { i ->
val item = ctrl.getMediaItemAt(i)
val meta = item.mediaMetadata
Song(
id = item.mediaId.toLongOrNull() ?: 0,
title = meta.title?.toString() ?: "Unknown",
artist = meta.artist?.toString() ?: "Unknown Artist",
album = meta.albumTitle?.toString() ?: "Unknown Album",
albumId = meta.extras?.getLong("album_id") ?: 0L,
duration = 0,
uri = item.localConfiguration?.uri ?: Uri.EMPTY,
path = meta.extras?.getString("path") ?: "",
dateAdded = 0,
size = 0
)
}
}
// ============ Sleep Timer (Delegated) ============
/**
* Start a sleep timer. Playback will pause after the specified duration.
* @param minutes Duration in minutes (0 to cancel)
*/
fun setSleepTimer(minutes: Int) = sleepTimerManager.setTimer(minutes)
/** Cancel the active sleep timer */
fun cancelSleepTimer() = sleepTimerManager.cancel()
/** Check if sleep timer is active */
fun isSleepTimerActive(): Boolean = sleepTimerManager.isActive()
// ============ Playback Speed (Delegated) ============
/**
* Set playback speed.
* @param speed Valid range: 0.25 to 3.0
*/
fun setPlaybackSpeed(speed: Float) = speedManager.setSpeed(speed)
/** Cycle through speed presets: 0.5x → 0.75x → 1.0x → 1.25x → 1.5x → 2.0x */
fun cyclePlaybackSpeed() = speedManager.cycleSpeed()
/** Reset speed to normal (1.0x) */
fun resetPlaybackSpeed() = speedManager.reset()
// ============ Crossfade ============
/**
* Set crossfade duration for track transitions.
* @param seconds Duration in seconds (0 = disabled)
* Note: Media3 does not natively support crossfade.
*/
fun setCrossfadeDuration(seconds: Int) {
val duration = seconds.coerceIn(0, 12)
_crossfadeDuration.value = duration
crossfadeManager.setDuration(duration)
}
// ============ Lifecycle ============
/** Release all resources. Call when the player is no longer needed. */
fun release() {
stopPositionUpdates()
sleepTimerManager.release()
speedManager.release()
controllerFuture?.let { MediaController.releaseFuture(it) }
controllerFuture = null
scope.cancel()
}
}