react-native-audio-browser 0.2.0-next.85 → 0.2.0-next.87

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.
@@ -5,6 +5,7 @@ import android.app.SearchManager
5
5
  import android.content.ComponentName
6
6
  import android.content.Intent
7
7
  import android.content.ServiceConnection
8
+ import android.content.pm.PackageManager
8
9
  import android.os.Binder
9
10
  import android.os.IBinder
10
11
  import android.provider.MediaStore
@@ -152,6 +153,7 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
152
153
  mediaSession =
153
154
  MediaLibrarySession.Builder(this, player.forwardingPlayer, player.getMediaSessionCallback())
154
155
  .setBitmapLoader(CacheBitmapLoader(coilBitmapLoader))
156
+ .setPeriodicPositionUpdateEnabled(periodicPositionUpdatesEnabled())
155
157
  // https://github.com/androidx/media/issues/1218
156
158
  .setSessionActivity(
157
159
  PendingIntent.getActivity(
@@ -173,6 +175,13 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
173
175
  }
174
176
  }
175
177
 
178
+ /** The app's [PERIODIC_POSITION_UPDATES] manifest meta-data; true when it declares none. */
179
+ private fun periodicPositionUpdatesEnabled(): Boolean =
180
+ packageManager
181
+ .getApplicationInfo(packageName, PackageManager.GET_META_DATA)
182
+ .metaData
183
+ ?.getBoolean(PERIODIC_POSITION_UPDATES, true) ?: true
184
+
176
185
  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
177
186
  Timber.d("onStartCommand: action=${intent?.action}")
178
187
 
@@ -360,4 +369,12 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
360
369
  inner class LocalBinder : Binder() {
361
370
  val service = this@Service
362
371
  }
372
+
373
+ companion object {
374
+ /**
375
+ * Application meta-data that, set to false, stops media3's periodic position update: the
376
+ * session re-sending External Surfaces the playback state every 3 s while playing or loading.
377
+ */
378
+ const val PERIODIC_POSITION_UPDATES = "com.audiobrowser.PERIODIC_POSITION_UPDATES"
379
+ }
363
380
  }
@@ -808,13 +808,17 @@ class MediaSessionCallback(private val player: Player) :
808
808
  return scope.future {
809
809
  val audioBrowser = player.awaitBrowser()
810
810
 
811
- // Returning the current state unchanged is how handleTrackLoad tells Media3 to do nothing.
811
+ // Media3 sets whatever this returns: the controller's position would undo the handler's seek.
812
812
  // Reads hop to Main: ExoPlayer is main-thread confined and this runs on IO.
813
813
  suspend fun currentPlayerState(): MediaSession.MediaItemsWithStartPosition =
814
814
  withContext(Dispatchers.Main) {
815
815
  val currentItems = player.tracks.map { TrackFactory.toMedia3(it) }
816
816
  val currentIndex = player.currentIndex ?: 0
817
- MediaSession.MediaItemsWithStartPosition(currentItems, currentIndex, startPositionMs)
817
+ MediaSession.MediaItemsWithStartPosition(
818
+ currentItems,
819
+ currentIndex,
820
+ player.restorablePositionMs,
821
+ )
818
822
  }
819
823
 
820
824
  val browserManager = audioBrowser.browserManager
@@ -109,9 +109,7 @@ class PlaybackStateStore(private val player: Player) {
109
109
  /** Saves the current track and its position; does nothing without a current track. */
110
110
  fun save() {
111
111
  val track = player.currentTrack ?: return
112
- // A live item reports 0 until it has loaded, so 0 is saved unset too.
113
- val positionMs =
114
- player.position.takeUnless { player.isCurrentItemLive || it == 0L } ?: C.TIME_UNSET
112
+ val positionMs = player.restorablePositionMs
115
113
 
116
114
  prefs.edit {
117
115
  putLong(KEY_POSITION_MS, positionMs)
@@ -1455,6 +1455,17 @@ internal constructor(
1455
1455
  val isCurrentItemLive: Boolean
1456
1456
  get() = sessionPlayer.isCurrentMediaItemLive
1457
1457
 
1458
+ /**
1459
+ * [position] to set the queue at again, or [C.TIME_UNSET], where Media3 starts at the default
1460
+ * position: for a live item, for 0, which a live item also reports before it has loaded, and
1461
+ * after the end, so the track plays again.
1462
+ */
1463
+ internal val restorablePositionMs: Long
1464
+ get() =
1465
+ position.takeUnless {
1466
+ isCurrentItemLive || it == 0L || sessionPlayer.playbackState == MediaPlayer.STATE_ENDED
1467
+ } ?: C.TIME_UNSET
1468
+
1458
1469
  // MARK: - Buffer Configuration
1459
1470
 
1460
1471
  /** Takes effect for future buffering; what is buffered stays. */
@@ -1,5 +1,10 @@
1
1
  package androidx.media3.session
2
2
 
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import androidx.media3.session.legacy.MediaControllerCompat
6
+ import androidx.media3.session.legacy.PlaybackStateCompat
7
+
3
8
  // Read in place: Robolectric can't connect a controller to the session.
4
9
 
5
10
  /** The state legacy controllers (Android Auto, Bluetooth, the system UI) were last told. */
@@ -17,3 +22,17 @@ internal fun MediaSession.controllerError() = impl.playerInfo.playerError
17
22
 
18
23
  /** Whether media3 controllers were last told it plays. */
19
24
  internal fun MediaSession.controllerPlaying() = impl.playerInfo.isPlaying
25
+
26
+ /** Counts the playback states legacy controllers are told from now on. */
27
+ internal fun MediaSession.countLegacyStateUpdates(): () -> Int {
28
+ var count = 0
29
+ impl.mediaSessionLegacyStub.sessionCompat.controller.registerCallback(
30
+ object : MediaControllerCompat.Callback() {
31
+ override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
32
+ count += 1
33
+ }
34
+ },
35
+ Handler(Looper.getMainLooper()),
36
+ )
37
+ return { count }
38
+ }
@@ -0,0 +1,32 @@
1
+ package com.audiobrowser
2
+
3
+ import android.net.Uri
4
+ import java.nio.ByteBuffer
5
+ import java.nio.ByteOrder
6
+ import java.time.Duration
7
+ import org.junit.rules.TemporaryFolder
8
+
9
+ /** A WAV of [duration] of 8 kHz mono 8-bit silence, its data size in its header. */
10
+ fun silentWavBytes(duration: Duration): ByteArray {
11
+ val samples = (duration.toMillis() * 8).toInt()
12
+ val header =
13
+ ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
14
+ put("RIFF".toByteArray())
15
+ putInt(36 + samples)
16
+ put("WAVEfmt ".toByteArray())
17
+ putInt(16)
18
+ putShort(1)
19
+ putShort(1)
20
+ putInt(8_000)
21
+ putInt(8_000)
22
+ putShort(1)
23
+ putShort(8)
24
+ put("data".toByteArray())
25
+ putInt(samples)
26
+ }
27
+ return header.array() + ByteArray(samples) { 0x80.toByte() }
28
+ }
29
+
30
+ /** The `file:` URI of [silentWavBytes] written to `silence.wav` here: a second call throws. */
31
+ fun TemporaryFolder.silentWavUri(duration: Duration): String =
32
+ Uri.fromFile(newFile("silence.wav").apply { writeBytes(silentWavBytes(duration)) }).toString()
@@ -1,7 +1,5 @@
1
1
  package com.audiobrowser
2
2
 
3
- import android.content.ComponentName
4
- import android.os.Binder
5
3
  import android.os.Bundle
6
4
  import android.os.Looper
7
5
  import androidx.media3.common.HeartRating
@@ -13,9 +11,7 @@ import org.junit.After
13
11
  import org.junit.Assert.assertEquals
14
12
  import org.junit.Test
15
13
  import org.junit.runner.RunWith
16
- import org.robolectric.Robolectric
17
14
  import org.robolectric.RobolectricTestRunner
18
- import org.robolectric.RuntimeEnvironment
19
15
  import org.robolectric.Shadows.shadowOf
20
16
 
21
17
  /**
@@ -26,15 +22,7 @@ import org.robolectric.Shadows.shadowOf
26
22
  @RunWith(RobolectricTestRunner::class)
27
23
  class LegacyRatingTest {
28
24
 
29
- private val controller = run {
30
- val application = RuntimeEnvironment.getApplication()
31
- shadowOf(application)
32
- .setComponentNameAndServiceForBindService(
33
- ComponentName(application, HeadlessTaskService::class.java),
34
- Binder(),
35
- )
36
- Robolectric.buildService(Service::class.java).create()
37
- }
25
+ private val controller = buildService()
38
26
  private val service = controller.get()
39
27
  private val player = service.player
40
28
  private val legacyController =
@@ -48,7 +36,6 @@ class LegacyRatingTest {
48
36
  Bundle.EMPTY,
49
37
  false,
50
38
  )
51
- private val session = service.onGetSession(legacyController)!!
52
39
 
53
40
  @After
54
41
  fun destroy() {
@@ -62,13 +49,13 @@ class LegacyRatingTest {
62
49
  val result =
63
50
  player
64
51
  .getMediaSessionCallback()
65
- .onSetRating(session, legacyController, mediaId, HeartRating(heart))
52
+ .onSetRating(service.session, legacyController, mediaId, HeartRating(heart))
66
53
  .get()
67
54
  idle()
68
55
  return result.resultCode
69
56
  }
70
57
 
71
- private fun currentMediaId() = session.player.currentMediaItem!!.mediaId
58
+ private fun currentMediaId() = service.session.player.currentMediaItem!!.mediaId
72
59
 
73
60
  private fun loadTrack() {
74
61
  controller.bind()
@@ -85,11 +72,11 @@ class LegacyRatingTest {
85
72
 
86
73
  assertEquals(SessionResult.RESULT_SUCCESS, rate(currentMediaId(), true))
87
74
  assertEquals(true, player.currentTrack?.favorited)
88
- assertEquals(HeartRating(true), session.player.mediaMetadata.userRating)
75
+ assertEquals(HeartRating(true), service.session.player.mediaMetadata.userRating)
89
76
 
90
77
  assertEquals(SessionResult.RESULT_SUCCESS, rate(currentMediaId(), false))
91
78
  assertEquals(false, player.currentTrack?.favorited)
92
- assertEquals(HeartRating(false), session.player.mediaMetadata.userRating)
79
+ assertEquals(HeartRating(false), service.session.player.mediaMetadata.userRating)
93
80
  }
94
81
 
95
82
  @Test
@@ -98,6 +85,6 @@ class LegacyRatingTest {
98
85
 
99
86
  assertEquals(SessionResult.RESULT_ERROR_NOT_SUPPORTED, rate("b", true))
100
87
  assertEquals(false, player.currentTrack?.favorited)
101
- assertEquals(HeartRating(false), session.player.mediaMetadata.userRating)
88
+ assertEquals(HeartRating(false), service.session.player.mediaMetadata.userRating)
102
89
  }
103
90
  }
@@ -0,0 +1,48 @@
1
+ package com.audiobrowser
2
+
3
+ import android.content.ComponentName
4
+ import android.os.Binder
5
+ import android.os.Bundle
6
+ import android.os.Process
7
+ import androidx.annotation.OptIn
8
+ import androidx.media3.common.util.UnstableApi
9
+ import androidx.media3.session.MediaLibraryService.MediaLibrarySession
10
+ import androidx.media3.session.MediaSession
11
+ import org.robolectric.Robolectric
12
+ import org.robolectric.RuntimeEnvironment
13
+ import org.robolectric.Shadows.shadowOf
14
+ import org.robolectric.android.controller.ServiceController
15
+
16
+ /** A created [Service], whose binding to HeadlessTaskService connects. */
17
+ fun buildService(): ServiceController<Service> {
18
+ val application = RuntimeEnvironment.getApplication()
19
+ // Robolectric connects an unregistered binding with a null ComponentName, which the
20
+ // HeadlessTaskService connection's non-null parameter rejects.
21
+ shadowOf(application)
22
+ .setComponentNameAndServiceForBindService(
23
+ ComponentName(application, HeadlessTaskService::class.java),
24
+ Binder(),
25
+ )
26
+ return Robolectric.buildService(Service::class.java).create()
27
+ }
28
+
29
+ /** The service's session, which it otherwise hands only to a connecting controller. */
30
+ @get:OptIn(UnstableApi::class)
31
+ val Service.session: MediaLibrarySession
32
+ get() {
33
+ // onGetSession ignores its argument.
34
+ val session =
35
+ onGetSession(
36
+ MediaSession.ControllerInfo.createTestOnlyControllerInfo(
37
+ packageName,
38
+ 0,
39
+ Process.myUid(),
40
+ 0,
41
+ 0,
42
+ false,
43
+ Bundle.EMPTY,
44
+ false,
45
+ )
46
+ )
47
+ return checkNotNull(session) { "the session is released" }
48
+ }
@@ -1,18 +1,12 @@
1
1
  package com.audiobrowser
2
2
 
3
3
  import android.app.SearchManager
4
- import android.content.ComponentName
5
4
  import android.content.ContextWrapper
6
5
  import android.content.Intent
7
- import android.os.Binder
8
- import android.os.Bundle
9
6
  import android.os.Looper
10
7
  import android.os.Process
11
- import androidx.annotation.OptIn
12
8
  import androidx.media3.common.C
13
- import androidx.media3.common.util.UnstableApi
14
9
  import androidx.media3.session.MediaController
15
- import androidx.media3.session.MediaSession
16
10
  import com.audiobrowser.model.PlayerUpdateOptions
17
11
  import com.audiobrowser.player.PlaybackStateStore
18
12
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
@@ -26,7 +20,6 @@ import org.junit.Assert.assertNull
26
20
  import org.junit.Assert.assertTrue
27
21
  import org.junit.Test
28
22
  import org.junit.runner.RunWith
29
- import org.robolectric.Robolectric
30
23
  import org.robolectric.RobolectricTestRunner
31
24
  import org.robolectric.RuntimeEnvironment
32
25
  import org.robolectric.Shadows.shadowOf
@@ -34,17 +27,7 @@ import org.robolectric.Shadows.shadowOf
34
27
  @RunWith(RobolectricTestRunner::class)
35
28
  class ServiceTaskRemovedTest {
36
29
 
37
- private val controller = run {
38
- // Robolectric connects an unregistered binding with a null ComponentName, which the
39
- // HeadlessTaskService connection's non-null parameter rejects.
40
- val application = RuntimeEnvironment.getApplication()
41
- shadowOf(application)
42
- .setComponentNameAndServiceForBindService(
43
- ComponentName(application, HeadlessTaskService::class.java),
44
- Binder(),
45
- )
46
- Robolectric.buildService(Service::class.java).create()
47
- }
30
+ private val controller = buildService()
48
31
  private val service = controller.get()
49
32
  private val player = service.player
50
33
 
@@ -61,7 +44,6 @@ class ServiceTaskRemovedTest {
61
44
  idle()
62
45
  }
63
46
 
64
- @OptIn(UnstableApi::class)
65
47
  private fun connectController(packageName: String) {
66
48
  val application = RuntimeEnvironment.getApplication()
67
49
  shadowOf(application.packageManager)
@@ -70,21 +52,7 @@ class ServiceTaskRemovedTest {
70
52
  object : ContextWrapper(application) {
71
53
  override fun getPackageName() = packageName
72
54
  }
73
- // Only to reach the private session: onGetSession ignores its argument.
74
- val session =
75
- service.onGetSession(
76
- MediaSession.ControllerInfo.createTestOnlyControllerInfo(
77
- packageName,
78
- 0,
79
- Process.myUid(),
80
- 0,
81
- 0,
82
- false,
83
- Bundle.EMPTY,
84
- false,
85
- )
86
- )
87
- val future = MediaController.Builder(context, session!!.token).buildAsync()
55
+ val future = MediaController.Builder(context, service.session.token).buildAsync()
88
56
  idle()
89
57
  // Throws if the session refused the controller.
90
58
  future.get()
@@ -0,0 +1,114 @@
1
+ package com.audiobrowser
2
+
3
+ import android.os.Bundle
4
+ import android.os.Looper
5
+ import androidx.media3.common.C
6
+ import androidx.media3.session.countLegacyStateUpdates
7
+ import com.audiobrowser.util.TrackFactory
8
+ import java.time.Duration
9
+ import org.junit.After
10
+ import org.junit.Assert.assertEquals
11
+ import org.junit.Assert.assertTrue
12
+ import org.junit.Assert.fail
13
+ import org.junit.Rule
14
+ import org.junit.Test
15
+ import org.junit.rules.TemporaryFolder
16
+ import org.junit.runner.RunWith
17
+ import org.robolectric.RobolectricTestRunner
18
+ import org.robolectric.RuntimeEnvironment
19
+ import org.robolectric.Shadows.shadowOf
20
+ import org.robolectric.android.controller.ServiceController
21
+ import org.robolectric.annotation.Config
22
+ import org.robolectric.shadows.ShadowSystemClock
23
+
24
+ /**
25
+ * What the service's session tells External Surfaces while playback runs with nothing changing,
26
+ * with and without the app's [Service.PERIODIC_POSITION_UPDATES] meta-data.
27
+ */
28
+ @RunWith(RobolectricTestRunner::class)
29
+ @Config(sdk = [28])
30
+ class SessionPositionUpdatesTest {
31
+
32
+ @get:Rule val folder = TemporaryFolder()
33
+
34
+ private val application = RuntimeEnvironment.getApplication()
35
+ private lateinit var controller: ServiceController<Service>
36
+ private val service
37
+ get() = controller.get()
38
+
39
+ private val player
40
+ get() = service.player
41
+
42
+ @After
43
+ fun destroy() {
44
+ controller.destroy()
45
+ }
46
+
47
+ @Test
48
+ fun `by default the session re-sends the playback state every 3 s`() {
49
+ startService(metaData = null)
50
+
51
+ assertEquals(10, legacyStateUpdatesOverSteadyPlayback(Duration.ofSeconds(30)))
52
+ }
53
+
54
+ @Test
55
+ fun `the app's meta-data stops the periodic playback state updates`() {
56
+ startService(metaData = Bundle().apply { putBoolean(Service.PERIODIC_POSITION_UPDATES, false) })
57
+
58
+ assertEquals(0, legacyStateUpdatesOverSteadyPlayback(Duration.ofSeconds(30)))
59
+
60
+ // The counter hears a real change.
61
+ val updates = service.session.countLegacyStateUpdates()
62
+ player.pause()
63
+ advance(Duration.ofMillis(500))
64
+ assertTrue(updates() > 0)
65
+ }
66
+
67
+ private fun startService(metaData: Bundle?) {
68
+ shadowOf(application.packageManager)
69
+ .getInternalMutablePackageInfo(application.packageName)
70
+ .applicationInfo!!
71
+ .metaData = metaData
72
+ controller = buildService()
73
+ }
74
+
75
+ /** Plays a silent WAV, then counts the legacy playback states sent over [duration]. */
76
+ private fun legacyStateUpdatesOverSteadyPlayback(duration: Duration): Int {
77
+ player.exoPlayer.trackSelectionParameters =
78
+ player.exoPlayer.trackSelectionParameters
79
+ .buildUpon()
80
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
81
+ .build()
82
+ goOnline(application)
83
+ val src = folder.silentWavUri(Duration.ofSeconds(45))
84
+ player.exoPlayer.setMediaItems(listOf(TrackFactory.toMedia3(TestFixtures.track(src = src))))
85
+ player.exoPlayer.prepare()
86
+ player.play()
87
+ advanceUntil("playing") { player.exoPlayer.isPlaying }
88
+ // Lets the updates that starting playback sends settle.
89
+ advance(Duration.ofSeconds(1))
90
+
91
+ val updates = service.session.countLegacyStateUpdates()
92
+ repeat((duration.toMillis() / 500).toInt()) { advance(Duration.ofMillis(500)) }
93
+
94
+ assertTrue(player.exoPlayer.isPlaying)
95
+ return updates()
96
+ }
97
+
98
+ private fun advance(duration: Duration) {
99
+ ShadowSystemClock.advanceBy(duration)
100
+ Thread.sleep(10)
101
+ shadowOf(Looper.getMainLooper()).idle()
102
+ }
103
+
104
+ private fun advanceUntil(what: String, condition: () -> Boolean) {
105
+ val deadline = System.currentTimeMillis() + 5_000
106
+ while (!condition()) {
107
+ if (System.currentTimeMillis() > deadline)
108
+ fail(
109
+ "timed out waiting for $what: ${player.playbackState}, exo ${player.exoPlayer.playbackState}"
110
+ )
111
+ advance(Duration.ofMillis(100))
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,182 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import androidx.media3.common.C
6
+ import androidx.media3.common.Player as MediaPlayer
7
+ import androidx.media3.common.Timeline
8
+ import androidx.media3.session.MediaController
9
+ import com.audiobrowser.AudioBrowser
10
+ import com.audiobrowser.TestFixtures
11
+ import com.audiobrowser.browser.BrowserManager
12
+ import com.audiobrowser.buildService
13
+ import com.audiobrowser.session
14
+ import com.audiobrowser.silentWavUri
15
+ import com.audiobrowser.util.JsPromise
16
+ import com.audiobrowser.util.TrackFactory
17
+ import com.margelo.nitro.audiobrowser.NativeBrowserConfiguration
18
+ import com.margelo.nitro.audiobrowser.Track
19
+ import com.margelo.nitro.audiobrowser.TrackLoadEvent
20
+ import com.margelo.nitro.core.Promise
21
+ import java.time.Duration
22
+ import java.util.concurrent.TimeUnit
23
+ import org.junit.After
24
+ import org.junit.Assert.assertEquals
25
+ import org.junit.Assert.fail
26
+ import org.junit.Rule
27
+ import org.junit.Test
28
+ import org.junit.rules.TemporaryFolder
29
+ import org.junit.runner.RunWith
30
+ import org.mockito.Mockito.RETURNS_DEFAULTS
31
+ import org.mockito.Mockito.mock
32
+ import org.mockito.stubbing.Answer
33
+ import org.robolectric.RobolectricTestRunner
34
+ import org.robolectric.RuntimeEnvironment
35
+ import org.robolectric.Shadows.shadowOf
36
+ import org.robolectric.annotation.Config
37
+ import org.robolectric.shadows.ShadowSystemClock
38
+
39
+ /** A controller's set of media items keeps where a handleTrackLoad left the player. */
40
+ @RunWith(RobolectricTestRunner::class)
41
+ @Config(sdk = [28])
42
+ class HandleTrackLoadSeekTest {
43
+
44
+ @get:Rule val folder = TemporaryFolder()
45
+
46
+ private val service = buildService()
47
+ private val player = service.get().player
48
+
49
+ /**
50
+ * Playlist changes since the handler's player calls ran, which change it too; null until they
51
+ * have.
52
+ */
53
+ private var setsAfterHandler: Int? = null
54
+
55
+ @After
56
+ fun destroy() {
57
+ service.destroy()
58
+ }
59
+
60
+ private fun handlingTrackLoadWith(onLoad: (Track) -> Unit) {
61
+ // JS runs the handler's player calls on the main thread before its promise settles.
62
+ val handler: (TrackLoadEvent) -> Promise<Promise<Unit>> = { event ->
63
+ val inner = JsPromise<Unit>()
64
+ val outer = JsPromise<Promise<Unit>>()
65
+ Handler(Looper.getMainLooper()).post {
66
+ onLoad(event.track)
67
+ setsAfterHandler = 0
68
+ inner.resolve(Unit)
69
+ outer.resolve(inner.promise)
70
+ }
71
+ outer.promise
72
+ }
73
+ val configuration =
74
+ NativeBrowserConfiguration(
75
+ path = null,
76
+ request = null,
77
+ requestResolver = null,
78
+ browse = null,
79
+ browseResolver = null,
80
+ media = null,
81
+ artwork = null,
82
+ nowPlayingArtwork = null,
83
+ routes = null,
84
+ singleTrack = null,
85
+ handleTrackLoad = handler,
86
+ androidControllerOfflineError = null,
87
+ viewMoreTitle = null,
88
+ carPlayLoadingTitle = null,
89
+ resolveAlbumPath = null,
90
+ formatNavigationError = null,
91
+ )
92
+ val browserManager = BrowserManager()
93
+ player.browser =
94
+ mock(
95
+ AudioBrowser::class.java,
96
+ Answer {
97
+ when {
98
+ it.method.name == "getConfiguration" -> configuration
99
+ it.method.name.startsWith("getBrowserManager") -> browserManager
100
+ else -> RETURNS_DEFAULTS.answer(it)
101
+ }
102
+ },
103
+ )
104
+ player.notifyBrowserConfigurationReady()
105
+ }
106
+
107
+ /**
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.
110
+ */
111
+ private fun setFromController(track: Track) {
112
+ player.exoPlayer.addListener(
113
+ object : MediaPlayer.Listener {
114
+ override fun onTimelineChanged(timeline: Timeline, reason: Int) {
115
+ if (reason == MediaPlayer.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED) {
116
+ setsAfterHandler = setsAfterHandler?.plus(1)
117
+ }
118
+ }
119
+ }
120
+ )
121
+ val future =
122
+ MediaController.Builder(RuntimeEnvironment.getApplication(), service.get().session.token)
123
+ .buildAsync()
124
+ idleUntil("the controller to connect") { future.isDone }
125
+ future.get().setMediaItem(TrackFactory.toMedia3(track))
126
+ idleUntil("media3 to set the items") { (setsAfterHandler ?: 0) >= 1 }
127
+ }
128
+
129
+ private fun idleUntil(what: String, condition: () -> Boolean) {
130
+ repeat(200) {
131
+ if (condition()) return
132
+ ShadowSystemClock.advanceBy(Duration.ofMillis(100))
133
+ Thread.sleep(10)
134
+ shadowOf(Looper.getMainLooper()).idle()
135
+ }
136
+ fail("timed out waiting for $what, the engine in state ${player.exoPlayer.playbackState}")
137
+ }
138
+
139
+ private fun silentTrack(duration: Duration) =
140
+ TestFixtures.track(id = "a", src = folder.silentWavUri(duration))
141
+
142
+ @Test
143
+ fun `a load then a seek in the handler holds the seek`() {
144
+ val track = silentTrack(Duration.ofMinutes(2))
145
+ handlingTrackLoadWith {
146
+ player.load(it)
147
+ player.seekTo(60, TimeUnit.SECONDS)
148
+ }
149
+
150
+ setFromController(track)
151
+
152
+ assertEquals(60_000L, player.exoPlayer.currentPosition)
153
+ }
154
+
155
+ @Test
156
+ fun `a setQueue at a position in the handler holds the position`() {
157
+ val track = silentTrack(Duration.ofMinutes(2))
158
+ handlingTrackLoadWith { player.setQueue(arrayOf(it), 0, 60_000) }
159
+
160
+ setFromController(track)
161
+
162
+ assertEquals(60_000L, player.exoPlayer.currentPosition)
163
+ }
164
+
165
+ @Test
166
+ fun `an ended track a handler leaves is set again at its start`() {
167
+ val track = silentTrack(Duration.ofMillis(500))
168
+ player.exoPlayer.trackSelectionParameters =
169
+ player.exoPlayer.trackSelectionParameters
170
+ .buildUpon()
171
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
172
+ .build()
173
+ player.setQueue(arrayOf(track))
174
+ player.play()
175
+ idleUntil("the track to end") { player.exoPlayer.playbackState == MediaPlayer.STATE_ENDED }
176
+ handlingTrackLoadWith {}
177
+
178
+ setFromController(track)
179
+
180
+ assertEquals(0L, player.exoPlayer.currentPosition)
181
+ }
182
+ }
@@ -17,11 +17,10 @@ import androidx.media3.exoplayer.upstream.DefaultAllocator
17
17
  import androidx.media3.exoplayer.upstream.DefaultBandwidthMeter
18
18
  import com.audiobrowser.TestFixtures.track
19
19
  import com.audiobrowser.model.RetryPolicy
20
+ import com.audiobrowser.silentWavBytes
20
21
  import com.audiobrowser.util.TrackFactory
21
22
  import java.io.IOException
22
23
  import java.net.ServerSocket
23
- import java.nio.ByteBuffer
24
- import java.nio.ByteOrder
25
24
  import java.time.Duration
26
25
  import java.util.concurrent.atomic.AtomicInteger
27
26
  import kotlin.concurrent.thread
@@ -97,7 +96,11 @@ class LiveStreamEndTest {
97
96
 
98
97
  @Test
99
98
  fun `a live stream whose container declares its end ends there`() {
100
- serve(framesFor = { 0 }, contentType = "audio/wav", body = { silentWav() })
99
+ serve(
100
+ framesFor = { 0 },
101
+ contentType = "audio/wav",
102
+ body = { silentWavBytes(Duration.ofSeconds(1)) },
103
+ )
101
104
 
102
105
  val outcome = play(live = true, RetryPolicy.Infinite())
103
106
 
@@ -287,27 +290,6 @@ class LiveStreamEndTest {
287
290
  const val SECONDS_1_5 = 57
288
291
  const val SECONDS_60 = 2_297
289
292
 
290
- /** A WAV of a second of 8 kHz mono 8-bit silence, its data size in its header. */
291
- fun silentWav(): ByteArray {
292
- val samples = 8_000
293
- val header =
294
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
295
- put("RIFF".toByteArray())
296
- putInt(36 + samples)
297
- put("WAVEfmt ".toByteArray())
298
- putInt(16)
299
- putShort(1)
300
- putShort(1)
301
- putInt(8_000)
302
- putInt(8_000)
303
- putShort(1)
304
- putShort(8)
305
- put("data".toByteArray())
306
- putInt(samples)
307
- }
308
- return header.array() + ByteArray(samples) { 0x80.toByte() }
309
- }
310
-
311
293
  /** [frames] ADTS frames of AAC LC at 44.1 kHz, mono, with 100 zero bytes of payload each. */
312
294
  fun silentAdts(frames: Int): ByteArray {
313
295
  val length = 7 + 100
@@ -4,7 +4,6 @@ import android.content.Context
4
4
  import android.media.AudioManager
5
5
  import android.net.ConnectivityManager
6
6
  import android.net.NetworkCapabilities
7
- import android.net.Uri
8
7
  import android.os.Looper
9
8
  import androidx.media3.common.C
10
9
  import androidx.media3.common.Metadata
@@ -17,15 +16,14 @@ import com.audiobrowser.TestFixtures
17
16
  import com.audiobrowser.goOnline
18
17
  import com.audiobrowser.model.PlayerSetupOptions
19
18
  import com.audiobrowser.model.RetryPolicy
19
+ import com.audiobrowser.silentWavBytes
20
+ import com.audiobrowser.silentWavUri
20
21
  import com.audiobrowser.util.TrackFactory
21
22
  import com.margelo.nitro.audiobrowser.AndroidPlayerWakeMode
22
23
  import com.margelo.nitro.audiobrowser.Playback
23
24
  import com.margelo.nitro.audiobrowser.PlaybackState
24
- import java.io.File
25
25
  import java.io.IOException
26
26
  import java.net.ServerSocket
27
- import java.nio.ByteBuffer
28
- import java.nio.ByteOrder
29
27
  import java.time.Duration
30
28
  import java.util.concurrent.CopyOnWriteArrayList
31
29
  import java.util.concurrent.CountDownLatch
@@ -85,7 +83,7 @@ class PlayerRetryTest {
85
83
 
86
84
  @Test
87
85
  fun `a terminal error ends the load`() {
88
- play(Uri.fromFile(silentWav()).toString())
86
+ play(folder.silentWavUri(Duration.ofMinutes(1)))
89
87
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
90
88
 
91
89
  player.playerListener.onPlayerError(
@@ -170,7 +168,7 @@ class PlayerRetryTest {
170
168
 
171
169
  @Test
172
170
  fun `removing a failed current track plays the next`() {
173
- failTerminally(Uri.fromFile(silentWav()).toString())
171
+ failTerminally(folder.silentWavUri(Duration.ofMinutes(1)))
174
172
 
175
173
  player.remove(listOf(0))
176
174
 
@@ -179,7 +177,7 @@ class PlayerRetryTest {
179
177
 
180
178
  @Test
181
179
  fun `removing another track keeps a terminal error`() {
182
- failTerminally(Uri.fromFile(silentWav()).toString())
180
+ failTerminally(folder.silentWavUri(Duration.ofMinutes(1)))
183
181
 
184
182
  player.remove(listOf(1))
185
183
  shadowOf(Looper.getMainLooper()).idle()
@@ -190,7 +188,7 @@ class PlayerRetryTest {
190
188
 
191
189
  @Test
192
190
  fun `removing the current track after a cancelled retry stays idle and paused`() {
193
- pauseDuringRetry(Uri.fromFile(silentWav()).toString()) { player.pause() }
191
+ pauseDuringRetry(folder.silentWavUri(Duration.ofMinutes(1))) { player.pause() }
194
192
 
195
193
  player.remove(listOf(0))
196
194
  shadowOf(Looper.getMainLooper()).idle()
@@ -202,7 +200,7 @@ class PlayerRetryTest {
202
200
 
203
201
  @Test
204
202
  fun `removing a failed current track while paused is paused`() {
205
- failTerminally(Uri.fromFile(silentWav()).toString())
203
+ failTerminally(folder.silentWavUri(Duration.ofMinutes(1)))
206
204
  player.pause()
207
205
  shadowOf(Looper.getMainLooper()).idle()
208
206
 
@@ -217,7 +215,7 @@ class PlayerRetryTest {
217
215
  fun `adding a track after a cancelled retry stays idle and paused`() {
218
216
  pauseDuringRetry { player.pause() }
219
217
 
220
- player.add(TestFixtures.track(src = Uri.fromFile(silentWav()).toString()))
218
+ player.add(TestFixtures.track(src = folder.silentWavUri(Duration.ofMinutes(1))))
221
219
  shadowOf(Looper.getMainLooper()).idle()
222
220
 
223
221
  assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
@@ -228,7 +226,7 @@ class PlayerRetryTest {
228
226
  fun `adding to an empty queue loads`() {
229
227
  player.setup(PlayerSetupOptions())
230
228
 
231
- player.add(TestFixtures.track(src = Uri.fromFile(silentWav()).toString()))
229
+ player.add(TestFixtures.track(src = folder.silentWavUri(Duration.ofMinutes(1))))
232
230
  shadowOf(Looper.getMainLooper()).idle()
233
231
 
234
232
  assertNotEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
@@ -276,7 +274,7 @@ class PlayerRetryTest {
276
274
  @Test
277
275
  fun `a load failing while paused stays paused and the next play reloads`() {
278
276
  val server = ServerSocket(0)
279
- val wav = silentWav().readBytes()
277
+ val wav = silentWavBytes(Duration.ofMinutes(1))
280
278
  val sent = CountDownLatch(1)
281
279
  val drop = CountDownLatch(1)
282
280
  // Serves five seconds of the minute, holds the connection until the drop, then refuses.
@@ -379,7 +377,7 @@ class PlayerRetryTest {
379
377
  @Test
380
378
  fun `a track change on a stopped engine starts no Load until it is prepared`() {
381
379
  goOnline(context)
382
- val wav = Uri.fromFile(silentWav()).toString()
380
+ val wav = folder.silentWavUri(Duration.ofMinutes(1))
383
381
  play(wav, wav, retryPolicy = RetryPolicy.Infinite())
384
382
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
385
383
  player.exoPlayer.stop()
@@ -491,7 +489,7 @@ class PlayerRetryTest {
491
489
  @Test
492
490
  fun `a failure report that arrives after a reconnect is not the new connection's`() {
493
491
  goOnline(context)
494
- play(Uri.fromFile(silentWav()).toString(), retryPolicy = RetryPolicy.Infinite())
492
+ play(folder.silentWavUri(Duration.ofMinutes(1)), retryPolicy = RetryPolicy.Infinite())
495
493
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
496
494
 
497
495
  // Posted from the playback thread before the go-live reconnect, run after it.
@@ -506,7 +504,7 @@ class PlayerRetryTest {
506
504
  @Test
507
505
  fun `with retry, a stuck engine reconnects and never ends in an error`() {
508
506
  goOnline(context)
509
- play(Uri.fromFile(silentWav()).toString(), retryPolicy = RetryPolicy.Infinite())
507
+ play(folder.silentWavUri(Duration.ofMinutes(1)), retryPolicy = RetryPolicy.Infinite())
510
508
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
511
509
 
512
510
  // As media3 leaves a stuck engine: idle, with the error.
@@ -522,7 +520,7 @@ class PlayerRetryTest {
522
520
  @Test
523
521
  fun `a title after a reconnect inside the retry loop shows`() {
524
522
  goOnline(context)
525
- play(Uri.fromFile(silentWav()).toString(), retryPolicy = RetryPolicy.Infinite())
523
+ play(folder.silentWavUri(Duration.ofMinutes(1)), retryPolicy = RetryPolicy.Infinite())
526
524
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
527
525
  player.exoPlayer.stop()
528
526
  player.playerListener.onPlayerError(stuck())
@@ -536,7 +534,7 @@ class PlayerRetryTest {
536
534
 
537
535
  @Test
538
536
  fun `with retry off, a stuck engine ends in the stalled error`() {
539
- play(Uri.fromFile(silentWav()).toString())
537
+ play(folder.silentWavUri(Duration.ofMinutes(1)))
540
538
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
541
539
 
542
540
  player.playerListener.onPlayerError(stuck())
@@ -606,27 +604,4 @@ class PlayerRetryTest {
606
604
  shadowOf(Looper.getMainLooper()).idle()
607
605
  }
608
606
  }
609
-
610
- /** A minute of 8 kHz mono 8-bit silence, long enough that no test reaches its end. */
611
- private fun silentWav(): File {
612
- val samples = 8_000 * 60
613
- val header =
614
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
615
- put("RIFF".toByteArray())
616
- putInt(36 + samples)
617
- put("WAVEfmt ".toByteArray())
618
- putInt(16)
619
- putShort(1)
620
- putShort(1)
621
- putInt(8_000)
622
- putInt(8_000)
623
- putShort(1)
624
- putShort(8)
625
- put("data".toByteArray())
626
- putInt(samples)
627
- }
628
- return folder.newFile("silence.wav").apply {
629
- writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
630
- }
631
- }
632
607
  }
@@ -1,6 +1,5 @@
1
1
  package com.audiobrowser.player
2
2
 
3
- import android.net.Uri
4
3
  import android.os.Looper
5
4
  import androidx.media3.common.C
6
5
  import androidx.media3.common.Player as MediaPlayer
@@ -8,12 +7,10 @@ import androidx.media3.common.util.Util
8
7
  import com.audiobrowser.Callbacks
9
8
  import com.audiobrowser.TestFixtures
10
9
  import com.audiobrowser.model.PlayerSetupOptions
10
+ import com.audiobrowser.silentWavUri
11
11
  import com.audiobrowser.util.TrackFactory
12
12
  import com.margelo.nitro.audiobrowser.Playback
13
13
  import com.margelo.nitro.audiobrowser.PlaybackState
14
- import java.io.File
15
- import java.nio.ByteBuffer
16
- import java.nio.ByteOrder
17
14
  import java.time.Duration
18
15
  import java.util.concurrent.TimeUnit
19
16
  import org.junit.After
@@ -152,7 +149,7 @@ class PlayerSetupEndedTest {
152
149
  player.setup(PlayerSetupOptions())
153
150
  player.setCallbacks(callbacks)
154
151
  disableAudio()
155
- val src = Uri.fromFile(silentWav()).toString()
152
+ val src = folder.silentWavUri(Duration.ofMillis(500))
156
153
  player.exoPlayer.setMediaItems(
157
154
  List(tracks) { TrackFactory.toMedia3(TestFixtures.track(title = "$it", src = src)) }
158
155
  )
@@ -195,27 +192,4 @@ class PlayerSetupEndedTest {
195
192
  shadowOf(Looper.getMainLooper()).idle()
196
193
  }
197
194
  }
198
-
199
- /** Half a second of 8 kHz mono 8-bit silence. */
200
- private fun silentWav(): File {
201
- val samples = 4_000
202
- val header =
203
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
204
- put("RIFF".toByteArray())
205
- putInt(36 + samples)
206
- put("WAVEfmt ".toByteArray())
207
- putInt(16)
208
- putShort(1)
209
- putShort(1)
210
- putInt(8_000)
211
- putInt(8_000)
212
- putShort(1)
213
- putShort(8)
214
- put("data".toByteArray())
215
- putInt(samples)
216
- }
217
- return folder.newFile("silence.wav").apply {
218
- writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
219
- }
220
- }
221
195
  }
@@ -2,7 +2,6 @@ package com.audiobrowser.player
2
2
 
3
3
  import android.content.Context
4
4
  import android.media.AudioManager
5
- import android.net.Uri
6
5
  import android.os.Looper
7
6
  import androidx.media3.common.C
8
7
  import androidx.media3.common.Player as MediaPlayer
@@ -10,14 +9,13 @@ import com.audiobrowser.Callbacks
10
9
  import com.audiobrowser.TestFixtures
11
10
  import com.audiobrowser.model.PlayerSetupOptions
12
11
  import com.audiobrowser.remote.FakeRemote
12
+ import com.audiobrowser.silentWavUri
13
13
  import com.audiobrowser.util.TrackFactory
14
14
  import com.margelo.nitro.audiobrowser.Playback
15
15
  import com.margelo.nitro.audiobrowser.PlaybackState
16
16
  import com.margelo.nitro.audiobrowser.PlayingState
17
17
  import com.margelo.nitro.audiobrowser.RemoteOutputsOptions
18
- import java.io.File
19
- import java.nio.ByteBuffer
20
- import java.nio.ByteOrder
18
+ import java.time.Duration
21
19
  import org.junit.After
22
20
  import org.junit.Assert.assertEquals
23
21
  import org.junit.Assert.assertFalse
@@ -65,7 +63,7 @@ class PlayerSuppressionTest {
65
63
  fun play() {
66
64
  player.setup(PlayerSetupOptions())
67
65
  player.setCallbacks(callbacks)
68
- val src = Uri.fromFile(silentWav()).toString()
66
+ val src = folder.silentWavUri(Duration.ofMinutes(1))
69
67
  player.exoPlayer.trackSelectionParameters =
70
68
  player.exoPlayer.trackSelectionParameters
71
69
  .buildUpon()
@@ -353,27 +351,4 @@ class PlayerSuppressionTest {
353
351
  shadowOf(Looper.getMainLooper()).idle()
354
352
  }
355
353
  }
356
-
357
- /** A minute of 8 kHz mono 8-bit silence, long enough that no test reaches its end. */
358
- private fun silentWav(): File {
359
- val samples = 8_000 * 60
360
- val header =
361
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
362
- put("RIFF".toByteArray())
363
- putInt(36 + samples)
364
- put("WAVEfmt ".toByteArray())
365
- putInt(16)
366
- putShort(1)
367
- putShort(1)
368
- putInt(8_000)
369
- putInt(8_000)
370
- putShort(1)
371
- putShort(8)
372
- put("data".toByteArray())
373
- putInt(samples)
374
- }
375
- return folder.newFile("silence.wav").apply {
376
- writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
377
- }
378
- }
379
354
  }
@@ -1,6 +1,5 @@
1
1
  package com.audiobrowser.player
2
2
 
3
- import android.net.Uri
4
3
  import android.os.Looper
5
4
  import androidx.media3.common.C
6
5
  import androidx.media3.common.Player as MediaPlayer
@@ -10,12 +9,10 @@ import com.audiobrowser.TestFixtures
10
9
  import com.audiobrowser.goOnline
11
10
  import com.audiobrowser.model.PlayerSetupOptions
12
11
  import com.audiobrowser.model.RetryPolicy
12
+ import com.audiobrowser.silentWavUri
13
13
  import com.audiobrowser.util.TrackFactory
14
14
  import com.margelo.nitro.audiobrowser.Playback
15
15
  import com.margelo.nitro.audiobrowser.PlaybackState
16
- import java.io.File
17
- import java.nio.ByteBuffer
18
- import java.nio.ByteOrder
19
16
  import java.time.Duration
20
17
  import org.junit.After
21
18
  import org.junit.Assert.assertEquals
@@ -55,7 +52,7 @@ class SessionPlayTest {
55
52
 
56
53
  @Test
57
54
  fun `an app's play handler takes a session play once and nothing plays`() {
58
- load(Uri.fromFile(silentWav()).toString())
55
+ load(folder.silentWavUri(Duration.ofMillis(500)))
59
56
  player.stop()
60
57
  `when`(callbacks.handleRemotePlay()).thenReturn(true)
61
58
 
@@ -70,7 +67,7 @@ class SessionPlayTest {
70
67
 
71
68
  @Test
72
69
  fun `a session play after a stop loads once and plays`() {
73
- load(Uri.fromFile(silentWav()).toString())
70
+ load(folder.silentWavUri(Duration.ofMillis(500)))
74
71
  player.stop()
75
72
  val before = states().size
76
73
 
@@ -82,7 +79,7 @@ class SessionPlayTest {
82
79
 
83
80
  @Test
84
81
  fun `setPlayWhenReady(true) after a stop loads`() {
85
- load(Uri.fromFile(silentWav()).toString())
82
+ load(folder.silentWavUri(Duration.ofMillis(500)))
86
83
  player.stop()
87
84
 
88
85
  // As JS setPlayWhenReady(true) does: the setter alone.
@@ -106,7 +103,7 @@ class SessionPlayTest {
106
103
 
107
104
  @Test
108
105
  fun `a setup's raised intent over a stop loads nothing`() {
109
- load(Uri.fromFile(silentWav()).toString())
106
+ load(folder.silentWavUri(Duration.ofMillis(500)))
110
107
  player.stop()
111
108
 
112
109
  val before = states().size
@@ -168,7 +165,7 @@ class SessionPlayTest {
168
165
  .build()
169
166
  player.applySetupPlayWhenReady(true)
170
167
 
171
- player.setQueue(arrayOf(TestFixtures.track(src = Uri.fromFile(silentWav()).toString())))
168
+ player.setQueue(arrayOf(TestFixtures.track(src = folder.silentWavUri(Duration.ofMillis(500)))))
172
169
 
173
170
  idleUntil("playing") { player.playbackState == PlaybackState.PLAYING }
174
171
  }
@@ -212,27 +209,4 @@ class SessionPlayTest {
212
209
  shadowOf(Looper.getMainLooper()).idle()
213
210
  }
214
211
  }
215
-
216
- /** Half a second of 8 kHz mono 8-bit silence. */
217
- private fun silentWav(): File {
218
- val samples = 4_000
219
- val header =
220
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
221
- put("RIFF".toByteArray())
222
- putInt(36 + samples)
223
- put("WAVEfmt ".toByteArray())
224
- putInt(16)
225
- putShort(1)
226
- putShort(1)
227
- putInt(8_000)
228
- putInt(8_000)
229
- putShort(1)
230
- putShort(8)
231
- put("data".toByteArray())
232
- putInt(samples)
233
- }
234
- return folder.newFile("silence.wav").apply {
235
- writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
236
- }
237
- }
238
212
  }
@@ -1,6 +1,5 @@
1
1
  package com.audiobrowser.player
2
2
 
3
- import android.net.Uri
4
3
  import android.os.Looper
5
4
  import androidx.media3.common.C
6
5
  import androidx.media3.common.Player as MediaPlayer
@@ -13,11 +12,9 @@ import com.audiobrowser.TestFixtures
13
12
  import com.audiobrowser.goOnline
14
13
  import com.audiobrowser.model.PlayerSetupOptions
15
14
  import com.audiobrowser.model.RetryPolicy
15
+ import com.audiobrowser.silentWavUri
16
16
  import com.audiobrowser.util.TrackFactory
17
17
  import com.margelo.nitro.audiobrowser.PlaybackState
18
- import java.io.File
19
- import java.nio.ByteBuffer
20
- import java.nio.ByteOrder
21
18
  import java.time.Duration
22
19
  import org.junit.After
23
20
  import org.junit.Assert.assertEquals
@@ -113,7 +110,7 @@ class SessionViewTest {
113
110
 
114
111
  @Test
115
112
  fun `an ended queue a rebuild carried idle reads ended`() {
116
- play(RetryPolicy.Default, Uri.fromFile(silentWav()).toString())
113
+ play(RetryPolicy.Default, folder.silentWavUri(Duration.ofMillis(500)))
117
114
  idleUntil("ENDED") { player.playbackState == PlaybackState.ENDED }
118
115
 
119
116
  player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
@@ -125,7 +122,7 @@ class SessionViewTest {
125
122
 
126
123
  @Test
127
124
  fun `the session hears the current track's title`() {
128
- play(RetryPolicy.Default, Uri.fromFile(silentWav()).toString())
125
+ play(RetryPolicy.Default, folder.silentWavUri(Duration.ofMillis(500)))
129
126
  idleUntil("ENDED") { player.playbackState == PlaybackState.ENDED }
130
127
 
131
128
  assertEquals("T", session.controllerTitle())
@@ -164,27 +161,4 @@ class SessionViewTest {
164
161
  shadowOf(Looper.getMainLooper()).idle()
165
162
  }
166
163
  }
167
-
168
- /** Half a second of 8 kHz mono 8-bit silence. */
169
- private fun silentWav(): File {
170
- val samples = 4_000
171
- val header =
172
- ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
173
- put("RIFF".toByteArray())
174
- putInt(36 + samples)
175
- put("WAVEfmt ".toByteArray())
176
- putInt(16)
177
- putShort(1)
178
- putShort(1)
179
- putInt(8_000)
180
- putInt(8_000)
181
- putShort(1)
182
- putShort(8)
183
- put("data".toByteArray())
184
- putInt(samples)
185
- }
186
- return folder.newFile("silence.wav").apply {
187
- writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
188
- }
189
- }
190
164
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.85",
3
+ "version": "0.2.0-next.87",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: 'The map for live audio: stream formats, missing durations, dropped connections, expiring URLs, and song titles carried in-band.'
2
+ description: "The map for live audio: stream formats, missing durations, dropped connections, expiring URLs, song titles carried in-band, and Android's periodic position updates."
3
3
  ---
4
4
 
5
5
  # Live Streams
@@ -144,13 +144,46 @@ resolved URL, so an expired one re-resolves only after that first attempt
144
144
  fails (see [Fresh URLs on reconnect](#fresh-urls-on-reconnect)).
145
145
  General seeking is in [Playback](/guide/playback).
146
146
 
147
+ ## Periodic position updates (Android)
148
+
149
+ While the player plays or loads, Media3's media session sends External
150
+ Surfaces the playback state again every 3 seconds: the notification, the lock
151
+ screen, Android Auto, Bluetooth, and Media3 controllers in other apps (a
152
+ watch, say). The update carries the current and buffered position, so a
153
+ surface that extrapolates the position corrects any drift.
154
+
155
+ A live track has no progress bar, so a drifting position never shows, and the
156
+ update only refreshes the state's timestamp. Android 16's Bluetooth service
157
+ logs each one as `tried to update with no new data`.
158
+
159
+ If your app plays only live streams, turn the update off with a literal
160
+ `false` in your app's manifest:
161
+
162
+ ```xml
163
+ <!-- android/app/src/main/AndroidManifest.xml, inside <application> -->
164
+ <meta-data
165
+ android:name="com.audiobrowser.PERIODIC_POSITION_UPDATES"
166
+ android:value="false" />
167
+ ```
168
+
169
+ Every real change still reaches the surfaces at once: state, play and pause,
170
+ seeks, speed, Now Playing and the queue. Surfaces extrapolate an on-demand
171
+ position from the last state, so their progress bars keep moving. What stops
172
+ is the correction: a position that drifts with no state change (a Sonos
173
+ speaker that slips while it still reports playing, say) stays wrong on the
174
+ surfaces until the next change.
175
+
176
+ Leave it on, the default, if your app plays on-demand audio. The flag is
177
+ Android-only: iOS and web have no such update.
178
+
147
179
  ## API summary
148
180
 
149
- | API | Purpose |
150
- | ------------------------------------------------------------ | ------------------------------------------------------------- |
151
- | [`Track.live`](/api/types/browser-nodes/#live) | Declare a live track: iOS live indicator, arms the live edge. |
152
- | [`seekToLiveEdge()`](/api/features/playback/#seektoliveedge) | Jump to the newest audio (no-op for non-live tracks). |
153
- | [`setupPlayer({ retry })`](/guide/errors#automatic-retry) | Automatic retry with first-connect and recovery budgets. |
154
- | [`retry()`](/guide/errors#manual-retry) | Restart from `'error'` with fresh budgets. |
155
- | [`media.resolve`](/guide/browser#media-and-artwork) | Build the stream request — signed / short-lived URLs. |
156
- | [`useOnline()`](/guide/network) | Connectivity for your own UI; playback reacts on its own. |
181
+ | API | Purpose |
182
+ | ----------------------------------------------------------------- | ----------------------------------------------------------------------- |
183
+ | [`Track.live`](/api/types/browser-nodes/#live) | Declare a live track: iOS live indicator, arms the live edge. |
184
+ | [`seekToLiveEdge()`](/api/features/playback/#seektoliveedge) | Jump to the newest audio (no-op for non-live tracks). |
185
+ | [`setupPlayer({ retry })`](/guide/errors#automatic-retry) | Automatic retry with first-connect and recovery budgets. |
186
+ | [`retry()`](/guide/errors#manual-retry) | Restart from `'error'` with fresh budgets. |
187
+ | [`media.resolve`](/guide/browser#media-and-artwork) | Build the stream request — signed / short-lived URLs. |
188
+ | [`useOnline()`](/guide/network) | Connectivity for your own UI; playback reacts on its own. |
189
+ | [`PERIODIC_POSITION_UPDATES`](#periodic-position-updates-android) | Android manifest flag: stop the 3 s position update for live-only apps. |