react-native-audio-browser 0.2.0-next.41 → 0.2.0-next.43

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.
@@ -918,8 +918,8 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
918
918
 
919
919
  override fun load(track: Track) {
920
920
  // Throws without a player, as on iOS: a track asked for and silently dropped hides a mistake.
921
- val player = player
922
- launchInScope { player.load(track) }
921
+ // Blocks rather than launching, so a track the player refuses fails this call.
922
+ runBlockingOnMain { player.load(track) }
923
923
  }
924
924
 
925
925
  override fun reset() =
@@ -90,7 +90,7 @@ class MediaSessionCommandManager {
90
90
  else -> CommandButton.ICON_SKIP_BACK
91
91
  }
92
92
 
93
- /** Player commands available to every controller, derived from capabilities alone */
93
+ /** Player commands available to every controller, derived from capabilities and liveness */
94
94
  var playerCommands: MediaPlayer.Commands = MediaSession.ConnectionResult.DEFAULT_PLAYER_COMMANDS
95
95
  private set
96
96
 
@@ -120,6 +120,7 @@ class MediaSessionCommandManager {
120
120
  )
121
121
  private var currentRemoteButtonLayout: RemoteButtonLayout? = null
122
122
  private var currentFavorited: Boolean? = null
123
+ private var currentLive: Boolean = false
123
124
  private var currentForwardJumpInterval: Double = DEFAULT_JUMP_INTERVAL
124
125
  private var currentBackwardJumpInterval: Double = DEFAULT_JUMP_INTERVAL
125
126
 
@@ -142,7 +143,7 @@ class MediaSessionCommandManager {
142
143
  // Initialize with defaults matching PlayerUpdateOptions (all capabilities enabled)
143
144
  val defaultCapabilities = currentCapabilities
144
145
 
145
- playerCommands = buildPlayerCommands(defaultCapabilities)
146
+ playerCommands = buildPlayerCommands(defaultCapabilities, live = false)
146
147
  sessionCommands = buildSessionCommands(defaultCapabilities, searchAvailable = false)
147
148
  buttonPreferences =
148
149
  buildButtonPreferences(
@@ -183,22 +184,39 @@ class MediaSessionCommandManager {
183
184
  currentForwardJumpInterval = forwardJumpInterval
184
185
  currentBackwardJumpInterval = backwardJumpInterval
185
186
 
186
- // Commands gate on capabilities only — placement never revokes one, so a control left out of
187
- // the layout still works from a Bluetooth remote or headset.
188
- playerCommands = buildPlayerCommands(capabilities)
187
+ // Commands gate on capabilities and liveness, never on placement, so a control left out of the
188
+ // layout still works from a Bluetooth remote or headset.
189
+ playerCommands = buildPlayerCommands(capabilities, currentLive)
189
190
  sessionCommands = buildSessionCommands(capabilities, searchAvailable)
190
191
  buttonPreferences =
191
192
  buildButtonPreferences(deriveButtonSlots(capabilities, remoteButtonLayout), currentFavorited)
192
193
 
193
- // Push the rebuilt commands to already-connected controllers — buildConnectionResult only
194
- // serves controllers that connect later, and an Android Auto session lives until the car shuts
195
- // down. Granted before the layout broadcast so a newly-added button arrives with its command
196
- // already available; Media3 disables buttons whose backing command is missing.
194
+ // Granted before the layout broadcast so a newly-added button arrives with its command already
195
+ // available; Media3 disables buttons whose backing command is missing.
196
+ publishAvailableCommands(mediaSession)
197
+ publishButtonPreferences(mediaSession)
198
+ }
199
+
200
+ /**
201
+ * Withholds seeking within the current item while it is live, whatever the `seekTo` capability
202
+ * says: a controller offered that command draws a seek bar, which a live stream has nothing to
203
+ * fill. Call this whenever the current track may have changed.
204
+ */
205
+ fun updateLiveState(mediaSession: MediaSession, live: Boolean) {
206
+ if (currentLive == live) return
207
+ currentLive = live
208
+ playerCommands = buildPlayerCommands(currentCapabilities, live)
209
+ publishAvailableCommands(mediaSession)
210
+ }
211
+
212
+ /**
213
+ * Pushes the commands to already-connected controllers — [buildConnectionResult] only serves
214
+ * controllers that connect later, and an Android Auto session lives until the car shuts down.
215
+ */
216
+ private fun publishAvailableCommands(mediaSession: MediaSession) {
197
217
  mediaSession.connectedControllers.forEach {
198
218
  mediaSession.setAvailableCommands(it, sessionCommands, playerCommands)
199
219
  }
200
-
201
- publishButtonPreferences(mediaSession)
202
220
  }
203
221
 
204
222
  /**
@@ -301,7 +319,10 @@ class MediaSessionCommandManager {
301
319
  }
302
320
  }
303
321
 
304
- private fun buildPlayerCommands(capabilities: PlayerCapabilities): MediaPlayer.Commands {
322
+ private fun buildPlayerCommands(
323
+ capabilities: PlayerCapabilities,
324
+ live: Boolean,
325
+ ): MediaPlayer.Commands {
305
326
  val playerCommandsBuilder = MediaSession.ConnectionResult.DEFAULT_PLAYER_COMMANDS.buildUpon()
306
327
 
307
328
  // Always filter out direct media item commands to avoid dual-command confusion.
@@ -316,6 +337,10 @@ class MediaSessionCommandManager {
316
337
  }
317
338
  }
318
339
 
340
+ if (live) {
341
+ playerCommandsBuilder.remove(MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)
342
+ }
343
+
319
344
  return playerCommandsBuilder.build()
320
345
  }
321
346
 
@@ -933,6 +933,11 @@ class Player(internal val context: Context) {
933
933
  mediaSessionCallback.commandManager.updateFavoriteState(mediaSession, favorited)
934
934
  }
935
935
 
936
+ internal fun updateLiveState(live: Boolean) {
937
+ if (!::mediaSession.isInitialized) return
938
+ mediaSessionCallback.commandManager.updateLiveState(mediaSession, live)
939
+ }
940
+
936
941
  /** Removes all the upcoming tracks, if any (the ones returned by [next]). */
937
942
  fun removeUpcomingTracks() {
938
943
  val index = exoPlayer.currentMediaItemIndex
@@ -116,6 +116,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
116
116
 
117
117
  // Update favorite button state for new track
118
118
  player.updateFavoriteButtonState(player.currentTrack?.favorited)
119
+ player.updateLiveState(player.currentTrack?.live == true)
119
120
 
120
121
  // Clear now playing override when track changes (new track = clean slate)
121
122
  player.nowPlaying.clearOverride()
@@ -351,6 +352,9 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
351
352
  // Only emit for playlist changes, not initial load or other reasons
352
353
  if (reason == MediaPlayer.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED) {
353
354
  player.callbacks?.onPlaybackQueueChanged(player.tracks)
355
+ // Replacing the current item with one of the same URL updates it in place, without a
356
+ // transition, so a changed `live` arrives only here.
357
+ player.updateLiveState(player.currentTrack?.live == true)
354
358
  }
355
359
  }
356
360
 
@@ -0,0 +1,138 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Looper
4
+ import androidx.media3.common.ForwardingPlayer
5
+ import androidx.media3.common.Player as MediaPlayer
6
+ import androidx.media3.exoplayer.ExoPlayer
7
+ import androidx.media3.session.MediaController
8
+ import androidx.media3.session.MediaSession
9
+ import com.margelo.nitro.audiobrowser.PlayerCapabilities
10
+ import org.junit.After
11
+ import org.junit.Assert.assertEquals
12
+ import org.junit.Assert.assertFalse
13
+ import org.junit.Assert.assertTrue
14
+ import org.junit.Test
15
+ import org.junit.runner.RunWith
16
+ import org.robolectric.RobolectricTestRunner
17
+ import org.robolectric.RuntimeEnvironment
18
+ import org.robolectric.Shadows.shadowOf
19
+
20
+ // Robolectric: a MediaSession needs the framework.
21
+ @RunWith(RobolectricTestRunner::class)
22
+ class LiveSeekCommandTest {
23
+
24
+ private val app = RuntimeEnvironment.getApplication()
25
+ private val exoPlayer = ExoPlayer.Builder(app).build()
26
+ // A controller sees the session's grant intersected with the player's own commands, and an empty
27
+ // player cannot seek, so this one offers every command to leave only the session's grant.
28
+ private val session =
29
+ MediaSession.Builder(
30
+ app,
31
+ object : ForwardingPlayer(exoPlayer) {
32
+ override fun getAvailableCommands() =
33
+ MediaPlayer.Commands.Builder().addAllCommands().build()
34
+
35
+ override fun isCommandAvailable(command: Int) = true
36
+ },
37
+ )
38
+ .build()
39
+ private val manager = MediaSessionCommandManager()
40
+
41
+ @After
42
+ fun release() {
43
+ session.release()
44
+ exoPlayer.release()
45
+ }
46
+
47
+ private fun capabilities(seekTo: Boolean? = null) =
48
+ PlayerCapabilities(
49
+ play = null,
50
+ pause = null,
51
+ stop = null,
52
+ seekTo = seekTo,
53
+ skipToNext = null,
54
+ skipToPrevious = null,
55
+ jumpForward = null,
56
+ jumpBackward = null,
57
+ favorite = null,
58
+ shuffleMode = null,
59
+ repeatMode = null,
60
+ playbackRate = null,
61
+ )
62
+
63
+ private fun update(capabilities: PlayerCapabilities) =
64
+ manager.updateMediaSession(
65
+ session,
66
+ capabilities,
67
+ remoteButtonLayout = null,
68
+ searchAvailable = false,
69
+ )
70
+
71
+ private fun offersSeek(): Boolean =
72
+ manager
73
+ .buildConnectionResult(session)
74
+ .availablePlayerCommands
75
+ .contains(MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)
76
+
77
+ @Test
78
+ fun `a live item cannot be seeked, though seekTo is enabled`() {
79
+ update(capabilities(seekTo = true))
80
+ manager.updateLiveState(session, live = true)
81
+ assertFalse(offersSeek())
82
+ }
83
+
84
+ @Test
85
+ fun `seeking returns when the next item is not live`() {
86
+ update(capabilities())
87
+ manager.updateLiveState(session, live = true)
88
+ manager.updateLiveState(session, live = false)
89
+ assertTrue(offersSeek())
90
+ }
91
+
92
+ @Test
93
+ fun `a capability update while live keeps seeking withheld`() {
94
+ manager.updateLiveState(session, live = true)
95
+ update(capabilities(seekTo = true))
96
+ assertFalse(offersSeek())
97
+ }
98
+
99
+ @Test
100
+ fun `a disabled seekTo stays disabled for an item that is not live`() {
101
+ update(capabilities(seekTo = false))
102
+ manager.updateLiveState(session, live = true)
103
+ manager.updateLiveState(session, live = false)
104
+ assertFalse(offersSeek())
105
+ }
106
+
107
+ @Test
108
+ fun `being live takes only seeking away`() {
109
+ update(capabilities())
110
+ val notLive = manager.buildConnectionResult(session).availablePlayerCommands
111
+ manager.updateLiveState(session, live = true)
112
+ val live = manager.buildConnectionResult(session).availablePlayerCommands
113
+ assertEquals(
114
+ notLive.buildUpon().remove(MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM).build(),
115
+ live,
116
+ )
117
+ }
118
+
119
+ @Test
120
+ fun `a controller already connected loses and regains seeking`() {
121
+ val future = MediaController.Builder(app, session.token).buildAsync()
122
+ shadowOf(Looper.getMainLooper()).idle()
123
+ val controller = future.get()
124
+ fun controllerOffersSeek(): Boolean {
125
+ shadowOf(Looper.getMainLooper()).idle()
126
+ return controller.isCommandAvailable(MediaPlayer.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)
127
+ }
128
+
129
+ try {
130
+ manager.updateLiveState(session, live = true)
131
+ assertFalse(controllerOffersSeek())
132
+ manager.updateLiveState(session, live = false)
133
+ assertTrue(controllerOffersSeek())
134
+ } finally {
135
+ controller.release()
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,67 @@
1
+ package com.audiobrowser.player
2
+
3
+ import com.audiobrowser.TestFixtures
4
+ import com.audiobrowser.model.PlayerSetupOptions
5
+ import org.junit.After
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertThrows
8
+ import org.junit.Before
9
+ import org.junit.Test
10
+ import org.junit.runner.RunWith
11
+ import org.robolectric.RobolectricTestRunner
12
+ import org.robolectric.RuntimeEnvironment
13
+
14
+ // Robolectric: Player builds a real ExoPlayer, which needs the framework and a main looper.
15
+ @RunWith(RobolectricTestRunner::class)
16
+ class PlayerInvalidTrackTest {
17
+
18
+ private val player = Player(RuntimeEnvironment.getApplication())
19
+ private val invalid = TestFixtures.track(title = "invalid", src = null)
20
+
21
+ @Before fun setup() = player.setup(PlayerSetupOptions())
22
+
23
+ @After fun release() = player.exoPlayer.release()
24
+
25
+ @Test
26
+ fun loadIntoAnEmptyQueueThrows() {
27
+ assertThrows(IllegalArgumentException::class.java) { player.load(invalid) }
28
+
29
+ assertEquals(emptyList<String>(), titles())
30
+ }
31
+
32
+ @Test
33
+ fun loadOverTheCurrentTrackThrows() {
34
+ player.setQueue(arrayOf(valid("a"), valid("b")), startIndex = 1)
35
+
36
+ assertThrows(IllegalArgumentException::class.java) { player.load(invalid) }
37
+
38
+ assertEquals(listOf("a", "b"), titles())
39
+ assertEquals(1, player.exoPlayer.currentMediaItemIndex)
40
+ }
41
+
42
+ @Test
43
+ fun addThrowsAndAddsNoneOfTheTracks() {
44
+ player.setQueue(arrayOf(valid("a")))
45
+
46
+ assertThrows(IllegalArgumentException::class.java) {
47
+ player.add(arrayOf(valid("b"), invalid), -1)
48
+ }
49
+
50
+ assertEquals(listOf("a"), titles())
51
+ }
52
+
53
+ @Test
54
+ fun setQueueThrowsAndKeepsTheQueue() {
55
+ player.setQueue(arrayOf(valid("a")))
56
+
57
+ assertThrows(IllegalArgumentException::class.java) {
58
+ player.setQueue(arrayOf(valid("b"), invalid))
59
+ }
60
+
61
+ assertEquals(listOf("a"), titles())
62
+ }
63
+
64
+ private fun valid(title: String) = TestFixtures.track(title = title, src = "https://s/$title.mp3")
65
+
66
+ private fun titles() = player.tracks.map { it.title }
67
+ }
@@ -56,7 +56,7 @@ enum MediaIntentPlayback {
56
56
  do {
57
57
  guard let tracks = try await browser.browserManager.searchPlayable(params),
58
58
  let player = livePlayer(of: browser) else { return false }
59
- player.setQueue(tracks, initialIndex: 0, playWhenReady: true)
59
+ try player.setQueue(tracks, initialIndex: 0, playWhenReady: true)
60
60
  browser.showNowPlayingRequestedEmitter.emit(())
61
61
  return true
62
62
  } catch {
@@ -13,7 +13,7 @@ public extension HybridAudioBrowser {
13
13
  guard let player else {
14
14
  throw NSError(domain: "AudioBrowser", code: 1, userInfo: [NSLocalizedDescriptionKey: "Player not initialized"])
15
15
  }
16
- player.load(track)
16
+ try player.load(track)
17
17
  }
18
18
  }
19
19
 
@@ -161,7 +161,7 @@ public extension HybridAudioBrowser {
161
161
  if let index = insertBeforeIndex {
162
162
  try player.add(tracks, at: Int(index))
163
163
  } else {
164
- player.add(tracks)
164
+ try player.add(tracks)
165
165
  }
166
166
  }
167
167
  }
@@ -248,9 +248,9 @@ public extension HybridAudioBrowser {
248
248
  }
249
249
 
250
250
  func setQueue(tracks: [Track], startIndex: Double?, startPosition: Double?) throws {
251
- onMainActor {
251
+ try onMainActor {
252
252
  guard let player else { return }
253
- player.setQueue(
253
+ try player.setQueue(
254
254
  tracks,
255
255
  initialIndex: startIndex.map { Int($0) } ?? 0,
256
256
  startPositionMs: startPosition.map { $0 * 1000 },
@@ -21,6 +21,8 @@ public enum TrackPlayerError: Error {
21
21
  case noCurrentItem
22
22
  case invalidIndex(index: Int, message: String)
23
23
  case empty
24
+ /// A track with neither `src` nor `path`, which no queue can hold.
25
+ case invalidTrack(title: String)
24
26
  }
25
27
  }
26
28
 
@@ -56,6 +58,8 @@ extension TrackPlayerError.QueueError: LocalizedError {
56
58
  "Invalid track index \(index): \(message)"
57
59
  case .empty:
58
60
  "Queue is empty"
61
+ case let .invalidTrack(title):
62
+ "Track must have either path or src defined. Track: title='\(title)'"
59
63
  }
60
64
  }
61
65
  }
@@ -431,7 +431,15 @@ final class Player {
431
431
 
432
432
  // MARK: - Queue Methods
433
433
 
434
- func load(_ track: Track, playWhenReady: Bool? = nil) {
434
+ /// Refuses a track with neither `src` nor `path`, before the queue changes.
435
+ private func throwIfInvalid(_ tracks: [Track]) throws {
436
+ if let track = tracks.first(where: { $0.src == nil && $0.path == nil }) {
437
+ throw TrackPlayerError.QueueError.invalidTrack(title: track.title)
438
+ }
439
+ }
440
+
441
+ func load(_ track: Track, playWhenReady: Bool? = nil) throws {
442
+ try throwIfInvalid([track])
435
443
  handlePlayWhenReady(playWhenReady) {
436
444
  if queue.currentIndex == -1 {
437
445
  afterQueueMutation(queue.add([track], initialIndex: 0))
@@ -457,7 +465,8 @@ final class Player {
457
465
  startPositionMs: Double? = nil,
458
466
  playWhenReady: Bool? = nil,
459
467
  sourcePath: String? = nil,
460
- ) {
468
+ ) throws {
469
+ try throwIfInvalid(newTracks)
461
470
  guard !newTracks.isEmpty else {
462
471
  clear()
463
472
  return
@@ -470,13 +479,15 @@ final class Player {
470
479
  }
471
480
  }
472
481
 
473
- func add(_ tracks: [Track], initialIndex: Int? = nil, playWhenReady: Bool? = nil) {
482
+ func add(_ tracks: [Track], initialIndex: Int? = nil, playWhenReady: Bool? = nil) throws {
483
+ try throwIfInvalid(tracks)
474
484
  handlePlayWhenReady(playWhenReady) {
475
485
  afterQueueMutation(queue.add(tracks, initialIndex: initialIndex ?? 0))
476
486
  }
477
487
  }
478
488
 
479
489
  func add(_ tracks: [Track], at index: Int) throws {
490
+ try throwIfInvalid(tracks)
480
491
  try afterQueueMutation(queue.addAt(tracks, at: index))
481
492
  }
482
493
 
@@ -904,26 +915,30 @@ final class Player {
904
915
  shuffleEnabled = snapshot.shuffleEnabled
905
916
  rate = snapshot.playbackSpeed
906
917
  let startMs = track.live == true ? nil : snapshot.positionMs
907
- if let expanded {
908
- setQueue(expanded.tracks, initialIndex: expanded.selectedIndex, startPositionMs: startMs, playWhenReady: true)
909
- } else {
910
- setQueue([track], initialIndex: 0, startPositionMs: startMs, playWhenReady: true)
918
+ do {
919
+ if let expanded {
920
+ try setQueue(expanded.tracks, initialIndex: expanded.selectedIndex, startPositionMs: startMs, playWhenReady: true)
921
+ } else {
922
+ try setQueue([track], initialIndex: 0, startPositionMs: startMs, playWhenReady: true)
923
+ }
924
+ } catch {
925
+ logger.error("resume: \(error)")
911
926
  }
912
927
  }
913
928
 
914
929
  /// Plays what `TrackSelector` resolved a picked track to.
915
930
  func execute(_ intent: TrackSelector.PlaybackIntent) {
916
- switch intent {
917
- case let .skipTo(index):
918
- do {
931
+ do {
932
+ switch intent {
933
+ case let .skipTo(index):
919
934
  try skipTo(index, playWhenReady: true)
920
- } catch {
921
- logger.error("Failed to skip to track at index \(index): \(error)")
935
+ case let .setQueue(tracks, startIndex, sourcePath):
936
+ try setQueue(tracks, initialIndex: startIndex, playWhenReady: true, sourcePath: sourcePath)
937
+ case let .loadTrack(track):
938
+ try load(track, playWhenReady: true)
922
939
  }
923
- case let .setQueue(tracks, startIndex, sourcePath):
924
- setQueue(tracks, initialIndex: startIndex, playWhenReady: true, sourcePath: sourcePath)
925
- case let .loadTrack(track):
926
- load(track, playWhenReady: true)
940
+ } catch {
941
+ logger.error("Failed to play the selected track: \(error)")
927
942
  }
928
943
  }
929
944
 
@@ -0,0 +1,65 @@
1
+ @testable import AudioBrowserTestable
2
+ import Testing
3
+
4
+ @Suite("Player - invalid tracks")
5
+ @MainActor
6
+ struct PlayerInvalidTrackTests {
7
+ private let invalid = Track(title: "Invalid")
8
+
9
+ private func valid(_ title: String) -> Track {
10
+ Track(src: "https://example.com/\(title).mp3", title: title)
11
+ }
12
+
13
+ private func expectInvalidTrack(_ body: () throws -> Void) {
14
+ let error = #expect(throws: TrackPlayerError.QueueError.self, performing: body)
15
+ guard case .invalidTrack = error else {
16
+ Issue.record("Expected invalidTrack, got \(String(describing: error))")
17
+ return
18
+ }
19
+ }
20
+
21
+ @Test func loadIntoAnEmptyQueueThrows() {
22
+ let player = makePlayer()
23
+
24
+ expectInvalidTrack { try player.load(invalid) }
25
+
26
+ #expect(player.tracks.isEmpty)
27
+ }
28
+
29
+ @Test func loadOverTheCurrentTrackThrows() throws {
30
+ let player = makePlayer()
31
+ try player.setQueue([valid("a"), valid("b")], initialIndex: 1)
32
+
33
+ expectInvalidTrack { try player.load(invalid) }
34
+
35
+ #expect(player.tracks.map(\.title) == ["a", "b"])
36
+ #expect(player.currentTrack?.title == "b")
37
+ }
38
+
39
+ @Test func addThrowsAndAddsNoneOfTheTracks() throws {
40
+ let player = makePlayer()
41
+ try player.setQueue([valid("a")])
42
+
43
+ expectInvalidTrack { try player.add([valid("b"), invalid]) }
44
+ expectInvalidTrack { try player.add([valid("b"), invalid], at: 0) }
45
+
46
+ #expect(player.tracks.map(\.title) == ["a"])
47
+ }
48
+
49
+ @Test func setQueueThrowsAndKeepsTheQueue() throws {
50
+ let player = makePlayer()
51
+ try player.setQueue([valid("a")])
52
+
53
+ expectInvalidTrack { try player.setQueue([valid("b"), invalid]) }
54
+
55
+ #expect(player.tracks.map(\.title) == ["a"])
56
+ }
57
+
58
+ @Test func aTrackWithOnlyAPathIsQueued() throws {
59
+ let player = makePlayer()
60
+
61
+ try player.setQueue([Track(path: "/browse/only", title: "Path")])
62
+
63
+ #expect(player.tracks.map(\.title) == ["Path"])
64
+ }
65
+ }