react-native-queue-player 1.0.3 → 1.0.6

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 (103) hide show
  1. package/android/src/main/java/com/margelo/nitro/queueplayer/BufferStateTranslator.kt +1 -1
  2. package/android/src/main/java/com/margelo/nitro/queueplayer/CarConnectionState.kt +46 -0
  3. package/android/src/main/java/com/margelo/nitro/queueplayer/Equalizer.kt +1 -3
  4. package/android/src/main/java/com/margelo/nitro/queueplayer/HeadlessJsMediaService.kt +2 -4
  5. package/android/src/main/java/com/margelo/nitro/queueplayer/LookaheadCacheWriter.kt +7 -9
  6. package/android/src/main/java/com/margelo/nitro/queueplayer/MilestoneTracker.kt +1 -2
  7. package/android/src/main/java/com/margelo/nitro/queueplayer/NotificationProvider.kt +6 -0
  8. package/android/src/main/java/com/margelo/nitro/queueplayer/PlaybackService.kt +33 -25
  9. package/android/src/main/java/com/margelo/nitro/queueplayer/PlaybackServiceCallback.kt +16 -1
  10. package/android/src/main/java/com/margelo/nitro/queueplayer/ProgressEmissionGate.kt +1 -1
  11. package/android/src/main/java/com/margelo/nitro/queueplayer/QueueMutationArithmetic.kt +1 -1
  12. package/android/src/main/java/com/margelo/nitro/queueplayer/QueueSkipArithmetic.kt +1 -1
  13. package/android/src/main/java/com/margelo/nitro/queueplayer/RemoteCommandDeduper.kt +1 -1
  14. package/android/src/main/java/com/margelo/nitro/queueplayer/SessionCommandForwardingPlayer.kt +9 -0
  15. package/android/src/main/java/com/margelo/nitro/queueplayer/SleepTimerCore.kt +1 -1
  16. package/android/src/main/java/com/margelo/nitro/queueplayer/TrackPlayer.kt +40 -27
  17. package/android/src/main/java/com/margelo/nitro/queueplayer/TransportStateTranslator.kt +2 -2
  18. package/android/src/main/res/values/strings.xml +0 -3
  19. package/android/src/test/java/com/margelo/nitro/queueplayer/AudioPipelineRenderersFactoryTest.kt +2 -5
  20. package/android/src/test/java/com/margelo/nitro/queueplayer/AvrcpMetadataTest.kt +1 -0
  21. package/android/src/test/java/com/margelo/nitro/queueplayer/BrowseCallbackRegistryTest.kt +1 -4
  22. package/android/src/test/java/com/margelo/nitro/queueplayer/CrossfadeEngineLifecycleTest.kt +1 -2
  23. package/android/src/test/java/com/margelo/nitro/queueplayer/CrossfadeEngineReplayGainTest.kt +3 -7
  24. package/android/src/test/java/com/margelo/nitro/queueplayer/EqualizerEngineTest.kt +1 -2
  25. package/android/src/test/java/com/margelo/nitro/queueplayer/EqualizerKtTest.kt +1 -3
  26. package/android/src/test/java/com/margelo/nitro/queueplayer/EqualizerLegacyEngineTest.kt +2 -3
  27. package/android/src/test/java/com/margelo/nitro/queueplayer/FFTProcessorTeeTest.kt +1 -2
  28. package/android/src/test/java/com/margelo/nitro/queueplayer/GaplessEngineLifecycleTest.kt +0 -2
  29. package/android/src/test/java/com/margelo/nitro/queueplayer/GaplessEngineReplayGainTest.kt +3 -8
  30. package/android/src/test/java/com/margelo/nitro/queueplayer/HeadlessJsMediaServiceTest.kt +2 -4
  31. package/android/src/test/java/com/margelo/nitro/queueplayer/MediaButtonDispatchTest.kt +1 -0
  32. package/android/src/test/java/com/margelo/nitro/queueplayer/MediaButtonPreferencesTest.kt +99 -0
  33. package/android/src/test/java/com/margelo/nitro/queueplayer/MediaItemBuilderTest.kt +2 -3
  34. package/android/src/test/java/com/margelo/nitro/queueplayer/MilestoneTrackerTest.kt +1 -3
  35. package/android/src/test/java/com/margelo/nitro/queueplayer/NowPlayingFormatExtractorTest.kt +1 -2
  36. package/android/src/test/java/com/margelo/nitro/queueplayer/PitchAwareAudioProcessorChainTest.kt +1 -1
  37. package/android/src/test/java/com/margelo/nitro/queueplayer/PitchCorrectionTest.kt +2 -2
  38. package/android/src/test/java/com/margelo/nitro/queueplayer/PlaybackServiceCallbackTest.kt +148 -7
  39. package/android/src/test/java/com/margelo/nitro/queueplayer/PlaybackServiceLifecycleTest.kt +2 -0
  40. package/android/src/test/java/com/margelo/nitro/queueplayer/ProgressEmissionGateTest.kt +1 -3
  41. package/android/src/test/java/com/margelo/nitro/queueplayer/SessionCommandForwardingPlayerTest.kt +58 -2
  42. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerEventsTest.kt +1 -2
  43. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerMutationTest.kt +2 -4
  44. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerPitchCorrectionTest.kt +1 -2
  45. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerPlaybackModeTest.kt +2 -3
  46. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerReplayGainTest.kt +1 -3
  47. package/android/src/test/java/com/margelo/nitro/queueplayer/TrackPlayerTransportTest.kt +2 -5
  48. package/android/src/test/java/com/margelo/nitro/queueplayer/VisualizerKtTest.kt +1 -2
  49. package/ios/AVPlayerItemQueueItemId.swift +2 -2
  50. package/ios/AVQueueBuilder.swift +12 -14
  51. package/ios/CarPlayCoordinator.swift +38 -0
  52. package/ios/CarPlayQueueBuilder.swift +82 -0
  53. package/ios/CarPlayQueueProvider.swift +73 -0
  54. package/ios/CarPlaySceneDelegate.swift +81 -7
  55. package/ios/CrossfadeEngine.swift +4 -5
  56. package/ios/InputGuards.swift +3 -3
  57. package/ios/LookaheadCache.swift +4 -6
  58. package/ios/LookaheadCachePrefetcher.swift +1 -1
  59. package/ios/MilestoneTracker.swift +1 -2
  60. package/ios/PlaybackErrorMapping.swift +6 -7
  61. package/ios/PlayerStateDerivation.swift +1 -2
  62. package/ios/ProgressEmissionGate.swift +1 -1
  63. package/ios/QueueMutationArithmetic.swift +2 -2
  64. package/ios/QueueSkipArithmetic.swift +8 -12
  65. package/ios/Siri/PlayMediaIntentHandler.swift +1 -5
  66. package/ios/SleepTimerCore.swift +1 -1
  67. package/ios/Tests/AudioTapProviderReplayGainTests.swift +5 -9
  68. package/ios/Tests/CarPlayBridgeTests.swift +2 -6
  69. package/ios/Tests/CarPlayBrowseBuilderTests.swift +1 -2
  70. package/ios/Tests/CarPlayCoordinatorTests.swift +35 -0
  71. package/ios/Tests/CarPlayQueueBuilderTests.swift +145 -0
  72. package/ios/Tests/EQProcessorTests.swift +1 -4
  73. package/ios/Tests/EQTapTests.swift +1 -2
  74. package/ios/Tests/EqualizerAudioMixProviderTests.swift +3 -4
  75. package/ios/Tests/EqualizerHybridTests.swift +1 -3
  76. package/ios/Tests/FFTProcessorTests.swift +10 -10
  77. package/ios/Tests/GaplessEngineLifecycleTests.swift +0 -2
  78. package/ios/Tests/LookaheadCacheEvictionTests.swift +1 -4
  79. package/ios/Tests/MetadataReaderTests.swift +0 -2
  80. package/ios/Tests/MilestoneTrackerTests.swift +1 -3
  81. package/ios/Tests/NowPlayingFormatExtractorTests.swift +3 -4
  82. package/ios/Tests/PlaybackErrorMappingTests.swift +0 -3
  83. package/ios/Tests/PlaybackModeStateMachineTests.swift +5 -9
  84. package/ios/Tests/PlayerStateDerivationTests.swift +1 -2
  85. package/ios/Tests/ProgressEmissionGateTests.swift +1 -3
  86. package/ios/Tests/QueueMutationArithmeticTests.swift +0 -3
  87. package/ios/Tests/RemoteCommandsTests.swift +2 -5
  88. package/ios/Tests/ReplayGainExtractorTests.swift +0 -5
  89. package/ios/Tests/SkipCapabilityTests.swift +4 -7
  90. package/ios/Tests/VoiceDonationTests.swift +4 -4
  91. package/ios/TrackPlayer.swift +52 -2
  92. package/lib/typescript/TrackPlayer.nitro.d.ts +17 -0
  93. package/lib/typescript/TrackPlayer.nitro.d.ts.map +1 -1
  94. package/nitrogen/generated/android/c++/JHybridTrackPlayerSpec.cpp +5 -0
  95. package/nitrogen/generated/android/c++/JHybridTrackPlayerSpec.hpp +1 -0
  96. package/nitrogen/generated/android/kotlin/com/margelo/nitro/queueplayer/HybridTrackPlayerSpec.kt +4 -0
  97. package/nitrogen/generated/ios/c++/HybridTrackPlayerSpecSwift.hpp +8 -0
  98. package/nitrogen/generated/ios/swift/HybridTrackPlayerSpec.swift +1 -0
  99. package/nitrogen/generated/ios/swift/HybridTrackPlayerSpec_cxx.swift +12 -0
  100. package/nitrogen/generated/shared/c++/HybridTrackPlayerSpec.cpp +1 -0
  101. package/nitrogen/generated/shared/c++/HybridTrackPlayerSpec.hpp +1 -0
  102. package/package.json +1 -1
  103. package/src/TrackPlayer.nitro.ts +18 -0
@@ -9,7 +9,7 @@ import androidx.media3.common.Player
9
9
  *
10
10
  * Extracted from [TrackPlayer.computeBufferState] so the discriminator
11
11
  * between an initial `BUFFERING` load and a mid-playback `STALLED`
12
- * rebuffer is unit-testable without a live ExoPlayer, matching the
12
+ * rebuffer stands alone without a live ExoPlayer, matching the
13
13
  * [TransportStateTranslator] pattern.
14
14
  */
15
15
  internal object BufferStateTranslator {
@@ -0,0 +1,46 @@
1
+ package com.margelo.nitro.queueplayer
2
+
3
+ import androidx.annotation.VisibleForTesting
4
+ import java.util.concurrent.atomic.AtomicInteger
5
+
6
+ /**
7
+ * Process-wide count of attached headless (automotive) controllers, backing
8
+ * the `isCarConnected()` getter. Holds the same "a car is connected" state
9
+ * the `onCarConnect` / `onCarDisconnect` events transition between, so a
10
+ * consumer that missed the connect event — because it fired before the
11
+ * consumer registered its handler in this process — can still gate car-only
12
+ * work (e.g. browse-snapshot pushes) on the current connection.
13
+ *
14
+ * The count is process-scoped rather than tied to a [PlaybackService]
15
+ * instance so it stays correct across a service restart while a controller
16
+ * remains attached: the new instance's `onConnect` and the dying instance's
17
+ * late `onConnect`/`onDisconnected` all mutate this single source of truth, so
18
+ * the getter can't momentarily read disconnected mid-handoff. It is
19
+ * floor-guarded so a stray disconnect can't drive it negative, and process
20
+ * death clears it (a fresh process starts disconnected), which is correct.
21
+ *
22
+ * Only [PlaybackServiceCallback] mutates this — at the same headless
23
+ * connect / disconnect points that drive the events. This count is separate
24
+ * from that callback's per-instance counter, which stays per-service so the
25
+ * events keep their per-session first/last edge semantics.
26
+ */
27
+ internal object CarConnectionState {
28
+ private val count = AtomicInteger(0)
29
+
30
+ fun isConnected(): Boolean = count.get() > 0
31
+
32
+ /** A headless controller attached. */
33
+ fun retain() {
34
+ count.incrementAndGet()
35
+ }
36
+
37
+ /** A headless controller detached; never drops below zero. */
38
+ fun release() {
39
+ count.updateAndGet { if (it > 0) it - 1 else 0 }
40
+ }
41
+
42
+ @VisibleForTesting
43
+ fun reset() {
44
+ count.set(0)
45
+ }
46
+ }
@@ -25,9 +25,7 @@ import com.margelo.nitro.core.Promise
25
25
  * The JS-facing methods that mutate state return `Promise<Unit>`
26
26
  * via `Promise.async` per the spec, but each delegates to a
27
27
  * synchronous `*Internal` method that owns the actual mutation.
28
- * Unit tests target the synchronous core; the async wrapper is a
29
- * JS-interface adapter and is exercised at integration via demo
30
- * Maestro.
28
+ * The async wrapper is a thin JS-interface adapter.
31
29
  *
32
30
  * Listener registries follow the same shape as other event
33
31
  * listeners on this lib: stable numeric IDs returned via the
@@ -141,8 +141,7 @@ public abstract class HeadlessJsMediaService :
141
141
  /**
142
142
  * The host's [ReactHost]. Returns `null` when the host
143
143
  * `Application` does not implement [ReactApplication] — production
144
- * Expo / RN consumers always do; the null branch covers the
145
- * Robolectric / unit-test path where the application is a stub.
144
+ * Expo / RN consumers always do.
146
145
  */
147
146
  protected val reactHost: ReactHost?
148
147
  get() = (application as? ReactApplication)?.reactHost
@@ -151,8 +150,7 @@ public abstract class HeadlessJsMediaService :
151
150
  * The live [ReactContext] from the consumer app's [ReactHost], or
152
151
  * `null` when no context has been created yet (the service kicks
153
152
  * one off via [createReactContextAndScheduleTask] in that case) OR
154
- * when the host application isn't a [ReactApplication] at all (e.g.
155
- * unit-test stubs).
153
+ * when the host application isn't a [ReactApplication] at all.
156
154
  */
157
155
  protected val reactContext: ReactContext?
158
156
  get() = reactHost?.currentReactContext
@@ -285,9 +285,8 @@ class LookaheadCacheWriter @VisibleForTesting internal constructor(
285
285
  * cache state.
286
286
  *
287
287
  * `runCatching` swallows the "Method myLooper in android.os.Looper
288
- * not mocked" exception that fires under plain-JUnit (the writer's
289
- * pure-orchestration tests deliberately avoid Robolectric to stay
290
- * fast); production reads the looper normally.
288
+ * not mocked" exception that fires on a JVM host without the Android
289
+ * framework present; production reads the looper normally.
291
290
  */
292
291
  private fun requireMainThread() {
293
292
  val onMain = runCatching {
@@ -429,12 +428,11 @@ class LookaheadCacheWriter @VisibleForTesting internal constructor(
429
428
  // Errors (OutOfMemoryError etc.) propagate — those are
430
429
  // not transient and shouldn't be hidden.
431
430
  //
432
- // Log via runCatching: android.util.Log is not stubbed in
433
- // plain-JUnit test runs (the writer's pure-orchestration
434
- // tests deliberately avoid Robolectric), so a Log.w call
435
- // would throw "Method w in android.util.Log not mocked"
436
- // and terminate the prefetch loop. Production reads this
437
- // log normally; tests get a silent no-op.
431
+ // Log via runCatching: on a JVM host without the Android
432
+ // framework present, android.util.Log is not stubbed, so a
433
+ // Log.w call would throw "Method w in android.util.Log not
434
+ // mocked" and terminate the prefetch loop. Production reads
435
+ // this log normally.
438
436
  runCatching { Log.w(TAG, "Lookahead prefetch failed for ${track.url}: ${e.message}") }
439
437
  }
440
438
 
@@ -2,8 +2,7 @@ package com.margelo.nitro.queueplayer
2
2
 
3
3
  /**
4
4
  * Tracks fixed playback-progress milestones (25/50/75/90%) for the
5
- * current track playthrough. Pure + deterministic (no Media3), so it
6
- * unit-tests directly.
5
+ * current track playthrough. Pure + deterministic (no Media3).
7
6
  *
8
7
  * A threshold emits only when forward playback crosses it: [seek] moves
9
8
  * the baseline WITHOUT emitting (so thresholds a seek jumps over are
@@ -18,6 +18,12 @@ import androidx.media3.session.DefaultMediaNotificationProvider
18
18
  * `setMediaButtonPreferences(...)` builder call; this provider reads
19
19
  * those preferences directly.
20
20
  *
21
+ * This provider only pins the channel + notification id — it does NOT
22
+ * restyle transport buttons. On API 33+ the System UI media control is
23
+ * derived from the media session, so `MediaNotification.Provider` layout
24
+ * changes take effect only pre-33; transport customization belongs in the
25
+ * session's available commands + media button preferences, never here.
26
+ *
21
27
  * Artwork loading is wired separately on the [androidx.media3.session.MediaSession]
22
28
  * via `setBitmapLoader(...)` — the provider routes artwork requests
23
29
  * through that loader chain
@@ -150,8 +150,8 @@ class PlaybackService : HeadlessJsMediaService() {
150
150
  * [PendingIntentBuffer] TTL: ~3 s for bridge boot + ~17 s of
151
151
  * headroom for the consumer's network calls before the controller
152
152
  * surfaces "no results" and the user retries. The two platforms'
153
- * cold-start windows are deliberately the same so the manual
154
- * playbook reads identically on iPhone + Android.
153
+ * cold-start windows are deliberately kept the same so the
154
+ * behaviour is identical on iPhone + Android.
155
155
  */
156
156
  private const val HEADLESS_DISPATCH_TIMEOUT_MS = 20_000L
157
157
 
@@ -788,20 +788,18 @@ class PlaybackService : HeadlessJsMediaService() {
788
788
  )
789
789
 
790
790
  /**
791
- * The compact notification view shows three buttons in priority
792
- * order: prev / play-pause / next. Media3 1.9+ resolves these from
793
- * standard player commands set via [CommandButton.Builder.setPlayerCommand]
794
- * no custom command handlers required. The expanded view shows
795
- * the same three buttons plus the scrub progress bar that
796
- * `DefaultMediaNotificationProvider` adds automatically when the
797
- * session reports a known duration.
791
+ * The back + forward buttons for the notification compact view and the
792
+ * Android Auto control row. Play/pause is intentionally NOT supplied:
793
+ * Media3 owns the central slot (`CommandButton.SLOT_CENTRAL`) and
794
+ * synthesizes a state-aware play/pause from `COMMAND_PLAY_PAUSE`. A
795
+ * caller-supplied central button is dropped on the notification path
796
+ * (`DefaultMediaNotificationProvider` builds its own play/pause) and on
797
+ * Android Auto forces a static, non-toggling icon — so supplying only
798
+ * back/forward lets Media3 render the toggling play/pause on both
799
+ * surfaces. The expanded view adds the scrub progress bar automatically
800
+ * when the session reports a known duration.
798
801
  */
799
802
  private fun buildMediaButtonPreferences(): List<CommandButton> {
800
- val playPause = CommandButton.Builder(CommandButton.ICON_PLAY)
801
- .setPlayerCommand(Player.COMMAND_PLAY_PAUSE)
802
- .setSlots(CommandButton.SLOT_CENTRAL)
803
- .setDisplayName(getString(R.string.rnqp_action_play_pause))
804
- .build()
805
803
  // In `interval` mode the back/forward slots jump within the current track
806
804
  // (COMMAND_SEEK_BACK / COMMAND_SEEK_FORWARD, honored by
807
805
  // [SessionCommandForwardingPlayer] with the runtime interval); in `track`
@@ -813,7 +811,6 @@ class PlaybackService : HeadlessJsMediaService() {
813
811
  .setSlots(CommandButton.SLOT_BACK)
814
812
  .setDisplayName(getString(R.string.rnqp_action_jump_backward))
815
813
  .build(),
816
- playPause,
817
814
  CommandButton.Builder(CommandButton.ICON_SKIP_FORWARD)
818
815
  .setPlayerCommand(Player.COMMAND_SEEK_FORWARD)
819
816
  .setSlots(CommandButton.SLOT_FORWARD)
@@ -826,7 +823,6 @@ class PlaybackService : HeadlessJsMediaService() {
826
823
  .setSlots(CommandButton.SLOT_BACK)
827
824
  .setDisplayName(getString(R.string.rnqp_action_previous))
828
825
  .build(),
829
- playPause,
830
826
  CommandButton.Builder(CommandButton.ICON_NEXT)
831
827
  .setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT)
832
828
  .setSlots(CommandButton.SLOT_FORWARD)
@@ -1455,10 +1451,9 @@ class PlaybackService : HeadlessJsMediaService() {
1455
1451
  override fun getTaskConfig(intent: Intent?): com.facebook.react.jstasks.HeadlessJsTaskConfig? {
1456
1452
  val action = intent?.action ?: return null
1457
1453
  if (action !in HEADLESS_WAKE_ACTIONS) return null
1458
- // Robolectric / non-ReactApplication hosts cannot spawn a JS
1459
- // task — short-circuit here so `Arguments.createMap()` never
1460
- // has to load the React native libs that aren't on the test
1461
- // classpath.
1454
+ // Non-ReactApplication hosts cannot spawn a JS task —
1455
+ // short-circuit here so `Arguments.createMap()` never has to load
1456
+ // the React native libs such a host lacks.
1462
1457
  if ((application as? com.facebook.react.ReactApplication) == null) return null
1463
1458
  // Belt-and-braces: if a wake intent somehow lands while a React
1464
1459
  // context is already alive (foreground app, prior wake already
@@ -1621,6 +1616,13 @@ class PlaybackService : HeadlessJsMediaService() {
1621
1616
  // Once both are zero, AA lands on the Library/Browse surface
1622
1617
  // instead of "Now Playing — To play something, tap the icon at
1623
1618
  // the top left."
1619
+ //
1620
+ // This rides Media3 1.10.0's internal Player.Commands →
1621
+ // PlaybackStateCompat action-mask translation, which is not a public
1622
+ // contract — re-validate on a Media3 upgrade. Unit tests cover the
1623
+ // command-strip input; the resulting action mask is verified on the
1624
+ // Android Auto lane, since the legacy bridge only populates for a
1625
+ // connected controller that can't be driven under Robolectric.
1624
1626
  builder.remove(Player.COMMAND_PLAY_PAUSE)
1625
1627
  builder.remove(Player.COMMAND_PREPARE)
1626
1628
  builder.remove(Player.COMMAND_STOP)
@@ -1647,11 +1649,11 @@ class PlaybackService : HeadlessJsMediaService() {
1647
1649
  /**
1648
1650
  * Hook the [PlaybackCallback] consults before letting Media3 route
1649
1651
  * a controller-initiated command to the bound player. Calls run on
1650
- * the service main looper. Skip-next / skip-previous return true
1651
- * when the implementation has handled the skip itself, so the
1652
- * default routing is suppressed; the transport hook fires for play /
1653
- * pause / seek / setPlaybackSpeed and is purely a side-channel
1654
- * notification (no return value).
1652
+ * the service main looper. Skip-next / skip-previous / seek-to-queue-item
1653
+ * return true when the implementation has handled the command itself,
1654
+ * so the default routing is suppressed; the transport hook fires for
1655
+ * play / pause / in-item seek / setPlaybackSpeed and is purely a
1656
+ * side-channel notification (no return value).
1655
1657
  */
1656
1658
  internal interface MediaSessionCommandHandler {
1657
1659
  /** Stamps `system` on the state-change channel for the upcoming
@@ -1663,6 +1665,12 @@ class PlaybackService : HeadlessJsMediaService() {
1663
1665
  /** Returns true if the lib intercepted the skip and the default
1664
1666
  * routing should be suppressed. */
1665
1667
  fun onSkipToPreviousCommand(): Boolean
1668
+ /** Routes an external controller's tap on a queue row (Android Auto's
1669
+ * "seek to this item") through the lib's `skipToIndex` path so the
1670
+ * canonical current index + track-change reason land. Returns true
1671
+ * when handled so the default per-item seek is suppressed; returns
1672
+ * false for an out-of-range index so the default routing no-ops it. */
1673
+ fun onSeekToMediaItemCommand(mediaItemIndex: Int): Boolean
1666
1674
 
1667
1675
  /**
1668
1676
  * Returns the lib's current authoritative skip capability —
@@ -73,7 +73,7 @@ internal class PlaybackServiceCallback(
73
73
  * package (Android Auto, Wear OS, Google Assistant) connects.
74
74
  * Production wires the React-context cold-start through here so
75
75
  * "Hey Google, play …" works from a phone with the app killed.
76
- * Default no-op so unit-test setups without a service can fall
76
+ * Default no-op so callers without a wired service fall
77
77
  * through harmlessly. */
78
78
  fun onHeadlessControllerConnect(packageName: String) {}
79
79
 
@@ -287,6 +287,9 @@ internal class PlaybackServiceCallback(
287
287
  ): MediaSession.ConnectionResult {
288
288
  if (controller.packageName in HEADLESS_ELIGIBLE_PACKAGES) {
289
289
  val previousCount = headlessControllerCount.getAndIncrement()
290
+ // A headless controller is now attached — record it in the process-wide
291
+ // count the `isCarConnected()` getter reads.
292
+ CarConnectionState.retain()
290
293
  environment.onHeadlessControllerConnect(controller.packageName)
291
294
  // Fire onCarConnect only on the FIRST headless controller of
292
295
  // this service-lifetime session — subsequent connects (Wear
@@ -348,6 +351,10 @@ internal class PlaybackServiceCallback(
348
351
  } else if (previousCount > 0 && remaining == 0) {
349
352
  environment.onHeadlessControllerDisconnect()
350
353
  }
354
+ // Drop this controller from the process-wide connection count the
355
+ // `isCarConnected()` getter reads (floor-guarded against a stray
356
+ // disconnect, so it can't go negative).
357
+ CarConnectionState.release()
351
358
  }
352
359
  super.onDisconnected(session, controller)
353
360
  }
@@ -361,6 +368,14 @@ internal class PlaybackServiceCallback(
361
368
  return dispatch.handle(intent, RemoteCommandDeduper.Channel.SESSION_KEY)
362
369
  }
363
370
 
371
+ /**
372
+ * Cold-start playback resumption: a hardware / Bluetooth media button that
373
+ * wakes the service while nothing is loaded. Returns an empty queue by
374
+ * design — the lib does not reconstruct a queue here; a consumer that wants
375
+ * resume-from-cold restores its own queue on launch via `setQueue`. The
376
+ * override exists (rather than being omitted) because Media3 requires a
377
+ * declared `MediaButtonReceiver` to pair with an `onPlaybackResumption`.
378
+ */
364
379
  override fun onPlaybackResumption(
365
380
  mediaSession: MediaSession,
366
381
  controller: MediaSession.ControllerInfo,
@@ -3,7 +3,7 @@ package com.margelo.nitro.queueplayer
3
3
  /**
4
4
  * Throttles the JS `onProgress` fan-out to a configurable cadence, with an
5
5
  * optional reduced rate while the app is backgrounded. Pure + deterministic
6
- * (the caller supplies a monotonic timestamp), so it unit-tests directly.
6
+ * (the caller supplies a monotonic timestamp).
7
7
  *
8
8
  * This gates ONLY the JS emission — the native 2 Hz sampler keeps running, so
9
9
  * milestone detection and buffer-state recomputation stay full-rate. A tick
@@ -2,7 +2,7 @@ package com.margelo.nitro.queueplayer
2
2
 
3
3
  /**
4
4
  * Pure-Kotlin index-shift arithmetic for queue mutations. Extracted
5
- * from [TrackPlayer] so the shift semantics are unit-testable without
5
+ * from [TrackPlayer] so the shift semantics stand alone without
6
6
  * an ExoPlayer. Mirrors (and lightly supersedes) the inline math
7
7
  * inside iOS `TrackPlayer.swift`'s `addToQueueBody` /
8
8
  * `removeFromQueueBody` / `moveInQueueBody` — the iOS backlog carries
@@ -4,7 +4,7 @@ package com.margelo.nitro.queueplayer
4
4
  * Pure-Kotlin skip-index arithmetic. Mirrors the iOS sibling
5
5
  * `ios/QueueSkipArithmetic.swift` 1-for-1.
6
6
  *
7
- * Extracted from [TrackPlayer] so the logic is unit-testable without
7
+ * Extracted from [TrackPlayer] so the logic stands alone without
8
8
  * instantiating an ExoPlayer. [TrackPlayer.computeNextIndex] /
9
9
  * [TrackPlayer.computePreviousIndex] are thin adapters that translate
10
10
  * the Nitrogen-generated [RepeatMode] enum into [QueueSkipRepeatMode]
@@ -29,7 +29,7 @@ package com.margelo.nitro.queueplayer
29
29
  *
30
30
  * Bias is toward emitting: when in doubt, act rather than swallow a real press.
31
31
  *
32
- * Pure and time-injected ([nowUptimeMs] is passed in) so it unit-tests without an
32
+ * Pure and time-injected ([nowUptimeMs] is passed in), so it needs no
33
33
  * Android runtime. [shouldEmit] is `@Synchronized` so it is safe regardless of
34
34
  * which thread an emit site runs on (today they are all main-thread-confined).
35
35
  */
@@ -89,6 +89,15 @@ internal class SessionCommandForwardingPlayer(
89
89
  Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ->
90
90
  if (commandHandler()?.onSkipToPreviousCommand() == true) Futures.immediateVoidFuture()
91
91
  else super.handleSeek(mediaItemIndex, positionMs, seekCommand)
92
+ // Android Auto's queue-row tap. A raw per-item seek would move the
93
+ // player without updating the lib's canonical current index — the
94
+ // SEEK transition handler only syncs the index for player-originated
95
+ // transitions, not controller seeks. Route through the skip path so
96
+ // the index + track-change reason land; an index the lib declines
97
+ // (out of range) falls through to the default seek.
98
+ Player.COMMAND_SEEK_TO_MEDIA_ITEM ->
99
+ if (commandHandler()?.onSeekToMediaItemCommand(mediaItemIndex) == true) Futures.immediateVoidFuture()
100
+ else super.handleSeek(mediaItemIndex, positionMs, seekCommand)
92
101
  // Interval-skip mode: recompute the target with the runtime jump interval
93
102
  // rather than the wrapped player's build-time seek increment, so the value
94
103
  // is adjustable at runtime.
@@ -2,7 +2,7 @@ package com.margelo.nitro.queueplayer
2
2
 
3
3
  /**
4
4
  * Pure state machine for the sleep timer — no player, volume, or handler
5
- * dependencies, so it is unit-testable in isolation. The owning [TrackPlayer]
5
+ * dependencies, so it stands alone. The owning [TrackPlayer]
6
6
  * drives it from a repeating main-looper runnable and applies the returned
7
7
  * decision (volume fade, pause) to the engine.
8
8
  *
@@ -46,10 +46,9 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
46
46
  // --- Stored state
47
47
  //
48
48
  // Mirrors iOS TrackPlayer.swift's "Stored state" block. Field
49
- // visibility is `internal` + `@VisibleForTesting` so Robolectric
50
- // tests can observe lifecycle transitions without going through
51
- // the JNI-backed Nitro Promise machinery (which does not load in
52
- // the JVM unit-test runtime).
49
+ // visibility is `internal` + `@VisibleForTesting` so lifecycle
50
+ // transitions can be observed without going through the JNI-backed
51
+ // Nitro Promise machinery (which does not load on a plain JVM).
53
52
 
54
53
  /**
55
54
  * `true` after [configureInternal] has bound + configured the
@@ -158,8 +157,7 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
158
157
  private var lastEmittedFormatMediaItem: MediaItem? = null
159
158
 
160
159
  // The fields below are written on main (via `onMain` / `syncMain`
161
- // from the Promise adapter path, or directly from Robolectric tests
162
- // which run on main). They are read off-main by the synchronous
160
+ // from the Promise adapter path). They are read off-main by the synchronous
163
161
  // snapshot accessors — `getCurrentTrackIndex`, `getQueue` —
164
162
  // dispatched on the JS thread by Nitro. `@Volatile` gives the
165
163
  // read path a happens-before edge on the most recent main-thread
@@ -581,7 +579,7 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
581
579
  private val progressEmissionGate = ProgressEmissionGate()
582
580
  // ProcessLifecycleOwner observer driving the gate's background state. Held in
583
581
  // a nullable field so a re-configureInternal without an intervening
584
- // destroyInternal (Robolectric) is a no-op instead of leaking a second
582
+ // destroyInternal is a no-op instead of leaking a second
585
583
  // observer. Registered in configureInternal, removed in destroyInternal.
586
584
  private var progressLifecycleObserver: DefaultLifecycleObserver? = null
587
585
  private val errorListeners = ListenerRegistry<(PlaybackError) -> Unit>()
@@ -866,11 +864,10 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
866
864
  }
867
865
 
868
866
  /**
869
- * Lifecycle configure body. `internal` so Robolectric tests can
870
- * exercise it without the Nitro Promise path. Callers MUST hop
871
- * to the main thread first ExoPlayer construction binds to the
872
- * calling Looper. Production path goes through `onMain`; tests
873
- * run on Robolectric's main-thread dispatcher.
867
+ * Lifecycle configure body. `internal`, bypassing the Nitro Promise
868
+ * path. Callers MUST hop to the main thread first ExoPlayer
869
+ * construction binds to the calling Looper. Production path goes
870
+ * through `onMain`.
874
871
  *
875
872
  * Builds the ExoPlayer with a [MediaSource.Factory] that attaches
876
873
  * the config's HTTP headers + User-Agent on every network request.
@@ -879,9 +876,8 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
879
876
  * Per the universal auto-destroy contract every `configure()` call
880
877
  * tears the player down upstream so this body is purely
881
878
  * constructive — `player` is guaranteed null on entry from the
882
- * production path. Robolectric tests that drive `configureInternal`
883
- * directly are responsible for calling `destroyInternal` first
884
- * between configures.
879
+ * production path. Any caller driving `configureInternal` directly
880
+ * must call `destroyInternal` first between configures.
885
881
  */
886
882
  @VisibleForTesting
887
883
  @MainThread
@@ -995,6 +991,25 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
995
991
  return true
996
992
  }
997
993
 
994
+ override fun onSeekToMediaItemCommand(mediaItemIndex: Int): Boolean {
995
+ // Decline an out-of-range index so the default per-item seek
996
+ // no-ops it (Media3 passes C.INDEX_UNSET when the seek implies
997
+ // no move).
998
+ if (mediaItemIndex < 0 || mediaItemIndex >= tracks.size) return false
999
+ pendingStateChangeReason = StateChangeReason.SYSTEM
1000
+ // Same path as the public skipToIndex: jump the receiver while
1001
+ // casting, else the local engine. Both write currentTrackIndex +
1002
+ // the USER_SKIP_TO_INDEX reason that a raw controller seek skips.
1003
+ // The tapped track starts at position 0 — the controller's
1004
+ // positionMs is intentionally not threaded through, matching the
1005
+ // public skipToIndex "play this track" contract.
1006
+ if (com.margelo.nitro.queueplayer.cast.CastTransportRouter.routeSkipToIndex(mediaItemIndex)) {
1007
+ return true
1008
+ }
1009
+ skipToIndexInternal(mediaItemIndex)
1010
+ return true
1011
+ }
1012
+
998
1013
  override fun onMediaPlay() {
999
1014
  pendingStateChangeReason = StateChangeReason.SYSTEM
1000
1015
  serviceBinder?.engine?.play()
@@ -2442,9 +2457,9 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
2442
2457
  /**
2443
2458
  * Main-thread body for [setPlaybackSpeed]. The engine applies the
2444
2459
  * active pitch-correction mode's pitch alongside the speed (voice/music
2445
- * preserve pitch; none lets it follow rate). Exposed `@VisibleForTesting`
2446
- * so Robolectric exercises the cast + speed-application logic rather than
2447
- * just bypassing through `ExoPlayer.playbackParameters`.
2460
+ * preserve pitch; none lets it follow rate). Exposed `@VisibleForTesting`;
2461
+ * centralizes the cast + speed-application logic rather than routing
2462
+ * straight through `ExoPlayer.playbackParameters`.
2448
2463
  *
2449
2464
  * Diverges from iOS: on iOS `player.rate = Float(rate)` implicitly
2450
2465
  * starts playback when the player was paused. Android's
@@ -3032,6 +3047,8 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
3032
3047
  override fun onCarDisconnect(callback: () -> Unit): () -> Unit =
3033
3048
  deferredRegister { it.registerOnCarDisconnect(callback) }
3034
3049
 
3050
+ override fun isCarConnected(): Boolean = CarConnectionState.isConnected()
3051
+
3035
3052
  override fun onServiceReady(
3036
3053
  callback: (reason: ServiceReadyReason) -> Unit
3037
3054
  ): () -> Unit = deferredRegister { it.registerOnServiceReady(callback) }
@@ -4157,11 +4174,9 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
4157
4174
  }
4158
4175
 
4159
4176
  /**
4160
- * Test hook: stash a [TrackChangeReason] that the next
4177
+ * Stash a [TrackChangeReason] that the next
4161
4178
  * [handleMediaItemTransition] with `REASON_SEEK` will consume.
4162
- * Production code reaches this field via `skipTo*Internal`
4163
- * bodies; the hook just lets Robolectric tests simulate the
4164
- * stash without driving a real skip + ExoPlayer seek.
4179
+ * Production code reaches this field via `skipTo*Internal` bodies.
4165
4180
  */
4166
4181
  @VisibleForTesting
4167
4182
  internal fun setPendingTrackChangeReasonForTest(reason: TrackChangeReason?) {
@@ -4169,9 +4184,8 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
4169
4184
  }
4170
4185
 
4171
4186
  /**
4172
- * Test hook: reset the [lastReportedState] dedup edge so
4173
- * [emitStateIfChanged] tests can force an emit from an already-
4174
- * NONE state without going through a real Player.Listener fire.
4187
+ * Reset the [lastReportedState] dedup edge, forcing [emitStateIfChanged]
4188
+ * to emit from an already-NONE state without a real Player.Listener fire.
4175
4189
  */
4176
4190
  @VisibleForTesting
4177
4191
  internal fun resetLastReportedStateForTest() {
@@ -4250,8 +4264,7 @@ class TrackPlayer : HybridTrackPlayerSpec(), PlaybackEngineDelegate {
4250
4264
 
4251
4265
  /**
4252
4266
  * Decide which [ServiceReadyReason] (if any) to dispatch on a
4253
- * fresh service-bind. Pure function so the reason-decision logic
4254
- * is unit-testable without spinning up a service controller.
4267
+ * fresh service-bind. Pure function no service controller needed.
4255
4268
  *
4256
4269
  * - First-ever bind ([prior] == null): [ServiceReadyReason.FIRST_BIND].
4257
4270
  * - Bind against a different binder identity:
@@ -7,8 +7,8 @@ import androidx.media3.common.Player
7
7
  * isPlaying, playWhenReady, playbackSuppressionReason, hasTracks,
8
8
  * currentTrackIndex)` tuple to the library's [PlayerState] enum.
9
9
  *
10
- * Extracted from [TrackPlayer.getStateInternal] so every branch is
11
- * unit-testable without a live ExoPlayer. Matches the pattern of
10
+ * Extracted from [TrackPlayer.getStateInternal] so every branch
11
+ * stands alone without a live ExoPlayer. Matches the pattern of
12
12
  * [QueueSkipArithmetic] + [QueueMutationArithmetic] — TrackPlayer
13
13
  * is a thin adapter that reads the live player's state and
14
14
  * delegates the translation here.
@@ -11,9 +11,6 @@
11
11
  transport button. Shown by TalkBack and by pre-Media3 controllers
12
12
  that read the platform PlaybackStateCompat custom-action name. -->
13
13
  <string name="rnqp_action_previous">Previous</string>
14
- <!-- Accessibility / legacy-controller label for the play-pause
15
- transport button. -->
16
- <string name="rnqp_action_play_pause">Play or pause</string>
17
14
  <!-- Accessibility / legacy-controller label for the next-track
18
15
  transport button. -->
19
16
  <string name="rnqp_action_next">Next</string>
@@ -14,12 +14,9 @@ import java.lang.reflect.Field
14
14
  /**
15
15
  * Unit coverage for [AudioPipelineRenderersFactory] construction — it wraps a
16
16
  * caller-supplied [androidx.media3.common.audio.AudioProcessorChain] and leaves
17
- * the produced sink at 16-bit (float output off). The engines drive end-to-end exercise of
18
- * `buildAudioSink` via `ExoPlayer.Builder.build()` in
19
- * [GaplessEngineLifecycleTest] / [CrossfadeEngineLifecycleTest]; `buildAudioSink`
17
+ * the produced sink at 16-bit (float output off). `buildAudioSink`
20
18
  * itself is `protected` on [DefaultRenderersFactory] and cannot be called
21
- * outside the Media3 internal call path. Chain composition + order is covered by
22
- * [PitchAwareAudioProcessorChainTest].
19
+ * outside the Media3 internal call path.
23
20
  */
24
21
  @RunWith(RobolectricTestRunner::class)
25
22
  @Config(sdk = [34])
@@ -252,6 +252,7 @@ class AvrcpMetadataTest {
252
252
  override fun onTransportCommand() {}
253
253
  override fun onSkipToNextCommand(): Boolean = false
254
254
  override fun onSkipToPreviousCommand(): Boolean = false
255
+ override fun onSeekToMediaItemCommand(mediaItemIndex: Int): Boolean = false
255
256
  override fun getCachedSkipCapability(): SkipCapability = capability
256
257
  override fun onMediaPlay() {}
257
258
  override fun onMediaPause() {}
@@ -9,10 +9,7 @@ import org.junit.Test
9
9
  /**
10
10
  * Pure-Kotlin coverage for [BrowseCallbackRegistry]'s slot-replace
11
11
  * + dispose semantics. The Promise-typed callbacks are stored as
12
- * function references; tests use simple stand-in lambdas — actual
13
- * dispatch coverage lives at the integration layer
14
- * (`PlaybackServiceCallbackSearchTest` for the search dispatch
15
- * path; future Maestro flows for end-to-end Auto cold-wake).
12
+ * function references; tests use simple stand-in lambdas.
16
13
  */
17
14
  @UnstableApi
18
15
  class BrowseCallbackRegistryTest {
@@ -15,8 +15,7 @@ import org.robolectric.annotation.Config
15
15
  /**
16
16
  * Lifecycle + fade-math coverage for [CrossfadeEngine].
17
17
  *
18
- * Audible verification of the dual-player crossfade runs at the
19
- * Maestro / demo-app integration layer; this suite exercises:
18
+ * This suite exercises:
20
19
  * empty-state sentinels, role-swap arithmetic, equal-power gain
21
20
  * curve, duration-clamp formula, manual-skip cancellation,
22
21
  * release idempotence + delegate clearing.
@@ -24,9 +24,7 @@ import org.robolectric.annotation.Config
24
24
  * Media3 metadata dispatch is not emulated by Robolectric without
25
25
  * playback, so the listener body composes its work through the
26
26
  * engine-internal `handleReplayGainParse(isA, parsed)` helper which
27
- * these tests drive directly with synthetic [ReplayGainData]. The
28
- * pure-math piece is covered in [ReplayGainGainTest]; end-to-end
29
- * propagation lands in the demo app's `replaygain` Maestro suite.
27
+ * these tests drive directly with synthetic [ReplayGainData].
30
28
  * This file covers the no-data baseline + the per-leg
31
29
  * `handleReplayGainParse` cache + recompute contract.
32
30
  */
@@ -173,8 +171,6 @@ class CrossfadeEngineReplayGainTest {
173
171
 
174
172
  // The per-leg cache-clear-on-transition path lives inline in each
175
173
  // leg's `Player.Listener.onMediaItemTransition` body. Robolectric
176
- // does not drive that callback without real playback; integration
177
- // coverage is in `RNQP-Demo/src/tests/suites/replaygain.ts` (steps
178
- // `cross-track-active-updates` +
179
- // `skip-next-mid-playback-resets-from-stale-cache`).
174
+ // does not drive that callback without real playback, so it is out
175
+ // of scope here.
180
176
  }
@@ -13,8 +13,7 @@ import org.robolectric.annotation.Config
13
13
  /**
14
14
  * State-mirror coverage for [EqualizerEngine] on the API 28+ path.
15
15
  * Robolectric stubs the audio-effect subsystem at this SDK level so
16
- * `attach` exercises the construction path without throwing; the
17
- * audible effect is verified at integration via demo Maestro.
16
+ * `attach` exercises the construction path without throwing.
18
17
  */
19
18
  @RunWith(RobolectricTestRunner::class)
20
19
  @Config(sdk = [34])