react-native-audio-browser 0.2.0-next.74 → 0.2.0-next.75

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.
@@ -268,26 +268,13 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
268
268
  Timber.d("A car is connected - pausing instead of stopping")
269
269
  player.pause()
270
270
  stopForeground(STOP_FOREGROUND_REMOVE)
271
- } else if (moduleBound) {
272
- Timber.d("AudioBrowser still bound - stopping playback but keeping the player")
271
+ } else {
272
+ Timber.d("No car connected - stopping playback, moduleBound = $moduleBound")
273
273
  stopPlaybackAndRemoveNotification()
274
- // Ends the service once AudioBrowser unbinds.
274
+ // AudioBrowser keeps the player. Otherwise tear down now: a media controller still bound
275
+ // keeps the service alive after stopSelf().
276
+ if (!moduleBound) tearDown()
275
277
  stopSelf()
276
- } else {
277
- Timber.d("No car connected - shutting the service down")
278
- try {
279
- if (::mediaSession.isInitialized) {
280
- mediaSession.release()
281
- }
282
- stopPlaybackAndRemoveNotification()
283
- tearDownArtworkProvider()
284
- player.destroy()
285
- scope.cancel()
286
- stopSelf()
287
- } catch (e: Exception) {
288
- Timber.e(e, "Error during aggressive cleanup in onTaskRemoved")
289
- stopSelf()
290
- }
291
278
  }
292
279
  }
293
280
 
@@ -340,16 +327,17 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
340
327
  onBatteryWarningPendingChanged?.invoke(true)
341
328
  }
342
329
 
343
- /**
344
- * Cancels the artwork provider's scope and clears its holder. Idempotent. Call it before
345
- * player.destroy() on every teardown path, so no in-flight load reaches a destroyed player.
346
- */
347
- private fun tearDownArtworkProvider() {
330
+ /** Idempotent: a swipe's shutdown runs it, and onDestroy runs it again. */
331
+ private fun tearDown() {
332
+ // Before player.destroy(), so no in-flight artwork load reaches a destroyed player.
348
333
  artworkProviderDeps?.let {
349
334
  it.scope.cancel()
350
335
  CoilArtworkLoaderHolder.clearIf(it)
351
336
  }
352
337
  artworkProviderDeps = null
338
+ if (::mediaSession.isInitialized) mediaSession.release()
339
+ player.destroy()
340
+ scope.cancel()
353
341
  }
354
342
 
355
343
  override fun onDestroy() {
@@ -361,13 +349,7 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
361
349
  headlessBound = false
362
350
  }
363
351
 
364
- tearDownArtworkProvider()
365
-
366
- Timber.d("Releasing media session and destroying player")
367
- if (::mediaSession.isInitialized) {
368
- mediaSession.release()
369
- }
370
- player.destroy()
352
+ tearDown()
371
353
 
372
354
  super.onDestroy()
373
355
  }
@@ -35,8 +35,28 @@ internal class InterceptingPlayer(
35
35
  private val optionsProvider: () -> PlayerUpdateOptions,
36
36
  private val keepSessionAliveOnError: Boolean,
37
37
  private val isPaused: () -> Boolean,
38
+ private val stopPlayer: () -> Unit,
38
39
  ) : ForwardingPlayer(player) {
39
40
 
41
+ private val listeners = mutableSetOf<MediaPlayer.Listener>()
42
+
43
+ override fun addListener(listener: MediaPlayer.Listener) {
44
+ listeners += listener
45
+ super.addListener(listener)
46
+ }
47
+
48
+ override fun removeListener(listener: MediaPlayer.Listener) {
49
+ listeners -= listener
50
+ super.removeListener(listener)
51
+ }
52
+
53
+ /** Call when [isPaused] changes: on an idle engine the masked state moves with no event. */
54
+ fun onPausedChanged() {
55
+ if (keepSessionAliveOnError && super.getPlaybackState() == MediaPlayer.STATE_IDLE) {
56
+ listeners.toList().forEach { it.onPlaybackStateChanged(playbackState) }
57
+ }
58
+ }
59
+
40
60
  private val parked: Boolean
41
61
  get() = super.getPlayerError() != null || isPaused()
42
62
 
@@ -86,7 +106,7 @@ internal class InterceptingPlayer(
86
106
  // the recovery.
87
107
  override fun setPlayWhenReady(playWhenReady: Boolean) = if (playWhenReady) play() else pause()
88
108
 
89
- override fun stop() = intercept({ it.handleRemoteStop() }) { super.stop() }
109
+ override fun stop() = intercept({ it.handleRemoteStop() }) { stopPlayer() }
90
110
 
91
111
  override fun seekToNext() =
92
112
  intercept({ it.handleRemoteNext() }, recover = true) { super.seekToNext() }
@@ -25,7 +25,6 @@ class MediaFactory(
25
25
  private val context: Context,
26
26
  private val cache: SimpleCache?,
27
27
  private val retryPolicy: RetryPolicy,
28
- private val shouldRetry: () -> Boolean,
29
28
  private val isOnline: () -> Boolean = { true },
30
29
  private val hasPlayed: () -> Boolean = { false },
31
30
  private val onRetryPending: ((exception: IOException) -> Unit)? = null,
@@ -61,7 +60,6 @@ class MediaFactory(
61
60
  maxRetries = null,
62
61
  maxRetryDurationMs = retryPolicy.maxRetryDurationMs,
63
62
  firstConnectMaxRetryDurationMs = retryPolicy.firstConnectMaxRetryDurationMs,
64
- shouldRetry = shouldRetry,
65
63
  isOnline = isOnline,
66
64
  hasPlayed = hasPlayed,
67
65
  onRetryPending = onRetryPending,
@@ -71,7 +69,6 @@ class MediaFactory(
71
69
  maxRetries = retryPolicy.maxRetries,
72
70
  maxRetryDurationMs = retryPolicy.maxRetryDurationMs,
73
71
  firstConnectMaxRetryDurationMs = retryPolicy.firstConnectMaxRetryDurationMs,
74
- shouldRetry = shouldRetry,
75
72
  isOnline = isOnline,
76
73
  hasPlayed = hasPlayed,
77
74
  onRetryPending = onRetryPending,
@@ -19,7 +19,16 @@ sealed interface PlaybackEvent {
19
19
  val shouldPlayWhenReady: Boolean,
20
20
  ) : PlaybackEvent
21
21
 
22
- data class MediaItemTransition(val hasTrack: Boolean, val isPlaying: Boolean) : PlaybackEvent
22
+ /**
23
+ * [loads] is false when the engine idles, so nothing loads the track. Read after the command's
24
+ * own prepare(): onEvents runs once the command returns.
25
+ */
26
+ data class MediaItemTransition(
27
+ val hasTrack: Boolean,
28
+ val isPlaying: Boolean,
29
+ val loads: Boolean,
30
+ val shouldPlayWhenReady: Boolean,
31
+ ) : PlaybackEvent
23
32
 
24
33
  /**
25
34
  * An input of [Player.shouldPlayWhenReady] changed: the intent, or a playback suppression such as
@@ -69,6 +78,11 @@ object PlaybackStateMachine {
69
78
  // the events arrive after it.
70
79
  !event.hasTrack ->
71
80
  if (current == PlaybackState.STOPPED) emptyList() else listOf(PlaybackState.NONE)
81
+ // Removing the current track after a stop, an error or a cancelled retry: play() loads
82
+ // the new one. With the intent up PAUSED would read as playing; ERROR's toggle reloads.
83
+ !event.loads ->
84
+ if (current == PlaybackState.STOPPED || event.shouldPlayWhenReady) emptyList()
85
+ else listOf(PlaybackState.PAUSED)
72
86
  // Already playing (gapless auto-advance): no IsPlayingChanged follows, so run the whole
73
87
  // sequence here or the state sticks on LOADING.
74
88
  event.isPlaying ->
@@ -117,7 +117,7 @@ internal constructor(
117
117
  private set
118
118
 
119
119
  /** [sessionPlayer] behind the remote-command seam: what the MediaSession wraps. */
120
- lateinit var forwardingPlayer: MediaPlayer
120
+ internal lateinit var forwardingPlayer: InterceptingPlayer
121
121
 
122
122
  private val remoteOutputs =
123
123
  RemoteOutputsController(context, ::resolveRemoteUrls, castRemote, sonosRemote)
@@ -127,12 +127,6 @@ internal constructor(
127
127
 
128
128
  private var keepSessionAliveOnError = true
129
129
 
130
- /**
131
- * [playWhenReady] for the retry policy, which reads it off the main thread. Written eagerly by
132
- * the setter, ahead of ExoPlayer's listener round-trip.
133
- */
134
- @Volatile internal var playWhenReadyCache = false
135
-
136
130
  /**
137
131
  * Whether the current load has produced audio: picks the retry policy's first-connect or recovery
138
132
  * budget. Read on ExoPlayer's loader thread. Cleared on a media-item transition; retry reloads of
@@ -311,7 +305,6 @@ internal constructor(
311
305
  if (value && sessionPlayer.playbackState == MediaPlayer.STATE_ENDED) {
312
306
  sessionPlayer.seekToDefaultPosition()
313
307
  }
314
- playWhenReadyCache = value
315
308
  sessionPlayer.playWhenReady = value
316
309
  }
317
310
 
@@ -463,7 +456,6 @@ internal constructor(
463
456
  context,
464
457
  setupOptions,
465
458
  cache,
466
- shouldRetry = { playWhenReadyCache },
467
459
  isOnline = { networkMonitor.getOnline() },
468
460
  hasPlayed = { hasPlayedCache },
469
461
  onRetryPending = ::reportRetryingError,
@@ -508,6 +500,7 @@ internal constructor(
508
500
  { options },
509
501
  keepSessionAliveOnError,
510
502
  isPaused = { playbackState == PlaybackState.PAUSED },
503
+ stopPlayer = ::stop,
511
504
  )
512
505
  forwardingPlayer.addListener(playerListener)
513
506
  if (::mediaSession.isInitialized) mediaSession.player = forwardingPlayer
@@ -557,25 +550,22 @@ internal constructor(
557
550
  }
558
551
  }
559
552
 
560
- fun add(track: Track) {
561
- val mediaItem = TrackFactory.toMedia3(track)
562
- sessionPlayer.addMediaItem(mediaItem)
563
- sessionPlayer.prepare()
564
- }
553
+ fun add(track: Track) = add(arrayOf(track))
565
554
 
566
- fun add(tracks: Array<Track>) {
567
- val mediaItems = TrackFactory.toMedia3(tracks)
568
- sessionPlayer.addMediaItems(mediaItems.toList())
569
- sessionPlayer.prepare()
570
- }
571
-
572
- /** @throws IllegalArgumentException unless [atIndex] is within the queue, or -1 to append. */
573
- fun add(tracks: Array<Track>, atIndex: Int) {
555
+ /**
556
+ * Loads only into an empty queue: a queue that had tracks keeps its current one as it was, idle
557
+ * after a stop or a cancelled retry.
558
+ *
559
+ * @throws IllegalArgumentException unless [atIndex] is within the queue, or -1 to append.
560
+ */
561
+ fun add(tracks: Array<Track>, atIndex: Int = -1) {
574
562
  validateInsertIndex(atIndex)
575
- val index = if (atIndex == -1) sessionPlayer.mediaItemCount else atIndex
576
- val mediaItems = tracks.map { TrackFactory.toMedia3(it) }
577
- sessionPlayer.addMediaItems(index, mediaItems)
578
- sessionPlayer.prepare()
563
+ val count = sessionPlayer.mediaItemCount
564
+ sessionPlayer.addMediaItems(
565
+ if (atIndex == -1) count else atIndex,
566
+ TrackFactory.toMedia3(tracks),
567
+ )
568
+ if (count == 0) sessionPlayer.prepare()
579
569
  }
580
570
 
581
571
  /** @throws IllegalArgumentException if an index is out of bounds or repeated. */
@@ -923,7 +913,6 @@ internal constructor(
923
913
  }
924
914
 
925
915
  fun pause() {
926
- // Through the setter, so the retry policy sees playWhenReadyCache drop at once.
927
916
  playWhenReady = false
928
917
  }
929
918
 
@@ -999,6 +988,14 @@ internal constructor(
999
988
  val generation = retryingErrorGeneration
1000
989
  mainHandler.post {
1001
990
  if (generation != retryingErrorGeneration) return@post
991
+ // Paused, the retry would run unseen and its failure be terminal. STOPPED, ERROR and ENDED
992
+ // reach here only from a post that raced them.
993
+ if (
994
+ !playWhenReady &&
995
+ playbackState !in setOf(PlaybackState.STOPPED, PlaybackState.ERROR, PlaybackState.ENDED)
996
+ ) {
997
+ return@post stopRetrying()
998
+ }
1002
999
  // Only over a spinner: while PLAYING, buffered audio still plays and ExoPlayer's in-place
1003
1000
  // retry can succeed with no state change, so an error attached there would never clear.
1004
1001
  if (
@@ -1013,19 +1010,23 @@ internal constructor(
1013
1010
  playbackError = error
1014
1011
  callbacks?.onPlaybackChanged(Playback(playbackState, error))
1015
1012
  nowPlaying.render()
1016
- // A pause before this first report found no retry to cancel.
1017
- if (!playWhenReadyCache) cancelRetry()
1018
1013
  }
1019
1014
  }
1020
1015
 
1021
1016
  /**
1022
- * Cancels the retry a dropped play intent leaves scheduled: ExoPlayer still runs it, and its
1023
- * failure would be terminal. The engine idles in PAUSED, where the next prepare() reloads where
1024
- * it failed. No-op unless a retrying error shows.
1017
+ * Cancels the retry a dropped play intent leaves scheduled. No-op unless a retrying error shows.
1025
1018
  */
1026
1019
  internal fun cancelRetry() {
1027
1020
  // The ENDED path drops the intent before it clears the error.
1028
1021
  if (playbackError?.retrying != true || playbackState == PlaybackState.ENDED) return
1022
+ stopRetrying()
1023
+ }
1024
+
1025
+ /**
1026
+ * Gives up a load ExoPlayer would retry. The engine idles in PAUSED, where the next prepare()
1027
+ * reloads where it failed.
1028
+ */
1029
+ private fun stopRetrying() {
1029
1030
  // Before the stop: the state machine holds PAUSED through the IDLE that follows.
1030
1031
  setPlaybackState(PlaybackState.PAUSED)
1031
1032
  clearRetryingError()
@@ -1052,6 +1053,9 @@ internal constructor(
1052
1053
  playbackState = state
1053
1054
 
1054
1055
  if (state == PlaybackState.PLAYING) hasPlayedCache = true
1056
+ if ((oldState == PlaybackState.PAUSED) != (state == PlaybackState.PAUSED)) {
1057
+ forwardingPlayer.onPausedChanged()
1058
+ }
1055
1059
  if (state == PlaybackState.ERROR) resetForNewLoad()
1056
1060
 
1057
1061
  // A natural end exhausts the play intent; held, it inverts the toggle, keeps audio focus and
@@ -49,7 +49,6 @@ internal fun buildPlayerEngine(
49
49
  context: Context,
50
50
  options: PlayerSetupOptions,
51
51
  cache: SimpleCache?,
52
- shouldRetry: () -> Boolean,
53
52
  isOnline: () -> Boolean,
54
53
  hasPlayed: () -> Boolean,
55
54
  onRetryPending: (exception: IOException) -> Unit,
@@ -67,7 +66,6 @@ internal fun buildPlayerEngine(
67
66
  context,
68
67
  cache,
69
68
  options.retryPolicy,
70
- shouldRetry = shouldRetry,
71
69
  isOnline = isOnline,
72
70
  hasPlayed = hasPlayed,
73
71
  onRetryPending = onRetryPending,
@@ -128,9 +128,6 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
128
128
  player.sleepTimer.clear()
129
129
  }
130
130
 
131
- // The second writer: Player.playWhenReady's setter writes first so loader-thread readers see
132
- // the intent early; this syncs changes ExoPlayer makes itself (e.g. audio focus).
133
- player.playWhenReadyCache = playWhenReady
134
131
  // Here rather than in Player.pause(): a session pause, a noisy-audio pause and a permanent
135
132
  // focus loss all drop the intent without it.
136
133
  if (!playWhenReady) player.cancelRetry()
@@ -164,7 +161,12 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
164
161
  player.shouldPlayWhenReady,
165
162
  )
166
163
  MediaPlayer.EVENT_MEDIA_ITEM_TRANSITION ->
167
- PlaybackEvent.MediaItemTransition(player.currentTrack != null, player.isPlaying)
164
+ PlaybackEvent.MediaItemTransition(
165
+ player.currentTrack != null,
166
+ player.isPlaying,
167
+ loads = player.sessionPlayer.playbackState != MediaPlayer.STATE_IDLE,
168
+ player.shouldPlayWhenReady,
169
+ )
168
170
  MediaPlayer.EVENT_PLAY_WHEN_READY_CHANGED,
169
171
  MediaPlayer.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED ->
170
172
  PlaybackEvent.ShouldPlayWhenReadyChanged(
@@ -29,7 +29,6 @@ import timber.log.Timber
29
29
  * @param maxRetryDurationMs the full recovery budget; null for 2 minutes
30
30
  * @param firstConnectMaxRetryDurationMs the online budget of a load that has never produced audio;
31
31
  * null for 12 seconds
32
- * @param shouldRetry false gives up at once (e.g. the player is paused)
33
32
  * @param hasPlayed whether the current load has produced audio; called on ExoPlayer's loader thread
34
33
  * @param onRetryPending called on ExoPlayer's loader thread each time a retry is scheduled, with
35
34
  * the error being retried
@@ -38,7 +37,6 @@ class RetryLoadErrorHandlingPolicy(
38
37
  private val maxRetries: Int? = null,
39
38
  maxRetryDurationMs: Long? = null,
40
39
  firstConnectMaxRetryDurationMs: Long? = null,
41
- private val shouldRetry: () -> Boolean = { true },
42
40
  private val isOnline: () -> Boolean = { true },
43
41
  private val hasPlayed: () -> Boolean = { false },
44
42
  private val onRetryPending: ((exception: IOException) -> Unit)? = null,
@@ -103,11 +101,6 @@ class RetryLoadErrorHandlingPolicy(
103
101
  val errorCount = loadErrorInfo.errorCount
104
102
  val currentTime = SystemClock.elapsedRealtime()
105
103
 
106
- if (!shouldRetry()) {
107
- Timber.d("Retry skipped: shouldRetry() returned false (player likely paused)")
108
- return C.TIME_UNSET
109
- }
110
-
111
104
  if (maxRetries != null && errorCount > maxRetries) {
112
105
  Timber.d("Max retries ($maxRetries) exceeded, not retrying")
113
106
  return C.TIME_UNSET
@@ -28,14 +28,7 @@ class MediaFactoryTest {
28
28
 
29
29
  private fun mediaFactory(
30
30
  getRequestConfig: (String, Track) -> MediaRequestConfig? = { _, _ -> null }
31
- ) =
32
- MediaFactory(
33
- context,
34
- cache = null,
35
- RetryPolicy.Default,
36
- shouldRetry = { false },
37
- getRequestConfig = getRequestConfig,
38
- )
31
+ ) = MediaFactory(context, cache = null, RetryPolicy.Default, getRequestConfig = getRequestConfig)
39
32
 
40
33
  /** Starts loading [track]'s media from position 0, runs [block], then releases the source. */
41
34
  private fun loading(factory: MediaFactory, track: Track, block: () -> Unit) {
@@ -138,17 +138,55 @@ class PlaybackStateMachineTest {
138
138
  fun `a transition to a track synthesizes the loading burst`() {
139
139
  assertEquals(
140
140
  listOf(PlaybackState.LOADING),
141
- on(PlaybackEvent.MediaItemTransition(hasTrack = true, isPlaying = false)),
141
+ on(
142
+ PlaybackEvent.MediaItemTransition(
143
+ hasTrack = true,
144
+ isPlaying = false,
145
+ loads = true,
146
+ shouldPlayWhenReady = false,
147
+ )
148
+ ),
142
149
  )
143
150
  assertEquals(
144
151
  listOf(PlaybackState.LOADING, PlaybackState.READY, PlaybackState.PLAYING),
145
- on(PlaybackEvent.MediaItemTransition(hasTrack = true, isPlaying = true)),
152
+ on(
153
+ PlaybackEvent.MediaItemTransition(
154
+ hasTrack = true,
155
+ isPlaying = true,
156
+ loads = true,
157
+ shouldPlayWhenReady = false,
158
+ )
159
+ ),
160
+ )
161
+ }
162
+
163
+ @Test
164
+ fun `a transition nothing loads is paused, except from stopped`() {
165
+ val idle =
166
+ PlaybackEvent.MediaItemTransition(
167
+ hasTrack = true,
168
+ isPlaying = false,
169
+ loads = false,
170
+ shouldPlayWhenReady = false,
171
+ )
172
+ assertEquals(listOf(PlaybackState.PAUSED), on(idle, from = PlaybackState.ERROR))
173
+ assertEquals(listOf(PlaybackState.PAUSED), on(idle, from = PlaybackState.PAUSED))
174
+ assertEquals(emptyList<PlaybackState>(), on(idle, from = PlaybackState.STOPPED))
175
+ assertEquals(
176
+ emptyList<PlaybackState>(),
177
+ on(idle.copy(shouldPlayWhenReady = true), from = PlaybackState.ERROR),
146
178
  )
147
179
  }
148
180
 
149
181
  @Test
150
182
  fun `a transition without a track is none, except from stopped`() {
151
- val emptied = PlaybackEvent.MediaItemTransition(hasTrack = false, isPlaying = false)
183
+ val emptied =
184
+ PlaybackEvent.MediaItemTransition(
185
+ hasTrack = false,
186
+ isPlaying = false,
187
+ loads = false,
188
+ shouldPlayWhenReady = false,
189
+ )
152
190
  assertEquals(listOf(PlaybackState.NONE), on(emptied, from = PlaybackState.ERROR))
153
191
  assertEquals(listOf(PlaybackState.NONE), on(emptied, from = PlaybackState.ENDED))
154
192
  assertEquals(emptyList<PlaybackState>(), on(emptied, from = PlaybackState.STOPPED))
@@ -17,15 +17,20 @@ import com.audiobrowser.util.TrackFactory
17
17
  import com.margelo.nitro.audiobrowser.Playback
18
18
  import com.margelo.nitro.audiobrowser.PlaybackState
19
19
  import java.io.File
20
+ import java.net.ServerSocket
20
21
  import java.nio.ByteBuffer
21
22
  import java.nio.ByteOrder
22
23
  import java.time.Duration
24
+ import java.util.concurrent.CountDownLatch
25
+ import java.util.concurrent.TimeUnit
26
+ import kotlin.concurrent.thread
23
27
  import kotlinx.coroutines.CoroutineScope
24
28
  import kotlinx.coroutines.Dispatchers
25
29
  import kotlinx.coroutines.cancel
26
30
  import org.junit.After
27
31
  import org.junit.Assert.assertEquals
28
32
  import org.junit.Assert.assertFalse
33
+ import org.junit.Assert.assertNotEquals
29
34
  import org.junit.Assert.assertTrue
30
35
  import org.junit.Assert.fail
31
36
  import org.junit.Rule
@@ -138,6 +143,11 @@ class PlayerRetryTest {
138
143
  awaitRetry("a pending retry")
139
144
 
140
145
  pause()
146
+ assertStaysPausedAndIdle()
147
+ }
148
+
149
+ /** Runs past every backoff a retry would have taken. */
150
+ private fun assertStaysPausedAndIdle() {
141
151
  repeat(10) {
142
152
  ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
143
153
  Thread.sleep(20)
@@ -181,13 +191,128 @@ class PlayerRetryTest {
181
191
  }
182
192
 
183
193
  @Test
184
- fun `removing the current track after a cancelled retry stays idle`() {
194
+ fun `removing the current track after a cancelled retry stays idle and paused`() {
185
195
  pauseDuringRetry(Uri.fromFile(silentWav()).toString()) { player.pause() }
186
196
 
187
197
  player.remove(listOf(0))
188
198
  shadowOf(Looper.getMainLooper()).idle()
189
199
 
190
200
  assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
201
+ assertEquals(PlaybackState.PAUSED, player.playbackState)
202
+ assertEquals(MediaPlayer.STATE_READY, player.forwardingPlayer.playbackState)
203
+ }
204
+
205
+ @Test
206
+ fun `removing a failed current track while paused is paused`() {
207
+ failTerminally(Uri.fromFile(silentWav()).toString())
208
+ player.pause()
209
+ shadowOf(Looper.getMainLooper()).idle()
210
+
211
+ player.remove(listOf(0))
212
+ shadowOf(Looper.getMainLooper()).idle()
213
+
214
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
215
+ assertEquals(Playback(PlaybackState.PAUSED, null), player.getPlayback())
216
+ }
217
+
218
+ @Test
219
+ fun `adding a track after a cancelled retry stays idle and paused`() {
220
+ pauseDuringRetry { player.pause() }
221
+
222
+ player.add(TestFixtures.track(src = Uri.fromFile(silentWav()).toString()))
223
+ shadowOf(Looper.getMainLooper()).idle()
224
+
225
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
226
+ assertEquals(PlaybackState.PAUSED, player.playbackState)
227
+ }
228
+
229
+ @Test
230
+ fun `adding to an empty queue loads`() {
231
+ player.setup(PlayerSetupOptions())
232
+
233
+ player.add(TestFixtures.track(src = Uri.fromFile(silentWav()).toString()))
234
+ shadowOf(Looper.getMainLooper()).idle()
235
+
236
+ assertNotEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
237
+ }
238
+
239
+ @Test
240
+ fun `a stop after a cancelled retry tells the session`() {
241
+ pauseDuringRetry { player.pause() }
242
+ val states = mutableListOf<Int>()
243
+ player.forwardingPlayer.addListener(
244
+ object : MediaPlayer.Listener {
245
+ override fun onPlaybackStateChanged(playbackState: Int) {
246
+ states += playbackState
247
+ }
248
+ }
249
+ )
250
+
251
+ player.stop()
252
+ shadowOf(Looper.getMainLooper()).idle()
253
+
254
+ assertEquals(MediaPlayer.STATE_IDLE, player.forwardingPlayer.playbackState)
255
+ assertEquals(listOf(MediaPlayer.STATE_IDLE), states)
256
+ }
257
+
258
+ @Test
259
+ fun `a session stop after a cancelled retry is a stop the session sees`() {
260
+ pauseDuringRetry { player.pause() }
261
+ val states = mutableListOf<Int>()
262
+ player.forwardingPlayer.addListener(
263
+ object : MediaPlayer.Listener {
264
+ override fun onPlaybackStateChanged(playbackState: Int) {
265
+ states += playbackState
266
+ }
267
+ }
268
+ )
269
+
270
+ player.forwardingPlayer.stop()
271
+ shadowOf(Looper.getMainLooper()).idle()
272
+
273
+ assertEquals(PlaybackState.STOPPED, player.playbackState)
274
+ assertEquals(MediaPlayer.STATE_IDLE, player.forwardingPlayer.playbackState)
275
+ assertEquals(listOf(MediaPlayer.STATE_IDLE), states)
276
+ }
277
+
278
+ @Test
279
+ fun `a load failing while paused stays paused and the next play reloads`() {
280
+ val server = ServerSocket(0)
281
+ val wav = silentWav().readBytes()
282
+ val sent = CountDownLatch(1)
283
+ val drop = CountDownLatch(1)
284
+ // Serves five seconds of the minute, holds the connection until the drop, then refuses.
285
+ thread(isDaemon = true) {
286
+ server.accept().use { socket ->
287
+ val request = socket.getInputStream().bufferedReader()
288
+ while (!request.readLine().isNullOrEmpty()) Unit
289
+ socket.getOutputStream().run {
290
+ write("HTTP/1.1 200 OK\r\nContent-Length: ${wav.size}\r\n\r\n".toByteArray())
291
+ write(wav, 0, 40_000)
292
+ flush()
293
+ }
294
+ sent.countDown()
295
+ drop.await(10, TimeUnit.SECONDS)
296
+ }
297
+ server.close()
298
+ }
299
+ play("http://127.0.0.1:${server.localPort}/stream.wav", retryPolicy = RetryPolicy.Infinite())
300
+ // A source with no track enabled stops loading, and the load must still run when it fails.
301
+ player.exoPlayer.trackSelectionParameters =
302
+ player.exoPlayer.trackSelectionParameters
303
+ .buildUpon()
304
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
305
+ .build()
306
+ idleUntil("the first bytes") { sent.count == 0L }
307
+
308
+ player.pause()
309
+ shadowOf(Looper.getMainLooper()).idle()
310
+ drop.countDown()
311
+ idleUntil("the load given up") { player.exoPlayer.playbackState == MediaPlayer.STATE_IDLE }
312
+ assertStaysPausedAndIdle()
313
+
314
+ player.play()
315
+ awaitRetry("the reload's retry")
191
316
  }
192
317
 
193
318
  @Test
@@ -73,7 +73,6 @@ class PlayerSetupTest {
73
73
  assertEquals(0.5f, rebuilt.volume)
74
74
  assertTrue(rebuilt.playbackState != MediaPlayer.STATE_IDLE)
75
75
  assertTrue(rebuilt.playWhenReady)
76
- assertTrue(player.playWhenReadyCache)
77
76
  // The new engine buffers again from the kept position.
78
77
  assertEquals(PlaybackState.BUFFERING, player.playbackState)
79
78
  assertEquals(
@@ -83,13 +83,6 @@ class RetryLoadErrorHandlingPolicyTest {
83
83
  assertTrue(retryPending)
84
84
  }
85
85
 
86
- @Test
87
- fun `retry is skipped when shouldRetry is false`() {
88
- val policy = RetryLoadErrorHandlingPolicy(shouldRetry = { false })
89
- val delay = policy.getRetryDelayMsFor(errorInfo(UnknownHostException("offline")))
90
- assertEquals(C.TIME_UNSET, delay)
91
- }
92
-
93
86
  @Test
94
87
  fun `retry stops once max retries is exceeded`() {
95
88
  val policy = RetryLoadErrorHandlingPolicy(maxRetries = 3)
@@ -112,7 +112,8 @@ final class AVPlayerEngine: PlayerEngine {
112
112
 
113
113
  var resumePosition: Double? {
114
114
  guard let item = avPlayer.currentItem, !item.duration.isIndefinite else { return nil }
115
- return item.currentTime().seconds
115
+ let seconds = item.currentTime().seconds
116
+ return seconds.isFinite ? seconds : nil
116
117
  }
117
118
 
118
119
  var liveEdge: Double? {
@@ -49,13 +49,23 @@ public extension HybridAudioBrowser {
49
49
  }
50
50
 
51
51
  func seekTo(position: Double) throws {
52
+ guard let position = finite(position, "seekTo") else { return }
52
53
  onMainActor { player?.seek(to: position) }
53
54
  }
54
55
 
55
56
  func seekBy(offset: Double) throws {
57
+ guard let offset = finite(offset, "seekBy") else { return }
56
58
  onMainActor { player?.seek(by: offset) }
57
59
  }
58
60
 
61
+ private func finite(_ seconds: Double, _ method: String) -> Double? {
62
+ guard seconds.isFinite else {
63
+ logger.error("\(method, privacy: .public) ignored a non-finite time: \(seconds)")
64
+ return nil
65
+ }
66
+ return seconds
67
+ }
68
+
59
69
  func seekToLiveEdge() throws {
60
70
  onMainActor { player?.seekToLiveEdge() }
61
71
  }
@@ -187,7 +197,7 @@ public extension HybridAudioBrowser {
187
197
  func skip(index: Double, initialPosition: Double?) throws {
188
198
  try onMainActor {
189
199
  try player?.skipTo(Int(index))
190
- if let position = initialPosition {
200
+ if let position = initialPosition.flatMap({ finite($0, "skip") }) {
191
201
  player?.seek(to: position)
192
202
  }
193
203
  }
@@ -196,7 +206,7 @@ public extension HybridAudioBrowser {
196
206
  func skipToNext(initialPosition: Double?) throws {
197
207
  onMainActor {
198
208
  player?.next()
199
- if let position = initialPosition {
209
+ if let position = initialPosition.flatMap({ finite($0, "skipToNext") }) {
200
210
  player?.seek(to: position)
201
211
  }
202
212
  }
@@ -205,7 +215,7 @@ public extension HybridAudioBrowser {
205
215
  func skipToPrevious(initialPosition: Double?) throws {
206
216
  onMainActor {
207
217
  player?.previous()
208
- if let position = initialPosition {
218
+ if let position = initialPosition.flatMap({ finite($0, "skipToPrevious") }) {
209
219
  player?.seek(to: position)
210
220
  }
211
221
  }
@@ -249,7 +259,7 @@ public extension HybridAudioBrowser {
249
259
  try player.setQueue(
250
260
  tracks,
251
261
  initialIndex: startIndex.map { Int($0) } ?? 0,
252
- startPositionMs: startPosition.map { $0 * 1000 },
262
+ startPositionMs: startPosition.flatMap { finite($0, "setQueue") }.map { $0 * 1000 },
253
263
  )
254
264
  }
255
265
  }
@@ -640,11 +640,11 @@ final class Player {
640
640
 
641
641
  // MARK: - Seeking
642
642
 
643
- /// Seeks the current item. While it awaits the next item, the target is held until that one is
644
- /// ready and the ready transition waits for it (`DeferredSeek`); `completion` then reports false
645
- /// at once.
643
+ /// Seeks the current item. While it awaits the next item, or in .error for the restart, the
644
+ /// target is held until the next item is ready and the ready transition waits for it
645
+ /// (`DeferredSeek`); `completion` then reports false at once.
646
646
  func seek(to seconds: TimeInterval, completion: @escaping @MainActor (Bool) -> Void = { _ in }) {
647
- if awaitingItem {
647
+ if awaitingItem || state == .error {
648
648
  deferredSeek.capture(seconds)
649
649
  completion(false)
650
650
  } else if engine.hasItem {
@@ -655,18 +655,19 @@ final class Player {
655
655
  }
656
656
 
657
657
  func seek(by offset: TimeInterval) {
658
- if awaitingItem {
659
- seek(to: (deferredSeek.target ?? 0) + offset)
658
+ if awaitingItem || state == .error {
659
+ seek(to: (resumePosition ?? 0) + offset)
660
660
  } else if engine.hasItem {
661
661
  seek(to: engine.currentTime + offset)
662
662
  }
663
663
  }
664
664
 
665
665
  /// Jumps to the live edge: the end of the seekable window when there is one; without one
666
- /// (ICY) there is nothing to seek within, so it reconnects. No-op for a track that isn't live.
666
+ /// (ICY), or in .error, whose item's window is stale, it reconnects. No-op for a track that
667
+ /// isn't live.
667
668
  func seekToLiveEdge() {
668
669
  guard currentTrack?.live == true, engine.hasItem else { return }
669
- if let edge = engine.liveEdge {
670
+ if let edge = engine.liveEdge, state != .error {
670
671
  seek(to: edge)
671
672
  } else {
672
673
  reloadResolving(startFromCurrentTime: false)
@@ -747,10 +748,14 @@ final class Player {
747
748
 
748
749
  /// Recovers from a media-services reset: every AVPlayer and session handle is invalid, so a
749
750
  /// new player reloads the current track, keeping the play intent, so a live stream reconnects
750
- /// instead of going silent. No-op when nothing is loaded.
751
+ /// instead of going silent. An on-demand track resumes where it was, unless it ended, or was
752
+ /// stopped and its rewind may not have landed. No-op when nothing is loaded.
751
753
  func mediaServicesWereReset() {
752
- guard currentTrack != nil else { return }
754
+ guard let track = currentTrack else { return }
753
755
  logger.info("Media services were reset — recreating player and reloading current track")
756
+ if track.live != true, state != .ended, state != .stopped, let position = resumePosition {
757
+ deferredSeek.capture(position)
758
+ }
754
759
  engine.clearItem()
755
760
  engine.recreate()
756
761
  reloadResolving(startFromCurrentTime: false)
@@ -42,7 +42,7 @@ enum EngineEvent {
42
42
  var currentTime: Double { get }
43
43
  var duration: Double { get }
44
44
  var bufferedPosition: Double { get }
45
- /// The position a reload resumes from: nil without an item, or for an indefinite duration.
45
+ /// The position a reload resumes from: nil without an item, for an indefinite duration, or when the item's time isn't finite.
46
46
  var resumePosition: Double? { get }
47
47
  /// The end of the seekable window; nil when there is none.
48
48
  var liveEdge: Double? { get }
@@ -183,6 +183,16 @@ struct PlayerSeekingTests {
183
183
  #expect(engine.resolveAndLoadCalls.count == 2)
184
184
  #expect(player.state == .loading)
185
185
  }
186
+
187
+ @Test func theLiveEdgeInAnErrorIsAReconnect() throws {
188
+ let (player, engine, _) = try makePlaying(live: true)
189
+ engine.liveEdge = 120
190
+ engine.emit(.failed(nil, httpStatusCode: 404))
191
+ player.seekToLiveEdge()
192
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
193
+ #expect(engine.seekCalls.isEmpty)
194
+ #expect(engine.resolveAndLoadCalls.count == 2)
195
+ }
186
196
  }
187
197
 
188
198
  @Suite("Player - engine events")
@@ -358,6 +368,35 @@ struct PlayerRecoveringTests {
358
368
  #expect(player.playWhenReady)
359
369
  }
360
370
 
371
+ @Test func aMediaServicesResetResumesAnOnDemandTrack_notALiveOne() throws {
372
+ let (player, engine, _) = try makePlaying()
373
+ engine.resumePosition = 120
374
+ player.mediaServicesWereReset()
375
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
376
+ #expect(engine.seekCalls == [120])
377
+
378
+ let (live, liveEngine, _) = try makePlaying(live: true)
379
+ liveEngine.resumePosition = 120
380
+ live.mediaServicesWereReset()
381
+ liveEngine.emit(.itemPrepared(likelyToKeepUp: true))
382
+ #expect(liveEngine.seekCalls.isEmpty)
383
+ }
384
+
385
+ @Test func aMediaServicesResetAfterTheEndOrAStopStartsOver() throws {
386
+ let (ended, endedEngine, _) = try makePlaying()
387
+ endedEngine.resumePosition = 300
388
+ ended.transition(.trackEndedNaturally)
389
+ ended.mediaServicesWereReset()
390
+ #expect(ended.deferredSeek.target == nil)
391
+
392
+ let (stopped, stoppedEngine, _) = try makePlaying()
393
+ stopped.stop()
394
+ // The stop's rewind has not landed.
395
+ stoppedEngine.resumePosition = 120
396
+ stopped.mediaServicesWereReset()
397
+ #expect(stopped.deferredSeek.target == nil)
398
+ }
399
+
361
400
  @Test func aStopRewindsAFiniteTrack_notALiveOne() throws {
362
401
  let (player, engine, _) = try makePlaying()
363
402
  player.stop()
@@ -413,6 +452,38 @@ struct PlayerReviewRegressionTests {
413
452
  #expect(engine.seekCalls == [25, 25])
414
453
  }
415
454
 
455
+ @Test func aSeekInAnErrorDuringTheStartSeekReplacesTheStart() throws {
456
+ let engine = MockPlayerEngine()
457
+ let player = makePlayer(engine: engine, retries: false)
458
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], startPositionMs: 25000)
459
+ engine.seekResult = nil
460
+ engine.hasItem = true
461
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
462
+ engine.emit(.failed(nil, httpStatusCode: 404))
463
+ #expect(player.state == .error)
464
+
465
+ player.seek(to: 40)
466
+ player.seek(by: 5)
467
+ engine.completeSeeks(false)
468
+ player.play()
469
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
470
+
471
+ #expect(engine.seekCalls == [25, 45])
472
+ }
473
+
474
+ @Test func aSeekInAnErrorIsWhereThePlayResumes() throws {
475
+ let (player, engine, _) = try makePlaying()
476
+ engine.resumePosition = 120
477
+ engine.emit(.failed(nil, httpStatusCode: 404))
478
+ #expect(player.state == .error)
479
+
480
+ player.seek(by: -80)
481
+ player.play()
482
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
483
+
484
+ #expect(engine.seekCalls == [40])
485
+ }
486
+
416
487
  @Test func endingWithTheIntentAlreadyOffSavesPositionZero() throws {
417
488
  UserDefaults(suiteName: "PlayerTests")!.removePersistentDomain(forName: "PlayerTests")
418
489
  let (player, engine, _) = try makePlaying()
@@ -55,7 +55,12 @@ final class MockPlayerEngine: PlayerEngine {
55
55
  func resolveAndLoad(src: String, track _: Track) { resolveAndLoadCalls.append(src) }
56
56
  func cancelLoading() { cancelLoadingCount += 1 }
57
57
  func dropAsset() { dropAssetCount += 1 }
58
- func clearItem() { clearItemCount += 1 }
58
+ func clearItem() {
59
+ clearItemCount += 1
60
+ hasItem = false
61
+ resumePosition = nil
62
+ }
63
+
59
64
  func stopObservingItem() { stopObservingItemCount += 1 }
60
65
  func recreate() { recreateCount += 1 }
61
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.74",
3
+ "version": "0.2.0-next.75",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",