@tobyt/react-native-audio-browser 1.1.0 → 1.1.1

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 (52) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +3 -2
  2. package/android/src/main/java/com/audiobrowser/ChosenChannelMode.kt +4 -1
  3. package/android/src/main/java/com/audiobrowser/LoopRangeCommand.kt +13 -0
  4. package/android/src/main/java/com/audiobrowser/player/Player.kt +100 -14
  5. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +11 -6
  6. package/android/src/test/java/com/audiobrowser/ChosenChannelModeTest.kt +22 -0
  7. package/android/src/test/java/com/audiobrowser/LoopRangeCommandTest.kt +22 -0
  8. package/android/src/test/java/com/audiobrowser/player/LoopRangeCaseTest.kt +6 -0
  9. package/android/src/test/java/com/audiobrowser/player/LoopRangeEngineLifecycleTest.kt +170 -0
  10. package/android/src/test/java/com/audiobrowser/player/LoopRangePinSeekTest.kt +158 -0
  11. package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +20 -0
  12. package/ios/AVPlayerEngine.swift +2 -2
  13. package/ios/Player/PlaybackBoundaryTime.swift +11 -0
  14. package/ios/Player/Player.swift +3 -3
  15. package/ios/Tests/ChannelModeTapAudioMixTests.swift +144 -0
  16. package/ios/Tests/LoopRangeCaseTests.swift +14 -3
  17. package/ios/Tests/PlaybackBoundaryTimeTests.swift +20 -0
  18. package/ios/Tests/PlayerChannelModeTests.swift +18 -0
  19. package/ios/Tests/SupersedingTaskTests.swift +4 -1
  20. package/lib/commonjs/test-utils/fakeAudioContext.js +221 -0
  21. package/lib/commonjs/test-utils/fakeAudioContext.js.map +1 -0
  22. package/lib/commonjs/web/NativeAudioBrowser.js +14 -10
  23. package/lib/commonjs/web/NativeAudioBrowser.js.map +1 -1
  24. package/lib/commonjs/web/TrackPlayer/ChannelRouter.js +34 -11
  25. package/lib/commonjs/web/TrackPlayer/ChannelRouter.js.map +1 -1
  26. package/lib/commonjs/web/TrackPlayer/Player.js +6 -0
  27. package/lib/commonjs/web/TrackPlayer/Player.js.map +1 -1
  28. package/lib/commonjs/web/TrackPlayer/QueuePlayer.js +6 -2
  29. package/lib/commonjs/web/TrackPlayer/QueuePlayer.js.map +1 -1
  30. package/lib/module/test-utils/fakeAudioContext.js +212 -0
  31. package/lib/module/test-utils/fakeAudioContext.js.map +1 -0
  32. package/lib/module/web/NativeAudioBrowser.js +14 -10
  33. package/lib/module/web/NativeAudioBrowser.js.map +1 -1
  34. package/lib/module/web/TrackPlayer/ChannelRouter.js +34 -11
  35. package/lib/module/web/TrackPlayer/ChannelRouter.js.map +1 -1
  36. package/lib/module/web/TrackPlayer/Player.js +6 -0
  37. package/lib/module/web/TrackPlayer/Player.js.map +1 -1
  38. package/lib/module/web/TrackPlayer/QueuePlayer.js +6 -2
  39. package/lib/module/web/TrackPlayer/QueuePlayer.js.map +1 -1
  40. package/lib/typescript/src/test-utils/fakeAudioContext.d.ts +86 -0
  41. package/lib/typescript/src/test-utils/fakeAudioContext.d.ts.map +1 -0
  42. package/package.json +1 -1
  43. package/src/test-utils/fakeAudioContext.ts +229 -0
  44. package/src/web/NativeAudioBrowser.audioProcessing.test.ts +7 -234
  45. package/src/web/NativeAudioBrowser.ts +19 -10
  46. package/src/web/TrackPlayer/ChannelRouter.ts +36 -12
  47. package/src/web/TrackPlayer/Player.channelMode.test.ts +159 -0
  48. package/src/web/TrackPlayer/Player.loopRange.test.ts +17 -4
  49. package/src/web/TrackPlayer/Player.ts +11 -0
  50. package/src/web/TrackPlayer/QueuePlayer.ts +4 -2
  51. package/src/web/__tests__/lifecycle.test.ts +53 -0
  52. package/src/web/__tests__/lifecycleHarness.ts +4 -2
@@ -1078,8 +1078,9 @@ class AudioBrowser : HybridAudioBrowserSpec(), ServiceConnection {
1078
1078
  // MARK: Sleep Timer
1079
1079
  // ============================================================================
1080
1080
 
1081
- override fun setLoopRange(range: LoopRange) =
1082
- commandPlayer("setLoopRange") { it.setLoopRange(range) }
1081
+ override fun setLoopRange(range: LoopRange) = runBlockingOnMain {
1082
+ setLoopRangeOn(connectedPlayer, range)
1083
+ }
1083
1084
 
1084
1085
  override fun getLoopRange(): LoopRange? = readPlayer(null) { it.getLoopRange() }
1085
1086
 
@@ -25,9 +25,12 @@ internal class ChosenChannelMode(private val emit: (ChannelMode) -> Unit) {
25
25
 
26
26
  /**
27
27
  * Gives a newly connected [player] the chosen mode. Call it before the Player has the module's
28
- * callbacks: the app already heard this mode.
28
+ * callbacks: the app already heard this mode. When the app chose none, as after a JS reload, the
29
+ * Player keeps its own mode, and the app hears it if it differs from what [get] reported so far.
29
30
  */
30
31
  fun handTo(player: Player) {
32
+ val reported = get(null)
31
33
  chosen?.let { player.channelMode = it }
34
+ if (player.channelMode != reported) emit(player.channelMode)
32
35
  }
33
36
  }
@@ -0,0 +1,13 @@
1
+ package com.audiobrowser
2
+
3
+ import com.audiobrowser.player.LOOP_RANGE_REQUIRES_ACTIVE_TRACK
4
+ import com.audiobrowser.player.Player
5
+ import com.margelo.nitro.audiobrowser.LoopRange
6
+
7
+ /**
8
+ * AudioBrowser.setLoopRange on the connected [player]. With none there is no Active Track to loop,
9
+ * so it throws as iOS does, rather than dropping the call as other commands do.
10
+ */
11
+ internal fun setLoopRangeOn(player: Player?, range: LoopRange) {
12
+ requireNotNull(player) { LOOP_RANGE_REQUIRES_ACTIVE_TRACK }.setLoopRange(range)
13
+ }
@@ -160,6 +160,7 @@ internal constructor(
160
160
 
161
161
  private var loopRange: LoopRange? = null
162
162
  private var loopRangeMessage: PlayerMessage? = null
163
+ private var loopEndPause: LoopEndPause = LoopEndPause.None
163
164
 
164
165
  fun getLoopRange(): LoopRange? = loopRange
165
166
 
@@ -170,9 +171,10 @@ internal constructor(
170
171
  require(range.start >= 0 && range.end >= 0) { "Loop Range positions must not be negative" }
171
172
  require(range.start < range.end) { "Loop Range start must be less than end" }
172
173
  require(localEngine.isActive) { "Loop Range is not available on a Remote Output" }
173
- val track = requireNotNull(currentTrack) { "Loop Range requires an Active Track" }
174
+ val track = requireNotNull(currentTrack) { LOOP_RANGE_REQUIRES_ACTIVE_TRACK }
174
175
  require(track.live != true) { "Loop Range is not available for a live Active Track" }
175
176
  loopRange = range
177
+ loopEndPause = LoopEndPause.None
176
178
  callbacks?.onLoopRangeChanged(LoopRangeChangedEvent(range))
177
179
  armLoopRange()
178
180
  }
@@ -180,8 +182,8 @@ internal constructor(
180
182
  fun clearLoopRange(): Boolean {
181
183
  if (loopRange == null) return false
182
184
  loopRange = null
183
- loopRangeMessage?.cancel()
184
- loopRangeMessage = null
185
+ loopEndPause = LoopEndPause.None
186
+ cancelLoopRangeMessage()
185
187
  exoPlayer.pauseAtEndOfMediaItems = false
186
188
  callbacks?.onLoopRangeChanged(LoopRangeChangedEvent(null))
187
189
  return true
@@ -190,28 +192,88 @@ internal constructor(
190
192
  internal val isLoopRangeHoldingTrackEnd: Boolean
191
193
  get() = loopRangeMessage != null && exoPlayer.pauseAtEndOfMediaItems
192
194
 
193
- internal fun armLoopRange() {
195
+ /**
196
+ * Whether an engine state change belongs to the pin seek and is dropped. The pin seek re-buffers,
197
+ * which would settle READY: the pause the sleep timer made holds as PAUSED, as it does anywhere
198
+ * else in the track.
199
+ *
200
+ * Only that seek's BUFFERING and the READY that ends it are dropped, while paused. Any other
201
+ * state ends the pin seek and reaches listeners: IDLE (a stop, an error), ENDED. So does every
202
+ * state after another seek ([onSeek]), a track change or a rebuild takes over the engine.
203
+ */
204
+ internal fun consumePinSeekStateChange(): Boolean {
205
+ if (loopEndPause !is LoopEndPause.PinSeekSettling) return false
206
+ val state = exoPlayer.playbackState
207
+ if (state != MediaPlayer.STATE_BUFFERING) loopEndPause = LoopEndPause.Paused
208
+ return !playWhenReady &&
209
+ (state == MediaPlayer.STATE_BUFFERING || state == MediaPlayer.STATE_READY)
210
+ }
211
+
212
+ /**
213
+ * A seek to [positionMs] took the engine. One to anywhere but the pin seek's target is another
214
+ * seek, and the state changes from here are its own. The pin seek's own discontinuity can arrive
215
+ * after the pin seek is recorded: the session player reports it a main-thread turn later.
216
+ */
217
+ internal fun onSeek(positionMs: Long) {
218
+ val pause = loopEndPause
219
+ if (pause is LoopEndPause.PinSeekSettling && positionMs != pause.targetMs) endPinSeek()
220
+ }
221
+
222
+ /** The state changes from here are not the pin seek's. */
223
+ private fun endPinSeek() {
224
+ if (loopEndPause is LoopEndPause.PinSeekSettling) loopEndPause = LoopEndPause.Paused
225
+ }
226
+
227
+ /** Paused at the loop end by the sleep timer: a play resumes from the loop start. */
228
+ private fun restartLoopRangeAfterSleep() {
229
+ if (loopEndPause == LoopEndPause.None) return
230
+ loopEndPause = LoopEndPause.None
231
+ val bounds = loopRange?.let(::loopBounds) ?: return
232
+ if (exoPlayer.currentPosition >= bounds.endMs) exoPlayer.seekTo(bounds.startMs)
233
+ }
234
+
235
+ /**
236
+ * The range on the engine's clock, its end capped at the track end once the duration is known.
237
+ */
238
+ private fun loopBounds(range: LoopRange): LoopBounds {
239
+ val requestedEndMs = (range.end * 1000).toLong()
240
+ val durationMs = exoPlayer.duration
241
+ val endsAtTrackEnd = durationMs > 0 && requestedEndMs >= durationMs
242
+ return LoopBounds(
243
+ startMs = (range.start * 1000).toLong(),
244
+ endMs = if (endsAtTrackEnd) durationMs else requestedEndMs,
245
+ endsAtTrackEnd = endsAtTrackEnd,
246
+ )
247
+ }
248
+
249
+ /** Before the engine is released: its pending loop-back must not outlive it. */
250
+ private fun cancelLoopRangeMessage() {
194
251
  loopRangeMessage?.cancel()
195
252
  loopRangeMessage = null
253
+ }
254
+
255
+ internal fun armLoopRange() {
256
+ cancelLoopRangeMessage()
196
257
  exoPlayer.pauseAtEndOfMediaItems = false
197
258
  val range = loopRange ?: return
198
- val requestedEndMs = (range.end * 1000).toLong()
199
- val durationMs = exoPlayer.duration
200
- val endMs = if (durationMs > 0) minOf(requestedEndMs, durationMs) else requestedEndMs
201
- if ((range.start * 1000).toLong() >= endMs) return
202
- if (exoPlayer.currentPosition >= endMs || exoPlayer.currentMediaItem == null) return
259
+ val bounds = loopBounds(range)
260
+ if (bounds.startMs >= bounds.endMs) return
261
+ if (exoPlayer.currentPosition >= bounds.endMs || exoPlayer.currentMediaItem == null) return
203
262
  // Hold the item before Media3's native repeat/advance can run. The main-thread position
204
263
  // message then either seeks back or consumes the end-of-track sleep timer.
205
- exoPlayer.pauseAtEndOfMediaItems = durationMs > 0 && requestedEndMs >= durationMs
264
+ exoPlayer.pauseAtEndOfMediaItems = bounds.endsAtTrackEnd
265
+ val engine = exoPlayer
206
266
  loopRangeMessage =
207
267
  exoPlayer
208
268
  .createMessage { _, _ ->
209
269
  // Delivery is on main: this seek stays native and does not depend on progress events.
210
- if (loopRange === range) {
270
+ // A delivery the old engine posted just before a rebuild must not seek the new one.
271
+ if (loopRange === range && exoPlayer === engine) {
211
272
  if (sleepTimer.onTrackEnd()) {
212
- exoPlayer.seekTo(endMs)
273
+ exoPlayer.seekTo(bounds.endMs)
274
+ loopEndPause = LoopEndPause.PinSeekSettling(targetMs = bounds.endMs)
213
275
  } else if (exoPlayer.playWhenReady || isLoopRangeHoldingTrackEnd) {
214
- exoPlayer.seekTo((range.start * 1000).toLong())
276
+ exoPlayer.seekTo(bounds.startMs)
215
277
  exoPlayer.playWhenReady = true
216
278
  armLoopRange()
217
279
  }
@@ -220,7 +282,7 @@ internal constructor(
220
282
  .setLooper(Looper.getMainLooper())
221
283
  .setPosition(
222
284
  exoPlayer.currentMediaItemIndex,
223
- if (durationMs > 0 && requestedEndMs >= durationMs) C.TIME_END_OF_SOURCE else endMs,
285
+ if (bounds.endsAtTrackEnd) C.TIME_END_OF_SOURCE else bounds.endMs,
224
286
  )
225
287
  .setDeleteAfterDelivery(true)
226
288
  .send()
@@ -472,6 +534,7 @@ internal constructor(
472
534
  // ExoPlayer's setPlayWhenReady(true) neither restarts an ended engine (media3 replays only on
473
535
  // its media-button path) nor loads an idle one. Here in the setter so every writer plays
474
536
  // alike: play(), togglePlayback(), JS, the session.
537
+ if (value) restartLoopRangeAfterSleep()
475
538
  if (value && sessionPlayer.playbackState == MediaPlayer.STATE_ENDED) {
476
539
  sessionPlayer.seekToDefaultPosition()
477
540
  }
@@ -705,6 +768,8 @@ internal constructor(
705
768
 
706
769
  if (!isInitialSetup) {
707
770
  forwardingPlayer.removeListener(playerListener)
771
+ cancelLoopRangeMessage()
772
+ endPinSeek()
708
773
  exoPlayer.release()
709
774
  Timber.Forest.d("Player cleanup completed")
710
775
  }
@@ -1320,6 +1385,7 @@ internal constructor(
1320
1385
  automaticBufferManager?.detach()
1321
1386
  automaticBufferManager = null
1322
1387
  remoteOutputs.release()
1388
+ cancelLoopRangeMessage()
1323
1389
  exoPlayer.release()
1324
1390
  cache?.release()
1325
1391
  cache = null
@@ -1681,3 +1747,23 @@ internal constructor(
1681
1747
  var lastQueueVersion = 0
1682
1748
  }
1683
1749
  }
1750
+
1751
+ /** A [LoopRange] on the engine's clock. */
1752
+ private class LoopBounds(val startMs: Long, val endMs: Long, val endsAtTrackEnd: Boolean)
1753
+
1754
+ /** Where the end-of-track sleep timer left a Loop Range. */
1755
+ private sealed interface LoopEndPause {
1756
+ data object None : LoopEndPause
1757
+
1758
+ /** Paused at the loop end: a play restarts the loop. */
1759
+ data object Paused : LoopEndPause
1760
+
1761
+ /**
1762
+ * Paused at the loop end, and the seek to [targetMs] that pins the position there (the pin seek)
1763
+ * has yet to settle.
1764
+ */
1765
+ data class PinSeekSettling(val targetMs: Long) : LoopEndPause
1766
+ }
1767
+
1768
+ /** Thrown where a Loop Range is set with no Active Track, by [Player] and by the bridge. */
1769
+ internal const val LOOP_RANGE_REQUIRES_ACTIVE_TRACK = "Loop Range requires an Active Track"
@@ -76,7 +76,10 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
76
76
  newPosition: MediaPlayer.PositionInfo,
77
77
  reason: Int,
78
78
  ) {
79
- if (reason == MediaPlayer.DISCONTINUITY_REASON_SEEK) player.armLoopRange()
79
+ if (reason == MediaPlayer.DISCONTINUITY_REASON_SEEK) {
80
+ player.onSeek(newPosition.positionMs)
81
+ player.armLoopRange()
82
+ }
80
83
  player.oldPosition = oldPosition.positionMs
81
84
  // A seek opens a new connection without passing through idle, clearing a failed one's error.
82
85
  val loop = player.retryLoop
@@ -212,13 +215,15 @@ class PlayerListener(private val player: Player) : MediaPlayer.Listener {
212
215
  val event =
213
216
  when (events[i]) {
214
217
  MediaPlayer.EVENT_PLAYBACK_STATE_CHANGED ->
218
+ if (player.consumePinSeekStateChange()) null
215
219
  // The session player's state, not the forwarding player's: InterceptingPlayer masks
216
220
  // IDLE as READY after a terminal error, which would clear our ERROR state here.
217
- PlaybackEvent.ExoPlaybackStateChanged(
218
- player.retryView(player.sessionPlayer.playbackState),
219
- media3Player.mediaItemCount,
220
- player.shouldPlayWhenReady,
221
- )
221
+ else
222
+ PlaybackEvent.ExoPlaybackStateChanged(
223
+ player.retryView(player.sessionPlayer.playbackState),
224
+ media3Player.mediaItemCount,
225
+ player.shouldPlayWhenReady,
226
+ )
222
227
  MediaPlayer.EVENT_MEDIA_ITEM_TRANSITION ->
223
228
  PlaybackEvent.MediaItemTransition(
224
229
  player.currentTrack != null,
@@ -84,6 +84,28 @@ class ChosenChannelModeTest {
84
84
  assertEquals(ChannelMode.RIGHT, chosen.get(player))
85
85
  }
86
86
 
87
+ @Test
88
+ fun `a reloaded runtime hears the mode of the player still playing`() {
89
+ val player = newPlayer()
90
+ player.channelMode = ChannelMode.LEFT
91
+
92
+ // The new runtime read stereo before the service connected.
93
+ assertEquals(ChannelMode.STEREO, chosen.get(null))
94
+ chosen.handTo(player)
95
+
96
+ assertEquals(ChannelMode.LEFT, chosen.get(player))
97
+ assertEquals(listOf(ChannelMode.LEFT), emitted)
98
+ }
99
+
100
+ @Test
101
+ fun `a player in stereo connects without an event`() {
102
+ val player = newPlayer()
103
+
104
+ chosen.handTo(player)
105
+
106
+ assertEquals(emptyList<ChannelMode>(), emitted)
107
+ }
108
+
87
109
  @Test
88
110
  fun `with a player, the player emits the change`() {
89
111
  val player = newPlayer()
@@ -0,0 +1,22 @@
1
+ package com.audiobrowser
2
+
3
+ import com.margelo.nitro.audiobrowser.LoopRange
4
+ import org.junit.Assert.assertEquals
5
+ import org.junit.Assert.assertThrows
6
+ import org.junit.Test
7
+
8
+ /**
9
+ * AudioBrowser.setLoopRange with no Player connected. AudioBrowser itself needs Nitro's native
10
+ * library, so the test drives the command it delegates to.
11
+ */
12
+ class LoopRangeCommandTest {
13
+ @Test
14
+ fun `setting a Loop Range with no player connected throws as iOS does`() {
15
+ val error =
16
+ assertThrows(IllegalArgumentException::class.java) {
17
+ setLoopRangeOn(null, LoopRange(1.0, 2.0))
18
+ }
19
+
20
+ assertEquals("Loop Range requires an Active Track", error.message)
21
+ }
22
+ }
@@ -308,6 +308,12 @@ class LoopRangeCaseTest {
308
308
  assertEquals(name + ": intent event", value.jsonPrimitive.boolean, reportedIntent)
309
309
  }
310
310
  "sleepChanges" -> assertEquals(name, value.jsonPrimitive.int, sleepChanges)
311
+ "state" ->
312
+ assertEquals(
313
+ name,
314
+ value.jsonPrimitive.content,
315
+ player.getPlayback().state.name.lowercase(),
316
+ )
311
317
  "sleepTimer" ->
312
318
  if (value is JsonNull) assertTrue(name, player.sleepTimer.get().isFirst)
313
319
  else if (value.jsonPrimitive.content == "time")
@@ -0,0 +1,170 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Looper
4
+ import androidx.media3.common.C
5
+ import androidx.media3.common.Player as MediaPlayer
6
+ import com.audiobrowser.TestFixtures
7
+ import com.audiobrowser.goOnline
8
+ import com.audiobrowser.model.PlayerSetupOptions
9
+ import com.audiobrowser.silentWavUri
10
+ import com.audiobrowser.util.TrackFactory
11
+ import com.margelo.nitro.audiobrowser.LoopRange
12
+ import java.time.Duration
13
+ import org.junit.After
14
+ import org.junit.Assert.assertEquals
15
+ import org.junit.Assert.assertNotSame
16
+ import org.junit.Assert.assertTrue
17
+ import org.junit.Assert.fail
18
+ import org.junit.Rule
19
+ import org.junit.Test
20
+ import org.junit.rules.TemporaryFolder
21
+ import org.junit.runner.RunWith
22
+ import org.robolectric.RobolectricTestRunner
23
+ import org.robolectric.RuntimeEnvironment
24
+ import org.robolectric.Shadows.shadowOf
25
+ import org.robolectric.annotation.Config
26
+ import org.robolectric.shadows.ShadowSystemClock
27
+
28
+ /**
29
+ * A Loop Range across an engine rebuild or destroy: a released engine's loop-back never seeks, and
30
+ * the range loops on the new one.
31
+ *
32
+ * Audio is disabled, so no renderer drives the engine: it wakes about once a second and a position
33
+ * moves in steps of a second. The ranges and waits here allow for that.
34
+ */
35
+ @RunWith(RobolectricTestRunner::class)
36
+ @Config(sdk = [28])
37
+ class LoopRangeEngineLifecycleTest {
38
+ @get:Rule val folder = TemporaryFolder()
39
+ private val application = RuntimeEnvironment.getApplication()
40
+ private val player = Player(application)
41
+
42
+ @After fun release() = player.destroy()
43
+
44
+ @Test
45
+ fun `a loop-back due as the engine is rebuilt does not seek the new engine`() {
46
+ playFrom(3_000, LoopRange(1.0, 3.5))
47
+ val engine = player.exoPlayer
48
+
49
+ // The old engine passes the Loop Range end and posts its loop-back to main...
50
+ runEngineOnly(seconds = 1.2)
51
+ // ...and the engine is rebuilt before main runs it.
52
+ rebuild()
53
+ assertNotSame(engine, player.exoPlayer)
54
+ val carried = player.exoPlayer.currentPosition
55
+ shadowOf(Looper.getMainLooper()).idle()
56
+
57
+ assertTrue(
58
+ "carried at ${carried}ms, then sought to ${player.exoPlayer.currentPosition}ms",
59
+ player.exoPlayer.currentPosition >= carried,
60
+ )
61
+ }
62
+
63
+ @Test
64
+ fun `a loop-back due as the engine is destroyed does not seek it`() {
65
+ // To the track end, so the loop-back seeks whatever the play intent: destroy() drops it.
66
+ playFrom(28_500, LoopRange(1.0, 30.0))
67
+ val engine = player.exoPlayer
68
+
69
+ // The engine reaches the track end and posts its loop-back to main...
70
+ runEngineOnly(seconds = 2.5)
71
+ // ...and the player is destroyed before main runs it.
72
+ player.destroy()
73
+ val stopped = engine.currentPosition
74
+ shadowOf(Looper.getMainLooper()).idle()
75
+
76
+ assertTrue(
77
+ "stopped at ${stopped}ms, then sought to ${engine.currentPosition}ms",
78
+ engine.currentPosition >= stopped,
79
+ )
80
+ }
81
+
82
+ @Test
83
+ fun `a Loop Range keeps looping on the rebuilt engine`() {
84
+ playFrom(1_000, LoopRange(1.0, 3.5))
85
+
86
+ rebuild()
87
+
88
+ var previous = player.exoPlayer.currentPosition
89
+ repeat(80) {
90
+ advance(0.1)
91
+ val position = player.exoPlayer.currentPosition
92
+ if (position < previous) {
93
+ assertEquals("looped to the start", 1.0, position / 1000.0, 1.0)
94
+ return
95
+ }
96
+ previous = position
97
+ }
98
+ fail("playback did not loop on the rebuilt engine, at ${previous}ms")
99
+ }
100
+
101
+ private fun playFrom(positionMs: Long, range: LoopRange) {
102
+ player.setup(PlayerSetupOptions())
103
+ disableAudio()
104
+ goOnline(application)
105
+ player.exoPlayer.setMediaItems(
106
+ listOf(
107
+ TrackFactory.toMedia3(TestFixtures.track(src = folder.silentWavUri(Duration.ofSeconds(30))))
108
+ )
109
+ )
110
+ player.exoPlayer.prepare()
111
+ until("ready") { player.exoPlayer.playbackState == MediaPlayer.STATE_READY }
112
+ player.setLoopRange(range)
113
+ player.exoPlayer.seekTo(positionMs)
114
+ settle()
115
+ player.play()
116
+ until("playing") { player.exoPlayer.isPlaying }
117
+ }
118
+
119
+ /**
120
+ * Rebuilds the engine, as a setup with changed engine options does. The new engine starts with
121
+ * audio enabled, and Robolectric's AudioTrack kills a playback thread that renders audio, so
122
+ * audio goes off again before that thread runs.
123
+ */
124
+ private fun rebuild() {
125
+ player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
126
+ disableAudio()
127
+ }
128
+
129
+ private fun disableAudio() {
130
+ player.exoPlayer.trackSelectionParameters =
131
+ player.exoPlayer.trackSelectionParameters
132
+ .buildUpon()
133
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
134
+ .build()
135
+ }
136
+
137
+ /** Plays on the engine's own thread while main stands still. */
138
+ private fun runEngineOnly(seconds: Double) {
139
+ repeat((seconds * 100).toInt()) {
140
+ ShadowSystemClock.advanceBy(Duration.ofMillis(10))
141
+ shadowOf(player.exoPlayer.playbackLooper).idle()
142
+ Thread.sleep(10)
143
+ }
144
+ }
145
+
146
+ private fun advance(seconds: Double) {
147
+ repeat((seconds * 100).toInt()) {
148
+ ShadowSystemClock.advanceBy(Duration.ofMillis(10))
149
+ shadowOf(player.exoPlayer.playbackLooper).idle()
150
+ Thread.sleep(10)
151
+ shadowOf(Looper.getMainLooper()).idle()
152
+ }
153
+ settle()
154
+ }
155
+
156
+ private fun settle() {
157
+ repeat(5) {
158
+ Thread.sleep(10)
159
+ shadowOf(Looper.getMainLooper()).idle()
160
+ }
161
+ }
162
+
163
+ private fun until(what: String, condition: () -> Boolean) {
164
+ val deadline = System.nanoTime() + 10_000_000_000
165
+ while (!condition()) {
166
+ if (System.nanoTime() > deadline) fail("timed out waiting for $what")
167
+ advance(0.01)
168
+ }
169
+ }
170
+ }
@@ -0,0 +1,158 @@
1
+ package com.audiobrowser.player
2
+
3
+ import android.os.Looper
4
+ import androidx.media3.common.C
5
+ import androidx.media3.common.Player as MediaPlayer
6
+ import com.audiobrowser.Callbacks
7
+ import com.audiobrowser.TestFixtures
8
+ import com.audiobrowser.goOnline
9
+ import com.audiobrowser.model.PlayerSetupOptions
10
+ import com.audiobrowser.silentWavUri
11
+ import com.margelo.nitro.audiobrowser.LoopRange
12
+ import com.margelo.nitro.audiobrowser.Playback
13
+ import com.margelo.nitro.audiobrowser.PlaybackState
14
+ import java.lang.reflect.Proxy
15
+ import java.time.Duration
16
+ import java.util.concurrent.TimeUnit
17
+ import org.junit.After
18
+ import org.junit.Assert.assertEquals
19
+ import org.junit.Assert.assertTrue
20
+ import org.junit.Assert.fail
21
+ import org.junit.Rule
22
+ import org.junit.Test
23
+ import org.junit.rules.TemporaryFolder
24
+ import org.junit.runner.RunWith
25
+ import org.robolectric.RobolectricTestRunner
26
+ import org.robolectric.RuntimeEnvironment
27
+ import org.robolectric.Shadows.shadowOf
28
+ import org.robolectric.annotation.Config
29
+ import org.robolectric.shadows.ShadowSystemClock
30
+
31
+ /**
32
+ * The pin seek: the end-of-track sleep timer pauses at an interior Loop Range end and seeks there,
33
+ * and the state changes of that one seek are dropped so the pause holds PAUSED. A state change that
34
+ * is not the pin seek's still reaches listeners, during the pin seek and after it.
35
+ *
36
+ * Audio is disabled, so no renderer drives the engine: it wakes about once a second and a position
37
+ * moves in steps of a second. The ranges and waits here allow for that.
38
+ */
39
+ @RunWith(RobolectricTestRunner::class)
40
+ @Config(sdk = [28])
41
+ class LoopRangePinSeekTest {
42
+ @get:Rule val folder = TemporaryFolder()
43
+ private val application = RuntimeEnvironment.getApplication()
44
+ private val player = Player(application)
45
+ private val states = mutableListOf<PlaybackState>()
46
+
47
+ @After fun release() = player.destroy()
48
+
49
+ @Test
50
+ fun `the pin seek holds the sleep timer pause as paused`() {
51
+ pauseAtLoopEnd()
52
+ advance(1.5)
53
+
54
+ assertEquals(PlaybackState.PAUSED, player.getPlayback().state)
55
+ assertTrue("reported $states", PlaybackState.READY !in states)
56
+ }
57
+
58
+ @Test
59
+ fun `a seek after the pin seek reports its own load`() {
60
+ pauseAtLoopEnd()
61
+ advance(1.5)
62
+ states.clear()
63
+
64
+ player.seekTo(10, TimeUnit.SECONDS)
65
+ until("ready") { player.getPlayback().state == PlaybackState.READY }
66
+
67
+ assertTrue("reported $states", PlaybackState.BUFFERING in states)
68
+ }
69
+
70
+ @Test
71
+ fun `a seek during the pin seek reports its own load`() {
72
+ pauseAtLoopEnd()
73
+ states.clear()
74
+
75
+ player.seekTo(10, TimeUnit.SECONDS)
76
+ until("ready") { player.getPlayback().state == PlaybackState.READY }
77
+ }
78
+
79
+ @Test
80
+ fun `a skip during the pin seek reports the new track's load`() {
81
+ pauseAtLoopEnd()
82
+ states.clear()
83
+
84
+ player.next()
85
+ until("ready") { player.getPlayback().state == PlaybackState.READY }
86
+
87
+ assertEquals("b", player.currentTrack?.id)
88
+ assertTrue("reported $states", PlaybackState.LOADING in states)
89
+ }
90
+
91
+ /**
92
+ * Plays a range from 1 to 3.5 seconds with the end-of-track sleep timer set, and stops with the
93
+ * sleep timer's pause and the pin seek just run on main: the engine has yet to act on the seek.
94
+ */
95
+ private fun pauseAtLoopEnd() {
96
+ player.setup(PlayerSetupOptions())
97
+ player.exoPlayer.trackSelectionParameters =
98
+ player.exoPlayer.trackSelectionParameters
99
+ .buildUpon()
100
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
101
+ .build()
102
+ goOnline(application)
103
+ val src = folder.silentWavUri(Duration.ofSeconds(30))
104
+ player.setQueue(
105
+ arrayOf(TestFixtures.track(id = "a", src = src), TestFixtures.track(id = "b", src = src))
106
+ )
107
+ until("ready") { player.exoPlayer.playbackState == MediaPlayer.STATE_READY }
108
+ player.setLoopRange(LoopRange(1.0, 3.5))
109
+ player.exoPlayer.seekTo(3_000)
110
+ settle()
111
+ player.sleepTimer.setEndOfTrack()
112
+ player.callbacks =
113
+ Proxy.newProxyInstance(Callbacks::class.java.classLoader, arrayOf(Callbacks::class.java)) {
114
+ _,
115
+ method,
116
+ args ->
117
+ if (method.name == "onPlaybackChanged") states += (args!![0] as Playback).state
118
+ if (method.returnType == Boolean::class.javaPrimitiveType) false else null
119
+ } as Callbacks
120
+ player.play()
121
+ until("playing") { player.exoPlayer.isPlaying }
122
+
123
+ // The engine passes the loop end and posts the sleep timer's stop to main...
124
+ repeat(120) {
125
+ ShadowSystemClock.advanceBy(Duration.ofMillis(10))
126
+ shadowOf(player.exoPlayer.playbackLooper).idle()
127
+ Thread.sleep(10)
128
+ }
129
+ // ...which pauses and pins the position at the loop end.
130
+ shadowOf(Looper.getMainLooper()).idle()
131
+ assertEquals(false, player.playWhenReady)
132
+ }
133
+
134
+ private fun advance(seconds: Double) {
135
+ repeat((seconds * 100).toInt()) {
136
+ ShadowSystemClock.advanceBy(Duration.ofMillis(10))
137
+ shadowOf(player.exoPlayer.playbackLooper).idle()
138
+ Thread.sleep(10)
139
+ shadowOf(Looper.getMainLooper()).idle()
140
+ }
141
+ settle()
142
+ }
143
+
144
+ private fun settle() {
145
+ repeat(5) {
146
+ Thread.sleep(10)
147
+ shadowOf(Looper.getMainLooper()).idle()
148
+ }
149
+ }
150
+
151
+ private fun until(what: String, condition: () -> Boolean) {
152
+ val deadline = System.nanoTime() + 10_000_000_000
153
+ while (!condition()) {
154
+ if (System.nanoTime() > deadline) fail("timed out waiting for $what (reported $states)")
155
+ advance(0.01)
156
+ }
157
+ }
158
+ }
@@ -52,6 +52,26 @@ class PlayerTrackChangeTest {
52
52
  assertEquals(listOf<TimedMetadata?>(null), seenAtTrackChange)
53
53
  }
54
54
 
55
+ /** Web announces the same flow; see the parity cases in src/web/__tests__/lifecycle.test.ts. */
56
+ @Test
57
+ fun `skipping between queue entries holding the same Track announces the change`() {
58
+ val track = TestFixtures.track(src = "https://s/a.mp3")
59
+ player.setup(PlayerSetupOptions())
60
+ player.setQueue(arrayOf(track, track))
61
+ idle()
62
+ var announced = 0
63
+ player.callbacks =
64
+ mock(Callbacks::class.java) { invocation ->
65
+ if (invocation.method.name == "onPlaybackActiveTrackChanged") announced++
66
+ Answers.RETURNS_DEFAULTS.answer(invocation)
67
+ }
68
+
69
+ player.skipTo(1)
70
+ idle()
71
+
72
+ assertEquals(1, announced)
73
+ }
74
+
55
75
  private fun icy(title: String) =
56
76
  Metadata(IcyInfo("StreamTitle='$title';".toByteArray(), title, null))
57
77