react-native-audio-browser 0.2.0-next.76 → 0.2.0-next.77
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.
- package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +1 -1
- package/android/src/main/java/com/audiobrowser/player/EnginePlayback.kt +9 -5
- package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +71 -39
- package/android/src/main/java/com/audiobrowser/player/LiveStreamExtractor.kt +65 -0
- package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +12 -3
- package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +5 -0
- package/android/src/main/java/com/audiobrowser/player/Player.kt +78 -36
- package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +6 -0
- package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +1 -1
- package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +21 -0
- package/android/src/test/java/androidx/media3/session/SessionViews.kt +10 -0
- package/android/src/test/java/com/audiobrowser/player/LiveStreamEndTest.kt +372 -0
- package/android/src/test/java/com/audiobrowser/player/PlayerSetupEndedTest.kt +221 -0
- package/android/src/test/java/com/audiobrowser/player/PlayerSetupTest.kt +17 -7
- package/android/src/test/java/com/audiobrowser/player/PlayerSuppressionTest.kt +183 -7
- package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +48 -0
- package/android/src/test/java/com/audiobrowser/player/SessionPlayTest.kt +236 -0
- package/android/src/test/java/com/audiobrowser/player/SessionViewRulesTest.kt +62 -0
- package/android/src/test/java/com/audiobrowser/player/SessionViewTest.kt +188 -0
- package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +11 -0
- package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +58 -0
- package/ios/AVPlayerEngine.swift +5 -1
- package/ios/Browser/BrowserManager.swift +2 -2
- package/ios/Browser/PageResolver.swift +14 -19
- package/ios/Browser/RequestPipeline.swift +6 -4
- package/ios/CarPlay/CarPlayNowPlayingManager.swift +1 -1
- package/ios/CarPlay/CarPlaySession+PageLoader.swift +1 -0
- package/ios/CarPlay/CarPlaySession+TabBar.swift +2 -0
- package/ios/Extension/Promise+AwaitCallback.swift +33 -0
- package/ios/HybridAudioBrowser+Player.swift +1 -1
- package/ios/HybridAudioBrowser.swift +1 -1
- package/ios/Player/MediaLoader.swift +1 -1
- package/ios/Player/PlaybackFailure.swift +3 -3
- package/ios/Player/Player.swift +67 -49
- package/ios/Player/PlayerEngine.swift +2 -0
- package/ios/Player/RetryLoop.swift +72 -12
- package/ios/Tests/AwaitCallbackTests.swift +210 -0
- package/ios/Tests/GenerationMemoTests.swift +57 -0
- package/ios/Tests/PlaybackFailureTests.swift +7 -0
- package/ios/Tests/PlayerPolicyTests.swift +346 -6
- package/ios/Tests/PlayerTests.swift +79 -1
- package/ios/Tests/RetryLoopTests.swift +30 -5
- package/ios/Tests/Support/TestTypes.swift +15 -7
- package/ios/Tests/Support/TimeLimit.swift +43 -0
- package/ios/Util/AwaitCallback.swift +80 -0
- package/ios/Util/GenerationMemo.swift +11 -4
- package/package.json +1 -1
- package/android/src/test/java/com/audiobrowser/player/SessionErrorMaskTest.kt +0 -63
- package/ios/Player/EndOfTrackJudgement.swift +0 -25
- package/ios/Tests/EndOfTrackJudgementTests.swift +0 -30
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import android.net.Uri
|
|
4
|
+
import android.os.Looper
|
|
5
|
+
import androidx.media3.common.C
|
|
6
|
+
import androidx.media3.common.Player as MediaPlayer
|
|
7
|
+
import androidx.media3.session.MediaSession
|
|
8
|
+
import androidx.media3.session.controllerTitle
|
|
9
|
+
import androidx.media3.session.legacy.PlaybackStateCompat
|
|
10
|
+
import androidx.media3.session.legacyState
|
|
11
|
+
import com.audiobrowser.Callbacks
|
|
12
|
+
import com.audiobrowser.TestFixtures
|
|
13
|
+
import com.audiobrowser.model.PlayerSetupOptions
|
|
14
|
+
import com.audiobrowser.model.RetryPolicy
|
|
15
|
+
import com.audiobrowser.util.TrackFactory
|
|
16
|
+
import com.margelo.nitro.audiobrowser.PlaybackState
|
|
17
|
+
import java.io.File
|
|
18
|
+
import java.nio.ByteBuffer
|
|
19
|
+
import java.nio.ByteOrder
|
|
20
|
+
import java.time.Duration
|
|
21
|
+
import org.junit.After
|
|
22
|
+
import org.junit.Assert.assertEquals
|
|
23
|
+
import org.junit.Assert.fail
|
|
24
|
+
import org.junit.Rule
|
|
25
|
+
import org.junit.Test
|
|
26
|
+
import org.junit.rules.TemporaryFolder
|
|
27
|
+
import org.junit.runner.RunWith
|
|
28
|
+
import org.mockito.Mockito.mock
|
|
29
|
+
import org.robolectric.RobolectricTestRunner
|
|
30
|
+
import org.robolectric.RuntimeEnvironment
|
|
31
|
+
import org.robolectric.Shadows.shadowOf
|
|
32
|
+
import org.robolectric.annotation.Config
|
|
33
|
+
import org.robolectric.shadows.ShadowSystemClock
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What the session tells legacy controllers (Android Auto, Bluetooth, the system UI) for each state
|
|
37
|
+
* on an idle engine.
|
|
38
|
+
*/
|
|
39
|
+
@RunWith(RobolectricTestRunner::class)
|
|
40
|
+
@Config(sdk = [28])
|
|
41
|
+
class SessionViewTest {
|
|
42
|
+
|
|
43
|
+
@get:Rule val folder = TemporaryFolder()
|
|
44
|
+
|
|
45
|
+
private val context = RuntimeEnvironment.getApplication()
|
|
46
|
+
private val player = Player(context)
|
|
47
|
+
private val callbacks = mock(Callbacks::class.java)
|
|
48
|
+
private lateinit var session: MediaSession
|
|
49
|
+
|
|
50
|
+
private val paused = PlaybackStateCompat.STATE_PAUSED
|
|
51
|
+
private val idle = PlaybackStateCompat.STATE_NONE
|
|
52
|
+
|
|
53
|
+
@After
|
|
54
|
+
fun release() {
|
|
55
|
+
session.release()
|
|
56
|
+
player.networkMonitor.destroy()
|
|
57
|
+
player.exoPlayer.release()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
@Test
|
|
61
|
+
fun `a cancelled retry reads paused`() {
|
|
62
|
+
play(RetryPolicy.Infinite())
|
|
63
|
+
idleUntil("a pending retry") { player.playbackError?.retrying == true }
|
|
64
|
+
|
|
65
|
+
player.pause()
|
|
66
|
+
idleUntil("an idle engine") { player.exoPlayer.playbackState == MediaPlayer.STATE_IDLE }
|
|
67
|
+
|
|
68
|
+
assertEquals(PlaybackState.PAUSED, player.playbackState)
|
|
69
|
+
assertEquals(paused, session.legacyState())
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@Test
|
|
73
|
+
fun `a terminal error reads paused`() {
|
|
74
|
+
failTerminally()
|
|
75
|
+
|
|
76
|
+
assertEquals(paused, session.legacyState())
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@Test
|
|
80
|
+
fun `an error a rebuild dropped reads paused`() {
|
|
81
|
+
failTerminally()
|
|
82
|
+
|
|
83
|
+
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
84
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
85
|
+
|
|
86
|
+
assertEquals(PlaybackState.ERROR, player.playbackState)
|
|
87
|
+
assertEquals(paused, session.legacyState())
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
@Test
|
|
91
|
+
fun `a stop after a terminal error reads idle`() {
|
|
92
|
+
failTerminally()
|
|
93
|
+
|
|
94
|
+
player.stop()
|
|
95
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
96
|
+
|
|
97
|
+
assertEquals(idle, session.legacyState())
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
@Test
|
|
101
|
+
fun `a stop after a cancelled retry reads idle`() {
|
|
102
|
+
play(RetryPolicy.Infinite())
|
|
103
|
+
idleUntil("a pending retry") { player.playbackError?.retrying == true }
|
|
104
|
+
player.pause()
|
|
105
|
+
idleUntil("an idle engine") { player.exoPlayer.playbackState == MediaPlayer.STATE_IDLE }
|
|
106
|
+
|
|
107
|
+
player.stop()
|
|
108
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
109
|
+
|
|
110
|
+
assertEquals(idle, session.legacyState())
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
@Test
|
|
114
|
+
fun `an ended queue a rebuild carried idle reads ended`() {
|
|
115
|
+
play(RetryPolicy.Default, Uri.fromFile(silentWav()).toString())
|
|
116
|
+
idleUntil("ENDED") { player.playbackState == PlaybackState.ENDED }
|
|
117
|
+
|
|
118
|
+
player.setup(PlayerSetupOptions(maxBuffer = 120_000.0))
|
|
119
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
120
|
+
|
|
121
|
+
assertEquals(MediaPlayer.STATE_IDLE, player.exoPlayer.playbackState)
|
|
122
|
+
assertEquals(PlaybackStateCompat.STATE_STOPPED, session.legacyState())
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@Test
|
|
126
|
+
fun `the session hears the current track's title`() {
|
|
127
|
+
play(RetryPolicy.Default, Uri.fromFile(silentWav()).toString())
|
|
128
|
+
idleUntil("ENDED") { player.playbackState == PlaybackState.ENDED }
|
|
129
|
+
|
|
130
|
+
assertEquals("T", session.controllerTitle())
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private fun failTerminally() {
|
|
134
|
+
play(RetryPolicy.Limited(maxRetries = 0))
|
|
135
|
+
idleUntil("a terminal error") { player.playbackState == PlaybackState.ERROR }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private fun play(retryPolicy: RetryPolicy, src: String = "https://127.0.0.1:9/stream") {
|
|
139
|
+
player.setup(PlayerSetupOptions(retryPolicy = retryPolicy))
|
|
140
|
+
player.setCallbacks(callbacks)
|
|
141
|
+
session = MediaSession.Builder(context, player.forwardingPlayer).build()
|
|
142
|
+
player.setMediaSession(session)
|
|
143
|
+
player.exoPlayer.trackSelectionParameters =
|
|
144
|
+
player.exoPlayer.trackSelectionParameters
|
|
145
|
+
.buildUpon()
|
|
146
|
+
.setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true)
|
|
147
|
+
.build()
|
|
148
|
+
player.exoPlayer.setMediaItems(listOf(TrackFactory.toMedia3(TestFixtures.track(src = src))))
|
|
149
|
+
player.exoPlayer.prepare()
|
|
150
|
+
player.play()
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private fun idleUntil(what: String, condition: () -> Boolean) {
|
|
154
|
+
val deadline = System.currentTimeMillis() + 5_000
|
|
155
|
+
while (!condition()) {
|
|
156
|
+
if (System.currentTimeMillis() > deadline)
|
|
157
|
+
fail(
|
|
158
|
+
"timed out waiting for $what: ${player.playbackState}, exo ${player.exoPlayer.playbackState}"
|
|
159
|
+
)
|
|
160
|
+
ShadowSystemClock.advanceBy(Duration.ofMillis(100))
|
|
161
|
+
Thread.sleep(10)
|
|
162
|
+
shadowOf(Looper.getMainLooper()).idle()
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Half a second of 8 kHz mono 8-bit silence. */
|
|
167
|
+
private fun silentWav(): File {
|
|
168
|
+
val samples = 4_000
|
|
169
|
+
val header =
|
|
170
|
+
ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
|
|
171
|
+
put("RIFF".toByteArray())
|
|
172
|
+
putInt(36 + samples)
|
|
173
|
+
put("WAVEfmt ".toByteArray())
|
|
174
|
+
putInt(16)
|
|
175
|
+
putShort(1)
|
|
176
|
+
putShort(1)
|
|
177
|
+
putInt(8_000)
|
|
178
|
+
putInt(8_000)
|
|
179
|
+
putShort(1)
|
|
180
|
+
putShort(8)
|
|
181
|
+
put("data".toByteArray())
|
|
182
|
+
putInt(samples)
|
|
183
|
+
}
|
|
184
|
+
return folder.newFile("silence.wav").apply {
|
|
185
|
+
writeBytes(header.array() + ByteArray(samples) { 0x80.toByte() })
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -4,12 +4,14 @@ import android.os.Looper
|
|
|
4
4
|
import androidx.media3.common.C
|
|
5
5
|
import androidx.media3.common.DeviceInfo
|
|
6
6
|
import androidx.media3.common.MediaItem
|
|
7
|
+
import androidx.media3.common.Metadata
|
|
7
8
|
import androidx.media3.common.PlaybackException
|
|
8
9
|
import androidx.media3.common.PlaybackParameters
|
|
9
10
|
import androidx.media3.common.Player as MediaPlayer
|
|
10
11
|
import androidx.media3.common.SimpleBasePlayer
|
|
11
12
|
import androidx.media3.common.TrackSelectionParameters
|
|
12
13
|
import androidx.media3.common.util.Util
|
|
14
|
+
import androidx.media3.extractor.metadata.icy.IcyInfo
|
|
13
15
|
import com.google.common.util.concurrent.Futures
|
|
14
16
|
import com.google.common.util.concurrent.ListenableFuture
|
|
15
17
|
|
|
@@ -140,6 +142,7 @@ internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
140
142
|
var lagging = false
|
|
141
143
|
private var held: MediaItem? = null
|
|
142
144
|
private var uid = Any()
|
|
145
|
+
private var metadata: Metadata? = null
|
|
143
146
|
|
|
144
147
|
fun catchUp() {
|
|
145
148
|
held?.let { item = it }
|
|
@@ -155,6 +158,12 @@ internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
155
158
|
|
|
156
159
|
fun update() = invalidateState()
|
|
157
160
|
|
|
161
|
+
/** Reports a stream title for whatever it plays, as a receiver's poll does; a load clears it. */
|
|
162
|
+
fun title(title: String) {
|
|
163
|
+
metadata = Metadata(0, IcyInfo(title.toByteArray(), title, null))
|
|
164
|
+
invalidateState()
|
|
165
|
+
}
|
|
166
|
+
|
|
158
167
|
override fun getState(): State =
|
|
159
168
|
State.Builder()
|
|
160
169
|
.setAvailableCommands(MediaPlayer.Commands.Builder().addAllCommands().build())
|
|
@@ -169,6 +178,7 @@ internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
169
178
|
.setPlaybackState(if (item == null) STATE_IDLE else readiness)
|
|
170
179
|
.setDeviceInfo(DEVICE_INFO)
|
|
171
180
|
.setDeviceVolume(volume)
|
|
181
|
+
.apply { metadata?.let(::setTimedMetadata) }
|
|
172
182
|
.build()
|
|
173
183
|
|
|
174
184
|
override fun handleSetMediaItems(
|
|
@@ -180,6 +190,7 @@ internal class FakeReceiver(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
180
190
|
loads += SentLoad(loaded, startPositionMs, intent)
|
|
181
191
|
// A fresh uid makes a reload of the same item a new playlist entry to listeners.
|
|
182
192
|
uid = Any()
|
|
193
|
+
metadata = null
|
|
183
194
|
positionMs = if (startPositionMs == C.TIME_UNSET) 0 else startPositionMs
|
|
184
195
|
readiness = STATE_READY
|
|
185
196
|
if (lagging) held = loaded else item = loaded
|
|
@@ -3,8 +3,10 @@ package com.audiobrowser.remote
|
|
|
3
3
|
import android.os.Looper
|
|
4
4
|
import androidx.media3.common.C
|
|
5
5
|
import androidx.media3.common.MediaItem
|
|
6
|
+
import androidx.media3.common.Metadata
|
|
6
7
|
import androidx.media3.common.PlaybackException
|
|
7
8
|
import androidx.media3.common.Player as MediaPlayer
|
|
9
|
+
import androidx.media3.extractor.metadata.icy.IcyInfo
|
|
8
10
|
import java.time.Duration
|
|
9
11
|
import kotlinx.coroutines.CompletableDeferred
|
|
10
12
|
import kotlinx.coroutines.MainScope
|
|
@@ -870,6 +872,45 @@ class RemoteSwitchingPlayerTest {
|
|
|
870
872
|
assertEquals(200_000, player.currentPosition)
|
|
871
873
|
}
|
|
872
874
|
|
|
875
|
+
@Test
|
|
876
|
+
fun `a title for the outgoing item while the next one resolves never shows on it`() {
|
|
877
|
+
playLocally(listOf("a", "b"))
|
|
878
|
+
remote.startSession()
|
|
879
|
+
idle()
|
|
880
|
+
remote.player.title("A 1")
|
|
881
|
+
idle()
|
|
882
|
+
val seen = transitionsAndTitles()
|
|
883
|
+
gate = CompletableDeferred()
|
|
884
|
+
|
|
885
|
+
player.seekToNextMediaItem()
|
|
886
|
+
idle()
|
|
887
|
+
remote.player.title("A 2")
|
|
888
|
+
idle()
|
|
889
|
+
gate!!.complete(Unit)
|
|
890
|
+
idle()
|
|
891
|
+
remote.player.title("B 1")
|
|
892
|
+
idle()
|
|
893
|
+
|
|
894
|
+
assertEquals(listOf("b", "B 1"), seen)
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
@Test
|
|
898
|
+
fun `a new load of the same stream shows its title again`() {
|
|
899
|
+
playLocally(listOf("a"))
|
|
900
|
+
remote.startSession()
|
|
901
|
+
idle()
|
|
902
|
+
remote.player.title("Song")
|
|
903
|
+
idle()
|
|
904
|
+
val seen = transitionsAndTitles()
|
|
905
|
+
|
|
906
|
+
player.setMediaItems(items("a"))
|
|
907
|
+
idle()
|
|
908
|
+
remote.player.title("Song")
|
|
909
|
+
idle()
|
|
910
|
+
|
|
911
|
+
assertEquals(listOf("a", "Song"), seen)
|
|
912
|
+
}
|
|
913
|
+
|
|
873
914
|
@Test
|
|
874
915
|
fun `release brings playback back and lets every remote go`() {
|
|
875
916
|
playLocally(listOf("a"))
|
|
@@ -906,6 +947,23 @@ class RemoteSwitchingPlayerTest {
|
|
|
906
947
|
idle()
|
|
907
948
|
}
|
|
908
949
|
|
|
950
|
+
/** The id of each item transitioned to, and each stream title, in the order the player tells. */
|
|
951
|
+
private fun transitionsAndTitles(): List<String> {
|
|
952
|
+
val seen = mutableListOf<String>()
|
|
953
|
+
player.addListener(
|
|
954
|
+
object : MediaPlayer.Listener {
|
|
955
|
+
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
|
956
|
+
seen += mediaItem?.mediaId.orEmpty()
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
override fun onMetadata(metadata: Metadata) {
|
|
960
|
+
seen += (metadata[0] as IcyInfo).title.orEmpty()
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
)
|
|
964
|
+
return seen
|
|
965
|
+
}
|
|
966
|
+
|
|
909
967
|
private fun queue() = (0 until player.mediaItemCount).map { player.getMediaItemAt(it).mediaId }
|
|
910
968
|
|
|
911
969
|
private fun SentLoad.short() = Triple(item.mediaId, positionMs, autoplay)
|
package/ios/AVPlayerEngine.swift
CHANGED
|
@@ -162,10 +162,14 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
162
162
|
itemObserver = nil
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
+
var playerFailed: Bool { avPlayer.status == .failed }
|
|
166
|
+
|
|
165
167
|
func recreate() {
|
|
166
168
|
playerObserver?.invalidate()
|
|
167
169
|
nowPlayingInfoController.unlinkPlayer()
|
|
170
|
+
let volume = avPlayer.volume
|
|
168
171
|
avPlayer = AVPlayer()
|
|
172
|
+
avPlayer.volume = volume
|
|
169
173
|
setUpAVPlayer()
|
|
170
174
|
}
|
|
171
175
|
|
|
@@ -264,7 +268,7 @@ final class AVPlayerEngine: PlayerEngine {
|
|
|
264
268
|
private func playerDidEmit(_ event: PlayerObserver.Event) {
|
|
265
269
|
switch event {
|
|
266
270
|
case let .status(status):
|
|
267
|
-
if status == .failed { reportFailure(
|
|
271
|
+
if status == .failed { reportFailure(avPlayer.error) }
|
|
268
272
|
case let .timeControlStatus(status):
|
|
269
273
|
let mapped: PlayerTimeControlStatus
|
|
270
274
|
switch status {
|
|
@@ -87,7 +87,7 @@ final class BrowserManager {
|
|
|
87
87
|
func awaitTrackLoadHandler(event: TrackLoadEvent) async -> Bool {
|
|
88
88
|
guard let handler = config.handleTrackLoad else { return false }
|
|
89
89
|
do {
|
|
90
|
-
try await handler(event).
|
|
90
|
+
try await handler(event).awaitNested()
|
|
91
91
|
} catch {
|
|
92
92
|
logger.error("handleTrackLoad failed: \(error.localizedDescription)")
|
|
93
93
|
}
|
|
@@ -204,7 +204,7 @@ final class BrowserManager {
|
|
|
204
204
|
let params = FormatNavigationErrorParams(
|
|
205
205
|
error: error, defaultFormatted: fallback, path: path, kind: NavigationErrorKind(path: path),
|
|
206
206
|
)
|
|
207
|
-
return await (try? formatter(params).
|
|
207
|
+
return await (try? formatter(params).awaitOrTimeout()) ?? fallback
|
|
208
208
|
}
|
|
209
209
|
|
|
210
210
|
// MARK: - Search
|
|
@@ -57,7 +57,7 @@ final class PageResolver {
|
|
|
57
57
|
throw BrowserError.contentNotFound(path: SimpleRouter.searchRoutePath)
|
|
58
58
|
}
|
|
59
59
|
if let callback = searchEntry.searchCallback {
|
|
60
|
-
return try await callback(params).
|
|
60
|
+
return try await callback(params).awaitNested()
|
|
61
61
|
}
|
|
62
62
|
if let searchConfig = searchEntry.searchConfig {
|
|
63
63
|
return try await requests.fetchSearch(searchConfig, params: params)
|
|
@@ -76,13 +76,13 @@ final class PageResolver {
|
|
|
76
76
|
let callbackParam = BrowserSourceCallbackParam(path: path, routeParams: params)
|
|
77
77
|
// Nitro flattens `(ResolvedTrack | BrowseError) | Promise<BrowseResult>` into three arms:
|
|
78
78
|
// a sync track, a sync error, or a promise of the same two.
|
|
79
|
-
switch try await callback(callbackParam).
|
|
79
|
+
switch try await callback(callbackParam).awaitCancellable() {
|
|
80
80
|
case let .first(resolvedTrack):
|
|
81
81
|
return resolvedTrack
|
|
82
82
|
case let .second(browseError):
|
|
83
83
|
throw BrowserError.callbackError(browseError.error)
|
|
84
84
|
case let .third(promise):
|
|
85
|
-
switch try await promise.
|
|
85
|
+
switch try await promise.awaitCancellable() {
|
|
86
86
|
case let .first(resolvedTrack):
|
|
87
87
|
return resolvedTrack
|
|
88
88
|
case let .second(browseError):
|
|
@@ -115,23 +115,18 @@ final class PageResolver {
|
|
|
115
115
|
) async throws -> [Section] {
|
|
116
116
|
let stamped = try BrowserPathHelper.stampingContextualPaths(sections, parentPath: parentPath)
|
|
117
117
|
let artworkConfig = routeEntry?.artwork
|
|
118
|
-
let
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
await self.requests.resolveArtworkUrl(track: track, perRouteConfig: artworkConfig)
|
|
122
|
-
}
|
|
123
|
-
}
|
|
118
|
+
let tracks = stamped.flatMap(\.children)
|
|
119
|
+
let artwork = await Array(tracks.indices).concurrentMap { index in
|
|
120
|
+
await self.requests.resolveArtworkUrl(track: tracks[index], perRouteConfig: artworkConfig)
|
|
124
121
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
transformed.append(section.copying(children: children))
|
|
122
|
+
// A cancelled resolve gives no artwork; that page must not reach the cache.
|
|
123
|
+
try Task.checkCancellation()
|
|
124
|
+
var next = 0
|
|
125
|
+
return stamped.map { section in
|
|
126
|
+
section.copying(children: section.children.map { track in
|
|
127
|
+
defer { next += 1 }
|
|
128
|
+
return artwork[next].map { track.copying(artworkSource: $0) } ?? track
|
|
129
|
+
})
|
|
134
130
|
}
|
|
135
|
-
return transformed
|
|
136
131
|
}
|
|
137
132
|
}
|
|
@@ -37,8 +37,8 @@ final class RequestPipeline {
|
|
|
37
37
|
let config = self.config
|
|
38
38
|
// Double await: the TS side wraps a sync-or-async thunk in a JS promise, behind the
|
|
39
39
|
// bridge's promise.
|
|
40
|
-
let request = try await config.requestResolver?().
|
|
41
|
-
let browse = try await config.browseResolver?().
|
|
40
|
+
let request = try await config.requestResolver?().awaitNested() ?? config.request
|
|
41
|
+
let browse = try await config.browseResolver?().awaitNested() ?? config.browse
|
|
42
42
|
return ResolvedLayers(request: request, browse: browse)
|
|
43
43
|
}
|
|
44
44
|
}
|
|
@@ -246,6 +246,8 @@ final class RequestPipeline {
|
|
|
246
246
|
headers: RequestLayer.imageHeaders(request),
|
|
247
247
|
body: request.body,
|
|
248
248
|
)
|
|
249
|
+
} catch is CancellationError {
|
|
250
|
+
return nil
|
|
249
251
|
} catch {
|
|
250
252
|
logger.error("Failed to transform artwork URL for track: \(track.title), error: \(error.localizedDescription)")
|
|
251
253
|
return nil
|
|
@@ -258,12 +260,12 @@ final class RequestPipeline {
|
|
|
258
260
|
/// bridge hop, then the JS promise): a single await hands a `Promise` downstream. Copies the
|
|
259
261
|
/// result out.
|
|
260
262
|
func awaitAsyncConfig(_ promise: Promise<Promise<RequestConfig>>) async throws -> RequestConfig {
|
|
261
|
-
try await extractConfig(promise.
|
|
263
|
+
try await extractConfig(promise.awaitNested())
|
|
262
264
|
}
|
|
263
265
|
|
|
264
266
|
/// Awaits a sync config callback (one bridge await) and copies the result out.
|
|
265
267
|
func awaitSyncConfig(_ promise: Promise<RequestConfig>) async throws -> RequestConfig {
|
|
266
|
-
try await extractConfig(promise.
|
|
268
|
+
try await extractConfig(promise.awaitCancellable())
|
|
267
269
|
}
|
|
268
270
|
|
|
269
271
|
/// A copy of `config`, so nothing reads the Nitro bridge's value after its Promise is gone.
|
|
@@ -202,7 +202,7 @@ final class CarPlayNowPlayingManager {
|
|
|
202
202
|
Task { @MainActor [weak self] in
|
|
203
203
|
let path: String?
|
|
204
204
|
do {
|
|
205
|
-
path = try await resolver(track).
|
|
205
|
+
path = try await resolver(track).awaitCancellable()
|
|
206
206
|
} catch {
|
|
207
207
|
self?.logger.error("resolveAlbumPath failed: \(error.localizedDescription)")
|
|
208
208
|
path = nil
|
|
@@ -48,6 +48,7 @@ extension CarPlaySession {
|
|
|
48
48
|
await showNavigationError(.code(.emptyContent), path: path, on: template)
|
|
49
49
|
}
|
|
50
50
|
case let .failure(error):
|
|
51
|
+
guard !(error is CancellationError || Task.isCancelled) else { return }
|
|
51
52
|
logger.error("Failed to load content for \(path): \(error.localizedDescription)")
|
|
52
53
|
await showNavigationError(NavigationError.from(error), path: path, on: template)
|
|
53
54
|
}
|
|
@@ -119,6 +119,8 @@ extension CarPlaySession {
|
|
|
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
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 }
|
|
122
124
|
reportGates([chrome], reason: reason)
|
|
123
125
|
return chrome
|
|
124
126
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import NitroModules
|
|
2
|
+
|
|
3
|
+
/// Awaits for JS callbacks in place of Nitro's `await()`, which ignores cancellation: see
|
|
4
|
+
/// `awaitCallback`. The nested forms are for a callback returning a promise, which crosses the
|
|
5
|
+
/// bridge as `Promise<Promise<U>>`.
|
|
6
|
+
extension Promise {
|
|
7
|
+
func awaitCancellable() async throws -> T {
|
|
8
|
+
try await awaitCallback(subscribe)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/// Throws `CallbackTimeoutError` after `callbackFallbackTimeout`; only for a caller with a
|
|
12
|
+
/// fallback.
|
|
13
|
+
func awaitOrTimeout() async throws -> T {
|
|
14
|
+
try await awaitCallback(timeout: callbackFallbackTimeout, subscribe)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
func awaitNested<U>() async throws -> U where T == Promise<U> {
|
|
18
|
+
try await awaitCallback(subscribeNested)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// The timeout covers both promises.
|
|
22
|
+
func awaitNestedOrTimeout<U>() async throws -> U where T == Promise<U> {
|
|
23
|
+
try await awaitCallback(timeout: callbackFallbackTimeout, subscribeNested)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
private func subscribe(_ deliver: @escaping @Sendable (Result<T, Error>) -> Void) {
|
|
27
|
+
then { deliver(.success($0)) }.catch { deliver(.failure($0)) }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private func subscribeNested<U>(_ deliver: @escaping @Sendable (Result<U, Error>) -> Void) where T == Promise<U> {
|
|
31
|
+
then { $0.subscribe(deliver) }.catch { deliver(.failure($0)) }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -132,7 +132,7 @@ public extension HybridAudioBrowser {
|
|
|
132
132
|
func retry() throws {
|
|
133
133
|
// Re-resolves rather than replaying the cached URL: short-lived URLs or tokens may have
|
|
134
134
|
// expired since the failure.
|
|
135
|
-
onMainActor { player?.
|
|
135
|
+
onMainActor { player?.retryNow() }
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
// MARK: - Sleep Timer
|
|
@@ -262,7 +262,7 @@ public class HybridAudioBrowser: HybridAudioBrowserSpec, @unchecked Sendable {
|
|
|
262
262
|
}
|
|
263
263
|
browseGate.resolve = { [weak self] request in
|
|
264
264
|
guard let self else { throw CancellationError() }
|
|
265
|
-
return try await resolveGate(request).
|
|
265
|
+
return try await resolveGate(request).awaitNestedOrTimeout()
|
|
266
266
|
}
|
|
267
267
|
// Unconditional: `shared` is weak, so after a reload the old instance may be gone while
|
|
268
268
|
// CarPlay is still subscribed to its emitters.
|
|
@@ -54,7 +54,7 @@ final class MediaLoader {
|
|
|
54
54
|
func resolveAndLoad(src: String, track: Track? = nil) {
|
|
55
55
|
mediaResolverTask?.cancel()
|
|
56
56
|
// `self` stays weak across the await: a consumer resolver that never settles must not pin
|
|
57
|
-
// the loader
|
|
57
|
+
// the loader.
|
|
58
58
|
let resolveUrl = resolveUrl
|
|
59
59
|
mediaResolverTask = Task { [weak self] in
|
|
60
60
|
guard !Task.isCancelled else { return }
|
|
@@ -15,8 +15,8 @@ enum PlaybackFailure {
|
|
|
15
15
|
/// The two answers rank the evidence differently, on purpose:
|
|
16
16
|
/// - The error: a transport failure first (no response arrived, so a logged status belongs to
|
|
17
17
|
/// an earlier attempt), then a non-2xx status, then undecodable media.
|
|
18
|
-
/// - Retrying: a status first (a retry cannot change what the server refused), then the
|
|
19
|
-
/// chain. An unrecognized failure counts as retryable, bounded by the retry budgets, as on
|
|
18
|
+
/// - Retrying: a non-2xx status first (a retry cannot change what the server refused), then the
|
|
19
|
+
/// error chain. An unrecognized failure counts as retryable, bounded by the retry budgets, as on
|
|
20
20
|
/// Android: AVFoundation reports most stream failures opaquely.
|
|
21
21
|
static func classify(
|
|
22
22
|
_ error: Error?,
|
|
@@ -93,7 +93,7 @@ enum PlaybackFailure {
|
|
|
93
93
|
])
|
|
94
94
|
|
|
95
95
|
private static func isRetryable(_ error: Error?, httpStatusCode: Int?) -> Bool {
|
|
96
|
-
if let status = httpStatusCode {
|
|
96
|
+
if let status = httpStatusCode, !(200 ... 299).contains(status) {
|
|
97
97
|
return retryableHTTPStatusCodes.contains(status) || (500 ... 599).contains(status)
|
|
98
98
|
}
|
|
99
99
|
guard let error else { return false }
|