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
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import androidx.media3.common.C
|
|
4
|
+
import androidx.media3.common.StreamKey
|
|
5
|
+
import androidx.media3.decoder.DecoderInputBuffer
|
|
6
|
+
import androidx.media3.exoplayer.FormatHolder
|
|
7
|
+
import androidx.media3.exoplayer.LoadingInfo
|
|
8
|
+
import androidx.media3.exoplayer.SeekParameters
|
|
9
|
+
import androidx.media3.exoplayer.source.MediaPeriod
|
|
10
|
+
import androidx.media3.exoplayer.source.MediaSource
|
|
11
|
+
import androidx.media3.exoplayer.source.SampleStream
|
|
12
|
+
import androidx.media3.exoplayer.source.TrackGroupArray
|
|
13
|
+
import androidx.media3.exoplayer.source.WrappingMediaSource
|
|
14
|
+
import androidx.media3.exoplayer.trackselection.ExoTrackSelection
|
|
15
|
+
import androidx.media3.exoplayer.upstream.Allocator
|
|
16
|
+
import java.io.IOException
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A progressive source whose fatal load error, such as a connection's end that
|
|
20
|
+
* [RetryLoadErrorHandlingPolicy] does not retry in place, surfaces only once the audio the
|
|
21
|
+
* connection delivered has been read. media3 surfaces a load error whenever it is buffering or a
|
|
22
|
+
* renderer is not ready, and before it has handled the period's preparation, so a burst that
|
|
23
|
+
* arrives with its close would otherwise never play. Once the connection has ended, the period has
|
|
24
|
+
* nothing more to load: playback starts on what it holds, short of the play buffer.
|
|
25
|
+
*/
|
|
26
|
+
class ConnectionEndSource(source: MediaSource) : WrappingMediaSource(source) {
|
|
27
|
+
|
|
28
|
+
override fun createPeriod(
|
|
29
|
+
id: MediaSource.MediaPeriodId,
|
|
30
|
+
allocator: Allocator,
|
|
31
|
+
startPositionUs: Long,
|
|
32
|
+
): MediaPeriod = Period(super.createPeriod(id, allocator, startPositionUs))
|
|
33
|
+
|
|
34
|
+
override fun releasePeriod(mediaPeriod: MediaPeriod) {
|
|
35
|
+
super.releasePeriod((mediaPeriod as Period).period)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private class Period(val period: MediaPeriod) : MediaPeriod {
|
|
39
|
+
/** Read on the playback thread only, where media3 calls back. */
|
|
40
|
+
private var prepared = false
|
|
41
|
+
|
|
42
|
+
private val connectionEnded: Boolean
|
|
43
|
+
get() =
|
|
44
|
+
try {
|
|
45
|
+
period.maybeThrowPrepareError()
|
|
46
|
+
false
|
|
47
|
+
} catch (_: IOException) {
|
|
48
|
+
true
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
override fun prepare(callback: MediaPeriod.Callback, positionUs: Long) {
|
|
52
|
+
period.prepare(
|
|
53
|
+
object : MediaPeriod.Callback {
|
|
54
|
+
override fun onPrepared(mediaPeriod: MediaPeriod) {
|
|
55
|
+
prepared = true
|
|
56
|
+
callback.onPrepared(this@Period)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
override fun onContinueLoadingRequested(source: MediaPeriod) {
|
|
60
|
+
callback.onContinueLoadingRequested(this@Period)
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
positionUs,
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
override fun maybeThrowPrepareError() {
|
|
68
|
+
if (!prepared) period.maybeThrowPrepareError()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
override fun getTrackGroups(): TrackGroupArray = period.trackGroups
|
|
72
|
+
|
|
73
|
+
override fun getStreamKeys(trackSelections: List<ExoTrackSelection>): List<StreamKey> =
|
|
74
|
+
period.getStreamKeys(trackSelections)
|
|
75
|
+
|
|
76
|
+
override fun selectTracks(
|
|
77
|
+
selections: Array<out ExoTrackSelection?>,
|
|
78
|
+
mayRetainStreamFlags: BooleanArray,
|
|
79
|
+
streams: Array<SampleStream?>,
|
|
80
|
+
streamResetFlags: BooleanArray,
|
|
81
|
+
positionUs: Long,
|
|
82
|
+
): Long {
|
|
83
|
+
val held = Array(streams.size) { streams[it] as Stream? }
|
|
84
|
+
val inner = Array(streams.size) { held[it]?.stream }
|
|
85
|
+
val enabledAtUs =
|
|
86
|
+
period.selectTracks(selections, mayRetainStreamFlags, inner, streamResetFlags, positionUs)
|
|
87
|
+
for (i in streams.indices) {
|
|
88
|
+
val stream = inner[i]
|
|
89
|
+
held[i] =
|
|
90
|
+
when {
|
|
91
|
+
stream == null -> null
|
|
92
|
+
held[i]?.stream === stream -> held[i]
|
|
93
|
+
else -> Stream(stream)
|
|
94
|
+
}
|
|
95
|
+
streams[i] = held[i]
|
|
96
|
+
}
|
|
97
|
+
return enabledAtUs
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
override fun discardBuffer(positionUs: Long, toKeyframe: Boolean) =
|
|
101
|
+
period.discardBuffer(positionUs, toKeyframe)
|
|
102
|
+
|
|
103
|
+
override fun readDiscontinuity(): Long = period.readDiscontinuity()
|
|
104
|
+
|
|
105
|
+
override fun setUsesStreamPrerollFlags() = period.setUsesStreamPrerollFlags()
|
|
106
|
+
|
|
107
|
+
override fun seekToUs(positionUs: Long): Long = period.seekToUs(positionUs)
|
|
108
|
+
|
|
109
|
+
override fun getAdjustedSeekPositionUs(positionUs: Long, seekParameters: SeekParameters): Long =
|
|
110
|
+
period.getAdjustedSeekPositionUs(positionUs, seekParameters)
|
|
111
|
+
|
|
112
|
+
override fun getBufferedPositionUs(): Long = period.bufferedPositionUs
|
|
113
|
+
|
|
114
|
+
override fun getNextLoadPositionUs(): Long =
|
|
115
|
+
if (connectionEnded) C.TIME_END_OF_SOURCE else period.nextLoadPositionUs
|
|
116
|
+
|
|
117
|
+
override fun continueLoading(loadingInfo: LoadingInfo): Boolean =
|
|
118
|
+
period.continueLoading(loadingInfo)
|
|
119
|
+
|
|
120
|
+
override fun isLoading(): Boolean = period.isLoading
|
|
121
|
+
|
|
122
|
+
override fun reevaluateBuffer(positionUs: Long) = period.reevaluateBuffer(positionUs)
|
|
123
|
+
|
|
124
|
+
override fun setEndPositionUs(endPositionUs: Long): Long =
|
|
125
|
+
period.setEndPositionUs(endPositionUs)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private class Stream(val stream: SampleStream) : SampleStream {
|
|
129
|
+
override fun isReady(): Boolean = stream.isReady
|
|
130
|
+
|
|
131
|
+
override fun maybeThrowError() {
|
|
132
|
+
if (!stream.isReady) stream.maybeThrowError()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
override fun readData(
|
|
136
|
+
formatHolder: FormatHolder,
|
|
137
|
+
buffer: DecoderInputBuffer,
|
|
138
|
+
readFlags: Int,
|
|
139
|
+
): Int = stream.readData(formatHolder, buffer, readFlags)
|
|
140
|
+
|
|
141
|
+
override fun skipData(positionUs: Long): Int = stream.skipData(positionUs)
|
|
142
|
+
|
|
143
|
+
override fun getFlags(): Int = stream.flags
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -129,11 +129,16 @@ class MediaFactory(
|
|
|
129
129
|
track.live == true -> liveMediaFactory to RetryLoadErrorHandlingPolicy.Sources.LIVE
|
|
130
130
|
else -> mediaFactory to RetryLoadErrorHandlingPolicy.Sources.PROGRESSIVE
|
|
131
131
|
}
|
|
132
|
+
val retrying = externalPolicy == null && retryPolicy != RetryPolicy.Default
|
|
132
133
|
// One policy per item: it tells the playing item's failures from a preload's.
|
|
133
|
-
if (
|
|
134
|
+
if (retrying)
|
|
134
135
|
factory.setLoadErrorHandlingPolicy(
|
|
135
136
|
RetryLoadErrorHandlingPolicy(sources, { isCurrent(mediaItem) }, onLoadFailure)
|
|
136
137
|
)
|
|
137
|
-
|
|
138
|
+
val source = factory.setDataSourceFactory(dataSourceFactory).createMediaSource(mediaItem)
|
|
139
|
+
// Adaptive sources retry in place: the policy never ends their connection.
|
|
140
|
+
return if (retrying && sources != RetryLoadErrorHandlingPolicy.Sources.ADAPTIVE)
|
|
141
|
+
ConnectionEndSource(source)
|
|
142
|
+
else source
|
|
138
143
|
}
|
|
139
144
|
}
|
|
@@ -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
|
|
|
@@ -2,11 +2,18 @@ package com.audiobrowser.player
|
|
|
2
2
|
|
|
3
3
|
import android.os.Looper
|
|
4
4
|
import androidx.media3.common.C
|
|
5
|
+
import androidx.media3.common.Format
|
|
5
6
|
import androidx.media3.common.ParserException
|
|
7
|
+
import androidx.media3.common.PlaybackException
|
|
8
|
+
import androidx.media3.common.Player as MediaPlayer
|
|
6
9
|
import androidx.media3.datasource.DataSourceException
|
|
7
10
|
import androidx.media3.decoder.DecoderInputBuffer
|
|
11
|
+
import androidx.media3.exoplayer.BaseRenderer
|
|
12
|
+
import androidx.media3.exoplayer.ExoPlayer
|
|
8
13
|
import androidx.media3.exoplayer.FormatHolder
|
|
9
14
|
import androidx.media3.exoplayer.LoadingInfo
|
|
15
|
+
import androidx.media3.exoplayer.Renderer
|
|
16
|
+
import androidx.media3.exoplayer.RendererCapabilities
|
|
10
17
|
import androidx.media3.exoplayer.analytics.PlayerId
|
|
11
18
|
import androidx.media3.exoplayer.source.MediaPeriod
|
|
12
19
|
import androidx.media3.exoplayer.source.MediaSource
|
|
@@ -22,6 +29,7 @@ import com.audiobrowser.util.TrackFactory
|
|
|
22
29
|
import java.io.IOException
|
|
23
30
|
import java.net.ServerSocket
|
|
24
31
|
import java.time.Duration
|
|
32
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
25
33
|
import java.util.concurrent.atomic.AtomicInteger
|
|
26
34
|
import kotlin.concurrent.thread
|
|
27
35
|
import org.junit.After
|
|
@@ -37,9 +45,10 @@ import org.robolectric.Shadows.shadowOf
|
|
|
37
45
|
import org.robolectric.shadows.ShadowSystemClock
|
|
38
46
|
|
|
39
47
|
/**
|
|
40
|
-
* A progressive stream that the server ends
|
|
41
|
-
* [MediaFactory] by media3's own media period
|
|
42
|
-
*
|
|
48
|
+
* A progressive stream that the server ends, served without a length, loaded through
|
|
49
|
+
* [MediaFactory]: by media3's own media period, whose samples the test reads as a renderer would,
|
|
50
|
+
* advancing the clock by the audio it reads since Robolectric plays no audio, or by an ExoPlayer
|
|
51
|
+
* whose one renderer reads them.
|
|
43
52
|
*/
|
|
44
53
|
@RunWith(RobolectricTestRunner::class)
|
|
45
54
|
class LiveStreamEndTest {
|
|
@@ -66,6 +75,87 @@ class LiveStreamEndTest {
|
|
|
66
75
|
assertEquals(1, requests.get())
|
|
67
76
|
}
|
|
68
77
|
|
|
78
|
+
@Test
|
|
79
|
+
fun `a live stream closed with its burst holds the close until the burst has been read`() {
|
|
80
|
+
serve(framesFor = { SECONDS_2 }, end = End.CLOSE)
|
|
81
|
+
|
|
82
|
+
val (heldWhileUnread, outcome) = playBurst()
|
|
83
|
+
|
|
84
|
+
assertNull("surfaced with the burst unread", heldWhileUnread)
|
|
85
|
+
assertTrue("not the close: ${outcome.error}", outcome.error is DataSourceException)
|
|
86
|
+
assertEquals(SECONDS_2, played.get())
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@Test
|
|
90
|
+
fun `a player plays a burst shorter than its play buffer that arrives with its close`() {
|
|
91
|
+
serve(framesFor = { SECONDS_2 }, end = End.CLOSE)
|
|
92
|
+
val ended = AtomicBoolean()
|
|
93
|
+
val renderer = WarmingRenderer(connectionEnded = ended::get)
|
|
94
|
+
val player =
|
|
95
|
+
ExoPlayer.Builder(context, { _, _, _, _, _ -> arrayOf<Renderer>(renderer) })
|
|
96
|
+
.setMediaSourceFactory(
|
|
97
|
+
MediaFactory(
|
|
98
|
+
context,
|
|
99
|
+
cache = null,
|
|
100
|
+
RetryPolicy.Infinite(),
|
|
101
|
+
onLoadFailure = { _, _ -> ended.set(true) },
|
|
102
|
+
getRequestConfig = { _, _ -> null },
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
.setLoadControl(
|
|
106
|
+
DynamicLoadControl(
|
|
107
|
+
BufferConfig(bufferForPlaybackMs = 2_500, bufferForPlaybackAfterRebufferMs = 2_500)
|
|
108
|
+
)
|
|
109
|
+
)
|
|
110
|
+
.build()
|
|
111
|
+
var ready = false
|
|
112
|
+
var error: PlaybackException? = null
|
|
113
|
+
player.addListener(
|
|
114
|
+
object : MediaPlayer.Listener {
|
|
115
|
+
override fun onPlaybackStateChanged(state: Int) {
|
|
116
|
+
if (state == MediaPlayer.STATE_READY) ready = true
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
override fun onPlayerError(e: PlaybackException) {
|
|
120
|
+
error = e
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
try {
|
|
125
|
+
player.setMediaItem(
|
|
126
|
+
TrackFactory.toMedia3(
|
|
127
|
+
track(src = "http://127.0.0.1:${server.localPort}/stream.mp3").copy(live = true)
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
player.prepare()
|
|
131
|
+
player.play()
|
|
132
|
+
val deadline = System.currentTimeMillis() + 10_000
|
|
133
|
+
while (error == null) {
|
|
134
|
+
if (System.currentTimeMillis() > deadline) fail("no error; ready: $ready")
|
|
135
|
+
ShadowSystemClock.advanceBy(Duration.ofMillis(10))
|
|
136
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
137
|
+
Thread.sleep(1)
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
player.release()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
assertTrue("never ready: ${error?.cause}", ready)
|
|
144
|
+
assertEquals(SECONDS_2, renderer.read)
|
|
145
|
+
assertTrue("not the close: ${error?.cause}", error?.cause is DataSourceException)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
@Test
|
|
149
|
+
fun `a stream of unknown length whose connection drops holds the drop until its audio has been read`() {
|
|
150
|
+
serve(framesFor = { SECONDS_2 }, end = End.DROP)
|
|
151
|
+
|
|
152
|
+
val (heldWhileUnread, outcome) = playBurst(live = false)
|
|
153
|
+
|
|
154
|
+
assertNull("surfaced with the audio unread", heldWhileUnread)
|
|
155
|
+
assertTrue("not the drop: ${outcome.error}", outcome.error is DataSourceException)
|
|
156
|
+
assertEquals(SECONDS_2, played.get())
|
|
157
|
+
}
|
|
158
|
+
|
|
69
159
|
@Test
|
|
70
160
|
fun `an on-demand file served without a length ends where the server ends it`() {
|
|
71
161
|
serve(framesFor = { SECONDS_1_5 })
|
|
@@ -152,12 +242,13 @@ class LiveStreamEndTest {
|
|
|
152
242
|
/**
|
|
153
243
|
* Answers the [n]th request, from 1, with the [body] of [framesFor]`(n)` frames as [contentType],
|
|
154
244
|
* silence by default and [withLength] or not, then ends it cleanly once they have all been read:
|
|
155
|
-
* a server sending in real time ends after its audio, never with it.
|
|
245
|
+
* a server sending in real time ends after its audio, never with it; see [End] for the others.
|
|
156
246
|
*/
|
|
157
247
|
private fun serve(
|
|
158
248
|
framesFor: (n: Int) -> Int,
|
|
159
249
|
contentType: String? = "audio/mpeg",
|
|
160
250
|
withLength: Boolean = false,
|
|
251
|
+
end: End = End.AFTER_PLAYED,
|
|
161
252
|
body: (frames: Int) -> ByteArray = ::silentMp3,
|
|
162
253
|
) {
|
|
163
254
|
val server = server
|
|
@@ -179,23 +270,72 @@ class LiveStreamEndTest {
|
|
|
179
270
|
append("HTTP/1.1 200 OK\r\nConnection: close\r\n")
|
|
180
271
|
contentType?.let { type -> append("Content-Type: $type\r\n") }
|
|
181
272
|
if (withLength) append("Content-Length: ${bytes.size}\r\n")
|
|
273
|
+
if (end == End.DROP) append("Transfer-Encoding: chunked\r\n")
|
|
182
274
|
append("\r\n")
|
|
183
275
|
}
|
|
184
276
|
it.getOutputStream().run {
|
|
185
277
|
write(headers.toByteArray())
|
|
278
|
+
// A chunk with no last chunk after it: the body ends short.
|
|
279
|
+
if (end == End.DROP) write("${bytes.size.toString(16)}\r\n".toByteArray())
|
|
186
280
|
write(bytes)
|
|
187
281
|
flush()
|
|
188
282
|
}
|
|
189
283
|
sent += frames
|
|
190
|
-
while (played.get() < sent && !server.isClosed) Thread.sleep(1)
|
|
284
|
+
while (end == End.AFTER_PLAYED && played.get() < sent && !server.isClosed) Thread.sleep(1)
|
|
191
285
|
}
|
|
192
286
|
}
|
|
193
287
|
}
|
|
194
288
|
}
|
|
195
289
|
|
|
290
|
+
private enum class End {
|
|
291
|
+
/** Cleanly, once the frames have been read. */
|
|
292
|
+
AFTER_PLAYED,
|
|
293
|
+
|
|
294
|
+
/** Cleanly, as soon as they are sent: a burst on connect, then a close. */
|
|
295
|
+
CLOSE,
|
|
296
|
+
|
|
297
|
+
/** As soon as they are sent, cut off within a chunked body: a dropped connection. */
|
|
298
|
+
DROP,
|
|
299
|
+
}
|
|
300
|
+
|
|
196
301
|
private class Outcome(val ended: Boolean, val error: IOException?)
|
|
197
302
|
|
|
198
|
-
|
|
303
|
+
/**
|
|
304
|
+
* Plays a track as [play] does, but first waits for the connection to end with its audio unread
|
|
305
|
+
* and asks the stream for its error, as ExoPlayer asks a renderer's stream while it buffers.
|
|
306
|
+
* Answers that error, if any, and the outcome.
|
|
307
|
+
*/
|
|
308
|
+
private fun playBurst(live: Boolean = true): Pair<IOException?, Outcome> {
|
|
309
|
+
var heldWhileUnread: IOException? = null
|
|
310
|
+
val outcome =
|
|
311
|
+
play(live, RetryPolicy.Infinite()) { period, stream ->
|
|
312
|
+
awaitConnectionEnd(period)
|
|
313
|
+
try {
|
|
314
|
+
// ExoPlayer asks the period until it has handled its preparation, which can come after
|
|
315
|
+
// the connection's end, and then asks the stream.
|
|
316
|
+
period.maybeThrowPrepareError()
|
|
317
|
+
stream.maybeThrowError()
|
|
318
|
+
} catch (e: IOException) {
|
|
319
|
+
heldWhileUnread = e
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return heldWhileUnread to outcome
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
private fun awaitConnectionEnd(period: MediaPeriod) {
|
|
326
|
+
val deadline = System.currentTimeMillis() + 5_000
|
|
327
|
+
while (period.isLoading) {
|
|
328
|
+
if (System.currentTimeMillis() > deadline) fail("the connection never ended")
|
|
329
|
+
Thread.sleep(5)
|
|
330
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private fun play(
|
|
335
|
+
live: Boolean,
|
|
336
|
+
retryPolicy: RetryPolicy,
|
|
337
|
+
beforeReading: (MediaPeriod, SampleStream) -> Unit = { _, _ -> },
|
|
338
|
+
): Outcome {
|
|
199
339
|
val factory =
|
|
200
340
|
MediaFactory(context, cache = null, retryPolicy, getRequestConfig = { _, _ -> null })
|
|
201
341
|
val item =
|
|
@@ -249,6 +389,7 @@ class LiveStreamEndTest {
|
|
|
249
389
|
0,
|
|
250
390
|
)
|
|
251
391
|
val stream = checkNotNull(streams[0])
|
|
392
|
+
beforeReading(period, stream)
|
|
252
393
|
val buffer = DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DISABLED)
|
|
253
394
|
val deadline = System.currentTimeMillis() + 60_000
|
|
254
395
|
while (true) {
|
|
@@ -282,12 +423,48 @@ class LiveStreamEndTest {
|
|
|
282
423
|
}
|
|
283
424
|
}
|
|
284
425
|
|
|
426
|
+
/**
|
|
427
|
+
* Reads samples once started, as a renderer playing them does, and is ready, with samples to
|
|
428
|
+
* read, from its second render after [connectionEnded]: a MediaCodec renderer can still be
|
|
429
|
+
* starting its codec when a burst's connection has already ended. From the first, ExoPlayer would
|
|
430
|
+
* never see it not ready with the connection ended.
|
|
431
|
+
*/
|
|
432
|
+
private class WarmingRenderer(private val connectionEnded: () -> Boolean) :
|
|
433
|
+
BaseRenderer(C.TRACK_TYPE_AUDIO) {
|
|
434
|
+
@Volatile var read = 0
|
|
435
|
+
private var rendersSinceEnd = 0
|
|
436
|
+
private var hasFormat = false
|
|
437
|
+
private var ended = false
|
|
438
|
+
private val buffer = DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DISABLED)
|
|
439
|
+
|
|
440
|
+
override fun getName() = "WarmingRenderer"
|
|
441
|
+
|
|
442
|
+
override fun supportsFormat(format: Format) = RendererCapabilities.create(C.FORMAT_HANDLED)
|
|
443
|
+
|
|
444
|
+
override fun render(positionUs: Long, elapsedRealtimeUs: Long) {
|
|
445
|
+
if (connectionEnded()) rendersSinceEnd++
|
|
446
|
+
while (!hasFormat || state == STATE_STARTED) {
|
|
447
|
+
buffer.clear()
|
|
448
|
+
when (readSource(formatHolder, buffer, SampleStream.FLAG_OMIT_SAMPLE_DATA)) {
|
|
449
|
+
C.RESULT_FORMAT_READ -> hasFormat = true
|
|
450
|
+
C.RESULT_BUFFER_READ -> if (buffer.isEndOfStream) ended = true else read++
|
|
451
|
+
else -> return
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
override fun isReady() = hasFormat && rendersSinceEnd >= 2 && isSourceReady
|
|
457
|
+
|
|
458
|
+
override fun isEnded() = ended
|
|
459
|
+
}
|
|
460
|
+
|
|
285
461
|
private companion object {
|
|
286
462
|
// MPEG-1 Layer III at 32 kbit/s, 44.1 kHz, mono: 104 bytes and 1152 samples a frame.
|
|
287
463
|
val FRAME_HEADER = byteArrayOf(0xFF.toByte(), 0xFB.toByte(), 0x10, 0xC0.toByte())
|
|
288
464
|
const val FRAME_BYTES = 104
|
|
289
465
|
const val FRAME_NS = 1152 * 1_000_000_000L / 44_100
|
|
290
466
|
const val SECONDS_1_5 = 57
|
|
467
|
+
const val SECONDS_2 = 77
|
|
291
468
|
const val SECONDS_60 = 2_297
|
|
292
469
|
|
|
293
470
|
/** [frames] ADTS frames of AAC LC at 44.1 kHz, mono, with 100 zero bytes of payload each. */
|