react-native-audio-browser 0.2.0-next.60 → 0.2.0-next.61
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.
- package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +9 -18
- package/android/src/main/java/com/audiobrowser/player/PlaybackStateStore.kt +4 -9
- package/android/src/main/java/com/audiobrowser/player/Player.kt +2 -2
- package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +4 -1
- package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +8 -0
- package/android/src/test/java/com/audiobrowser/player/PlayerCastTest.kt +22 -0
- package/android/src/test/java/com/audiobrowser/player/PlayerDestroyTest.kt +48 -0
- package/android/src/test/java/com/audiobrowser/player/PlayerSleepTimerTest.kt +38 -0
- package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +7 -1
- package/ios/PlaybackEvent.swift +2 -0
- package/ios/Player/ErrorStatus.swift +3 -2
- package/ios/Player/PlaybackStateMachine.swift +3 -0
- package/ios/Player/Player.swift +34 -15
- package/ios/Player/RetryLoop.swift +0 -6
- package/ios/Tests/PlayerPolicyTests.swift +17 -0
- package/ios/Tests/PlayerTests.swift +139 -0
- package/ios/Tests/Support/TestTypes.swift +4 -4
- package/package.json +1 -1
|
@@ -91,11 +91,9 @@ import com.margelo.nitro.core.NullType
|
|
|
91
91
|
import com.margelo.nitro.core.Promise
|
|
92
92
|
import java.util.concurrent.TimeUnit
|
|
93
93
|
import java.util.concurrent.atomic.AtomicReference
|
|
94
|
-
import kotlin.coroutines.resume
|
|
95
|
-
import kotlin.coroutines.resumeWithException
|
|
96
|
-
import kotlin.coroutines.suspendCoroutine
|
|
97
94
|
import kotlin.time.Duration.Companion.seconds
|
|
98
95
|
import kotlinx.coroutines.CancellationException
|
|
96
|
+
import kotlinx.coroutines.CompletableDeferred
|
|
99
97
|
import kotlinx.coroutines.CoroutineScope
|
|
100
98
|
import kotlinx.coroutines.Job
|
|
101
99
|
import kotlinx.coroutines.MainScope
|
|
@@ -151,7 +149,6 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
|
|
|
151
149
|
// connected list, holding a binder and a listener.
|
|
152
150
|
mediaBrowserFuture?.let { MediaBrowser.releaseFuture(it) }
|
|
153
151
|
mediaBrowserFuture = null
|
|
154
|
-
setupPromise = null
|
|
155
152
|
|
|
156
153
|
serviceBinding.unbind(this)
|
|
157
154
|
|
|
@@ -232,7 +229,9 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
|
|
|
232
229
|
private val onBatteryWarningPending: (Boolean) -> Unit = { pending ->
|
|
233
230
|
post { onBatteryWarningPendingChanged(BatteryWarningPendingChangedEvent(pending)) }
|
|
234
231
|
}
|
|
235
|
-
|
|
232
|
+
// Every setupPlayer waiting for the service awaits it. Replaced on disconnect, after
|
|
233
|
+
// cancelChildren has rejected its waiters.
|
|
234
|
+
private var connectionReady = CompletableDeferred<Unit>()
|
|
236
235
|
|
|
237
236
|
// Staged by setup options or by setters called before the player exists; last write wins, and
|
|
238
237
|
// [applyPendingPlayerState] consumes them.
|
|
@@ -792,18 +791,10 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
|
|
|
792
791
|
return@async
|
|
793
792
|
}
|
|
794
793
|
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
val bound = serviceBinding.bind(Intent(context, Service::class.java), this@AudioBrowser)
|
|
798
|
-
|
|
799
|
-
if (!bound) {
|
|
800
|
-
continuation.resumeWithException(
|
|
801
|
-
RuntimeException("Failed to bind to AudioBrowserService")
|
|
802
|
-
)
|
|
803
|
-
} else {
|
|
804
|
-
setupPromise = { continuation.resume(Unit) }
|
|
805
|
-
}
|
|
794
|
+
if (!serviceBinding.bind(Intent(context, Service::class.java), this@AudioBrowser)) {
|
|
795
|
+
throw RuntimeException("Failed to bind to AudioBrowserService")
|
|
806
796
|
}
|
|
797
|
+
connectionReady.await()
|
|
807
798
|
}
|
|
808
799
|
}
|
|
809
800
|
|
|
@@ -1150,8 +1141,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
|
|
|
1150
1141
|
val sessionToken = SessionToken(context, ComponentName(context, Service::class.java))
|
|
1151
1142
|
mediaBrowserFuture = MediaBrowser.Builder(context, sessionToken).buildAsync()
|
|
1152
1143
|
|
|
1153
|
-
|
|
1154
|
-
setupPromise = null
|
|
1144
|
+
connectionReady.complete(Unit)
|
|
1155
1145
|
}
|
|
1156
1146
|
}
|
|
1157
1147
|
|
|
@@ -1171,6 +1161,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
|
|
|
1171
1161
|
mainScope.coroutineContext.cancelChildren()
|
|
1172
1162
|
mediaBrowserFuture = null
|
|
1173
1163
|
connectedService = null
|
|
1164
|
+
connectionReady = CompletableDeferred()
|
|
1174
1165
|
Timber.d("AudioBrowser.onServiceDisconnected()")
|
|
1175
1166
|
}
|
|
1176
1167
|
|
|
@@ -76,8 +76,7 @@ class PlaybackStateStore(private val player: Player) {
|
|
|
76
76
|
|
|
77
77
|
/** Restarts the interval, so a [save] on track change is not followed by an immediate repeat. */
|
|
78
78
|
fun resetPeriodicSave() {
|
|
79
|
-
|
|
80
|
-
periodicSaveJob = null
|
|
79
|
+
cancelPeriodicSave()
|
|
81
80
|
launchPeriodicSave()
|
|
82
81
|
}
|
|
83
82
|
|
|
@@ -92,11 +91,7 @@ class PlaybackStateStore(private val player: Player) {
|
|
|
92
91
|
}
|
|
93
92
|
}
|
|
94
93
|
|
|
95
|
-
|
|
96
|
-
* Stops the periodic save without a final save, for engine teardown: a save against the released
|
|
97
|
-
* player would persist position 0 over the real one.
|
|
98
|
-
*/
|
|
99
|
-
fun cancelPeriodicSave() {
|
|
94
|
+
private fun cancelPeriodicSave() {
|
|
100
95
|
periodicSaveJob?.cancel()
|
|
101
96
|
periodicSaveJob = null
|
|
102
97
|
}
|
|
@@ -104,8 +99,8 @@ class PlaybackStateStore(private val player: Player) {
|
|
|
104
99
|
/** Stops the periodic save and calls [save] once more. */
|
|
105
100
|
fun stopPeriodicSave() {
|
|
106
101
|
cancelPeriodicSave()
|
|
107
|
-
// After a natural end, setPlaybackState(ENDED) has saved position 0
|
|
108
|
-
//
|
|
102
|
+
// After a natural end, setPlaybackState(ENDED) has saved position 0; a save here, from the
|
|
103
|
+
// dropped intent or a teardown, would make resumption start at the end of the track.
|
|
109
104
|
if (player.playbackState != PlaybackState.ENDED) {
|
|
110
105
|
save()
|
|
111
106
|
}
|
|
@@ -949,8 +949,8 @@ internal constructor(
|
|
|
949
949
|
}
|
|
950
950
|
|
|
951
951
|
fun destroy() {
|
|
952
|
-
//
|
|
953
|
-
playbackStateStore.
|
|
952
|
+
// stop() saves only if playing; before it, so its STOPPED doesn't defeat the ENDED guard.
|
|
953
|
+
playbackStateStore.stopPeriodicSave()
|
|
954
954
|
// An armed timer would fire pause() into the released player. Cleared before the release,
|
|
955
955
|
// while a mid-ramp fade can still restore the volume.
|
|
956
956
|
sleepTimer.clear()
|
|
@@ -83,7 +83,10 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
83
83
|
)
|
|
84
84
|
player.callbacks?.onPlaybackActiveTrackChanged(event)
|
|
85
85
|
|
|
86
|
-
if (
|
|
86
|
+
if (
|
|
87
|
+
reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_AUTO ||
|
|
88
|
+
reason == MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_REPEAT
|
|
89
|
+
) {
|
|
87
90
|
player.sleepTimer.onTrackEnd()
|
|
88
91
|
}
|
|
89
92
|
|
|
@@ -54,6 +54,9 @@ internal class RemoteSwitchingPlayer(
|
|
|
54
54
|
private var repeat = MediaPlayer.REPEAT_MODE_OFF
|
|
55
55
|
private var shuffle = false
|
|
56
56
|
|
|
57
|
+
/** Set as the receiver moves on at an item's end; the next [getState] reports it as automatic. */
|
|
58
|
+
private var pendingAutoTransition = false
|
|
59
|
+
|
|
57
60
|
private sealed interface Route {
|
|
58
61
|
data object Local : Route
|
|
59
62
|
|
|
@@ -393,6 +396,7 @@ internal class RemoteSwitchingPlayer(
|
|
|
393
396
|
val duration = remote.receiver.duration
|
|
394
397
|
remote.load = Load.Ended(if (duration == C.TIME_UNSET) positionOn(remote) else duration)
|
|
395
398
|
} else {
|
|
399
|
+
pendingAutoTransition = true
|
|
396
400
|
queue.moveTo(next)
|
|
397
401
|
load(remote, C.TIME_UNSET)
|
|
398
402
|
}
|
|
@@ -459,6 +463,10 @@ internal class RemoteSwitchingPlayer(
|
|
|
459
463
|
is Load.Playing -> if (!holds) setPlaybackState(STATE_IDLE).setContentPositionMs(0)
|
|
460
464
|
}
|
|
461
465
|
if (queue.isEmpty) setPlaybackState(STATE_IDLE)
|
|
466
|
+
if (pendingAutoTransition) {
|
|
467
|
+
pendingAutoTransition = false
|
|
468
|
+
setPositionDiscontinuity(DISCONTINUITY_REASON_AUTO_TRANSITION, 0)
|
|
469
|
+
}
|
|
462
470
|
}
|
|
463
471
|
.build()
|
|
464
472
|
}
|
|
@@ -133,6 +133,28 @@ class PlayerCastTest {
|
|
|
133
133
|
assertEquals(10, receiver.volume)
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
+
@Test
|
|
137
|
+
fun `the end-of-track sleep pauses when the receiver ends a track short of its duration`() {
|
|
138
|
+
player.setQueue(
|
|
139
|
+
arrayOf(
|
|
140
|
+
TestFixtures.track(title = "b", src = "https://s/b.mp3"),
|
|
141
|
+
TestFixtures.track(title = "c", src = "https://s/c.mp3"),
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
idleUntil("the first item on the receiver") { receiver.loads.size == 2 }
|
|
145
|
+
receiver.durationMs = 180_000
|
|
146
|
+
receiver.positionMs = 179_000
|
|
147
|
+
receiver.update()
|
|
148
|
+
idle()
|
|
149
|
+
player.sleepTimer.setEndOfTrack()
|
|
150
|
+
|
|
151
|
+
remote.end()
|
|
152
|
+
idleUntil("the next item on the receiver") { receiver.loads.size == 3 }
|
|
153
|
+
|
|
154
|
+
assertTrue(player.sleepTimer.get().isFirst)
|
|
155
|
+
assertFalse(receiver.loads.last().autoplay)
|
|
156
|
+
}
|
|
157
|
+
|
|
136
158
|
private fun calls(name: String) =
|
|
137
159
|
mockingDetails(callbacks).invocations.filter { it.method.name == name }
|
|
138
160
|
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import com.audiobrowser.TestFixtures
|
|
4
|
+
import com.audiobrowser.model.PlayerSetupOptions
|
|
5
|
+
import com.audiobrowser.util.TrackFactory
|
|
6
|
+
import com.margelo.nitro.audiobrowser.PlaybackState
|
|
7
|
+
import org.junit.Assert.assertEquals
|
|
8
|
+
import org.junit.Before
|
|
9
|
+
import org.junit.Test
|
|
10
|
+
import org.junit.runner.RunWith
|
|
11
|
+
import org.robolectric.RobolectricTestRunner
|
|
12
|
+
import org.robolectric.RuntimeEnvironment
|
|
13
|
+
|
|
14
|
+
@RunWith(RobolectricTestRunner::class)
|
|
15
|
+
class PlayerDestroyTest {
|
|
16
|
+
|
|
17
|
+
private val player = Player(RuntimeEnvironment.getApplication())
|
|
18
|
+
|
|
19
|
+
@Before
|
|
20
|
+
fun load() {
|
|
21
|
+
player.setup(PlayerSetupOptions())
|
|
22
|
+
player.sessionPlayer.setMediaItems(
|
|
23
|
+
listOf(TrackFactory.toMedia3(TestFixtures.track(title = "a", src = "https://s/a.mp3"))),
|
|
24
|
+
0,
|
|
25
|
+
5_000,
|
|
26
|
+
)
|
|
27
|
+
player.sessionPlayer.prepare()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
@Test
|
|
31
|
+
fun destroySavesASeekMadeWhileNotPlaying() {
|
|
32
|
+
player.sessionPlayer.seekTo(8_000)
|
|
33
|
+
|
|
34
|
+
player.destroy()
|
|
35
|
+
|
|
36
|
+
assertEquals(8_000L, player.playbackStateStore.get()?.positionMs)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
@Test
|
|
40
|
+
fun destroyAfterTheQueueEndedKeepsPositionZero() {
|
|
41
|
+
player.playWhenReady = true
|
|
42
|
+
player.setPlaybackState(PlaybackState.ENDED)
|
|
43
|
+
|
|
44
|
+
player.destroy()
|
|
45
|
+
|
|
46
|
+
assertEquals(0L, player.playbackStateStore.get()?.positionMs)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import androidx.media3.common.Player as MediaPlayer
|
|
4
|
+
import com.audiobrowser.TestFixtures
|
|
5
|
+
import com.audiobrowser.model.PlayerSetupOptions
|
|
6
|
+
import com.audiobrowser.util.TrackFactory
|
|
7
|
+
import org.junit.After
|
|
8
|
+
import org.junit.Assert.assertFalse
|
|
9
|
+
import org.junit.Assert.assertTrue
|
|
10
|
+
import org.junit.Test
|
|
11
|
+
import org.junit.runner.RunWith
|
|
12
|
+
import org.robolectric.RobolectricTestRunner
|
|
13
|
+
import org.robolectric.RuntimeEnvironment
|
|
14
|
+
|
|
15
|
+
@RunWith(RobolectricTestRunner::class)
|
|
16
|
+
class PlayerSleepTimerTest {
|
|
17
|
+
|
|
18
|
+
private val player = Player(RuntimeEnvironment.getApplication())
|
|
19
|
+
|
|
20
|
+
@After fun release() = player.exoPlayer.release()
|
|
21
|
+
|
|
22
|
+
@Test
|
|
23
|
+
fun `the end-of-track sleep pauses a repeating track when it loops`() {
|
|
24
|
+
player.setup(PlayerSetupOptions())
|
|
25
|
+
val item = TrackFactory.toMedia3(TestFixtures.track())
|
|
26
|
+
player.sessionPlayer.setMediaItems(listOf(item))
|
|
27
|
+
player.playWhenReady = true
|
|
28
|
+
player.sleepTimer.setEndOfTrack()
|
|
29
|
+
|
|
30
|
+
player.playerListener.onMediaItemTransition(
|
|
31
|
+
item,
|
|
32
|
+
MediaPlayer.MEDIA_ITEM_TRANSITION_REASON_REPEAT,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
assertFalse(player.playWhenReady)
|
|
36
|
+
assertTrue(player.sleepTimer.get().isFirst)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -9,6 +9,7 @@ import androidx.media3.common.PlaybackParameters
|
|
|
9
9
|
import androidx.media3.common.Player as MediaPlayer
|
|
10
10
|
import androidx.media3.common.SimpleBasePlayer
|
|
11
11
|
import androidx.media3.common.TrackSelectionParameters
|
|
12
|
+
import androidx.media3.common.util.Util
|
|
12
13
|
import com.google.common.util.concurrent.Futures
|
|
13
14
|
import com.google.common.util.concurrent.ListenableFuture
|
|
14
15
|
|
|
@@ -125,6 +126,7 @@ internal data class SentLoad(val item: MediaItem, val positionMs: Long, val auto
|
|
|
125
126
|
internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
126
127
|
var item: MediaItem? = null
|
|
127
128
|
var positionMs = 0L
|
|
129
|
+
var durationMs = C.TIME_UNSET
|
|
128
130
|
var intent = false
|
|
129
131
|
var readiness = STATE_IDLE
|
|
130
132
|
var volume = 10
|
|
@@ -156,7 +158,11 @@ internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
156
158
|
override fun getState(): State =
|
|
157
159
|
State.Builder()
|
|
158
160
|
.setAvailableCommands(MediaPlayer.Commands.Builder().addAllCommands().build())
|
|
159
|
-
.setPlaylist(
|
|
161
|
+
.setPlaylist(
|
|
162
|
+
listOfNotNull(item).map {
|
|
163
|
+
MediaItemData.Builder(uid).setMediaItem(it).setDurationUs(Util.msToUs(durationMs)).build()
|
|
164
|
+
}
|
|
165
|
+
)
|
|
160
166
|
.setCurrentMediaItemIndex(if (item == null) C.INDEX_UNSET else 0)
|
|
161
167
|
.setContentPositionMs(positionMs)
|
|
162
168
|
.setPlayWhenReady(intent, PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST)
|
package/ios/PlaybackEvent.swift
CHANGED
|
@@ -27,12 +27,13 @@ enum ErrorStatus: Equatable {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/// The status once `event` moves the state from `old` to `new`: an error event is a new
|
|
30
|
-
/// terminal report; leaving `.error` clears it, and so does a
|
|
31
|
-
/// that carries no advisory error.
|
|
30
|
+
/// terminal report; leaving `.error` clears it, and so does a cancelled retry or a retrying
|
|
31
|
+
/// error reaching a state that carries no advisory error.
|
|
32
32
|
func after(event: PlaybackEvent, from old: PlaybackState, to new: PlaybackState) -> ErrorStatus {
|
|
33
33
|
if case let .errorOccurred(error) = event {
|
|
34
34
|
return .terminal(error, report: terminalReport &+ 1)
|
|
35
35
|
}
|
|
36
|
+
if case .retryCancelled = event { return .none }
|
|
36
37
|
if old == .error || (isRetrying && !new.carriesAdvisoryError) { return .none }
|
|
37
38
|
return self
|
|
38
39
|
}
|
|
@@ -12,6 +12,9 @@ func nextPlaybackState(from current: PlaybackState, on event: PlaybackEvent) ->
|
|
|
12
12
|
case .avPlayerPlaying: return .playing
|
|
13
13
|
case .audioFrameDecoded: return .playing
|
|
14
14
|
case .errorOccurred: return .error
|
|
15
|
+
case .retryCancelled:
|
|
16
|
+
guard current != .stopped, current != .ended, current != .error else { return nil }
|
|
17
|
+
return .paused
|
|
15
18
|
case .loadSeekCompleted:
|
|
16
19
|
guard current == .loading else { return nil }
|
|
17
20
|
return .ready
|
package/ios/Player/Player.swift
CHANGED
|
@@ -55,6 +55,8 @@ final class Player {
|
|
|
55
55
|
var primedNowPlaying = false
|
|
56
56
|
/// One of this load's items is in the engine; until then it reports the previous one's position.
|
|
57
57
|
var itemPrepared = false
|
|
58
|
+
/// A pause cancelled this load's retry, leaving the failed item for the next play to replace.
|
|
59
|
+
var reloadOnPlay = false
|
|
58
60
|
|
|
59
61
|
mutating func claimNowPlayingPrime() -> Bool {
|
|
60
62
|
guard !primedNowPlaying else { return false }
|
|
@@ -105,10 +107,16 @@ final class Player {
|
|
|
105
107
|
}
|
|
106
108
|
}
|
|
107
109
|
|
|
110
|
+
/// Whether the engine's item is not this Load's playable one: one loads, or a pause cancelled
|
|
111
|
+
/// the retry that was to replace a failed one. A seek waits for the next item meanwhile.
|
|
112
|
+
private var awaitingItem: Bool {
|
|
113
|
+
state == .loading || load?.reloadOnPlay == true
|
|
114
|
+
}
|
|
115
|
+
|
|
108
116
|
/// Whether the engine reports this Load's position: not before one of its items is prepared,
|
|
109
|
-
/// nor while one
|
|
117
|
+
/// nor while it awaits the next one.
|
|
110
118
|
private var enginePositionIsCurrent: Bool {
|
|
111
|
-
|
|
119
|
+
!awaitingItem && load?.itemPrepared == true
|
|
112
120
|
}
|
|
113
121
|
|
|
114
122
|
private var resumePosition: TimeInterval? {
|
|
@@ -169,16 +177,24 @@ final class Player {
|
|
|
169
177
|
// A play during an interruption owns the intent: a later pause must not be auto-resumed.
|
|
170
178
|
if newValue { shouldResumeAfterInterruption = false }
|
|
171
179
|
|
|
172
|
-
// A terminal state has no item to play, or one parked at its end: reload,
|
|
173
|
-
// that may have expired since. Only .error
|
|
174
|
-
|
|
175
|
-
|
|
180
|
+
// A terminal state or a cancelled retry has no item to play, or one parked at its end: reload,
|
|
181
|
+
// re-resolving a URL that may have expired since. Only .error and a cancelled retry resume where they failed.
|
|
182
|
+
let resumes = state == .error || load?.reloadOnPlay == true
|
|
183
|
+
if newValue, resumes || state == .stopped || state == .ended {
|
|
184
|
+
reloadResolving(startFromCurrentTime: resumes)
|
|
176
185
|
}
|
|
177
186
|
if state != .loading {
|
|
178
187
|
if newValue { engine.play() } else { engine.pause() }
|
|
179
188
|
}
|
|
180
189
|
|
|
181
190
|
guard changed else { return }
|
|
191
|
+
// Left to run, the retry would give up on the dropped intent and surface .error.
|
|
192
|
+
if !newValue, retry.pendingTask != nil {
|
|
193
|
+
retry.reset()
|
|
194
|
+
if let position = resumePosition { deferredSeek.capture(position) }
|
|
195
|
+
load?.reloadOnPlay = true
|
|
196
|
+
transition(.retryCancelled)
|
|
197
|
+
}
|
|
182
198
|
// A pause during the sleep fade ends the timer early, restoring the pre-fade volume.
|
|
183
199
|
if !newValue, sleepTimerManager.isFading { sleepTimerManager.clear() }
|
|
184
200
|
publish()
|
|
@@ -361,8 +377,10 @@ final class Player {
|
|
|
361
377
|
}
|
|
362
378
|
|
|
363
379
|
func stop() {
|
|
364
|
-
//
|
|
380
|
+
// A pending retry would turn the stop into .error, and the next play must start over rather
|
|
381
|
+
// than resume where it failed.
|
|
365
382
|
retry.cancel()
|
|
383
|
+
load?.reloadOnPlay = false
|
|
366
384
|
shouldResumeAfterInterruption = false
|
|
367
385
|
transition(.stopped)
|
|
368
386
|
setPlayWhenReady(false)
|
|
@@ -384,7 +402,7 @@ final class Player {
|
|
|
384
402
|
// A nested interruption keeps the intent the first one captured.
|
|
385
403
|
shouldResumeAfterInterruption = shouldResumeAfterInterruption || playWhenReady
|
|
386
404
|
pause()
|
|
387
|
-
if playbackActive, state != .loading {
|
|
405
|
+
if playbackActive, state != .loading, state != .paused {
|
|
388
406
|
transition(.avPlayerPaused(hasAsset: engine.hasLoadedAsset))
|
|
389
407
|
}
|
|
390
408
|
}
|
|
@@ -620,10 +638,11 @@ final class Player {
|
|
|
620
638
|
|
|
621
639
|
// MARK: - Seeking
|
|
622
640
|
|
|
623
|
-
/// Seeks the current item. While
|
|
624
|
-
/// ready transition waits for it (`DeferredSeek`); `completion` then reports false
|
|
641
|
+
/// Seeks the current item. While it awaits the next item, the target is held until that one is
|
|
642
|
+
/// ready and the ready transition waits for it (`DeferredSeek`); `completion` then reports false
|
|
643
|
+
/// at once.
|
|
625
644
|
func seek(to seconds: TimeInterval, completion: @escaping @MainActor (Bool) -> Void = { _ in }) {
|
|
626
|
-
if
|
|
645
|
+
if awaitingItem {
|
|
627
646
|
deferredSeek.capture(seconds)
|
|
628
647
|
completion(false)
|
|
629
648
|
} else if engine.hasItem {
|
|
@@ -634,7 +653,7 @@ final class Player {
|
|
|
634
653
|
}
|
|
635
654
|
|
|
636
655
|
func seek(by offset: TimeInterval) {
|
|
637
|
-
if
|
|
656
|
+
if awaitingItem {
|
|
638
657
|
seek(to: (deferredSeek.target ?? 0) + offset)
|
|
639
658
|
} else if engine.hasItem {
|
|
640
659
|
seek(to: engine.currentTime + offset)
|
|
@@ -703,6 +722,7 @@ final class Player {
|
|
|
703
722
|
/// never get here in .error, since the retry loop keeps the state non-terminal. `time` is held
|
|
704
723
|
/// as the deferred seek before the loading transition saves the snapshot.
|
|
705
724
|
private func prepareForReload(resumingAt time: TimeInterval?) {
|
|
725
|
+
load?.reloadOnPlay = false
|
|
706
726
|
if state == .error {
|
|
707
727
|
beginLoad()
|
|
708
728
|
clearItem()
|
|
@@ -861,11 +881,10 @@ final class Player {
|
|
|
861
881
|
/// connectivity returns re-establishes a stalled stream. AVPlayer doesn't reliably report a
|
|
862
882
|
/// live stream's mid-stream drop as a failure: it waits with no error, so the retry loop never
|
|
863
883
|
/// engages. Only while stalled (.buffering) with play intent, so a pause or a retry that gave up
|
|
864
|
-
/// isn't resumed; and not while
|
|
865
|
-
/// that reload.
|
|
884
|
+
/// isn't resumed; and not while a retry is pending, which owns that reload.
|
|
866
885
|
func networkStatusDidChange(isOnline: Bool) {
|
|
867
886
|
engine.renderNowPlaying()
|
|
868
|
-
guard isOnline, playWhenReady, state == .buffering,
|
|
887
|
+
guard isOnline, playWhenReady, state == .buffering, retry.pendingTask == nil else { return }
|
|
869
888
|
logger.info("Connectivity restored while stalled — re-resolving to reconnect")
|
|
870
889
|
reloadResolving(startFromCurrentTime: true)
|
|
871
890
|
}
|
|
@@ -78,9 +78,6 @@ final class RetryLoop {
|
|
|
78
78
|
|
|
79
79
|
/// The retry in flight; session release waits while there is one.
|
|
80
80
|
private(set) var pendingTask: Task<Void, Never>?
|
|
81
|
-
/// True only while a scheduled retry waits for connectivity, so a stall-driven reconnect can
|
|
82
|
-
/// defer to it rather than load twice.
|
|
83
|
-
private(set) var isWaitingForNetwork = false
|
|
84
81
|
private(set) var attempts = 0
|
|
85
82
|
|
|
86
83
|
/// Continuous audible playback after which the budgets refill (Android's HEALTHY_PLAYBACK_MS).
|
|
@@ -171,7 +168,6 @@ final class RetryLoop {
|
|
|
171
168
|
attempts = 0
|
|
172
169
|
firstRetryTime = nil
|
|
173
170
|
firstOnlineRetryTime = nil
|
|
174
|
-
isWaitingForNetwork = false
|
|
175
171
|
}
|
|
176
172
|
|
|
177
173
|
// MARK: - Healthy Playback
|
|
@@ -269,8 +265,6 @@ final class RetryLoop {
|
|
|
269
265
|
}
|
|
270
266
|
|
|
271
267
|
private func waitForNetworkRestored(monitor: any NetworkStatusProviding) async -> Bool {
|
|
272
|
-
isWaitingForNetwork = true
|
|
273
|
-
defer { isWaitingForNetwork = false }
|
|
274
268
|
while !monitor.isOnline {
|
|
275
269
|
guard await (try? sleep(0.5)) != nil else { return false }
|
|
276
270
|
}
|
|
@@ -185,6 +185,23 @@ struct PlayerRecoveringTests {
|
|
|
185
185
|
#expect(engine.resolveAndLoadCalls.count == 1)
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
+
@Test func theNetworkReturningDuringABackoffLeavesTheReloadToTheRetry() async throws {
|
|
189
|
+
let engine = MockPlayerEngine()
|
|
190
|
+
let player = makePlayer(engine: engine, retry: makeRetryLoop(delay: 0.05), retries: nil)
|
|
191
|
+
try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")])
|
|
192
|
+
player.play()
|
|
193
|
+
player.transition(.avPlayerWaiting)
|
|
194
|
+
engine.emit(.failed(URLError(.timedOut), httpStatusCode: nil))
|
|
195
|
+
let retrying = player.retry.pendingTask
|
|
196
|
+
let loadsBefore = engine.resolveAndLoadCalls.count
|
|
197
|
+
|
|
198
|
+
player.networkStatusDidChange(isOnline: true)
|
|
199
|
+
await retrying?.value
|
|
200
|
+
|
|
201
|
+
#expect(player.state == .loading)
|
|
202
|
+
#expect(engine.resolveAndLoadCalls.count == loadsBefore + 1)
|
|
203
|
+
}
|
|
204
|
+
|
|
188
205
|
@Test func theNetworkGoingReRendersTheStallLineWithoutReconnecting() throws {
|
|
189
206
|
let (player, engine, _) = try makePlaying()
|
|
190
207
|
player.transition(.avPlayerWaiting)
|
|
@@ -198,6 +198,132 @@ struct RetryingErrorTests {
|
|
|
198
198
|
#expect(cb.playbackChanges.last?.error?.retrying == nil)
|
|
199
199
|
#expect(cb.errorEvents.count == 1)
|
|
200
200
|
}
|
|
201
|
+
|
|
202
|
+
/// The listener chose to pause, so the retry the pause stops is no failure; the next play
|
|
203
|
+
/// reloads where it failed, since the item it would have replaced is dead.
|
|
204
|
+
@Test @MainActor
|
|
205
|
+
func pauseDuringRetry_staysQuietAndReloadsOnPlay() async throws {
|
|
206
|
+
let (c, eh, cb) = try makePlayingWithRetries()
|
|
207
|
+
eh.resumePosition = 42
|
|
208
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
209
|
+
let retrying = c.retry.pendingTask
|
|
210
|
+
|
|
211
|
+
c.pause()
|
|
212
|
+
await retrying?.value
|
|
213
|
+
|
|
214
|
+
#expect(c.state != .error)
|
|
215
|
+
#expect(cb.errorEvents.isEmpty)
|
|
216
|
+
#expect(eh.resolveAndLoadCalls.isEmpty)
|
|
217
|
+
|
|
218
|
+
c.play()
|
|
219
|
+
|
|
220
|
+
#expect(eh.resolveAndLoadCalls.count == 1)
|
|
221
|
+
#expect(c.deferredSeek.target == 42)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
@Test @MainActor
|
|
225
|
+
func pauseDuringRetry_whileBuffering_reportsPausedWithoutTheRetryingError() throws {
|
|
226
|
+
let (c, eh, cb) = try makePlayingWithRetries()
|
|
227
|
+
c.transition(.avPlayerWaiting)
|
|
228
|
+
eh.emit(.failed(URLError(.cannotConnectToHost), httpStatusCode: nil))
|
|
229
|
+
#expect(cb.playbackChanges.last?.error?.retrying == true)
|
|
230
|
+
|
|
231
|
+
c.pause()
|
|
232
|
+
|
|
233
|
+
#expect(cb.playbackChanges.last?.state == .paused)
|
|
234
|
+
#expect(cb.playbackChanges.last?.error == nil)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
@Test @MainActor
|
|
238
|
+
func pauseDuringRetry_whileLoading_reportsPausedWithoutTheRetryingError() throws {
|
|
239
|
+
let (c, eh, cb) = try makePlayingWithRetries()
|
|
240
|
+
c.reloadResolving(startFromCurrentTime: false)
|
|
241
|
+
eh.emit(.loadFailed(URLError(.cannotConnectToHost)))
|
|
242
|
+
#expect(cb.playbackChanges.last?.state == .loading)
|
|
243
|
+
#expect(cb.playbackChanges.last?.error?.retrying == true)
|
|
244
|
+
|
|
245
|
+
c.pause()
|
|
246
|
+
|
|
247
|
+
#expect(cb.playbackChanges.last?.state == .paused)
|
|
248
|
+
#expect(cb.playbackChanges.last?.error == nil)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
@Test @MainActor
|
|
252
|
+
func interruptionDuringALoadRetry_reportsPaused() throws {
|
|
253
|
+
let (c, eh, cb) = try makePlayingWithRetries()
|
|
254
|
+
c.reloadResolving(startFromCurrentTime: false)
|
|
255
|
+
eh.hasLoadedAsset = false
|
|
256
|
+
eh.emit(.loadFailed(URLError(.cannotConnectToHost)))
|
|
257
|
+
|
|
258
|
+
c.handleInterruptionBegan()
|
|
259
|
+
|
|
260
|
+
#expect(cb.playbackChanges.last?.state == .paused)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/// The failed item can't seek, so a seek waits for the reload, as one does while loading.
|
|
264
|
+
@Test @MainActor
|
|
265
|
+
func seekAfterPauseDuringRetry_landsOnTheReload() throws {
|
|
266
|
+
let (c, eh, _) = try makePlayingWithRetries()
|
|
267
|
+
eh.resumePosition = 42
|
|
268
|
+
eh.currentTime = 42
|
|
269
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
270
|
+
c.pause()
|
|
271
|
+
|
|
272
|
+
c.seek(by: 10)
|
|
273
|
+
#expect(c.deferredSeek.target == 52)
|
|
274
|
+
c.seek(to: 100)
|
|
275
|
+
c.play()
|
|
276
|
+
|
|
277
|
+
#expect(eh.seekCalls.isEmpty)
|
|
278
|
+
#expect(c.deferredSeek.target == 100)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
@Test @MainActor
|
|
282
|
+
func pauseDuringRetry_refillsTheBudgets() async throws {
|
|
283
|
+
let (c, _, cb) = try makePlayingWithRetries()
|
|
284
|
+
c.retry.updatePolicy(from: .second(RetryConfig(
|
|
285
|
+
maxRetries: 1, maxRetryDurationMs: nil, firstConnectMaxRetryDurationMs: nil,
|
|
286
|
+
)))
|
|
287
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
288
|
+
await c.retry.pendingTask?.value
|
|
289
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
290
|
+
|
|
291
|
+
c.pause()
|
|
292
|
+
c.play()
|
|
293
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
294
|
+
await c.retry.pendingTask?.value
|
|
295
|
+
|
|
296
|
+
#expect(c.state != .error)
|
|
297
|
+
#expect(cb.errorEvents.isEmpty)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
@Test @MainActor
|
|
301
|
+
func pauseDuringRetry_thenStop_playsFromTheStart() throws {
|
|
302
|
+
let (c, eh, _) = try makePlayingWithRetries()
|
|
303
|
+
eh.resumePosition = 42
|
|
304
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
305
|
+
|
|
306
|
+
c.pause()
|
|
307
|
+
c.stop()
|
|
308
|
+
c.play()
|
|
309
|
+
|
|
310
|
+
#expect(eh.resolveAndLoadCalls.count == 1)
|
|
311
|
+
#expect(c.deferredSeek.target ?? 0 == 0)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/// Playing a track whose retries follow the play intent and back off long enough to pause in.
|
|
316
|
+
@MainActor
|
|
317
|
+
private func makePlayingWithRetries() throws -> (Player, MockPlayerEngine, MockPlayerCallbacks) {
|
|
318
|
+
let engine = MockPlayerEngine()
|
|
319
|
+
let player = makePlayer(engine: engine, retry: makeRetryLoop(delay: 0.05), retries: nil)
|
|
320
|
+
let callbacks = MockPlayerCallbacks()
|
|
321
|
+
player.callbacks = callbacks
|
|
322
|
+
try startPlaying(player, engine)
|
|
323
|
+
// The engine's position counts only once an item is prepared.
|
|
324
|
+
engine.emit(.itemPrepared(likelyToKeepUp: false))
|
|
325
|
+
engine.resolveAndLoadCalls.removeAll()
|
|
326
|
+
return (player, engine, callbacks)
|
|
201
327
|
}
|
|
202
328
|
|
|
203
329
|
// MARK: - emitStateChange
|
|
@@ -1281,6 +1407,19 @@ struct SessionReleaseTests {
|
|
|
1281
1407
|
c.handleInterruptionEnded(shouldResume: false)
|
|
1282
1408
|
#expect(eh.scheduleAudioSessionReleaseCount == 1)
|
|
1283
1409
|
}
|
|
1410
|
+
|
|
1411
|
+
@Test @MainActor
|
|
1412
|
+
func pauseDuringRetry_requestsRelease() async throws {
|
|
1413
|
+
let (c, eh, _) = try makePlayingWithRetries()
|
|
1414
|
+
c.retry.handleError(URLError(.cannotConnectToHost), context: .playback)
|
|
1415
|
+
let retrying = c.retry.pendingTask
|
|
1416
|
+
eh.scheduleAudioSessionReleaseCount = 0
|
|
1417
|
+
|
|
1418
|
+
c.pause()
|
|
1419
|
+
await retrying?.value
|
|
1420
|
+
|
|
1421
|
+
#expect(eh.scheduleAudioSessionReleaseCount == 1)
|
|
1422
|
+
}
|
|
1284
1423
|
}
|
|
1285
1424
|
|
|
1286
1425
|
// MARK: - Media-stack effects of a publish
|
|
@@ -143,13 +143,13 @@ final class MockPlayerEngine: PlayerEngine {
|
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
/// A Player whose retries reload while `retries` and otherwise give up,
|
|
147
|
-
/// test-only defaults suite.
|
|
146
|
+
/// A Player whose retries reload while `retries` and otherwise give up, or follow the play intent
|
|
147
|
+
/// when `retries` is nil, persisting to a test-only defaults suite.
|
|
148
148
|
@MainActor
|
|
149
149
|
func makePlayer(
|
|
150
150
|
engine: MockPlayerEngine = MockPlayerEngine(),
|
|
151
151
|
retry: RetryLoop = makeRetryLoop(),
|
|
152
|
-
retries: Bool = true,
|
|
152
|
+
retries: Bool? = true,
|
|
153
153
|
sleepTimerScheduler: any SleepTimerScheduling = ManualSleepTimerScheduler(),
|
|
154
154
|
saveInterval: Duration = .seconds(5),
|
|
155
155
|
) -> Player {
|
|
@@ -158,7 +158,7 @@ func makePlayer(
|
|
|
158
158
|
persistenceDefaults: UserDefaults(suiteName: "PlayerTests")!, persistenceSaveInterval: saveInterval,
|
|
159
159
|
)
|
|
160
160
|
// Player's init installs its own `shouldRetry`; replace it afterwards.
|
|
161
|
-
retry.shouldRetry = { retries }
|
|
161
|
+
if let retries { retry.shouldRetry = { retries } }
|
|
162
162
|
return player
|
|
163
163
|
}
|
|
164
164
|
|