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

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.
@@ -13,7 +13,7 @@ Pod::Spec.new do |s|
13
13
  s.platforms = { :ios => "16.0", :visionos => 1.0 }
14
14
  s.source = { :git => "https://github.com/puckey/react-native-audio-browser.git", :tag => "#{s.version}" }
15
15
 
16
- s.swift_version = '6.2'
16
+ s.swift_version = '6.3'
17
17
 
18
18
  s.source_files = [
19
19
  # Implementation (Swift)
package/README.md CHANGED
@@ -35,7 +35,9 @@ Use the same tree in your app UI, or keep it focused on CarPlay and Android Auto
35
35
 
36
36
  ## Requirements
37
37
 
38
- React Native with the **New Architecture** (Fabric + TurboModules), [`react-native-nitro-modules`](https://nitro.margelo.com) as a peer dependency, and on web [`shaka-player`](https://github.com/shaka-project/shaka-player) as an optional peer dependency. The minimum React Native, React, iOS, Android, nitro and shaka-player versions are listed in [Getting Started](https://audiobrowser.dev/guide/getting-started#installation).
38
+ React Native with the **New Architecture** (Fabric + TurboModules), [`react-native-nitro-modules`](https://nitro.margelo.com) as a peer dependency, and on web [`shaka-player`](https://github.com/shaka-project/shaka-player) as an optional peer dependency. The minimum React Native, React, iOS, Android, nitro and shaka-player versions are listed in [Getting Started](https://audiobrowser.dev/guide/getting-started#installation). iOS builds need Xcode 26.4 or later (Swift 6.3).
39
+
40
+ Built with Xcode 27, an app whose `react-native-nitro-modules` lacks the fix of [margelo/nitro#1824](https://github.com/margelo/nitro/pull/1824) does not launch on iOS below 18 (dyld: `Symbol not found: std::exception_ptr::__from_native_exception_pointer`). The fix is in 0.37.2; where 0.37.2 does not build ([margelo/nitro#2052](https://github.com/margelo/nitro/issues/2052)), patch the two header hunks of #1824 into the version you use.
39
41
 
40
42
  ## Installation
41
43
 
@@ -1,4 +1,6 @@
1
- import NitroModules
1
+ #if canImport(NitroModules)
2
+ import NitroModules
3
+ #endif
2
4
 
3
5
  /// The Browse Gate: the app's block on browsing and searching from external surfaces,
4
6
  /// decided per request. It never blocks the Player, the Queue or Now Playing.
@@ -54,4 +56,15 @@ final class BrowseGate {
54
56
  return decision.gate ?? defaultChrome ?? Self.builtInChrome
55
57
  }
56
58
  }
59
+
60
+ /// The chrome to show if `request` is gated, as `decide(_:)` answers, and the gate passed to
61
+ /// `report`, unless the caller was cancelled: a cancelled decision fails closed, but the user
62
+ /// never met this gate.
63
+ func decide(_ request: NativeGateRequest, report: (GateEvent) -> Void) async -> Gate? {
64
+ let chrome = await decide(request)
65
+ if chrome != nil, !Task.isCancelled {
66
+ report(GateEvent(reason: request.reason))
67
+ }
68
+ return chrome
69
+ }
57
70
  }
@@ -3,6 +3,10 @@ import Foundation
3
3
  import NitroModules
4
4
  #endif
5
5
 
6
+ #if !compiler(>=6.3)
7
+ #error("react-native-audio-browser needs Swift 6.3 or later (Xcode 26.4 or later): Swift 6.2 compiles this library's nonisolated(nonsending) closures into code that crashes on iOS below 18 (swiftlang/swift#86829)")
8
+ #endif
9
+
6
10
  /// The fields every request config kind (request, browse, media, artwork) has.
7
11
  protocol RequestFieldValues<Method> {
8
12
  associatedtype Method
@@ -30,8 +30,7 @@ final class CarPlayNowPlayingManager {
30
30
 
31
31
  /// Resolved on track change, not on tap, so the album line shows only when a destination exists.
32
32
  private var albumArtistDestination: String?
33
- /// Drops a `resolveAlbumPath` result that finishes after the track changed.
34
- private var albumArtistGeneration: UInt = 0
33
+ private let albumPathResolution = SupersedingTask<String, String>()
35
34
  /// The tapped track while its load runs, which wins over `currentTrack`: CarPlay reads
36
35
  /// `isAlbumArtistButtonEnabled` only when Now Playing is displayed, and that push comes first.
37
36
  private var pendingAlbumArtistTrack: Track?
@@ -61,7 +60,11 @@ final class CarPlayNowPlayingManager {
61
60
 
62
61
  let browserManager = audioBrowser.browserManager
63
62
  subscriptions = [
64
- browserManager.configChanged.subscribeOnMain { [weak self] _ in self?.refresh() },
63
+ browserManager.configChanged.subscribeOnMain { [weak self] _ in
64
+ // A new config may bring a new `resolveAlbumPath`, so the current track is asked again.
65
+ self?.albumPathResolution.cancel()
66
+ self?.refresh()
67
+ },
65
68
  audioBrowser.playerOptionsChangedEmitter.subscribeOnMain { [weak self] in self?.refresh() },
66
69
  browserManager.favoritesChanged.subscribeOnMain { [weak self] in self?.refreshButtons() },
67
70
  audioBrowser.favoriteChangedEmitter.subscribeOnMain { [weak self] _ in self?.refreshButtons() },
@@ -84,7 +87,7 @@ final class CarPlayNowPlayingManager {
84
87
  subscriptions = []
85
88
  pendingAlbumArtistTrack = nil
86
89
  // A resolve in flight must not set the shared template for the next session.
87
- albumArtistGeneration &+= 1
90
+ albumPathResolution.cancel()
88
91
  }
89
92
 
90
93
  func refresh() {
@@ -182,36 +185,37 @@ final class CarPlayNowPlayingManager {
182
185
  // MARK: - Album Line
183
186
 
184
187
  private func updateAlbumArtistDestination() {
185
- albumArtistGeneration &+= 1
186
- let generation = albumArtistGeneration
187
-
188
188
  guard let track = pendingAlbumArtistTrack ?? player?.currentTrack else {
189
189
  logger.debug("AlbumArtist: no current track → disabled")
190
- setAlbumArtistDestination(nil)
190
+ settleAlbumArtistDestination(nil)
191
191
  return
192
192
  }
193
193
  logger.info("AlbumArtist: track=\(track.title) albumPath=\(track.albumPath ?? "nil") resolver=\(self.config.resolveAlbumPath != nil)")
194
194
  if let albumPath = track.albumPath {
195
- setAlbumArtistDestination(albumPath)
195
+ settleAlbumArtistDestination(albumPath)
196
196
  return
197
197
  }
198
198
  guard let resolver = config.resolveAlbumPath else {
199
- setAlbumArtistDestination(nil)
199
+ settleAlbumArtistDestination(nil)
200
200
  return
201
201
  }
202
- Task { @MainActor [weak self] in
203
- let path: String?
204
- do {
205
- path = try await resolver(track).awaitCancellable()
206
- } catch {
207
- self?.logger.error("resolveAlbumPath failed: \(error.localizedDescription)")
208
- path = nil
202
+ albumPathResolution.run(key: track.identity) {
203
+ try await resolver(track).awaitCancellable()
204
+ } deliver: { [weak self] result in
205
+ guard let self else { return }
206
+ if case let .failure(error) = result {
207
+ logger.error("resolveAlbumPath failed: \(error.localizedDescription)")
209
208
  }
210
- guard let self, self.albumArtistGeneration == generation else { return }
211
- self.setAlbumArtistDestination(path)
209
+ setAlbumArtistDestination(try? result.get())
212
210
  }
213
211
  }
214
212
 
213
+ /// Sets the destination without a resolve, ending any in flight so it cannot overwrite this.
214
+ private func settleAlbumArtistDestination(_ path: String?) {
215
+ albumPathResolution.cancel()
216
+ setAlbumArtistDestination(path)
217
+ }
218
+
215
219
  private func setAlbumArtistDestination(_ path: String?) {
216
220
  albumArtistDestination = path
217
221
  let template = CPNowPlayingTemplate.shared
@@ -118,11 +118,9 @@ extension CarPlaySession {
118
118
 
119
119
  /// The chrome to show if the Browse Gate gates this request, reported to JS; nil when allowed.
120
120
  func gate(_ reason: GateReason, path: String?, search: SearchParams? = nil) async -> Gate? {
121
- let chrome = await audioBrowser.browseGate.decide(NativeGateRequest(reason: reason, path: path, search: search))
122
- // A cancelled decision fails closed, but the user never met this gate.
123
- guard !Task.isCancelled else { return chrome }
124
- reportGates([chrome], reason: reason)
125
- return chrome
121
+ await audioBrowser.browseGate.decide(NativeGateRequest(reason: reason, path: path, search: search)) {
122
+ audioBrowser.onGate($0)
123
+ }
126
124
  }
127
125
 
128
126
  /// One decision per path, made concurrently, in path order. Reports nothing: the caller
@@ -23,8 +23,13 @@ final class MediaIntentHandler: NSObject, INPlayMediaIntentHandling {
23
23
  Self.logger.info("Play media intent — query=\(criteria.query) matchesApp=\(criteria.matchesAppName) resume=\(criteria.isResume)")
24
24
 
25
25
  Task { @MainActor in
26
- let success = await MediaIntentPlayback.play(criteria: criteria)
27
- completion(INPlayMediaIntentResponse(code: success ? .success : .failure, userActivity: nil))
26
+ let success = await withDeadline(MediaIntentPlayback.budget) { deadline in
27
+ await MediaIntentPlayback.play(criteria: criteria, deadline: deadline)
28
+ }
29
+ if success == nil {
30
+ Self.logger.error("Play media intent — no answer within \(MediaIntentPlayback.budget)")
31
+ }
32
+ completion(INPlayMediaIntentResponse(code: success == true ? .success : .failure, userActivity: nil))
28
33
  }
29
34
  }
30
35
 
@@ -7,14 +7,18 @@ private let logger = Logger(subsystem: "com.audiobrowser", category: "MediaInten
7
7
  /// Plays a Siri play-media intent through the single voice play funnel (ADR 0002): resume, or
8
8
  /// search, queue and play, then ask for Now Playing.
9
9
  enum MediaIntentPlayback {
10
- /// Callable before React Native has booted: waits, within the assistant's time budget, for the
11
- /// player and a configured browser. A JS reload or a second setup can replace the bridge during
12
- /// any await, so the player is looked up again after one and the intent fails once the bridge is
13
- /// gone. Returns whether playback was requested; true does not mean audio has started, and a
14
- /// failed cold resume still returns true.
10
+ /// Siri gives the handle phase 10 s from its connection, and the app's launch counts against it
11
+ /// (WWDC20, "Empower your intents").
12
+ static let budget: Duration = .seconds(8)
13
+
14
+ /// Callable before React Native has booted: waits, until `deadline`, for the player and a
15
+ /// configured browser. Each action looks the player up again through `livePlayer(of:)`, so the
16
+ /// intent fails once a reload has replaced the bridge or the deadline has cancelled it. Returns
17
+ /// whether playback was requested; true does not mean audio has started, and a failed cold
18
+ /// resume still returns true.
15
19
  @MainActor
16
- static func play(criteria: MediaIntentCriteria) async -> Bool {
17
- guard let (browser, player) = await playerAndConfiguredBrowser.wait(timeout: .seconds(8)) else {
20
+ static func play(criteria: MediaIntentCriteria, deadline: ContinuousClock.Instant) async -> Bool {
21
+ guard let (browser, player) = await playerAndConfiguredBrowser.wait(timeout: ContinuousClock.now.duration(to: deadline)) else {
18
22
  logger.error("browser/player not ready within budget")
19
23
  return false
20
24
  }
@@ -22,6 +26,7 @@ enum MediaIntentPlayback {
22
26
  // persisted track.
23
27
  if criteria.isResume {
24
28
  if player.currentTrack != nil {
29
+ guard let player = livePlayer(of: browser) else { return false }
25
30
  logger.info("resume: warm — playing current track")
26
31
  player.play()
27
32
  } else {
@@ -49,9 +54,11 @@ enum MediaIntentPlayback {
49
54
  playlist: criteria.playlist,
50
55
  reference: criteria.reference == .my ? .my : .unknown,
51
56
  )
52
- guard await browser.browseGate.decide(NativeGateRequest(reason: .search, path: nil, search: params)) == nil else {
57
+ guard await browser.browseGate.decide(
58
+ NativeGateRequest(reason: .search, path: nil, search: params),
59
+ report: { browser.onGate($0) },
60
+ ) == nil else {
53
61
  logger.info("search refused — gated")
54
- browser.onGate(GateEvent(reason: .search))
55
62
  return false
56
63
  }
57
64
  do {
@@ -60,16 +67,20 @@ enum MediaIntentPlayback {
60
67
  try player.setQueue(tracks, initialIndex: 0, playWhenReady: true)
61
68
  browser.showNowPlayingRequestedEmitter.emit(())
62
69
  return true
70
+ } catch is CancellationError {
71
+ return false
63
72
  } catch {
64
73
  logger.error("search failed: \(error.localizedDescription)")
65
74
  return false
66
75
  }
67
76
  }
68
77
 
69
- /// `browser`'s player while `browser` is still the live bridge; a replaced bridge keeps its
70
- /// destroyed player.
78
+ /// `browser`'s player while `browser` is still the live bridge, as a replaced bridge keeps its
79
+ /// destroyed player, and while the intent is not cancelled: once `withDeadline` has answered
80
+ /// Siri, nothing plays.
71
81
  @MainActor
72
82
  private static func livePlayer(of browser: HybridAudioBrowser) -> Player? {
73
- HybridAudioBrowser.shared === browser ? browser.player : nil
83
+ guard !Task.isCancelled, HybridAudioBrowser.shared === browser else { return nil }
84
+ return browser.player
74
85
  }
75
86
  }
@@ -29,7 +29,7 @@ public extension HybridAudioBrowser {
29
29
  nowPlayingEnabled: options.autoUpdateNowPlayingMetadata ?? true,
30
30
  nowPlayingFormatter: options.nowPlayingMetadataFormatter,
31
31
  )
32
- let newPlayer = Player(engine: newEngine, callbacks: self, retry: RetryLoop(networkMonitor: networkMonitor))
32
+ let newPlayer = Player(engine: newEngine, callbacks: self, retry: RetryLoop(online: networkMonitor.isOnline))
33
33
  if let retry = options.retry { newPlayer.retry.updatePolicy(from: retry) }
34
34
  newEngine.nowPlayingUpdater.source = newPlayer
35
35
  engine = newEngine
@@ -177,6 +177,31 @@
177
177
  var reference: MediaReference
178
178
  }
179
179
 
180
+ enum GateReason {
181
+ case browse
182
+ case search
183
+ }
184
+
185
+ struct Gate {
186
+ var title: String
187
+ var message: String?
188
+ }
189
+
190
+ struct GateDecision {
191
+ var gated: Bool
192
+ var gate: Gate?
193
+ }
194
+
195
+ struct NativeGateRequest {
196
+ var reason: GateReason
197
+ var path: String?
198
+ var search: SearchParams?
199
+ }
200
+
201
+ struct GateEvent {
202
+ var reason: GateReason
203
+ }
204
+
180
205
  struct ImageContext {
181
206
  var width: Double?
182
207
  var height: Double?
@@ -8,9 +8,10 @@ func nextPlaybackState(from current: PlaybackState, on event: PlaybackEvent) ->
8
8
  case .trackLoading: return .loading
9
9
  case .trackUnloaded: return PlaybackState.none
10
10
  case .trackEndedNaturally: return .ended
11
- case .avPlayerWaiting: return .buffering
12
- case .avPlayerPlaying: return .playing
13
- case .audioFrameDecoded: return .playing
11
+ // .error holds against the AVPlayer's own events: an item still connecting when the retry gave
12
+ // up can report them late. Leaving .error takes an explicit reload, through .loading.
13
+ case .avPlayerWaiting: return current == .error ? nil : .buffering
14
+ case .avPlayerPlaying, .audioFrameDecoded: return current == .error ? nil : .playing
14
15
  case .errorOccurred: return .error
15
16
  case .retryCancelled:
16
17
  guard current != .stopped, current != .ended, current != .error else { return nil }
@@ -49,8 +49,6 @@ final class Player {
49
49
  /// One track's playback session, which automatic retry reloads keep (glossary: Load).
50
50
  struct Load: Equatable {
51
51
  let id: UInt
52
- /// Audio has rendered: retries get the recovery budget, not the first-connect one (ADR 0004).
53
- var hasPlayed = false
54
52
  /// The silent primer has run for this load's first failure (ADR 0005).
55
53
  var primedNowPlaying = false
56
54
  /// One of this load's items is in the engine; until then it reports the previous one's position.
@@ -73,7 +71,7 @@ final class Player {
73
71
  private func beginLoad() {
74
72
  loadCount &+= 1
75
73
  load = Load(id: loadCount)
76
- retry.reset()
74
+ retry.loadStarted()
77
75
  deferredSeek.reset()
78
76
  }
79
77
 
@@ -88,7 +86,8 @@ final class Player {
88
86
  rate = oldValue
89
87
  return
90
88
  }
91
- engine.setRate(rate, playing: playWhenReady)
89
+ // The intent stays up in .error, over an item the retry gave up on.
90
+ engine.setRate(rate, playing: playWhenReady && state != .error)
92
91
  persistence.save()
93
92
  }
94
93
  }
@@ -179,6 +178,7 @@ final class Player {
179
178
  func setPlayWhenReady(_ newValue: Bool) {
180
179
  let changed = newValue != playWhenReady
181
180
  playWhenReady = newValue
181
+ retry.playIntentChanged(newValue)
182
182
  // A play during an interruption owns the intent: a later pause must not be auto-resumed.
183
183
  if newValue { shouldResumeAfterInterruption = false }
184
184
 
@@ -251,12 +251,17 @@ final class Player {
251
251
  sleepTimerManager.onComplete = { [weak self] in self?.pause() }
252
252
  sleepTimerManager.onChanged = { [weak self] in self?.callbacks?.playerDidChangeSleepTimer($0) }
253
253
 
254
- retry.onError = { [weak self] in self?.transition(.errorOccurred($0)) }
254
+ retry.onError = { [weak self] error in
255
+ guard let self else { return }
256
+ // The deadline can pass with a connect in flight: its item must neither play nor fail
257
+ // under the error.
258
+ engine.cancelLoading()
259
+ engine.stopObservingItem()
260
+ transition(.errorOccurred(error))
261
+ }
255
262
  retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
256
263
  retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
257
264
  retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
258
- retry.shouldRetry = { [weak self] in self?.playWhenReady ?? false }
259
- retry.hasPlayed = { [weak self] in self?.load?.hasPlayed ?? false }
260
265
  retry.bufferedPosition = { [weak self] in self?.engine.bufferedPosition ?? 0 }
261
266
  }
262
267
 
@@ -367,6 +372,7 @@ final class Player {
367
372
  // A stall or a lost connection can fail an item that is still alive: data arriving later
368
373
  // must not play it under the error.
369
374
  engine.pause()
375
+ retry.cancel()
370
376
  default: break
371
377
  }
372
378
 
@@ -627,6 +633,7 @@ final class Player {
627
633
  persistence.save()
628
634
 
629
635
  if let src = currentTrack.src {
636
+ retry.connectionStarted()
630
637
  engine.resolveAndLoad(src: src, track: currentTrack)
631
638
  } else {
632
639
  logger.error("No src for track \(currentTrack.path ?? currentTrack.title)")
@@ -731,6 +738,7 @@ final class Player {
731
738
  return
732
739
  }
733
740
  prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
741
+ retry.connectionStarted()
734
742
  engine.resolveAndLoad(src: src, track: track)
735
743
  }
736
744
 
@@ -741,7 +749,7 @@ final class Player {
741
749
  }
742
750
 
743
751
  private func parkForReloadOnPlay() {
744
- retry.reset()
752
+ retry.cancel()
745
753
  if let position = reloadPosition { deferredSeek.capture(position) }
746
754
  load?.reloadOnPlay = true
747
755
  transition(.retryCancelled)
@@ -762,7 +770,7 @@ final class Player {
762
770
  engine.recreate()
763
771
  } else {
764
772
  engine.cancelLoading()
765
- engine.dropAsset()
773
+ engine.stopObservingItem()
766
774
  engine.pause()
767
775
  }
768
776
  if let target { deferredSeek.capture(target) }
@@ -800,6 +808,8 @@ final class Player {
800
808
  if playWhenReady { engine.play() }
801
809
  if !beginDeferredSeek(), likelyToKeepUp { bufferBecameSufficient() }
802
810
  case let .loadFailed(error):
811
+ // A failure after the terminal error is the same connection's, reported late.
812
+ guard state != .error else { return }
803
813
  primeNowPlayingIfNeeded()
804
814
  retry.handleError(error, context: .mediaLoad)
805
815
  case .unplayable:
@@ -809,6 +819,7 @@ final class Player {
809
819
  primeNowPlayingIfNeeded()
810
820
  transition(.errorOccurred(.invalidSourceUrl(url)))
811
821
  case let .failed(error, httpStatusCode):
822
+ guard state != .error else { return }
812
823
  retry.handleError(error, context: .playback, httpStatusCode: httpStatusCode)
813
824
  case let .likelyToKeepUp(isLikely):
814
825
  guard isLikely, engine.hasItem, !beginDeferredSeek() else { return }
@@ -817,7 +828,6 @@ final class Player {
817
828
  recoverIfAirPlayStalled(transitioningTo: status, waitingForNoItem: waitingForNoItem)
818
829
  timeControlStatusDidChange(status)
819
830
  case .audioDidStart:
820
- load?.hasPlayed = true
821
831
  if state != .loading { transition(.audioFrameDecoded) }
822
832
  case .playedToEnd:
823
833
  itemDidPlayToEnd()
@@ -900,16 +910,19 @@ final class Player {
900
910
 
901
911
  // MARK: - Connectivity
902
912
 
903
- /// Re-renders the now-playing lines, whose stall line tells offline from buffering, and when
904
- /// connectivity returns retries a stalled stream at once, spending an attempt, rather than wait
905
- /// for AVPlayer to fail it. Only while stalled (.buffering) with play intent, so a pause or a
906
- /// retry that gave up isn't resumed; not while a retry is pending, whose wait watches connectivity
907
- /// itself; and not with retry off, which leaves the stall to AVPlayer.
913
+ /// Re-renders the now-playing lines, whose stall line tells offline from buffering, and passes
914
+ /// the change to the retry loop. When connectivity returns to a stalled stream, its connection
915
+ /// is given up first, as one that ended offline, so the reconnect goes out at once rather than
916
+ /// wait for AVPlayer to fail it. Only while stalled (.buffering) with play intent, so a pause or
917
+ /// a retry that gave up isn't resumed; not while a retry is pending, which the loop paces itself;
918
+ /// and not with retry off, which leaves the stall to AVPlayer.
908
919
  func networkStatusDidChange(isOnline: Bool) {
909
920
  engine.renderNowPlaying()
910
- guard isOnline, playWhenReady, state == .buffering, retry.isEnabled, retry.pendingTask == nil else { return }
911
- logger.info("Connectivity restored while stalled — retrying now")
912
- retry.handleFailure(.stall, immediately: true)
921
+ if isOnline, playWhenReady, state == .buffering, retry.isEnabled, retry.pendingTask == nil {
922
+ logger.info("Connectivity restored while stalled — retrying now")
923
+ retry.handleFailure(.stall)
924
+ }
925
+ retry.onlineChanged(isOnline)
913
926
  }
914
927
 
915
928
  /// Time playback must have progressed before a buffer dip counts as a stall, so the initial