react-native-audio-browser 0.2.0-next.91 → 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/ConnectionEndSource.kt +145 -0
- package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +7 -2
- 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/LiveStreamEndTest.kt +183 -6
- package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +101 -1
- package/android/src/test/java/com/audiobrowser/player/PlayerSuppressionTest.kt +27 -16
- 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
|
@@ -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()
|
|
@@ -38,7 +38,8 @@ import org.robolectric.Shadows.shadowOf
|
|
|
38
38
|
import org.robolectric.annotation.Config
|
|
39
39
|
|
|
40
40
|
// Robolectric's clock stands still, so a delayed message on ExoPlayer's playback thread never
|
|
41
|
-
// runs: the audio track is disabled because an audio renderer can wait in BUFFERING on one.
|
|
41
|
+
// runs: the audio track is disabled because an audio renderer can wait in BUFFERING on one. A
|
|
42
|
+
// rebuild builds an engine with it enabled, so idle() disables it on each new engine.
|
|
42
43
|
// SDK 28: from 33, media3 asks AudioManager.getAudioDevicesForAttributes, which Robolectric 4.11
|
|
43
44
|
// answers with null.
|
|
44
45
|
@RunWith(RobolectricTestRunner::class)
|
|
@@ -64,11 +65,7 @@ class PlayerSuppressionTest {
|
|
|
64
65
|
player.setup(PlayerSetupOptions())
|
|
65
66
|
player.setCallbacks(callbacks)
|
|
66
67
|
val src = folder.silentWavUri(Duration.ofMinutes(1))
|
|
67
|
-
|
|
68
|
-
player.exoPlayer.trackSelectionParameters
|
|
69
|
-
.buildUpon()
|
|
70
|
-
.setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
|
|
71
|
-
.build()
|
|
68
|
+
disableAudio()
|
|
72
69
|
player.exoPlayer.setMediaItems(
|
|
73
70
|
listOf(TrackFactory.toMedia3(TestFixtures.track(title = "a", src = src)))
|
|
74
71
|
)
|
|
@@ -131,7 +128,7 @@ class PlayerSuppressionTest {
|
|
|
131
128
|
audioManager.setNextFocusRequestResponse(AudioManager.AUDIOFOCUS_REQUEST_FAILED)
|
|
132
129
|
|
|
133
130
|
player.togglePlayback()
|
|
134
|
-
|
|
131
|
+
idle()
|
|
135
132
|
assertEquals(PlaybackState.PAUSED, player.playbackState)
|
|
136
133
|
focus(AudioManager.AUDIOFOCUS_GAIN)
|
|
137
134
|
|
|
@@ -157,7 +154,7 @@ class PlayerSuppressionTest {
|
|
|
157
154
|
val engine = player.exoPlayer
|
|
158
155
|
|
|
159
156
|
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
160
|
-
|
|
157
|
+
idle()
|
|
161
158
|
|
|
162
159
|
assertSame(engine, player.exoPlayer)
|
|
163
160
|
assertSuppressed()
|
|
@@ -175,7 +172,7 @@ class PlayerSuppressionTest {
|
|
|
175
172
|
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
176
173
|
// ExoPlayer requests focus on its playback thread and posts a refusal back.
|
|
177
174
|
Thread.sleep(200)
|
|
178
|
-
|
|
175
|
+
idle()
|
|
179
176
|
|
|
180
177
|
assertSuppressed()
|
|
181
178
|
audioManager.setNextFocusRequestResponse(AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
|
|
@@ -200,7 +197,7 @@ class PlayerSuppressionTest {
|
|
|
200
197
|
assertSame(engine, player.exoPlayer)
|
|
201
198
|
drop()
|
|
202
199
|
|
|
203
|
-
|
|
200
|
+
idle()
|
|
204
201
|
|
|
205
202
|
assertNotSame(engine, player.exoPlayer)
|
|
206
203
|
assertFalse(player.exoPlayer.playWhenReady)
|
|
@@ -219,7 +216,7 @@ class PlayerSuppressionTest {
|
|
|
219
216
|
player.play()
|
|
220
217
|
// The rebuild follows the play: it is posted, never run inside it.
|
|
221
218
|
assertSame(engine, player.exoPlayer)
|
|
222
|
-
|
|
219
|
+
idle()
|
|
223
220
|
|
|
224
221
|
assertNotSame(engine, player.exoPlayer)
|
|
225
222
|
idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
|
|
@@ -230,7 +227,7 @@ class PlayerSuppressionTest {
|
|
|
230
227
|
focus(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
|
|
231
228
|
// As a handover to a remote output does: the engine stops but keeps the intent.
|
|
232
229
|
player.exoPlayer.stop()
|
|
233
|
-
|
|
230
|
+
idle()
|
|
234
231
|
val engine = player.exoPlayer
|
|
235
232
|
|
|
236
233
|
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
@@ -259,7 +256,7 @@ class PlayerSuppressionTest {
|
|
|
259
256
|
|
|
260
257
|
remote.startSession()
|
|
261
258
|
idleUntil("remote") { !player.localEngine.isActive }
|
|
262
|
-
|
|
259
|
+
idle()
|
|
263
260
|
|
|
264
261
|
assertNotSame(engine, player.exoPlayer)
|
|
265
262
|
assertFalse(player.localEngine.isActive)
|
|
@@ -274,7 +271,7 @@ class PlayerSuppressionTest {
|
|
|
274
271
|
|
|
275
272
|
// As a terminal error does: the engine idles with the intent and the suppression unchanged.
|
|
276
273
|
player.exoPlayer.stop()
|
|
277
|
-
|
|
274
|
+
idle()
|
|
278
275
|
|
|
279
276
|
assertNotSame(engine, player.exoPlayer)
|
|
280
277
|
}
|
|
@@ -319,7 +316,7 @@ class PlayerSuppressionTest {
|
|
|
319
316
|
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
320
317
|
|
|
321
318
|
player.destroy()
|
|
322
|
-
|
|
319
|
+
idle()
|
|
323
320
|
|
|
324
321
|
assertSame(engine, player.exoPlayer)
|
|
325
322
|
}
|
|
@@ -348,7 +345,21 @@ class PlayerSuppressionTest {
|
|
|
348
345
|
"exo ${player.exoPlayer.playbackState}, ${player.exoPlayer.playerError}"
|
|
349
346
|
)
|
|
350
347
|
Thread.sleep(10)
|
|
351
|
-
|
|
348
|
+
idle()
|
|
352
349
|
}
|
|
353
350
|
}
|
|
351
|
+
|
|
352
|
+
private fun idle() {
|
|
353
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
354
|
+
if (C.TRACK_TYPE_AUDIO !in player.exoPlayer.trackSelectionParameters.disabledTrackTypes)
|
|
355
|
+
disableAudio()
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private fun disableAudio() {
|
|
359
|
+
player.exoPlayer.trackSelectionParameters =
|
|
360
|
+
player.exoPlayer.trackSelectionParameters
|
|
361
|
+
.buildUpon()
|
|
362
|
+
.setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
|
|
363
|
+
.build()
|
|
364
|
+
}
|
|
354
365
|
}
|
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
|
}
|
package/ios/Player/Player.swift
CHANGED
|
@@ -21,6 +21,7 @@ final class Player {
|
|
|
21
21
|
let retry: RetryLoop
|
|
22
22
|
let sleepTimerManager: SleepTimerManager
|
|
23
23
|
var deferredSeek = DeferredSeek()
|
|
24
|
+
private let scheduler: any SleepTimerScheduling
|
|
24
25
|
|
|
25
26
|
private lazy var progressTimer = PlaybackTimer(
|
|
26
27
|
isActive: { $0 == .loading || $0 == .buffering || $0 == .playing },
|
|
@@ -53,7 +54,7 @@ final class Player {
|
|
|
53
54
|
var primedNowPlaying = false
|
|
54
55
|
/// One of this load's items is in the engine; until then it reports the previous one's position.
|
|
55
56
|
var itemPrepared = false
|
|
56
|
-
/// A pause
|
|
57
|
+
/// A pause parked this load, cancelling its retry or dropping a live item: the next play reloads.
|
|
57
58
|
var reloadOnPlay = false
|
|
58
59
|
|
|
59
60
|
mutating func claimNowPlayingPrime() -> Bool {
|
|
@@ -69,6 +70,7 @@ final class Player {
|
|
|
69
70
|
/// Starts a Load: a track becoming current, or a restart of this one from a terminal error.
|
|
70
71
|
/// Fresh retry budgets, no pending seek, unproven playback.
|
|
71
72
|
private func beginLoad() {
|
|
73
|
+
cancelIdleLivePark()
|
|
72
74
|
loadCount &+= 1
|
|
73
75
|
load = Load(id: loadCount)
|
|
74
76
|
retry.loadStarted()
|
|
@@ -106,8 +108,8 @@ final class Player {
|
|
|
106
108
|
}
|
|
107
109
|
}
|
|
108
110
|
|
|
109
|
-
/// Whether the engine's item is not this Load's playable one: one loads, or a pause
|
|
110
|
-
///
|
|
111
|
+
/// Whether the engine's item is not this Load's playable one: one loads, or a pause parked the
|
|
112
|
+
/// load. A seek waits for the next item meanwhile.
|
|
111
113
|
private var awaitingItem: Bool {
|
|
112
114
|
state == .loading || load?.reloadOnPlay == true
|
|
113
115
|
}
|
|
@@ -190,6 +192,10 @@ final class Player {
|
|
|
190
192
|
}
|
|
191
193
|
// While loading, the engine may still hold the previous track's item: a play waits for the new one.
|
|
192
194
|
if !newValue { engine.pause() } else if state != .loading { engine.play() }
|
|
195
|
+
if changed, !newValue { parkIdleLiveStream() }
|
|
196
|
+
if changed, currentTrack?.live == true, liveItemPausable {
|
|
197
|
+
engine.capForwardBuffer(newValue ? nil : Self.pausedLiveBufferSeconds)
|
|
198
|
+
}
|
|
193
199
|
|
|
194
200
|
guard changed else { return }
|
|
195
201
|
// A resume can find the state still .buffering (a pause near the end leaves it) or .loading,
|
|
@@ -238,6 +244,7 @@ final class Player {
|
|
|
238
244
|
self.engine = engine
|
|
239
245
|
self.callbacks = callbacks
|
|
240
246
|
self.retry = retry
|
|
247
|
+
self.scheduler = sleepTimerScheduler
|
|
241
248
|
sleepTimerManager = SleepTimerManager(
|
|
242
249
|
fader: VolumeFader(
|
|
243
250
|
getVolume: { [weak engine] in engine?.volume ?? 1 },
|
|
@@ -262,7 +269,7 @@ final class Player {
|
|
|
262
269
|
}
|
|
263
270
|
retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
|
|
264
271
|
retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
|
|
265
|
-
retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
|
|
272
|
+
retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0, shortStartBuffer: true) }
|
|
266
273
|
// Until the connect's item is prepared, the engine still holds the item it replaces.
|
|
267
274
|
retry.bufferedPosition = { [weak self] in
|
|
268
275
|
guard let self, connectionItemPrepared else { return 0 }
|
|
@@ -404,12 +411,18 @@ final class Player {
|
|
|
404
411
|
// A pending retry would turn the stop into .error, and the next play must start over rather
|
|
405
412
|
// than resume where it failed. Cancelled first, or the lowered intent parks it for a reload.
|
|
406
413
|
retry.cancel()
|
|
407
|
-
load?.reloadOnPlay = false
|
|
408
414
|
shouldResumeAfterInterruption = false
|
|
409
415
|
engine.clearTimedMetadata()
|
|
416
|
+
// Closed here, as dropping the intent would close it on the way to .stopped through .paused.
|
|
417
|
+
// A stop during a deferred park leaves the previous track's item in the engine: closed too.
|
|
418
|
+
if holdsLiveConnection || pendingIdleLivePark != nil {
|
|
419
|
+
cancelIdleLivePark()
|
|
420
|
+
closeLiveConnection()
|
|
421
|
+
}
|
|
410
422
|
// Before the transition, whose render the formatter reads the intent from.
|
|
411
423
|
setPlayWhenReady(false)
|
|
412
424
|
transition(.stopped)
|
|
425
|
+
load?.reloadOnPlay = false
|
|
413
426
|
deferredSeek.reset()
|
|
414
427
|
if currentTrack?.live != true { seek(to: 0) }
|
|
415
428
|
}
|
|
@@ -465,10 +478,19 @@ final class Player {
|
|
|
465
478
|
/// Applies `false` before `action` and `true` after it; nil leaves the intent alone.
|
|
466
479
|
private func handlePlayWhenReady(_ playWhenReady: Bool?, action: () throws -> Void) rethrows {
|
|
467
480
|
if playWhenReady == false { setPlayWhenReady(false) }
|
|
481
|
+
let outerIntentFollows = playIntentFollows
|
|
482
|
+
playIntentFollows = playWhenReady == true
|
|
483
|
+
defer { playIntentFollows = outerIntentFollows }
|
|
468
484
|
try action()
|
|
469
485
|
if playWhenReady == true { setPlayWhenReady(true) }
|
|
470
486
|
}
|
|
471
487
|
|
|
488
|
+
/// The running operation raises the intent once its action is done: a live track it loads
|
|
489
|
+
/// connects for that play rather than park first.
|
|
490
|
+
private var playIntentFollows = false
|
|
491
|
+
|
|
492
|
+
private var toPlay: Bool { playWhenReady || playIntentFollows }
|
|
493
|
+
|
|
472
494
|
// MARK: - Queue Methods
|
|
473
495
|
|
|
474
496
|
private func throwIfInvalid(_ tracks: [Track]) throws {
|
|
@@ -668,9 +690,11 @@ final class Player {
|
|
|
668
690
|
|
|
669
691
|
/// Seeks the current item. While it awaits the next item, or in .error for the restart, the
|
|
670
692
|
/// target is held until the next item is ready and the ready transition waits for it
|
|
671
|
-
/// (`DeferredSeek`); `completion` then reports false at once.
|
|
693
|
+
/// (`DeferredSeek`); `completion` then reports false at once. A parked live stream ignores it.
|
|
672
694
|
func seek(to seconds: TimeInterval, completion: @escaping @MainActor (Bool) -> Void = { _ in }) {
|
|
673
|
-
if
|
|
695
|
+
if liveStreamClosed {
|
|
696
|
+
completion(false)
|
|
697
|
+
} else if awaitingItem || state == .error {
|
|
674
698
|
deferredSeek.capture(seconds)
|
|
675
699
|
completion(false)
|
|
676
700
|
} else if engine.hasItem {
|
|
@@ -681,7 +705,9 @@ final class Player {
|
|
|
681
705
|
}
|
|
682
706
|
|
|
683
707
|
func seek(by offset: TimeInterval) {
|
|
684
|
-
if
|
|
708
|
+
if liveStreamClosed {
|
|
709
|
+
return
|
|
710
|
+
} else if awaitingItem || state == .error {
|
|
685
711
|
seek(to: (resumePosition ?? 0) + offset)
|
|
686
712
|
} else if engine.hasItem {
|
|
687
713
|
seek(to: engine.currentTime + offset)
|
|
@@ -690,9 +716,9 @@ final class Player {
|
|
|
690
716
|
|
|
691
717
|
/// Jumps to the live edge: the end of the seekable window when there is one; without one
|
|
692
718
|
/// (ICY), or in .error, whose item's window is stale, it reconnects. No-op for a track that
|
|
693
|
-
/// isn't live.
|
|
719
|
+
/// isn't live, or a parked one, whose next play reconnects at the edge.
|
|
694
720
|
func seekToLiveEdge() {
|
|
695
|
-
guard currentTrack?.live == true, engine.hasItem else { return }
|
|
721
|
+
guard currentTrack?.live == true, engine.hasItem, !liveStreamClosed else { return }
|
|
696
722
|
if let edge = engine.liveEdge, state != .error {
|
|
697
723
|
seek(to: edge)
|
|
698
724
|
} else {
|
|
@@ -738,26 +764,31 @@ final class Player {
|
|
|
738
764
|
/// Loads the current track again, re-running the media-URL resolver, so a consumer whose
|
|
739
765
|
/// resolver mints short-lived URLs or tokens recovers once they expire. A track without a `src`
|
|
740
766
|
/// fails as an invalid source; with no current track, nothing loads.
|
|
741
|
-
|
|
767
|
+
/// - Parameter shortStartBuffer: For the retry loop's reconnects, which would otherwise be silent
|
|
768
|
+
/// for seconds each: see `PlayerEngine.resolveAndLoad`.
|
|
769
|
+
func reloadResolving(startFromCurrentTime: Bool, shortStartBuffer: Bool = false) {
|
|
742
770
|
guard let track = currentTrack else { return }
|
|
743
771
|
guard let src = track.src else {
|
|
744
772
|
transition(.errorOccurred(.invalidSourceUrl("nil")))
|
|
745
773
|
return
|
|
746
774
|
}
|
|
747
775
|
prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
|
|
748
|
-
connect(src: src, track: track)
|
|
776
|
+
connect(src: src, track: track, shortStartBuffer: shortStartBuffer)
|
|
749
777
|
}
|
|
750
778
|
|
|
751
779
|
private var connectionItemPrepared = false
|
|
752
780
|
|
|
753
|
-
private func connect(src: String, track: Track) {
|
|
781
|
+
private func connect(src: String, track: Track, shortStartBuffer: Bool = false) {
|
|
782
|
+
if track.live == true, !toPlay { return deferIdleLivePark() }
|
|
754
783
|
connectionItemPrepared = false
|
|
755
784
|
retry.connectionStarted()
|
|
756
|
-
engine.resolveAndLoad(src: src, track: track)
|
|
785
|
+
engine.resolveAndLoad(src: src, track: track, shortStartBuffer: shortStartBuffer)
|
|
757
786
|
}
|
|
758
787
|
|
|
759
|
-
/// The caller's retry: reloads now, resuming where it was, in place of any retry pending.
|
|
788
|
+
/// The caller's retry: reloads now, resuming where it was, in place of any retry pending. A parked
|
|
789
|
+
/// live stream waits for its play.
|
|
760
790
|
func retryNow() {
|
|
791
|
+
guard !liveStreamClosed || toPlay else { return }
|
|
761
792
|
retry.cancel()
|
|
762
793
|
reloadResolving(startFromCurrentTime: true)
|
|
763
794
|
}
|
|
@@ -769,11 +800,74 @@ final class Player {
|
|
|
769
800
|
transition(.retryCancelled)
|
|
770
801
|
}
|
|
771
802
|
|
|
803
|
+
/// A live stream holds a connection only while it is to play: a paused AVPlayer goes on reading
|
|
804
|
+
/// one, on macOS for as long as it stays paused, and a resume would play what it buffered,
|
|
805
|
+
/// minutes behind the stream. Parked, the next play reconnects at the live edge.
|
|
806
|
+
private func parkIdleLiveStream() {
|
|
807
|
+
guard holdsLiveConnection, !toPlay else { return }
|
|
808
|
+
closeLiveConnection()
|
|
809
|
+
transition(.retryCancelled)
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
static let idleLiveParkDelaySeconds: TimeInterval = 1
|
|
813
|
+
/// The window behind its live edge that lets a live item pause in place, as on-demand does (a
|
|
814
|
+
/// DVR window). A shorter one is a stream that can't be rewound: a pause closes it.
|
|
815
|
+
static let pausableLiveWindowSeconds: TimeInterval = 30
|
|
816
|
+
/// A paused live item with a window goes on loading toward its edge at the stream's rate for as
|
|
817
|
+
/// long as it stays paused: capped while paused, so it stops this far ahead of the paused position.
|
|
818
|
+
static let pausedLiveBufferSeconds: TimeInterval = 10
|
|
819
|
+
|
|
820
|
+
private var liveItemPausable: Bool {
|
|
821
|
+
(engine.liveWindowSeconds ?? 0) >= Self.pausableLiveWindowSeconds
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
private var pendingIdleLivePark: (any SleepTimerJob)?
|
|
825
|
+
|
|
826
|
+
/// A live track loaded without play intent opens no connection and stays .loading, so a play
|
|
827
|
+
/// sent as a separate call (`setQueue`, then `play()`) connects with no `paused` between. With
|
|
828
|
+
/// no play after `idleLiveParkDelaySeconds`, it parks.
|
|
829
|
+
private func deferIdleLivePark() {
|
|
830
|
+
retry.cancel()
|
|
831
|
+
engine.cancelLoading()
|
|
832
|
+
load?.reloadOnPlay = true
|
|
833
|
+
cancelIdleLivePark()
|
|
834
|
+
pendingIdleLivePark = scheduler.schedule(after: Self.idleLiveParkDelaySeconds) { [weak self] in
|
|
835
|
+
guard let self else { return }
|
|
836
|
+
pendingIdleLivePark = nil
|
|
837
|
+
engine.replaceItemWithNowPlayingCarrier()
|
|
838
|
+
transition(.retryCancelled)
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
private func cancelIdleLivePark() {
|
|
843
|
+
pendingIdleLivePark?.cancel()
|
|
844
|
+
pendingIdleLivePark = nil
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/// A retry that gave up leaves its item in place, connected still: .error holds one too.
|
|
848
|
+
private var holdsLiveConnection: Bool {
|
|
849
|
+
currentTrack?.live == true && !liveItemPausable && (playbackActive || state == .error)
|
|
850
|
+
&& load?.reloadOnPlay != true
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/// Parked or stopped: its next play is at the live edge, so a seek has no position to go to.
|
|
854
|
+
private var liveStreamClosed: Bool {
|
|
855
|
+
currentTrack?.live == true && (load?.reloadOnPlay == true || state == .stopped && !liveItemPausable)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
private func closeLiveConnection() {
|
|
859
|
+
retry.cancel()
|
|
860
|
+
engine.cancelLoading()
|
|
861
|
+
engine.replaceItemWithNowPlayingCarrier()
|
|
862
|
+
load?.reloadOnPlay = true
|
|
863
|
+
}
|
|
864
|
+
|
|
772
865
|
/// A restart from a terminal error begins a new Load on a new AVPlayer; automatic retries
|
|
773
866
|
/// never get here in .error, since the retry loop keeps the state non-terminal, but get a new
|
|
774
867
|
/// AVPlayer in the same Load when the AVPlayer itself failed. `time`, else the pending target,
|
|
775
868
|
/// is held as the deferred seek before the loading transition saves the snapshot.
|
|
776
869
|
private func prepareForReload(resumingAt time: TimeInterval?) {
|
|
870
|
+
cancelIdleLivePark()
|
|
777
871
|
load?.reloadOnPlay = false
|
|
778
872
|
let target = time ?? deferredSeek.target
|
|
779
873
|
deferredSeek.reset()
|
|
@@ -843,7 +937,7 @@ final class Player {
|
|
|
843
937
|
recoverIfAirPlayStalled(transitioningTo: status, waitingForNoItem: waitingForNoItem)
|
|
844
938
|
timeControlStatusDidChange(status)
|
|
845
939
|
case .audioDidStart:
|
|
846
|
-
if
|
|
940
|
+
if !awaitingItem { transition(.audioFrameDecoded) }
|
|
847
941
|
case .playedToEnd:
|
|
848
942
|
itemDidPlayToEnd()
|
|
849
943
|
case .stalled:
|
|
@@ -861,10 +955,11 @@ final class Player {
|
|
|
861
955
|
transition(.bufferingSufficient)
|
|
862
956
|
}
|
|
863
957
|
|
|
864
|
-
/// While
|
|
865
|
-
/// end arriving, which `.playedToEnd` handles; one with the play intent
|
|
958
|
+
/// While the load awaits its item, a status change belongs to the one it replaces, or to none. A
|
|
959
|
+
/// pause near the end is the end arriving, which `.playedToEnd` handles; one with the play intent
|
|
960
|
+
/// is a buffer or a seek.
|
|
866
961
|
private func timeControlStatusDidChange(_ status: PlayerTimeControlStatus) {
|
|
867
|
-
guard
|
|
962
|
+
guard !awaitingItem else { return }
|
|
868
963
|
switch status {
|
|
869
964
|
case .paused:
|
|
870
965
|
let duration = engine.duration
|