react-native-audio-browser 0.2.0-next.92 → 0.2.0-next.94
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/MediaFactory.kt +1 -1
- package/android/src/main/java/com/audiobrowser/player/Player.kt +67 -5
- package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +8 -7
- package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +19 -1
- package/android/src/test/java/com/audiobrowser/AudioFixtures.kt +27 -0
- package/android/src/test/java/com/audiobrowser/TestFixtures.kt +2 -1
- package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +132 -1
- package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +31 -2
- package/ios/AVPlayerEngine.swift +24 -2
- package/ios/Observer/ItemObserver.swift +10 -3
- package/ios/Player/MediaLoader.swift +11 -5
- package/ios/Player/Player.swift +114 -19
- package/ios/Player/PlayerEngine.swift +10 -1
- package/ios/Tests/MediaLoaderTests.swift +21 -0
- package/ios/Tests/ObserverTests.swift +18 -0
- package/ios/Tests/PlayerPolicyTests.swift +365 -8
- package/ios/Tests/Support/SilentAudioFile.swift +13 -0
- package/ios/Tests/Support/TestTypes.swift +19 -1
- package/package.json +1 -1
- package/website/guide/live-streams.md +29 -0
|
@@ -133,7 +133,7 @@ class MediaFactory(
|
|
|
133
133
|
// One policy per item: it tells the playing item's failures from a preload's.
|
|
134
134
|
if (retrying)
|
|
135
135
|
factory.setLoadErrorHandlingPolicy(
|
|
136
|
-
RetryLoadErrorHandlingPolicy(sources, { isCurrent(mediaItem) }, onLoadFailure)
|
|
136
|
+
RetryLoadErrorHandlingPolicy(sources, { isCurrent(mediaItem) }, cache, onLoadFailure)
|
|
137
137
|
)
|
|
138
138
|
val source = factory.setDataSourceFactory(dataSourceFactory).createMediaSource(mediaItem)
|
|
139
139
|
// Adaptive sources retry in place: the policy never ends their connection.
|
|
@@ -12,6 +12,7 @@ import androidx.media3.common.MediaItem
|
|
|
12
12
|
import androidx.media3.common.MediaMetadata
|
|
13
13
|
import androidx.media3.common.PlaybackException
|
|
14
14
|
import androidx.media3.common.Player as MediaPlayer
|
|
15
|
+
import androidx.media3.common.Timeline
|
|
15
16
|
import androidx.media3.database.StandaloneDatabaseProvider
|
|
16
17
|
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
|
|
17
18
|
import androidx.media3.datasource.cache.SimpleCache
|
|
@@ -79,6 +80,25 @@ import kotlinx.coroutines.withContext
|
|
|
79
80
|
import kotlinx.coroutines.withTimeout
|
|
80
81
|
import timber.log.Timber
|
|
81
82
|
|
|
83
|
+
/**
|
|
84
|
+
* The window behind its live edge that lets a live item pause in place, as on-demand does (a DVR
|
|
85
|
+
* window). A shorter one is a stream that can't be rewound: a pause closes it.
|
|
86
|
+
*/
|
|
87
|
+
private const val PAUSABLE_LIVE_WINDOW_MS = 30_000L
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* STOPPED stays out: stop() idles the engine itself, and [Player.stopRetrying] would make it
|
|
91
|
+
* PAUSED.
|
|
92
|
+
*/
|
|
93
|
+
private val LIVE_CONNECTION_STATES =
|
|
94
|
+
setOf(
|
|
95
|
+
PlaybackState.LOADING,
|
|
96
|
+
PlaybackState.READY,
|
|
97
|
+
PlaybackState.BUFFERING,
|
|
98
|
+
PlaybackState.PLAYING,
|
|
99
|
+
PlaybackState.PAUSED,
|
|
100
|
+
)
|
|
101
|
+
|
|
82
102
|
@SuppressLint("RestrictedApi")
|
|
83
103
|
class Player
|
|
84
104
|
internal constructor(
|
|
@@ -386,8 +406,12 @@ internal constructor(
|
|
|
386
406
|
value &&
|
|
387
407
|
currentTrack != null &&
|
|
388
408
|
retryView(sessionPlayer.playbackState) == MediaPlayer.STATE_IDLE
|
|
389
|
-
)
|
|
409
|
+
) {
|
|
410
|
+
// An idle engine keeps its position, a seek's while parked included: within a live
|
|
411
|
+
// window, the reconnect would resume there.
|
|
412
|
+
if (currentTrack?.live == true && !liveItemPausable) sessionPlayer.seekToDefaultPosition()
|
|
390
413
|
sessionPlayer.prepare()
|
|
414
|
+
}
|
|
391
415
|
}
|
|
392
416
|
|
|
393
417
|
/**
|
|
@@ -1061,7 +1085,7 @@ internal constructor(
|
|
|
1061
1085
|
* stream is the live edge.
|
|
1062
1086
|
*/
|
|
1063
1087
|
fun seekToLiveEdge() {
|
|
1064
|
-
if (currentTrack?.live != true) return
|
|
1088
|
+
if (currentTrack?.live != true || liveStreamParked) return
|
|
1065
1089
|
// A receiver loads a live stream again on a seek to its default position.
|
|
1066
1090
|
if (!localEngine.reconnectAtLiveEdge()) sessionPlayer.seekToDefaultPosition()
|
|
1067
1091
|
}
|
|
@@ -1108,6 +1132,7 @@ internal constructor(
|
|
|
1108
1132
|
|
|
1109
1133
|
/** An ended queue stays ended, as on an ended engine. */
|
|
1110
1134
|
fun prepare() {
|
|
1135
|
+
if (liveStreamParked) return
|
|
1111
1136
|
if (currentTrack != null && playbackState != PlaybackState.ENDED) sessionPlayer.prepare()
|
|
1112
1137
|
}
|
|
1113
1138
|
|
|
@@ -1180,8 +1205,8 @@ internal constructor(
|
|
|
1180
1205
|
}
|
|
1181
1206
|
|
|
1182
1207
|
/**
|
|
1183
|
-
* Bumped on track change so an [onLoadFailure] post for
|
|
1184
|
-
* main, read on ExoPlayer's playback thread.
|
|
1208
|
+
* Bumped on track change and seek so an [onLoadFailure] post for an earlier connection is
|
|
1209
|
+
* dropped. Written on main, read on ExoPlayer's playback thread.
|
|
1185
1210
|
*/
|
|
1186
1211
|
@Volatile private var retryingErrorGeneration = 0
|
|
1187
1212
|
|
|
@@ -1203,6 +1228,11 @@ internal constructor(
|
|
|
1203
1228
|
}
|
|
1204
1229
|
}
|
|
1205
1230
|
|
|
1231
|
+
/** Drops the [onLoadFailure] reports still on their way: they belong to an earlier connection. */
|
|
1232
|
+
internal fun dropFailureReports() {
|
|
1233
|
+
retryingErrorGeneration++
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1206
1236
|
private fun showRetryingError(error: PlaybackError) {
|
|
1207
1237
|
// Paused, the retry would run unseen and its failure be terminal. STOPPED, ERROR and ENDED
|
|
1208
1238
|
// reach here only from a post that raced them.
|
|
@@ -1237,6 +1267,38 @@ internal constructor(
|
|
|
1237
1267
|
stopRetrying()
|
|
1238
1268
|
}
|
|
1239
1269
|
|
|
1270
|
+
/**
|
|
1271
|
+
* A paused engine goes on loading a live stream until its buffer is full, and a resume plays what
|
|
1272
|
+
* it buffered, behind the stream. The engine idles in PAUSED instead, closing the connection, and
|
|
1273
|
+
* the next play's prepare() reconnects at the live edge.
|
|
1274
|
+
*/
|
|
1275
|
+
internal fun dropLiveConnection() {
|
|
1276
|
+
if (currentTrack?.live != true || !localEngine.isActive || liveItemPausable) return
|
|
1277
|
+
if (playbackState !in LIVE_CONNECTION_STATES) return
|
|
1278
|
+
if (exoPlayer.playbackState == ExoPlayer.STATE_IDLE) return
|
|
1279
|
+
stopRetrying()
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/** A live window that seeks at least [PAUSABLE_LIVE_WINDOW_MS] behind its live edge. */
|
|
1283
|
+
private val liveItemPausable: Boolean
|
|
1284
|
+
get() {
|
|
1285
|
+
val timeline = exoPlayer.currentTimeline
|
|
1286
|
+
if (timeline.isEmpty) return false
|
|
1287
|
+
val window = timeline.getWindow(exoPlayer.currentMediaItemIndex, Timeline.Window())
|
|
1288
|
+
return window.isDynamic &&
|
|
1289
|
+
window.isSeekable &&
|
|
1290
|
+
!window.isPlaceholder &&
|
|
1291
|
+
window.defaultPositionMs >= PAUSABLE_LIVE_WINDOW_MS
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/** A live track paused on an idle engine: it reconnects only to play, at the live edge. */
|
|
1295
|
+
private val liveStreamParked: Boolean
|
|
1296
|
+
get() =
|
|
1297
|
+
currentTrack?.live == true &&
|
|
1298
|
+
!playWhenReady &&
|
|
1299
|
+
localEngine.isActive &&
|
|
1300
|
+
exoPlayer.playbackState == ExoPlayer.STATE_IDLE
|
|
1301
|
+
|
|
1240
1302
|
/**
|
|
1241
1303
|
* Gives up a load ExoPlayer would retry. The engine idles in PAUSED, where the next prepare()
|
|
1242
1304
|
* reloads where it failed.
|
|
@@ -1255,7 +1317,7 @@ internal constructor(
|
|
|
1255
1317
|
* with no state change to emit the clear.
|
|
1256
1318
|
*/
|
|
1257
1319
|
internal fun clearRetryingError() {
|
|
1258
|
-
|
|
1320
|
+
dropFailureReports()
|
|
1259
1321
|
if (playbackError?.retrying != true) return
|
|
1260
1322
|
playbackError = null
|
|
1261
1323
|
callbacks?.onPlaybackChanged(Playback(playbackState, null))
|
|
@@ -79,13 +79,13 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
79
79
|
player.oldPosition = oldPosition.positionMs
|
|
80
80
|
// A seek opens a new connection without passing through idle, clearing a failed one's error.
|
|
81
81
|
val loop = player.retryLoop
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
82
|
+
if (reason == MediaPlayer.DISCONTINUITY_REASON_SEEK && player.localEngine.isActive) {
|
|
83
|
+
if (loop?.failurePending == true) {
|
|
84
|
+
player.clearRetryingError()
|
|
85
|
+
loop.connectionStarted()
|
|
86
|
+
} else {
|
|
87
|
+
player.dropFailureReports()
|
|
88
|
+
}
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
@@ -151,6 +151,7 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
|
|
|
151
151
|
if (!playWhenReady) player.retryFocus.release()
|
|
152
152
|
player.retryLoop?.playIntentChanged(player.shouldPlayWhenReady)
|
|
153
153
|
if (!playWhenReady) player.cancelRetry()
|
|
154
|
+
if (!playWhenReady) player.dropLiveConnection()
|
|
154
155
|
// Deduped: the ENDED path in setPlaybackState may already have emitted it, before queue-ended.
|
|
155
156
|
player.emitPlayWhenReadyChanged(playWhenReady)
|
|
156
157
|
player.refreshPlayingState()
|
|
@@ -3,7 +3,11 @@ package com.audiobrowser.player
|
|
|
3
3
|
import androidx.media3.common.C
|
|
4
4
|
import androidx.media3.common.ParserException
|
|
5
5
|
import androidx.media3.datasource.DataSourceException
|
|
6
|
+
import androidx.media3.datasource.DataSpec
|
|
6
7
|
import androidx.media3.datasource.HttpDataSource
|
|
8
|
+
import androidx.media3.datasource.cache.Cache
|
|
9
|
+
import androidx.media3.datasource.cache.CacheKeyFactory
|
|
10
|
+
import androidx.media3.datasource.cache.ContentMetadata
|
|
7
11
|
import androidx.media3.exoplayer.source.LoadEventInfo
|
|
8
12
|
import androidx.media3.exoplayer.upstream.DefaultLoadErrorHandlingPolicy
|
|
9
13
|
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy
|
|
@@ -20,11 +24,13 @@ import java.io.IOException
|
|
|
20
24
|
* loop's silence deadline does. Called on ExoPlayer's playback thread.
|
|
21
25
|
*
|
|
22
26
|
* @param isCurrent whether the item is the one playing; read on the playback thread
|
|
27
|
+
* @param cache the cache the item's loads read through, if any
|
|
23
28
|
* @param onFailure each recoverable failure of the current item, and whether it is retried in place
|
|
24
29
|
*/
|
|
25
30
|
class RetryLoadErrorHandlingPolicy(
|
|
26
31
|
private val sources: Sources,
|
|
27
32
|
private val isCurrent: () -> Boolean,
|
|
33
|
+
private val cache: Cache? = null,
|
|
28
34
|
private val onFailure: (exception: IOException, inPlace: Boolean) -> Unit,
|
|
29
35
|
) : DefaultLoadErrorHandlingPolicy() {
|
|
30
36
|
|
|
@@ -67,10 +73,22 @@ class RetryLoadErrorHandlingPolicy(
|
|
|
67
73
|
private val knownLength = mutableSetOf<Long>()
|
|
68
74
|
|
|
69
75
|
private fun hasKnownLength(info: LoadEventInfo): Boolean {
|
|
70
|
-
if (
|
|
76
|
+
if (
|
|
77
|
+
declaresLength(info.responseHeaders) ||
|
|
78
|
+
(info.responseHeaders.isEmpty() && cachedLengthKnown(info.dataSpec))
|
|
79
|
+
)
|
|
80
|
+
knownLength += info.loadTaskId
|
|
71
81
|
return info.loadTaskId in knownLength
|
|
72
82
|
}
|
|
73
83
|
|
|
84
|
+
/** A load reading from the cache has no response: the cache keeps the length one declared. */
|
|
85
|
+
private fun cachedLengthKnown(dataSpec: DataSpec): Boolean {
|
|
86
|
+
val cache = cache ?: return false
|
|
87
|
+
val key = CacheKeyFactory.DEFAULT.buildCacheKey(dataSpec)
|
|
88
|
+
return ContentMetadata.getContentLength(cache.getContentMetadata(key)) !=
|
|
89
|
+
C.LENGTH_UNSET.toLong()
|
|
90
|
+
}
|
|
91
|
+
|
|
74
92
|
/** Never media3's verdict: the in-place path retries until the loop gives up on it. */
|
|
75
93
|
override fun getMinimumLoadableRetryCount(dataType: Int): Int = Int.MAX_VALUE
|
|
76
94
|
|
|
@@ -30,3 +30,30 @@ fun silentWavBytes(duration: Duration): ByteArray {
|
|
|
30
30
|
/** The `file:` URI of [silentWavBytes] written to `silence.wav` here: a second call throws. */
|
|
31
31
|
fun TemporaryFolder.silentWavUri(duration: Duration): String =
|
|
32
32
|
Uri.fromFile(newFile("silence.wav").apply { writeBytes(silentWavBytes(duration)) }).toString()
|
|
33
|
+
|
|
34
|
+
/** MPEG-1 Layer III frames of silence, 32 kHz mono at 32 kbit/s: 144 bytes and 36 ms each. */
|
|
35
|
+
fun silentMp3Bytes(duration: Duration): ByteArray {
|
|
36
|
+
val frame =
|
|
37
|
+
ByteArray(144).apply {
|
|
38
|
+
this[0] = 0xFF.toByte()
|
|
39
|
+
this[1] = 0xFB.toByte()
|
|
40
|
+
this[2] = 0x18
|
|
41
|
+
this[3] = 0xC0.toByte()
|
|
42
|
+
}
|
|
43
|
+
val frames = (duration.toMillis() + 35) / 36
|
|
44
|
+
return ByteArray((frames * frame.size).toInt()) { frame[it % frame.size] }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The `file:` URI of a live HLS playlist, one with no end tag, of [segments] silent MP3 segments of
|
|
49
|
+
* [segmentSeconds] each, written to `live.m3u8` here: a second call throws.
|
|
50
|
+
*/
|
|
51
|
+
fun TemporaryFolder.liveHlsUri(segments: Int, segmentSeconds: Int = 10): String {
|
|
52
|
+
newFile("segment.mp3").writeBytes(silentMp3Bytes(Duration.ofSeconds(segmentSeconds.toLong())))
|
|
53
|
+
val playlist = buildString {
|
|
54
|
+
append("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:$segmentSeconds\n")
|
|
55
|
+
append("#EXT-X-MEDIA-SEQUENCE:0\n")
|
|
56
|
+
repeat(segments) { append("#EXTINF:$segmentSeconds.0,\nsegment.mp3\n") }
|
|
57
|
+
}
|
|
58
|
+
return Uri.fromFile(newFile("live.m3u8").apply { writeText(playlist) }).toString()
|
|
59
|
+
}
|
|
@@ -36,6 +36,7 @@ object TestFixtures {
|
|
|
36
36
|
favorited: Boolean? = null,
|
|
37
37
|
disabled: Boolean? = null,
|
|
38
38
|
style: TrackStyle? = null,
|
|
39
|
+
live: Boolean? = null,
|
|
39
40
|
) =
|
|
40
41
|
Track(
|
|
41
42
|
id = id,
|
|
@@ -55,7 +56,7 @@ object TestFixtures {
|
|
|
55
56
|
style = style,
|
|
56
57
|
disabled = disabled,
|
|
57
58
|
favorited = favorited,
|
|
58
|
-
live =
|
|
59
|
+
live = live,
|
|
59
60
|
icyCharset = null,
|
|
60
61
|
)
|
|
61
62
|
|
|
@@ -9,11 +9,13 @@ import androidx.media3.common.C
|
|
|
9
9
|
import androidx.media3.common.Metadata
|
|
10
10
|
import androidx.media3.common.PlaybackException
|
|
11
11
|
import androidx.media3.common.Player as MediaPlayer
|
|
12
|
+
import androidx.media3.common.Timeline
|
|
12
13
|
import androidx.media3.common.util.StuckPlayerException
|
|
13
14
|
import androidx.media3.extractor.metadata.icy.IcyInfo
|
|
14
15
|
import com.audiobrowser.Callbacks
|
|
15
16
|
import com.audiobrowser.TestFixtures
|
|
16
17
|
import com.audiobrowser.goOnline
|
|
18
|
+
import com.audiobrowser.liveHlsUri
|
|
17
19
|
import com.audiobrowser.model.PlayerSetupOptions
|
|
18
20
|
import com.audiobrowser.model.RetryPolicy
|
|
19
21
|
import com.audiobrowser.silentWavBytes
|
|
@@ -133,6 +135,103 @@ class PlayerRetryTest {
|
|
|
133
135
|
awaitRetry("the reload's retry")
|
|
134
136
|
}
|
|
135
137
|
|
|
138
|
+
@Test
|
|
139
|
+
fun `a live pause idles the engine paused, and the next play reconnects`() {
|
|
140
|
+
play(folder.silentWavUri(Duration.ofMinutes(1)), live = true)
|
|
141
|
+
idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
|
|
142
|
+
|
|
143
|
+
player.pause()
|
|
144
|
+
assertStaysPausedAndIdle()
|
|
145
|
+
player.prepare()
|
|
146
|
+
player.seekToLiveEdge()
|
|
147
|
+
assertStaysPausedAndIdle()
|
|
148
|
+
// A seek while paused, as far into a live window as the reconnect must not resume.
|
|
149
|
+
player.seekTo(30, TimeUnit.SECONDS)
|
|
150
|
+
// Masked as paused and ready, so the session shows the station paused.
|
|
151
|
+
assertEquals(MediaPlayer.STATE_READY, player.forwardingPlayer.playbackState)
|
|
152
|
+
|
|
153
|
+
player.play()
|
|
154
|
+
idleUntil("the reconnect") {
|
|
155
|
+
player.exoPlayer.playbackState != MediaPlayer.STATE_IDLE &&
|
|
156
|
+
player.playbackState in
|
|
157
|
+
setOf(PlaybackState.LOADING, PlaybackState.BUFFERING, PlaybackState.PLAYING)
|
|
158
|
+
}
|
|
159
|
+
assertTrue(player.exoPlayer.currentPosition < 30_000)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@Test
|
|
163
|
+
fun `a seekable live pause keeps its position, and play resumes from it`() {
|
|
164
|
+
playLiveHls(segments = 12)
|
|
165
|
+
player.seekTo(30, TimeUnit.SECONDS)
|
|
166
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
167
|
+
|
|
168
|
+
player.pause()
|
|
169
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
170
|
+
assertPausedInPlace()
|
|
171
|
+
assertEquals(30_000L, player.exoPlayer.currentPosition)
|
|
172
|
+
|
|
173
|
+
player.play()
|
|
174
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
175
|
+
assertNotEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
|
|
176
|
+
assertEquals(30_000L, player.exoPlayer.currentPosition)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
@Test
|
|
180
|
+
fun `a jump to the live edge while a seekable live track is paused moves to the window end`() {
|
|
181
|
+
val edge = playLiveHls(segments = 12)
|
|
182
|
+
player.seekTo(0, TimeUnit.SECONDS)
|
|
183
|
+
player.pause()
|
|
184
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
185
|
+
|
|
186
|
+
player.seekToLiveEdge()
|
|
187
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
188
|
+
assertEquals(edge, player.exoPlayer.currentPosition)
|
|
189
|
+
assertPausedInPlace()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
@Test
|
|
193
|
+
fun `a live window shorter than a pause is worth idles the engine like a stream with none`() {
|
|
194
|
+
playLiveHls(segments = 3)
|
|
195
|
+
player.pause()
|
|
196
|
+
assertStaysPausedAndIdle()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Not playing, the engine loaded: READY once a load finishes while paused. */
|
|
200
|
+
private fun assertPausedInPlace() {
|
|
201
|
+
assertTrue(player.playbackState in setOf(PlaybackState.PAUSED, PlaybackState.READY))
|
|
202
|
+
assertNotEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Plays a live HLS playlist of 10-second segments until its window is known, its media unloaded
|
|
207
|
+
* as the audio track is disabled.
|
|
208
|
+
*
|
|
209
|
+
* @return the window's default position, the live edge it starts at.
|
|
210
|
+
*/
|
|
211
|
+
private fun playLiveHls(segments: Int): Long {
|
|
212
|
+
play(folder.liveHlsUri(segments), live = true)
|
|
213
|
+
idleUntil("the live window") { liveWindow()?.isPlaceholder == false }
|
|
214
|
+
return liveWindow()!!.defaultPositionMs
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private fun liveWindow(): Timeline.Window? {
|
|
218
|
+
val timeline = player.exoPlayer.currentTimeline
|
|
219
|
+
if (timeline.isEmpty) return null
|
|
220
|
+
return timeline.getWindow(player.exoPlayer.currentMediaItemIndex, Timeline.Window())
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
@Test
|
|
224
|
+
fun `an on-demand pause keeps the engine loaded`() {
|
|
225
|
+
play(folder.silentWavUri(Duration.ofMinutes(1)))
|
|
226
|
+
idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
|
|
227
|
+
|
|
228
|
+
player.pause()
|
|
229
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
230
|
+
|
|
231
|
+
assertEquals(PlaybackState.PAUSED, player.playbackState)
|
|
232
|
+
assertEquals(MediaPlayer.STATE_READY, player.exoPlayer.playbackState)
|
|
233
|
+
}
|
|
234
|
+
|
|
136
235
|
/** Pauses with a retry pending and runs past every backoff it would have taken. */
|
|
137
236
|
private fun pauseDuringRetry(vararg next: String, pause: () -> Unit) {
|
|
138
237
|
play("https://127.0.0.1:9/stream", *next, retryPolicy = RetryPolicy.Infinite())
|
|
@@ -501,6 +600,37 @@ class PlayerRetryTest {
|
|
|
501
600
|
assertEquals(null, player.playbackError)
|
|
502
601
|
}
|
|
503
602
|
|
|
603
|
+
@Test
|
|
604
|
+
fun `a seek over a held connection failure is a new connection for the loop`() {
|
|
605
|
+
goOnline(context)
|
|
606
|
+
play(folder.silentWavUri(Duration.ofMinutes(1)), retryPolicy = RetryPolicy.Infinite())
|
|
607
|
+
idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
|
|
608
|
+
player.onLoadFailure(IOException("dropped"), inPlace = false)
|
|
609
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
610
|
+
assertTrue("the failure is held", player.retryLoop!!.failurePending)
|
|
611
|
+
|
|
612
|
+
player.seekTo(10, TimeUnit.SECONDS)
|
|
613
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
614
|
+
|
|
615
|
+
assertFalse(player.retryLoop!!.failurePending)
|
|
616
|
+
assertFalse(player.retryLoop!!.reconnecting)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
@Test
|
|
620
|
+
fun `a failure report that arrives after a seek is not the new connection's`() {
|
|
621
|
+
goOnline(context)
|
|
622
|
+
play(folder.silentWavUri(Duration.ofMinutes(1)), retryPolicy = RetryPolicy.Infinite())
|
|
623
|
+
idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
|
|
624
|
+
|
|
625
|
+
// Posted from the playback thread before the seek, run after it.
|
|
626
|
+
player.onLoadFailure(IOException("dropped"), inPlace = false)
|
|
627
|
+
player.seekTo(10, TimeUnit.SECONDS)
|
|
628
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
629
|
+
|
|
630
|
+
assertFalse(player.retryLoop!!.failurePending)
|
|
631
|
+
assertEquals(null, player.playbackError)
|
|
632
|
+
}
|
|
633
|
+
|
|
504
634
|
@Test
|
|
505
635
|
fun `with retry, a stuck engine reconnects and never ends in an error`() {
|
|
506
636
|
goOnline(context)
|
|
@@ -570,6 +700,7 @@ class PlayerRetryTest {
|
|
|
570
700
|
vararg srcs: String,
|
|
571
701
|
retryPolicy: RetryPolicy = RetryPolicy.Default,
|
|
572
702
|
wakeMode: AndroidPlayerWakeMode = AndroidPlayerWakeMode.NONE,
|
|
703
|
+
live: Boolean? = null,
|
|
573
704
|
) {
|
|
574
705
|
player.setup(PlayerSetupOptions(retryPolicy = retryPolicy, wakeMode = wakeMode))
|
|
575
706
|
player.setCallbacks(callbacks)
|
|
@@ -580,7 +711,7 @@ class PlayerRetryTest {
|
|
|
580
711
|
.build()
|
|
581
712
|
player.exoPlayer.setMediaItems(
|
|
582
713
|
srcs.mapIndexed { i, src ->
|
|
583
|
-
TrackFactory.toMedia3(TestFixtures.track(title = "$i", src = src))
|
|
714
|
+
TrackFactory.toMedia3(TestFixtures.track(title = "$i", src = src, live = live))
|
|
584
715
|
}
|
|
585
716
|
)
|
|
586
717
|
player.exoPlayer.prepare()
|
|
@@ -3,9 +3,14 @@ package com.audiobrowser.player
|
|
|
3
3
|
import android.net.Uri
|
|
4
4
|
import androidx.media3.common.C
|
|
5
5
|
import androidx.media3.common.ParserException
|
|
6
|
+
import androidx.media3.database.StandaloneDatabaseProvider
|
|
6
7
|
import androidx.media3.datasource.DataSourceException
|
|
7
8
|
import androidx.media3.datasource.DataSpec
|
|
8
9
|
import androidx.media3.datasource.HttpDataSource
|
|
10
|
+
import androidx.media3.datasource.cache.Cache
|
|
11
|
+
import androidx.media3.datasource.cache.ContentMetadataMutations
|
|
12
|
+
import androidx.media3.datasource.cache.NoOpCacheEvictor
|
|
13
|
+
import androidx.media3.datasource.cache.SimpleCache
|
|
9
14
|
import androidx.media3.exoplayer.source.LoadEventInfo
|
|
10
15
|
import androidx.media3.exoplayer.source.MediaLoadData
|
|
11
16
|
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy
|
|
@@ -15,20 +20,22 @@ import java.io.FileNotFoundException
|
|
|
15
20
|
import java.io.IOException
|
|
16
21
|
import java.net.SocketTimeoutException
|
|
17
22
|
import java.net.UnknownHostException
|
|
23
|
+
import java.nio.file.Files
|
|
18
24
|
import org.junit.Assert.assertEquals
|
|
19
25
|
import org.junit.Assert.assertTrue
|
|
20
26
|
import org.junit.Test
|
|
21
27
|
import org.junit.runner.RunWith
|
|
22
28
|
import org.mockito.Mockito.mock
|
|
23
29
|
import org.robolectric.RobolectricTestRunner
|
|
30
|
+
import org.robolectric.RuntimeEnvironment
|
|
24
31
|
|
|
25
32
|
@RunWith(RobolectricTestRunner::class)
|
|
26
33
|
class RetryLoadErrorHandlingPolicyTest {
|
|
27
34
|
private val failures = mutableListOf<Boolean>()
|
|
28
35
|
private var current = true
|
|
29
36
|
|
|
30
|
-
private fun policy(sources: Sources) =
|
|
31
|
-
RetryLoadErrorHandlingPolicy(sources, { current }) { _, inPlace -> failures += inPlace }
|
|
37
|
+
private fun policy(sources: Sources, cache: Cache? = null) =
|
|
38
|
+
RetryLoadErrorHandlingPolicy(sources, { current }, cache) { _, inPlace -> failures += inPlace }
|
|
32
39
|
|
|
33
40
|
private fun errorInfo(
|
|
34
41
|
exception: IOException = UnknownHostException("dead host"),
|
|
@@ -102,6 +109,28 @@ class RetryLoadErrorHandlingPolicyTest {
|
|
|
102
109
|
assertEquals(listOf(true, true, false), failures)
|
|
103
110
|
}
|
|
104
111
|
|
|
112
|
+
@Test
|
|
113
|
+
fun `a file of known length read from the cache stays in place when the switch upstream fails`() {
|
|
114
|
+
val cache =
|
|
115
|
+
SimpleCache(
|
|
116
|
+
Files.createTempDirectory("cache").toFile(),
|
|
117
|
+
NoOpCacheEvictor(),
|
|
118
|
+
StandaloneDatabaseProvider(RuntimeEnvironment.getApplication()),
|
|
119
|
+
)
|
|
120
|
+
try {
|
|
121
|
+
cache.applyContentMetadataMutations(
|
|
122
|
+
"https://example.com/stream",
|
|
123
|
+
ContentMetadataMutations().also { ContentMetadataMutations.setContentLength(it, 1234) },
|
|
124
|
+
)
|
|
125
|
+
val policy = policy(Sources.PROGRESSIVE, cache)
|
|
126
|
+
|
|
127
|
+
assertEquals(1000L, policy.getRetryDelayMsFor(errorInfo()))
|
|
128
|
+
assertEquals(listOf(true), failures)
|
|
129
|
+
} finally {
|
|
130
|
+
cache.release()
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
105
134
|
@Test
|
|
106
135
|
fun `an item that only preloads retries in place and reports nothing`() {
|
|
107
136
|
current = false
|
package/ios/AVPlayerEngine.swift
CHANGED
|
@@ -123,6 +123,14 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
123
123
|
return range.end.seconds
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
+
var liveWindowSeconds: Double? {
|
|
127
|
+
guard let item = avPlayer.currentItem, item.duration.isIndefinite,
|
|
128
|
+
let seconds = item.seekableTimeRanges.last?.timeRangeValue.duration.seconds,
|
|
129
|
+
seconds.isFinite, seconds > 0
|
|
130
|
+
else { return nil }
|
|
131
|
+
return seconds
|
|
132
|
+
}
|
|
133
|
+
|
|
126
134
|
var isPlaybackLikelyToKeepUp: Bool {
|
|
127
135
|
avPlayer.currentItem?.isPlaybackLikelyToKeepUp ?? false
|
|
128
136
|
}
|
|
@@ -138,9 +146,9 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
138
146
|
|
|
139
147
|
// MARK: - Loading
|
|
140
148
|
|
|
141
|
-
func resolveAndLoad(src: String, track: Track) {
|
|
149
|
+
func resolveAndLoad(src: String, track: Track, shortStartBuffer: Bool) {
|
|
142
150
|
icyCharset = track.icyCharset
|
|
143
|
-
mediaLoader.resolveAndLoad(src: src, track: track)
|
|
151
|
+
mediaLoader.resolveAndLoad(src: src, track: track, shortStartBuffer: shortStartBuffer)
|
|
144
152
|
}
|
|
145
153
|
|
|
146
154
|
func cancelLoading() {
|
|
@@ -157,6 +165,13 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
157
165
|
avPlayer.replaceCurrentItem(with: nil)
|
|
158
166
|
}
|
|
159
167
|
|
|
168
|
+
func replaceItemWithNowPlayingCarrier() {
|
|
169
|
+
dropAsset()
|
|
170
|
+
let carrier = AVPlayerItem(asset: AVMutableComposition())
|
|
171
|
+
nowPlayingInfoController.prepareItem(carrier)
|
|
172
|
+
avPlayer.replaceCurrentItem(with: carrier)
|
|
173
|
+
}
|
|
174
|
+
|
|
160
175
|
func stopObservingItem() {
|
|
161
176
|
itemObserver?.invalidate()
|
|
162
177
|
itemObserver = nil
|
|
@@ -192,6 +207,10 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
192
207
|
avPlayer.pause()
|
|
193
208
|
}
|
|
194
209
|
|
|
210
|
+
func capForwardBuffer(_ seconds: Double?) {
|
|
211
|
+
avPlayer.currentItem?.preferredForwardBufferDuration = seconds ?? bufferDuration / 1000
|
|
212
|
+
}
|
|
213
|
+
|
|
195
214
|
func setRate(_ rate: Float, playing: Bool) {
|
|
196
215
|
self.rate = rate
|
|
197
216
|
avPlayer.defaultRate = rate
|
|
@@ -289,6 +308,9 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
289
308
|
|
|
290
309
|
private func itemDidEmit(_ event: ItemObserver.Event) {
|
|
291
310
|
switch event {
|
|
311
|
+
case .readyToPlay:
|
|
312
|
+
// Ends the short start buffer `MediaLoader.resolveAndLoad` may have given the item.
|
|
313
|
+
avPlayer.currentItem?.preferredForwardBufferDuration = bufferDuration / 1000
|
|
292
314
|
case let .likelyToKeepUp(isLikely): onEvent?(.likelyToKeepUp(isLikely))
|
|
293
315
|
case let .failed(error), let .failedToPlayToEnd(error): reportFailure(error)
|
|
294
316
|
case .playedToEnd: onEvent?(.playedToEnd)
|
|
@@ -12,6 +12,7 @@ extension AVTimedMetadataGroup: @retroactive @unchecked Sendable {}
|
|
|
12
12
|
final class ItemObserver: NSObject {
|
|
13
13
|
enum Event {
|
|
14
14
|
case likelyToKeepUp(Bool)
|
|
15
|
+
case readyToPlay
|
|
15
16
|
case failed(Error?)
|
|
16
17
|
case playedToEnd
|
|
17
18
|
case failedToPlayToEnd(Error?)
|
|
@@ -37,9 +38,15 @@ final class ItemObserver: NSObject {
|
|
|
37
38
|
Task { @MainActor in self?.emit(.likelyToKeepUp(isLikely)) }
|
|
38
39
|
},
|
|
39
40
|
item.observe(\.status, options: [.new]) { [weak self] item, _ in
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
switch item.status {
|
|
42
|
+
case .readyToPlay:
|
|
43
|
+
Task { @MainActor in self?.emit(.readyToPlay) }
|
|
44
|
+
case .failed:
|
|
45
|
+
let error = item.error
|
|
46
|
+
Task { @MainActor in self?.emit(.failed(error)) }
|
|
47
|
+
default:
|
|
48
|
+
break
|
|
49
|
+
}
|
|
43
50
|
},
|
|
44
51
|
]
|
|
45
52
|
notificationTokens = [
|
|
@@ -51,7 +51,10 @@ final class MediaLoader {
|
|
|
51
51
|
/// Resolves `src` and loads the result, reporting through `onEvent`. Cancels a resolve in
|
|
52
52
|
/// flight; the previous asset's loads stay current, and can still report, until the new
|
|
53
53
|
/// resolve loads an asset (an invalid source leaves them current).
|
|
54
|
-
|
|
54
|
+
/// - Parameter shortStartBuffer: The item's forward buffer is 1 s, or the configured one when
|
|
55
|
+
/// shorter, until its owner restores `bufferDuration`. An item becomes ready only once its
|
|
56
|
+
/// forward buffer is filled: by default about 4.5 s of a progressive stream, whatever the bitrate.
|
|
57
|
+
func resolveAndLoad(src: String, track: Track? = nil, shortStartBuffer: Bool = false) {
|
|
55
58
|
mediaResolverTask?.cancel()
|
|
56
59
|
// `self` stays weak across the await: a consumer resolver that never settles must not pin
|
|
57
60
|
// the loader.
|
|
@@ -60,11 +63,11 @@ final class MediaLoader {
|
|
|
60
63
|
guard !Task.isCancelled else { return }
|
|
61
64
|
let resolved = await resolveUrl(src, track)
|
|
62
65
|
guard !Task.isCancelled, let self else { return }
|
|
63
|
-
loadWithResolvedUrl(resolved)
|
|
66
|
+
loadWithResolvedUrl(resolved, shortStartBuffer: shortStartBuffer)
|
|
64
67
|
}
|
|
65
68
|
}
|
|
66
69
|
|
|
67
|
-
private func loadAsset(url: URL, options: [String: Any]
|
|
70
|
+
private func loadAsset(url: URL, options: [String: Any]?, shortStartBuffer: Bool) {
|
|
68
71
|
let pendingAsset = AVURLAsset(url: url, options: options)
|
|
69
72
|
asset = pendingAsset
|
|
70
73
|
|
|
@@ -124,7 +127,9 @@ final class MediaLoader {
|
|
|
124
127
|
return
|
|
125
128
|
}
|
|
126
129
|
let avItem = AVPlayerItem(asset: pendingAsset)
|
|
127
|
-
avItem.preferredForwardBufferDuration =
|
|
130
|
+
avItem.preferredForwardBufferDuration = shortStartBuffer
|
|
131
|
+
? min(1, bufferDuration > 0 ? bufferDuration / 1000 : 1)
|
|
132
|
+
: bufferDuration / 1000
|
|
128
133
|
onEvent?(.prepared(avItem))
|
|
129
134
|
} catch {
|
|
130
135
|
guard isCurrent(pendingAsset) else { return }
|
|
@@ -177,7 +182,7 @@ final class MediaLoader {
|
|
|
177
182
|
|
|
178
183
|
// MARK: - Private
|
|
179
184
|
|
|
180
|
-
private func loadWithResolvedUrl(_ resolved: MediaResolvedUrl) {
|
|
185
|
+
private func loadWithResolvedUrl(_ resolved: MediaResolvedUrl, shortStartBuffer: Bool) {
|
|
181
186
|
guard let mediaUrl = URL(string: resolved.url) else {
|
|
182
187
|
logger.error("Invalid media URL: \(resolved.url)")
|
|
183
188
|
onEvent?(.invalidSource(resolved.url))
|
|
@@ -187,6 +192,7 @@ final class MediaLoader {
|
|
|
187
192
|
loadAsset(
|
|
188
193
|
url: mediaUrl.isFileURL ? URL(fileURLWithPath: mediaUrl.path) : mediaUrl,
|
|
189
194
|
options: Self.buildAssetOptions(headers: resolved.headers, userAgent: resolved.userAgent),
|
|
195
|
+
shortStartBuffer: shortStartBuffer,
|
|
190
196
|
)
|
|
191
197
|
}
|
|
192
198
|
}
|