react-native-audio-browser 0.2.0-next.82 → 0.2.0-next.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +31 -9
  2. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +39 -46
  3. package/android/src/main/java/com/audiobrowser/player/Player.kt +219 -54
  4. package/android/src/main/java/com/audiobrowser/player/PlayerEngineFactory.kt +5 -6
  5. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +88 -73
  6. package/android/src/main/java/com/audiobrowser/player/ReconnectPacer.kt +8 -9
  7. package/android/src/main/java/com/audiobrowser/player/RetryFocus.kt +126 -0
  8. package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +55 -121
  9. package/android/src/main/java/com/audiobrowser/player/RetryLocks.kt +52 -0
  10. package/android/src/main/java/com/audiobrowser/player/RetryLoop.kt +310 -0
  11. package/android/src/main/java/com/audiobrowser/player/RetryView.kt +31 -0
  12. package/android/src/main/java/com/audiobrowser/player/SessionViewListener.kt +148 -0
  13. package/android/src/main/java/com/audiobrowser/remote/RemoteOutputsController.kt +4 -1
  14. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +3 -1
  15. package/android/src/main/java/com/audiobrowser/util/NetworkConnectivityMonitor.kt +4 -6
  16. package/android/src/test/java/androidx/media3/session/SessionViews.kt +9 -0
  17. package/android/src/test/java/com/audiobrowser/NetworkFixtures.kt +25 -0
  18. package/android/src/test/java/com/audiobrowser/player/LiveStreamEndTest.kt +15 -53
  19. package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +190 -53
  20. package/android/src/test/java/com/audiobrowser/player/RetryFocusTest.kt +97 -0
  21. package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +90 -152
  22. package/android/src/test/java/com/audiobrowser/player/RetryLocksTest.kt +48 -0
  23. package/android/src/test/java/com/audiobrowser/player/RetryLoopCaseTest.kt +181 -0
  24. package/android/src/test/java/com/audiobrowser/player/RetryLoopTest.kt +221 -0
  25. package/android/src/test/java/com/audiobrowser/player/RetryMaskingTest.kt +176 -0
  26. package/android/src/test/java/com/audiobrowser/player/SessionPlayTest.kt +2 -0
  27. package/android/src/test/java/com/audiobrowser/player/SessionViewListenerTest.kt +21 -0
  28. package/android/src/test/java/com/audiobrowser/player/SessionViewTest.kt +2 -0
  29. package/android/src/test/java/com/audiobrowser/util/NetworkConnectivityMonitorTest.kt +13 -4
  30. package/ios/Player/ErrorStatus.swift +4 -0
  31. package/ios/Player/Player.swift +23 -9
  32. package/ios/Player/RetryLoop.swift +13 -9
  33. package/ios/Tests/PlayerPolicyTests.swift +114 -5
  34. package/ios/Tests/PlayerTests.swift +32 -0
  35. package/ios/Tests/RetryLoopTests.swift +8 -5
  36. package/lib/commonjs/features/player/setup.js +5 -4
  37. package/lib/commonjs/features/player/setup.js.map +1 -1
  38. package/lib/module/features/player/setup.js +5 -4
  39. package/lib/module/features/player/setup.js.map +1 -1
  40. package/lib/typescript/src/features/player/setup.d.ts +19 -13
  41. package/lib/typescript/src/features/player/setup.d.ts.map +1 -1
  42. package/package.json +1 -1
  43. package/src/features/player/setup.ts +19 -13
  44. package/website/guide/errors.md +42 -38
  45. package/website/guide/network.md +4 -3
  46. package/android/src/main/java/com/audiobrowser/player/StuckRecoveryPolicy.kt +0 -37
  47. package/android/src/test/java/com/audiobrowser/player/StuckRecoveryPolicyTest.kt +0 -40
@@ -0,0 +1,221 @@
1
+ package com.audiobrowser.player
2
+
3
+ import androidx.media3.common.PlaybackException
4
+ import androidx.media3.common.Player as MediaPlayer
5
+ import org.junit.Assert.assertEquals
6
+ import org.junit.Assert.assertFalse
7
+ import org.junit.Assert.assertNull
8
+ import org.junit.Assert.assertTrue
9
+ import org.junit.Test
10
+
11
+ /** What the loop does around its engine that the case file's timelines do not reach. */
12
+ class RetryLoopTest {
13
+ private var now = 0L
14
+ private val tasks = mutableListOf<Pair<Long, () -> Unit>>()
15
+ private var reconnects = 0
16
+ private var gaveUp = false
17
+ private var holding = false
18
+ private var keeping = false
19
+
20
+ private val loop =
21
+ RetryLoop(
22
+ clock = { now },
23
+ timer = { delayMs, action ->
24
+ val task = (now + delayMs) to action
25
+ tasks += task
26
+ val cancel: () -> Unit = { tasks.remove(task) }
27
+ cancel
28
+ },
29
+ engine =
30
+ object : RetryLoop.Engine {
31
+ override fun reconnect() {
32
+ reconnects++
33
+ }
34
+
35
+ override fun awaitNetwork() {}
36
+
37
+ override fun holdChanged(held: Boolean, kept: Boolean) {
38
+ holding = held
39
+ keeping = kept
40
+ }
41
+
42
+ override fun giveUp(cause: PlaybackException?) {
43
+ gaveUp = true
44
+ }
45
+ },
46
+ maxRetries = null,
47
+ recoveryMs = 120_000,
48
+ firstConnectMs = 12_000,
49
+ online = true,
50
+ )
51
+
52
+ private fun advanceTo(at: Long) {
53
+ while (true) {
54
+ val next = tasks.filter { it.first <= at }.minByOrNull { it.first } ?: break
55
+ tasks.remove(next)
56
+ now = maxOf(now, next.first)
57
+ next.second()
58
+ }
59
+ now = at
60
+ }
61
+
62
+ /** A Load that played from 0 and whose connection ended at [at], its error surfaced. */
63
+ private fun playedAndEnded(at: Long) {
64
+ loop.loadStarted()
65
+ loop.playIntentChanged(true)
66
+ advanceTo(500)
67
+ loop.isPlayingChanged(true)
68
+ advanceTo(at)
69
+ loop.isPlayingChanged(false)
70
+ loop.connectionFailed(inPlace = false, atMs = at)
71
+ assertTrue(loop.onPlayerError(null, stuck = false))
72
+ }
73
+
74
+ @Test
75
+ fun `a transient focus loss during a reconnect wait reconnects when it ends`() {
76
+ playedAndEnded(at = 30_000)
77
+ loop.connectionStarted()
78
+ advanceTo(30_100)
79
+ loop.connectionFailed(inPlace = false, atMs = 30_100)
80
+ loop.onPlayerError(null, stuck = false)
81
+ assertEquals(31_100L, loop.reconnectDueMs)
82
+
83
+ // The suppression drops the intent and, unlike a pause, prepares nothing when it ends.
84
+ loop.playIntentChanged(false)
85
+ advanceTo(40_000)
86
+ assertEquals(0, reconnects)
87
+ loop.playIntentChanged(true)
88
+ advanceTo(40_000)
89
+
90
+ assertEquals(1, reconnects)
91
+ }
92
+
93
+ @Test
94
+ fun `a terminal error elsewhere stops the loop until a new Load`() {
95
+ loop.loadStarted()
96
+ loop.playIntentChanged(true)
97
+ assertEquals(120_000L, loop.deadlineMs)
98
+
99
+ loop.suspend()
100
+ advanceTo(200_000)
101
+
102
+ assertFalse("the old deadline fired", gaveUp)
103
+ assertTrue(loop.stopped)
104
+ loop.loadStarted()
105
+ assertEquals(320_000L, loop.deadlineMs)
106
+ }
107
+
108
+ @Test
109
+ fun `the audio a failed connection's buffer plays counts as delivered`() {
110
+ loop.loadStarted()
111
+ loop.playIntentChanged(true)
112
+ advanceTo(300)
113
+ // The burst arrived and the server closed before anything played.
114
+ loop.connectionFailed(inPlace = false, atMs = 300)
115
+ advanceTo(1_000)
116
+ loop.isPlayingChanged(true)
117
+ advanceTo(3_000)
118
+ loop.isPlayingChanged(false)
119
+ loop.onPlayerError(null, stuck = false)
120
+
121
+ // Delivered audio reconnects as soon as the 1 s floor allows, not after the first backoff.
122
+ assertEquals(3_000L, loop.reconnectDueMs)
123
+ }
124
+
125
+ @Test
126
+ fun `an error that arrives after the engine was stopped is still the loop's`() {
127
+ loop.loadStarted()
128
+ loop.playIntentChanged(true)
129
+ loop.connectionFailed(inPlace = false, atMs = 300)
130
+ loop.playIntentChanged(false)
131
+ loop.engineStopped()
132
+
133
+ assertTrue(loop.onPlayerError(null, stuck = false))
134
+ assertNull("a paused loop reconnects nothing", loop.reconnectDueMs)
135
+ }
136
+
137
+ @Test
138
+ fun `a connection that starts over a pending failure starts clean`() {
139
+ loop.loadStarted()
140
+ loop.playIntentChanged(true)
141
+ loop.connectionFailed(inPlace = false, atMs = 300)
142
+
143
+ loop.connectionStarted()
144
+
145
+ assertFalse(loop.failurePending)
146
+ assertFalse(loop.reconnecting)
147
+ loop.connectionFailed(inPlace = false, atMs = 2_000)
148
+ assertTrue("the new connection's end is the loop's", loop.onPlayerError(null, stuck = false))
149
+ }
150
+
151
+ @Test
152
+ fun `holds the device awake only while it keeps the idle engine for a play intent`() {
153
+ playedAndEnded(at = 30_000)
154
+ assertTrue("held between connections", holding)
155
+
156
+ loop.playIntentChanged(false)
157
+ assertFalse("held over a pause", holding)
158
+ assertTrue("the idle engine still kept", keeping)
159
+ loop.playIntentChanged(true)
160
+ assertTrue(holding)
161
+
162
+ advanceTo(31_000)
163
+ loop.connectionStarted()
164
+ assertFalse("held over a connection", holding)
165
+
166
+ loop.connectionFailed(inPlace = false, atMs = 31_100)
167
+ loop.onPlayerError(null, stuck = false)
168
+ advanceTo(200_000)
169
+ assertTrue(gaveUp)
170
+ assertFalse("held after the give-up", holding)
171
+ assertFalse("kept after the give-up", keeping)
172
+ }
173
+
174
+ @Test
175
+ fun `a stuck engine reconnects as a plain connection end`() {
176
+ playedAndEnded(at = 30_000)
177
+ advanceTo(30_000)
178
+ loop.connectionStarted()
179
+ advanceTo(31_500)
180
+ loop.isPlayingChanged(true)
181
+ advanceTo(100_000)
182
+ loop.isPlayingChanged(false)
183
+
184
+ assertTrue(loop.onPlayerError(null, stuck = true))
185
+ assertEquals(100_000L, loop.reconnectDueMs)
186
+ }
187
+ }
188
+
189
+ class RetryViewTest {
190
+ @Test
191
+ fun `the loop's idle engine reads buffering, a settled one idle`() {
192
+ assertEquals(
193
+ MediaPlayer.STATE_BUFFERING,
194
+ RetryView.engineState(MediaPlayer.STATE_IDLE, true, false, 0),
195
+ )
196
+ assertEquals(
197
+ MediaPlayer.STATE_IDLE,
198
+ RetryView.engineState(MediaPlayer.STATE_IDLE, false, false, 0),
199
+ )
200
+ }
201
+
202
+ @Test
203
+ fun `a READY with nothing buffered over a failed connection is the blip`() {
204
+ assertEquals(
205
+ MediaPlayer.STATE_BUFFERING,
206
+ RetryView.engineState(MediaPlayer.STATE_READY, true, true, 0),
207
+ )
208
+ }
209
+
210
+ @Test
211
+ fun `a READY with audio buffered is real, failed connection or not`() {
212
+ assertEquals(
213
+ MediaPlayer.STATE_READY,
214
+ RetryView.engineState(MediaPlayer.STATE_READY, true, true, 2_000),
215
+ )
216
+ assertEquals(
217
+ MediaPlayer.STATE_READY,
218
+ RetryView.engineState(MediaPlayer.STATE_READY, false, false, 0),
219
+ )
220
+ }
221
+ }
@@ -0,0 +1,176 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Looper
4
+ import android.support.v4.media.session.PlaybackStateCompat
5
+ import androidx.media3.common.C
6
+ import androidx.media3.common.Player as MediaPlayer
7
+ import androidx.media3.session.MediaSession
8
+ import androidx.media3.session.controllerError
9
+ import androidx.media3.session.controllerPlaying
10
+ import androidx.media3.session.controllerState
11
+ import androidx.media3.session.legacyState
12
+ import com.audiobrowser.Callbacks
13
+ import com.audiobrowser.TestFixtures
14
+ import com.audiobrowser.goOnline
15
+ import com.audiobrowser.model.PlayerSetupOptions
16
+ import com.audiobrowser.model.RetryPolicy
17
+ import com.audiobrowser.util.TrackFactory
18
+ import com.margelo.nitro.audiobrowser.Playback
19
+ import com.margelo.nitro.audiobrowser.PlaybackState
20
+ import java.io.IOException
21
+ import java.net.ServerSocket
22
+ import java.time.Duration
23
+ import java.util.concurrent.atomic.AtomicInteger
24
+ import kotlin.concurrent.thread
25
+ import org.junit.After
26
+ import org.junit.Assert.assertEquals
27
+ import org.junit.Assert.assertFalse
28
+ import org.junit.Assert.assertNotEquals
29
+ import org.junit.Assert.assertNull
30
+ import org.junit.Assert.assertTrue
31
+ import org.junit.Assert.fail
32
+ import org.junit.Test
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.ShadowSystemClock
41
+
42
+ /**
43
+ * While the retry loop holds the engine, its idle engine and its error reach no one: not JS (the
44
+ * callbacks), not media3 controllers such as the notification (the session's player info), not
45
+ * Android Auto and the system UI (the legacy session). Each surface is read after every turn of the
46
+ * main looper, as a controller would be told. The READY blip needs decoded audio, which these tests
47
+ * never play: [RetryViewTest] covers its view.
48
+ */
49
+ @RunWith(RobolectricTestRunner::class)
50
+ @Config(sdk = [28])
51
+ class RetryMaskingTest {
52
+
53
+ private val context = RuntimeEnvironment.getApplication()
54
+ private val player = Player(context)
55
+ private val callbacks = mock(Callbacks::class.java)
56
+ private lateinit var session: MediaSession
57
+
58
+ @After
59
+ fun release() {
60
+ server.close()
61
+ session.release()
62
+ player.networkMonitor.destroy()
63
+ player.exoPlayer.release()
64
+ }
65
+
66
+ private val server = ServerSocket(0)
67
+ private val connections = AtomicInteger()
68
+
69
+ init {
70
+ // Takes each connection and ends it unanswered: a recoverable failure of a live stream.
71
+ thread(isDaemon = true) {
72
+ while (!server.isClosed) {
73
+ try {
74
+ server.accept().close()
75
+ connections.incrementAndGet()
76
+ } catch (_: IOException) {
77
+ return@thread
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ @Test
84
+ fun `the loop reconnects, and its idle engine and error reach no surface`() {
85
+ play("http://127.0.0.1:${server.localPort}/live.mp3")
86
+ var held = 0
87
+ stepUntil("the loop holding the idle engine a while") {
88
+ if (player.exoPlayer.playbackState == MediaPlayer.STATE_IDLE) {
89
+ assertTrue("the loop holds the idle engine", player.retryLoop!!.reconnecting)
90
+ held++
91
+ }
92
+ if (player.retryLoop!!.reconnecting) assertLoading()
93
+ held >= 30 && connections.get() >= 3
94
+ }
95
+ assertNoTerminalError()
96
+ }
97
+
98
+ @Test
99
+ fun `a give-up while the loop holds the idle engine leaves no surface buffering`() {
100
+ play(
101
+ "http://127.0.0.1:${server.localPort}/live.mp3",
102
+ RetryPolicy.Infinite(firstConnectMaxRetryDurationMs = 2_000),
103
+ )
104
+ stepUntil("the give-up") { player.playbackState == PlaybackState.ERROR }
105
+
106
+ assertNotEquals("media3 controllers", MediaPlayer.STATE_BUFFERING, session.controllerState())
107
+ assertNotEquals(
108
+ "legacy controllers",
109
+ PlaybackStateCompat.STATE_BUFFERING,
110
+ session.legacyState(),
111
+ )
112
+ }
113
+
114
+ private fun assertLoading() {
115
+ assertTrue(
116
+ "JS: ${player.playbackState}",
117
+ player.playbackState in setOf(PlaybackState.LOADING, PlaybackState.BUFFERING),
118
+ )
119
+ assertEquals("media3 controllers", MediaPlayer.STATE_BUFFERING, session.controllerState())
120
+ assertNull("media3 controllers", session.controllerError())
121
+ assertFalse("media3 controllers", session.controllerPlaying())
122
+ assertEquals("legacy controllers", PlaybackStateCompat.STATE_BUFFERING, session.legacyState())
123
+ }
124
+
125
+ private fun assertNoTerminalError() {
126
+ assertFalse(
127
+ "JS heard a terminal error",
128
+ mockingDetails(callbacks).invocations.any {
129
+ it.method.name == "onPlaybackError" && it.arguments[0] != null
130
+ },
131
+ )
132
+ assertFalse(
133
+ "JS heard the engine idle",
134
+ mockingDetails(callbacks).invocations.any {
135
+ it.method.name == "onPlaybackChanged" &&
136
+ (it.arguments[0] as Playback).state in setOf(PlaybackState.NONE, PlaybackState.ERROR)
137
+ },
138
+ )
139
+ }
140
+
141
+ private fun play(src: String, retryPolicy: RetryPolicy = RetryPolicy.Infinite()) {
142
+ goOnline(context)
143
+ player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
144
+ player.setCallbacks(callbacks)
145
+ session = MediaSession.Builder(context, player.forwardingPlayer).build()
146
+ player.setMediaSession(session)
147
+ player.exoPlayer.trackSelectionParameters =
148
+ player.exoPlayer.trackSelectionParameters
149
+ .buildUpon()
150
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
151
+ .build()
152
+ player.exoPlayer.setMediaItems(
153
+ listOf(TrackFactory.toMedia3(TestFixtures.track(src = src).copy(live = true)))
154
+ )
155
+ player.exoPlayer.prepare()
156
+ player.play()
157
+ }
158
+
159
+ /** Steps the clock 100 ms and the main looper a turn at a time, checking [step] after each. */
160
+ private fun stepUntil(what: String, step: () -> Boolean) {
161
+ val deadline = System.currentTimeMillis() + 10_000
162
+ while (!step()) {
163
+ if (System.currentTimeMillis() > deadline)
164
+ fail(
165
+ "timed out waiting for $what: ${player.playbackState}, exo ${player.exoPlayer.playbackState}"
166
+ )
167
+ ShadowSystemClock.advanceBy(Duration.ofMillis(100))
168
+ Thread.sleep(10)
169
+ val looper = shadowOf(Looper.getMainLooper())
170
+ while (!looper.isIdle) {
171
+ looper.runOneTask()
172
+ step()
173
+ }
174
+ }
175
+ }
176
+ }
@@ -7,6 +7,7 @@ import androidx.media3.common.Player as MediaPlayer
7
7
  import androidx.media3.common.util.Util
8
8
  import com.audiobrowser.Callbacks
9
9
  import com.audiobrowser.TestFixtures
10
+ import com.audiobrowser.goOnline
10
11
  import com.audiobrowser.model.PlayerSetupOptions
11
12
  import com.audiobrowser.model.RetryPolicy
12
13
  import com.audiobrowser.util.TrackFactory
@@ -173,6 +174,7 @@ class SessionPlayTest {
173
174
  }
174
175
 
175
176
  private fun load(src: String, retryPolicy: RetryPolicy = RetryPolicy.Default) {
177
+ goOnline(context)
176
178
  player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
177
179
  player.setCallbacks(callbacks)
178
180
  player.exoPlayer.trackSelectionParameters =
@@ -0,0 +1,21 @@
1
+ package com.audiobrowser.player
2
+
3
+ import androidx.media3.common.Player as MediaPlayer
4
+ import org.junit.Assert.assertEquals
5
+ import org.junit.Test
6
+
7
+ class SessionViewListenerTest {
8
+ @Test
9
+ fun `forwards every callback media3's listener declares`() {
10
+ val declared =
11
+ MediaPlayer.Listener::class.java.declaredMethods.map { it.name to it.parameterTypes.toList() }
12
+ val overridden =
13
+ SessionViewListener::class
14
+ .java
15
+ .declaredMethods
16
+ .map { it.name to it.parameterTypes.toList() }
17
+ .toSet()
18
+
19
+ assertEquals(emptyList<Any>(), declared.filterNot { it in overridden })
20
+ }
21
+ }
@@ -10,6 +10,7 @@ import androidx.media3.session.legacy.PlaybackStateCompat
10
10
  import androidx.media3.session.legacyState
11
11
  import com.audiobrowser.Callbacks
12
12
  import com.audiobrowser.TestFixtures
13
+ import com.audiobrowser.goOnline
13
14
  import com.audiobrowser.model.PlayerSetupOptions
14
15
  import com.audiobrowser.model.RetryPolicy
15
16
  import com.audiobrowser.util.TrackFactory
@@ -136,6 +137,7 @@ class SessionViewTest {
136
137
  }
137
138
 
138
139
  private fun play(retryPolicy: RetryPolicy, src: String = "https://127.0.0.1:9/stream") {
140
+ goOnline(context)
139
141
  player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
140
142
  player.setCallbacks(callbacks)
141
143
  session = MediaSession.Builder(context, player.forwardingPlayer).build()
@@ -53,6 +53,8 @@ class NetworkConnectivityMonitorTest {
53
53
  shadowOf(it).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
54
54
  }
55
55
 
56
+ private fun noInternet() = ShadowNetworkCapabilities.newInstance()
57
+
56
58
  private fun becomesDefault(network: Network) {
57
59
  callback.onAvailable(network)
58
60
  callback.onCapabilitiesChanged(network, connectivityManager.getNetworkCapabilities(network)!!)
@@ -74,17 +76,24 @@ class NetworkConnectivityMonitorTest {
74
76
  }
75
77
 
76
78
  @Test
77
- fun `is offline while the default network is not validated`() {
79
+ fun `is online on a default network with internet that never validates`() {
78
80
  shadow.setNetworkCapabilities(wifi, unvalidated())
79
81
  becomesDefault(wifi)
82
+ assertTrue(monitor.getOnline())
83
+ }
84
+
85
+ @Test
86
+ fun `is offline while the default network has no internet`() {
87
+ shadow.setNetworkCapabilities(wifi, noInternet())
88
+ becomesDefault(wifi)
80
89
  assertFalse(monitor.getOnline())
81
- callback.onCapabilitiesChanged(wifi, validated())
90
+ callback.onCapabilitiesChanged(wifi, unvalidated())
82
91
  assertTrue(monitor.getOnline())
83
92
  }
84
93
 
85
94
  @Test
86
95
  fun `takes the capabilities of a new default network on its arrival`() {
87
- shadow.setNetworkCapabilities(wifi, unvalidated())
96
+ shadow.setNetworkCapabilities(wifi, noInternet())
88
97
  becomesDefault(mobile)
89
98
  callback.onAvailable(wifi)
90
99
  assertFalse(monitor.getOnline())
@@ -93,7 +102,7 @@ class NetworkConnectivityMonitorTest {
93
102
  @Test
94
103
  fun `ignores capability changes of a network that is not the default`() {
95
104
  becomesDefault(wifi)
96
- callback.onCapabilitiesChanged(mobile, unvalidated())
105
+ callback.onCapabilitiesChanged(mobile, noInternet())
97
106
  assertTrue(monitor.getOnline())
98
107
  }
99
108
  }
@@ -49,4 +49,8 @@ extension PlaybackState {
49
49
  var carriesAdvisoryError: Bool {
50
50
  self == .loading || self == .buffering || self == .paused
51
51
  }
52
+
53
+ var awaitsData: Bool {
54
+ self == .loading || self == .buffering
55
+ }
52
56
  }
@@ -192,8 +192,9 @@ final class Player {
192
192
  if !newValue { engine.pause() } else if state != .loading { engine.play() }
193
193
 
194
194
  guard changed else { return }
195
- // A resume can find the state still .buffering (a pause near the end leaves it), with no watch.
196
- if newValue, state == .buffering { retry.startStallWatch() }
195
+ // A resume can find the state still .buffering (a pause near the end leaves it) or .loading,
196
+ // with no transition to start the watch.
197
+ if newValue, state.awaitsData { retry.startStallWatch() }
197
198
  // Left to run, the retry would give up on the dropped intent and surface .error.
198
199
  if !newValue, retry.pendingTask != nil { parkForReloadOnPlay() }
199
200
  // A pause during the sleep fade ends the timer early, restoring the pre-fade volume.
@@ -262,7 +263,11 @@ final class Player {
262
263
  retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
263
264
  retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
264
265
  retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
265
- retry.bufferedPosition = { [weak self] in self?.engine.bufferedPosition ?? 0 }
266
+ // Until the connect's item is prepared, the engine still holds the item it replaces.
267
+ retry.bufferedPosition = { [weak self] in
268
+ guard let self, connectionItemPrepared else { return 0 }
269
+ return engine.bufferedPosition
270
+ }
266
271
  }
267
272
 
268
273
  /// Shows a failure the retry loop is still working on over the current state: not a
@@ -353,9 +358,10 @@ final class Player {
353
358
  } else if old == .playing {
354
359
  retry.playbackStoppedBeingAudible()
355
360
  }
361
+ // A reload within .loading is no transition: the retry loop watches each connect itself.
356
362
  if new == .buffering, playWhenReady {
357
363
  retry.startStallWatch()
358
- } else if old == .buffering {
364
+ } else if old.awaitsData, !new.awaitsData {
359
365
  retry.stopStallWatch()
360
366
  }
361
367
 
@@ -396,13 +402,14 @@ final class Player {
396
402
 
397
403
  func stop() {
398
404
  // A pending retry would turn the stop into .error, and the next play must start over rather
399
- // than resume where it failed.
405
+ // than resume where it failed. Cancelled first, or the lowered intent parks it for a reload.
400
406
  retry.cancel()
401
407
  load?.reloadOnPlay = false
402
408
  shouldResumeAfterInterruption = false
403
409
  engine.clearTimedMetadata()
404
- transition(.stopped)
410
+ // Before the transition, whose render the formatter reads the intent from.
405
411
  setPlayWhenReady(false)
412
+ transition(.stopped)
406
413
  deferredSeek.reset()
407
414
  if currentTrack?.live != true { seek(to: 0) }
408
415
  }
@@ -633,8 +640,7 @@ final class Player {
633
640
  persistence.save()
634
641
 
635
642
  if let src = currentTrack.src {
636
- retry.connectionStarted()
637
- engine.resolveAndLoad(src: src, track: currentTrack)
643
+ connect(src: src, track: currentTrack)
638
644
  } else {
639
645
  logger.error("No src for track \(currentTrack.path ?? currentTrack.title)")
640
646
  engine.clearItem()
@@ -738,6 +744,13 @@ final class Player {
738
744
  return
739
745
  }
740
746
  prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
747
+ connect(src: src, track: track)
748
+ }
749
+
750
+ private var connectionItemPrepared = false
751
+
752
+ private func connect(src: String, track: Track) {
753
+ connectionItemPrepared = false
741
754
  retry.connectionStarted()
742
755
  engine.resolveAndLoad(src: src, track: track)
743
756
  }
@@ -805,6 +818,7 @@ final class Player {
805
818
  switch event {
806
819
  case let .itemPrepared(likelyToKeepUp):
807
820
  load?.itemPrepared = true
821
+ connectionItemPrepared = true
808
822
  if playWhenReady { engine.play() }
809
823
  if !beginDeferredSeek(), likelyToKeepUp { bufferBecameSufficient() }
810
824
  case let .loadFailed(error):
@@ -832,7 +846,7 @@ final class Player {
832
846
  case .playedToEnd:
833
847
  itemDidPlayToEnd()
834
848
  case .stalled:
835
- // A nudge only: this also arrives while audio plays, so the stall watch keys on .buffering.
849
+ // A nudge only: this also arrives while audio plays, so the stall watch keys on the state.
836
850
  if playWhenReady, state != .error { engine.play() }
837
851
  case let .timedMetadata(metadata):
838
852
  callbacks?.playerDidReceiveTimedMetadata(metadata)
@@ -84,10 +84,11 @@ final class RetryLoop {
84
84
  /// The retry in flight; session release waits while there is one.
85
85
  private(set) var pendingTask: Task<Void, Never>?
86
86
 
87
- /// How long a stall may go without new data before it counts as a failure; longer than AVPlayer
88
- /// takes to fail a stalled item itself, so its error, which says more, is the one usually retried.
87
+ /// How long a connect or a stall may go without new data before it counts as a failure. Longer
88
+ /// than AVPlayer takes to fail a stalled item itself, so its error, which says more, is usually
89
+ /// the one retried; a connect's request can outlast it.
89
90
  var stallTimeout: Duration = .seconds(30)
90
- /// The end of the loaded range; the stall watch reads progress off it.
91
+ /// The end of the current connection's loaded range; the stall watch reads progress off it.
91
92
  var bufferedPosition: () -> Double = { 0 }
92
93
  private(set) var stallTask: Task<Void, Never>?
93
94
 
@@ -145,7 +146,8 @@ final class RetryLoop {
145
146
 
146
147
  /// A connect going out: the Load's first, a reconnect, or a reload by the Player, which ends the
147
148
  /// connection it replaces. A replaced connection counts only if it delivered audio: one cut off
148
- /// while connecting says nothing about the source.
149
+ /// while connecting says nothing about the source. With the play intent up, the stall watch runs
150
+ /// from the start, so a connect that opens and sends nothing is replaced (docs/adr/0014, rule 9).
149
151
  func connectionStarted() {
150
152
  let now = clock.nowMs
151
153
  if let startedAtMs = connectionStartedAtMs, replacedConnectionCounts, connectionDeliveredAudio, !connectionEndReported {
@@ -157,6 +159,7 @@ final class RetryLoop {
157
159
  connectionEndReported = false
158
160
  deadlineArmed = true
159
161
  armDeadline()
162
+ if playIntent { startStallWatch() }
160
163
  }
161
164
 
162
165
  func playIntentChanged(_ up: Bool) {
@@ -181,6 +184,7 @@ final class RetryLoop {
181
184
  /// Audio clears the failure the deadline would report: a silence after it that ends with no
182
185
  /// failure is a stall.
183
186
  func playbackBecameAudible() {
187
+ stopStallWatch()
184
188
  connectionDeliveredAudio = true
185
189
  lastFailure = nil
186
190
  budget.audioStarted(atMs: clock.nowMs)
@@ -304,14 +308,14 @@ final class RetryLoop {
304
308
 
305
309
  // MARK: - Stalls
306
310
 
307
- /// Starts the stall watch: a `stallTimeout` in which `bufferedPosition` does not advance makes
308
- /// the stall a `.stall` failure, provided the play intent holds and no retry is pending; one in
309
- /// which it advances starts another. Any failure ends it.
311
+ /// Starts the stall watch, over a connect or a stall: a `stallTimeout` in which `bufferedPosition`
312
+ /// does not advance makes it a `.stall` failure, provided the play intent holds and no retry is
313
+ /// pending; one in which it advances starts another. Any failure ends it.
310
314
  func startStallWatch() {
311
315
  stallTask?.cancel()
312
316
  let buffered = bufferedPosition()
313
- stallTask = Task { [weak self, stallTimeout] in
314
- try? await Task.sleep(for: stallTimeout)
317
+ stallTask = Task { [weak self, clock, stallTimeout] in
318
+ guard await (try? clock.sleep(ms: Int(stallTimeout / .milliseconds(1)))) != nil else { return }
315
319
  guard let self, !Task.isCancelled else { return }
316
320
  stallTask = nil
317
321
  if bufferedPosition() > buffered { return startStallWatch() }