react-native-audio-browser 0.2.0-next.83 → 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.
- package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +31 -9
- package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +39 -46
- package/android/src/main/java/com/audiobrowser/player/Player.kt +219 -54
- package/android/src/main/java/com/audiobrowser/player/PlayerEngineFactory.kt +5 -6
- package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +88 -73
- package/android/src/main/java/com/audiobrowser/player/ReconnectPacer.kt +8 -9
- package/android/src/main/java/com/audiobrowser/player/RetryFocus.kt +126 -0
- package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +55 -121
- package/android/src/main/java/com/audiobrowser/player/RetryLocks.kt +52 -0
- package/android/src/main/java/com/audiobrowser/player/RetryLoop.kt +310 -0
- package/android/src/main/java/com/audiobrowser/player/RetryView.kt +31 -0
- package/android/src/main/java/com/audiobrowser/player/SessionViewListener.kt +148 -0
- package/android/src/main/java/com/audiobrowser/remote/RemoteOutputsController.kt +4 -1
- package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +3 -1
- package/android/src/main/java/com/audiobrowser/util/NetworkConnectivityMonitor.kt +4 -6
- package/android/src/test/java/androidx/media3/session/SessionViews.kt +9 -0
- package/android/src/test/java/com/audiobrowser/NetworkFixtures.kt +25 -0
- package/android/src/test/java/com/audiobrowser/player/LiveStreamEndTest.kt +15 -53
- package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +190 -53
- package/android/src/test/java/com/audiobrowser/player/RetryFocusTest.kt +97 -0
- package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +90 -152
- package/android/src/test/java/com/audiobrowser/player/RetryLocksTest.kt +48 -0
- package/android/src/test/java/com/audiobrowser/player/RetryLoopCaseTest.kt +181 -0
- package/android/src/test/java/com/audiobrowser/player/RetryLoopTest.kt +221 -0
- package/android/src/test/java/com/audiobrowser/player/RetryMaskingTest.kt +176 -0
- package/android/src/test/java/com/audiobrowser/player/SessionPlayTest.kt +2 -0
- package/android/src/test/java/com/audiobrowser/player/SessionViewListenerTest.kt +21 -0
- package/android/src/test/java/com/audiobrowser/player/SessionViewTest.kt +2 -0
- package/android/src/test/java/com/audiobrowser/util/NetworkConnectivityMonitorTest.kt +13 -4
- package/lib/commonjs/features/player/setup.js +5 -4
- package/lib/commonjs/features/player/setup.js.map +1 -1
- package/lib/module/features/player/setup.js +5 -4
- package/lib/module/features/player/setup.js.map +1 -1
- package/lib/typescript/src/features/player/setup.d.ts +19 -13
- package/lib/typescript/src/features/player/setup.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/features/player/setup.ts +19 -13
- package/website/guide/errors.md +42 -38
- package/website/guide/network.md +4 -3
- package/android/src/main/java/com/audiobrowser/player/StuckRecoveryPolicy.kt +0 -37
- package/android/src/test/java/com/audiobrowser/player/StuckRecoveryPolicyTest.kt +0 -40
|
@@ -21,28 +21,14 @@ import com.margelo.nitro.audiobrowser.PlaybackState
|
|
|
21
21
|
import java.util.Locale
|
|
22
22
|
import timber.log.Timber
|
|
23
23
|
|
|
24
|
-
// Continuous playback that refills the stuck-recovery and load-retry budgets. Shorter lets a
|
|
25
|
-
// stream that keeps re-stalling look alive between stalls; longer stops forgiving a single hiccup.
|
|
26
|
-
private const val HEALTHY_PLAYBACK_MS = 20_000L
|
|
27
|
-
|
|
28
24
|
class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
29
|
-
private val stuckRecoveryPolicy = StuckRecoveryPolicy()
|
|
30
|
-
|
|
31
25
|
// Main looper: Player.Listener callbacks arrive on the main thread.
|
|
32
26
|
private val mainHandler = Handler(Looper.getMainLooper())
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
// long-lived stream no retries for its next outage.
|
|
39
|
-
player.resetRetryTimer()
|
|
40
|
-
// Re-arm while playing: errors the buffer absorbs never flip isPlaying.
|
|
41
|
-
if (player.isPlaying) {
|
|
42
|
-
mainHandler.postDelayed(this, HEALTHY_PLAYBACK_MS)
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
27
|
+
|
|
28
|
+
/** Whether the phone's engine played at the last event, so a hand-over starts a new Load. */
|
|
29
|
+
private var localActive = true
|
|
30
|
+
|
|
31
|
+
@MediaPlayer.State private var lastEngineState = MediaPlayer.STATE_IDLE
|
|
46
32
|
|
|
47
33
|
/**
|
|
48
34
|
* Set from an app-started track change until the playback thread has handled it. Until then every
|
|
@@ -91,6 +77,16 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
91
77
|
reason: Int,
|
|
92
78
|
) {
|
|
93
79
|
player.oldPosition = oldPosition.positionMs
|
|
80
|
+
// A seek opens a new connection without passing through idle, clearing a failed one's error.
|
|
81
|
+
val loop = player.retryLoop
|
|
82
|
+
if (
|
|
83
|
+
reason == MediaPlayer.DISCONTINUITY_REASON_SEEK &&
|
|
84
|
+
loop?.failurePending == true &&
|
|
85
|
+
player.localEngine.isActive
|
|
86
|
+
) {
|
|
87
|
+
player.clearRetryingError()
|
|
88
|
+
loop.connectionStarted()
|
|
89
|
+
}
|
|
94
90
|
}
|
|
95
91
|
|
|
96
92
|
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
|
@@ -123,23 +119,24 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
123
119
|
// It also emits onNowPlayingChanged.
|
|
124
120
|
player.nowPlaying.render()
|
|
125
121
|
|
|
126
|
-
player.
|
|
122
|
+
player.startRetryLoad()
|
|
127
123
|
|
|
128
124
|
// Emits on its own: the incoming track may hold LOADING/BUFFERING and emit no state change.
|
|
129
125
|
player.clearRetryingError()
|
|
130
126
|
|
|
131
|
-
mainHandler.removeCallbacks(healthyPlaybackRunnable)
|
|
132
|
-
stuckRecoveryPolicy.reset()
|
|
133
|
-
|
|
134
127
|
player.playbackStateStore.save()
|
|
135
128
|
player.playbackStateStore.resetPeriodicSave()
|
|
136
129
|
}
|
|
137
130
|
|
|
138
131
|
override fun onIsPlayingChanged(isPlaying: Boolean) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
132
|
+
if (player.localEngine.isActive)
|
|
133
|
+
player.retryLoop?.isPlayingChanged(isPlaying && !player.retryMasksPlaying)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A new engine or session player is attached: what this listener knew of the old one is gone. */
|
|
137
|
+
internal fun engineAttached() {
|
|
138
|
+
lastEngineState = player.exoPlayer.playbackState
|
|
139
|
+
localActive = player.localEngine.isActive
|
|
143
140
|
}
|
|
144
141
|
|
|
145
142
|
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
|
|
@@ -151,6 +148,8 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
151
148
|
|
|
152
149
|
// Here rather than in Player.pause(): a session pause, a noisy-audio pause and a permanent
|
|
153
150
|
// focus loss all drop the intent without it.
|
|
151
|
+
if (!playWhenReady) player.retryFocus.release()
|
|
152
|
+
player.retryLoop?.playIntentChanged(player.shouldPlayWhenReady)
|
|
154
153
|
if (!playWhenReady) player.cancelRetry()
|
|
155
154
|
// Deduped: the ENDED path in setPlaybackState may already have emitted it, before queue-ended.
|
|
156
155
|
player.emitPlayWhenReadyChanged(playWhenReady)
|
|
@@ -165,15 +164,40 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
165
164
|
}
|
|
166
165
|
|
|
167
166
|
override fun onPlaybackSuppressionReasonChanged(playbackSuppressionReason: Int) {
|
|
167
|
+
player.retryLoop?.playIntentChanged(player.shouldPlayWhenReady)
|
|
168
168
|
player.refreshPlayingState()
|
|
169
169
|
player.rebuildIfDueLater()
|
|
170
170
|
}
|
|
171
171
|
|
|
172
172
|
override fun onPlaybackStateChanged(playbackState: Int) {
|
|
173
|
+
// The engine's own state: InterceptingPlayer also sends its view here.
|
|
174
|
+
val engineState = player.sessionPlayer.playbackState
|
|
175
|
+
val left = lastEngineState == MediaPlayer.STATE_IDLE && engineState != MediaPlayer.STATE_IDLE
|
|
176
|
+
lastEngineState = engineState
|
|
177
|
+
val loop = player.retryLoop
|
|
178
|
+
// A prepare: the retry's reconnect, or the listener's play, which after a give-up or a stop is
|
|
179
|
+
// a new Load.
|
|
180
|
+
if (loop != null && player.localEngine.isActive) {
|
|
181
|
+
if (left) {
|
|
182
|
+
if (loop.stopped) player.startRetryLoad() else loop.connectionStarted()
|
|
183
|
+
} else if (
|
|
184
|
+
engineState == MediaPlayer.STATE_IDLE && player.sessionPlayer.playerError == null
|
|
185
|
+
) {
|
|
186
|
+
// A failure report still on its way belongs to the stopped connection, not the next.
|
|
187
|
+
player.clearRetryingError()
|
|
188
|
+
loop.engineStopped()
|
|
189
|
+
}
|
|
190
|
+
}
|
|
173
191
|
player.rebuildIfDueLater()
|
|
174
192
|
}
|
|
175
193
|
|
|
176
194
|
override fun onEvents(media3Player: MediaPlayer, events: MediaPlayer.Events) {
|
|
195
|
+
val local = player.localEngine.isActive
|
|
196
|
+
if (local != localActive) {
|
|
197
|
+
localActive = local
|
|
198
|
+
// The retry loop never acts on a remote output; the phone taking over is a new Load.
|
|
199
|
+
if (local) player.startRetryLoad() else player.retryLoop?.suspend()
|
|
200
|
+
}
|
|
177
201
|
// In event-constant order, not the order the events happened; the transitions rely on it.
|
|
178
202
|
// Each setPlaybackState emits.
|
|
179
203
|
for (i in 0 until events.size()) {
|
|
@@ -183,7 +207,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
183
207
|
// The session player's state, not the forwarding player's: InterceptingPlayer masks
|
|
184
208
|
// IDLE as READY after a terminal error, which would clear our ERROR state here.
|
|
185
209
|
PlaybackEvent.ExoPlaybackStateChanged(
|
|
186
|
-
player.sessionPlayer.playbackState,
|
|
210
|
+
player.retryView(player.sessionPlayer.playbackState),
|
|
187
211
|
media3Player.mediaItemCount,
|
|
188
212
|
player.shouldPlayWhenReady,
|
|
189
213
|
)
|
|
@@ -198,9 +222,10 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
198
222
|
MediaPlayer.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED ->
|
|
199
223
|
PlaybackEvent.ShouldPlayWhenReadyChanged(
|
|
200
224
|
player.shouldPlayWhenReady,
|
|
201
|
-
player.sessionPlayer.playbackState,
|
|
225
|
+
player.retryView(player.sessionPlayer.playbackState),
|
|
202
226
|
)
|
|
203
|
-
MediaPlayer.EVENT_IS_PLAYING_CHANGED ->
|
|
227
|
+
MediaPlayer.EVENT_IS_PLAYING_CHANGED ->
|
|
228
|
+
PlaybackEvent.IsPlayingChanged(player.isPlaying && !player.retryMasksPlaying)
|
|
204
229
|
else -> null
|
|
205
230
|
} ?: continue
|
|
206
231
|
|
|
@@ -208,6 +233,8 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
208
233
|
player.setPlaybackState(state)
|
|
209
234
|
}
|
|
210
235
|
}
|
|
236
|
+
// The retry loop's state moved with these events, after the session's listeners heard them.
|
|
237
|
+
player.forwardingPlayer.refreshViews()
|
|
211
238
|
}
|
|
212
239
|
|
|
213
240
|
override fun onPlayerError(error: PlaybackException) {
|
|
@@ -219,25 +246,35 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
219
246
|
private fun recoverLocally(error: PlaybackException): Boolean {
|
|
220
247
|
if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) {
|
|
221
248
|
Timber.d("Playback fell behind live window, recovering to live edge")
|
|
222
|
-
player.resetRetryTimer()
|
|
223
249
|
player.localEngine.retry(toLiveEdge = true)
|
|
224
250
|
return true
|
|
225
251
|
}
|
|
226
252
|
|
|
227
253
|
// media3 1.9+ stuck-player detection wraps a StuckPlayerException (not a PlaybackException) in
|
|
228
254
|
// the cause chain, and the wrapper's errorCode varies by stuck type: match the cause.
|
|
229
|
-
val stuck =
|
|
230
|
-
generateSequence(error.cause) { it.cause }
|
|
231
|
-
.filterIsInstance<StuckPlayerException>()
|
|
232
|
-
.firstOrNull()
|
|
255
|
+
val stuck = stuckCause(error)
|
|
233
256
|
if (stuck != null) {
|
|
234
|
-
|
|
257
|
+
Timber.w("Stuck player: type=${stuck.stuckType} timeoutMs=${stuck.timeoutMs}")
|
|
258
|
+
// media3 detects stuck only while playWhenReady, but a paused player never gets recovery
|
|
259
|
+
// work.
|
|
260
|
+
if (!player.playWhenReady) return true
|
|
261
|
+
if (player.retryLoop?.onPlayerError(error, stuck = true) == true) return true
|
|
262
|
+
surfaceStalled(error)
|
|
235
263
|
return true
|
|
236
264
|
}
|
|
237
|
-
return false
|
|
265
|
+
return player.retryLoop?.onPlayerError(error, stuck = false) == true
|
|
238
266
|
}
|
|
239
267
|
|
|
240
|
-
private fun
|
|
268
|
+
private fun stuckCause(error: PlaybackException) =
|
|
269
|
+
generateSequence(error.cause) { it.cause }
|
|
270
|
+
.filterIsInstance<StuckPlayerException>()
|
|
271
|
+
.firstOrNull()
|
|
272
|
+
|
|
273
|
+
/** The retry loop's give-up: stalled when the last connection ended stuck, as without a loop. */
|
|
274
|
+
internal fun surfaceTerminal(error: PlaybackException) =
|
|
275
|
+
if (stuckCause(error) != null) surfaceStalled(error) else surface(error)
|
|
276
|
+
|
|
277
|
+
internal fun surface(error: PlaybackException) {
|
|
241
278
|
val online = player.networkMonitor.getOnline()
|
|
242
279
|
// `code` keeps ExoPlayer's name for telemetry; consumers branch on the classified kind. Offline
|
|
243
280
|
// is the one case ExoPlayer's codes can't tell, so it overrides the code too.
|
|
@@ -263,41 +300,19 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
263
300
|
player.setPlaybackState(PlaybackState.ERROR)
|
|
264
301
|
}
|
|
265
302
|
|
|
266
|
-
/**
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
"live=${player.isCurrentItemLive}"
|
|
280
|
-
)
|
|
281
|
-
// Offline time counts against the recovery budget, and offline media3 reports stuck every
|
|
282
|
-
// minute: a refill here would keep the budget from ever running out.
|
|
283
|
-
if (player.networkMonitor.getOnline()) player.resetRetryTimer()
|
|
284
|
-
player.localEngine.retry(toLiveEdge = player.isCurrentItemLive)
|
|
285
|
-
}
|
|
286
|
-
StuckRecoveryPolicy.Decision.GIVE_UP -> {
|
|
287
|
-
Timber.w("Stuck player recovery exhausted (type=${error.stuckType}), surfacing error")
|
|
288
|
-
val playbackError =
|
|
289
|
-
PlaybackError(
|
|
290
|
-
PlaybackErrorKind.STALLED,
|
|
291
|
-
"playback-stalled",
|
|
292
|
-
error.message ?: "Playback stalled",
|
|
293
|
-
null,
|
|
294
|
-
retrying = null,
|
|
295
|
-
)
|
|
296
|
-
player.callbacks?.onPlaybackError(playbackError)
|
|
297
|
-
player.playbackError = playbackError
|
|
298
|
-
player.setPlaybackState(PlaybackState.ERROR)
|
|
299
|
-
}
|
|
300
|
-
}
|
|
303
|
+
/** No retry loop takes the stuck engine: it is terminal. */
|
|
304
|
+
private fun surfaceStalled(error: PlaybackException) {
|
|
305
|
+
val playbackError =
|
|
306
|
+
PlaybackError(
|
|
307
|
+
PlaybackErrorKind.STALLED,
|
|
308
|
+
"playback-stalled",
|
|
309
|
+
error.message ?: "Playback stalled",
|
|
310
|
+
null,
|
|
311
|
+
retrying = null,
|
|
312
|
+
)
|
|
313
|
+
player.callbacks?.onPlaybackError(playbackError)
|
|
314
|
+
player.playbackError = playbackError
|
|
315
|
+
player.setPlaybackState(PlaybackState.ERROR)
|
|
301
316
|
}
|
|
302
317
|
|
|
303
318
|
override fun onRepeatModeChanged(repeatMode: Int) {
|
|
@@ -28,9 +28,13 @@ sealed interface ReconnectWait {
|
|
|
28
28
|
class ReconnectPacer(var maxRetries: Int? = null, private var online: Boolean) {
|
|
29
29
|
companion object {
|
|
30
30
|
const val MIN_CONNECT_INTERVAL_MS = 1_000L
|
|
31
|
-
const val FIRST_BACKOFF_MS = 1_000L
|
|
32
|
-
const val MAX_BACKOFF_MS = 5_000L
|
|
33
|
-
const val BACKOFF_GROWTH = 1.5
|
|
31
|
+
private const val FIRST_BACKOFF_MS = 1_000L
|
|
32
|
+
private const val MAX_BACKOFF_MS = 5_000L
|
|
33
|
+
private const val BACKOFF_GROWTH = 1.5
|
|
34
|
+
|
|
35
|
+
/** The backoff before [attempt], counted from 1. */
|
|
36
|
+
fun backoffMs(attempt: Int): Long =
|
|
37
|
+
min(FIRST_BACKOFF_MS * BACKOFF_GROWTH.pow(attempt - 1), MAX_BACKOFF_MS.toDouble()).toLong()
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
private var playIntent = false
|
|
@@ -79,7 +83,7 @@ class ReconnectPacer(var maxRetries: Int? = null, private var online: Boolean) {
|
|
|
79
83
|
deliveredNothingInARow = 0
|
|
80
84
|
} else if (online) {
|
|
81
85
|
deliveredNothingInARow++
|
|
82
|
-
next = maxOf(next, atMs + backoffMs())
|
|
86
|
+
next = maxOf(next, atMs + backoffMs(deliveredNothingInARow))
|
|
83
87
|
}
|
|
84
88
|
nextConnectMs = next
|
|
85
89
|
}
|
|
@@ -89,9 +93,4 @@ class ReconnectPacer(var maxRetries: Int? = null, private var online: Boolean) {
|
|
|
89
93
|
if (!online) return ReconnectWait.UntilOnline
|
|
90
94
|
return ReconnectWait.After(maxOf(0, (nextConnectMs ?: atMs) - atMs))
|
|
91
95
|
}
|
|
92
|
-
|
|
93
|
-
private fun backoffMs(): Long {
|
|
94
|
-
val grown = FIRST_BACKOFF_MS * BACKOFF_GROWTH.pow(deliveredNothingInARow - 1)
|
|
95
|
-
return min(grown, MAX_BACKOFF_MS.toDouble()).toLong()
|
|
96
|
-
}
|
|
97
96
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import android.media.AudioAttributes
|
|
4
|
+
import android.media.AudioFocusRequest
|
|
5
|
+
import android.media.AudioManager
|
|
6
|
+
import android.os.Build
|
|
7
|
+
import android.os.Handler
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Audio focus while [RetryLoop] keeps the engine idle between connections: media3 abandons the
|
|
11
|
+
* engine's focus in IDLE, so the library holds its own and answers a change as media3 answers one
|
|
12
|
+
* while playing. A permanent loss, or a request refused, is a pause; a transient loss, or a request
|
|
13
|
+
* that waits (a call), suppresses the play intent until focus returns.
|
|
14
|
+
*/
|
|
15
|
+
internal class RetryFocus(
|
|
16
|
+
private val port: Port,
|
|
17
|
+
private val onLoss: () -> Unit,
|
|
18
|
+
private val onSuppressionChanged: () -> Unit,
|
|
19
|
+
) {
|
|
20
|
+
interface Port {
|
|
21
|
+
/** Requests focus, accepting a delayed gain; returns AudioManager's result. */
|
|
22
|
+
fun request(listener: AudioManager.OnAudioFocusChangeListener): Int
|
|
23
|
+
|
|
24
|
+
fun abandon()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
private var requested = false
|
|
28
|
+
private var generation = 0
|
|
29
|
+
|
|
30
|
+
/** Whether focus is lost for now, or not yet granted: the play intent stays down until it is. */
|
|
31
|
+
var suppressed = false
|
|
32
|
+
private set
|
|
33
|
+
|
|
34
|
+
fun hold() {
|
|
35
|
+
if (requested) return
|
|
36
|
+
requested = true
|
|
37
|
+
val ours = ++generation
|
|
38
|
+
val listener =
|
|
39
|
+
AudioManager.OnAudioFocusChangeListener { change ->
|
|
40
|
+
// A change for a request since abandoned: at the reconnect, see [handOver].
|
|
41
|
+
if (ours == generation) changed(change)
|
|
42
|
+
}
|
|
43
|
+
when (port.request(listener)) {
|
|
44
|
+
AudioManager.AUDIOFOCUS_REQUEST_GRANTED -> Unit
|
|
45
|
+
AudioManager.AUDIOFOCUS_REQUEST_DELAYED -> suppress(true)
|
|
46
|
+
else -> lose()
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
fun release() {
|
|
51
|
+
if (!requested) return
|
|
52
|
+
requested = false
|
|
53
|
+
generation++
|
|
54
|
+
port.abandon()
|
|
55
|
+
suppress(false)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Runs the reconnect's [prepare], then lets this request go. ExoPlayer requests the engine's
|
|
60
|
+
* focus on its playback thread a few milliseconds later: another app's request in that gap is
|
|
61
|
+
* overridden by the engine's, as by a tap on play, and its loss to this request is dropped.
|
|
62
|
+
*/
|
|
63
|
+
fun handOver(prepare: () -> Unit) {
|
|
64
|
+
prepare()
|
|
65
|
+
release()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private fun changed(change: Int) {
|
|
69
|
+
when (change) {
|
|
70
|
+
AudioManager.AUDIOFOCUS_GAIN -> suppress(false)
|
|
71
|
+
AudioManager.AUDIOFOCUS_LOSS -> lose()
|
|
72
|
+
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> suppress(true)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private fun lose() {
|
|
77
|
+
release()
|
|
78
|
+
onLoss()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private fun suppress(suppressed: Boolean) {
|
|
82
|
+
if (suppressed == this.suppressed) return
|
|
83
|
+
this.suppressed = suppressed
|
|
84
|
+
onSuppressionChanged()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** [Port] on the platform's AudioManager, its changes delivered on [handler]. */
|
|
88
|
+
class Platform(
|
|
89
|
+
private val audioManager: AudioManager,
|
|
90
|
+
private val handler: Handler,
|
|
91
|
+
private val attributes: () -> AudioAttributes,
|
|
92
|
+
) : Port {
|
|
93
|
+
private var request: AudioFocusRequest? = null
|
|
94
|
+
private var legacyListener: AudioManager.OnAudioFocusChangeListener? = null
|
|
95
|
+
|
|
96
|
+
override fun request(listener: AudioManager.OnAudioFocusChangeListener): Int =
|
|
97
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
98
|
+
val request =
|
|
99
|
+
AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
|
100
|
+
.setAudioAttributes(attributes())
|
|
101
|
+
.setAcceptsDelayedFocusGain(true)
|
|
102
|
+
.setOnAudioFocusChangeListener(listener, handler)
|
|
103
|
+
.build()
|
|
104
|
+
this.request = request
|
|
105
|
+
audioManager.requestAudioFocus(request)
|
|
106
|
+
} else {
|
|
107
|
+
legacyListener = listener
|
|
108
|
+
@Suppress("DEPRECATION")
|
|
109
|
+
audioManager.requestAudioFocus(
|
|
110
|
+
listener,
|
|
111
|
+
AudioManager.STREAM_MUSIC,
|
|
112
|
+
AudioManager.AUDIOFOCUS_GAIN,
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
override fun abandon() {
|
|
117
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
118
|
+
request?.let { audioManager.abandonAudioFocusRequest(it) }
|
|
119
|
+
request = null
|
|
120
|
+
} else {
|
|
121
|
+
@Suppress("DEPRECATION") legacyListener?.let { audioManager.abandonAudioFocus(it) }
|
|
122
|
+
legacyListener = null
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -1,150 +1,89 @@
|
|
|
1
1
|
package com.audiobrowser.player
|
|
2
2
|
|
|
3
|
-
import android.os.SystemClock
|
|
4
3
|
import androidx.media3.common.C
|
|
5
4
|
import androidx.media3.common.ParserException
|
|
6
5
|
import androidx.media3.datasource.DataSourceException
|
|
7
6
|
import androidx.media3.datasource.HttpDataSource
|
|
7
|
+
import androidx.media3.exoplayer.source.LoadEventInfo
|
|
8
8
|
import androidx.media3.exoplayer.upstream.DefaultLoadErrorHandlingPolicy
|
|
9
9
|
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy
|
|
10
10
|
import androidx.media3.exoplayer.upstream.Loader
|
|
11
11
|
import java.io.FileNotFoundException
|
|
12
12
|
import java.io.IOException
|
|
13
|
-
import kotlin.math.min
|
|
14
|
-
import kotlin.math.pow
|
|
15
|
-
import timber.log.Timber
|
|
16
13
|
|
|
17
14
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
15
|
+
* What becomes of a recoverable load failure of one media item (docs/adr/0014). Where media3
|
|
16
|
+
* resumes the connection in place (an adaptive stream's segment or playlist, a file whose response
|
|
17
|
+
* declared its length), it retries after the backoff; anything else ends the connection, for
|
|
18
|
+
* [RetryLoop] to reconnect once the buffer has played out. An item that is only preloading retries
|
|
19
|
+
* in place: the loop serves the current item. It never gives up on a recoverable failure: the
|
|
20
|
+
* loop's silence deadline does. Called on ExoPlayer's playback thread.
|
|
20
21
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* its seconds once connectivity returns. Every load is also bounded by the full recovery budget,
|
|
24
|
-
* offline time included. Budgets are kept here, never through
|
|
25
|
-
* [LoadErrorHandlingPolicy.LoadErrorInfo.errorCount]: that counts per loadable (an HLS stream has a
|
|
26
|
-
* playlist and segment loadables, each counted apart), so it cannot bound a load.
|
|
27
|
-
*
|
|
28
|
-
* @param maxRetries the most retries per loadable; null for no limit
|
|
29
|
-
* @param maxRetryDurationMs the full recovery budget; null for 2 minutes
|
|
30
|
-
* @param firstConnectMaxRetryDurationMs the online budget of a load that has never produced audio;
|
|
31
|
-
* null for 12 seconds
|
|
32
|
-
* @param hasPlayed whether the current load has produced audio; called on ExoPlayer's loader thread
|
|
33
|
-
* @param onRetryPending called on ExoPlayer's loader thread each time a retry is scheduled, with
|
|
34
|
-
* the error being retried
|
|
22
|
+
* @param isCurrent whether the item is the one playing; read on the playback thread
|
|
23
|
+
* @param onFailure each recoverable failure of the current item, and whether it is retried in place
|
|
35
24
|
*/
|
|
36
25
|
class RetryLoadErrorHandlingPolicy(
|
|
37
|
-
private val
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
private val isOnline: () -> Boolean = { true },
|
|
41
|
-
private val hasPlayed: () -> Boolean = { false },
|
|
42
|
-
private val onRetryPending: ((exception: IOException) -> Unit)? = null,
|
|
26
|
+
private val sources: Sources,
|
|
27
|
+
private val isCurrent: () -> Boolean,
|
|
28
|
+
private val onFailure: (exception: IOException, inPlace: Boolean) -> Unit,
|
|
43
29
|
) : DefaultLoadErrorHandlingPolicy() {
|
|
44
30
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
private const val BACKOFF_MULTIPLIER = 1.5
|
|
49
|
-
// Fixed while offline, so the first retry after connectivity returns lands soon.
|
|
50
|
-
private const val OFFLINE_RETRY_DELAY_MS = 1000L
|
|
51
|
-
private const val DEFAULT_MAX_RETRY_DURATION_MS = 120_000L
|
|
52
|
-
private const val DEFAULT_FIRST_CONNECT_MAX_RETRY_DURATION_MS = 12_000L
|
|
53
|
-
|
|
54
|
-
private val RETRYABLE_HTTP_STATUS_CODES = setOf(408, 429, 500, 502, 503, 504)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Stops playback resuming by surprise after a long time offline.
|
|
58
|
-
private val maxRetryDurationMs: Long = maxRetryDurationMs ?: DEFAULT_MAX_RETRY_DURATION_MS
|
|
31
|
+
enum class Sources {
|
|
32
|
+
/** HLS, DASH and SmoothStreaming: segments and playlists retry in place. */
|
|
33
|
+
ADAPTIVE,
|
|
59
34
|
|
|
60
|
-
|
|
61
|
-
|
|
35
|
+
/** A progressive stream: in place only once the response declared its length. */
|
|
36
|
+
PROGRESSIVE,
|
|
62
37
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
// The first-connect budget's clock: set at the first error seen online and wiped by any seen
|
|
67
|
-
// offline, so an offline stretch never burns it.
|
|
68
|
-
@Volatile private var firstOnlineErrorTime: Long? = null
|
|
38
|
+
/** A progressive stream marked live: every failure ends the connection. */
|
|
39
|
+
LIVE,
|
|
40
|
+
}
|
|
69
41
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
firstErrorTime = null
|
|
73
|
-
firstOnlineErrorTime = null
|
|
42
|
+
companion object {
|
|
43
|
+
private val RETRYABLE_HTTP_STATUS_CODES = setOf(408, 429, 500, 502, 503, 504)
|
|
74
44
|
}
|
|
75
45
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
46
|
+
override fun getRetryDelayMsFor(loadErrorInfo: LoadErrorHandlingPolicy.LoadErrorInfo): Long {
|
|
47
|
+
// Not super's verdict: it still backs off on some errors it doesn't treat as fatal (a 404),
|
|
48
|
+
// which would retry a dead URL until the silence deadline.
|
|
49
|
+
if (!isRecoverable(loadErrorInfo.exception)) return C.TIME_UNSET
|
|
50
|
+
val backoff = ReconnectPacer.backoffMs(loadErrorInfo.errorCount)
|
|
51
|
+
if (!isCurrent()) return backoff
|
|
52
|
+
val inPlace =
|
|
53
|
+
when (sources) {
|
|
54
|
+
Sources.ADAPTIVE -> true
|
|
55
|
+
Sources.PROGRESSIVE -> hasKnownLength(loadErrorInfo.loadEventInfo)
|
|
56
|
+
Sources.LIVE -> false
|
|
87
57
|
}
|
|
88
|
-
|
|
89
|
-
return
|
|
58
|
+
onFailure(loadErrorInfo.exception, inPlace)
|
|
59
|
+
return if (inPlace) backoff else C.TIME_UNSET
|
|
90
60
|
}
|
|
91
61
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
val exponentialDelay =
|
|
95
|
-
INITIAL_RETRY_DELAY_MS * BACKOFF_MULTIPLIER.pow((errorCount - 1).toDouble())
|
|
96
|
-
return min(exponentialDelay.toLong(), MAX_RETRY_DELAY_MS)
|
|
62
|
+
override fun onLoadTaskConcluded(loadTaskId: Long) {
|
|
63
|
+
knownLength -= loadTaskId
|
|
97
64
|
}
|
|
98
65
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
val errorCount = loadErrorInfo.errorCount
|
|
102
|
-
val currentTime = SystemClock.elapsedRealtime()
|
|
66
|
+
/** Load tasks whose response declared a length: a reopen that fails carries no headers. */
|
|
67
|
+
private val knownLength = mutableSetOf<Long>()
|
|
103
68
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (firstErrorTime == null) {
|
|
110
|
-
firstErrorTime = currentTime
|
|
111
|
-
}
|
|
112
|
-
if (isOnline()) {
|
|
113
|
-
if (firstOnlineErrorTime == null) firstOnlineErrorTime = currentTime
|
|
114
|
-
} else {
|
|
115
|
-
firstOnlineErrorTime = null
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
exhaustedBudget(currentTime)?.let { budget ->
|
|
119
|
-
Timber.d("$budget exceeded, giving up")
|
|
120
|
-
return C.TIME_UNSET
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
return if (isRecoverable(exception)) {
|
|
124
|
-
val currentlyOffline = !isOnline()
|
|
125
|
-
|
|
126
|
-
val delay =
|
|
127
|
-
if (currentlyOffline) {
|
|
128
|
-
Timber.d("Device is offline, using short retry delay")
|
|
129
|
-
OFFLINE_RETRY_DELAY_MS
|
|
130
|
-
} else {
|
|
131
|
-
calculateBackoffDelay(errorCount)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
Timber.d(
|
|
135
|
-
"Retrying after IO error (load error $errorCount, delay ${delay}ms unless deferred, offline=$currentlyOffline): ${exception.message}"
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
onRetryPending?.invoke(exception)
|
|
69
|
+
private fun hasKnownLength(info: LoadEventInfo): Boolean {
|
|
70
|
+
if (declaresLength(info.responseHeaders)) knownLength += info.loadTaskId
|
|
71
|
+
return info.loadTaskId in knownLength
|
|
72
|
+
}
|
|
139
73
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
74
|
+
/** Never media3's verdict: the in-place path retries until the loop gives up on it. */
|
|
75
|
+
override fun getMinimumLoadableRetryCount(dataType: Int): Int = Int.MAX_VALUE
|
|
76
|
+
|
|
77
|
+
private fun declaresLength(headers: Map<String, List<String>>): Boolean =
|
|
78
|
+
headers.any { (name, values) ->
|
|
79
|
+
when {
|
|
80
|
+
name.equals("Content-Length", ignoreCase = true) -> true
|
|
81
|
+
// A Range response's total, `bytes 0-99/1234`; `*` is a length the server doesn't know.
|
|
82
|
+
name.equals("Content-Range", ignoreCase = true) ->
|
|
83
|
+
values.any { !it.substringAfterLast('/').trim().startsWith('*') }
|
|
84
|
+
else -> false
|
|
85
|
+
}
|
|
146
86
|
}
|
|
147
|
-
}
|
|
148
87
|
|
|
149
88
|
/**
|
|
150
89
|
* Walks the cause chain: load errors arrive as raw IOExceptions (a Wi-Fi drop is a socket or DNS
|
|
@@ -169,9 +108,4 @@ class RetryLoadErrorHandlingPolicy(
|
|
|
169
108
|
// in-place retry.
|
|
170
109
|
return !DataSourceException.isCausedByPositionOutOfRange(exception)
|
|
171
110
|
}
|
|
172
|
-
|
|
173
|
-
override fun getMinimumLoadableRetryCount(dataType: Int): Int {
|
|
174
|
-
// Unbounded by default: the duration budgets decide when to stop.
|
|
175
|
-
return maxRetries ?: Int.MAX_VALUE
|
|
176
|
-
}
|
|
177
111
|
}
|