react-native-audio-browser 0.2.0-next.50 → 0.2.0-next.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/android/build.gradle +15 -0
  2. package/android/src/cast/java/com/audiobrowser/cast/CastSupport.kt +215 -0
  3. package/android/src/main/AndroidManifest.xml +11 -0
  4. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +0 -4
  5. package/android/src/main/java/com/audiobrowser/RemoteOutputs.kt +47 -10
  6. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +12 -3
  7. package/android/src/main/java/com/audiobrowser/player/EqualizerController.kt +4 -1
  8. package/android/src/main/java/com/audiobrowser/player/LocalEngine.kt +49 -0
  9. package/android/src/main/java/com/audiobrowser/player/Player.kt +170 -119
  10. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +18 -13
  11. package/android/src/main/java/com/audiobrowser/player/TransformingDataSource.kt +10 -13
  12. package/android/src/main/java/com/audiobrowser/remote/RemoteItem.kt +64 -0
  13. package/android/src/main/java/com/audiobrowser/remote/RemoteOutputsController.kt +98 -0
  14. package/android/src/main/java/com/audiobrowser/remote/RemotePlayback.kt +42 -0
  15. package/android/src/main/java/com/audiobrowser/remote/RemoteQueue.kt +110 -0
  16. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +696 -0
  17. package/android/src/main/java/com/audiobrowser/sonos/DeviceDescriptionParser.kt +113 -0
  18. package/android/src/main/java/com/audiobrowser/sonos/DidlLite.kt +39 -0
  19. package/android/src/main/java/com/audiobrowser/sonos/SoapClient.kt +59 -0
  20. package/android/src/main/java/com/audiobrowser/sonos/SoapEnvelopes.kt +92 -0
  21. package/android/src/main/java/com/audiobrowser/sonos/SoapResponseParser.kt +105 -0
  22. package/android/src/main/java/com/audiobrowser/sonos/SonosDiscoverer.kt +69 -0
  23. package/android/src/main/java/com/audiobrowser/sonos/SonosOutputs.kt +128 -0
  24. package/android/src/main/java/com/audiobrowser/sonos/SonosPlayer.kt +550 -0
  25. package/android/src/main/java/com/audiobrowser/sonos/SonosRemote.kt +99 -0
  26. package/android/src/main/java/com/audiobrowser/sonos/SonosRouteProviderService.kt +201 -0
  27. package/android/src/main/java/com/audiobrowser/sonos/SonosStreamUri.kt +15 -0
  28. package/android/src/main/java/com/audiobrowser/sonos/SonosTransport.kt +66 -0
  29. package/android/src/main/java/com/audiobrowser/sonos/SpeakerXml.kt +26 -0
  30. package/android/src/main/java/com/audiobrowser/sonos/SsdpDiscovery.kt +63 -0
  31. package/android/src/main/java/com/audiobrowser/sonos/SsdpMessages.kt +63 -0
  32. package/android/src/main/java/com/audiobrowser/sonos/ZoneGroupState.kt +68 -0
  33. package/android/src/main/java/com/audiobrowser/util/OutputMonitor.kt +2 -1
  34. package/android/src/nocast/java/com/audiobrowser/cast/CastSupport.kt +18 -0
  35. package/android/src/test/java/com/audiobrowser/RemoteOutputsTest.kt +20 -3
  36. package/android/src/test/java/com/audiobrowser/model/PlayerSetupOptionsTest.kt +35 -0
  37. package/android/src/test/java/com/audiobrowser/player/EqualizerControllerTest.kt +12 -0
  38. package/android/src/test/java/com/audiobrowser/player/PlayerCastTest.kt +136 -0
  39. package/android/src/test/java/com/audiobrowser/player/PlayerSonosTest.kt +213 -0
  40. package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +275 -0
  41. package/android/src/test/java/com/audiobrowser/remote/RemoteItemTest.kt +61 -0
  42. package/android/src/test/java/com/audiobrowser/remote/RemoteOutputsControllerTest.kt +77 -0
  43. package/android/src/test/java/com/audiobrowser/remote/RemoteQueueTest.kt +101 -0
  44. package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +815 -0
  45. package/android/src/test/java/com/audiobrowser/sonos/DeviceDescriptionParserTest.kt +203 -0
  46. package/android/src/test/java/com/audiobrowser/sonos/DidlLiteTest.kt +90 -0
  47. package/android/src/test/java/com/audiobrowser/sonos/SoapClientTest.kt +73 -0
  48. package/android/src/test/java/com/audiobrowser/sonos/SoapEnvelopesTest.kt +135 -0
  49. package/android/src/test/java/com/audiobrowser/sonos/SoapResponseParserTest.kt +170 -0
  50. package/android/src/test/java/com/audiobrowser/sonos/SonosDiscovererTest.kt +174 -0
  51. package/android/src/test/java/com/audiobrowser/sonos/SonosPlayerTest.kt +691 -0
  52. package/android/src/test/java/com/audiobrowser/sonos/SonosRemoteTest.kt +129 -0
  53. package/android/src/test/java/com/audiobrowser/sonos/SonosRoutesTest.kt +165 -0
  54. package/android/src/test/java/com/audiobrowser/sonos/SonosStreamUriTest.kt +64 -0
  55. package/android/src/test/java/com/audiobrowser/sonos/SonosTransportTest.kt +204 -0
  56. package/android/src/test/java/com/audiobrowser/sonos/SsdpMessagesTest.kt +99 -0
  57. package/android/src/test/java/com/audiobrowser/sonos/ZoneGroupStateTest.kt +139 -0
  58. package/android/src/test/java/com/audiobrowser/util/OutputMonitorTest.kt +12 -10
  59. package/android/src/test/resources/sonos/device_description.xml +78 -0
  60. package/android/src/testCast/java/com/audiobrowser/cast/CastEndsTest.kt +56 -0
  61. package/android/src/testCast/java/com/audiobrowser/cast/SendingMediaItemConverterTest.kt +79 -0
  62. package/lib/commonjs/features/player/setup.js +2 -0
  63. package/lib/commonjs/features/player/setup.js.map +1 -1
  64. package/lib/module/features/player/setup.js +2 -0
  65. package/lib/module/features/player/setup.js.map +1 -1
  66. package/lib/typescript/src/features/player/setup.d.ts +37 -7
  67. package/lib/typescript/src/features/player/setup.d.ts.map +1 -1
  68. package/lib/typescript/src/specs/audio-browser.nitro.d.ts +3 -3
  69. package/lib/typescript/src/specs/audio-browser.nitro.d.ts.map +1 -1
  70. package/nitrogen/generated/android/c++/JHybridAudioBrowserSpec.cpp +4 -0
  71. package/nitrogen/generated/android/c++/JNativeSetupPlayerOptions.hpp +7 -5
  72. package/nitrogen/generated/android/c++/JOutputType.hpp +3 -0
  73. package/nitrogen/generated/android/c++/JRemoteOutputsOptions.hpp +66 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/NativeSetupPlayerOptions.kt +3 -3
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/OutputType.kt +3 -2
  76. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/RemoteOutputsOptions.kt +61 -0
  77. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Bridge.hpp +18 -0
  78. package/nitrogen/generated/ios/AudioBrowser-Swift-Cxx-Umbrella.hpp +3 -0
  79. package/nitrogen/generated/ios/c++/HybridAudioBrowserSpecSwift.hpp +3 -0
  80. package/nitrogen/generated/ios/swift/NativeSetupPlayerOptions.swift +5 -12
  81. package/nitrogen/generated/ios/swift/OutputType.swift +4 -0
  82. package/nitrogen/generated/ios/swift/RemoteOutputsOptions.swift +78 -0
  83. package/nitrogen/generated/shared/c++/NativeSetupPlayerOptions.hpp +8 -5
  84. package/nitrogen/generated/shared/c++/OutputType.hpp +6 -2
  85. package/nitrogen/generated/shared/c++/RemoteOutputsOptions.hpp +92 -0
  86. package/package.json +1 -1
  87. package/src/features/player/setup.ts +38 -7
  88. package/src/specs/audio-browser.nitro.ts +4 -3
  89. package/website/guide/audio-output.md +185 -4
  90. package/website/guide/configuration.md +6 -0
@@ -210,11 +210,11 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
210
210
  val event =
211
211
  when (events[i]) {
212
212
  MediaPlayer.EVENT_PLAYBACK_STATE_CHANGED ->
213
- // Read the real ExoPlayer state, not the forwarding player's — the InterceptingPlayer
214
- // masks STATE_IDLE→READY on a terminal error, and that mask must not feed back into
215
- // our own state machine (it would clear the ERROR state/subtitle).
213
+ // Read the session player's real state, not the forwarding player's: the
214
+ // InterceptingPlayer masks STATE_IDLE→READY on a terminal error, and that mask must
215
+ // not feed back into our own state machine (it would clear the ERROR state/subtitle).
216
216
  PlaybackEvent.ExoPlaybackStateChanged(
217
- player.exoPlayer.playbackState,
217
+ player.sessionPlayer.playbackState,
218
218
  media3Player.mediaItemCount,
219
219
  player.shouldPlayWhenReady,
220
220
  )
@@ -224,7 +224,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
224
224
  MediaPlayer.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED ->
225
225
  PlaybackEvent.ShouldPlayWhenReadyChanged(
226
226
  player.shouldPlayWhenReady,
227
- player.exoPlayer.playbackState,
227
+ player.sessionPlayer.playbackState,
228
228
  )
229
229
  MediaPlayer.EVENT_IS_PLAYING_CHANGED -> PlaybackEvent.IsPlayingChanged(player.isPlaying)
230
230
  else -> null
@@ -243,12 +243,17 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
243
243
  }
244
244
 
245
245
  override fun onPlayerError(error: PlaybackException) {
246
+ if (player.localEngine.isActive && recoverLocally(error)) return
247
+ surface(error)
248
+ }
249
+
250
+ /** Recovers what the local engine can recover by itself; false for an error to surface. */
251
+ private fun recoverLocally(error: PlaybackException): Boolean {
246
252
  // Handle live stream recovery when playback position falls behind the live window
247
253
  if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) {
248
254
  Timber.d("Playback fell behind live window, recovering to live edge")
249
- player.exoPlayer.seekToDefaultPosition()
250
- player.exoPlayer.prepare()
251
- return
255
+ player.localEngine.retry(toLiveEdge = true)
256
+ return true
252
257
  }
253
258
 
254
259
  // media3 1.9.0+ stuck-player detection arrives here wrapped in a PlaybackException: the actual
@@ -261,9 +266,12 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
261
266
  .firstOrNull()
262
267
  if (stuck != null) {
263
268
  handleStuckPlayer(stuck)
264
- return
269
+ return true
265
270
  }
271
+ return false
272
+ }
266
273
 
274
+ private fun surface(error: PlaybackException) {
267
275
  val online = player.networkMonitor.getOnline()
268
276
  // `code` stays the raw ExoPlayer name for telemetry; `kind` is the normalized classification
269
277
  // consumers branch on. Offline is the one distinction ExoPlayer's codes cannot make on their
@@ -307,10 +315,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
307
315
  "Stuck player recovery: type=${error.stuckType} timeoutMs=${error.timeoutMs} " +
308
316
  "live=${player.isCurrentItemLive}"
309
317
  )
310
- if (player.isCurrentItemLive) {
311
- player.exoPlayer.seekToDefaultPosition()
312
- }
313
- player.exoPlayer.prepare()
318
+ player.localEngine.retry(toLiveEdge = player.isCurrentItemLive)
314
319
  }
315
320
  StuckRecoveryPolicy.Decision.GIVE_UP -> {
316
321
  Timber.w("Stuck player recovery exhausted (type=${error.stuckType}), surfacing error")
@@ -137,19 +137,7 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
137
137
  return try {
138
138
  val requestConfig = factory.getRequestConfig(originalUrl)
139
139
  if (requestConfig != null) {
140
- val path = requestConfig.path ?: ""
141
- val baseUrl = requestConfig.baseUrl
142
- val url = BrowserPathHelper.buildUrl(baseUrl, path)
143
-
144
- val finalUrl =
145
- if (requestConfig.query?.isNotEmpty() == true) {
146
- val uri = Uri.parse(url).buildUpon()
147
- requestConfig.query?.forEach { (key, value) -> uri.appendQueryParameter(key, value) }
148
- uri.build().toString()
149
- } else {
150
- url
151
- }
152
-
140
+ val finalUrl = requestConfig.url()
153
141
  val headers = requestConfig.headers ?: emptyMap()
154
142
  val userAgent = requestConfig.userAgent ?: DEFAULT_USER_AGENT
155
143
 
@@ -196,3 +184,12 @@ class TransformingDataSource(private val upstream: DataSource, private val facto
196
184
  }
197
185
  }
198
186
  }
187
+
188
+ /** The URL this config requests: its path against its base URL, with its query appended. */
189
+ internal fun MediaRequestConfig.url(): String {
190
+ val url = BrowserPathHelper.buildUrl(baseUrl, path ?: "")
191
+ val query = query?.takeIf { it.isNotEmpty() } ?: return url
192
+ val uri = Uri.parse(url).buildUpon()
193
+ query.forEach { (key, value) -> uri.appendQueryParameter(key, value) }
194
+ return uri.build().toString()
195
+ }
@@ -0,0 +1,64 @@
1
+ package com.audiobrowser.remote
2
+
3
+ import android.webkit.MimeTypeMap
4
+ import androidx.core.net.toUri
5
+ import androidx.media3.common.C
6
+ import androidx.media3.common.MediaItem
7
+ import androidx.media3.common.MediaMetadata
8
+ import androidx.media3.common.MimeTypes
9
+ import androidx.media3.common.util.Util
10
+
11
+ /**
12
+ * [item] as a receiver loads it, which fetches its URL and artwork itself, without request headers:
13
+ * [url], its MIME type, artwork only over http(s), and a [live] item as a live stream (its live
14
+ * configuration set, a radio station in its metadata) that loads at its live edge.
15
+ */
16
+ internal fun remoteItemOf(
17
+ item: MediaItem,
18
+ url: String,
19
+ artworkUrl: String?,
20
+ live: Boolean,
21
+ ): MediaItem {
22
+ val artwork =
23
+ (artworkUrl?.toUri() ?: item.mediaMetadata.artworkUri)?.takeIf {
24
+ it.scheme == "http" || it.scheme == "https"
25
+ }
26
+ val metadata =
27
+ item.mediaMetadata
28
+ .buildUpon()
29
+ .setArtworkUri(artwork)
30
+ .apply { if (live) setMediaType(MediaMetadata.MEDIA_TYPE_RADIO_STATION) }
31
+ .build()
32
+ return item
33
+ .buildUpon()
34
+ .setUri(url)
35
+ .setMimeType(remoteMimeType(url, item.localConfiguration?.mimeType))
36
+ .setMediaMetadata(metadata)
37
+ .setLiveConfiguration(if (live) LIVE else MediaItem.LiveConfiguration.UNSET)
38
+ .build()
39
+ }
40
+
41
+ /**
42
+ * The MIME type a receiver is told for [url]: [declared] when the item has one, else inferred from
43
+ * the URL. A stream without a recognised extension is `audio/mpeg`: a Cast receiver skips an item
44
+ * with no type and sniffs the codec of one it plays.
45
+ */
46
+ internal fun remoteMimeType(url: String, declared: String?): String {
47
+ if (declared != null) return declared
48
+ when (Util.inferContentType(url.toUri())) {
49
+ C.CONTENT_TYPE_HLS -> return MimeTypes.APPLICATION_M3U8
50
+ C.CONTENT_TYPE_DASH -> return MimeTypes.APPLICATION_MPD
51
+ }
52
+ val extension = MimeTypeMap.getFileExtensionFromUrl(url)
53
+ return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)?.takeIf {
54
+ MimeTypes.isAudio(it)
55
+ } ?: MimeTypes.AUDIO_MPEG
56
+ }
57
+
58
+ /** Whether a receiver loads [item] as a live stream. */
59
+ internal val MediaItem.isRemoteLive: Boolean
60
+ get() = liveConfiguration != MediaItem.LiveConfiguration.UNSET
61
+
62
+ // No speed adjustment at the live edge.
63
+ private val LIVE: MediaItem.LiveConfiguration =
64
+ MediaItem.LiveConfiguration.Builder().setMinPlaybackSpeed(1f).setMaxPlaybackSpeed(1f).build()
@@ -0,0 +1,98 @@
1
+ package com.audiobrowser.remote
2
+
3
+ import android.content.Context
4
+ import androidx.annotation.MainThread
5
+ import androidx.media3.common.MediaItem
6
+ import androidx.media3.common.Player as MediaPlayer
7
+ import com.audiobrowser.RemoteOutputs
8
+ import com.audiobrowser.cast.castRouteCategory
9
+ import com.audiobrowser.sonos.SonosOutputs
10
+ import com.margelo.nitro.audiobrowser.OutputType
11
+ import com.margelo.nitro.audiobrowser.RemoteOutputsOptions
12
+ import com.margelo.nitro.audiobrowser.Track
13
+ import kotlinx.coroutines.CoroutineScope
14
+ import kotlinx.coroutines.Dispatchers
15
+ import kotlinx.coroutines.MainScope
16
+ import kotlinx.coroutines.cancel
17
+ import kotlinx.coroutines.withContext
18
+
19
+ /**
20
+ * The URLs a receiver fetches for a track: its media through the media transform, and its artwork.
21
+ */
22
+ internal data class RemoteUrls(val url: String, val artworkUrl: String?)
23
+
24
+ /**
25
+ * The remote outputs as the app sets them up: the Output Switcher's routes and the Sonos route
26
+ * provider, the remote of each output turned on, and the [RemoteSwitchingPlayer] that plays on
27
+ * them, with the items it sends resolved through [resolveUrls].
28
+ */
29
+ internal class RemoteOutputsController(
30
+ private val context: Context,
31
+ private val resolveUrls: suspend (Track) -> RemoteUrls,
32
+ private val castRemote: (Context, String?) -> RemotePlayback?,
33
+ private val sonosRemote: (Context, CoroutineScope) -> RemotePlayback,
34
+ ) {
35
+ private val scope = MainScope()
36
+ private var options: RemoteOutputsOptions? = null
37
+ private var cast: RemotePlayback? = null
38
+ private var sonos: RemotePlayback? = null
39
+
40
+ /** What plays while any output is on, or null. */
41
+ var player: RemoteSwitchingPlayer? = null
42
+ private set
43
+
44
+ /**
45
+ * Turns the outputs in [options] on and the rest off; null turns remote outputs off. An output
46
+ * that stays on keeps its session and what it plays. Returns whether [player] changed.
47
+ */
48
+ @MainThread
49
+ fun apply(options: RemoteOutputsOptions?, local: MediaPlayer): Boolean {
50
+ val wantCast = options?.cast == true
51
+ val wantSonos = options?.sonos == true
52
+ val receiver = options?.castReceiverApplicationId
53
+ val types = buildMap {
54
+ castRouteCategory(receiver)?.takeIf { wantCast }?.let { put(it, OutputType.CAST) }
55
+ if (wantSonos) put(SonosOutputs.CATEGORY, OutputType.SONOS)
56
+ }
57
+ RemoteOutputs.setEnabled(context, options != null, types)
58
+ SonosOutputs.setEnabled(context, wantSonos)
59
+ val had = this.options
60
+ this.options = options
61
+ if (wantCast != (had?.cast == true))
62
+ cast = if (wantCast) castRemote(context, receiver) else null
63
+ if (wantSonos != (had?.sonos == true))
64
+ sonos = if (wantSonos) sonosRemote(context, scope) else null
65
+ val remotes = listOfNotNull(cast, sonos)
66
+ val previous = player
67
+ player =
68
+ when {
69
+ remotes.isEmpty() -> null.also { previous?.release() }
70
+ previous == null -> RemoteSwitchingPlayer(local, remotes, ::resolve, scope)
71
+ else -> previous.also { it.setRemotes(remotes) }
72
+ }
73
+ return player !== previous
74
+ }
75
+
76
+ fun setLocal(local: MediaPlayer) {
77
+ player?.setLocal(local)
78
+ }
79
+
80
+ /** Brings playback back here and lets go of the outputs. Remote outputs stay as set up. */
81
+ fun release() {
82
+ player?.release()
83
+ player = null
84
+ cast = null
85
+ sonos = null
86
+ options = null
87
+ scope.cancel()
88
+ }
89
+
90
+ /** [item] as a receiver loads it, its URLs resolved off the main thread. */
91
+ private suspend fun resolve(item: MediaItem): MediaItem {
92
+ val track = item.localConfiguration?.tag as? Track
93
+ val urls =
94
+ if (track != null) withContext(Dispatchers.IO) { resolveUrls(track) }
95
+ else RemoteUrls(checkNotNull(item.localConfiguration?.uri) { "No URL" }.toString(), null)
96
+ return remoteItemOf(item, urls.url, urls.artworkUrl, live = track?.live == true)
97
+ }
98
+ }
@@ -0,0 +1,42 @@
1
+ package com.audiobrowser.remote
2
+
3
+ import androidx.media3.common.PlaybackException
4
+ import androidx.media3.common.Player as MediaPlayer
5
+
6
+ /**
7
+ * A remote output's side of [RemoteSwitchingPlayer]: a Cast receiver or a Sonos room, each kept
8
+ * apart from its SDK or protocol so the rest of the library compiles without them.
9
+ */
10
+ internal interface RemotePlayback {
11
+ /**
12
+ * Plays one item at a time on the receiver, read while [isSessionAvailable]. Setting its item
13
+ * loads it there, from the start position given, and plays as its play intent says, without
14
+ * [MediaPlayer.prepare]. A session can bring a new player: the switch moves playback to it.
15
+ */
16
+ val player: MediaPlayer
17
+
18
+ val isSessionAvailable: Boolean
19
+
20
+ /** Calls [listener] on the main thread; null stops the calls. */
21
+ fun setListener(listener: Listener?)
22
+
23
+ /** Ends the session on this side; the receiver stops or plays on as it was told. */
24
+ fun release()
25
+
26
+ interface Listener {
27
+ /** [isSessionAvailable] or [player] changed. */
28
+ fun onSessionChanged()
29
+
30
+ /**
31
+ * The receiver reports its item playing, as it plays it: [player]'s own play state follows a
32
+ * play as soon as it is asked.
33
+ */
34
+ fun onPlaying()
35
+
36
+ /** The receiver played its item to the end: the only end the switch acts on. */
37
+ fun onEnded()
38
+
39
+ /** The receiver failed to play its item: the only failure the switch acts on. */
40
+ fun onFailed(error: PlaybackException)
41
+ }
42
+ }
@@ -0,0 +1,110 @@
1
+ package com.audiobrowser.remote
2
+
3
+ import androidx.media3.common.C
4
+ import androidx.media3.common.MediaItem
5
+ import androidx.media3.common.Player as MediaPlayer
6
+ import androidx.media3.common.util.Util
7
+
8
+ /**
9
+ * The queue [RemoteSwitchingPlayer] keeps while remote: its items, each with a uid of its own, and
10
+ * the current one. It plays in list order.
11
+ */
12
+ internal class RemoteQueue {
13
+ private val itemList = mutableListOf<MediaItem>()
14
+ private val uidList = mutableListOf<Any>()
15
+
16
+ val items: List<MediaItem>
17
+ get() = itemList
18
+
19
+ val uids: List<Any>
20
+ get() = uidList
21
+
22
+ var index = C.INDEX_UNSET
23
+ private set
24
+
25
+ val current: MediaItem?
26
+ get() = itemList.getOrNull(index)
27
+
28
+ val isEmpty: Boolean
29
+ get() = itemList.isEmpty()
30
+
31
+ fun set(newItems: List<MediaItem>, newIndex: Int) {
32
+ itemList.clear()
33
+ itemList.addAll(newItems)
34
+ uidList.clear()
35
+ uidList.addAll(newItems.map { Any() })
36
+ index = if (newItems.isEmpty()) C.INDEX_UNSET else newIndex.coerceIn(0, newItems.size - 1)
37
+ }
38
+
39
+ fun add(at: Int, newItems: List<MediaItem>) {
40
+ val to = at.coerceIn(0, itemList.size)
41
+ itemList.addAll(to, newItems)
42
+ uidList.addAll(to, newItems.map { Any() })
43
+ when {
44
+ index == C.INDEX_UNSET -> index = 0
45
+ index >= to -> index += newItems.size
46
+ }
47
+ }
48
+
49
+ /** Removes the items from [fromIndex] to [toIndex]; true when the current one went with them. */
50
+ fun remove(fromIndex: Int, toIndex: Int): Boolean {
51
+ val to = toIndex.coerceAtMost(itemList.size)
52
+ val removesCurrent = index in fromIndex until to
53
+ itemList.subList(fromIndex, to).clear()
54
+ uidList.subList(fromIndex, to).clear()
55
+ index =
56
+ when {
57
+ itemList.isEmpty() -> C.INDEX_UNSET
58
+ removesCurrent -> fromIndex.coerceAtMost(itemList.size - 1)
59
+ index >= to -> index - (to - fromIndex)
60
+ else -> index
61
+ }
62
+ return removesCurrent
63
+ }
64
+
65
+ /**
66
+ * Puts [newItems] in place of the items from [fromIndex] to [toIndex]. True when the current item
67
+ * is now another media; a restamp of its metadata alone is not.
68
+ */
69
+ fun replace(fromIndex: Int, toIndex: Int, newItems: List<MediaItem>): Boolean {
70
+ val to = toIndex.coerceAtMost(itemList.size)
71
+ if (to - fromIndex == newItems.size) {
72
+ val before = current
73
+ newItems.forEachIndexed { offset, item -> itemList[fromIndex + offset] = item }
74
+ val after = current
75
+ return before != null &&
76
+ after != null &&
77
+ (before.mediaId != after.mediaId ||
78
+ before.localConfiguration?.uri != after.localConfiguration?.uri)
79
+ }
80
+ val replacesCurrent = remove(fromIndex, to)
81
+ add(fromIndex, newItems)
82
+ if (replacesCurrent) index = fromIndex.coerceAtMost(itemList.size - 1)
83
+ return replacesCurrent
84
+ }
85
+
86
+ fun move(fromIndex: Int, toIndex: Int, newIndex: Int) {
87
+ val current = uidList.getOrNull(index)
88
+ val to = toIndex.coerceAtMost(itemList.size)
89
+ Util.moveItems(itemList, fromIndex, to, newIndex)
90
+ Util.moveItems(uidList, fromIndex, to, newIndex)
91
+ index = uidList.indexOf(current)
92
+ }
93
+
94
+ fun moveTo(newIndex: Int) {
95
+ require(newIndex in itemList.indices) { "No item at $newIndex" }
96
+ index = newIndex
97
+ }
98
+
99
+ /**
100
+ * The item that follows the current one at its end, or [C.INDEX_UNSET] at the end of the queue.
101
+ */
102
+ fun nextAtEnd(repeatMode: Int): Int =
103
+ when {
104
+ isEmpty -> C.INDEX_UNSET
105
+ repeatMode == MediaPlayer.REPEAT_MODE_ONE -> index
106
+ index + 1 < itemList.size -> index + 1
107
+ repeatMode == MediaPlayer.REPEAT_MODE_ALL -> 0
108
+ else -> C.INDEX_UNSET
109
+ }
110
+ }