react-native-audio-browser 0.2.0-next.90 → 0.2.0-next.92

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.
Files changed (29) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +4 -0
  2. package/android/src/main/java/com/audiobrowser/RemoteOutputs.kt +60 -1
  3. package/android/src/main/java/com/audiobrowser/browser/TrackLoadHandler.kt +2 -1
  4. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +80 -7
  5. package/android/src/main/java/com/audiobrowser/player/ConnectionEndSource.kt +145 -0
  6. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +7 -2
  7. package/android/src/main/java/com/audiobrowser/player/MediaSessionCallback.kt +10 -2
  8. package/android/src/main/java/com/audiobrowser/sonos/SonosRouteProviderService.kt +13 -10
  9. package/android/src/test/java/com/audiobrowser/RemoteOutputRoutesTest.kt +29 -0
  10. package/android/src/test/java/com/audiobrowser/RemoteOutputsTest.kt +46 -4
  11. package/android/src/test/java/com/audiobrowser/browser/TrackLoadHandlerTest.kt +1 -0
  12. package/android/src/test/java/com/audiobrowser/player/AutomaticBufferManagerTest.kt +208 -0
  13. package/android/src/test/java/com/audiobrowser/player/HandleTrackLoadSeekTest.kt +70 -9
  14. package/android/src/test/java/com/audiobrowser/player/LiveStreamEndTest.kt +183 -6
  15. package/android/src/test/java/com/audiobrowser/player/PlayerSuppressionTest.kt +27 -16
  16. package/android/src/test/java/com/audiobrowser/player/RetryMaskingTest.kt +3 -1
  17. package/android/src/test/java/com/audiobrowser/sonos/SonosRoutesTest.kt +32 -0
  18. package/ios/Model/NitroTypeStubs.swift +1 -0
  19. package/ios/TrackSelector.swift +6 -1
  20. package/lib/typescript/src/types/browser.d.ts +6 -0
  21. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  22. package/nitrogen/generated/android/c++/JTrackLoadEvent.hpp +7 -3
  23. package/nitrogen/generated/android/kotlin/com/margelo/nitro/audiobrowser/TrackLoadEvent.kt +9 -4
  24. package/nitrogen/generated/ios/swift/TrackLoadEvent.swift +20 -2
  25. package/nitrogen/generated/shared/c++/TrackLoadEvent.hpp +7 -2
  26. package/package.json +2 -1
  27. package/src/types/browser.ts +6 -0
  28. package/website/guide/audio-output.md +27 -2
  29. package/website/guide/browser.md +2 -2
@@ -28,6 +28,7 @@ class TrackLoadHandlerTest {
28
28
  station,
29
29
  arrayOf(station),
30
30
  0.0,
31
+ startPosition = null,
31
32
  intercepted = { ran = true },
32
33
  defaultBehavior = { ran = true },
33
34
  )
@@ -0,0 +1,208 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.net.Uri
4
+ import androidx.media3.common.C
5
+ import androidx.media3.common.Player as MediaPlayer
6
+ import androidx.media3.common.Timeline
7
+ import androidx.media3.datasource.DataSpec
8
+ import androidx.media3.exoplayer.ExoPlayer
9
+ import androidx.media3.exoplayer.analytics.AnalyticsListener
10
+ import androidx.media3.exoplayer.source.LoadEventInfo
11
+ import androidx.media3.exoplayer.source.MediaLoadData
12
+ import java.io.IOException
13
+ import org.junit.Assert.assertEquals
14
+ import org.junit.Test
15
+ import org.junit.runner.RunWith
16
+ import org.mockito.Mockito.mock
17
+ import org.mockito.Mockito.`when`
18
+ import org.robolectric.RobolectricTestRunner
19
+
20
+ @RunWith(RobolectricTestRunner::class)
21
+ class AutomaticBufferManagerTest {
22
+
23
+ private val fastStart =
24
+ BufferConfig(bufferForPlaybackMs = 500, bufferForPlaybackAfterRebufferMs = 1000)
25
+ private val loadControl = DynamicLoadControl(fastStart)
26
+ private var nowMs = 3_600_000L
27
+ private val engine = mock(ExoPlayer::class.java)
28
+ private val manager =
29
+ AutomaticBufferManager(loadControl, fastStart, clock = { nowMs }).also { it.attach(engine) }
30
+
31
+ private val threshold: Int
32
+ get() = loadControl.getBufferConfig().bufferForPlaybackAfterRebufferMs
33
+
34
+ /** Ready with [bufferedMs] buffered, then [playedMs] of playback. */
35
+ private fun play(bufferedMs: Long = 2_000, playedMs: Long = 20_000) {
36
+ `when`(engine.totalBufferedDuration).thenReturn(bufferedMs)
37
+ manager.onPlaybackStateChanged(MediaPlayer.STATE_READY)
38
+ nowMs += playedMs
39
+ }
40
+
41
+ private fun state(state: Int) = manager.onPlaybackStateChanged(state)
42
+
43
+ private fun eventTime(windowIndex: Int = 0) =
44
+ AnalyticsListener.EventTime(
45
+ nowMs,
46
+ Timeline.EMPTY,
47
+ windowIndex,
48
+ null,
49
+ 0,
50
+ Timeline.EMPTY,
51
+ /* currentWindowIndex= */ 0,
52
+ null,
53
+ 0,
54
+ 0,
55
+ )
56
+
57
+ private fun load(taskId: Long) =
58
+ LoadEventInfo(taskId, DataSpec(Uri.parse("https://example.com/a")), nowMs)
59
+
60
+ private val data = MediaLoadData(C.DATA_TYPE_MEDIA)
61
+
62
+ private fun loadFailed(taskId: Long = 1, windowIndex: Int = 0, canceled: Boolean = false) =
63
+ manager.onLoadError(eventTime(windowIndex), load(taskId), data, IOException(), canceled)
64
+
65
+ private fun loadCompleted(taskId: Long = 1) =
66
+ manager.onLoadCompleted(eventTime(), load(taskId), data)
67
+
68
+ @Test
69
+ fun `an underrun raises the threshold to what the drain rate says lasts a minute`() {
70
+ state(MediaPlayer.STATE_BUFFERING)
71
+ // 2 s drained over 20 s: 100 ms a second, 6 s for a minute.
72
+ play(bufferedMs = 2_000, playedMs = 20_000)
73
+ state(MediaPlayer.STATE_BUFFERING)
74
+ assertEquals(6_000, threshold)
75
+ }
76
+
77
+ @Test
78
+ fun `a reconnect's first buffering is not a rebuffer`() {
79
+ play()
80
+ state(MediaPlayer.STATE_IDLE)
81
+ state(MediaPlayer.STATE_BUFFERING)
82
+ play()
83
+ assertEquals(1_000, threshold)
84
+ }
85
+
86
+ @Test
87
+ fun `a clean close of a stream with an end is not a rebuffer`() {
88
+ play()
89
+ state(MediaPlayer.STATE_ENDED)
90
+ state(MediaPlayer.STATE_BUFFERING)
91
+ play()
92
+ assertEquals(1_000, threshold)
93
+ }
94
+
95
+ @Test
96
+ fun `a buffering while a failed load retries in place keeps the threshold`() {
97
+ play()
98
+ loadFailed()
99
+ state(MediaPlayer.STATE_BUFFERING)
100
+ assertEquals(1_000, threshold)
101
+ }
102
+
103
+ @Test
104
+ fun `the drain is measured afresh once the failed load recovers`() {
105
+ play()
106
+ loadFailed()
107
+ state(MediaPlayer.STATE_BUFFERING)
108
+ // 4 s drained over 20 s: 12 s for a minute, at most 8 s.
109
+ play(bufferedMs = 4_000)
110
+ state(MediaPlayer.STATE_BUFFERING)
111
+ assertEquals(8_000, threshold)
112
+ }
113
+
114
+ @Test
115
+ fun `a failed load that completed leaves the next underrun counted`() {
116
+ play()
117
+ loadFailed()
118
+ loadCompleted()
119
+ state(MediaPlayer.STATE_BUFFERING)
120
+ assertEquals(6_000, threshold)
121
+ }
122
+
123
+ @Test
124
+ fun `a failed preload of the next item leaves the underrun counted`() {
125
+ play()
126
+ loadFailed(windowIndex = 1)
127
+ state(MediaPlayer.STATE_BUFFERING)
128
+ assertEquals(6_000, threshold)
129
+ }
130
+
131
+ @Test
132
+ fun `a load that recovered without completing stops counting as failing`() {
133
+ play()
134
+ loadFailed()
135
+ // A progressive load that recovers in place completes only at the end of its file.
136
+ nowMs += 20_000
137
+ state(MediaPlayer.STATE_BUFFERING)
138
+ // 2 s drained over 40 s: 3 s for a minute.
139
+ assertEquals(3_000, threshold)
140
+ }
141
+
142
+ @Test
143
+ fun `a load that starts without failing does not count as failing`() {
144
+ play()
145
+ manager.onLoadStarted(eventTime(), load(2), data, 0)
146
+ state(MediaPlayer.STATE_BUFFERING)
147
+ assertEquals(6_000, threshold)
148
+ }
149
+
150
+ @Test
151
+ fun `a load that keeps failing counts until its last error is old`() {
152
+ play()
153
+ loadFailed()
154
+ nowMs += 15_000
155
+ loadFailed()
156
+ nowMs += 15_000
157
+ state(MediaPlayer.STATE_BUFFERING)
158
+ assertEquals(1_000, threshold)
159
+ }
160
+
161
+ @Test
162
+ fun `a failed load media3 cancels still counts as failing`() {
163
+ play()
164
+ // An HLS variant media3 excludes: its load is canceled, and the next variant's starts.
165
+ loadFailed(canceled = true)
166
+ state(MediaPlayer.STATE_BUFFERING)
167
+ assertEquals(1_000, threshold)
168
+ }
169
+
170
+ @Test
171
+ fun `each retry of a failing load keeps it failing`() {
172
+ play()
173
+ loadFailed()
174
+ nowMs += 15_000
175
+ manager.onLoadStarted(eventTime(), load(1), data, 1)
176
+ nowMs += 15_000
177
+ state(MediaPlayer.STATE_BUFFERING)
178
+ assertEquals(1_000, threshold)
179
+ }
180
+
181
+ @Test
182
+ fun `playing again forgets the failed loads`() {
183
+ play()
184
+ loadFailed()
185
+ state(MediaPlayer.STATE_BUFFERING)
186
+ // 2 s drained over 5 s: 24 s for a minute, at most 8 s.
187
+ play(playedMs = 5_000)
188
+ state(MediaPlayer.STATE_BUFFERING)
189
+ assertEquals(8_000, threshold)
190
+ }
191
+
192
+ @Test
193
+ fun `a canceled load no longer counts as failing`() {
194
+ play()
195
+ loadFailed()
196
+ manager.onLoadCanceled(eventTime(), load(1), data)
197
+ state(MediaPlayer.STATE_BUFFERING)
198
+ assertEquals(6_000, threshold)
199
+ }
200
+
201
+ @Test
202
+ fun `reset restores the fast start`() {
203
+ play()
204
+ state(MediaPlayer.STATE_BUFFERING)
205
+ manager.reset()
206
+ assertEquals(fastStart, loadControl.getBufferConfig())
207
+ }
208
+ }
@@ -22,6 +22,8 @@ import java.time.Duration
22
22
  import java.util.concurrent.TimeUnit
23
23
  import org.junit.After
24
24
  import org.junit.Assert.assertEquals
25
+ import org.junit.Assert.assertNotNull
26
+ import org.junit.Assert.assertNull
25
27
  import org.junit.Assert.fail
26
28
  import org.junit.Rule
27
29
  import org.junit.Test
@@ -36,7 +38,10 @@ import org.robolectric.Shadows.shadowOf
36
38
  import org.robolectric.annotation.Config
37
39
  import org.robolectric.shadows.ShadowSystemClock
38
40
 
39
- /** A controller's set of media items keeps where a handleTrackLoad left the player. */
41
+ /**
42
+ * A controller's set of media items reaches handleTrackLoad with the position it asked for, and
43
+ * keeps where the handler left the player.
44
+ */
40
45
  @RunWith(RobolectricTestRunner::class)
41
46
  @Config(sdk = [28])
42
47
  class HandleTrackLoadSeekTest {
@@ -57,13 +62,13 @@ class HandleTrackLoadSeekTest {
57
62
  service.destroy()
58
63
  }
59
64
 
60
- private fun handlingTrackLoadWith(onLoad: (Track) -> Unit) {
65
+ private fun handlingTrackLoadWith(onLoad: (TrackLoadEvent) -> Unit) {
61
66
  // JS runs the handler's player calls on the main thread before its promise settles.
62
67
  val handler: (TrackLoadEvent) -> Promise<Promise<Unit>> = { event ->
63
68
  val inner = JsPromise<Unit>()
64
69
  val outer = JsPromise<Promise<Unit>>()
65
70
  Handler(Looper.getMainLooper()).post {
66
- onLoad(event.track)
71
+ onLoad(event)
67
72
  setsAfterHandler = 0
68
73
  inner.resolve(Unit)
69
74
  outer.resolve(inner.promise)
@@ -105,10 +110,10 @@ class HandleTrackLoadSeekTest {
105
110
  }
106
111
 
107
112
  /**
108
- * As a controller starts a track: media3 passes no index or position on a reset. Returns once
109
- * media3 has set the items the callback returned, after the handler.
113
+ * As a controller starts a track, at [positionMs] when given; without one media3 passes no index
114
+ * or position. Returns once media3 has set the items the callback returned, after the handler.
110
115
  */
111
- private fun setFromController(track: Track) {
116
+ private fun setFromController(track: Track, positionMs: Long? = null) {
112
117
  player.exoPlayer.addListener(
113
118
  object : MediaPlayer.Listener {
114
119
  override fun onTimelineChanged(timeline: Timeline, reason: Int) {
@@ -122,7 +127,9 @@ class HandleTrackLoadSeekTest {
122
127
  MediaController.Builder(RuntimeEnvironment.getApplication(), service.get().session.token)
123
128
  .buildAsync()
124
129
  idleUntil("the controller to connect") { future.isDone }
125
- future.get().setMediaItem(TrackFactory.toMedia3(track))
130
+ val item = TrackFactory.toMedia3(track)
131
+ if (positionMs == null) future.get().setMediaItem(item)
132
+ else future.get().setMediaItem(item, positionMs)
126
133
  idleUntil("media3 to set the items") { (setsAfterHandler ?: 0) >= 1 }
127
134
  }
128
135
 
@@ -143,7 +150,7 @@ class HandleTrackLoadSeekTest {
143
150
  fun `a load then a seek in the handler holds the seek`() {
144
151
  val track = silentTrack(Duration.ofMinutes(2))
145
152
  handlingTrackLoadWith {
146
- player.load(it)
153
+ player.load(it.track)
147
154
  player.seekTo(60, TimeUnit.SECONDS)
148
155
  }
149
156
 
@@ -155,13 +162,67 @@ class HandleTrackLoadSeekTest {
155
162
  @Test
156
163
  fun `a setQueue at a position in the handler holds the position`() {
157
164
  val track = silentTrack(Duration.ofMinutes(2))
158
- handlingTrackLoadWith { player.setQueue(arrayOf(it), 0, 60_000) }
165
+ handlingTrackLoadWith { player.setQueue(arrayOf(it.track), 0, 60_000) }
159
166
 
160
167
  setFromController(track)
161
168
 
162
169
  assertEquals(60_000L, player.exoPlayer.currentPosition)
163
170
  }
164
171
 
172
+ @Test
173
+ fun `a controller's start position reaches the handler in seconds`() {
174
+ var startPosition: Double? = null
175
+ handlingTrackLoadWith {
176
+ startPosition = it.startPosition
177
+ player.load(it.track)
178
+ }
179
+
180
+ setFromController(silentTrack(Duration.ofMinutes(2)), positionMs = 45_500)
181
+
182
+ assertEquals(45.5, startPosition)
183
+ }
184
+
185
+ @Test
186
+ fun `a controller that asks for no position leaves the start position absent`() {
187
+ var event: TrackLoadEvent? = null
188
+ handlingTrackLoadWith {
189
+ event = it
190
+ player.load(it.track)
191
+ }
192
+
193
+ setFromController(silentTrack(Duration.ofMinutes(2)))
194
+
195
+ assertNotNull(event)
196
+ assertNull(event?.startPosition)
197
+ }
198
+
199
+ @Test
200
+ fun `a controller that resets the position gives the handler the first index`() {
201
+ var startIndex: Double? = null
202
+ handlingTrackLoadWith {
203
+ startIndex = it.startIndex
204
+ player.load(it.track)
205
+ }
206
+
207
+ setFromController(silentTrack(Duration.ofMinutes(2)))
208
+
209
+ assertEquals(0.0, startIndex)
210
+ }
211
+
212
+ @Test
213
+ fun `a handler that seeks to the start position starts playback there`() {
214
+ handlingTrackLoadWith {
215
+ player.load(it.track)
216
+ it.startPosition?.let { position ->
217
+ player.seekTo((position * 1000).toLong(), TimeUnit.MILLISECONDS)
218
+ }
219
+ }
220
+
221
+ setFromController(silentTrack(Duration.ofMinutes(2)), positionMs = 45_000)
222
+
223
+ assertEquals(45_000L, player.exoPlayer.currentPosition)
224
+ }
225
+
165
226
  @Test
166
227
  fun `an ended track a handler leaves is set again at its start`() {
167
228
  val track = silentTrack(Duration.ofMillis(500))
@@ -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 cleanly, served without a length, loaded through
41
- * [MediaFactory] by media3's own media period. The test reads the samples as a renderer would and
42
- * advances the clock by the audio it reads, since Robolectric plays no audio.
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
- private fun play(live: Boolean, retryPolicy: RetryPolicy): Outcome {
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. */