react-native-audio-browser 0.2.0-next.57 → 0.2.0-next.58

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.
@@ -28,7 +28,7 @@ class MediaFactory(
28
28
  private val shouldRetry: () -> Boolean,
29
29
  private val isOnline: () -> Boolean = { true },
30
30
  private val hasPlayed: () -> Boolean = { false },
31
- private val onRetryPending: ((exception: IOException, isNetworkError: Boolean) -> Unit)? = null,
31
+ private val onRetryPending: ((exception: IOException) -> Unit)? = null,
32
32
  private val transferListener: TransferListener? = null,
33
33
  private val getRequestConfig: (originalUrl: String, track: Track) -> MediaRequestConfig?,
34
34
  ) : MediaSource.Factory {
@@ -83,7 +83,7 @@ class MediaFactory(
83
83
  customRetryPolicy?.let { setLoadErrorHandlingPolicy(it) }
84
84
  }
85
85
 
86
- /** Restarts the retry policy's time budget; call when the track changes. */
86
+ /** Restarts the retry policy's time budgets. */
87
87
  fun resetRetryTimer() {
88
88
  customRetryPolicy?.reset()
89
89
  }
@@ -157,9 +157,6 @@ internal constructor(
157
157
  private lateinit var loadControl: DynamicLoadControl
158
158
  private var automaticBufferManager: AutomaticBufferManager? = null
159
159
 
160
- /** A network-caused retry is waiting; regaining connectivity retries at once. */
161
- @Volatile private var pendingNetworkRetry = false
162
-
163
160
  @Volatile private var browserRegistered = CompletableDeferred<AudioBrowser>()
164
161
  private var _coilBitmapLoader: CoilBitmapLoader? = null
165
162
 
@@ -239,7 +236,9 @@ internal constructor(
239
236
  throw e
240
237
  }
241
238
 
242
- private lateinit var playerListener: PlayerListener
239
+ internal lateinit var playerListener: PlayerListener
240
+ private set
241
+
243
242
  private var cache: SimpleCache? = null
244
243
 
245
244
  private val progressTimer: PlaybackTimer by lazy {
@@ -465,13 +464,7 @@ internal constructor(
465
464
  shouldRetry = { playWhenReadyCache },
466
465
  isOnline = { networkMonitor.getOnline() },
467
466
  hasPlayed = { hasPlayedCache },
468
- onRetryPending = { exception, isNetworkError ->
469
- pendingNetworkRetry = isNetworkError
470
- if (isNetworkError) {
471
- Timber.d("Network retry pending, will accelerate on connectivity restoration")
472
- }
473
- reportRetryingError(exception)
474
- },
467
+ onRetryPending = ::reportRetryingError,
475
468
  resolveMediaConfig = { url, track -> browser?.getMediaRequestConfig(url, track) },
476
469
  )
477
470
  loadControl = engine.loadControl
@@ -543,13 +536,6 @@ internal constructor(
543
536
 
544
537
  // The formatter tells a stall from being offline, so it renders on a connectivity change too.
545
538
  nowPlaying.render()
546
-
547
- if (isOnline && pendingNetworkRetry) {
548
- Timber.d("Network restored with pending retry, triggering immediate retry")
549
- pendingNetworkRetry = false
550
- // Only while the play intent holds, and only locally: a receiver reconnects by itself.
551
- if (playWhenReadyCache) localEngine.retry()
552
- }
553
539
  }
554
540
  }
555
541
 
@@ -799,9 +785,9 @@ internal constructor(
799
785
  .build()
800
786
 
801
787
  /**
802
- * Fresh retry budgets and unproven playback, as when the track is selected again (ADR 0004).
803
- * Called when the player error clears: every restart from a terminal error goes through
804
- * prepare().
788
+ * Fresh retry budgets and unproven playback (ADR 0004): when the track changes, and when an error
789
+ * goes terminal, since whatever restarts playback from it starts a new load and nothing loads
790
+ * until then.
805
791
  */
806
792
  internal fun resetForNewLoad() {
807
793
  resetRetryTimer()
@@ -1043,9 +1029,8 @@ internal constructor(
1043
1029
  val oldState = playbackState
1044
1030
  playbackState = state
1045
1031
 
1046
- if (state == PlaybackState.PLAYING) {
1047
- hasPlayedCache = true
1048
- }
1032
+ if (state == PlaybackState.PLAYING) hasPlayedCache = true
1033
+ if (state == PlaybackState.ERROR) resetForNewLoad()
1049
1034
 
1050
1035
  // A natural end exhausts the play intent; held, it inverts the toggle, keeps audio focus and
1051
1036
  // the periodic save. Emitted before the state and queue-ended callbacks, matching iOS. The
@@ -52,7 +52,7 @@ internal fun buildPlayerEngine(
52
52
  shouldRetry: () -> Boolean,
53
53
  isOnline: () -> Boolean,
54
54
  hasPlayed: () -> Boolean,
55
- onRetryPending: (exception: IOException, isNetworkError: Boolean) -> Unit,
55
+ onRetryPending: (exception: IOException) -> Unit,
56
56
  resolveMediaConfig: (url: String, track: Track) -> MediaRequestConfig?,
57
57
  ): PlayerEngine {
58
58
  val renderer = DefaultRenderersFactory(context)
@@ -100,9 +100,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
100
100
  // It also emits onNowPlayingChanged.
101
101
  player.nowPlaying.render()
102
102
 
103
- // The new load is unproven: its failures get the short first-connect budget until it plays.
104
- player.resetRetryTimer()
105
- player.hasPlayedCache = false
103
+ player.resetForNewLoad()
106
104
 
107
105
  // Emits on its own: the incoming track may hold LOADING/BUFFERING and emit no state change.
108
106
  player.clearRetryingError()
@@ -182,11 +180,6 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
182
180
  }
183
181
  }
184
182
 
185
- override fun onPlayerErrorChanged(error: PlaybackException?) {
186
- // Cleared means a recovery path ran prepare(), which starts a new load.
187
- if (error == null) player.resetForNewLoad()
188
- }
189
-
190
183
  override fun onPlayerError(error: PlaybackException) {
191
184
  if (player.localEngine.isActive && recoverLocally(error)) return
192
185
  surface(error)
@@ -196,6 +189,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
196
189
  private fun recoverLocally(error: PlaybackException): Boolean {
197
190
  if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) {
198
191
  Timber.d("Playback fell behind live window, recovering to live edge")
192
+ player.resetRetryTimer()
199
193
  player.localEngine.retry(toLiveEdge = true)
200
194
  return true
201
195
  }
@@ -254,6 +248,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
254
248
  "Stuck player recovery: type=${error.stuckType} timeoutMs=${error.timeoutMs} " +
255
249
  "live=${player.isCurrentItemLive}"
256
250
  )
251
+ player.resetRetryTimer()
257
252
  player.localEngine.retry(toLiveEdge = player.isCurrentItemLive)
258
253
  }
259
254
  StuckRecoveryPolicy.Decision.GIVE_UP -> {
@@ -40,15 +40,14 @@ class RetryLoadErrorHandlingPolicy(
40
40
  private val shouldRetry: () -> Boolean = { true },
41
41
  private val isOnline: () -> Boolean = { true },
42
42
  private val hasPlayed: () -> Boolean = { false },
43
- private val onRetryPending: ((exception: IOException, isNetworkError: Boolean) -> Unit)? = null,
43
+ private val onRetryPending: ((exception: IOException) -> Unit)? = null,
44
44
  ) : DefaultLoadErrorHandlingPolicy() {
45
45
 
46
46
  companion object {
47
47
  private const val INITIAL_RETRY_DELAY_MS = 1000L
48
48
  private const val MAX_RETRY_DELAY_MS = 5000L
49
49
  private const val BACKOFF_MULTIPLIER = 1.5
50
- // Fixed while offline: ExoPlayer's retry timer can't be interrupted, so a short delay lets the
51
- // retry fired on network restoration land soon, and keeps polling if that never fires.
50
+ // Fixed while offline, so the first retry after connectivity returns lands soon.
52
51
  private const val OFFLINE_RETRY_DELAY_MS = 1000L
53
52
  private const val DEFAULT_MAX_RETRY_DURATION_MS = 120_000L
54
53
  private const val DEFAULT_FIRST_CONNECT_MAX_RETRY_DURATION_MS = 12_000L
@@ -135,9 +134,7 @@ class RetryLoadErrorHandlingPolicy(
135
134
 
136
135
  val delay =
137
136
  if (currentlyOffline && isNetworkError) {
138
- Timber.d(
139
- "Device is offline, using short retry delay (will accelerate when network returns)"
140
- )
137
+ Timber.d("Device is offline, using short retry delay")
141
138
  OFFLINE_RETRY_DELAY_MS
142
139
  } else {
143
140
  calculateBackoffDelay(errorCount)
@@ -147,7 +144,7 @@ class RetryLoadErrorHandlingPolicy(
147
144
  "Retrying after IO error (attempt $errorCount, delay ${delay}ms, offline=$currentlyOffline): ${exception.message}"
148
145
  )
149
146
 
150
- onRetryPending?.invoke(exception, isNetworkError)
147
+ onRetryPending?.invoke(exception)
151
148
 
152
149
  delay
153
150
  } else {
@@ -162,8 +159,7 @@ class RetryLoadErrorHandlingPolicy(
162
159
 
163
160
  /**
164
161
  * Walks the cause chain: load errors arrive as raw IOExceptions (a Wi-Fi drop is a socket or DNS
165
- * error), never as a PlaybackException. Anything not known to be fatal counts as a network error,
166
- * so connectivity restoration can retry it at once.
162
+ * error), never as a PlaybackException. Anything not known to be fatal counts as a network error.
167
163
  */
168
164
  private fun classifyError(exception: IOException): ErrorClassification {
169
165
  val nonRecoverable = ErrorClassification(isRecoverable = false, isNetworkError = false)
@@ -0,0 +1,179 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.content.Context
4
+ import android.net.ConnectivityManager
5
+ import android.net.NetworkCapabilities
6
+ import android.net.Uri
7
+ import android.os.Looper
8
+ import androidx.media3.common.C
9
+ import androidx.media3.common.PlaybackException
10
+ import androidx.media3.common.Player as MediaPlayer
11
+ import com.audiobrowser.Callbacks
12
+ import com.audiobrowser.TestFixtures
13
+ import com.audiobrowser.model.PlayerSetupOptions
14
+ import com.audiobrowser.model.RetryPolicy
15
+ import com.audiobrowser.util.TrackFactory
16
+ import com.margelo.nitro.audiobrowser.Playback
17
+ import com.margelo.nitro.audiobrowser.PlaybackState
18
+ import java.io.File
19
+ import java.nio.ByteBuffer
20
+ import java.nio.ByteOrder
21
+ import java.time.Duration
22
+ import kotlinx.coroutines.CoroutineScope
23
+ import kotlinx.coroutines.Dispatchers
24
+ import kotlinx.coroutines.cancel
25
+ import org.junit.After
26
+ import org.junit.Assert.assertEquals
27
+ import org.junit.Assert.assertFalse
28
+ import org.junit.Assert.assertTrue
29
+ import org.junit.Assert.fail
30
+ import org.junit.Rule
31
+ import org.junit.Test
32
+ import org.junit.rules.TemporaryFolder
33
+ import org.junit.runner.RunWith
34
+ import org.mockito.Mockito.mock
35
+ import org.mockito.Mockito.mockingDetails
36
+ import org.robolectric.RobolectricTestRunner
37
+ import org.robolectric.RuntimeEnvironment
38
+ import org.robolectric.Shadows.shadowOf
39
+ import org.robolectric.annotation.Config
40
+ import org.robolectric.shadows.ShadowNetwork
41
+ import org.robolectric.shadows.ShadowNetworkCapabilities
42
+ import org.robolectric.shadows.ShadowSystemClock
43
+
44
+ // SDK 28 and the disabled audio track as in PlayerSuppressionTest.
45
+ @RunWith(RobolectricTestRunner::class)
46
+ @Config(sdk = [28])
47
+ class PlayerRetryTest {
48
+
49
+ @get:Rule val folder = TemporaryFolder()
50
+
51
+ private val context = RuntimeEnvironment.getApplication()
52
+ private val connectivity =
53
+ shadowOf(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
54
+ private val wifi = ShadowNetwork.newInstance(103)
55
+ private val player = Player(context)
56
+ private val scope = CoroutineScope(Dispatchers.Unconfined)
57
+ private val callbacks = mock(Callbacks::class.java)
58
+
59
+ @After
60
+ fun release() {
61
+ scope.cancel()
62
+ player.networkMonitor.destroy()
63
+ player.exoPlayer.release()
64
+ }
65
+
66
+ @Test
67
+ fun `a recovery keeps a load that has played`() {
68
+ play(Uri.fromFile(silentWav()).toString())
69
+ idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
70
+
71
+ player.playerListener.onPlayerError(
72
+ PlaybackException("behind", null, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW)
73
+ )
74
+ player.playerListener.onPlayerErrorChanged(null)
75
+
76
+ assertTrue(player.hasPlayedCache)
77
+ }
78
+
79
+ @Test
80
+ fun `a terminal error ends the load`() {
81
+ play(Uri.fromFile(silentWav()).toString())
82
+ idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
83
+
84
+ player.playerListener.onPlayerError(
85
+ PlaybackException("failed", null, PlaybackException.ERROR_CODE_IO_UNSPECIFIED)
86
+ )
87
+
88
+ assertEquals(PlaybackState.ERROR, player.playbackState)
89
+ assertFalse(player.hasPlayedCache)
90
+ }
91
+
92
+ @Test
93
+ fun `a player that gave up stays stopped when the network returns`() {
94
+ connectivity.setNetworkCapabilities(wifi, capabilities(validated = false))
95
+ connectivity.networkCallbacks.forEach { it.onAvailable(wifi) }
96
+ // A closed port: the load fails at once, the retry is pending, and the next failure is
97
+ // terminal.
98
+ play("https://127.0.0.1:9/stream", RetryPolicy.Limited(maxRetries = 1))
99
+ player.observeNetworkConnectivity(scope)
100
+ idleUntil("the retry gave up") {
101
+ ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
102
+ player.playbackState == PlaybackState.ERROR
103
+ }
104
+ assertTrue(player.exoPlayer.playWhenReady)
105
+ assertTrue(
106
+ "a retry was pending",
107
+ mockingDetails(callbacks).invocations.any {
108
+ it.method.name == "onPlaybackChanged" &&
109
+ (it.arguments[0] as Playback).error?.retrying == true
110
+ },
111
+ )
112
+
113
+ connectivity.setNetworkCapabilities(wifi, capabilities(validated = true))
114
+ connectivity.networkCallbacks.forEach {
115
+ it.onCapabilitiesChanged(wifi, capabilities(validated = true))
116
+ }
117
+ shadowOf(Looper.getMainLooper()).idle()
118
+
119
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
120
+ assertEquals(PlaybackState.ERROR, player.playbackState)
121
+ }
122
+
123
+ private fun play(src: String, retryPolicy: RetryPolicy = RetryPolicy.Default) {
124
+ player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
125
+ player.setCallbacks(callbacks)
126
+ player.exoPlayer.trackSelectionParameters =
127
+ player.exoPlayer.trackSelectionParameters
128
+ .buildUpon()
129
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
130
+ .build()
131
+ player.exoPlayer.setMediaItems(
132
+ listOf(TrackFactory.toMedia3(TestFixtures.track(title = "a", src = src)))
133
+ )
134
+ player.exoPlayer.prepare()
135
+ player.play()
136
+ }
137
+
138
+ private fun capabilities(validated: Boolean) =
139
+ ShadowNetworkCapabilities.newInstance().also {
140
+ shadowOf(it).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
141
+ if (validated) shadowOf(it).addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
142
+ }
143
+
144
+ private fun idleUntil(what: String, condition: () -> Boolean) {
145
+ val deadline = System.currentTimeMillis() + 5_000
146
+ while (!condition()) {
147
+ if (System.currentTimeMillis() > deadline)
148
+ fail(
149
+ "timed out waiting for $what: ${player.playbackState}, " +
150
+ "exo ${player.exoPlayer.playbackState}, ${player.exoPlayer.playerError}"
151
+ )
152
+ Thread.sleep(10)
153
+ shadowOf(Looper.getMainLooper()).idle()
154
+ }
155
+ }
156
+
157
+ /** A minute of 8 kHz mono 8-bit silence, long enough that no test reaches its end. */
158
+ private fun silentWav(): File {
159
+ val samples = 8_000 * 60
160
+ val header =
161
+ ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
162
+ put("RIFF".toByteArray())
163
+ putInt(36 + samples)
164
+ put("WAVEfmt ".toByteArray())
165
+ putInt(16)
166
+ putShort(1)
167
+ putShort(1)
168
+ putInt(8_000)
169
+ putInt(8_000)
170
+ putShort(1)
171
+ putShort(8)
172
+ put("data".toByteArray())
173
+ putInt(samples)
174
+ }
175
+ return folder.newFile("silence.wav").apply {
176
+ writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
177
+ }
178
+ }
179
+ }
@@ -14,8 +14,8 @@ import java.io.IOException
14
14
  import java.net.SocketTimeoutException
15
15
  import java.net.UnknownHostException
16
16
  import org.junit.Assert.assertEquals
17
+ import org.junit.Assert.assertFalse
17
18
  import org.junit.Assert.assertNotEquals
18
- import org.junit.Assert.assertNull
19
19
  import org.junit.Assert.assertTrue
20
20
  import org.junit.Test
21
21
  import org.mockito.Mockito.mock
@@ -40,24 +40,21 @@ class RetryLoadErrorHandlingPolicyTest {
40
40
  )
41
41
 
42
42
  private fun assertNonRecoverable(exception: IOException) {
43
- var pendingNetwork: Boolean? = null
44
- val policy =
45
- RetryLoadErrorHandlingPolicy(
46
- onRetryPending = { _, isNetworkError -> pendingNetwork = isNetworkError }
47
- )
43
+ var retryPending = false
44
+ val policy = RetryLoadErrorHandlingPolicy(onRetryPending = { retryPending = true })
48
45
  val delay = policy.getRetryDelayMsFor(errorInfo(exception))
49
46
  assertEquals(C.TIME_UNSET, delay)
50
- assertNull(pendingNetwork)
47
+ assertFalse(retryPending)
51
48
  }
52
49
 
53
50
  @Test
54
- fun `offline network IOException is retried and arms the network-retry callback`() {
55
- var pendingNetwork: Boolean? = null
51
+ fun `offline network IOException is retried and reports the pending retry`() {
52
+ var retryPending = false
56
53
  val policy =
57
54
  RetryLoadErrorHandlingPolicy(
58
55
  maxRetries = null,
59
56
  isOnline = { false },
60
- onRetryPending = { _, isNetworkError -> pendingNetwork = isNetworkError },
57
+ onRetryPending = { retryPending = true },
61
58
  )
62
59
 
63
60
  val delay = policy.getRetryDelayMsFor(errorInfo(UnknownHostException("Unable to resolve host")))
@@ -65,23 +62,20 @@ class RetryLoadErrorHandlingPolicyTest {
65
62
  assertNotEquals(C.TIME_UNSET, delay)
66
63
  // The offline delay.
67
64
  assertEquals(1000L, delay)
68
- assertEquals(true, pendingNetwork)
65
+ assertTrue(retryPending)
69
66
  }
70
67
 
71
68
  @Test
72
69
  fun `socket timeout is classified as a recoverable network error`() {
73
- var pendingNetwork: Boolean? = null
70
+ var retryPending = false
74
71
  val policy =
75
- RetryLoadErrorHandlingPolicy(
76
- isOnline = { true },
77
- onRetryPending = { _, isNetworkError -> pendingNetwork = isNetworkError },
78
- )
72
+ RetryLoadErrorHandlingPolicy(isOnline = { true }, onRetryPending = { retryPending = true })
79
73
 
80
74
  val delay = policy.getRetryDelayMsFor(errorInfo(SocketTimeoutException("timeout")))
81
75
 
82
76
  assertNotEquals(C.TIME_UNSET, delay)
83
77
  assertTrue("expected a positive retry delay, got $delay", delay > 0)
84
- assertEquals(true, pendingNetwork)
78
+ assertTrue(retryPending)
85
79
  }
86
80
 
87
81
  @Test
@@ -100,32 +94,26 @@ class RetryLoadErrorHandlingPolicyTest {
100
94
  }
101
95
 
102
96
  @Test
103
- fun `retryable HTTP status (503) is recoverable and arms the network-retry callback`() {
104
- var pendingNetwork: Boolean? = null
97
+ fun `retryable HTTP status (503) is recoverable and reports the pending retry`() {
98
+ var retryPending = false
105
99
  val policy =
106
- RetryLoadErrorHandlingPolicy(
107
- isOnline = { true },
108
- onRetryPending = { _, isNetworkError -> pendingNetwork = isNetworkError },
109
- )
100
+ RetryLoadErrorHandlingPolicy(isOnline = { true }, onRetryPending = { retryPending = true })
110
101
 
111
102
  val delay = policy.getRetryDelayMsFor(errorInfo(httpError(503)))
112
103
 
113
104
  assertNotEquals(C.TIME_UNSET, delay)
114
- assertEquals(true, pendingNetwork)
105
+ assertTrue(retryPending)
115
106
  }
116
107
 
117
108
  @Test
118
109
  fun `non-retryable HTTP status (404) is not retried`() {
119
- var pendingNetwork: Boolean? = null
120
- val policy =
121
- RetryLoadErrorHandlingPolicy(
122
- onRetryPending = { _, isNetworkError -> pendingNetwork = isNetworkError }
123
- )
110
+ var retryPending = false
111
+ val policy = RetryLoadErrorHandlingPolicy(onRetryPending = { retryPending = true })
124
112
 
125
113
  val delay = policy.getRetryDelayMsFor(errorInfo(httpError(404)))
126
114
 
127
115
  assertEquals(C.TIME_UNSET, delay)
128
- assertNull(pendingNetwork)
116
+ assertFalse(retryPending)
129
117
  }
130
118
 
131
119
  @Test
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.57",
3
+ "version": "0.2.0-next.58",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",