react-native-audio-browser 0.2.0-next.92 → 0.2.0-next.93
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/Player.kt +59 -2
- package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +1 -0
- 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 +101 -1
- 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
|
@@ -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
|
|
|
@@ -1237,6 +1262,38 @@ internal constructor(
|
|
|
1237
1262
|
stopRetrying()
|
|
1238
1263
|
}
|
|
1239
1264
|
|
|
1265
|
+
/**
|
|
1266
|
+
* A paused engine goes on loading a live stream until its buffer is full, and a resume plays what
|
|
1267
|
+
* it buffered, behind the stream. The engine idles in PAUSED instead, closing the connection, and
|
|
1268
|
+
* the next play's prepare() reconnects at the live edge.
|
|
1269
|
+
*/
|
|
1270
|
+
internal fun dropLiveConnection() {
|
|
1271
|
+
if (currentTrack?.live != true || !localEngine.isActive || liveItemPausable) return
|
|
1272
|
+
if (playbackState !in LIVE_CONNECTION_STATES) return
|
|
1273
|
+
if (exoPlayer.playbackState == ExoPlayer.STATE_IDLE) return
|
|
1274
|
+
stopRetrying()
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/** A live window that seeks at least [PAUSABLE_LIVE_WINDOW_MS] behind its live edge. */
|
|
1278
|
+
private val liveItemPausable: Boolean
|
|
1279
|
+
get() {
|
|
1280
|
+
val timeline = exoPlayer.currentTimeline
|
|
1281
|
+
if (timeline.isEmpty) return false
|
|
1282
|
+
val window = timeline.getWindow(exoPlayer.currentMediaItemIndex, Timeline.Window())
|
|
1283
|
+
return window.isDynamic &&
|
|
1284
|
+
window.isSeekable &&
|
|
1285
|
+
!window.isPlaceholder &&
|
|
1286
|
+
window.defaultPositionMs >= PAUSABLE_LIVE_WINDOW_MS
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** A live track paused on an idle engine: it reconnects only to play, at the live edge. */
|
|
1290
|
+
private val liveStreamParked: Boolean
|
|
1291
|
+
get() =
|
|
1292
|
+
currentTrack?.live == true &&
|
|
1293
|
+
!playWhenReady &&
|
|
1294
|
+
localEngine.isActive &&
|
|
1295
|
+
exoPlayer.playbackState == ExoPlayer.STATE_IDLE
|
|
1296
|
+
|
|
1240
1297
|
/**
|
|
1241
1298
|
* Gives up a load ExoPlayer would retry. The engine idles in PAUSED, where the next prepare()
|
|
1242
1299
|
* reloads where it failed.
|
|
@@ -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()
|
|
@@ -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())
|
|
@@ -570,6 +669,7 @@ class PlayerRetryTest {
|
|
|
570
669
|
vararg srcs: String,
|
|
571
670
|
retryPolicy: RetryPolicy = RetryPolicy.Default,
|
|
572
671
|
wakeMode: AndroidPlayerWakeMode = AndroidPlayerWakeMode.NONE,
|
|
672
|
+
live: Boolean? = null,
|
|
573
673
|
) {
|
|
574
674
|
player.setup(PlayerSetupOptions(retryPolicy = retryPolicy, wakeMode = wakeMode))
|
|
575
675
|
player.setCallbacks(callbacks)
|
|
@@ -580,7 +680,7 @@ class PlayerRetryTest {
|
|
|
580
680
|
.build()
|
|
581
681
|
player.exoPlayer.setMediaItems(
|
|
582
682
|
srcs.mapIndexed { i, src ->
|
|
583
|
-
TrackFactory.toMedia3(TestFixtures.track(title = "$i", src = src))
|
|
683
|
+
TrackFactory.toMedia3(TestFixtures.track(title = "$i", src = src, live = live))
|
|
584
684
|
}
|
|
585
685
|
)
|
|
586
686
|
player.exoPlayer.prepare()
|
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
|
}
|