react-native-audio-browser 0.2.0-next.64 → 0.2.0-next.66

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.
@@ -95,11 +95,14 @@ import kotlin.time.Duration.Companion.seconds
95
95
  import kotlinx.coroutines.CancellationException
96
96
  import kotlinx.coroutines.CompletableDeferred
97
97
  import kotlinx.coroutines.CoroutineScope
98
+ import kotlinx.coroutines.CoroutineStart
99
+ import kotlinx.coroutines.DelicateCoroutinesApi
98
100
  import kotlinx.coroutines.Job
99
101
  import kotlinx.coroutines.MainScope
100
102
  import kotlinx.coroutines.async
101
103
  import kotlinx.coroutines.cancel
102
104
  import kotlinx.coroutines.cancelChildren
105
+ import kotlinx.coroutines.ensureActive
103
106
  import kotlinx.coroutines.launch
104
107
  import kotlinx.coroutines.runBlocking
105
108
  import kotlinx.coroutines.withTimeoutOrNull
@@ -230,7 +233,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
230
233
  post { onBatteryWarningPendingChanged(BatteryWarningPendingChangedEvent(pending)) }
231
234
  }
232
235
  // Every setupPlayer waiting for the service awaits it. Replaced on disconnect, after
233
- // cancelChildren has rejected its waiters.
236
+ // cancelChildren has rejected its waiters, and on a dead binding, after failing them.
234
237
  private var connectionReady = CompletableDeferred<Unit>()
235
238
 
236
239
  // Staged by setup options or by setters called before the player exists; last write wins, and
@@ -659,7 +662,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
659
662
  }
660
663
 
661
664
  override fun search(query: String): Promise<Array<Track>> {
662
- return Promise.async(mainScope) {
665
+ return promise {
663
666
  Timber.d("Searching for: $query")
664
667
  // Rejects with the error a browse would raise but leaves the navigation error unset: a failed
665
668
  // search must not replace the displayed page's state (mirrors iOS HybridAudioBrowser.search).
@@ -776,7 +779,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
776
779
  // ============================================================================
777
780
 
778
781
  override fun setupPlayer(options: NativeSetupPlayerOptions): Promise<Unit> {
779
- return Promise.async(mainScope) {
782
+ return promise {
780
783
  setupOptions.update(options)
781
784
  // Staged to apply together with the engine below, or at service connect. Last write wins
782
785
  // against the imperative setters.
@@ -788,7 +791,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
788
791
  it.player.applyOptions(updateOptions)
789
792
  it.player.setup(setupOptions)
790
793
  applyPendingPlayerState(it.player)
791
- return@async
794
+ return@promise
792
795
  }
793
796
 
794
797
  if (!serviceBinding.bind(Intent(context, Service::class.java), this@AudioBrowser)) {
@@ -1165,10 +1168,27 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
1165
1168
  Timber.d("AudioBrowser.onServiceDisconnected()")
1166
1169
  }
1167
1170
 
1171
+ // Android never reconnects a dead binding: release it so the next setupPlayer binds afresh.
1172
+ override fun onBindingDied(name: ComponentName) = dropDeadBinding()
1173
+
1174
+ override fun onNullBinding(name: ComponentName) = dropDeadBinding()
1175
+
1176
+ private fun dropDeadBinding() {
1177
+ serviceBinding.unbind(this)
1178
+ connectionReady.completeExceptionally(IllegalStateException("AudioBrowserService binding died"))
1179
+ connectionReady = CompletableDeferred()
1180
+ }
1181
+
1168
1182
  // ============================================================================
1169
1183
  // MARK: Internal Helpers
1170
1184
  // ============================================================================
1171
1185
 
1186
+ private fun <T> promise(run: suspend () -> T): Promise<T> {
1187
+ val promise = Promise<T>()
1188
+ mainScope.launchSettled({ it.fold(promise::resolve, promise::reject) }, run)
1189
+ return promise
1190
+ }
1191
+
1172
1192
  private fun launchInScope(block: suspend () -> Unit) {
1173
1193
  mainScope.launch { block() }
1174
1194
  }
@@ -1554,6 +1574,22 @@ internal suspend fun formattedOrDefault(
1554
1574
  return withTimeoutOrNull(FORMATTER_TIMEOUT) { hop.await() } ?: default
1555
1575
  }
1556
1576
 
1577
+ /**
1578
+ * Runs [run] in this scope and hands its outcome to [settle] once. Unlike Nitro's `Promise.async`,
1579
+ * a scope cancelled before [run] starts still settles, with the cancellation, and [run] never runs.
1580
+ */
1581
+ @OptIn(DelicateCoroutinesApi::class)
1582
+ internal fun <T> CoroutineScope.launchSettled(settle: (Result<T>) -> Unit, run: suspend () -> T) {
1583
+ launch(start = CoroutineStart.ATOMIC) {
1584
+ settle(
1585
+ runCatching {
1586
+ ensureActive()
1587
+ run()
1588
+ }
1589
+ )
1590
+ }
1591
+ }
1592
+
1557
1593
  private fun httpStatusText(statusCode: Int): String {
1558
1594
  return when (statusCode) {
1559
1595
  400 -> "Bad Request"
@@ -9,9 +9,10 @@ import com.margelo.nitro.audiobrowser.RemoteJumpForwardEvent
9
9
  import com.margelo.nitro.audiobrowser.RemoteSeekEvent
10
10
 
11
11
  /**
12
- * With `keepAlive`, a terminal error (idle with an error) reads as paused and ready to the platform
13
- * session rather than STATE_NONE, which Android Auto takes for "nothing playing": it closes the
14
- * now-playing screen and its next/previous buttons with it.
12
+ * With `keepAlive`, a terminal error (idle with an error) or a pause that cancelled a retry (idle
13
+ * in PAUSED) reads as paused and ready to the platform session rather than STATE_NONE, which
14
+ * Android Auto takes for "nothing playing": it closes the now-playing screen and its next/previous
15
+ * buttons with it.
15
16
  */
16
17
  internal object SessionErrorMask {
17
18
  fun playbackState(state: Int, hasError: Boolean, keepAlive: Boolean): Int =
@@ -24,16 +25,21 @@ internal object SessionErrorMask {
24
25
  /**
25
26
  * The player the MediaSession sees. Offers each transport command from an external surface (lock
26
27
  * screen, notification, Bluetooth, Android Auto) to the app's `handleRemote*` callback first: true
27
- * consumes it, anything else runs the default. Masks a terminal error from the session (see
28
- * [SessionErrorMask]); the error still reaches JS through `onPlaybackError` and `playbackState`.
28
+ * consumes it, anything else runs the default. Masks a terminal error and a cancelled retry from
29
+ * the session (see [SessionErrorMask]); the error still reaches JS through `onPlaybackError` and
30
+ * `playbackState`.
29
31
  */
30
32
  internal class InterceptingPlayer(
31
33
  player: MediaPlayer,
32
34
  private val callbacksProvider: () -> Callbacks?,
33
35
  private val optionsProvider: () -> PlayerUpdateOptions,
34
36
  private val keepSessionAliveOnError: Boolean,
37
+ private val isPaused: () -> Boolean,
35
38
  ) : ForwardingPlayer(player) {
36
39
 
40
+ private val parked: Boolean
41
+ get() = super.getPlayerError() != null || isPaused()
42
+
37
43
  // Media3 maps a player error to the legacy STATE_ERROR, which Android Auto and the notification
38
44
  // show as a disruptive error. Hidden whatever keepSessionAliveOnError says.
39
45
  override fun getPlayerError(): androidx.media3.common.PlaybackException? = null
@@ -42,7 +48,7 @@ internal class InterceptingPlayer(
42
48
  override fun getPlaybackState(): Int =
43
49
  SessionErrorMask.playbackState(
44
50
  super.getPlaybackState(),
45
- hasError = super.getPlayerError() != null,
51
+ hasError = parked,
46
52
  keepAlive = keepSessionAliveOnError,
47
53
  )
48
54
 
@@ -50,14 +56,14 @@ internal class InterceptingPlayer(
50
56
  SessionErrorMask.playWhenReady(
51
57
  super.getPlayWhenReady(),
52
58
  super.getPlaybackState(),
53
- hasError = super.getPlayerError() != null,
59
+ hasError = parked,
54
60
  keepAlive = keepSessionAliveOnError,
55
61
  )
56
62
 
57
- // After a terminal error the player is idle, and the default play/skip only move playWhenReady or
58
- // the index; prepare() restarts it. prepare() is a no-op unless idle.
63
+ // After a terminal error or a cancelled retry the player is idle, and the default play/skip only
64
+ // move playWhenReady or the index; prepare() restarts it. prepare() is a no-op unless idle.
59
65
  private fun recoverFromErrorIfNeeded() {
60
- if (keepSessionAliveOnError && super.getPlayerError() != null) {
66
+ if (keepSessionAliveOnError && parked) {
61
67
  prepare()
62
68
  }
63
69
  }
@@ -53,9 +53,10 @@ object PlaybackStateMachine {
53
53
  // a load finished, so consumers can drop their loading indicator.
54
54
  if (event.shouldPlayWhenReady) emptyList() else listOf(PlaybackState.READY)
55
55
  MediaPlayer.STATE_IDLE ->
56
- // A terminal error and stop() both idle ExoPlayer; NONE would clear the ERROR or
57
- // STOPPED state the session shows.
58
- if (current == PlaybackState.ERROR || current == PlaybackState.STOPPED) emptyList()
56
+ // A terminal error, stop() and a pause during a retry all idle ExoPlayer; NONE would
57
+ // clear the state the session shows.
58
+ if (current in setOf(PlaybackState.ERROR, PlaybackState.STOPPED, PlaybackState.PAUSED))
59
+ emptyList()
59
60
  else listOf(PlaybackState.NONE)
60
61
  MediaPlayer.STATE_ENDED ->
61
62
  // An emptied queue also reports STATE_ENDED: nothing loaded, not played to the end.
@@ -502,7 +502,13 @@ internal constructor(
502
502
  if (::forwardingPlayer.isInitialized) forwardingPlayer.removeListener(playerListener)
503
503
  sessionPlayer = remoteOutputs.player ?: exoPlayer
504
504
  forwardingPlayer =
505
- InterceptingPlayer(sessionPlayer, { callbacks }, { options }, keepSessionAliveOnError)
505
+ InterceptingPlayer(
506
+ sessionPlayer,
507
+ { callbacks },
508
+ { options },
509
+ keepSessionAliveOnError,
510
+ isPaused = { playbackState == PlaybackState.PAUSED },
511
+ )
506
512
  forwardingPlayer.addListener(playerListener)
507
513
  if (::mediaSession.isInitialized) mediaSession.player = forwardingPlayer
508
514
  }
@@ -1008,9 +1014,26 @@ internal constructor(
1008
1014
  playbackError = error
1009
1015
  callbacks?.onPlaybackChanged(Playback(playbackState, error))
1010
1016
  nowPlaying.render()
1017
+ // A pause before this first report found no retry to cancel.
1018
+ if (!playWhenReadyCache) cancelRetry()
1011
1019
  }
1012
1020
  }
1013
1021
 
1022
+ /**
1023
+ * Cancels the retry a dropped play intent leaves scheduled: ExoPlayer still runs it, and its
1024
+ * failure would be terminal. The engine idles in PAUSED, where the next prepare() reloads where
1025
+ * it failed. No-op unless a retrying error shows.
1026
+ */
1027
+ internal fun cancelRetry() {
1028
+ // The ENDED path drops the intent before it clears the error.
1029
+ if (playbackError?.retrying != true || playbackState == PlaybackState.ENDED) return
1030
+ // Before the stop: the state machine holds PAUSED through the IDLE that follows.
1031
+ setPlaybackState(PlaybackState.PAUSED)
1032
+ clearRetryingError()
1033
+ exoPlayer.stop()
1034
+ resetRetryTimer()
1035
+ }
1036
+
1014
1037
  /**
1015
1038
  * Drops the retrying error of a track that is gone. The new track may stay LOADING or BUFFERING
1016
1039
  * with no state change to emit the clear.
@@ -132,6 +132,9 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
132
132
  // The second writer: Player.playWhenReady's setter writes first so loader-thread readers see
133
133
  // the intent early; this syncs changes ExoPlayer makes itself (e.g. audio focus).
134
134
  player.playWhenReadyCache = playWhenReady
135
+ // Here rather than in Player.pause(): a session pause, a noisy-audio pause and a permanent
136
+ // focus loss all drop the intent without it.
137
+ if (!playWhenReady) player.cancelRetry()
135
138
  // Deduped: the ENDED path in setPlaybackState may already have emitted it, before queue-ended.
136
139
  player.emitPlayWhenReadyChanged(playWhenReady)
137
140
  player.refreshPlayingState()
@@ -0,0 +1,81 @@
1
+ package com.audiobrowser
2
+
3
+ import kotlinx.coroutines.CancellationException
4
+ import kotlinx.coroutines.CompletableDeferred
5
+ import kotlinx.coroutines.CoroutineScope
6
+ import kotlinx.coroutines.ExperimentalCoroutinesApi
7
+ import kotlinx.coroutines.cancel
8
+ import kotlinx.coroutines.test.StandardTestDispatcher
9
+ import kotlinx.coroutines.test.advanceUntilIdle
10
+ import kotlinx.coroutines.test.runTest
11
+ import org.junit.Assert.assertEquals
12
+ import org.junit.Assert.assertFalse
13
+ import org.junit.Assert.assertTrue
14
+ import org.junit.Test
15
+
16
+ @OptIn(ExperimentalCoroutinesApi::class)
17
+ class LaunchSettledTest {
18
+
19
+ @Test
20
+ fun `a call into a cancelled scope settles without running`() = runTest {
21
+ val scope = CoroutineScope(StandardTestDispatcher(testScheduler)).apply { cancel() }
22
+ val outcomes = mutableListOf<Result<Int>>()
23
+ var ran = false
24
+
25
+ scope.launchSettled({ outcomes += it }) {
26
+ ran = true
27
+ 1
28
+ }
29
+ advanceUntilIdle()
30
+
31
+ assertFalse(ran)
32
+ assertEquals(1, outcomes.size)
33
+ assertTrue(outcomes.single().exceptionOrNull() is CancellationException)
34
+ }
35
+
36
+ @Test
37
+ fun `a call whose scope is cancelled before it is dispatched settles without running`() =
38
+ runTest {
39
+ val scope = CoroutineScope(StandardTestDispatcher(testScheduler))
40
+ val outcomes = mutableListOf<Result<Int>>()
41
+ var ran = false
42
+
43
+ scope.launchSettled({ outcomes += it }) {
44
+ ran = true
45
+ 1
46
+ }
47
+ scope.cancel()
48
+ advanceUntilIdle()
49
+
50
+ assertFalse(ran)
51
+ assertEquals(1, outcomes.size)
52
+ assertTrue(outcomes.single().exceptionOrNull() is CancellationException)
53
+ }
54
+
55
+ @Test
56
+ fun `a call cancelled while it waits settles once`() = runTest {
57
+ val scope = CoroutineScope(StandardTestDispatcher(testScheduler))
58
+ val outcomes = mutableListOf<Result<Unit>>()
59
+
60
+ scope.launchSettled({ outcomes += it }) { CompletableDeferred<Unit>().await() }
61
+ advanceUntilIdle()
62
+ scope.cancel()
63
+ advanceUntilIdle()
64
+
65
+ assertEquals(1, outcomes.size)
66
+ assertTrue(outcomes.single().exceptionOrNull() is CancellationException)
67
+ }
68
+
69
+ @Test
70
+ fun `a call settles with what it returns or throws`() = runTest {
71
+ val scope = CoroutineScope(StandardTestDispatcher(testScheduler))
72
+ val outcomes = mutableListOf<Result<Int>>()
73
+ val boom = IllegalStateException("boom")
74
+
75
+ scope.launchSettled({ outcomes += it }) { 1 }
76
+ scope.launchSettled({ outcomes += it }) { throw boom }
77
+ advanceUntilIdle()
78
+
79
+ assertEquals(listOf(Result.success(1), Result.failure<Int>(boom)), outcomes)
80
+ }
81
+ }
@@ -55,7 +55,7 @@ class PlaybackStateMachineTest {
55
55
  }
56
56
 
57
57
  @Test
58
- fun `idle maps to none except from error or stopped`() {
58
+ fun `idle maps to none except from error, stopped or paused`() {
59
59
  val idle =
60
60
  PlaybackEvent.ExoPlaybackStateChanged(
61
61
  MediaPlayer.STATE_IDLE,
@@ -65,6 +65,7 @@ class PlaybackStateMachineTest {
65
65
  assertEquals(listOf(PlaybackState.NONE), on(idle, from = PlaybackState.PLAYING))
66
66
  assertEquals(emptyList<PlaybackState>(), on(idle, from = PlaybackState.ERROR))
67
67
  assertEquals(emptyList<PlaybackState>(), on(idle, from = PlaybackState.STOPPED))
68
+ assertEquals(emptyList<PlaybackState>(), on(idle, from = PlaybackState.PAUSED))
68
69
  }
69
70
 
70
71
  @Test
@@ -103,6 +103,52 @@ class PlayerRetryTest {
103
103
  verify(callbacks, never()).onPlaybackError(null)
104
104
  }
105
105
 
106
+ @Test
107
+ fun `a pause during a retry stays paused and the next play reloads`() {
108
+ pauseDuringRetry { player.pause() }
109
+
110
+ player.play()
111
+ awaitRetry("the reload's retry")
112
+ }
113
+
114
+ @Test
115
+ fun `a session pause during a retry stays paused and a session play reloads`() {
116
+ pauseDuringRetry { player.forwardingPlayer.pause() }
117
+
118
+ // Masked as paused and ready, so the session's play button doesn't prepare it itself.
119
+ assertEquals(MediaPlayer.STATE_READY, player.forwardingPlayer.playbackState)
120
+ player.forwardingPlayer.play()
121
+ awaitRetry("the reload's retry")
122
+ }
123
+
124
+ /** Pauses with a retry pending and runs past every backoff it would have taken. */
125
+ private fun pauseDuringRetry(pause: () -> Unit) {
126
+ play("https://127.0.0.1:9/stream", RetryPolicy.Infinite())
127
+ awaitRetry("a pending retry")
128
+
129
+ pause()
130
+ repeat(10) {
131
+ ShadowSystemClock.advanceBy(Duration.ofSeconds(1))
132
+ Thread.sleep(20)
133
+ shadowOf(Looper.getMainLooper()).idle()
134
+ }
135
+
136
+ assertEquals(Playback(PlaybackState.PAUSED, null), player.getPlayback())
137
+ assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
138
+ assertFalse(
139
+ "a terminal error was reported",
140
+ mockingDetails(callbacks).invocations.any {
141
+ it.method.name == "onPlaybackError" && it.arguments[0] != null
142
+ },
143
+ )
144
+ }
145
+
146
+ private fun awaitRetry(what: String) =
147
+ idleUntil(what) {
148
+ ShadowSystemClock.advanceBy(Duration.ofMillis(100))
149
+ player.playbackError?.retrying == true
150
+ }
151
+
106
152
  @Test
107
153
  fun `emptying the queue clears a terminal error`() {
108
154
  failTerminally()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.64",
3
+ "version": "0.2.0-next.66",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",