react-native-audio-browser 0.2.0-next.82 → 0.2.0-next.83

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.
@@ -49,4 +49,8 @@ extension PlaybackState {
49
49
  var carriesAdvisoryError: Bool {
50
50
  self == .loading || self == .buffering || self == .paused
51
51
  }
52
+
53
+ var awaitsData: Bool {
54
+ self == .loading || self == .buffering
55
+ }
52
56
  }
@@ -192,8 +192,9 @@ final class Player {
192
192
  if !newValue { engine.pause() } else if state != .loading { engine.play() }
193
193
 
194
194
  guard changed else { return }
195
- // A resume can find the state still .buffering (a pause near the end leaves it), with no watch.
196
- if newValue, state == .buffering { retry.startStallWatch() }
195
+ // A resume can find the state still .buffering (a pause near the end leaves it) or .loading,
196
+ // with no transition to start the watch.
197
+ if newValue, state.awaitsData { retry.startStallWatch() }
197
198
  // Left to run, the retry would give up on the dropped intent and surface .error.
198
199
  if !newValue, retry.pendingTask != nil { parkForReloadOnPlay() }
199
200
  // A pause during the sleep fade ends the timer early, restoring the pre-fade volume.
@@ -262,7 +263,11 @@ final class Player {
262
263
  retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
263
264
  retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
264
265
  retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
265
- retry.bufferedPosition = { [weak self] in self?.engine.bufferedPosition ?? 0 }
266
+ // Until the connect's item is prepared, the engine still holds the item it replaces.
267
+ retry.bufferedPosition = { [weak self] in
268
+ guard let self, connectionItemPrepared else { return 0 }
269
+ return engine.bufferedPosition
270
+ }
266
271
  }
267
272
 
268
273
  /// Shows a failure the retry loop is still working on over the current state: not a
@@ -353,9 +358,10 @@ final class Player {
353
358
  } else if old == .playing {
354
359
  retry.playbackStoppedBeingAudible()
355
360
  }
361
+ // A reload within .loading is no transition: the retry loop watches each connect itself.
356
362
  if new == .buffering, playWhenReady {
357
363
  retry.startStallWatch()
358
- } else if old == .buffering {
364
+ } else if old.awaitsData, !new.awaitsData {
359
365
  retry.stopStallWatch()
360
366
  }
361
367
 
@@ -396,13 +402,14 @@ final class Player {
396
402
 
397
403
  func stop() {
398
404
  // A pending retry would turn the stop into .error, and the next play must start over rather
399
- // than resume where it failed.
405
+ // than resume where it failed. Cancelled first, or the lowered intent parks it for a reload.
400
406
  retry.cancel()
401
407
  load?.reloadOnPlay = false
402
408
  shouldResumeAfterInterruption = false
403
409
  engine.clearTimedMetadata()
404
- transition(.stopped)
410
+ // Before the transition, whose render the formatter reads the intent from.
405
411
  setPlayWhenReady(false)
412
+ transition(.stopped)
406
413
  deferredSeek.reset()
407
414
  if currentTrack?.live != true { seek(to: 0) }
408
415
  }
@@ -633,8 +640,7 @@ final class Player {
633
640
  persistence.save()
634
641
 
635
642
  if let src = currentTrack.src {
636
- retry.connectionStarted()
637
- engine.resolveAndLoad(src: src, track: currentTrack)
643
+ connect(src: src, track: currentTrack)
638
644
  } else {
639
645
  logger.error("No src for track \(currentTrack.path ?? currentTrack.title)")
640
646
  engine.clearItem()
@@ -738,6 +744,13 @@ final class Player {
738
744
  return
739
745
  }
740
746
  prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
747
+ connect(src: src, track: track)
748
+ }
749
+
750
+ private var connectionItemPrepared = false
751
+
752
+ private func connect(src: String, track: Track) {
753
+ connectionItemPrepared = false
741
754
  retry.connectionStarted()
742
755
  engine.resolveAndLoad(src: src, track: track)
743
756
  }
@@ -805,6 +818,7 @@ final class Player {
805
818
  switch event {
806
819
  case let .itemPrepared(likelyToKeepUp):
807
820
  load?.itemPrepared = true
821
+ connectionItemPrepared = true
808
822
  if playWhenReady { engine.play() }
809
823
  if !beginDeferredSeek(), likelyToKeepUp { bufferBecameSufficient() }
810
824
  case let .loadFailed(error):
@@ -832,7 +846,7 @@ final class Player {
832
846
  case .playedToEnd:
833
847
  itemDidPlayToEnd()
834
848
  case .stalled:
835
- // A nudge only: this also arrives while audio plays, so the stall watch keys on .buffering.
849
+ // A nudge only: this also arrives while audio plays, so the stall watch keys on the state.
836
850
  if playWhenReady, state != .error { engine.play() }
837
851
  case let .timedMetadata(metadata):
838
852
  callbacks?.playerDidReceiveTimedMetadata(metadata)
@@ -84,10 +84,11 @@ final class RetryLoop {
84
84
  /// The retry in flight; session release waits while there is one.
85
85
  private(set) var pendingTask: Task<Void, Never>?
86
86
 
87
- /// How long a stall may go without new data before it counts as a failure; longer than AVPlayer
88
- /// takes to fail a stalled item itself, so its error, which says more, is the one usually retried.
87
+ /// How long a connect or a stall may go without new data before it counts as a failure. Longer
88
+ /// than AVPlayer takes to fail a stalled item itself, so its error, which says more, is usually
89
+ /// the one retried; a connect's request can outlast it.
89
90
  var stallTimeout: Duration = .seconds(30)
90
- /// The end of the loaded range; the stall watch reads progress off it.
91
+ /// The end of the current connection's loaded range; the stall watch reads progress off it.
91
92
  var bufferedPosition: () -> Double = { 0 }
92
93
  private(set) var stallTask: Task<Void, Never>?
93
94
 
@@ -145,7 +146,8 @@ final class RetryLoop {
145
146
 
146
147
  /// A connect going out: the Load's first, a reconnect, or a reload by the Player, which ends the
147
148
  /// connection it replaces. A replaced connection counts only if it delivered audio: one cut off
148
- /// while connecting says nothing about the source.
149
+ /// while connecting says nothing about the source. With the play intent up, the stall watch runs
150
+ /// from the start, so a connect that opens and sends nothing is replaced (docs/adr/0014, rule 9).
149
151
  func connectionStarted() {
150
152
  let now = clock.nowMs
151
153
  if let startedAtMs = connectionStartedAtMs, replacedConnectionCounts, connectionDeliveredAudio, !connectionEndReported {
@@ -157,6 +159,7 @@ final class RetryLoop {
157
159
  connectionEndReported = false
158
160
  deadlineArmed = true
159
161
  armDeadline()
162
+ if playIntent { startStallWatch() }
160
163
  }
161
164
 
162
165
  func playIntentChanged(_ up: Bool) {
@@ -181,6 +184,7 @@ final class RetryLoop {
181
184
  /// Audio clears the failure the deadline would report: a silence after it that ends with no
182
185
  /// failure is a stall.
183
186
  func playbackBecameAudible() {
187
+ stopStallWatch()
184
188
  connectionDeliveredAudio = true
185
189
  lastFailure = nil
186
190
  budget.audioStarted(atMs: clock.nowMs)
@@ -304,14 +308,14 @@ final class RetryLoop {
304
308
 
305
309
  // MARK: - Stalls
306
310
 
307
- /// Starts the stall watch: a `stallTimeout` in which `bufferedPosition` does not advance makes
308
- /// the stall a `.stall` failure, provided the play intent holds and no retry is pending; one in
309
- /// which it advances starts another. Any failure ends it.
311
+ /// Starts the stall watch, over a connect or a stall: a `stallTimeout` in which `bufferedPosition`
312
+ /// does not advance makes it a `.stall` failure, provided the play intent holds and no retry is
313
+ /// pending; one in which it advances starts another. Any failure ends it.
310
314
  func startStallWatch() {
311
315
  stallTask?.cancel()
312
316
  let buffered = bufferedPosition()
313
- stallTask = Task { [weak self, stallTimeout] in
314
- try? await Task.sleep(for: stallTimeout)
317
+ stallTask = Task { [weak self, clock, stallTimeout] in
318
+ guard await (try? clock.sleep(ms: Int(stallTimeout / .milliseconds(1)))) != nil else { return }
315
319
  guard let self, !Task.isCancelled else { return }
316
320
  stallTask = nil
317
321
  if bufferedPosition() > buffered { return startStallWatch() }
@@ -62,6 +62,23 @@ private func makeVirtual(online: Bool = true) throws -> (Player, MockPlayerEngin
62
62
  return (player, engine, callbacks, clock)
63
63
  }
64
64
 
65
+ /// A live stream connecting, its retry loop on a virtual clock; the engine reports `previousBuffered`
66
+ /// from the item the connect replaces until the test prepares one.
67
+ @MainActor
68
+ private func makeConnecting(
69
+ playWhenReady: Bool = true,
70
+ previousBuffered: Double = 0,
71
+ ) throws -> (Player, MockPlayerEngine, VirtualClock) {
72
+ let clock = VirtualClock()
73
+ let retry = RetryLoop(clock: clock)
74
+ retry.updatePolicy(from: .first(true))
75
+ let engine = MockPlayerEngine()
76
+ engine.bufferedPosition = previousBuffered
77
+ let player = makePlayer(engine: engine, retry: retry)
78
+ try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T", live: true)], playWhenReady: playWhenReady)
79
+ return (player, engine, clock)
80
+ }
81
+
65
82
  @Suite("Player - seeking")
66
83
  @MainActor
67
84
  struct PlayerSeekingTests {
@@ -476,8 +493,91 @@ struct PlayerRecoveringTests {
476
493
 
477
494
  @Test func aTrackChangeEndsTheStallWatch() throws {
478
495
  let (player, _, _) = try makeStalling()
496
+ let stallWatch = player.retry.stallTask
479
497
  try player.setQueue([Track(id: "t2", src: "https://example.com/b.mp3", title: "B")])
480
- #expect(player.retry.stallTask == nil)
498
+ #expect(stallWatch?.isCancelled == true)
499
+ }
500
+
501
+ @Test func aConnectThatSendsNothingIsReplacedAfterTheTimeout() async throws {
502
+ let (player, engine, clock) = try makeConnecting()
503
+ await clock.run(until: 30_999)
504
+ #expect(engine.resolveAndLoadCalls.count == 1)
505
+ await clock.run(until: 31_000)
506
+ #expect(engine.resolveAndLoadCalls.count == 2)
507
+ #expect(player.state == .loading)
508
+ }
509
+
510
+ /// The item it replaces had buffered further than the new one has yet.
511
+ @Test func aSlowConnectThatKeepsReceivingDataIsKept() async throws {
512
+ let (player, engine, clock) = try makeConnecting(previousBuffered: 50)
513
+ engine.hasItem = true
514
+ engine.bufferedPosition = 1
515
+ engine.emit(.itemPrepared(likelyToKeepUp: false))
516
+ for atMs in stride(from: 20_000, through: 100_000, by: 20_000) {
517
+ clock.at(atMs) { engine.bufferedPosition += 1 }
518
+ }
519
+ await clock.run(until: 100_000)
520
+ #expect(player.state == .loading)
521
+ #expect(engine.resolveAndLoadCalls.count == 1)
522
+ }
523
+
524
+ /// A stall's reconnect: the stalled item stays in the engine, still buffering, while the new
525
+ /// connect sends nothing.
526
+ @Test func theItemAConnectReplacesBufferingOnIsNoProgress() async throws {
527
+ let (player, engine, _, clock) = try makeVirtual()
528
+ engine.bufferedPosition = 50
529
+ player.transition(.avPlayerPlaying)
530
+ await clock.run(until: 10_000)
531
+ player.transition(.avPlayerWaiting)
532
+ await clock.run(until: 40_000)
533
+ #expect(engine.resolveAndLoadCalls.count == 2)
534
+
535
+ for atMs in stride(from: 45_000, through: 70_000, by: 5_000) {
536
+ clock.at(atMs) { engine.bufferedPosition += 1 }
537
+ }
538
+ await clock.run(until: 70_000)
539
+ await clock.run(until: 71_000)
540
+ #expect(engine.resolveAndLoadCalls.count == 3)
541
+ }
542
+
543
+ @Test func aPauseDuringAConnectHoldsItPastTheTimeout() async throws {
544
+ let (player, engine, clock) = try makeConnecting()
545
+ await clock.run(until: 10_000)
546
+ player.pause()
547
+ await clock.run(until: 200_000)
548
+ #expect(engine.resolveAndLoadCalls.count == 1)
549
+ #expect(player.load?.reloadOnPlay == false)
550
+ #expect(player.state == .loading)
551
+ }
552
+
553
+ @Test func withRetryOffASilentConnectIsTerminalAtTheTimeout() async throws {
554
+ let (player, engine, clock) = try makeConnecting()
555
+ player.retry.updatePolicy(from: nil)
556
+ await clock.run(until: 29_999)
557
+ #expect(player.state == .loading)
558
+ await clock.run(until: 30_000)
559
+ #expect(player.state == .error)
560
+ #expect(player.errorStatus.error == .playbackStalled)
561
+ #expect(engine.resolveAndLoadCalls.count == 1)
562
+ }
563
+
564
+ @Test func aPlayWhileConnectingWatchesTheConnect() async throws {
565
+ let (player, engine, clock) = try makeConnecting(playWhenReady: false)
566
+ await clock.run(until: 10_000)
567
+ player.play()
568
+ await clock.run(until: 41_000)
569
+ #expect(engine.resolveAndLoadCalls.count == 2)
570
+ }
571
+
572
+ /// Ready and waiting for AVPlayer to start: its waiting is a stall, watched in .buffering.
573
+ @Test func aConnectThatIsReadyIsNoLongerWatched() async throws {
574
+ let (player, engine, clock) = try makeConnecting()
575
+ engine.hasItem = true
576
+ engine.hasLoadedAsset = true
577
+ engine.emit(.itemPrepared(likelyToKeepUp: true))
578
+ #expect(player.state == .ready)
579
+ await clock.run(until: 100_000)
580
+ #expect(engine.resolveAndLoadCalls.count == 1)
481
581
  }
482
582
 
483
583
  /// A link slower than the bitrate rebuffers for longer than the timeout, and a reload would
@@ -550,11 +650,15 @@ struct PlayerRecoveringTests {
550
650
  let callbacks = MockPlayerCallbacks()
551
651
  player.callbacks = callbacks
552
652
  try player.setQueue([Track(id: "t1", src: "https://example.com/a.mp3", title: "T")], playWhenReady: true)
653
+ // The watch replaces the silent connect at 30 s, 1 s after it gives up on it; that failure
654
+ // brings the deadline to 42 s.
655
+ await clock.run(until: 31_000)
656
+ #expect(engine.resolveAndLoadCalls.count == 2)
553
657
  let cancels = engine.cancelLoadingCount, stops = engine.stopObservingItemCount
554
658
 
555
- await clock.run(until: 119_999)
659
+ await clock.run(until: 41_999)
556
660
  #expect(player.state == .loading)
557
- await clock.run(until: 120_000)
661
+ await clock.run(until: 42_000)
558
662
 
559
663
  #expect(player.state == .error)
560
664
  #expect(player.errorStatus.error == .playbackStalled)
@@ -598,14 +702,17 @@ struct PlayerRecoveringTests {
598
702
  #expect(engine.resolveAndLoadCalls.count == 2)
599
703
  }
600
704
 
705
+ /// The watch replaces the stall at 40 s at once, having played, then each silent connect 30 s
706
+ /// after it starts, 1 s and then 1.5 s later: the deadline still falls 120 s into the silence.
601
707
  @Test func playbackThatStopsWithNoFailureEndsAtTheDeadline() async throws {
602
- let (player, _, callbacks, clock) = try makeVirtual()
708
+ let (player, engine, callbacks, clock) = try makeVirtual()
603
709
  player.transition(.avPlayerPlaying)
604
710
  await clock.run(until: 10_000)
605
711
  player.transition(.avPlayerWaiting)
606
712
 
607
713
  await clock.run(until: 129_999)
608
- #expect(player.state == .buffering)
714
+ #expect(player.state == .loading)
715
+ #expect(engine.resolveAndLoadCalls.count == 4)
609
716
  await clock.run(until: 130_000)
610
717
  #expect(player.state == .error)
611
718
  #expect(player.errorStatus.error == .playbackStalled)
@@ -614,6 +721,8 @@ struct PlayerRecoveringTests {
614
721
 
615
722
  @Test func aRetryNowKeepsTheSilenceDeadline() async throws {
616
723
  let (player, _, _, clock) = try makeVirtual()
724
+ // Its watch would end the reload's connect first.
725
+ player.retry.stallTimeout = .seconds(600)
617
726
  await clock.run(until: 60_000)
618
727
  player.retryNow()
619
728
 
@@ -1402,6 +1402,22 @@ struct StopCancelsRetryTests {
1402
1402
  #expect(player.state == .stopped)
1403
1403
  #expect(callbacks.errorEvents.isEmpty)
1404
1404
  }
1405
+
1406
+ /// Guards where stop() cancels the retry, not the order of its render: lowering the intent with
1407
+ /// a retry pending would park it for a reload on play, and a stop is no pause.
1408
+ @Test @MainActor
1409
+ func stop_duringARetry_goesStraightToStopped() throws {
1410
+ let (c, eh, cb, _) = makeCoordinator()
1411
+ try startPlaying(c, eh)
1412
+ eh.emit(.failed(URLError(.timedOut), httpStatusCode: nil))
1413
+ #expect(c.retry.pendingTask != nil)
1414
+ cb.playbackChanges.removeAll()
1415
+
1416
+ c.stop()
1417
+
1418
+ #expect(cb.playbackChanges.map(\.state) == [.stopped])
1419
+ #expect(c.load?.reloadOnPlay == false)
1420
+ }
1405
1421
  }
1406
1422
 
1407
1423
  // MARK: - Audio session release (#60)
@@ -1563,6 +1579,22 @@ struct MediaStackEffectTests {
1563
1579
  #expect(try cleared < #require(cb.publishOrder.firstIndex(of: "renderNowPlaying")))
1564
1580
  }
1565
1581
 
1582
+ @Test @MainActor
1583
+ func stop_rendersTheStoppedStateWithThePlayIntentDown() throws {
1584
+ let (c, eh, _, _) = makeCoordinator()
1585
+ try startPlaying(c, eh)
1586
+ var renders: [(PlaybackState, Bool)] = []
1587
+ eh.onSeamCall = { [unowned c] in
1588
+ if $0 == "renderNowPlaying" { renders.append((c.state, c.playWhenReady)) }
1589
+ }
1590
+
1591
+ c.stop()
1592
+
1593
+ let stopped = renders.filter { $0.0 == .stopped }
1594
+ #expect(!stopped.isEmpty)
1595
+ #expect(stopped.allSatisfy { !$0.1 })
1596
+ }
1597
+
1566
1598
  @Test @MainActor
1567
1599
  func pause_keepsTheStreamTitle() throws {
1568
1600
  let (c, eh, cb) = makeTraced()
@@ -116,13 +116,15 @@ struct RetryLoopCaseTests {
116
116
  #expect(rig.connects.allSatisfy { $0 < endedAt })
117
117
  }
118
118
 
119
- @Test func aConnectionOpenWithNoDataEndsAt120s() async {
119
+ /// The watch gives the silent connect up at 30 s, a failure that starts the first-connect
120
+ /// budget; having delivered nothing, it is replaced 1 s later.
121
+ @Test func aConnectionOpenWithNoDataIsReplacedAt30s_andEndsAt42s() async {
120
122
  let rig = Rig()
121
123
  rig.play { _ in }
122
124
  await rig.run(untilMs: 300_000)
123
- #expect(rig.errors.map(\.atMs) == [120_000])
125
+ #expect(rig.connects == [0, 31_000])
126
+ #expect(rig.errors.map(\.atMs) == [42_000])
124
127
  #expect(rig.errors.map(\.error) == [.playbackStalled])
125
- #expect(rig.connects == [0])
126
128
  }
127
129
 
128
130
  @Test func aDeadAddressThatNeverPlayedEnds12sAfterItsFirstFailure() async {
@@ -204,7 +206,8 @@ struct RetryLoopCaseTests {
204
206
  @Test func aPauseClearsTheDeadline() async {
205
207
  let rig = Rig()
206
208
  rig.play { _ in }
207
- rig.clock.at(60_000) { rig.loop.playIntentChanged(false) }
209
+ // Before the watch gives the connect up at 30 s.
210
+ rig.clock.at(20_000) { rig.loop.playIntentChanged(false) }
208
211
  await rig.run(untilMs: 300_000)
209
212
  #expect(rig.errors.isEmpty)
210
213
  }
@@ -212,7 +215,7 @@ struct RetryLoopCaseTests {
212
215
  @Test func aCancelClearsTheDeadline_untilTheNextConnect() async {
213
216
  let rig = Rig()
214
217
  rig.play { _ in }
215
- rig.clock.at(60_000) { rig.loop.cancel() }
218
+ rig.clock.at(20_000) { rig.loop.cancel() }
216
219
  await rig.run(untilMs: 300_000)
217
220
  #expect(rig.errors.isEmpty)
218
221
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.82",
3
+ "version": "0.2.0-next.83",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",