react-native-audio-browser 0.2.0-next.66 → 0.2.0-next.68

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.
@@ -37,6 +37,7 @@ import kotlinx.coroutines.Dispatchers
37
37
  import kotlinx.coroutines.MainScope
38
38
  import kotlinx.coroutines.SupervisorJob
39
39
  import kotlinx.coroutines.cancel
40
+ import kotlinx.coroutines.isActive
40
41
  import timber.log.Timber
41
42
 
42
43
  /**
@@ -244,19 +245,12 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
244
245
  super.onRebind(intent)
245
246
  }
246
247
 
248
+ @OptIn(UnstableApi::class)
247
249
  override fun onTaskRemoved(rootIntent: Intent?) {
248
250
  val appKilledPlaybackBehavior = player.appKilledPlaybackBehavior
249
251
 
250
252
  Timber.d("player = $player, appKilledPlaybackBehavior = $appKilledPlaybackBehavior")
251
253
 
252
- // The system UI's controller backs the notification, so it doesn't count as external.
253
- val hasExternalControllers =
254
- mediaSession.connectedControllers.any { controller ->
255
- controller.packageName != packageName && controller.packageName != "com.android.systemui"
256
- }
257
-
258
- Timber.d("hasExternalControllers = $hasExternalControllers")
259
-
260
254
  when (appKilledPlaybackBehavior) {
261
255
  AppKilledPlaybackBehavior.PAUSE_PLAYBACK -> {
262
256
  Timber.d("Pausing playback - appKilledPlaybackBehavior = $appKilledPlaybackBehavior")
@@ -264,8 +258,14 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
264
258
  }
265
259
 
266
260
  AppKilledPlaybackBehavior.STOP_PLAYBACK_AND_REMOVE_NOTIFICATION -> {
267
- if (hasExternalControllers) {
268
- Timber.d("External controllers still connected - deferring aggressive cleanup")
261
+ // Only a car keeps the session through a swipe: the Bluetooth stack connects as a
262
+ // controller whenever Bluetooth is on, with or without a device.
263
+ val carConnected =
264
+ mediaSession.connectedControllers.any {
265
+ mediaSession.isAutomotiveController(it) || mediaSession.isAutoCompanionController(it)
266
+ }
267
+ if (carConnected) {
268
+ Timber.d("A car is connected - pausing instead of stopping")
269
269
  player.pause()
270
270
  stopForeground(STOP_FOREGROUND_REMOVE)
271
271
  } else if (moduleBound) {
@@ -274,7 +274,7 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
274
274
  // Ends the service once AudioBrowser unbinds.
275
275
  stopSelf()
276
276
  } else {
277
- Timber.d("No external controllers - proceeding with service shutdown")
277
+ Timber.d("No car connected - shutting the service down")
278
278
  try {
279
279
  if (::mediaSession.isInitialized) {
280
280
  mediaSession.release()
@@ -305,9 +305,13 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
305
305
  stopForeground(STOP_FOREGROUND_REMOVE)
306
306
  }
307
307
 
308
- override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession {
308
+ override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? {
309
309
  Timber.d("onGetSession requested by: ${controllerInfo.packageName}")
310
310
 
311
+ // Cancelled with the session's release. A client still bound keeps the service alive after
312
+ // a swipe's shutdown, and Media3 throws on adding a released session.
313
+ if (!scope.isActive) return null
314
+
311
315
  // No setup() here: default options would replace the ones setupPlayer applied.
312
316
  if (player.getCallbacks() == null) {
313
317
  Timber.w("External controller connecting before React Native setup - using default options")
@@ -578,20 +578,16 @@ internal constructor(
578
578
  sessionPlayer.prepare()
579
579
  }
580
580
 
581
- /** @throws IllegalArgumentException if [index] is out of bounds. */
582
- fun remove(index: Int) {
583
- validateIndex(index)
584
- sessionPlayer.removeMediaItem(index)
585
- }
586
-
587
581
  /** @throws IllegalArgumentException if an index is out of bounds or repeated. */
588
582
  fun remove(indexes: List<Int>) {
589
583
  if (indexes.toSet().size != indexes.size) {
590
584
  throw IllegalArgumentException("Duplicate indexes provided")
591
585
  }
592
586
  indexes.forEach { validateIndex(it) }
593
- val sorted = indexes.sortedDescending()
594
- sorted.forEach { sessionPlayer.removeMediaItem(it) }
587
+ val removesCurrent = sessionPlayer.currentMediaItemIndex in indexes
588
+ indexes.sortedDescending().forEach { sessionPlayer.removeMediaItem(it) }
589
+ // Loads the new current track on an engine an error left idle; a no-op otherwise.
590
+ if (removesCurrent && playWhenReady) prepare()
595
591
  }
596
592
 
597
593
  fun next() {
@@ -933,10 +929,10 @@ internal constructor(
933
929
 
934
930
  fun togglePlayback() {
935
931
  when {
936
- shouldPlayWhenReady -> pause()
937
932
  // Suppressed with the intent raised: ExoPlayer resumes when focus returns. play() would
938
933
  // request focus again, and during a call that refusal drops the intent.
939
- playWhenReady -> Unit
934
+ playWhenReady && !shouldPlayWhenReady -> Unit
935
+ PlayingStateFactory.derive(shouldPlayWhenReady, playbackState).playing -> pause()
940
936
  else -> play()
941
937
  }
942
938
  }
@@ -151,7 +151,8 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
151
151
  }
152
152
 
153
153
  override fun onEvents(media3Player: MediaPlayer, events: MediaPlayer.Events) {
154
- // In event order: each setPlaybackState emits.
154
+ // In event-constant order, not the order the events happened; the transitions rely on it.
155
+ // Each setPlaybackState emits.
155
156
  for (i in 0 until events.size()) {
156
157
  val event =
157
158
  when (events[i]) {
@@ -249,7 +250,9 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
249
250
  "Stuck player recovery: type=${error.stuckType} timeoutMs=${error.timeoutMs} " +
250
251
  "live=${player.isCurrentItemLive}"
251
252
  )
252
- player.resetRetryTimer()
253
+ // Offline time counts against the recovery budget, and offline media3 reports stuck every
254
+ // minute: a refill here would keep the budget from ever running out.
255
+ if (player.networkMonitor.getOnline()) player.resetRetryTimer()
253
256
  player.localEngine.retry(toLiveEdge = player.isCurrentItemLive)
254
257
  }
255
258
  StuckRecoveryPolicy.Decision.GIVE_UP -> {
@@ -1,5 +1,6 @@
1
1
  package com.audiobrowser.player
2
2
 
3
+ import android.os.SystemClock
3
4
  import androidx.media3.common.C
4
5
  import androidx.media3.common.ParserException
5
6
  import androidx.media3.datasource.DataSourceException
@@ -100,7 +101,7 @@ class RetryLoadErrorHandlingPolicy(
100
101
  override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long {
101
102
  val exception = loadErrorInfo.exception
102
103
  val errorCount = loadErrorInfo.errorCount
103
- val currentTime = System.currentTimeMillis()
104
+ val currentTime = SystemClock.elapsedRealtime()
104
105
 
105
106
  if (!shouldRetry()) {
106
107
  Timber.d("Retry skipped: shouldRetry() returned false (player likely paused)")
@@ -126,14 +127,11 @@ class RetryLoadErrorHandlingPolicy(
126
127
  return C.TIME_UNSET
127
128
  }
128
129
 
129
- val errorClassification = classifyError(exception)
130
-
131
- return if (errorClassification.isRecoverable) {
130
+ return if (isRecoverable(exception)) {
132
131
  val currentlyOffline = !isOnline()
133
- val isNetworkError = errorClassification.isNetworkError
134
132
 
135
133
  val delay =
136
- if (currentlyOffline && isNetworkError) {
134
+ if (currentlyOffline) {
137
135
  Timber.d("Device is offline, using short retry delay")
138
136
  OFFLINE_RETRY_DELAY_MS
139
137
  } else {
@@ -155,38 +153,28 @@ class RetryLoadErrorHandlingPolicy(
155
153
  }
156
154
  }
157
155
 
158
- private data class ErrorClassification(val isRecoverable: Boolean, val isNetworkError: Boolean)
159
-
160
156
  /**
161
157
  * Walks the cause chain: load errors arrive as raw IOExceptions (a Wi-Fi drop is a socket or DNS
162
- * error), never as a PlaybackException. Anything not known to be fatal counts as a network error.
158
+ * error), never as a PlaybackException. Anything not known to be fatal is recoverable.
163
159
  */
164
- private fun classifyError(exception: IOException): ErrorClassification {
165
- val nonRecoverable = ErrorClassification(isRecoverable = false, isNetworkError = false)
166
-
160
+ private fun isRecoverable(exception: IOException): Boolean {
167
161
  var current: Throwable? = exception
168
162
  while (current != null) {
169
163
  when (current) {
170
- is HttpDataSource.InvalidResponseCodeException -> {
171
- val retryable = current.responseCode in RETRYABLE_HTTP_STATUS_CODES
172
- return ErrorClassification(isRecoverable = retryable, isNetworkError = retryable)
173
- }
164
+ is HttpDataSource.InvalidResponseCodeException ->
165
+ return current.responseCode in RETRYABLE_HTTP_STATUS_CODES
174
166
  // Mirrors DefaultLoadErrorHandlingPolicy's fatal set.
175
167
  is HttpDataSource.CleartextNotPermittedException,
176
168
  is ParserException,
177
169
  is FileNotFoundException,
178
- is Loader.UnexpectedLoaderException -> return nonRecoverable
170
+ is Loader.UnexpectedLoaderException -> return false
179
171
  }
180
172
  current = current.cause
181
173
  }
182
174
 
183
175
  // A position the source can no longer serve (e.g. behind a live window) won't come back on an
184
176
  // in-place retry.
185
- if (DataSourceException.isCausedByPositionOutOfRange(exception)) {
186
- return nonRecoverable
187
- }
188
-
189
- return ErrorClassification(isRecoverable = true, isNetworkError = true)
177
+ return !DataSourceException.isCausedByPositionOutOfRange(exception)
190
178
  }
191
179
 
192
180
  override fun getMinimumLoadableRetryCount(dataType: Int): Int {
@@ -48,7 +48,7 @@ class LegacyRatingTest {
48
48
  Bundle.EMPTY,
49
49
  false,
50
50
  )
51
- private val session = service.onGetSession(legacyController)
51
+ private val session = service.onGetSession(legacyController)!!
52
52
 
53
53
  @After
54
54
  fun destroy() {
@@ -1,10 +1,17 @@
1
1
  package com.audiobrowser
2
2
 
3
3
  import android.content.ComponentName
4
+ import android.content.ContextWrapper
4
5
  import android.content.Intent
5
6
  import android.os.Binder
7
+ import android.os.Bundle
6
8
  import android.os.Looper
9
+ import android.os.Process
10
+ import androidx.annotation.OptIn
7
11
  import androidx.media3.common.C
12
+ import androidx.media3.common.util.UnstableApi
13
+ import androidx.media3.session.MediaController
14
+ import androidx.media3.session.MediaSession
8
15
  import com.audiobrowser.model.PlayerUpdateOptions
9
16
  import com.audiobrowser.player.PlaybackStateStore
10
17
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
@@ -14,6 +21,7 @@ import java.util.concurrent.TimeUnit
14
21
  import org.junit.After
15
22
  import org.junit.Assert.assertEquals
16
23
  import org.junit.Assert.assertFalse
24
+ import org.junit.Assert.assertNull
17
25
  import org.junit.Assert.assertTrue
18
26
  import org.junit.Test
19
27
  import org.junit.runner.RunWith
@@ -52,6 +60,35 @@ class ServiceTaskRemovedTest {
52
60
  idle()
53
61
  }
54
62
 
63
+ @OptIn(UnstableApi::class)
64
+ private fun connectController(packageName: String) {
65
+ val application = RuntimeEnvironment.getApplication()
66
+ shadowOf(application.packageManager)
67
+ .setPackagesForUid(Process.myUid(), application.packageName, packageName)
68
+ val context =
69
+ object : ContextWrapper(application) {
70
+ override fun getPackageName() = packageName
71
+ }
72
+ // Only to reach the private session: onGetSession ignores its argument.
73
+ val session =
74
+ service.onGetSession(
75
+ MediaSession.ControllerInfo.createTestOnlyControllerInfo(
76
+ packageName,
77
+ 0,
78
+ Process.myUid(),
79
+ 0,
80
+ 0,
81
+ false,
82
+ Bundle.EMPTY,
83
+ false,
84
+ )
85
+ )
86
+ val future = MediaController.Builder(context, session!!.token).buildAsync()
87
+ idle()
88
+ // Throws if the session refused the controller.
89
+ future.get()
90
+ }
91
+
55
92
  private fun removeTask(behavior: AppKilledPlaybackBehavior? = null) {
56
93
  behavior?.let { player.applyOptions(PlayerUpdateOptions(appKilledPlaybackBehavior = it)) }
57
94
  service.onTaskRemoved(null)
@@ -198,4 +235,52 @@ class ServiceTaskRemovedTest {
198
235
  assertTrue(player.exoPlayer.playWhenReady)
199
236
  assertFalse(shadowOf(service).isStoppedBySelf)
200
237
  }
238
+
239
+ @Test
240
+ fun `a removed task stops playback while the Bluetooth stack is connected as a controller`() {
241
+ controller.bind()
242
+ playTrack("a")
243
+ connectController("com.google.android.bluetooth")
244
+
245
+ removeTask()
246
+
247
+ assertEquals(emptyList<String>(), player.tracks.map { it.title })
248
+ assertEquals(PlaybackState.STOPPED, player.playbackState)
249
+ assertTrue(shadowOf(service).isStoppedBySelf)
250
+ }
251
+
252
+ @Test
253
+ fun `a removed task only pauses while Android Auto is connected`() {
254
+ playTrack("a")
255
+ connectController("com.google.android.projection.gearhead")
256
+
257
+ removeTask()
258
+
259
+ assertFalse(player.exoPlayer.isReleased)
260
+ assertEquals(listOf("a"), player.tracks.map { it.title })
261
+ assertFalse(player.exoPlayer.playWhenReady)
262
+ assertTrue(shadowOf(service).isForegroundStopped)
263
+ assertTrue(shadowOf(service).notificationShouldRemoved)
264
+ assertFalse(shadowOf(service).isStoppedBySelf)
265
+ }
266
+
267
+ @Test
268
+ fun `a removed task only pauses while Android Automotive is connected`() {
269
+ playTrack("a")
270
+ connectController("com.android.car.media")
271
+
272
+ removeTask()
273
+
274
+ assertFalse(player.exoPlayer.isReleased)
275
+ assertEquals(listOf("a"), player.tracks.map { it.title })
276
+ }
277
+
278
+ @Test
279
+ fun `a media browser binding after the task is removed gets no session`() {
280
+ playTrack("a")
281
+ connectController("com.google.android.bluetooth")
282
+ removeTask()
283
+
284
+ assertNull(service.onBind(Intent("android.media.browse.MediaBrowserService")))
285
+ }
201
286
  }
@@ -8,6 +8,7 @@ import android.os.Looper
8
8
  import androidx.media3.common.C
9
9
  import androidx.media3.common.PlaybackException
10
10
  import androidx.media3.common.Player as MediaPlayer
11
+ import androidx.media3.common.util.StuckPlayerException
11
12
  import com.audiobrowser.Callbacks
12
13
  import com.audiobrowser.TestFixtures
13
14
  import com.audiobrowser.model.PlayerSetupOptions
@@ -103,6 +104,16 @@ class PlayerRetryTest {
103
104
  verify(callbacks, never()).onPlaybackError(null)
104
105
  }
105
106
 
107
+ @Test
108
+ fun `a toggle after a terminal error reloads`() {
109
+ failTerminally()
110
+
111
+ player.togglePlayback()
112
+
113
+ assertTrue(player.exoPlayer.playWhenReady)
114
+ assertEquals(MediaPlayer.STATE_BUFFERING, player.exoPlayer.playbackState)
115
+ }
116
+
106
117
  @Test
107
118
  fun `a pause during a retry stays paused and the next play reloads`() {
108
119
  pauseDuringRetry { player.pause() }
@@ -122,8 +133,8 @@ class PlayerRetryTest {
122
133
  }
123
134
 
124
135
  /** Pauses with a retry pending and runs past every backoff it would have taken. */
125
- private fun pauseDuringRetry(pause: () -> Unit) {
126
- play("https://127.0.0.1:9/stream", RetryPolicy.Infinite())
136
+ private fun pauseDuringRetry(vararg next: String, pause: () -> Unit) {
137
+ play("https://127.0.0.1:9/stream", *next, retryPolicy = RetryPolicy.Infinite())
127
138
  awaitRetry("a pending retry")
128
139
 
129
140
  pause()
@@ -149,6 +160,36 @@ class PlayerRetryTest {
149
160
  player.playbackError?.retrying == true
150
161
  }
151
162
 
163
+ @Test
164
+ fun `removing a failed current track plays the next`() {
165
+ failTerminally(Uri.fromFile(silentWav()).toString())
166
+
167
+ player.remove(listOf(0))
168
+
169
+ idleUntil("the next track playing") { player.playbackState == PlaybackState.PLAYING }
170
+ }
171
+
172
+ @Test
173
+ fun `removing another track keeps a terminal error`() {
174
+ failTerminally(Uri.fromFile(silentWav()).toString())
175
+
176
+ player.remove(listOf(1))
177
+ shadowOf(Looper.getMainLooper()).idle()
178
+
179
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
180
+ assertEquals(PlaybackState.ERROR, player.playbackState)
181
+ }
182
+
183
+ @Test
184
+ fun `removing the current track after a cancelled retry stays idle`() {
185
+ pauseDuringRetry(Uri.fromFile(silentWav()).toString()) { player.pause() }
186
+
187
+ player.remove(listOf(0))
188
+ shadowOf(Looper.getMainLooper()).idle()
189
+
190
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
191
+ }
192
+
152
193
  @Test
153
194
  fun `emptying the queue clears a terminal error`() {
154
195
  failTerminally()
@@ -167,7 +208,7 @@ class PlayerRetryTest {
167
208
  connectivity.networkCallbacks.forEach { it.onAvailable(wifi) }
168
209
  // A closed port: the load fails at once, the retry is pending, and the next failure is
169
210
  // terminal.
170
- play("https://127.0.0.1:9/stream", RetryPolicy.Limited(maxRetries = 1))
211
+ play("https://127.0.0.1:9/stream", retryPolicy = RetryPolicy.Limited(maxRetries = 1))
171
212
  player.observeNetworkConnectivity(scope)
172
213
  idleUntil("the retry gave up") {
173
214
  ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
@@ -192,16 +233,66 @@ class PlayerRetryTest {
192
233
  assertEquals(PlaybackState.ERROR, player.playbackState)
193
234
  }
194
235
 
236
+ @Test
237
+ fun `offline, a stuck recovery leaves the recovery budget running`() {
238
+ stuckRecoveryMidBudget(online = false)
239
+
240
+ assertEquals(PlaybackState.ERROR, player.playbackState)
241
+ // The load error, not a stuck give-up.
242
+ assertEquals("not-connected-to-internet", player.playbackError?.code)
243
+ }
244
+
245
+ @Test
246
+ fun `online, a stuck recovery refills the recovery budget`() {
247
+ stuckRecoveryMidBudget(online = true)
248
+
249
+ assertEquals(true, player.playbackError?.retrying)
250
+ }
251
+
252
+ /**
253
+ * A load marked as played retries a closed port under a 30 s recovery budget, takes a stuck
254
+ * report at 25 s, and runs on to 45 s, short of media3's own 60 s stuck detection. The player is
255
+ * not idle, so the recovery's re-prepare does nothing: this covers the budget refill only.
256
+ */
257
+ private fun stuckRecoveryMidBudget(online: Boolean) {
258
+ connectivity.setNetworkCapabilities(wifi, capabilities(validated = online))
259
+ connectivity.networkCallbacks.forEach { it.onAvailable(wifi) }
260
+ play(
261
+ "https://127.0.0.1:9/stream",
262
+ retryPolicy = RetryPolicy.Infinite(maxRetryDurationMs = 30_000),
263
+ )
264
+ awaitRetry("a pending retry")
265
+ player.hasPlayedCache = true
266
+ advanceSeconds(25)
267
+ assertEquals(true, player.playbackError?.retrying)
268
+
269
+ player.playerListener.onPlayerError(
270
+ PlaybackException(
271
+ "stuck",
272
+ StuckPlayerException(StuckPlayerException.STUCK_BUFFERING_NO_PROGRESS, 60_000),
273
+ PlaybackException.ERROR_CODE_TIMEOUT,
274
+ )
275
+ )
276
+ advanceSeconds(20)
277
+ }
278
+
279
+ private fun advanceSeconds(seconds: Int) =
280
+ repeat(seconds) {
281
+ ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
282
+ Thread.sleep(10)
283
+ shadowOf(Looper.getMainLooper()).idle()
284
+ }
285
+
195
286
  /** A closed port: the load fails at once, and with no retries the failure is terminal. */
196
- private fun failTerminally() {
197
- play("https://127.0.0.1:9/stream", RetryPolicy.Limited(maxRetries = 0))
287
+ private fun failTerminally(vararg next: String) {
288
+ play("https://127.0.0.1:9/stream", *next, retryPolicy = RetryPolicy.Limited(maxRetries = 0))
198
289
  idleUntil("a terminal error") {
199
290
  ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
200
291
  player.playbackState == PlaybackState.ERROR
201
292
  }
202
293
  }
203
294
 
204
- private fun play(src: String, retryPolicy: RetryPolicy = RetryPolicy.Default) {
295
+ private fun play(vararg srcs: String, retryPolicy: RetryPolicy = RetryPolicy.Default) {
205
296
  player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
206
297
  player.setCallbacks(callbacks)
207
298
  player.exoPlayer.trackSelectionParameters =
@@ -210,7 +301,9 @@ class PlayerRetryTest {
210
301
  .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
211
302
  .build()
212
303
  player.exoPlayer.setMediaItems(
213
- listOf(TrackFactory.toMedia3(TestFixtures.track(title = "a", src = src)))
304
+ srcs.mapIndexed { i, src ->
305
+ TrackFactory.toMedia3(TestFixtures.track(title = "$i", src = src))
306
+ }
214
307
  )
215
308
  player.exoPlayer.prepare()
216
309
  player.play()
@@ -13,13 +13,18 @@ import java.io.FileNotFoundException
13
13
  import java.io.IOException
14
14
  import java.net.SocketTimeoutException
15
15
  import java.net.UnknownHostException
16
+ import java.time.Duration
16
17
  import org.junit.Assert.assertEquals
17
18
  import org.junit.Assert.assertFalse
18
19
  import org.junit.Assert.assertNotEquals
19
20
  import org.junit.Assert.assertTrue
20
21
  import org.junit.Test
22
+ import org.junit.runner.RunWith
21
23
  import org.mockito.Mockito.mock
24
+ import org.robolectric.RobolectricTestRunner
25
+ import org.robolectric.shadows.ShadowSystemClock
22
26
 
27
+ @RunWith(RobolectricTestRunner::class)
23
28
  class RetryLoadErrorHandlingPolicyTest {
24
29
  // LoadEventInfo needs an Android Uri to construct; the policy reads only the exception and the
25
30
  // error count.
@@ -138,7 +143,7 @@ class RetryLoadErrorHandlingPolicyTest {
138
143
  }
139
144
  }
140
145
 
141
- /** Clock-based: 100ms budgets and 150ms sleeps between errors leave margin both ways. */
146
+ @RunWith(RobolectricTestRunner::class)
142
147
  class RetryLoadErrorHandlingPolicyBudgetTest {
143
148
  private val loadEventInfo = org.mockito.Mockito.mock(LoadEventInfo::class.java)
144
149
  private val mediaLoadData = MediaLoadData(C.DATA_TYPE_MEDIA)
@@ -157,7 +162,7 @@ class RetryLoadErrorHandlingPolicyBudgetTest {
157
162
  RetryLoadErrorHandlingPolicy(firstConnectMaxRetryDurationMs = 100, hasPlayed = { false })
158
163
 
159
164
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
160
- Thread.sleep(150)
165
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
161
166
  assertEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 2)))
162
167
  }
163
168
 
@@ -167,7 +172,7 @@ class RetryLoadErrorHandlingPolicyBudgetTest {
167
172
  RetryLoadErrorHandlingPolicy(firstConnectMaxRetryDurationMs = 100, hasPlayed = { true })
168
173
 
169
174
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
170
- Thread.sleep(150)
175
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
171
176
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 2)))
172
177
  }
173
178
 
@@ -182,12 +187,12 @@ class RetryLoadErrorHandlingPolicyBudgetTest {
182
187
  )
183
188
 
184
189
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
185
- Thread.sleep(150)
190
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
186
191
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 2)))
187
192
 
188
193
  online = true
189
194
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 3)))
190
- Thread.sleep(150)
195
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
191
196
  assertEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 4)))
192
197
  }
193
198
 
@@ -202,13 +207,13 @@ class RetryLoadErrorHandlingPolicyBudgetTest {
202
207
  )
203
208
 
204
209
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
205
- Thread.sleep(150)
210
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
206
211
  online = false
207
212
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 2)))
208
213
 
209
214
  online = true
210
215
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 3)))
211
- Thread.sleep(150)
216
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
212
217
  assertEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo(errorCount = 4)))
213
218
  }
214
219
 
@@ -218,7 +223,7 @@ class RetryLoadErrorHandlingPolicyBudgetTest {
218
223
  RetryLoadErrorHandlingPolicy(firstConnectMaxRetryDurationMs = 100, hasPlayed = { false })
219
224
 
220
225
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
221
- Thread.sleep(150)
226
+ ShadowSystemClock.advanceBy(Duration.ofMillis(150))
222
227
  policy.reset()
223
228
  assertNotEquals(C.TIME_UNSET, policy.getRetryDelayMsFor(errorInfo()))
224
229
  }
@@ -373,7 +373,7 @@ final class Player {
373
373
  }
374
374
 
375
375
  func togglePlayback() {
376
- setPlayWhenReady(!playWhenReady)
376
+ setPlayWhenReady(!playingState.playing)
377
377
  }
378
378
 
379
379
  func stop() {
@@ -538,6 +538,21 @@ struct PlayWhenReadyTests {
538
538
  #expect(c.deferredSeek.target == 42)
539
539
  }
540
540
 
541
+ @Test @MainActor
542
+ func toggle_fromErrorWithIntentRaised_reloads() throws {
543
+ let (c, eh, _, _) = makeCoordinator()
544
+ try loadTrack(c)
545
+ c.setPlayWhenReady(true)
546
+ c.transition(.errorOccurred(.playbackFailed))
547
+ let resolvesBefore = eh.resolveAndLoadCalls.count
548
+
549
+ c.togglePlayback()
550
+
551
+ #expect(c.playWhenReady)
552
+ #expect(eh.resolveAndLoadCalls.count == resolvesBefore + 1)
553
+ #expect(c.state == .loading)
554
+ }
555
+
541
556
  @Test @MainActor
542
557
  func true_fromStopped_triggersReload() throws {
543
558
  let (c, eh, _, _) = makeCoordinator()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.66",
3
+ "version": "0.2.0-next.68",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",
@@ -172,7 +172,8 @@ restarted from a terminal error_ (`retry()`, or any play command while in
172
172
  `'error'`), and it survives every automatic retry of that track.
173
173
 
174
174
  A new load starts fresh budgets. Within a load, the recovery budget refills
175
- after a stretch of uninterrupted playback (see below).
175
+ after a stretch of uninterrupted playback, and on Android after a recovery
176
+ (see below).
176
177
 
177
178
  How long the player keeps trying depends on one piece of evidence: **has this
178
179
  load ever produced audio?**
@@ -204,7 +205,9 @@ on.
204
205
 
205
206
  After 20 seconds of uninterrupted audible playback, the stream counts as
206
207
  recovered and the recovery budget refills (on iOS, the attempt count too), so
207
- each later dropout of a long-lived stream gets a full window.
208
+ each later dropout of a long-lived stream gets a full window. On Android, a
209
+ recovery from falling behind a live window refills it too, and so does one
210
+ from a stalled player while the device is online.
208
211
 
209
212
  The load stays the same, and so does its evidence that it has played: the
210
213
  first-connect budget does not come back.