react-native-audio-browser 0.2.0-next.92 → 0.2.0-next.94

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.
@@ -21,6 +21,7 @@ final class Player {
21
21
  let retry: RetryLoop
22
22
  let sleepTimerManager: SleepTimerManager
23
23
  var deferredSeek = DeferredSeek()
24
+ private let scheduler: any SleepTimerScheduling
24
25
 
25
26
  private lazy var progressTimer = PlaybackTimer(
26
27
  isActive: { $0 == .loading || $0 == .buffering || $0 == .playing },
@@ -53,7 +54,7 @@ final class Player {
53
54
  var primedNowPlaying = false
54
55
  /// One of this load's items is in the engine; until then it reports the previous one's position.
55
56
  var itemPrepared = false
56
- /// A pause cancelled this load's retry, leaving the failed item for the next play to replace.
57
+ /// A pause parked this load, cancelling its retry or dropping a live item: the next play reloads.
57
58
  var reloadOnPlay = false
58
59
 
59
60
  mutating func claimNowPlayingPrime() -> Bool {
@@ -69,6 +70,7 @@ final class Player {
69
70
  /// Starts a Load: a track becoming current, or a restart of this one from a terminal error.
70
71
  /// Fresh retry budgets, no pending seek, unproven playback.
71
72
  private func beginLoad() {
73
+ cancelIdleLivePark()
72
74
  loadCount &+= 1
73
75
  load = Load(id: loadCount)
74
76
  retry.loadStarted()
@@ -106,8 +108,8 @@ final class Player {
106
108
  }
107
109
  }
108
110
 
109
- /// Whether the engine's item is not this Load's playable one: one loads, or a pause cancelled
110
- /// the retry that was to replace a failed one. A seek waits for the next item meanwhile.
111
+ /// Whether the engine's item is not this Load's playable one: one loads, or a pause parked the
112
+ /// load. A seek waits for the next item meanwhile.
111
113
  private var awaitingItem: Bool {
112
114
  state == .loading || load?.reloadOnPlay == true
113
115
  }
@@ -190,6 +192,10 @@ final class Player {
190
192
  }
191
193
  // While loading, the engine may still hold the previous track's item: a play waits for the new one.
192
194
  if !newValue { engine.pause() } else if state != .loading { engine.play() }
195
+ if changed, !newValue { parkIdleLiveStream() }
196
+ if changed, currentTrack?.live == true, liveItemPausable {
197
+ engine.capForwardBuffer(newValue ? nil : Self.pausedLiveBufferSeconds)
198
+ }
193
199
 
194
200
  guard changed else { return }
195
201
  // A resume can find the state still .buffering (a pause near the end leaves it) or .loading,
@@ -238,6 +244,7 @@ final class Player {
238
244
  self.engine = engine
239
245
  self.callbacks = callbacks
240
246
  self.retry = retry
247
+ self.scheduler = sleepTimerScheduler
241
248
  sleepTimerManager = SleepTimerManager(
242
249
  fader: VolumeFader(
243
250
  getVolume: { [weak engine] in engine?.volume ?? 1 },
@@ -262,7 +269,7 @@ final class Player {
262
269
  }
263
270
  retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
264
271
  retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
265
- retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
272
+ retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0, shortStartBuffer: true) }
266
273
  // Until the connect's item is prepared, the engine still holds the item it replaces.
267
274
  retry.bufferedPosition = { [weak self] in
268
275
  guard let self, connectionItemPrepared else { return 0 }
@@ -404,12 +411,18 @@ final class Player {
404
411
  // A pending retry would turn the stop into .error, and the next play must start over rather
405
412
  // than resume where it failed. Cancelled first, or the lowered intent parks it for a reload.
406
413
  retry.cancel()
407
- load?.reloadOnPlay = false
408
414
  shouldResumeAfterInterruption = false
409
415
  engine.clearTimedMetadata()
416
+ // Closed here, as dropping the intent would close it on the way to .stopped through .paused.
417
+ // A stop during a deferred park leaves the previous track's item in the engine: closed too.
418
+ if holdsLiveConnection || pendingIdleLivePark != nil {
419
+ cancelIdleLivePark()
420
+ closeLiveConnection()
421
+ }
410
422
  // Before the transition, whose render the formatter reads the intent from.
411
423
  setPlayWhenReady(false)
412
424
  transition(.stopped)
425
+ load?.reloadOnPlay = false
413
426
  deferredSeek.reset()
414
427
  if currentTrack?.live != true { seek(to: 0) }
415
428
  }
@@ -465,10 +478,19 @@ final class Player {
465
478
  /// Applies `false` before `action` and `true` after it; nil leaves the intent alone.
466
479
  private func handlePlayWhenReady(_ playWhenReady: Bool?, action: () throws -> Void) rethrows {
467
480
  if playWhenReady == false { setPlayWhenReady(false) }
481
+ let outerIntentFollows = playIntentFollows
482
+ playIntentFollows = playWhenReady == true
483
+ defer { playIntentFollows = outerIntentFollows }
468
484
  try action()
469
485
  if playWhenReady == true { setPlayWhenReady(true) }
470
486
  }
471
487
 
488
+ /// The running operation raises the intent once its action is done: a live track it loads
489
+ /// connects for that play rather than park first.
490
+ private var playIntentFollows = false
491
+
492
+ private var toPlay: Bool { playWhenReady || playIntentFollows }
493
+
472
494
  // MARK: - Queue Methods
473
495
 
474
496
  private func throwIfInvalid(_ tracks: [Track]) throws {
@@ -668,9 +690,11 @@ final class Player {
668
690
 
669
691
  /// Seeks the current item. While it awaits the next item, or in .error for the restart, the
670
692
  /// target is held until the next item is ready and the ready transition waits for it
671
- /// (`DeferredSeek`); `completion` then reports false at once.
693
+ /// (`DeferredSeek`); `completion` then reports false at once. A parked live stream ignores it.
672
694
  func seek(to seconds: TimeInterval, completion: @escaping @MainActor (Bool) -> Void = { _ in }) {
673
- if awaitingItem || state == .error {
695
+ if liveStreamClosed {
696
+ completion(false)
697
+ } else if awaitingItem || state == .error {
674
698
  deferredSeek.capture(seconds)
675
699
  completion(false)
676
700
  } else if engine.hasItem {
@@ -681,7 +705,9 @@ final class Player {
681
705
  }
682
706
 
683
707
  func seek(by offset: TimeInterval) {
684
- if awaitingItem || state == .error {
708
+ if liveStreamClosed {
709
+ return
710
+ } else if awaitingItem || state == .error {
685
711
  seek(to: (resumePosition ?? 0) + offset)
686
712
  } else if engine.hasItem {
687
713
  seek(to: engine.currentTime + offset)
@@ -690,9 +716,9 @@ final class Player {
690
716
 
691
717
  /// Jumps to the live edge: the end of the seekable window when there is one; without one
692
718
  /// (ICY), or in .error, whose item's window is stale, it reconnects. No-op for a track that
693
- /// isn't live.
719
+ /// isn't live, or a parked one, whose next play reconnects at the edge.
694
720
  func seekToLiveEdge() {
695
- guard currentTrack?.live == true, engine.hasItem else { return }
721
+ guard currentTrack?.live == true, engine.hasItem, !liveStreamClosed else { return }
696
722
  if let edge = engine.liveEdge, state != .error {
697
723
  seek(to: edge)
698
724
  } else {
@@ -738,26 +764,31 @@ final class Player {
738
764
  /// Loads the current track again, re-running the media-URL resolver, so a consumer whose
739
765
  /// resolver mints short-lived URLs or tokens recovers once they expire. A track without a `src`
740
766
  /// fails as an invalid source; with no current track, nothing loads.
741
- func reloadResolving(startFromCurrentTime: Bool) {
767
+ /// - Parameter shortStartBuffer: For the retry loop's reconnects, which would otherwise be silent
768
+ /// for seconds each: see `PlayerEngine.resolveAndLoad`.
769
+ func reloadResolving(startFromCurrentTime: Bool, shortStartBuffer: Bool = false) {
742
770
  guard let track = currentTrack else { return }
743
771
  guard let src = track.src else {
744
772
  transition(.errorOccurred(.invalidSourceUrl("nil")))
745
773
  return
746
774
  }
747
775
  prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
748
- connect(src: src, track: track)
776
+ connect(src: src, track: track, shortStartBuffer: shortStartBuffer)
749
777
  }
750
778
 
751
779
  private var connectionItemPrepared = false
752
780
 
753
- private func connect(src: String, track: Track) {
781
+ private func connect(src: String, track: Track, shortStartBuffer: Bool = false) {
782
+ if track.live == true, !toPlay { return deferIdleLivePark() }
754
783
  connectionItemPrepared = false
755
784
  retry.connectionStarted()
756
- engine.resolveAndLoad(src: src, track: track)
785
+ engine.resolveAndLoad(src: src, track: track, shortStartBuffer: shortStartBuffer)
757
786
  }
758
787
 
759
- /// The caller's retry: reloads now, resuming where it was, in place of any retry pending.
788
+ /// The caller's retry: reloads now, resuming where it was, in place of any retry pending. A parked
789
+ /// live stream waits for its play.
760
790
  func retryNow() {
791
+ guard !liveStreamClosed || toPlay else { return }
761
792
  retry.cancel()
762
793
  reloadResolving(startFromCurrentTime: true)
763
794
  }
@@ -769,11 +800,74 @@ final class Player {
769
800
  transition(.retryCancelled)
770
801
  }
771
802
 
803
+ /// A live stream holds a connection only while it is to play: a paused AVPlayer goes on reading
804
+ /// one, on macOS for as long as it stays paused, and a resume would play what it buffered,
805
+ /// minutes behind the stream. Parked, the next play reconnects at the live edge.
806
+ private func parkIdleLiveStream() {
807
+ guard holdsLiveConnection, !toPlay else { return }
808
+ closeLiveConnection()
809
+ transition(.retryCancelled)
810
+ }
811
+
812
+ static let idleLiveParkDelaySeconds: TimeInterval = 1
813
+ /// The window behind its live edge that lets a live item pause in place, as on-demand does (a
814
+ /// DVR window). A shorter one is a stream that can't be rewound: a pause closes it.
815
+ static let pausableLiveWindowSeconds: TimeInterval = 30
816
+ /// A paused live item with a window goes on loading toward its edge at the stream's rate for as
817
+ /// long as it stays paused: capped while paused, so it stops this far ahead of the paused position.
818
+ static let pausedLiveBufferSeconds: TimeInterval = 10
819
+
820
+ private var liveItemPausable: Bool {
821
+ (engine.liveWindowSeconds ?? 0) >= Self.pausableLiveWindowSeconds
822
+ }
823
+
824
+ private var pendingIdleLivePark: (any SleepTimerJob)?
825
+
826
+ /// A live track loaded without play intent opens no connection and stays .loading, so a play
827
+ /// sent as a separate call (`setQueue`, then `play()`) connects with no `paused` between. With
828
+ /// no play after `idleLiveParkDelaySeconds`, it parks.
829
+ private func deferIdleLivePark() {
830
+ retry.cancel()
831
+ engine.cancelLoading()
832
+ load?.reloadOnPlay = true
833
+ cancelIdleLivePark()
834
+ pendingIdleLivePark = scheduler.schedule(after: Self.idleLiveParkDelaySeconds) { [weak self] in
835
+ guard let self else { return }
836
+ pendingIdleLivePark = nil
837
+ engine.replaceItemWithNowPlayingCarrier()
838
+ transition(.retryCancelled)
839
+ }
840
+ }
841
+
842
+ private func cancelIdleLivePark() {
843
+ pendingIdleLivePark?.cancel()
844
+ pendingIdleLivePark = nil
845
+ }
846
+
847
+ /// A retry that gave up leaves its item in place, connected still: .error holds one too.
848
+ private var holdsLiveConnection: Bool {
849
+ currentTrack?.live == true && !liveItemPausable && (playbackActive || state == .error)
850
+ && load?.reloadOnPlay != true
851
+ }
852
+
853
+ /// Parked or stopped: its next play is at the live edge, so a seek has no position to go to.
854
+ private var liveStreamClosed: Bool {
855
+ currentTrack?.live == true && (load?.reloadOnPlay == true || state == .stopped && !liveItemPausable)
856
+ }
857
+
858
+ private func closeLiveConnection() {
859
+ retry.cancel()
860
+ engine.cancelLoading()
861
+ engine.replaceItemWithNowPlayingCarrier()
862
+ load?.reloadOnPlay = true
863
+ }
864
+
772
865
  /// A restart from a terminal error begins a new Load on a new AVPlayer; automatic retries
773
866
  /// never get here in .error, since the retry loop keeps the state non-terminal, but get a new
774
867
  /// AVPlayer in the same Load when the AVPlayer itself failed. `time`, else the pending target,
775
868
  /// is held as the deferred seek before the loading transition saves the snapshot.
776
869
  private func prepareForReload(resumingAt time: TimeInterval?) {
870
+ cancelIdleLivePark()
777
871
  load?.reloadOnPlay = false
778
872
  let target = time ?? deferredSeek.target
779
873
  deferredSeek.reset()
@@ -843,7 +937,7 @@ final class Player {
843
937
  recoverIfAirPlayStalled(transitioningTo: status, waitingForNoItem: waitingForNoItem)
844
938
  timeControlStatusDidChange(status)
845
939
  case .audioDidStart:
846
- if state != .loading { transition(.audioFrameDecoded) }
940
+ if !awaitingItem { transition(.audioFrameDecoded) }
847
941
  case .playedToEnd:
848
942
  itemDidPlayToEnd()
849
943
  case .stalled:
@@ -861,10 +955,11 @@ final class Player {
861
955
  transition(.bufferingSufficient)
862
956
  }
863
957
 
864
- /// While loading, a status change belongs to the previous item. A pause near the end is the
865
- /// end arriving, which `.playedToEnd` handles; one with the play intent is a buffer or a seek.
958
+ /// While the load awaits its item, a status change belongs to the one it replaces, or to none. A
959
+ /// pause near the end is the end arriving, which `.playedToEnd` handles; one with the play intent
960
+ /// is a buffer or a seek.
866
961
  private func timeControlStatusDidChange(_ status: PlayerTimeControlStatus) {
867
- guard state != .loading else { return }
962
+ guard !awaitingItem else { return }
868
963
  switch status {
869
964
  case .paused:
870
965
  let duration = engine.duration
@@ -46,6 +46,8 @@ enum EngineEvent {
46
46
  var resumePosition: Double? { get }
47
47
  /// The end of the seekable window; nil when there is none.
48
48
  var liveEdge: Double? { get }
49
+ /// How far back a live item can seek from its live edge; nil for an on-demand item or none.
50
+ var liveWindowSeconds: Double? { get }
49
51
  var isPlaybackLikelyToKeepUp: Bool { get }
50
52
  var isAirPlayRoute: Bool { get }
51
53
  /// 0–1.
@@ -55,12 +57,17 @@ enum EngineEvent {
55
57
 
56
58
  /// Resolves `src` for `track` afresh, so a short-lived URL is minted anew, and loads it. The
57
59
  /// outcome arrives as `itemPrepared`, `loadFailed`, `unplayable` or `invalidSource`.
58
- func resolveAndLoad(src: String, track: Track)
60
+ /// - Parameter shortStartBuffer: The item is ready once about 1 s is buffered, not the several
61
+ /// seconds AVPlayer otherwise waits for, then buffers as configured.
62
+ func resolveAndLoad(src: String, track: Track, shortStartBuffer: Bool)
59
63
  func cancelLoading()
60
64
  /// Drops the asset and stops observing the item, leaving the item in place for the reload.
61
65
  func dropAsset()
62
66
  /// Drops the asset and removes the item.
63
67
  func clearItem()
68
+ /// Drops the asset and its connection, leaving in the item's place one with no media that carries
69
+ /// the now-playing info: auto-publishing reads it only from the current item (docs/adr/0005).
70
+ func replaceItemWithNowPlayingCarrier()
64
71
  func stopObservingItem()
65
72
  /// Whether the AVPlayer itself has failed, not only its item: it plays nothing until recreated.
66
73
  var playerFailed: Bool { get }
@@ -71,6 +78,8 @@ enum EngineEvent {
71
78
 
72
79
  func play()
73
80
  func pause()
81
+ /// Caps how far ahead the current item loads, in seconds; nil restores the configured buffer.
82
+ func capForwardBuffer(_ seconds: Double?)
74
83
  /// Stages `rate` for the next play; applies it now only when `playing`, since a nonzero
75
84
  /// AVPlayer rate starts playback.
76
85
  func setRate(_ rate: Float, playing: Bool)
@@ -197,4 +197,25 @@ struct AsyncLoadingTests {
197
197
  let hasError = !spy.retryableErrors.isEmpty || spy.unplayableCount > 0
198
198
  #expect(hasError, "expected a retryable error or unplayable callback for non-existent file")
199
199
  }
200
+
201
+ @Test(arguments: [(0.0, 0.0, 1.0), (500, 0.5, 0.5), (5000, 5, 1)])
202
+ func aShortStartBufferIsOneSecond_orTheConfiguredOneWhenShorter(
203
+ configuredMs: Double, expected: Double, expectedShort: Double,
204
+ ) async throws {
205
+ let url = try makeSilentAudioFile()
206
+ defer { try? FileManager.default.removeItem(at: url) }
207
+ var buffers: [Double] = []
208
+ for shortStartBuffer in [false, true] {
209
+ let (loader, spy) = makeLoader()
210
+ loader.bufferDuration = configuredMs
211
+ loader.resolveAndLoad(src: url.absoluteString, shortStartBuffer: shortStartBuffer)
212
+ let deadline = ContinuousClock.now + .seconds(5)
213
+ while spy.preparedItems.isEmpty, ContinuousClock.now < deadline {
214
+ try await Task.sleep(for: .milliseconds(10))
215
+ }
216
+ let item = try #require(spy.preparedItems.first)
217
+ buffers.append(item.preferredForwardBufferDuration)
218
+ }
219
+ #expect(buffers == [expected, expectedShort])
220
+ }
200
221
  }
@@ -49,6 +49,23 @@ struct ItemObserverTests {
49
49
  observer.invalidate()
50
50
  }
51
51
 
52
+ @Test func reportsTheItemBecomingReady() async throws {
53
+ let url = try makeSilentAudioFile()
54
+ defer { try? FileManager.default.removeItem(at: url) }
55
+
56
+ let item = AVPlayerItem(url: url)
57
+ var events: [ItemObserver.Event] = []
58
+ let observer = ItemObserver(item: item) { events.append($0) }
59
+ let player = AVPlayer(playerItem: item)
60
+ let deadline = ContinuousClock.now + .seconds(5)
61
+ while !events.map(label).contains("readyToPlay"), ContinuousClock.now < deadline {
62
+ try await Task.sleep(for: .milliseconds(10))
63
+ }
64
+ #expect(events.map(label).contains("readyToPlay"))
65
+ observer.invalidate()
66
+ _ = player
67
+ }
68
+
52
69
  @Test func dropsADeliveryThatLandsAfterInvalidate() async {
53
70
  let item = makeItem()
54
71
  var events: [ItemObserver.Event] = []
@@ -71,6 +88,7 @@ struct ItemObserverTests {
71
88
  private func label(_ event: ItemObserver.Event) -> String {
72
89
  switch event {
73
90
  case .likelyToKeepUp: "likelyToKeepUp"
91
+ case .readyToPlay: "readyToPlay"
74
92
  case .failed: "failed"
75
93
  case .playedToEnd: "playedToEnd"
76
94
  case .failedToPlayToEnd: "failedToPlayToEnd"