react-native-audio-browser 0.2.0-next.74 → 0.2.0-next.76

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 (40) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -26
  2. package/android/src/main/java/com/audiobrowser/Service.kt +15 -30
  3. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +16 -8
  4. package/android/src/main/java/com/audiobrowser/browser/TrackLoadHandler.kt +5 -3
  5. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +10 -2
  6. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +21 -1
  7. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +0 -3
  8. package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +3 -0
  9. package/android/src/main/java/com/audiobrowser/player/PlaybackStateMachine.kt +15 -1
  10. package/android/src/main/java/com/audiobrowser/player/Player.kt +43 -33
  11. package/android/src/main/java/com/audiobrowser/player/PlayerEngineFactory.kt +0 -2
  12. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +38 -15
  13. package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +0 -7
  14. package/android/src/main/java/com/audiobrowser/util/AwaitCancellable.kt +45 -0
  15. package/android/src/test/java/com/audiobrowser/GateDecisionTest.kt +128 -0
  16. package/android/src/test/java/com/audiobrowser/ResolveFormattedErrorTest.kt +93 -0
  17. package/android/src/test/java/com/audiobrowser/ServiceTaskRemovedTest.kt +35 -0
  18. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerLayerResolutionTest.kt +75 -5
  19. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerTest.kt +42 -0
  20. package/android/src/test/java/com/audiobrowser/browser/TrackLoadHandlerTest.kt +43 -0
  21. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +62 -0
  22. package/android/src/test/java/com/audiobrowser/player/BrowseTilesTest.kt +31 -32
  23. package/android/src/test/java/com/audiobrowser/player/MediaFactoryTest.kt +1 -8
  24. package/android/src/test/java/com/audiobrowser/player/NowPlayingFormatterTest.kt +75 -0
  25. package/android/src/test/java/com/audiobrowser/player/NowPlayingUpdaterTest.kt +25 -0
  26. package/android/src/test/java/com/audiobrowser/player/PlayFromSearchTest.kt +108 -0
  27. package/android/src/test/java/com/audiobrowser/player/PlaybackStateMachineTest.kt +41 -3
  28. package/android/src/test/java/com/audiobrowser/player/PlayerRetryTest.kt +126 -1
  29. package/android/src/test/java/com/audiobrowser/player/PlayerSetupTest.kt +0 -1
  30. package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +105 -0
  31. package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +0 -7
  32. package/android/src/test/java/com/audiobrowser/util/AwaitCancellableTest.kt +136 -0
  33. package/android/src/test/java/com/audiobrowser/util/JsPromise.kt +44 -0
  34. package/ios/AVPlayerEngine.swift +2 -1
  35. package/ios/HybridAudioBrowser+Player.swift +14 -4
  36. package/ios/Player/Player.swift +15 -10
  37. package/ios/Player/PlayerEngine.swift +1 -1
  38. package/ios/Tests/PlayerPolicyTests.swift +71 -0
  39. package/ios/Tests/Support/TestTypes.swift +6 -1
  40. package/package.json +2 -1
@@ -34,6 +34,8 @@ import com.audiobrowser.util.BrowserPathHelper
34
34
  import com.audiobrowser.util.OutputMonitor
35
35
  import com.audiobrowser.util.OutputSwitcher
36
36
  import com.audiobrowser.util.SystemVolumeMonitor
37
+ import com.audiobrowser.util.awaitNestedOrTimeout
38
+ import com.audiobrowser.util.awaitOrTimeout
37
39
  import com.facebook.proguard.annotations.DoNotStrip
38
40
  import com.google.common.util.concurrent.ListenableFuture
39
41
  import com.margelo.nitro.NitroModules
@@ -91,7 +93,6 @@ import com.margelo.nitro.core.NullType
91
93
  import com.margelo.nitro.core.Promise
92
94
  import java.util.concurrent.TimeUnit
93
95
  import java.util.concurrent.atomic.AtomicReference
94
- import kotlin.time.Duration.Companion.seconds
95
96
  import kotlinx.coroutines.CancellationException
96
97
  import kotlinx.coroutines.CompletableDeferred
97
98
  import kotlinx.coroutines.CoroutineScope
@@ -99,13 +100,12 @@ import kotlinx.coroutines.CoroutineStart
99
100
  import kotlinx.coroutines.DelicateCoroutinesApi
100
101
  import kotlinx.coroutines.Job
101
102
  import kotlinx.coroutines.MainScope
102
- import kotlinx.coroutines.async
103
103
  import kotlinx.coroutines.cancel
104
104
  import kotlinx.coroutines.cancelChildren
105
+ import kotlinx.coroutines.currentCoroutineContext
105
106
  import kotlinx.coroutines.ensureActive
106
107
  import kotlinx.coroutines.launch
107
108
  import kotlinx.coroutines.runBlocking
108
- import kotlinx.coroutines.withTimeoutOrNull
109
109
  import timber.log.Timber
110
110
 
111
111
  @Keep
@@ -489,7 +489,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
489
489
  ): FormattedNavigationError {
490
490
  val default = defaultFormattedError(error)
491
491
  val formatter = _configuration.formatNavigationError ?: return default
492
- return formattedOrDefault(mainScope, default) {
492
+ return formattedOrDefault(default) {
493
493
  formatter(
494
494
  FormatNavigationErrorParams(
495
495
  error,
@@ -498,7 +498,7 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
498
498
  BrowserPathHelper.navigationErrorKind(path),
499
499
  )
500
500
  )
501
- .await()
501
+ .awaitOrTimeout()
502
502
  }
503
503
  }
504
504
 
@@ -749,15 +749,16 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
749
749
  * Whether [request] is gated, and with which chrome. No active gate allows; a gate without a
750
750
  * resolver gates with its stored chrome and never asks JS. A resolver that throws, rejects or
751
751
  * times out fails closed, gating rather than serving content; only a successful `gated: false`
752
- * allows. Chrome falls back from the resolver's to the stored one to [builtInGate].
752
+ * allows. Chrome falls back from the resolver's to the stored one to [builtInGate]. A caller
753
+ * cancelled while it waits gets the cancellation.
753
754
  */
754
755
  suspend fun gateDecision(request: NativeGateRequest): GateOutcome {
755
756
  val s = gateState
756
757
  if (!s.active) return GateOutcome(false, null)
757
758
  if (!s.hasResolver) return GateOutcome(true, s.chrome ?: builtInGate)
758
- val decision =
759
- runCatching { resolveGate(request).await().await() }.getOrNull()
760
- ?: return GateOutcome(true, s.chrome ?: builtInGate)
759
+ val result = runCatching { resolveGate(request).awaitNestedOrTimeout() }
760
+ currentCoroutineContext().ensureActive()
761
+ val decision = result.getOrNull() ?: return GateOutcome(true, s.chrome ?: builtInGate)
761
762
  if (!decision.gated) return GateOutcome(false, null)
762
763
  return GateOutcome(true, decision.gate ?: s.chrome ?: builtInGate)
763
764
  }
@@ -1490,9 +1491,6 @@ private fun NativeRouteEntry.strippingJSCallbacks() =
1490
1491
  artwork = artwork?.strippingJSCallbacks(),
1491
1492
  )
1492
1493
 
1493
- // The budget [Player.awaitBrowser] gives JS, the other JS wait a browse serve blocks on.
1494
- private val FORMATTER_TIMEOUT = 10.seconds
1495
-
1496
1494
  /**
1497
1495
  * The navigation error [e] raises, shared by failed navigations, the rejection
1498
1496
  * [AudioBrowser.search] hands JS and the Android Auto browse-error tile, so one failure is named
@@ -1559,23 +1557,18 @@ internal fun defaultFormattedError(error: NavigationError): FormattedNavigationE
1559
1557
  return FormattedNavigationError(title, error.message.takeIf { it.isNotEmpty() })
1560
1558
  }
1561
1559
 
1562
- /**
1563
- * The app's formatted error from [format], or [default] when it returns null, throws, or outruns
1564
- * [FORMATTER_TIMEOUT].
1565
- *
1566
- * [format] runs in [scope] and is awaited through the Deferred because Nitro's `Promise.await`
1567
- * parks in a plain `suspendCoroutine` that cancellation does not unpark; awaiting the Deferred is
1568
- * cancellable, so the timeout releases the caller instead of holding it until JS answers, which for
1569
- * a browse serve may be never.
1570
- */
1560
+ /** The app's formatted error from [format], or [default] when it returns null or throws. */
1571
1561
  internal suspend fun formattedOrDefault(
1572
- scope: CoroutineScope,
1573
1562
  default: FormattedNavigationError,
1574
1563
  format: suspend () -> FormattedNavigationError?,
1575
- ): FormattedNavigationError {
1576
- val hop = scope.async { runCatching { format() }.getOrNull() }
1577
- return withTimeoutOrNull(FORMATTER_TIMEOUT) { hop.await() } ?: default
1578
- }
1564
+ ): FormattedNavigationError =
1565
+ try {
1566
+ format()
1567
+ } catch (e: CancellationException) {
1568
+ throw e
1569
+ } catch (e: Exception) {
1570
+ null
1571
+ } ?: default
1579
1572
 
1580
1573
  /**
1581
1574
  * Runs [run] in this scope and hands its outcome to [settle] once. Unlike Nitro's `Promise.async`,
@@ -37,6 +37,7 @@ import kotlinx.coroutines.Dispatchers
37
37
  import kotlinx.coroutines.MainScope
38
38
  import kotlinx.coroutines.SupervisorJob
39
39
  import kotlinx.coroutines.cancel
40
+ import kotlinx.coroutines.cancelChildren
40
41
  import kotlinx.coroutines.isActive
41
42
  import timber.log.Timber
42
43
 
@@ -268,26 +269,15 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
268
269
  Timber.d("A car is connected - pausing instead of stopping")
269
270
  player.pause()
270
271
  stopForeground(STOP_FOREGROUND_REMOVE)
271
- } else if (moduleBound) {
272
- Timber.d("AudioBrowser still bound - stopping playback but keeping the player")
272
+ } else {
273
+ Timber.d("No car connected - stopping playback, moduleBound = $moduleBound")
273
274
  stopPlaybackAndRemoveNotification()
274
- // Ends the service once AudioBrowser unbinds.
275
+ // Ends a waiting play-from-search, also while AudioBrowser is bound.
276
+ scope.coroutineContext.cancelChildren()
277
+ // AudioBrowser keeps the player. Otherwise tear down now: a media controller still bound
278
+ // keeps the service alive after stopSelf().
279
+ if (!moduleBound) tearDown()
275
280
  stopSelf()
276
- } else {
277
- Timber.d("No car connected - shutting the service down")
278
- try {
279
- if (::mediaSession.isInitialized) {
280
- mediaSession.release()
281
- }
282
- stopPlaybackAndRemoveNotification()
283
- tearDownArtworkProvider()
284
- player.destroy()
285
- scope.cancel()
286
- stopSelf()
287
- } catch (e: Exception) {
288
- Timber.e(e, "Error during aggressive cleanup in onTaskRemoved")
289
- stopSelf()
290
- }
291
281
  }
292
282
  }
293
283
 
@@ -340,16 +330,17 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
340
330
  onBatteryWarningPendingChanged?.invoke(true)
341
331
  }
342
332
 
343
- /**
344
- * Cancels the artwork provider's scope and clears its holder. Idempotent. Call it before
345
- * player.destroy() on every teardown path, so no in-flight load reaches a destroyed player.
346
- */
347
- private fun tearDownArtworkProvider() {
333
+ /** Idempotent: a swipe's shutdown runs it, and onDestroy runs it again. */
334
+ private fun tearDown() {
335
+ // Before player.destroy(), so no in-flight artwork load reaches a destroyed player.
348
336
  artworkProviderDeps?.let {
349
337
  it.scope.cancel()
350
338
  CoilArtworkLoaderHolder.clearIf(it)
351
339
  }
352
340
  artworkProviderDeps = null
341
+ if (::mediaSession.isInitialized) mediaSession.release()
342
+ player.destroy()
343
+ scope.cancel()
353
344
  }
354
345
 
355
346
  override fun onDestroy() {
@@ -361,13 +352,7 @@ class Service : MediaLibraryService(), MediaSessionService.Listener {
361
352
  headlessBound = false
362
353
  }
363
354
 
364
- tearDownArtworkProvider()
365
-
366
- Timber.d("Releasing media session and destroying player")
367
- if (::mediaSession.isInitialized) {
368
- mediaSession.release()
369
- }
370
- player.destroy()
355
+ tearDown()
371
356
 
372
357
  super.onDestroy()
373
358
  }
@@ -8,8 +8,12 @@ import com.audiobrowser.extension.identity
8
8
  import com.audiobrowser.http.HttpClient
9
9
  import com.audiobrowser.http.RequestConfigBuilder
10
10
  import com.audiobrowser.util.BrowserPathHelper
11
+ import com.audiobrowser.util.FALLBACK_TIMEOUT
11
12
  import com.audiobrowser.util.TrackFactory
12
13
  import com.audiobrowser.util.artworkOf
14
+ import com.audiobrowser.util.awaitCancellable
15
+ import com.audiobrowser.util.awaitNested
16
+ import com.audiobrowser.util.awaitOrTimeout
13
17
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
14
18
  import com.margelo.nitro.audiobrowser.BrowserSourceCallbackParam
15
19
  import com.margelo.nitro.audiobrowser.Func_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____
@@ -25,6 +29,7 @@ import com.margelo.nitro.audiobrowser.StyleDisplay
25
29
  import com.margelo.nitro.audiobrowser.Track
26
30
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
27
31
  import com.margelo.nitro.core.Promise
32
+ import kotlinx.coroutines.CancellationException
28
33
  import kotlinx.coroutines.Dispatchers
29
34
  import kotlinx.coroutines.async
30
35
  import kotlinx.coroutines.awaitAll
@@ -677,6 +682,8 @@ class BrowserManager {
677
682
  "singleTrack=false - returning ${playableTracks.size} playable tracks (from ${sectionTracks.size} in section), starting at index $selectedIndex"
678
683
  )
679
684
  return Pair(playableTracks.toTypedArray(), selectedIndex)
685
+ } catch (e: CancellationException) {
686
+ throw e
680
687
  } catch (e: Exception) {
681
688
  Timber.e(e, "Error expanding queue from contextual path: $contextualPath")
682
689
  return null
@@ -962,13 +969,13 @@ class BrowserManager {
962
969
  // Nitro flattens `(ResolvedTrack | BrowseError) | Promise<BrowseResult>` into three arms.
963
970
  return callback
964
971
  .invoke(param)
965
- .await()
972
+ .awaitCancellable()
966
973
  .match(
967
974
  first = { resolvedTrack -> resolvedTrack },
968
975
  second = { browseError -> throw CallbackException(browseError.error) },
969
976
  third = { promise ->
970
977
  promise
971
- .await()
978
+ .awaitCancellable()
972
979
  .match(
973
980
  first = { resolvedTrack -> resolvedTrack },
974
981
  second = { browseError -> throw CallbackException(browseError.error) },
@@ -1001,9 +1008,7 @@ class BrowserManager {
1001
1008
 
1002
1009
  searchEntry.searchCallback?.let { callback ->
1003
1010
  Timber.d("Resolving search via callback")
1004
- val promise = callback.invoke(params)
1005
- val innerPromise = promise.await()
1006
- return innerPromise.await()
1011
+ return callback.invoke(params).awaitNested()
1007
1012
  }
1008
1013
 
1009
1014
  searchEntry.searchConfig?.let { apiConfig ->
@@ -1036,7 +1041,7 @@ class BrowserManager {
1036
1041
  ): TransformableRequestConfig? {
1037
1042
  if (resolver == null) return staticConfig
1038
1043
  // The TS layer wraps the thunk in Promise.resolve: await the bridge promise, then the JS one.
1039
- return resolver.invoke().await().await()
1044
+ return resolver.invoke().awaitNested()
1040
1045
  }
1041
1046
 
1042
1047
  // No in-flight dedupe: concurrent first requests may both resolve, which is harmless, and a
@@ -1064,14 +1069,17 @@ class BrowserManager {
1064
1069
  /**
1065
1070
  * The title of the "view more" row appended to a pathed section where the header can't be tapped
1066
1071
  * (Android Auto). Re-read once per generation, so invalidateAllContent picks up a new language.
1067
- * Falls back to [DEFAULT_VIEW_MORE_TITLE] when unset, blank or throwing.
1072
+ * Falls back to [DEFAULT_VIEW_MORE_TITLE] when unset, blank, throwing or outrunning
1073
+ * [FALLBACK_TIMEOUT].
1068
1074
  */
1069
1075
  internal suspend fun viewMoreTitle(): String {
1070
1076
  val generation = layerGeneration
1071
1077
  if (resolvedViewMoreTitleGeneration == generation) return resolvedViewMoreTitle
1072
1078
  val title =
1073
1079
  try {
1074
- config.viewMoreTitle?.invoke()?.await()?.takeIf { it.isNotBlank() }
1080
+ config.viewMoreTitle?.invoke()?.awaitOrTimeout()?.takeIf { it.isNotBlank() }
1081
+ } catch (e: CancellationException) {
1082
+ throw e
1075
1083
  } catch (e: Exception) {
1076
1084
  Timber.e(e, "viewMoreTitle callback failed; falling back to the default")
1077
1085
  null
@@ -1,8 +1,10 @@
1
1
  package com.audiobrowser.browser
2
2
 
3
+ import com.audiobrowser.util.awaitNested
3
4
  import com.margelo.nitro.audiobrowser.Track
4
5
  import com.margelo.nitro.audiobrowser.TrackLoadEvent
5
6
  import com.margelo.nitro.core.Promise
7
+ import kotlinx.coroutines.CancellationException
6
8
  import timber.log.Timber
7
9
 
8
10
  /**
@@ -23,9 +25,9 @@ suspend fun <T> handleTrackLoad(
23
25
  if (handler != null) {
24
26
  val event = TrackLoadEvent(track, queue, startIndex)
25
27
  try {
26
- val outerPromise = handler(event)
27
- val innerPromise = outerPromise.await()
28
- innerPromise.await()
28
+ handler(event).awaitNested()
29
+ } catch (e: CancellationException) {
30
+ throw e
29
31
  } catch (e: Exception) {
30
32
  Timber.e(e, "handleTrackLoad failed")
31
33
  }
@@ -1,6 +1,8 @@
1
1
  package com.audiobrowser.http
2
2
 
3
3
  import com.audiobrowser.util.BrowserPathHelper
4
+ import com.audiobrowser.util.awaitCancellable
5
+ import com.audiobrowser.util.awaitNested
4
6
  import com.margelo.nitro.audiobrowser.ArtworkRequestConfig
5
7
  import com.margelo.nitro.audiobrowser.MediaRequestConfig
6
8
  import com.margelo.nitro.audiobrowser.RequestConfig
@@ -8,6 +10,7 @@ import com.margelo.nitro.audiobrowser.Track
8
10
  import com.margelo.nitro.audiobrowser.TransformableRequestConfig
9
11
  import com.margelo.nitro.core.Promise
10
12
  import java.net.URLEncoder
13
+ import kotlinx.coroutines.CancellationException
11
14
  import kotlinx.coroutines.Dispatchers
12
15
  import kotlinx.coroutines.withContext
13
16
  import timber.log.Timber
@@ -58,9 +61,10 @@ object RequestConfigBuilder {
58
61
  * JS promise); awaiting it once hands a Promise downstream as the config.
59
62
  */
60
63
  suspend fun awaitAsyncConfig(promise: Promise<Promise<RequestConfig>>): RequestConfig =
61
- promise.await().await()
64
+ promise.awaitNested()
62
65
 
63
- suspend fun awaitSyncConfig(promise: Promise<RequestConfig>): RequestConfig = promise.await()
66
+ suspend fun awaitSyncConfig(promise: Promise<RequestConfig>): RequestConfig =
67
+ promise.awaitCancellable()
64
68
 
65
69
  private fun MediaRequestConfig.withRequestFields(c: RequestConfig) =
66
70
  MediaRequestConfig(
@@ -104,6 +108,8 @@ object RequestConfigBuilder {
104
108
  override.transform?.let { result = awaitAsyncConfig(it.invoke(result, routeParams)) }
105
109
  override.transformSync?.let { result = awaitSyncConfig(it.invoke(result, routeParams)) }
106
110
  result
111
+ } catch (e: CancellationException) {
112
+ throw e
107
113
  } catch (e: Exception) {
108
114
  Timber.e(e, "Failed to apply transform function, using base config")
109
115
  base
@@ -147,6 +153,8 @@ object RequestConfigBuilder {
147
153
  val asyncResolved = layered.resolve?.let { awaitAsyncConfig(it.invoke(track)) }
148
154
  val syncResolved = layered.resolveSync?.let { awaitSyncConfig(it.invoke(track)) }
149
155
  composeResolved(asyncResolved, syncResolved) ?: return layered
156
+ } catch (e: CancellationException) {
157
+ throw e
150
158
  } catch (e: Exception) {
151
159
  Timber.e(e, "Failed to apply media.resolve, using layered config")
152
160
  return layered
@@ -35,8 +35,28 @@ internal class InterceptingPlayer(
35
35
  private val optionsProvider: () -> PlayerUpdateOptions,
36
36
  private val keepSessionAliveOnError: Boolean,
37
37
  private val isPaused: () -> Boolean,
38
+ private val stopPlayer: () -> Unit,
38
39
  ) : ForwardingPlayer(player) {
39
40
 
41
+ private val listeners = mutableSetOf<MediaPlayer.Listener>()
42
+
43
+ override fun addListener(listener: MediaPlayer.Listener) {
44
+ listeners += listener
45
+ super.addListener(listener)
46
+ }
47
+
48
+ override fun removeListener(listener: MediaPlayer.Listener) {
49
+ listeners -= listener
50
+ super.removeListener(listener)
51
+ }
52
+
53
+ /** Call when [isPaused] changes: on an idle engine the masked state moves with no event. */
54
+ fun onPausedChanged() {
55
+ if (keepSessionAliveOnError && super.getPlaybackState() == MediaPlayer.STATE_IDLE) {
56
+ listeners.toList().forEach { it.onPlaybackStateChanged(playbackState) }
57
+ }
58
+ }
59
+
40
60
  private val parked: Boolean
41
61
  get() = super.getPlayerError() != null || isPaused()
42
62
 
@@ -86,7 +106,7 @@ internal class InterceptingPlayer(
86
106
  // the recovery.
87
107
  override fun setPlayWhenReady(playWhenReady: Boolean) = if (playWhenReady) play() else pause()
88
108
 
89
- override fun stop() = intercept({ it.handleRemoteStop() }) { super.stop() }
109
+ override fun stop() = intercept({ it.handleRemoteStop() }) { stopPlayer() }
90
110
 
91
111
  override fun seekToNext() =
92
112
  intercept({ it.handleRemoteNext() }, recover = true) { super.seekToNext() }
@@ -25,7 +25,6 @@ class MediaFactory(
25
25
  private val context: Context,
26
26
  private val cache: SimpleCache?,
27
27
  private val retryPolicy: RetryPolicy,
28
- private val shouldRetry: () -> Boolean,
29
28
  private val isOnline: () -> Boolean = { true },
30
29
  private val hasPlayed: () -> Boolean = { false },
31
30
  private val onRetryPending: ((exception: IOException) -> Unit)? = null,
@@ -61,7 +60,6 @@ class MediaFactory(
61
60
  maxRetries = null,
62
61
  maxRetryDurationMs = retryPolicy.maxRetryDurationMs,
63
62
  firstConnectMaxRetryDurationMs = retryPolicy.firstConnectMaxRetryDurationMs,
64
- shouldRetry = shouldRetry,
65
63
  isOnline = isOnline,
66
64
  hasPlayed = hasPlayed,
67
65
  onRetryPending = onRetryPending,
@@ -71,7 +69,6 @@ class MediaFactory(
71
69
  maxRetries = retryPolicy.maxRetries,
72
70
  maxRetryDurationMs = retryPolicy.maxRetryDurationMs,
73
71
  firstConnectMaxRetryDurationMs = retryPolicy.firstConnectMaxRetryDurationMs,
74
- shouldRetry = shouldRetry,
75
72
  isOnline = isOnline,
76
73
  hasPlayed = hasPlayed,
77
74
  onRetryPending = onRetryPending,
@@ -10,6 +10,7 @@ import com.margelo.nitro.audiobrowser.PlaybackState
10
10
  import com.margelo.nitro.audiobrowser.StallReason
11
11
  import com.margelo.nitro.audiobrowser.TimedMetadata
12
12
  import com.margelo.nitro.audiobrowser.Track
13
+ import kotlinx.coroutines.CancellationException
13
14
  import kotlinx.coroutines.CoroutineScope
14
15
  import kotlinx.coroutines.Job
15
16
  import kotlinx.coroutines.cancel
@@ -255,6 +256,8 @@ class NowPlayingUpdater(private val surface: NowPlayingSurface, private val scop
255
256
  val formatted =
256
257
  try {
257
258
  activeFormatter(params)
259
+ } catch (e: CancellationException) {
260
+ throw e
258
261
  } catch (e: Exception) {
259
262
  Timber.e(e, "NowPlaying formatter threw; using default")
260
263
  null
@@ -19,7 +19,16 @@ sealed interface PlaybackEvent {
19
19
  val shouldPlayWhenReady: Boolean,
20
20
  ) : PlaybackEvent
21
21
 
22
- data class MediaItemTransition(val hasTrack: Boolean, val isPlaying: Boolean) : PlaybackEvent
22
+ /**
23
+ * [loads] is false when the engine idles, so nothing loads the track. Read after the command's
24
+ * own prepare(): onEvents runs once the command returns.
25
+ */
26
+ data class MediaItemTransition(
27
+ val hasTrack: Boolean,
28
+ val isPlaying: Boolean,
29
+ val loads: Boolean,
30
+ val shouldPlayWhenReady: Boolean,
31
+ ) : PlaybackEvent
23
32
 
24
33
  /**
25
34
  * An input of [Player.shouldPlayWhenReady] changed: the intent, or a playback suppression such as
@@ -69,6 +78,11 @@ object PlaybackStateMachine {
69
78
  // the events arrive after it.
70
79
  !event.hasTrack ->
71
80
  if (current == PlaybackState.STOPPED) emptyList() else listOf(PlaybackState.NONE)
81
+ // Removing the current track after a stop, an error or a cancelled retry: play() loads
82
+ // the new one. With the intent up PAUSED would read as playing; ERROR's toggle reloads.
83
+ !event.loads ->
84
+ if (current == PlaybackState.STOPPED || event.shouldPlayWhenReady) emptyList()
85
+ else listOf(PlaybackState.PAUSED)
72
86
  // Already playing (gapless auto-advance): no IsPlayingChanged follows, so run the whole
73
87
  // sequence here or the state sticks on LOADING.
74
88
  event.isPlaying ->
@@ -40,6 +40,7 @@ import com.audiobrowser.util.RepeatModeFactory
40
40
  import com.audiobrowser.util.SvgArtworkRenderer
41
41
  import com.audiobrowser.util.TrackFactory
42
42
  import com.audiobrowser.util.TrackFactory.setFavorite
43
+ import com.audiobrowser.util.awaitOrTimeout
43
44
  import com.audiobrowser.util.isAutomotive
44
45
  import com.margelo.nitro.audiobrowser.AppKilledPlaybackBehavior
45
46
  import com.margelo.nitro.audiobrowser.FavoriteChangedEvent
@@ -68,6 +69,8 @@ import kotlinx.coroutines.CoroutineScope
68
69
  import kotlinx.coroutines.Dispatchers
69
70
  import kotlinx.coroutines.MainScope
70
71
  import kotlinx.coroutines.TimeoutCancellationException
72
+ import kotlinx.coroutines.currentCoroutineContext
73
+ import kotlinx.coroutines.ensureActive
71
74
  import kotlinx.coroutines.withContext
72
75
  import kotlinx.coroutines.withTimeout
73
76
  import timber.log.Timber
@@ -117,7 +120,7 @@ internal constructor(
117
120
  private set
118
121
 
119
122
  /** [sessionPlayer] behind the remote-command seam: what the MediaSession wraps. */
120
- lateinit var forwardingPlayer: MediaPlayer
123
+ internal lateinit var forwardingPlayer: InterceptingPlayer
121
124
 
122
125
  private val remoteOutputs =
123
126
  RemoteOutputsController(context, ::resolveRemoteUrls, castRemote, sonosRemote)
@@ -127,12 +130,6 @@ internal constructor(
127
130
 
128
131
  private var keepSessionAliveOnError = true
129
132
 
130
- /**
131
- * [playWhenReady] for the retry policy, which reads it off the main thread. Written eagerly by
132
- * the setter, ahead of ExoPlayer's listener round-trip.
133
- */
134
- @Volatile internal var playWhenReadyCache = false
135
-
136
133
  /**
137
134
  * Whether the current load has produced audio: picks the retry policy's first-connect or recovery
138
135
  * budget. Read on ExoPlayer's loader thread. Cleared on a media-item transition; retry reloads of
@@ -311,7 +308,6 @@ internal constructor(
311
308
  if (value && sessionPlayer.playbackState == MediaPlayer.STATE_ENDED) {
312
309
  sessionPlayer.seekToDefaultPosition()
313
310
  }
314
- playWhenReadyCache = value
315
311
  sessionPlayer.playWhenReady = value
316
312
  }
317
313
 
@@ -418,7 +414,9 @@ internal constructor(
418
414
  nowPlaying.enabled = setupOptions.autoUpdateNowPlayingMetadata
419
415
  // Unwrapped from the Nitro Func so the updater never touches bridge types.
420
416
  nowPlaying.formatter =
421
- setupOptions.nowPlayingMetadataFormatter?.let { f -> { params -> f.invoke(params).await() } }
417
+ setupOptions.nowPlayingMetadataFormatter?.let { f ->
418
+ { params -> f.invoke(params).awaitOrTimeout() }
419
+ }
422
420
 
423
421
  val newEngineOptions = setupOptions.engineOptions()
424
422
  if (newEngineOptions == engineOptions) {
@@ -463,7 +461,6 @@ internal constructor(
463
461
  context,
464
462
  setupOptions,
465
463
  cache,
466
- shouldRetry = { playWhenReadyCache },
467
464
  isOnline = { networkMonitor.getOnline() },
468
465
  hasPlayed = { hasPlayedCache },
469
466
  onRetryPending = ::reportRetryingError,
@@ -508,6 +505,7 @@ internal constructor(
508
505
  { options },
509
506
  keepSessionAliveOnError,
510
507
  isPaused = { playbackState == PlaybackState.PAUSED },
508
+ stopPlayer = ::stop,
511
509
  )
512
510
  forwardingPlayer.addListener(playerListener)
513
511
  if (::mediaSession.isInitialized) mediaSession.player = forwardingPlayer
@@ -557,25 +555,22 @@ internal constructor(
557
555
  }
558
556
  }
559
557
 
560
- fun add(track: Track) {
561
- val mediaItem = TrackFactory.toMedia3(track)
562
- sessionPlayer.addMediaItem(mediaItem)
563
- sessionPlayer.prepare()
564
- }
558
+ fun add(track: Track) = add(arrayOf(track))
565
559
 
566
- fun add(tracks: Array<Track>) {
567
- val mediaItems = TrackFactory.toMedia3(tracks)
568
- sessionPlayer.addMediaItems(mediaItems.toList())
569
- sessionPlayer.prepare()
570
- }
571
-
572
- /** @throws IllegalArgumentException unless [atIndex] is within the queue, or -1 to append. */
573
- fun add(tracks: Array<Track>, atIndex: Int) {
560
+ /**
561
+ * Loads only into an empty queue: a queue that had tracks keeps its current one as it was, idle
562
+ * after a stop or a cancelled retry.
563
+ *
564
+ * @throws IllegalArgumentException unless [atIndex] is within the queue, or -1 to append.
565
+ */
566
+ fun add(tracks: Array<Track>, atIndex: Int = -1) {
574
567
  validateInsertIndex(atIndex)
575
- val index = if (atIndex == -1) sessionPlayer.mediaItemCount else atIndex
576
- val mediaItems = tracks.map { TrackFactory.toMedia3(it) }
577
- sessionPlayer.addMediaItems(index, mediaItems)
578
- sessionPlayer.prepare()
568
+ val count = sessionPlayer.mediaItemCount
569
+ sessionPlayer.addMediaItems(
570
+ if (atIndex == -1) count else atIndex,
571
+ TrackFactory.toMedia3(tracks),
572
+ )
573
+ if (count == 0) sessionPlayer.prepare()
579
574
  }
580
575
 
581
576
  /** @throws IllegalArgumentException if an index is out of bounds or repeated. */
@@ -911,6 +906,7 @@ internal constructor(
911
906
  false
912
907
  }
913
908
  } catch (e: Exception) {
909
+ currentCoroutineContext().ensureActive()
914
910
  Timber.e(e, "Error handling voice search: ${params}")
915
911
  false
916
912
  }
@@ -923,7 +919,6 @@ internal constructor(
923
919
  }
924
920
 
925
921
  fun pause() {
926
- // Through the setter, so the retry policy sees playWhenReadyCache drop at once.
927
922
  playWhenReady = false
928
923
  }
929
924
 
@@ -999,6 +994,14 @@ internal constructor(
999
994
  val generation = retryingErrorGeneration
1000
995
  mainHandler.post {
1001
996
  if (generation != retryingErrorGeneration) return@post
997
+ // Paused, the retry would run unseen and its failure be terminal. STOPPED, ERROR and ENDED
998
+ // reach here only from a post that raced them.
999
+ if (
1000
+ !playWhenReady &&
1001
+ playbackState !in setOf(PlaybackState.STOPPED, PlaybackState.ERROR, PlaybackState.ENDED)
1002
+ ) {
1003
+ return@post stopRetrying()
1004
+ }
1002
1005
  // Only over a spinner: while PLAYING, buffered audio still plays and ExoPlayer's in-place
1003
1006
  // retry can succeed with no state change, so an error attached there would never clear.
1004
1007
  if (
@@ -1013,19 +1016,23 @@ internal constructor(
1013
1016
  playbackError = error
1014
1017
  callbacks?.onPlaybackChanged(Playback(playbackState, error))
1015
1018
  nowPlaying.render()
1016
- // A pause before this first report found no retry to cancel.
1017
- if (!playWhenReadyCache) cancelRetry()
1018
1019
  }
1019
1020
  }
1020
1021
 
1021
1022
  /**
1022
- * Cancels the retry a dropped play intent leaves scheduled: ExoPlayer still runs it, and its
1023
- * failure would be terminal. The engine idles in PAUSED, where the next prepare() reloads where
1024
- * it failed. No-op unless a retrying error shows.
1023
+ * Cancels the retry a dropped play intent leaves scheduled. No-op unless a retrying error shows.
1025
1024
  */
1026
1025
  internal fun cancelRetry() {
1027
1026
  // The ENDED path drops the intent before it clears the error.
1028
1027
  if (playbackError?.retrying != true || playbackState == PlaybackState.ENDED) return
1028
+ stopRetrying()
1029
+ }
1030
+
1031
+ /**
1032
+ * Gives up a load ExoPlayer would retry. The engine idles in PAUSED, where the next prepare()
1033
+ * reloads where it failed.
1034
+ */
1035
+ private fun stopRetrying() {
1029
1036
  // Before the stop: the state machine holds PAUSED through the IDLE that follows.
1030
1037
  setPlaybackState(PlaybackState.PAUSED)
1031
1038
  clearRetryingError()
@@ -1052,6 +1059,9 @@ internal constructor(
1052
1059
  playbackState = state
1053
1060
 
1054
1061
  if (state == PlaybackState.PLAYING) hasPlayedCache = true
1062
+ if ((oldState == PlaybackState.PAUSED) != (state == PlaybackState.PAUSED)) {
1063
+ forwardingPlayer.onPausedChanged()
1064
+ }
1055
1065
  if (state == PlaybackState.ERROR) resetForNewLoad()
1056
1066
 
1057
1067
  // A natural end exhausts the play intent; held, it inverts the toggle, keeps audio focus and
@@ -49,7 +49,6 @@ internal fun buildPlayerEngine(
49
49
  context: Context,
50
50
  options: PlayerSetupOptions,
51
51
  cache: SimpleCache?,
52
- shouldRetry: () -> Boolean,
53
52
  isOnline: () -> Boolean,
54
53
  hasPlayed: () -> Boolean,
55
54
  onRetryPending: (exception: IOException) -> Unit,
@@ -67,7 +66,6 @@ internal fun buildPlayerEngine(
67
66
  context,
68
67
  cache,
69
68
  options.retryPolicy,
70
- shouldRetry = shouldRetry,
71
69
  isOnline = isOnline,
72
70
  hasPlayed = hasPlayed,
73
71
  onRetryPending = onRetryPending,