react-native-audio-browser 0.2.0-next.77 → 0.2.0-next.79
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/build.gradle +2 -0
- package/android/src/main/java/com/audiobrowser/player/ReconnectPacer.kt +97 -0
- package/android/src/main/java/com/audiobrowser/player/SilenceBudget.kt +89 -0
- package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +27 -2
- package/android/src/test/java/com/audiobrowser/player/RetryCaseTest.kt +125 -0
- package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +12 -0
- package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +16 -0
- package/ios/Player/ReconnectPacer.swift +83 -0
- package/ios/Player/SilenceBudget.swift +78 -0
- package/ios/Tests/RetryCaseTests.swift +146 -0
- package/package.json +1 -1
package/android/build.gradle
CHANGED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import kotlin.math.min
|
|
4
|
+
import kotlin.math.pow
|
|
5
|
+
|
|
6
|
+
sealed interface ReconnectWait {
|
|
7
|
+
data class After(val ms: Long) : ReconnectWait
|
|
8
|
+
|
|
9
|
+
/** Offline: no connect until the network returns; ask again then. */
|
|
10
|
+
data object UntilOnline : ReconnectWait
|
|
11
|
+
|
|
12
|
+
/** More than `maxRetries` connections in a row delivered nothing. */
|
|
13
|
+
data object GiveUp : ReconnectWait
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* When the next connect goes out after one ends (docs/adr/0014, rules 5 to 8), for one sequence of
|
|
18
|
+
* connections made one at a time. Pure and not thread-safe: time comes in as milliseconds on one
|
|
19
|
+
* monotonic clock.
|
|
20
|
+
*
|
|
21
|
+
* The 1 s floor counts from when the last connection started and the backoff from when it ended, so
|
|
22
|
+
* the floor binds only where no backoff applies: after a connection that delivered audio or ended
|
|
23
|
+
* offline, and once the network returns.
|
|
24
|
+
*
|
|
25
|
+
* @param maxRetries connections in a row that may deliver nothing before giving up; null for no
|
|
26
|
+
* limit
|
|
27
|
+
*/
|
|
28
|
+
class ReconnectPacer(var maxRetries: Int? = null, private var online: Boolean) {
|
|
29
|
+
companion object {
|
|
30
|
+
const val MIN_CONNECT_INTERVAL_MS = 1_000L
|
|
31
|
+
const val FIRST_BACKOFF_MS = 1_000L
|
|
32
|
+
const val MAX_BACKOFF_MS = 5_000L
|
|
33
|
+
const val BACKOFF_GROWTH = 1.5
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private var playIntent = false
|
|
37
|
+
private var deliveredNothingInARow = 0
|
|
38
|
+
private var lastStartedAtMs: Long? = null
|
|
39
|
+
private var nextConnectMs: Long? = null
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Starts the count and the waits over on a new Load: a track change, or a restart from the
|
|
43
|
+
* terminal error. Never on a retry's reload.
|
|
44
|
+
*/
|
|
45
|
+
fun reset() {
|
|
46
|
+
deliveredNothingInARow = 0
|
|
47
|
+
lastStartedAtMs = null
|
|
48
|
+
nextConnectMs = null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A play intent that comes up starts the count and the waits over; a repeat while up does not.
|
|
53
|
+
*/
|
|
54
|
+
fun playIntentChanged(up: Boolean) {
|
|
55
|
+
if (up && !playIntent) reset()
|
|
56
|
+
playIntent = up
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The network returning drops what remains of the wait, keeping the floor, so the next connect
|
|
61
|
+
* goes out at once; the backoff still grows from where it was. A repeat while online does
|
|
62
|
+
* nothing.
|
|
63
|
+
*/
|
|
64
|
+
fun onlineChanged(online: Boolean) {
|
|
65
|
+
if (online && !this.online)
|
|
66
|
+
nextConnectMs = lastStartedAtMs?.let { it + MIN_CONNECT_INTERVAL_MS }
|
|
67
|
+
this.online = online
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Records how a connection ended. One that ends while offline does not grow the backoff: it
|
|
72
|
+
* delivered nothing for want of a network, not of a source. A stall the watch gives up on reports
|
|
73
|
+
* what its connection delivered.
|
|
74
|
+
*/
|
|
75
|
+
fun connectionEnded(deliveredAudio: Boolean, startedAtMs: Long, atMs: Long) {
|
|
76
|
+
lastStartedAtMs = startedAtMs
|
|
77
|
+
var next = startedAtMs + MIN_CONNECT_INTERVAL_MS
|
|
78
|
+
if (deliveredAudio) {
|
|
79
|
+
deliveredNothingInARow = 0
|
|
80
|
+
} else if (online) {
|
|
81
|
+
deliveredNothingInARow++
|
|
82
|
+
next = maxOf(next, atMs + backoffMs())
|
|
83
|
+
}
|
|
84
|
+
nextConnectMs = next
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fun wait(atMs: Long): ReconnectWait {
|
|
88
|
+
maxRetries?.let { if (deliveredNothingInARow > it) return ReconnectWait.GiveUp }
|
|
89
|
+
if (!online) return ReconnectWait.UntilOnline
|
|
90
|
+
return ReconnectWait.After(maxOf(0, (nextConnectMs ?: atMs) - atMs))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private fun backoffMs(): Long {
|
|
94
|
+
val grown = FIRST_BACKOFF_MS * BACKOFF_GROWTH.pow(deliveredNothingInARow - 1)
|
|
95
|
+
return min(grown, MAX_BACKOFF_MS.toDouble()).toLong()
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* When automatic retry gives up: after [recoveryMs] of silence, or, for a Load that never played,
|
|
5
|
+
* [firstConnectMs] after its first failure within one online stretch (docs/adr/0014, rules 1 to 4).
|
|
6
|
+
* Pure and not thread-safe: time comes in as milliseconds on one monotonic clock, and nothing fires
|
|
7
|
+
* on its own. Every input can move the deadline, so read [deadlineMs] again after each.
|
|
8
|
+
*/
|
|
9
|
+
class SilenceBudget(
|
|
10
|
+
var recoveryMs: Long = 120_000,
|
|
11
|
+
var firstConnectMs: Long = 12_000,
|
|
12
|
+
private var online: Boolean,
|
|
13
|
+
) {
|
|
14
|
+
companion object {
|
|
15
|
+
/** The audio a silence needs, in a row, to end; a shorter burst leaves its deadline. */
|
|
16
|
+
const val AUDIBLE_TO_END_SILENCE_MS = 5_000L
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Whether the current Load has rendered audio; only [loadStarted] clears it. */
|
|
20
|
+
var hasPlayed = false
|
|
21
|
+
private set
|
|
22
|
+
|
|
23
|
+
private var playIntent = false
|
|
24
|
+
private var audibleSinceMs: Long? = null
|
|
25
|
+
private var silentSinceMs: Long? = null
|
|
26
|
+
private var firstOnlineFailureMs: Long? = null
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* When to give up, or null while audio plays or no audio is wanted. It can lie in the past: a
|
|
30
|
+
* burst that outlasts it ends past the deadline, which means give up at once.
|
|
31
|
+
*/
|
|
32
|
+
val deadlineMs: Long?
|
|
33
|
+
get() {
|
|
34
|
+
val silentSince = silentSinceMs
|
|
35
|
+
if (!playIntent || audibleSinceMs != null || silentSince == null) return null
|
|
36
|
+
val recovery = silentSince + recoveryMs
|
|
37
|
+
val firstFailure = firstOnlineFailureMs
|
|
38
|
+
if (hasPlayed || !online || firstFailure == null) return recovery
|
|
39
|
+
return minOf(recovery, firstFailure + firstConnectMs)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A new Load: a track change, or a restart from the terminal error. Never a retry's reload, which
|
|
44
|
+
* would restart the silence on every reconnect.
|
|
45
|
+
*/
|
|
46
|
+
fun loadStarted(atMs: Long) {
|
|
47
|
+
hasPlayed = false
|
|
48
|
+
audibleSinceMs = null
|
|
49
|
+
firstOnlineFailureMs = null
|
|
50
|
+
silentSinceMs = if (playIntent) atMs else null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A play intent that comes up starts a new silence; one that goes down ends it. */
|
|
54
|
+
fun playIntentChanged(up: Boolean, atMs: Long) {
|
|
55
|
+
if (up == playIntent) return
|
|
56
|
+
playIntent = up
|
|
57
|
+
firstOnlineFailureMs = null
|
|
58
|
+
silentSinceMs = if (up && audibleSinceMs == null) atMs else null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
fun audioStarted(atMs: Long) {
|
|
62
|
+
if (audibleSinceMs != null) return
|
|
63
|
+
audibleSinceMs = atMs
|
|
64
|
+
hasPlayed = true
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
fun audioStopped(atMs: Long) {
|
|
68
|
+
val audibleSince = audibleSinceMs ?: return
|
|
69
|
+
audibleSinceMs = null
|
|
70
|
+
if (!playIntent) return
|
|
71
|
+
if (silentSinceMs == null || atMs - audibleSince >= AUDIBLE_TO_END_SILENCE_MS) {
|
|
72
|
+
silentSinceMs = atMs
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Going offline restarts the first-connect clock, which only an online failure sets again. */
|
|
77
|
+
fun onlineChanged(online: Boolean) {
|
|
78
|
+
this.online = online
|
|
79
|
+
if (!online) firstOnlineFailureMs = null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Every connection's end, whatever it delivered: the first one online starts the first-connect
|
|
84
|
+
* clock of a Load that has not played.
|
|
85
|
+
*/
|
|
86
|
+
fun connectionEnded(atMs: Long) {
|
|
87
|
+
if (online && firstOnlineFailureMs == null) firstOnlineFailureMs = atMs
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -135,6 +135,27 @@ internal class RemoteSwitchingPlayer(
|
|
|
135
135
|
private val remoteRoute: Route.Remote?
|
|
136
136
|
get() = route as? Route.Remote
|
|
137
137
|
|
|
138
|
+
/** For the next [getState] to take [titleAtStop]: super.getState() consumes pending events. */
|
|
139
|
+
private var localStopPending = false
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The phone's metadata as it stopped, reported as none until the phone sends more. The state
|
|
143
|
+
* emits only a change, and a stream's first title after a reconnect often equals its last.
|
|
144
|
+
*/
|
|
145
|
+
private var titleAtStop: Metadata? = null
|
|
146
|
+
|
|
147
|
+
private fun withoutStoppedTitle(state: State): State {
|
|
148
|
+
if (localStopPending) {
|
|
149
|
+
localStopPending = false
|
|
150
|
+
titleAtStop = state.timedMetadata
|
|
151
|
+
}
|
|
152
|
+
if (state.timedMetadata !== titleAtStop) {
|
|
153
|
+
titleAtStop = null
|
|
154
|
+
return state
|
|
155
|
+
}
|
|
156
|
+
return state.buildUpon().setTimedMetadata(NO_TIMED_METADATA).build()
|
|
157
|
+
}
|
|
158
|
+
|
|
138
159
|
private val receiverListener =
|
|
139
160
|
object : MediaPlayer.Listener {
|
|
140
161
|
override fun onMetadata(metadata: Metadata) {
|
|
@@ -441,7 +462,7 @@ internal class RemoteSwitchingPlayer(
|
|
|
441
462
|
|
|
442
463
|
override fun getState(): State {
|
|
443
464
|
val state = super.getState()
|
|
444
|
-
val remote = remoteRoute ?: return state
|
|
465
|
+
val remote = remoteRoute ?: return withoutStoppedTitle(state)
|
|
445
466
|
val load = remote.load
|
|
446
467
|
val holds = load is Load.Playing && receiverHolds(remote, load.item)
|
|
447
468
|
// Duration, seekability and liveness come from the receiver's data for the item it plays.
|
|
@@ -541,7 +562,11 @@ internal class RemoteSwitchingPlayer(
|
|
|
541
562
|
}
|
|
542
563
|
|
|
543
564
|
override fun handleStop(): ListenableFuture<*> {
|
|
544
|
-
val remote = remoteRoute
|
|
565
|
+
val remote = remoteRoute
|
|
566
|
+
if (remote == null) {
|
|
567
|
+
localStopPending = true
|
|
568
|
+
return super.handleStop()
|
|
569
|
+
}
|
|
545
570
|
val positionMs = positionOn(remote)
|
|
546
571
|
cancelLoad(remote)
|
|
547
572
|
stopReceiver(remote.receiver)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
package com.audiobrowser.player
|
|
2
|
+
|
|
3
|
+
import kotlinx.serialization.json.Json
|
|
4
|
+
import kotlinx.serialization.json.JsonElement
|
|
5
|
+
import kotlinx.serialization.json.JsonNull
|
|
6
|
+
import kotlinx.serialization.json.JsonObject
|
|
7
|
+
import kotlinx.serialization.json.JsonPrimitive
|
|
8
|
+
import kotlinx.serialization.json.jsonArray
|
|
9
|
+
import kotlinx.serialization.json.jsonObject
|
|
10
|
+
import kotlinx.serialization.json.jsonPrimitive
|
|
11
|
+
import kotlinx.serialization.json.longOrNull
|
|
12
|
+
import org.junit.Assert.assertEquals
|
|
13
|
+
import org.junit.Test
|
|
14
|
+
import org.junit.runner.RunWith
|
|
15
|
+
import org.junit.runners.Parameterized
|
|
16
|
+
|
|
17
|
+
/** Runs every case in spec/retry-cases.json, which build.gradle puts on the test classpath. */
|
|
18
|
+
@RunWith(Parameterized::class)
|
|
19
|
+
class RetryCaseTest(private val name: String, private val case: JsonObject) {
|
|
20
|
+
companion object {
|
|
21
|
+
private val CASE_KEYS = setOf("name", "maxRetries", "recoveryMs", "firstConnectMs", "steps")
|
|
22
|
+
private val STEP_KEYS = setOf("at", "event", "delivered", "startedAt", "deadline", "wait")
|
|
23
|
+
|
|
24
|
+
@JvmStatic
|
|
25
|
+
@Parameterized.Parameters(name = "{0}")
|
|
26
|
+
fun cases(): List<Array<Any>> {
|
|
27
|
+
val text =
|
|
28
|
+
checkNotNull(RetryCaseTest::class.java.getResource("/retry-cases.json")) {
|
|
29
|
+
"spec/retry-cases.json is not on the test classpath"
|
|
30
|
+
}
|
|
31
|
+
.readText()
|
|
32
|
+
val file = Json.parseToJsonElement(text).jsonObject
|
|
33
|
+
(file.keys - setOf("about", "cases")).firstOrNull()?.let { error("unknown key $it") }
|
|
34
|
+
val cases = file.getValue("cases").jsonArray
|
|
35
|
+
check(cases.isNotEmpty()) { "spec/retry-cases.json holds no case" }
|
|
36
|
+
return cases.map {
|
|
37
|
+
arrayOf(it.jsonObject.getValue("name").jsonPrimitive.content, it.jsonObject)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** An integer, not a numeric string or a fraction. */
|
|
42
|
+
private fun JsonElement.strictLong(what: String): Long {
|
|
43
|
+
val primitive = this as? JsonPrimitive
|
|
44
|
+
return primitive?.takeUnless { it.isString }?.longOrNull ?: error("$what is not an integer")
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
@Test
|
|
49
|
+
fun runs() {
|
|
50
|
+
(case.keys - CASE_KEYS).firstOrNull()?.let { error("unknown key $it") }
|
|
51
|
+
val budget = SilenceBudget(online = true)
|
|
52
|
+
case["recoveryMs"]?.let { budget.recoveryMs = it.strictLong("recoveryMs") }
|
|
53
|
+
case["firstConnectMs"]?.let { budget.firstConnectMs = it.strictLong("firstConnectMs") }
|
|
54
|
+
val pacer =
|
|
55
|
+
ReconnectPacer(
|
|
56
|
+
maxRetries = case["maxRetries"]?.strictLong("maxRetries")?.toInt(),
|
|
57
|
+
online = true,
|
|
58
|
+
)
|
|
59
|
+
var lastAt = Long.MIN_VALUE
|
|
60
|
+
val steps = case.getValue("steps").jsonArray
|
|
61
|
+
check(steps.isNotEmpty()) { "$name: no steps" }
|
|
62
|
+
for (element in steps) {
|
|
63
|
+
// Strict, so a misspelt or missing key fails the case instead of dropping an assertion.
|
|
64
|
+
val step = element.jsonObject
|
|
65
|
+
(step.keys - STEP_KEYS).firstOrNull()?.let { error("unknown key $it") }
|
|
66
|
+
val at = step.getValue("at").strictLong("at")
|
|
67
|
+
check(at >= lastAt) { "at $at: time runs backwards" }
|
|
68
|
+
lastAt = at
|
|
69
|
+
val event = step.getValue("event").jsonPrimitive.content
|
|
70
|
+
when (event) {
|
|
71
|
+
"load" -> {
|
|
72
|
+
budget.loadStarted(at)
|
|
73
|
+
pacer.reset()
|
|
74
|
+
}
|
|
75
|
+
"intentUp",
|
|
76
|
+
"intentDown" -> {
|
|
77
|
+
budget.playIntentChanged(event == "intentUp", at)
|
|
78
|
+
pacer.playIntentChanged(event == "intentUp")
|
|
79
|
+
}
|
|
80
|
+
"audioStarts" -> budget.audioStarted(at)
|
|
81
|
+
"audioStops" -> budget.audioStopped(at)
|
|
82
|
+
"offline",
|
|
83
|
+
"online" -> {
|
|
84
|
+
budget.onlineChanged(event == "online")
|
|
85
|
+
pacer.onlineChanged(event == "online")
|
|
86
|
+
}
|
|
87
|
+
"ended" -> {
|
|
88
|
+
check("wait" in step) { "at $at: an end states the wait" }
|
|
89
|
+
val deliveredAudio =
|
|
90
|
+
when (val delivered = step["delivered"]?.jsonPrimitive?.content) {
|
|
91
|
+
"audio" -> true
|
|
92
|
+
"nothing" -> false
|
|
93
|
+
else -> error("at $at: an end delivers audio or nothing, not $delivered")
|
|
94
|
+
}
|
|
95
|
+
val startedAt =
|
|
96
|
+
checkNotNull(step["startedAt"]) { "at $at: an end states when it started" }
|
|
97
|
+
budget.connectionEnded(at)
|
|
98
|
+
val startedAtMs = startedAt.strictLong("startedAt")
|
|
99
|
+
check(startedAtMs <= at) { "at $at: started after it ended" }
|
|
100
|
+
pacer.connectionEnded(deliveredAudio, startedAtMs, at)
|
|
101
|
+
}
|
|
102
|
+
else -> error("at $at: unknown event $event")
|
|
103
|
+
}
|
|
104
|
+
val deadline = checkNotNull(step["deadline"]) { "at $at: every step states its deadline" }
|
|
105
|
+
assertEquals(
|
|
106
|
+
"deadline at $at ($event)",
|
|
107
|
+
if (deadline is JsonNull) null else deadline.strictLong("deadline at $at"),
|
|
108
|
+
budget.deadlineMs,
|
|
109
|
+
)
|
|
110
|
+
step["wait"]?.let { wait ->
|
|
111
|
+
val expected =
|
|
112
|
+
if (wait is JsonPrimitive && wait.isString) {
|
|
113
|
+
when (wait.content) {
|
|
114
|
+
"online" -> ReconnectWait.UntilOnline
|
|
115
|
+
"giveUp" -> ReconnectWait.GiveUp
|
|
116
|
+
else -> error("at $at: unknown wait ${wait.content}")
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
ReconnectWait.After(wait.strictLong("wait at $at"))
|
|
120
|
+
}
|
|
121
|
+
assertEquals("wait at $at ($event)", expected, pacer.wait(at))
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -26,6 +26,16 @@ internal class FakeLocalPlayer(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
26
26
|
private var repeat = REPEAT_MODE_OFF
|
|
27
27
|
private var shuffle = false
|
|
28
28
|
private val uids = mutableListOf<Any>()
|
|
29
|
+
private var metadata = Metadata(C.TIME_UNSET)
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Sends a stream title. ExoPlayer sends each one it decodes; this state emits only a change, so a
|
|
33
|
+
* stop clears it for the stream's first title after a reconnect to go out again.
|
|
34
|
+
*/
|
|
35
|
+
fun title(title: String) {
|
|
36
|
+
metadata = Metadata(0, IcyInfo(title.toByteArray(), title, null))
|
|
37
|
+
invalidateState()
|
|
38
|
+
}
|
|
29
39
|
|
|
30
40
|
override fun getState(): State =
|
|
31
41
|
State.Builder()
|
|
@@ -44,6 +54,7 @@ internal class FakeLocalPlayer(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
44
54
|
.setPlaybackState(if (items.isEmpty()) STATE_IDLE else readiness)
|
|
45
55
|
.setRepeatMode(repeat)
|
|
46
56
|
.setShuffleModeEnabled(shuffle)
|
|
57
|
+
.setTimedMetadata(metadata)
|
|
47
58
|
.build()
|
|
48
59
|
|
|
49
60
|
/** Moves to [index] without a seek, as the player does at an item's end. */
|
|
@@ -86,6 +97,7 @@ internal class FakeLocalPlayer(looper: Looper) : SimpleBasePlayer(looper) {
|
|
|
86
97
|
|
|
87
98
|
override fun handleStop(): ListenableFuture<*> {
|
|
88
99
|
readiness = STATE_IDLE
|
|
100
|
+
metadata = Metadata(C.TIME_UNSET)
|
|
89
101
|
stops++
|
|
90
102
|
return done()
|
|
91
103
|
}
|
|
@@ -911,6 +911,22 @@ class RemoteSwitchingPlayerTest {
|
|
|
911
911
|
assertEquals(listOf("a", "Song"), seen)
|
|
912
912
|
}
|
|
913
913
|
|
|
914
|
+
@Test
|
|
915
|
+
fun `a play after a local stop shows the stream's title again`() {
|
|
916
|
+
playLocally(listOf("a"))
|
|
917
|
+
local.title("Song")
|
|
918
|
+
idle()
|
|
919
|
+
val seen = transitionsAndTitles()
|
|
920
|
+
|
|
921
|
+
player.stop()
|
|
922
|
+
player.prepare()
|
|
923
|
+
idle()
|
|
924
|
+
local.title("Song")
|
|
925
|
+
idle()
|
|
926
|
+
|
|
927
|
+
assertEquals(listOf("Song"), seen)
|
|
928
|
+
}
|
|
929
|
+
|
|
914
930
|
@Test
|
|
915
931
|
fun `release brings playback back and lets every remote go`() {
|
|
916
932
|
playLocally(listOf("a"))
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
enum ReconnectWait: Equatable {
|
|
4
|
+
case after(ms: Int)
|
|
5
|
+
/// Offline: no connect until the network returns; ask again then.
|
|
6
|
+
case untilOnline
|
|
7
|
+
/// More than `maxRetries` connections in a row delivered nothing.
|
|
8
|
+
case giveUp
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/// When the next connect goes out after one ends (docs/adr/0014, rules 5 to 8), for one sequence of
|
|
12
|
+
/// connections made one at a time. Pure: time comes in as milliseconds on one monotonic clock.
|
|
13
|
+
///
|
|
14
|
+
/// The 1 s floor counts from when the last connection started and the backoff from when it
|
|
15
|
+
/// ended, so the floor binds only where no backoff applies: after a connection that delivered
|
|
16
|
+
/// audio or ended offline, and once the network returns.
|
|
17
|
+
struct ReconnectPacer {
|
|
18
|
+
static let minConnectIntervalMs = 1_000
|
|
19
|
+
static let firstBackoffMs = 1_000
|
|
20
|
+
static let maxBackoffMs = 5_000
|
|
21
|
+
static let backoffGrowth = 1.5
|
|
22
|
+
|
|
23
|
+
/// Connections in a row that may deliver nothing before giving up; nil for no limit.
|
|
24
|
+
var maxRetries: Int?
|
|
25
|
+
|
|
26
|
+
private var online: Bool
|
|
27
|
+
private var playIntent = false
|
|
28
|
+
private var deliveredNothingInARow = 0
|
|
29
|
+
private var lastStartedAtMs: Int?
|
|
30
|
+
private var nextConnectMs: Int?
|
|
31
|
+
|
|
32
|
+
init(maxRetries: Int? = nil, online: Bool) {
|
|
33
|
+
self.maxRetries = maxRetries
|
|
34
|
+
self.online = online
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// Starts the count and the waits over on a new Load: a track change, or a restart from the
|
|
38
|
+
/// terminal error. Never on a retry's reload.
|
|
39
|
+
mutating func reset() {
|
|
40
|
+
deliveredNothingInARow = 0
|
|
41
|
+
lastStartedAtMs = nil
|
|
42
|
+
nextConnectMs = nil
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// A play intent that comes up starts the count and the waits over; a repeat while up does not.
|
|
46
|
+
mutating func playIntentChanged(_ up: Bool) {
|
|
47
|
+
if up, !playIntent { reset() }
|
|
48
|
+
playIntent = up
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// The network returning drops what remains of the wait, keeping the floor, so the next connect
|
|
52
|
+
/// goes out at once; the backoff still grows from where it was. A repeat while online does
|
|
53
|
+
/// nothing.
|
|
54
|
+
mutating func onlineChanged(_ online: Bool) {
|
|
55
|
+
if online, !self.online { nextConnectMs = lastStartedAtMs.map { $0 + Self.minConnectIntervalMs } }
|
|
56
|
+
self.online = online
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Records how a connection ended. One that ends while offline does not grow the backoff: it
|
|
60
|
+
/// delivered nothing for want of a network, not of a source. A stall the watch gives up on
|
|
61
|
+
/// reports what its connection delivered.
|
|
62
|
+
mutating func connectionEnded(deliveredAudio: Bool, startedAtMs: Int, atMs now: Int) {
|
|
63
|
+
lastStartedAtMs = startedAtMs
|
|
64
|
+
nextConnectMs = startedAtMs + Self.minConnectIntervalMs
|
|
65
|
+
if deliveredAudio {
|
|
66
|
+
deliveredNothingInARow = 0
|
|
67
|
+
} else if online {
|
|
68
|
+
deliveredNothingInARow += 1
|
|
69
|
+
nextConnectMs = max(nextConnectMs ?? now, now + backoffMs)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
func wait(atMs now: Int) -> ReconnectWait {
|
|
74
|
+
if let maxRetries, deliveredNothingInARow > maxRetries { return .giveUp }
|
|
75
|
+
guard online else { return .untilOnline }
|
|
76
|
+
return .after(ms: max(0, (nextConnectMs ?? now) - now))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private var backoffMs: Int {
|
|
80
|
+
let grown = Double(Self.firstBackoffMs) * pow(Self.backoffGrowth, Double(deliveredNothingInARow - 1))
|
|
81
|
+
return Int(min(grown, Double(Self.maxBackoffMs)))
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/// When automatic retry gives up: after `recoveryMs` of silence, or, for a Load that never played,
|
|
2
|
+
/// `firstConnectMs` after its first failure within one online stretch (docs/adr/0014, rules 1 to 4).
|
|
3
|
+
/// Pure: time comes in as milliseconds on one monotonic clock, and nothing fires on its own.
|
|
4
|
+
/// Every input can move the deadline, so read `deadlineMs` again after each.
|
|
5
|
+
struct SilenceBudget {
|
|
6
|
+
/// The audio a silence needs, in a row, to end; a shorter burst leaves its deadline where it was.
|
|
7
|
+
static let audibleToEndSilenceMs = 5_000
|
|
8
|
+
|
|
9
|
+
var recoveryMs: Int
|
|
10
|
+
var firstConnectMs: Int
|
|
11
|
+
|
|
12
|
+
/// Whether the current Load has rendered audio; only `loadStarted` clears it.
|
|
13
|
+
private(set) var hasPlayed = false
|
|
14
|
+
private var playIntent = false
|
|
15
|
+
private var online: Bool
|
|
16
|
+
private var audibleSinceMs: Int?
|
|
17
|
+
private var silentSinceMs: Int?
|
|
18
|
+
private var firstOnlineFailureMs: Int?
|
|
19
|
+
|
|
20
|
+
init(recoveryMs: Int = 120_000, firstConnectMs: Int = 12_000, online: Bool) {
|
|
21
|
+
self.recoveryMs = recoveryMs
|
|
22
|
+
self.firstConnectMs = firstConnectMs
|
|
23
|
+
self.online = online
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// When to give up, or nil while audio plays or no audio is wanted. It can lie in the past: a
|
|
27
|
+
/// burst that outlasts it ends past the deadline, which means give up at once.
|
|
28
|
+
var deadlineMs: Int? {
|
|
29
|
+
guard playIntent, audibleSinceMs == nil, let silentSinceMs else { return nil }
|
|
30
|
+
let recovery = silentSinceMs + recoveryMs
|
|
31
|
+
guard !hasPlayed, online, let firstOnlineFailureMs else { return recovery }
|
|
32
|
+
return min(recovery, firstOnlineFailureMs + firstConnectMs)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// A new Load: a track change, or a restart from the terminal error. Never a retry's reload,
|
|
36
|
+
/// which would restart the silence on every reconnect.
|
|
37
|
+
mutating func loadStarted(atMs now: Int) {
|
|
38
|
+
hasPlayed = false
|
|
39
|
+
audibleSinceMs = nil
|
|
40
|
+
firstOnlineFailureMs = nil
|
|
41
|
+
silentSinceMs = playIntent ? now : nil
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// A play intent that comes up starts a new silence; one that goes down ends it.
|
|
45
|
+
mutating func playIntentChanged(_ up: Bool, atMs now: Int) {
|
|
46
|
+
guard up != playIntent else { return }
|
|
47
|
+
playIntent = up
|
|
48
|
+
firstOnlineFailureMs = nil
|
|
49
|
+
silentSinceMs = up && audibleSinceMs == nil ? now : nil
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
mutating func audioStarted(atMs now: Int) {
|
|
53
|
+
guard audibleSinceMs == nil else { return }
|
|
54
|
+
audibleSinceMs = now
|
|
55
|
+
hasPlayed = true
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
mutating func audioStopped(atMs now: Int) {
|
|
59
|
+
guard let audibleSinceMs else { return }
|
|
60
|
+
self.audibleSinceMs = nil
|
|
61
|
+
guard playIntent else { return }
|
|
62
|
+
if silentSinceMs == nil || now - audibleSinceMs >= Self.audibleToEndSilenceMs {
|
|
63
|
+
silentSinceMs = now
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// Going offline restarts the first-connect clock, which only an online failure sets again.
|
|
68
|
+
mutating func onlineChanged(_ online: Bool) {
|
|
69
|
+
self.online = online
|
|
70
|
+
if !online { firstOnlineFailureMs = nil }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Every connection's end, whatever it delivered: the first one online starts the first-connect
|
|
74
|
+
/// clock of a Load that has not played.
|
|
75
|
+
mutating func connectionEnded(atMs now: Int) {
|
|
76
|
+
if online, firstOnlineFailureMs == nil { firstOnlineFailureMs = now }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Testing
|
|
3
|
+
|
|
4
|
+
@testable import AudioBrowserTestable
|
|
5
|
+
|
|
6
|
+
/// One step of a case in spec/retry-cases.json: an event at a time, and what `SilenceBudget` and
|
|
7
|
+
/// `ReconnectPacer` answer after it.
|
|
8
|
+
private struct RetryStep: Decodable {
|
|
9
|
+
enum Event: String, Decodable {
|
|
10
|
+
case load, intentUp, intentDown, audioStarts, audioStops, offline, online, ended
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
enum Delivered: String, Decodable { case audio, nothing }
|
|
14
|
+
|
|
15
|
+
let at: Int
|
|
16
|
+
let event: Event
|
|
17
|
+
let delivered: Delivered?
|
|
18
|
+
let startedAt: Int?
|
|
19
|
+
let deadline: Int?
|
|
20
|
+
let wait: ReconnectWait?
|
|
21
|
+
|
|
22
|
+
private static let keys: Set = ["at", "event", "delivered", "startedAt", "deadline", "wait"]
|
|
23
|
+
|
|
24
|
+
/// Strict, so a misspelt or missing key fails the case instead of dropping an assertion.
|
|
25
|
+
init(from decoder: Decoder) throws {
|
|
26
|
+
let c = try strictContainer(decoder, keys: Self.keys)
|
|
27
|
+
func fail(_ message: String) -> DecodingError {
|
|
28
|
+
.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: message))
|
|
29
|
+
}
|
|
30
|
+
at = try c.decode(Int.self, forKey: Key(stringValue: "at"))
|
|
31
|
+
event = try c.decode(Event.self, forKey: Key(stringValue: "event"))
|
|
32
|
+
delivered = try c.decodeIfPresent(Delivered.self, forKey: Key(stringValue: "delivered"))
|
|
33
|
+
startedAt = try c.decodeIfPresent(Int.self, forKey: Key(stringValue: "startedAt"))
|
|
34
|
+
let deadlineKey = Key(stringValue: "deadline"), waitKey = Key(stringValue: "wait")
|
|
35
|
+
guard c.contains(deadlineKey) else { throw fail("at \(at): every step states its deadline") }
|
|
36
|
+
deadline = try c.decodeNil(forKey: deadlineKey) ? nil : c.decode(Int.self, forKey: deadlineKey)
|
|
37
|
+
if !c.contains(waitKey) {
|
|
38
|
+
wait = nil
|
|
39
|
+
} else if let ms = try? c.decode(Int.self, forKey: waitKey) {
|
|
40
|
+
wait = .after(ms: ms)
|
|
41
|
+
} else {
|
|
42
|
+
wait = switch try c.decode(String.self, forKey: waitKey) {
|
|
43
|
+
case "online": .untilOnline
|
|
44
|
+
case "giveUp": .giveUp
|
|
45
|
+
case let other: throw fail("at \(at): unknown wait \(other)")
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if event == .ended, delivered == nil || startedAt == nil || wait == nil {
|
|
49
|
+
throw fail("at \(at): an end states what it delivered, when it started and the wait")
|
|
50
|
+
}
|
|
51
|
+
if let startedAt, startedAt > at { throw fail("at \(at): started after it ended") }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private struct Key: CodingKey {
|
|
56
|
+
let stringValue: String
|
|
57
|
+
init(stringValue: String) { self.stringValue = stringValue }
|
|
58
|
+
var intValue: Int? { nil }
|
|
59
|
+
init?(intValue _: Int) { nil }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Fails on a key outside `keys`, so a misspelt one is not silently ignored.
|
|
63
|
+
private func strictContainer(_ decoder: Decoder, keys: Set<String>) throws -> KeyedDecodingContainer<Key> {
|
|
64
|
+
let c = try decoder.container(keyedBy: Key.self)
|
|
65
|
+
if let unknown = c.allKeys.first(where: { !keys.contains($0.stringValue) }) {
|
|
66
|
+
throw DecodingError.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: "unknown key \(unknown.stringValue)"))
|
|
67
|
+
}
|
|
68
|
+
return c
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private struct RetryCase: Decodable, CustomTestStringConvertible {
|
|
72
|
+
let name: String
|
|
73
|
+
let maxRetries: Int?
|
|
74
|
+
let recoveryMs: Int?
|
|
75
|
+
let firstConnectMs: Int?
|
|
76
|
+
let steps: [RetryStep]
|
|
77
|
+
|
|
78
|
+
var testDescription: String { name }
|
|
79
|
+
|
|
80
|
+
init(from decoder: Decoder) throws {
|
|
81
|
+
let c = try strictContainer(decoder, keys: ["name", "maxRetries", "recoveryMs", "firstConnectMs", "steps"])
|
|
82
|
+
name = try c.decode(String.self, forKey: Key(stringValue: "name"))
|
|
83
|
+
maxRetries = try c.decodeIfPresent(Int.self, forKey: Key(stringValue: "maxRetries"))
|
|
84
|
+
recoveryMs = try c.decodeIfPresent(Int.self, forKey: Key(stringValue: "recoveryMs"))
|
|
85
|
+
firstConnectMs = try c.decodeIfPresent(Int.self, forKey: Key(stringValue: "firstConnectMs"))
|
|
86
|
+
steps = try c.decode([RetryStep].self, forKey: Key(stringValue: "steps"))
|
|
87
|
+
if steps.isEmpty {
|
|
88
|
+
throw DecodingError.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: "\(name): no steps"))
|
|
89
|
+
}
|
|
90
|
+
if zip(steps, steps.dropFirst()).contains(where: { $0.at > $1.at }) {
|
|
91
|
+
throw DecodingError.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: "\(name): time runs backwards"))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private let loadedCases = Result<[RetryCase], Error> {
|
|
97
|
+
let url = URL(fileURLWithPath: #filePath)
|
|
98
|
+
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
|
99
|
+
.appendingPathComponent("spec/retry-cases.json")
|
|
100
|
+
struct File: Decodable {
|
|
101
|
+
let cases: [RetryCase]
|
|
102
|
+
init(from decoder: Decoder) throws {
|
|
103
|
+
cases = try strictContainer(decoder, keys: ["about", "cases"]).decode([RetryCase].self, forKey: Key(stringValue: "cases"))
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return try JSONDecoder().decode(File.self, from: Data(contentsOf: url)).cases
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
@Suite("spec/retry-cases.json")
|
|
110
|
+
struct RetryCaseTests {
|
|
111
|
+
@Test func theCaseFileLoads() throws {
|
|
112
|
+
#expect(try !loadedCases.get().isEmpty)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@Test(arguments: (try? loadedCases.get()) ?? [])
|
|
116
|
+
fileprivate func runs(_ retryCase: RetryCase) throws {
|
|
117
|
+
var budget = SilenceBudget(online: true)
|
|
118
|
+
if let recoveryMs = retryCase.recoveryMs { budget.recoveryMs = recoveryMs }
|
|
119
|
+
if let firstConnectMs = retryCase.firstConnectMs { budget.firstConnectMs = firstConnectMs }
|
|
120
|
+
var pacer = ReconnectPacer(maxRetries: retryCase.maxRetries, online: true)
|
|
121
|
+
for step in retryCase.steps {
|
|
122
|
+
switch step.event {
|
|
123
|
+
case .load:
|
|
124
|
+
budget.loadStarted(atMs: step.at)
|
|
125
|
+
pacer.reset()
|
|
126
|
+
case .intentUp, .intentDown:
|
|
127
|
+
budget.playIntentChanged(step.event == .intentUp, atMs: step.at)
|
|
128
|
+
pacer.playIntentChanged(step.event == .intentUp)
|
|
129
|
+
case .audioStarts: budget.audioStarted(atMs: step.at)
|
|
130
|
+
case .audioStops: budget.audioStopped(atMs: step.at)
|
|
131
|
+
case .offline, .online:
|
|
132
|
+
budget.onlineChanged(step.event == .online)
|
|
133
|
+
pacer.onlineChanged(step.event == .online)
|
|
134
|
+
case .ended:
|
|
135
|
+
let delivered = try #require(step.delivered)
|
|
136
|
+
let startedAt = try #require(step.startedAt)
|
|
137
|
+
budget.connectionEnded(atMs: step.at)
|
|
138
|
+
pacer.connectionEnded(deliveredAudio: delivered == .audio, startedAtMs: startedAt, atMs: step.at)
|
|
139
|
+
}
|
|
140
|
+
#expect(budget.deadlineMs == step.deadline, "deadline at \(step.at) (\(step.event))")
|
|
141
|
+
if let wait = step.wait {
|
|
142
|
+
#expect(pacer.wait(atMs: step.at) == wait, "wait at \(step.at) (\(step.event))")
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|