Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Dissolve one track into the next, and follow the other devices

Leloniof574057f22bb
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index bda750f..f108121 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -260,6 +260,10 @@ val cargoBuild by tasks.registering(Exec::class) {
// Gradle can skip this entirely when nothing in the crate changed.
inputs.dir(nativeDir.resolve("src"))
+ // The patched copies of librespot's own crates, which are compiled from
+ // here rather than fetched. Left out, a change to one of them was not a
+ // change to this task, and the build quietly shipped the previous library.
+ inputs.dir(nativeDir.resolve("vendor"))
inputs.file(nativeDir.resolve("Cargo.toml"))
inputs.file(nativeDir.resolve("Cargo.lock"))
outputs.dir(layout.projectDirectory.dir("src/main/jniLibs"))
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 5376f0c..6d2b254 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -33,6 +33,11 @@ class SquareApplication : Application() {
dev.lelonio.square.data.QualityStore(this)
}
+ /** How long one track dissolves into the next. */
+ val crossfade: dev.lelonio.square.data.CrossfadeStore by lazy {
+ dev.lelonio.square.data.CrossfadeStore(this)
+ }
+
/** What language the app is read in, and what the engine asks Spotify for. */
val language: LanguageStore by lazy { LanguageStore(this) }
diff --git a/app/src/main/java/dev/lelonio/square/data/CrossfadeStore.kt b/app/src/main/java/dev/lelonio/square/data/CrossfadeStore.kt
new file mode 100644
index 0000000..5a89b78
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/CrossfadeStore.kt
@@ -0,0 +1,52 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * How long one track dissolves into the next, in seconds.
+ *
+ * Fixed steps rather than a free slider: the difference between six seconds and
+ * seven is not something anyone can hear, and a list of choices says what the
+ * setting is for without having to be dragged to find out.
+ *
+ * Zero is off, and off is the same code path as before crossfading existed:
+ * the player is told a duration of zero and behaves exactly as upstream does.
+ */
+val CrossfadeSteps = listOf(0, 3, 6, 9, 12)
+
+/** What a fresh install gets. Long enough to hear, short enough to stay out of the way. */
+const val CROSSFADE_DEFAULT_SECONDS = 6
+
+class CrossfadeStore(context: Context) {
+
+ private val prefs = context.applicationContext
+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val _seconds = MutableStateFlow(
+ prefs.getInt(KEY_SECONDS, CROSSFADE_DEFAULT_SECONDS),
+ )
+ val seconds: StateFlow<Int> = _seconds.asStateFlow()
+
+ fun set(seconds: Int) {
+ if (seconds == _seconds.value) return
+ _seconds.value = seconds
+ prefs.edit().putInt(KEY_SECONDS, seconds).apply()
+ }
+
+ /**
+ * What the engine is started with.
+ *
+ * Read when a player is built rather than watched, like the bitrate: the
+ * player owns its configuration for its whole life, so changing this means
+ * building another one.
+ */
+ fun durationMs(): Int = _seconds.value * 1000
+
+ private companion object {
+ const val FILE_NAME = "square_crossfade"
+ const val KEY_SECONDS = "seconds"
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index d5ad61b..7bac56c 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -27,6 +27,19 @@ class PreferencesStore(context: Context) {
prefs.edit().putString(KEY_TRACK_SORT, value).apply()
}
+ /**
+ * This phone's Connect id, made once and kept for good.
+ *
+ * A uuid rather than anything drawn from the hardware: it identifies an
+ * install to one account's device list and nothing else, and there is no
+ * reason for it to survive the app being removed.
+ */
+ fun deviceId(): String = prefs.getString(KEY_DEVICE_ID, null) ?: run {
+ val id = java.util.UUID.randomUUID().toString()
+ prefs.edit().putString(KEY_DEVICE_ID, id).apply()
+ id
+ }
+
private val _onboarded = MutableStateFlow(prefs.getBoolean(KEY_ONBOARDED, false))
/**
@@ -106,6 +119,7 @@ class PreferencesStore(context: Context) {
private companion object {
const val FILE_NAME = "square_preferences"
const val KEY_TRACK_SORT = "track_sort"
+ const val KEY_DEVICE_ID = "device_id"
const val KEY_ONBOARDED = "onboarded"
const val KEY_PLAYER_OPEN = "player_open"
const val KEY_BACKEND = "backend"
diff --git a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
new file mode 100644
index 0000000..67c6929
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
@@ -0,0 +1,316 @@
+package dev.lelonio.square.data
+
+import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * What the account is playing on its other devices.
+ *
+ * Square is a Connect device, so it is already told: Spotify pushes a cluster
+ * update to every device of an account whenever anything changes anywhere, and
+ * the engine surfaces one as an event. Nothing here polls, and nothing here
+ * asks the Web API.
+ *
+ * An object rather than something injected, for the same reason the engine is
+ * one: there is a single session behind it, and the parts that care about this
+ * are spread from the service to the player screen.
+ */
+object RemoteConnect {
+
+ /** This device's own id, read once the engine has a session. */
+ private var ownId: String = ""
+
+ private val _playback = MutableStateFlow<RemotePlayback?>(null)
+
+ /**
+ * The account's playback when it is happening somewhere else, null when it
+ * is happening here or not at all.
+ *
+ * Deliberately null for this device: what plays here is the app's own
+ * player, and two sources for one truth is how a seek bar ends up fighting
+ * itself.
+ */
+ val playback: StateFlow<RemotePlayback?> = _playback.asStateFlow()
+
+ private val _elsewhere = MutableStateFlow(false)
+
+ /**
+ * Whether the account's playback belongs to another device.
+ *
+ * The engine's own answer, kept here so the screen can read it without a
+ * JNI call on every frame. This is the one fact everything else is decided
+ * from, which is how go-librespot is built: one boolean, and no guessing
+ * around it.
+ */
+ val elsewhereActive: StateFlow<Boolean> = _elsewhere.asStateFlow()
+
+ private val _here = MutableStateFlow<RemotePlayback?>(null)
+
+ /**
+ * The account's playback when this phone is the one doing it.
+ *
+ * The mirror image of [playback], and it exists because being handed
+ * playback is something that happens *to* this app: another client presses
+ * "Square" in its own device list, Spotify sends the engine a transfer, and
+ * the engine starts playing a track the app knows nothing about. This is
+ * where it finds out what it is playing and, more importantly, what queue it
+ * came from.
+ */
+ val here: StateFlow<RemotePlayback?> = _here.asStateFlow()
+
+ private val _devices = MutableStateFlow<List<RemoteDevice>>(emptyList())
+
+ /** Everything the account can play on, this phone included. */
+ val devices: StateFlow<List<RemoteDevice>> = _devices.asStateFlow()
+
+ /** Whether an id is this phone's own. */
+ fun isThisPhone(deviceId: String): Boolean {
+ if (ownId.isEmpty()) ownId = NativeBridge.deviceId()
+ return deviceId.isNotEmpty() && deviceId == ownId
+ }
+
+ /** Called on every `cluster` event from the engine. */
+ fun refresh() {
+ if (ownId.isEmpty()) {
+ ownId = NativeBridge.deviceId()
+ android.util.Log.i(TAG, "this device is $ownId")
+ }
+
+ _devices.value = runCatching { parseDevices(NativeBridge.remoteDevices()) }
+ .getOrDefault(emptyList())
+
+ val state = runCatching { JSONObject(NativeBridge.remoteState()) }.getOrNull()
+ val active = state?.optString("activeDevice").orEmpty()
+ val playback = state?.let { read(it, active) }?.filled()
+
+ // Asked of the engine, not worked out from the id in the update.
+ //
+ // The two disagree exactly when it matters: after playback is handed to
+ // this phone it starts playing at once, while the account goes on naming
+ // the device it came from until that device lets go. Comparing ids meant
+ // the app believed the account and not its own ears.
+ val elsewhere = NativeBridge.playbackElsewhere
+ _elsewhere.value = elsewhere
+ _playback.value = playback?.takeIf { elsewhere }
+ _here.value = playback?.takeIf { !elsewhere && active.isNotEmpty() }
+ }
+
+ private fun read(state: JSONObject, active: String): RemotePlayback? {
+ if (active.isEmpty()) return null
+ return RemotePlayback(
+ deviceId = active,
+ deviceName = state.optString("deviceName"),
+ uri = state.optString("uri"),
+ title = state.optString("title"),
+ artist = state.optString("artist"),
+ album = state.optString("album"),
+ coverUri = state.optString("coverUri"),
+ contextUri = state.optString("contextUri"),
+ positionMs = state.optLong("positionMs"),
+ durationMs = state.optLong("durationMs"),
+ playing = state.optBoolean("playing"),
+ shuffle = state.optBoolean("shuffle"),
+ repeatContext = state.optBoolean("repeatContext"),
+ repeatTrack = state.optBoolean("repeatTrack"),
+ )
+ }
+
+ /**
+ * Replaces what is known about the playback elsewhere, with more of it.
+ *
+ * The cluster carries a track's title and artist as metadata beside the
+ * uri, and whether it carries them at all is up to whichever client is
+ * playing: some publish everything, some publish the uri and little else.
+ * The uri is always there, so the rest can be looked up; this is where the
+ * answer comes back.
+ */
+ fun describe(playback: RemotePlayback) {
+ known[playback.uri] = playback
+ if (_playback.value?.uri != playback.uri) return
+ _playback.value = playback
+ }
+
+ /**
+ * Titles, artists and covers looked up for tracks the cluster named without
+ * describing, kept by uri.
+ *
+ * Remembered here rather than only where the answer was needed, because
+ * every cluster update rebuilds the state from what the other device
+ * published: without this the notification kept the filled-in version while
+ * the screen, reading the same flow a moment later, went back to a song
+ * with no artist.
+ */
+ private val known = mutableMapOf<String, RemotePlayback>()
+
+ /** What was learned about this track earlier, over what arrived now. */
+ private fun RemotePlayback.filled(): RemotePlayback {
+ val earlier = known[uri] ?: return this
+ return copy(
+ title = title.ifEmpty { earlier.title },
+ artist = artist.ifEmpty { earlier.artist },
+ album = album.ifEmpty { earlier.album },
+ coverUri = coverUri.ifEmpty { earlier.coverUri },
+ )
+ }
+
+ /** Forgets everything. For a session ending, where none of it is true any more. */
+ fun clear() {
+ _elsewhere.value = false
+ _playback.value = null
+ _here.value = null
+ _devices.value = emptyList()
+ }
+
+ private fun parseDevices(json: String): List<RemoteDevice> {
+ val array = JSONArray(json)
+ return (0 until array.length()).map { index ->
+ val device = array.getJSONObject(index)
+ val id = device.optString("id")
+ RemoteDevice(
+ id = id,
+ name = device.optString("name"),
+ type = device.optString("type"),
+ volume = device.optInt("volume"),
+ active = device.optBoolean("active"),
+ isThisPhone = id == ownId,
+ )
+ }
+ }
+
+ // --- Commands ---
+ //
+ // Worded the way Spotify's own clients word them, because that is what the
+ // device on the other end is written to obey. Each one blocks on a request
+ // to the access point, so none of them may be called from the main thread.
+
+ fun play(deviceId: String) = command(deviceId, "resume")
+
+ fun pause(deviceId: String) = command(deviceId, "pause")
+
+ fun next(deviceId: String) = command(deviceId, "skip_next")
+
+ fun previous(deviceId: String) = command(deviceId, "skip_prev")
+
+ fun seek(deviceId: String, positionMs: Long) =
+ send(deviceId, """{"command":{"endpoint":"seek_to","value":$positionMs}}""")
+
+ fun setShuffle(deviceId: String, shuffle: Boolean) =
+ send(deviceId, """{"command":{"endpoint":"set_shuffling_context","value":$shuffle}}""")
+
+ fun setRepeat(deviceId: String, context: Boolean, track: Boolean) {
+ send(
+ deviceId,
+ """{"command":{"endpoint":"set_options","repeating_context":$context,""" +
+ """"repeating_track":$track}}""",
+ )
+ }
+
+ fun setVolume(deviceId: String, volume: Int) {
+ runCatching { NativeBridge.remoteVolume(deviceId, volume) }
+ .onFailure { android.util.Log.w(TAG, "volume did not reach $deviceId", it) }
+ }
+
+ /**
+ * Moves playback to another device, this phone included.
+ *
+ * The command goes *to* the device that should take over, which is how the
+ * protocol reads: a device is told to take the account's playback, not told
+ * to give it away.
+ */
+ fun transferTo(deviceId: String) {
+ if (deviceId == ownId) {
+ // Coming back here is not a request to the server. A device cannot
+ // address a command to itself: it goes out to the access point and
+ // comes back refused, which is why choosing Square in the list did
+ // nothing at all.
+ runCatching { NativeBridge.takeOver() }
+ .onFailure { android.util.Log.w(TAG, "could not take playback back", it) }
+ return
+ }
+ send(
+ deviceId,
+ """{"command":{"endpoint":"transfer","transfer_options":{"restore_paused":"restore"}}}""",
+ )
+ }
+
+ private fun command(deviceId: String, endpoint: String) =
+ send(deviceId, """{"command":{"endpoint":"$endpoint"}}""")
+
+ private fun send(deviceId: String, body: String) {
+ runCatching { NativeBridge.remoteCommand(deviceId, body) }
+ .onFailure { android.util.Log.w(TAG, "command did not reach $deviceId: $body", it) }
+ }
+
+ private const val TAG = "RemoteConnect"
+}
+
+/** Playback happening on another of the account's devices. */
+data class RemotePlayback(
+ val deviceId: String,
+ val deviceName: String,
+ val uri: String,
+ val title: String,
+ val artist: String,
+ val album: String,
+ /**
+ * The cover as the cluster carries it, which is a plain https URL to
+ * i.scdn.co and not the `spotify:image:` form the rest of the protocol uses.
+ */
+ val coverUri: String,
+ /** The playlist or album the other device is playing from, if any. */
+ val contextUri: String,
+ val positionMs: Long,
+ val durationMs: Long,
+ val playing: Boolean,
+ val shuffle: Boolean,
+ val repeatContext: Boolean,
+ val repeatTrack: Boolean,
+) {
+ /**
+ * The cover as something that can actually be fetched.
+ *
+ * The cluster sends a URL already. It was being treated as a
+ * `spotify:image:` uri and cut at the last colon, which turned
+ * `https://i.scdn.co/…` into `//i.scdn.co/…` and fetched nothing: the
+ * artwork went missing everywhere the moment another device took over.
+ * Both forms are accepted, since only one of them is documented anywhere
+ * and neither is promised.
+ */
+ val coverUrl: String
+ get() = when {
+ coverUri.isEmpty() -> ""
+ coverUri.startsWith("http") -> coverUri
+ else -> "https://i.scdn.co/image/${coverUri.substringAfterLast(':')}"
+ }
+
+ /**
+ * The playlist or album behind this playback, or null when there is none.
+ *
+ * `spotify:web-api` is not one. It is the placeholder librespot publishes
+ * for a queue handed over as a bare list of track URIs, and asking Spotify
+ * to resolve it answers 400: it was taken for a playlist twice, once when
+ * bringing playback back to this phone and once when filling in a queue
+ * handed to it, and both simply failed.
+ */
+ val realContext: String?
+ get() = contextUri.takeIf { it.startsWith("spotify:") && it != WEB_API_CONTEXT }
+}
+
+/** What librespot publishes in place of a context it does not have. */
+const val WEB_API_CONTEXT = "spotify:web-api"
+
+/** One device the account can play on. */
+data class RemoteDevice(
+ val id: String,
+ val name: String,
+ /** librespot's own spelling of the device type: `Smartphone`, `Computer`. */
+ val type: String,
+ /** Raw 0..65535, as everywhere else in the protocol. */
+ val volume: Int,
+ val active: Boolean,
+ val isThisPhone: Boolean,
+)
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
index 79ea842..c204c03 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -151,6 +151,18 @@ interface SpotifyApi {
@PUT("v1/me/player")
suspend fun transferPlayback(@Body request: TransferRequestDto)
+ /**
+ * Resumes on a named device.
+ *
+ * The device is named rather than assumed. Spotify's play endpoint acts on
+ * "the active device", and just after a handover there is a moment where
+ * the account has not settled on one: the request then answers 404, whose
+ * message is the same for "device not found" and "nothing is active".
+ * Saying which device removes the question.
+ */
+ @PUT("v1/me/player/play")
+ suspend fun play(@Query("device_id") deviceId: String)
+
/**
* Appends tracks to a playlist. Needs `playlist-modify-private` for the
* user's own private playlists and `playlist-modify-public` for their
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index ec28ce3..f1cd267 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -61,6 +61,14 @@ object NativeBridge {
fun start(
clientId: String,
deviceName: String,
+ /**
+ * This phone's Connect id, the same on every launch.
+ *
+ * Chosen and kept by the app because librespot's own default is a fresh
+ * one per session, which shows the account a brand new device every time
+ * the engine starts.
+ */
+ deviceId: String,
accessToken: String,
credentialsDir: String,
cacheDir: String,
@@ -74,15 +82,23 @@ object NativeBridge {
* setting means starting a new engine.
*/
bitrateKbps: Int,
+ /**
+ * How long one track dissolves into the next, in milliseconds; zero is
+ * off. Fixed for the life of the engine for the same reason as the
+ * bitrate: it belongs to the player's configuration.
+ */
+ crossfadeMs: Int,
listener: NativeEvents,
) = nativeStart(
clientId,
deviceName,
+ deviceId,
accessToken,
credentialsDir,
cacheDir,
language,
bitrateKbps,
+ crossfadeMs,
listener,
)
@@ -153,6 +169,78 @@ object NativeBridge {
*/
fun reconnect() = nativeReconnect()
+ // --- The account's other devices ---
+ //
+ // Square is a Connect device, and this is the other half of the same
+ // protocol: what the official client does when it shows you a speaker
+ // playing in another room and lets you press pause on it.
+ //
+ // Nothing here is polled. Spotify pushes a cluster update to every device
+ // whenever anything changes, and the engine reports one as an event named
+ // "cluster"; these read what that update left behind.
+
+ /**
+ * Whether the account's playback belongs to another device right now.
+ *
+ * The one question that decides whether this app may touch the engine at
+ * all. go-librespot keeps the same answer as a single boolean it owns, and
+ * everything it does is gated on it; here it comes from the cluster, which
+ * is the same source by another road.
+ */
+ val playbackElsewhere: Boolean
+ get() = runCatching { nativePlaybackElsewhere() }.getOrDefault(false)
+
+ /**
+ * Republishes the queue as the playlist it came from.
+ *
+ * For the moment before playback is handed to another device: a queue sent
+ * as a bare list of URIs carries a context nobody else can resolve, and the
+ * device receiving it ends up with a queue that does not play. Blocking.
+ */
+ fun publishContext(positionMs: Int) = nativePublishContext(positionMs)
+
+ /**
+ * Starts playing here what another device was playing, at its position.
+ *
+ * One call, so the music moves before the queue behind it has been read:
+ * resolving a long playlist first is a second of silence in which the only
+ * honest thing the screen can say is nothing. Blocking.
+ */
+ fun resumeHere(contextUri: String, trackUri: String, positionMs: Int) =
+ nativeResumeHere(contextUri, trackUri, positionMs)
+
+ /**
+ * Takes the account's playback for this device.
+ *
+ * The picker's own row. A transfer is addressed from one device to another
+ * through the server, and this phone cannot address itself that way: the
+ * request goes out and comes back refused. Activating does it directly.
+ */
+ fun takeOver() = nativeTakeOver()
+
+ /** This device's own Connect id, which is what says "here" rather than "there". */
+ fun deviceId(): String = runCatching { nativeDeviceId() }.getOrDefault("")
+
+ /** What the account is playing and where, as JSON; `{}` when nothing is. */
+ fun remoteState(): String = nativeRemoteState()
+
+ /** Every device the account can see, this one included, as a JSON array. */
+ fun remoteDevices(): String = nativeRemoteDevices()
+
+ /**
+ * Sends one command to another device.
+ *
+ * [body] is the JSON Spotify's own clients send, so the caller names the
+ * endpoint. Accepted for delivery is not obeyed: the device is what acts,
+ * and the cluster update that follows is what says it did.
+ *
+ * Blocking. Never call it from the main thread.
+ */
+ fun remoteCommand(deviceId: String, body: String) = nativeRemoteCommand(deviceId, body)
+
+ /** Volume in librespot's raw 0..65535 range, on another device. */
+ fun remoteVolume(deviceId: String, volume: Int) = nativeRemoteVolume(deviceId, volume)
+
fun shutdown() = nativeShutdown()
// --- Catalogue, served by the access point rather than api.spotify.com ---
@@ -201,11 +289,13 @@ object NativeBridge {
private external fun nativeStart(
clientId: String,
deviceName: String,
+ deviceId: String,
accessToken: String,
credentialsDir: String,
cacheDir: String,
language: String,
bitrateKbps: Int,
+ crossfadeMs: Int,
listener: NativeEvents,
)
@@ -230,6 +320,15 @@ object NativeBridge {
private external fun nativeIsConnected(): Boolean
private external fun nativeSpircLost(): Boolean
private external fun nativeReconnect()
+ private external fun nativePlaybackElsewhere(): Boolean
+ private external fun nativePublishContext(positionMs: Int): Boolean
+ private external fun nativeResumeHere(contextUri: String, trackUri: String, positionMs: Int)
+ private external fun nativeTakeOver()
+ private external fun nativeDeviceId(): String
+ private external fun nativeRemoteState(): String
+ private external fun nativeRemoteDevices(): String
+ private external fun nativeRemoteCommand(deviceId: String, body: String)
+ private external fun nativeRemoteVolume(deviceId: String, volume: Int)
private external fun nativeShutdown()
private external fun nativeUsername(): String
private external fun nativeCollectionUri(): String
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 17e3a77..5fe470b 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -148,17 +148,64 @@ class LibrespotPlayer(
private val handler = android.os.Handler(looper)
+ /**
+ * The other device's playback, when the account is playing on one.
+ *
+ * Mirrored into this player rather than drawn only by the app, because the
+ * notification and anything else holding a media controller read this and
+ * nothing else: a car head unit and the lock screen do not know the app has
+ * a second idea of what is playing. Fed by the service; see
+ * PlaybackService.
+ */
+ private var remote: dev.lelonio.square.data.RemotePlayback? = null
+
+ fun showRemote(playback: dev.lelonio.square.data.RemotePlayback?) {
+ if (released) return
+ val was = remote
+ remote = playback
+ if (was?.uri != playback?.uri) cachedPlaylist = null
+ invalidateState()
+ }
+
+ /**
+ * What the transport buttons act on: the other device, or this one.
+ *
+ * A command sent to the wrong end is worse than a command that fails, since
+ * it moves music the listener is not hearing.
+ */
+ private fun onRemote(what: String, command: (String) -> Unit): Boolean {
+ val target = remote ?: return false
+ Thread({
+ runCatching { command(target.deviceId) }
+ .onFailure { android.util.Log.w("SquarePlayer", "$what did not reach it", it) }
+ }, "square-remote").start()
+ return true
+ }
+
override fun getState(): State {
+ remote?.let { return remoteState(it) }
+
+ val items = queue.items
+
+ // Media3 refuses a playing state with nothing to play, and says so by
+ // throwing out of this method: "Empty playlist only allowed in
+ // STATE_IDLE or STATE_ENDED", on the main thread, taking the app with
+ // it. The two can come apart for a moment whenever the engine is
+ // playing something this side has not been told about yet, which is
+ // what taking playback back from another device does. Idle is the
+ // honest answer while the queue is empty, and the next event, once the
+ // queue has arrived, corrects it.
+ val reportedState = if (items.isEmpty()) Player.STATE_IDLE else playbackState
+
val builder = State.Builder()
.setAvailableCommands(COMMANDS)
- .setPlaybackState(playbackState)
+ .setPlaybackState(reportedState)
.setPlayWhenReady(playWhenReady, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST)
.setContentPositionMs(positionMs)
.setRepeatMode(repeatMode)
.setShuffleModeEnabled(shuffleEnabled)
.setPlaybackParameters(playbackParameters)
- val items = queue.items
if (items.isNotEmpty()) {
builder.setPlaylist(playlistSnapshot())
.setCurrentMediaItemIndex(queue.currentIndex.coerceIn(0, items.lastIndex))
@@ -175,6 +222,56 @@ class LibrespotPlayer(
* change — enough GC churn to make the audio stutter. The cache is dropped
* by [onQueueChanged] at the few points that mutate the queue.
*/
+ /**
+ * The same shape of state, describing a device in another room.
+ *
+ * One item rather than the whole queue: the account publishes what is
+ * playing, not the list behind it, and inventing the rest would be inventing
+ * a queue this app cannot skip through anyway.
+ */
+ private fun remoteState(playback: dev.lelonio.square.data.RemotePlayback): State {
+ val item = cachedPlaylist?.firstOrNull() ?: MediaItemData.Builder(playback.uri)
+ .setMediaItem(
+ MediaItem.Builder()
+ .setMediaId(playback.uri)
+ .setUri(playback.uri)
+ .setMediaMetadata(
+ MediaMetadata.Builder()
+ .setTitle(playback.title)
+ .setArtist(playback.artist)
+ .setAlbumTitle(playback.album)
+ .setArtworkUri(
+ playback.coverUrl.takeIf { it.isNotEmpty() }
+ ?.let(android.net.Uri::parse),
+ )
+ .setIsBrowsable(false)
+ .setIsPlayable(true)
+ .build(),
+ )
+ .build(),
+ )
+ .setDurationUs(playback.durationMs * 1000)
+ .build()
+ .also { cachedPlaylist = listOf(it) }
+
+ return State.Builder()
+ .setAvailableCommands(COMMANDS)
+ .setPlaybackState(Player.STATE_READY)
+ .setPlayWhenReady(playback.playing, Player.PLAY_WHEN_READY_CHANGE_REASON_REMOTE)
+ .setContentPositionMs(playback.positionMs)
+ .setRepeatMode(
+ when {
+ playback.repeatTrack -> Player.REPEAT_MODE_ONE
+ playback.repeatContext -> Player.REPEAT_MODE_ALL
+ else -> Player.REPEAT_MODE_OFF
+ },
+ )
+ .setShuffleModeEnabled(playback.shuffle)
+ .setPlaylist(listOf(item))
+ .setCurrentMediaItemIndex(0)
+ .build()
+ }
+
private fun playlistSnapshot(): List<MediaItemData> =
cachedPlaylist ?: queue.items
.mapIndexed(::toMediaItemData)
@@ -341,6 +438,16 @@ class LibrespotPlayer(
* a load at the target, which is one request instead of a dozen.
*/
private fun requestSkipTo(index: Int, positionMs: Long) {
+ // A skip on a device in another room is a skip there; the index this
+ // side would step through means nothing to it.
+ if (remote != null) {
+ val forward = index >= queue.currentIndex
+ onRemote(if (forward) "next" else "previous") { id ->
+ if (forward) dev.lelonio.square.data.RemoteConnect.next(id) else dev.lelonio.square.data.RemoteConnect.previous(id)
+ }
+ return
+ }
+
queue.currentIndex = index.coerceIn(0, maxOf(0, queue.items.lastIndex))
// A skip starts the new track at its beginning. Media3 sends
// C.TIME_UNSET for "wherever it starts", which as a number is very
@@ -434,6 +541,16 @@ class LibrespotPlayer(
}
override fun handleSetPlayWhenReady(playWhenReady: Boolean): ListenableFuture<*> {
+ // The buttons follow the music. Everything below drives this phone's
+ // own engine, which is silent while another device is playing.
+ val wanted = playWhenReady
+ if (onRemote(if (wanted) "play" else "pause") { id ->
+ if (wanted) dev.lelonio.square.data.RemoteConnect.play(id) else dev.lelonio.square.data.RemoteConnect.pause(id)
+ }
+ ) {
+ return Futures.immediateVoidFuture()
+ }
+
if (playWhenReady) {
// Refusing focus means something else owns the output — starting
// anyway would talk over it.
@@ -484,6 +601,23 @@ class LibrespotPlayer(
newPositionMs: Long,
seekCommand: @Player.Command Int,
): ListenableFuture<*> {
+ // Seeking, skipping and stopping all belong to whichever device is
+ // playing; see onRemote.
+ if (remote != null) {
+ when (seekCommand) {
+ Player.COMMAND_SEEK_TO_NEXT,
+ Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
+ -> onRemote("next", dev.lelonio.square.data.RemoteConnect::next)
+
+ Player.COMMAND_SEEK_TO_PREVIOUS,
+ Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
+ -> onRemote("previous", dev.lelonio.square.data.RemoteConnect::previous)
+
+ else -> onRemote("seek") { id -> dev.lelonio.square.data.RemoteConnect.seek(id, newPositionMs) }
+ }
+ return Futures.immediateVoidFuture()
+ }
+
queue.items.getOrNull(mediaItemIndex) ?: return Futures.immediateVoidFuture()
if (mediaItemIndex == queue.currentIndex && !skipPending) {
@@ -503,6 +637,16 @@ class LibrespotPlayer(
startIndex: Int,
startPositionMs: Long,
): ListenableFuture<*> {
+ // Choosing a track here is the listener asking for this phone, and it
+ // is the only moment in the app where taking the account's playback is
+ // what they meant. Everything else that reaches the engine leaves the
+ // other device alone; see engine.rs.
+ if (runCatching { NativeBridge.playbackElsewhere }.getOrDefault(false)) {
+ android.util.Log.i("SquarePlayer", "taking playback back for this device")
+ runCatching { NativeBridge.takeOver() }
+ .onFailure { android.util.Log.w("SquarePlayer", "could not take over", it) }
+ }
+
queue.replaceFromMediaItems(mediaItems, startIndex)
// A new queue: whatever the engine was playing is no longer at any
// index of this one.
@@ -655,6 +799,45 @@ class LibrespotPlayer(
invalidateState()
}
+ /**
+ * Takes on a queue the engine is already playing.
+ *
+ * The other half of Connect, and the one this app was missing. Another
+ * client can hand playback to this phone from its own device list: Spotify
+ * sends the engine a transfer, the engine starts playing, and nothing here
+ * is asked or told. What was left was a track playing with an empty queue,
+ * so there was nothing after it and nothing on screen.
+ *
+ * Unlike [restore] this loads nothing. The engine already has the queue and
+ * the position; the point is only that this side stops disagreeing.
+ */
+ fun adopt(
+ tracks: List<PlayQueue.Track>,
+ index: Int,
+ positionMs: Long,
+ contextUri: String?,
+ contextLabel: String,
+ playing: Boolean,
+ ) {
+ if (tracks.isEmpty()) return
+ android.util.Log.i("SquarePlayer", "adopting ${tracks.size} tracks at $index")
+
+ queue.restoreContext(contextUri, contextUri != null, contextLabel)
+ queue.replace(tracks, 0)
+ queue.currentIndex = index.coerceIn(0, queue.items.lastIndex)
+ // The engine is playing this queue; it is this side that has just
+ // learned of it.
+ engineIndex = queue.currentIndex
+ engineQueueStale = false
+
+ this.positionMs = positionMs
+ playWhenReady = playing
+ wantPlay = playing
+ playbackState = Player.STATE_READY
+ onQueueChanged()
+ invalidateState()
+ }
+
/**
* Reorders the queue rather than only recording a flag; see [PlayQueue].
*/
@@ -662,10 +845,19 @@ class LibrespotPlayer(
shuffleEnabled = shuffleModeEnabled
queue.setShuffled(shuffleModeEnabled)
onQueueChanged()
- // Told to the engine as well: shuffle is part of the published Connect
- // state, and a device whose local order disagrees with what the account
- // shows is worse than one that cannot shuffle at all.
- runCatching { NativeBridge.setShuffle(shuffleModeEnabled) }
+ // Deliberately not passed on to the Connect device, and its own shuffle
+ // is held off instead.
+ //
+ // Both sides can shuffle, and both doing it is one shuffle too many: the
+ // queue on screen is this list in this order, and the device was being
+ // handed that list and then reordering it again for itself. A track put
+ // up next landed somewhere else entirely, the engine played whatever its
+ // own permutation said, and what came back looked like the queue being
+ // thrown away and rebuilt.
+ //
+ // The order on screen is the one the user arranged, so it wins. The cost
+ // is that the account shows this device as not shuffling.
+ runCatching { NativeBridge.setShuffle(false) }
invalidateState()
return Futures.immediateVoidFuture()
}
@@ -787,12 +979,39 @@ class LibrespotPlayer(
// own next one and the queued track would never be heard. Taking
// over reloads the queue, which is the only way to tell Spirc about
// an insertion.
+ // Something changed on another of the account's devices. Nothing
+ // here plays, so nothing here has to react: the state is read and
+ // published, and whoever is showing it redraws.
+ "cluster" -> {
+ dev.lelonio.square.data.RemoteConnect.refresh()
+ // And again shortly after.
+ //
+ // A handover is two facts arriving separately: the account says
+ // which device is active, and the engine works out whether that
+ // is this one. They settle a moment apart, and whichever is
+ // read first leaves the screen describing the wrong device
+ // until something else happens to change it, which can be
+ // never. The second look costs two reads of memory.
+ handler.postDelayed({ dev.lelonio.square.data.RemoteConnect.refresh() }, 700)
+ handler.postDelayed({ dev.lelonio.square.data.RemoteConnect.refresh() }, 2_000)
+ return
+ }
+
"end_of_track", "unavailable" -> {
takeOverForQueued()
return
}
else -> return
}
+ // Whether the music is here or somewhere else can change without any
+ // word from the account: taking playback back starts this player, and
+ // the cluster may say nothing for a minute afterwards. The screen was
+ // deciding with an answer from before the handover, which is how a
+ // pause pressed here went out to a laptop.
+ if (type == "playing" || type == "paused" || type == "stopped") {
+ dev.lelonio.square.data.RemoteConnect.refresh()
+ }
+
invalidateState()
}
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 1bf5b46..a36ace2 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -63,6 +63,7 @@ class PlaybackService : MediaLibraryService() {
private lateinit var playbackStore: PlaybackStore
private lateinit var quality: dev.lelonio.square.data.QualityStore
+ private lateinit var crossfade: dev.lelonio.square.data.CrossfadeStore
private var saveJob: Job? = null
private val playbackHost = object : dev.lelonio.square.backend.PlaybackHost {
@@ -76,6 +77,7 @@ class PlaybackService : MediaLibraryService() {
playbackStore = PlaybackStore(this)
container = application as dev.lelonio.square.SquareApplication
quality = container.quality
+ crossfade = container.crossfade
player = buildPlayer(container.preferences.backend.value)
session = MediaLibrarySession.Builder(this, player, MediaBrowseTree(this, scope))
@@ -121,6 +123,34 @@ class PlaybackService : MediaLibraryService() {
quality.quality.drop(1).collect { restartForQuality() }
}
+ // The crossfade is part of the same configuration and just as fixed, so
+ // it takes the same road: a new engine, with the queue put back where
+ // it was.
+ scope.launch {
+ crossfade.seconds.drop(1).collect { rebuildEngine("crossfade") }
+ }
+
+ // Playback handed to this phone from another client's device list.
+ //
+ // The engine obeys that transfer on its own and starts playing, so the
+ // only thing missing is the queue: without it there is one track and
+ // nothing after it. Watched here rather than in the UI because the
+ // queue belongs to the service, and this has to work with no screen on.
+ scope.launch {
+ dev.lelonio.square.data.RemoteConnect.here.collect(::adoptRemoteQueue)
+ }
+
+ // Playback on another device, mirrored into this one's player.
+ //
+ // The notification, the lock screen and anything else holding a media
+ // controller read the player and nothing else, so without this they
+ // showed a stopped app while the account was playing in the next room.
+ scope.launch {
+ dev.lelonio.square.data.RemoteConnect.playback.collect { elsewhere ->
+ librespot?.showRemote(elsewhere?.let { describeRemote(it) })
+ }
+ }
+
// Same reasoning for the source itself: swapping backends is swapping
// the player under a live session, which only the service can do.
scope.launch {
@@ -228,6 +258,73 @@ class PlaybackService : MediaLibraryService() {
}
}
+ /**
+ * Fills in what the other device did not say about its track.
+ *
+ * Whether a client publishes a title and an artist beside the uri is up to
+ * that client: the web player does, the desktop app does not always, and
+ * what reached the notification then was a song with no name. The uri is
+ * always there, and this app can read a track from a uri, so it does.
+ */
+ private suspend fun describeRemote(
+ playback: dev.lelonio.square.data.RemotePlayback,
+ ): dev.lelonio.square.data.RemotePlayback {
+ if (playback.title.isNotEmpty() && playback.artist.isNotEmpty()) return playback
+ val track = runCatching { container.activeBackend.tracksOf(playback.uri).firstOrNull() }
+ .onFailure { android.util.Log.w(TAG, "cannot read ${playback.uri}: $it") }
+ .getOrNull() ?: return playback
+
+ val filled = playback.copy(
+ title = playback.title.ifEmpty { track.name },
+ artist = playback.artist.ifEmpty { track.artist },
+ album = playback.album.ifEmpty { track.album },
+ coverUri = playback.coverUri.ifEmpty { track.artworkUrl.orEmpty() },
+ )
+ // Kept there rather than here: every part of the app reads that state,
+ // and the next cluster update rebuilds it from what the other device
+ // published, which is what left this out in the first place.
+ dev.lelonio.square.data.RemoteConnect.describe(filled)
+ return filled
+ }
+
+ /** The queue last taken on, so the same transfer is not resolved twice. */
+ private var adoptedContext: String? = null
+
+ /**
+ * Fills in the queue behind a track the engine was handed.
+ *
+ * Only when this side does not already know the track: playing from Square
+ * puts it in the queue first, and re-resolving the context then would throw
+ * away the order the listener is looking at.
+ */
+ private suspend fun adoptRemoteQueue(here: dev.lelonio.square.data.RemotePlayback?) {
+ val engine = librespot ?: return
+ if (here == null || here.uri.isEmpty()) return
+ if (queue?.items.orEmpty().any { it.uri == here.uri }) return
+
+ val key = "${here.contextUri}|${here.uri}"
+ if (adoptedContext == key) return
+ adoptedContext = key
+
+ val tracks = runCatching {
+ container.activeBackend.tracksOf(here.realContext ?: here.uri)
+ }
+ .onFailure { android.util.Log.w(TAG, "handed a queue we cannot read: $it") }
+ .getOrDefault(emptyList())
+
+ val index = tracks.indexOfFirst { it.uri == here.uri }
+ if (tracks.isEmpty()) return
+
+ engine.adopt(
+ tracks = tracks.map(::toQueueTrack),
+ index = index.coerceAtLeast(0),
+ positionMs = here.positionMs,
+ contextUri = here.realContext,
+ contextLabel = "",
+ playing = here.playing,
+ )
+ }
+
/**
* Rebuilds the engine so a new bitrate takes effect.
*
@@ -319,6 +416,9 @@ class PlaybackService : MediaLibraryService() {
// access point rejects every catalogue call.
clientId = SpotifyOAuth.CLIENT_ID,
deviceName = android.os.Build.MODEL ?: "Android",
+ // Kept across launches, so the account sees this phone as
+ // one device rather than a new one every time.
+ deviceId = container.preferences.deviceId(),
accessToken = accessToken,
// filesDir, not cacheDir: credentials must survive the
// system reclaiming cache space, or the next launch loses
@@ -331,6 +431,8 @@ class PlaybackService : MediaLibraryService() {
// URL, so the tiles came back in English.
language = appLanguage(),
bitrateKbps = quality.bitrateKbps(),
+ // Off is zero, which is upstream librespot's own behaviour.
+ crossfadeMs = crossfade.durationMs(),
listener = engine,
)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index 422365c..5505bce 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -148,12 +148,20 @@ class MainActivity : ComponentActivity() {
contextUri: String? = null,
asContext: Boolean = false,
contextLabel: String = "",
+ /**
+ * Where in the track to start, for playback that is being picked up
+ * rather than begun: bringing the music back from another device is the
+ * one caller that has somewhere to resume from. Starting at zero and
+ * seeking afterwards is not the same thing, and sounds like it: the
+ * track begins, then jumps.
+ */
+ positionMs: Long = 0L,
) {
val player = controller ?: return
player.setMediaItems(
tracks.map { toMediaItem(it, contextUri, asContext, contextLabel) },
index,
- 0L,
+ positionMs,
)
player.prepare()
player.play()
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index dfeec8d..aedd3ba 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -29,6 +29,10 @@ import dev.lelonio.square.playback.EffectPreset
import dev.lelonio.square.playback.PlaybackService
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -312,6 +316,13 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
data class DevicesState(
val open: Boolean = false,
val loading: Boolean = false,
+ /**
+ * The device being switched to, while the switch is in flight.
+ *
+ * A handover takes a moment and used to look like nothing at all, so
+ * the row was pressed again and again.
+ */
+ val switchingTo: String? = null,
val devices: List<SpotifyDevice> = emptyList(),
val error: String? = null,
)
@@ -327,6 +338,32 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val devices: StateFlow<DevicesState> = _devices.asStateFlow()
private var devicesJob: Job? = null
+ init {
+ // The list, kept true by the engine rather than by asking.
+ //
+ // The Web API answers this too, but only when asked, so a sheet left
+ // open while playback moved went on showing the old active device until
+ // it was closed and opened again. The cluster arrives on its own from
+ // the session's own socket, and it is the same list.
+ viewModelScope.launch {
+ dev.lelonio.square.data.RemoteConnect.devices.collect { cluster ->
+ if (cluster.isEmpty()) return@collect
+ _devices.value = _devices.value.copy(
+ loading = false,
+ error = null,
+ devices = cluster.map { device ->
+ SpotifyDevice(
+ id = device.id,
+ name = device.name,
+ type = device.type,
+ isActive = device.active,
+ )
+ },
+ )
+ }
+ }
+ }
+
fun openDevices() {
_devices.value = _devices.value.copy(open = true)
refreshDevices()
@@ -382,12 +419,157 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
/** Moves playback to another device, keeping it playing. */
- fun transferPlayback(deviceId: String) = viewModelScope.launch {
+ /**
+ * Moves playback to another device.
+ *
+ * Through the engine when the device came from the cluster, which is the
+ * same road the official clients take and needs no registered Web API
+ * application. The Web API is the fallback for a list that came from it.
+ */
+ /**
+ * What the player needs in order to carry on here what another device was
+ * playing: the same queue, the same track, the same second.
+ */
+ data class ResumeHere(
+ val tracks: List<CatalogTrack>,
+ val index: Int,
+ val contextUri: String?,
+ val positionMs: Long,
+ )
+
+ private val _resumeHere = MutableSharedFlow<ResumeHere>(extraBufferCapacity = 1)
+
+ /** Emitted when the listener asks for the music to come back to this phone. */
+ val resumeHere = _resumeHere.asSharedFlow()
+
+ /**
+ * Brings the account's playback back to this phone.
+ *
+ * Not a transfer: a device cannot address a command to itself, and taking
+ * the session on its own only makes this one active and silent, which is
+ * exactly what choosing Square in the list used to do. A handover has to
+ * carry the music with it, so the context the other device was playing is
+ * reopened here, at the track it was on, at the position it had reached.
+ *
+ * A device playing something with no context, a single track started from a
+ * search, leaves nothing to reopen: the track alone is the queue.
+ */
+ private fun takeBackPlayback() = viewModelScope.launch {
+ // Whatever the account is playing, wherever it thinks it is playing it.
+ //
+ // Reading only the "somewhere else" half meant the request quietly did
+ // nothing whenever the engine had already decided this phone was
+ // active: choosing Square answered with silence and no explanation.
+ val remote = dev.lelonio.square.data.RemoteConnect.playback.value
+ ?: dev.lelonio.square.data.RemoteConnect.here.value
+ if (remote == null) {
+ android.util.Log.i(TAG, "nothing to bring back: the account is playing nothing")
+ return@launch
+ }
+
+ android.util.Log.i(
+ TAG,
+ "taking playback back: ${remote.uri} from ${remote.realContext} at ${remote.positionMs}",
+ )
+
+ // The music first, the list afterwards.
+ //
+ // This used to resolve the whole context before a note was played,
+ // which on a long playlist is a second or two in which nothing happens
+ // and the listener, quite reasonably, presses the button again. The
+ // queue on screen fills itself in from the state this publishes; see
+ // PlaybackService.adoptRemoteQueue.
+ val started = withContext(Dispatchers.IO) {
+ runCatching {
+ NativeBridge.resumeHere(
+ remote.realContext.orEmpty(),
+ remote.uri,
+ remote.positionMs.toInt(),
+ )
+ }.onFailure { android.util.Log.w(TAG, "could not resume here: $it") }.isSuccess
+ }
+ if (started) return@launch
+
+ // The engine refused it. Fall back to opening the context the long way,
+ // which is slower but asks nothing of the Connect layer.
+ val context = remote.realContext
+ val tracks = runCatching {
+ if (context != null) container.activeBackend.tracksOf(context) else emptyList()
+ }
+ .onFailure { android.util.Log.w(TAG, "context unreadable: ${describe(it)}") }
+ .getOrDefault(emptyList())
+
+ val index = tracks.indexOfFirst { it.uri == remote.uri }
+ if (tracks.isEmpty() || index < 0) {
+ val single = runCatching { container.activeBackend.tracksOf(remote.uri) }
+ .getOrDefault(emptyList())
+ .ifEmpty { return@launch }
+ _resumeHere.emit(ResumeHere(single, 0, null, remote.positionMs))
+ return@launch
+ }
+
+ _resumeHere.emit(ResumeHere(tracks, index, context, remote.positionMs))
+ }
+
+ fun transferPlayback(deviceId: String, positionMs: Long = 0L) = viewModelScope.launch {
+ if (_devices.value.switchingTo != null) return@launch
+ _devices.value = _devices.value.copy(switchingTo = deviceId)
+ try {
+ switchTo(deviceId, positionMs)
+ } finally {
+ _devices.value = _devices.value.copy(switchingTo = null)
+ }
+ }
+
+ private suspend fun switchTo(deviceId: String, positionMs: Long) {
+ val devices = dev.lelonio.square.data.RemoteConnect.devices.value
+ android.util.Log.i(TAG, "device chosen: $deviceId, ${devices.size} known")
+ // Asked of the engine rather than looked up in the list: the list is
+ // filled by cluster updates and is empty until the first one arrives,
+ // and a handover chosen in that window took the wrong road entirely.
+ if (dev.lelonio.square.data.RemoteConnect.isThisPhone(deviceId)) {
+ takeBackPlayback().join()
+ return
+ }
+ // The queue is republished as the playlist it came from first, so
+ // whatever carries the handover has something resolvable to carry; see
+ // NativeBridge.publishContext.
+ if (!dev.lelonio.square.data.RemoteConnect.elsewhereActive.value) {
+ val republished = withContext(Dispatchers.IO) {
+ runCatching { NativeBridge.publishContext(positionMs.toInt()) }
+ .onFailure { android.util.Log.w(TAG, "context not republished: $it") }
+ .getOrDefault(false)
+ }
+ // Only when something actually changed does Spotify need a moment
+ // to see it. A queue that already carried its playlist goes over at
+ // once, which is nearly every handover.
+ if (republished) delay(TRANSFER_SETTLE_MS)
+ }
+
+ // Spotify's own transfer, when the account has an application to ask it
+ // with. The dealer command below is the same word without the state:
+ // its `data` field is the playback being moved, and building that is
+ // Spotify's job in this call. Sent without it, the device does become
+ // active and has nothing to play, which is a progress bar advancing over
+ // silence and controls that answer to nothing.
+ if (!container.webApi.isReady) {
+ withContext(Dispatchers.IO) {
+ dev.lelonio.square.data.RemoteConnect.transferTo(deviceId)
+ }
+ return
+ }
+
runCatching { container.api.transferPlayback(TransferRequestDto(listOf(deviceId))) }
.onSuccess {
// Spotify reports the move a beat after acknowledging it, so the
// list is re-read rather than edited optimistically.
delay(TRANSFER_SETTLE_MS)
+ // Named, not assumed: a transfer that lands on a device which
+ // then sits there paused is the one failure this cannot see
+ // from here, and asking the device by name to play costs one
+ // request that is harmless when it is playing already.
+ runCatching { container.api.play(deviceId) }
+ .onFailure { android.util.Log.i(TAG, "play on $deviceId: ${describe(it)}") }
refreshDevices()
}
.onFailure {
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index f6fd71e..54a1183 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -106,6 +106,10 @@ import com.adamglin.phosphoricons.regular.Queue
import com.adamglin.phosphoricons.regular.SpotifyLogo
import com.adamglin.phosphoricons.regular.YoutubeLogo
import com.adamglin.phosphoricons.regular.Trash
+import dev.lelonio.square.data.RemoteConnect
+import dev.lelonio.square.ui.player.asPlaybackState
+import dev.lelonio.square.ui.player.rememberRemotePositionMs
+import kotlinx.coroutines.Dispatchers
import dev.lelonio.square.ui.player.MiniPlayer
import dev.lelonio.square.ui.player.PlaybackState
import dev.lelonio.square.ui.player.MiniPlayerHeight
@@ -184,7 +188,7 @@ fun SquareApp(
* the queue *is* that context in its own order, in which case playback is
* handed to Spotify as the context itself.
*/
- onPlay: (List<CatalogTrack>, Int, String?, Boolean, String) -> Unit,
+ onPlay: (List<CatalogTrack>, Int, String?, Boolean, String, Long) -> Unit,
/** Appends one track to the end of the queue; see the swipe gesture on rows. */
onEnqueue: (CatalogTrack) -> Unit,
/**
@@ -204,10 +208,64 @@ fun SquareApp(
// The session as it was left, so the player has something to draw before
// the media controller connects. Read once, off the saved queue.
val seed = remember(context) { savedPlaybackSeed(context) }
- val playback by rememberPlaybackState(player, seed)
+ val local by rememberPlaybackState(player, seed)
+
+ /**
+ * Playback on another of the account's devices, when there is any.
+ *
+ * When there is, it is what the player shows and what the buttons drive:
+ * the phone is not playing, so a player drawn from the phone would be an
+ * empty screen next to music the user can hear. This is what the official
+ * client does with a speaker in another room.
+ */
+ val elsewhere by dev.lelonio.square.data.RemoteConnect.playback.collectAsStateWithLifecycle()
+
+ /**
+ * Whether the screen is attached to another device.
+ *
+ * The engine's answer, not a guess. This started as a rule about who was
+ * making sound, because that was all this side could see, and every version
+ * of it was wrong somewhere: attached to a device that was only paused, or
+ * detached the moment the listener paused it, or pointed at the local player
+ * while the music was elsewhere, which left the play button reaching for
+ * nothing and a spinner turning for ever.
+ */
+ val elsewhereActive by dev.lelonio.square.data.RemoteConnect.elsewhereActive
+ .collectAsStateWithLifecycle()
+ val remote = elsewhere?.takeIf { elsewhereActive }
+ val remoteLabel = stringResource(R.string.playing_on, remote?.deviceName.orEmpty())
+ val playback = remote?.asPlaybackState(remoteLabel) ?: local
+
+ // Commands to another device are HTTP requests, so none of them may run on
+ // the main thread; the screen redraws when the cluster update comes back.
+ val remoteScope = rememberCoroutineScope()
+ val onRemote: ((String) -> Unit) -> Unit = { action ->
+ remote?.deviceId?.let { id -> remoteScope.launch(Dispatchers.IO) { action(id) } }
+ }
+
+ // Playback coming back from another device: the queue it was playing is
+ // opened here and then wound forward to where it had got to. The seek is a
+ // second step because starting a queue is always a start, and the position
+ // belongs to the track rather than to the act of playing it.
+ LaunchedEffect(Unit) {
+ viewModel.resumeHere.collect { resume ->
+ onPlay(
+ resume.tracks,
+ resume.index,
+ resume.contextUri,
+ resume.contextUri != null,
+ "",
+ // Straight into the load: the track starts where it was left.
+ resume.positionMs,
+ )
+ }
+ }
+
// Held as State, not read here: reading the position at this level would
// recompose the whole app — lists included — several times a second.
- val positionMs = rememberPositionMs(player, playback.isPlaying)
+ val localPosition = rememberPositionMs(player, local.isPlaying)
+ val remotePosition = rememberRemotePositionMs(remote)
+ val positionMs = if (remote != null) remotePosition else localPosition
val queue by rememberQueue(player)
val videoOn by YouTubeVideoMode.enabled.collectAsStateWithLifecycle()
@@ -589,10 +647,10 @@ fun SquareApp(
playlistOrder = playlistOrder,
recent = recent,
onPlayRecent = { tracks, index ->
- onPlay(tracks, index, null, false, playAgainLabel)
+ onPlay(tracks, index, null, false, playAgainLabel, 0L)
},
onPlayFeed = { tracks, index, label ->
- onPlay(tracks, index, null, false, label)
+ onPlay(tracks, index, null, false, label, 0L)
},
feed = feed,
onOpenItem = { item ->
@@ -604,7 +662,7 @@ fun SquareApp(
backend == dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC,
youtubeHome = youtubeHome,
onPlayTrending = { tracks, index ->
- onPlay(tracks, index, null, false, trendingLabel)
+ onPlay(tracks, index, null, false, trendingLabel, 0L)
},
onOpenSettings = { navController.navigate(Routes.SETTINGS) },
)
@@ -620,7 +678,7 @@ fun SquareApp(
onClientIdChange = viewModel::onWebApiClientIdChange,
onConnectWebApi = { viewModel.connectWebApi() },
onPlayTrack = { tracks, index ->
- onPlay(tracks, index, null, false, searchLabel)
+ onPlay(tracks, index, null, false, searchLabel, 0L)
},
onEnqueue = onEnqueue,
onTrackMenu = { track ->
@@ -697,6 +755,7 @@ fun SquareApp(
playlist.uri,
asContext,
source,
+ 0L,
)
},
onEnqueue = onEnqueue,
@@ -714,6 +773,7 @@ fun SquareApp(
playlist.uri,
false,
source,
+ 0L,
)
},
onAddToPlaylist = { track ->
@@ -787,13 +847,27 @@ fun SquareApp(
collapsedContent = {
MiniPlayer(
state = playback,
+ remoteDevice = remote?.deviceName,
progress = {
progressOf(positionMs.value, playback.durationMs)
},
backdrop = pageBackdrop,
onExpand = { scope.launch { expand.animateTo(1f, expandSpec) } },
- onTogglePlay = { player?.togglePlay() },
- onNext = { player?.seekToNextMediaItem() },
+ onTogglePlay = {
+ if (remote != null) {
+ val playing = remote?.playing == true
+ onRemote { id ->
+ if (playing) RemoteConnect.pause(id)
+ else RemoteConnect.play(id)
+ }
+ } else {
+ player?.togglePlay()
+ }
+ },
+ onNext = {
+ if (remote != null) onRemote(RemoteConnect::next)
+ else player?.seekToNextMediaItem()
+ },
)
},
expandedContent = {
@@ -801,14 +875,53 @@ fun SquareApp(
state = playback,
positionMs = positionMs,
onCollapse = { scope.launch { expand.animateTo(0f, expandSpec) } },
- onTogglePlay = { player?.togglePlay() },
- onNext = { player?.seekToNextMediaItem() },
- onPrevious = { player?.seekToPreviousMediaItem() },
- onSeek = { player?.seekTo(it) },
+ onTogglePlay = {
+ if (remote != null) {
+ val playing = remote?.playing == true
+ onRemote { id ->
+ if (playing) RemoteConnect.pause(id)
+ else RemoteConnect.play(id)
+ }
+ } else {
+ player?.togglePlay()
+ }
+ },
+ onNext = {
+ if (remote != null) onRemote(RemoteConnect::next)
+ else player?.seekToNextMediaItem()
+ },
+ onPrevious = {
+ if (remote != null) onRemote(RemoteConnect::previous)
+ else player?.seekToPreviousMediaItem()
+ },
+ onSeek = { target ->
+ if (remote != null) {
+ onRemote { id -> RemoteConnect.seek(id, target) }
+ } else {
+ player?.seekTo(target)
+ }
+ },
onToggleShuffle = {
- player?.let { it.shuffleModeEnabled = !it.shuffleModeEnabled }
+ if (remote != null) {
+ val wanted = remote?.shuffle != true
+ onRemote { id -> RemoteConnect.setShuffle(id, wanted) }
+ } else {
+ player?.let { it.shuffleModeEnabled = !it.shuffleModeEnabled }
+ }
+ },
+ onCycleRepeat = {
+ if (remote != null) {
+ val current = remote
+ // Off, all, one, off: the same cycle the
+ // local button walks.
+ val context = current?.repeatContext != true &&
+ current?.repeatTrack != true
+ val track = current?.repeatContext == true
+ onRemote { id -> RemoteConnect.setRepeat(id, context, track) }
+ } else {
+ player?.cycleRepeatMode()
+ }
},
- onCycleRepeat = { player?.cycleRepeatMode() },
queue = queue,
lyrics = lyrics,
lyricsLoading = lyricsLoading,
@@ -846,12 +959,19 @@ fun SquareApp(
backdrop = artBackdrop,
canvas = canvas,
devices = devices,
+ onAnotherDevice = remote != null,
onOpenDevices = viewModel::openDevices,
connectAvailable =
backend == dev.lelonio.square.backend.BackendId.SPOTIFY,
onCloseDevices = viewModel::closeDevices,
onRefreshDevices = viewModel::refreshDevices,
- onSelectDevice = { viewModel.transferPlayback(it) },
+ // The position goes with the request: a
+ // handover resumes where the listener was, and
+ // this is the only side that knows to the
+ // second.
+ onSelectDevice = {
+ viewModel.transferPlayback(it, positionMs.value)
+ },
onAddToPlaylist = {
viewModel.openAddToPlaylist(
playback.mediaId,
@@ -968,7 +1088,7 @@ fun SquareApp(
if (menu != null) {
TrackSheetAction(stringResource(R.string.play), PhosphorIcons.Fill.Play) {
trackMenu = null
- onPlay(listOf(menu.track), 0, null, false, "")
+ onPlay(listOf(menu.track), 0, null, false, "", 0L)
}
TrackSheetAction(stringResource(R.string.add_to_queue), PhosphorIcons.Regular.Queue) {
trackMenu = null
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/DevicePicker.kt b/app/src/main/java/dev/lelonio/square/ui/player/DevicePicker.kt
index e400964..452576c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/DevicePicker.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/DevicePicker.kt
@@ -138,7 +138,9 @@ fun DevicePicker(
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
state.devices.forEach { device ->
- DeviceRow(device) { onSelect(device.id) }
+ DeviceRow(device, switching = state.switchingTo == device.id) {
+ onSelect(device.id)
+ }
}
}
}
@@ -220,7 +222,9 @@ fun DeviceList(
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
state.devices.forEach { device ->
- DeviceRow(device) { onSelect(device.id) }
+ DeviceRow(device, switching = state.switchingTo == device.id) {
+ onSelect(device.id)
+ }
}
}
}
@@ -228,11 +232,16 @@ fun DeviceList(
}
@Composable
-private fun DeviceRow(device: MainViewModel.SpotifyDevice, onClick: () -> Unit) {
+private fun DeviceRow(
+ device: MainViewModel.SpotifyDevice,
+ /** Whether this is the row the playback is moving to right now. */
+ switching: Boolean = false,
+ onClick: () -> Unit,
+) {
Row(
Modifier
.fillMaxWidth()
- .clickable(enabled = !device.isActive, onClick = onClick)
+ .clickable(enabled = !device.isActive && !switching, onClick = onClick)
.padding(horizontal = 22.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
@@ -257,12 +266,27 @@ private fun DeviceRow(device: MainViewModel.SpotifyDevice, onClick: () -> Unit)
overflow = TextOverflow.Ellipsis,
)
Text(
- if (device.isActive) stringResource(R.string.now_playing) else device.type,
+ when {
+ switching -> stringResource(R.string.switching)
+ device.isActive -> stringResource(R.string.now_playing)
+ else -> device.type
+ },
style = MaterialTheme.typography.bodySmall,
color = GlassInkDim,
maxLines = 1,
)
}
+
+ // The one piece of feedback a handover has. Moving playback takes a
+ // moment, and without this the row simply sat there, so it was pressed
+ // again and again.
+ if (switching) {
+ CircularProgressIndicator(
+ color = GlassInkDim,
+ strokeWidth = 2.dp,
+ modifier = Modifier.size(18.dp),
+ )
+ }
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt b/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt
index 28f4c92..ab26507 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt
@@ -42,6 +42,8 @@ import dev.lelonio.square.ui.glass.LiquidButton
import dev.lelonio.square.ui.theme.softShadow
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.regular.Broadcast
import com.adamglin.phosphoricons.fill.Pause
import com.adamglin.phosphoricons.fill.Play
import com.adamglin.phosphoricons.fill.SkipForward
@@ -130,6 +132,13 @@ fun MiniPlayer(
*/
sharedScope: androidx.compose.animation.SharedTransitionScope? = null,
animatedScope: androidx.compose.animation.AnimatedVisibilityScope? = null,
+ /**
+ * The device the music is coming out of, when it is not this one.
+ *
+ * A name rather than a flag: "playing somewhere else" is not useful on its
+ * own, and the bar is the one place the answer is always in view.
+ */
+ remoteDevice: String? = null,
onExpand: () -> Unit,
onTogglePlay: () -> Unit,
onNext: () -> Unit,
@@ -187,13 +196,30 @@ fun MiniPlayer(
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
- Text(
- artist,
- style = MaterialTheme.typography.bodySmall,
- color = MiniPlayerInkDim,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
+ // The second line answers "where", when that is a
+ // question, and "who" the rest of the time. Not both at
+ // once: on a bar this size the two would elide each
+ // other into nothing.
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (remoteDevice != null) {
+ Icon(
+ PhosphorIcons.Regular.Broadcast,
+ contentDescription = null,
+ tint = MiniPlayerAccent,
+ modifier = Modifier
+ .size(13.dp)
+ .padding(end = 1.dp),
+ )
+ }
+ Text(
+ remoteDevice ?: artist,
+ style = MaterialTheme.typography.bodySmall,
+ color = if (remoteDevice != null) MiniPlayerAccent else MiniPlayerInkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(start = if (remoteDevice != null) 4.dp else 0.dp),
+ )
+ }
}
}
@@ -264,6 +290,15 @@ fun MiniPlayer(
private val MiniPlayerInk = Color(0xFFF7F8FA)
private val MiniPlayerInkDim = Color(0xFFF7F8FA).copy(alpha = 0.66f)
+/**
+ * The green everyone already reads as "this is coming out of something else".
+ *
+ * Spotify's own, and deliberately so: the mark is theirs, it means one thing,
+ * and inventing a colour for it would be asking people to learn a private
+ * signal for something they already recognise.
+ */
+private val MiniPlayerAccent = Color(0xFF1ED760)
+
/** Guarded against the duration being unknown while a track loads. */
fun progressOf(positionMs: Long, durationMs: Long): Float =
if (durationMs <= 0) 0f else (positionMs.toFloat() / durationMs).coerceIn(0f, 1f)
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
index fefca37..0efadf2 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
@@ -206,6 +206,8 @@ fun PlayerScreen(
* ever be empty, so it is not drawn at all.
*/
connectAvailable: Boolean = true,
+ /** Whether the sound is coming out of another of the account's devices. */
+ onAnotherDevice: Boolean = false,
) {
var panel by remember { mutableStateOf(PlayerPanel.NONE) }
@@ -395,6 +397,7 @@ fun PlayerScreen(
}
},
connectAvailable = connectAvailable,
+ onAnotherDevice = onAnotherDevice,
onWatchVideo = onWatchVideo,
videoOn = videoOn,
)
@@ -860,6 +863,7 @@ private fun TopBar(
onCollapse: () -> Unit,
onOpenDevices: () -> Unit,
connectAvailable: Boolean,
+ onAnotherDevice: Boolean,
/** Null when the track has no video to watch. */
onWatchVideo: (() -> Unit)?,
videoOn: Boolean,
@@ -922,7 +926,15 @@ private fun TopBar(
Icon(
PhosphorIcons.Regular.Devices,
contentDescription = stringResource(R.string.devices),
- tint = panelTint(panel == PlayerPanel.DEVICES),
+ // Lit for as long as the music is coming out of another
+ // device, not only while its list is open: on this screen it
+ // is the one thing that says the buttons are reaching
+ // somewhere else, and it has to still say it once the panel
+ // is closed.
+ tint = when {
+ onAnotherDevice -> ConnectedInk
+ else -> panelTint(panel == PlayerPanel.DEVICES)
+ },
)
}
}
@@ -1200,6 +1212,9 @@ private fun GlassButton(
private fun panelTint(active: Boolean) =
if (active) MaterialTheme.colorScheme.primary else GlassInk
+/** Spotify's own green, which already means "playing over there". */
+private val ConnectedInk = androidx.compose.ui.graphics.Color(0xFF1ED760)
+
@Composable
private fun ToggleIcon(
icon: androidx.compose.ui.graphics.vector.ImageVector,
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
index 05dd9e6..71387d9 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
@@ -48,6 +48,65 @@ data class PlaybackState(
val source: String = "",
)
+/**
+ * The same picture, drawn from another device's playback.
+ *
+ * The player UI does not need to know where the music is: it is the same track,
+ * the same artwork and the same buttons, and only the thing on the other end of
+ * the buttons changes. [source] carries the device's name, where the screen
+ * already draws the line about where a queue came from.
+ *
+ * `hasNext` and `hasPrevious` are simply true. The cluster does not say, and a
+ * skip button greyed out on a device that would have obeyed is worse than one
+ * that occasionally does nothing.
+ */
+fun dev.lelonio.square.data.RemotePlayback.asPlaybackState(on: String) = PlaybackState(
+ hasItem = uri.isNotEmpty(),
+ mediaId = uri,
+ title = title,
+ artist = artist,
+ artworkUrl = coverUrl.ifEmpty { null },
+ isPlaying = playing,
+ durationMs = durationMs,
+ hasNext = true,
+ hasPrevious = true,
+ shuffleEnabled = shuffle,
+ repeatMode = when {
+ repeatTrack -> Player.REPEAT_MODE_ONE
+ repeatContext -> Player.REPEAT_MODE_ALL
+ else -> Player.REPEAT_MODE_OFF
+ },
+ source = on,
+)
+
+/**
+ * The position of a track playing somewhere else.
+ *
+ * Counted here rather than asked for: the cluster says where the track was at a
+ * given moment and arrives only when something changes, so between updates the
+ * only honest way to draw a moving bar is to move it.
+ */
+@Composable
+fun rememberRemotePositionMs(remote: dev.lelonio.square.data.RemotePlayback?): State<Long> {
+ val position = remember { mutableLongStateOf(0L) }
+
+ LaunchedEffect(remote?.uri, remote?.positionMs, remote?.playing) {
+ val current = remote ?: run {
+ position.longValue = 0
+ return@LaunchedEffect
+ }
+ position.longValue = current.positionMs.coerceAtLeast(0)
+ if (!current.playing) return@LaunchedEffect
+
+ while (true) {
+ delay(250)
+ position.longValue += 250
+ }
+ }
+
+ return position
+}
+
/** How long an empty freshly connected player is given before it is believed. */
private const val EMPTY_PLAYER_GRACE_MS = 4_000L
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 0e8d036..8137608 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -19,6 +19,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
+import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -31,6 +32,8 @@ import androidx.compose.ui.draw.clip
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.activity.compose.BackHandler
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -45,12 +48,14 @@ import com.adamglin.phosphoricons.regular.ArrowLeft
import com.adamglin.phosphoricons.regular.Check
import com.adamglin.phosphoricons.regular.ArrowUpRight
import com.adamglin.phosphoricons.regular.CaretDown
+import com.adamglin.phosphoricons.regular.CaretRight
import com.adamglin.phosphoricons.regular.CaretUp
import com.kyant.backdrop.Backdrop
import dev.lelonio.square.BuildConfig
import dev.lelonio.square.R
import dev.lelonio.square.data.AppLanguages
import dev.lelonio.square.backend.BackendId
+import dev.lelonio.square.data.CrossfadeSteps
import dev.lelonio.square.data.Quality
import dev.lelonio.square.ui.MainViewModel
import dev.lelonio.square.ui.components.Artwork
@@ -108,6 +113,21 @@ fun SettingsScreen(
val spotifyActive by app.preferences.backend.collectAsStateWithLifecycle()
val showSpotify = spotifyActive == BackendId.SPOTIFY
+ /**
+ * Which page is open, or null for the list of them.
+ *
+ * One screen with a page inside it rather than a second destination: every
+ * page here reads the same state and the same stores, and threading all of
+ * it through a navigation graph would buy nothing but the plumbing.
+ * Remembered across a rotation, since coming back to the top of the
+ * settings after turning the phone is not what anyone meant to do.
+ */
+ var open by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
+
+ // The back gesture closes the page first and leaves the settings second,
+ // which is the order the screen is read in.
+ BackHandler(enabled = open != null) { open = null }
+
LazyColumn(
Modifier.fillMaxSize(),
contentPadding = PaddingValues(
@@ -122,18 +142,32 @@ fun SettingsScreen(
.padding(start = 16.dp, end = 24.dp, top = 8.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
- LiquidButton(onClick = onBack, backdrop = backdrop) {
+ LiquidButton(
+ onClick = { if (open != null) open = null else onBack() },
+ backdrop = backdrop,
+ ) {
Icon(PhosphorIcons.Regular.ArrowLeft, contentDescription = stringResource(R.string.back))
}
Text(
- stringResource(R.string.settings),
+ stringResource(open?.title ?: R.string.settings),
style = MaterialTheme.typography.displayLarge,
modifier = Modifier.padding(start = 14.dp),
)
}
}
- if (showSpotify) item("account") {
+ if (open == null) item("pages") {
+ Section(null) {
+ SettingsPage.entries.forEachIndexed { index, page ->
+ if (index > 0) RowDivider()
+ PageRow(stringResource(page.title), stringResource(page.summary)) {
+ open = page
+ }
+ }
+ }
+ }
+
+ if (open == SettingsPage.Account && showSpotify) item("account") {
Section(stringResource(R.string.account)) {
Row(
Modifier
@@ -178,7 +212,7 @@ fun SettingsScreen(
}
}
- if (showSpotify) item("webapi") {
+ if (open == SettingsPage.Account && showSpotify) item("webapi") {
Section(stringResource(R.string.web_api)) {
if (webApi.connected) {
InfoRow(stringResource(R.string.application), stringResource(R.string.connected))
@@ -198,7 +232,7 @@ fun SettingsScreen(
}
}
- if (showSpotify) item("tutorial") {
+ if (open == SettingsPage.Account && showSpotify) item("tutorial") {
Section(stringResource(R.string.guide)) {
ActionRow(stringResource(R.string.see_setup_again), destructive = false) {
onShowTutorial()
@@ -206,20 +240,25 @@ fun SettingsScreen(
}
}
- item("backend") {
+ if (open == SettingsPage.Playback) item("backend") {
BackendSection()
}
- item("youtube-account") {
+ if (open == SettingsPage.Account) item("youtube-account") {
YouTubeAccountSection(onSignIn = onYouTubeSignIn)
}
// The bitrate is librespot's; ExoPlayer takes what YouTube serves.
- if (showSpotify) item("quality") {
+ if (open == SettingsPage.Playback && showSpotify) item("quality") {
QualitySection()
}
- item("language") {
+ // Also librespot's: the crossfade is mixed by the engine's own player.
+ if (open == SettingsPage.Playback && showSpotify) item("crossfade") {
+ CrossfadeSection()
+ }
+
+ if (open == SettingsPage.App) item("language") {
Section(stringResource(R.string.language)) {
AppLanguages.forEachIndexed { index, (tag, name) ->
if (index > 0) RowDivider()
@@ -231,7 +270,7 @@ fun SettingsScreen(
}
}
- item("permissions") {
+ if (open == SettingsPage.About) item("permissions") {
Section(stringResource(R.string.permissions_asked)) {
Text(
stringResource(R.string.permissions_note),
@@ -246,7 +285,7 @@ fun SettingsScreen(
}
}
- item("author") {
+ if (open == SettingsPage.About) item("author") {
Section(stringResource(R.string.developed_by)) {
val uriHandler = LocalUriHandler.current
Row(
@@ -290,7 +329,7 @@ fun SettingsScreen(
}
}
- item("about") {
+ if (open == SettingsPage.About) item("about") {
Section(stringResource(R.string.about)) {
InfoRow(stringResource(R.string.version), "${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE})")
RowDivider()
@@ -300,7 +339,7 @@ fun SettingsScreen(
}
}
- if (ready != null) {
+ if (ready != null && open == SettingsPage.Account) {
item("logout") {
Section(null) {
ActionRow(stringResource(R.string.log_out), destructive = true, onClick = onLogOut)
@@ -310,6 +349,56 @@ fun SettingsScreen(
}
}
+/**
+ * The pages the settings are divided into.
+ *
+ * Four, and no deeper: a page that holds one row is a row that was hidden, and
+ * a tree that goes further than this is somewhere to lose things in.
+ *
+ * The order is how often they are wanted. The account is what a first launch
+ * comes here for, playback is what a settled install comes back for, and the
+ * rest is read once.
+ */
+private enum class SettingsPage(
+ @StringRes val title: Int,
+ /** One line under the name, so a page can be chosen without opening it. */
+ @StringRes val summary: Int,
+) {
+ Account(R.string.account, R.string.page_account_summary),
+ Playback(R.string.page_playback, R.string.page_playback_summary),
+ App(R.string.page_app, R.string.page_app_summary),
+ About(R.string.about, R.string.page_about_summary),
+}
+
+/** A row that opens a page. */
+@Composable
+private fun PageRow(title: String, summary: String, onClick: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onClick)
+ .padding(horizontal = 18.dp, vertical = 16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(title, style = MaterialTheme.typography.titleMedium)
+ Text(
+ summary,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ Icon(
+ PhosphorIcons.Regular.CaretRight,
+ contentDescription = null,
+ tint = InkDim,
+ modifier = Modifier.size(18.dp),
+ )
+ }
+}
+
/**
* Which file the engine asks Spotify for.
*
@@ -421,6 +510,37 @@ private fun YouTubeAccountSection(onSignIn: () -> Unit) {
}
}
+@Composable
+private fun CrossfadeSection() {
+ val context = LocalContext.current
+ val store = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).crossfade
+ }
+ val chosen by store.seconds.collectAsStateWithLifecycle()
+
+ Section(stringResource(R.string.crossfade)) {
+ CrossfadeSteps.forEachIndexed { index, seconds ->
+ if (index > 0) RowDivider()
+ ChoiceRow(
+ label = if (seconds == 0) {
+ stringResource(R.string.crossfade_off)
+ } else {
+ stringResource(R.string.crossfade_seconds, seconds)
+ },
+ selected = seconds == chosen,
+ ) { store.set(seconds) }
+ }
+ RowDivider()
+ Text(
+ stringResource(R.string.crossfade_note) + " " +
+ stringResource(R.string.quality_restarts),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
+ )
+ }
+}
+
@Composable
private fun QualitySection() {
val context = LocalContext.current
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 1186476..8ac1a2b 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -212,4 +212,16 @@
<string name="update_install">Installieren</string>
<string name="download_get_app">YTDLnis installieren</string>
<string name="download_with">Mit YTDLnis herunterladen</string>
+ <string name="crossfade">Überblendung</string>
+ <string name="crossfade_off">Aus</string>
+ <string name="crossfade_seconds">%1$d Sekunden</string>
+ <string name="crossfade_note">Ein Titel geht in den nächsten über. Nur wenn er von selbst endet, nicht beim Überspringen.</string>
+ <string name="page_playback">Wiedergabe</string>
+ <string name="page_app">App</string>
+ <string name="page_account_summary">Ihr Konto, die Web-API-Anwendung und das Abmelden</string>
+ <string name="page_playback_summary">Woher die Musik kommt, Qualität und Überblendung</string>
+ <string name="page_app_summary">Sprache</string>
+ <string name="page_about_summary">Version, Berechtigungen, Lizenzen und Entwickler</string>
+ <string name="playing_on">Wiedergabe auf %1$s</string>
+ <string name="switching">Wechsel…</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 2de847b..192de5a 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -212,4 +212,16 @@
<string name="update_install">Instalar</string>
<string name="download_get_app">Instalar YTDLnis</string>
<string name="download_with">Descargar con YTDLnis</string>
+ <string name="crossfade">Fundido</string>
+ <string name="crossfade_off">Apagado</string>
+ <string name="crossfade_seconds">%1$d segundos</string>
+ <string name="crossfade_note">Una canción se funde con la siguiente. Solo cuando termina sola, no al saltarla.</string>
+ <string name="page_playback">Reproducción</string>
+ <string name="page_app">Aplicación</string>
+ <string name="page_account_summary">Tu cuenta, la aplicación de la Web API y cerrar sesión</string>
+ <string name="page_playback_summary">De dónde viene la música, calidad y fundido</string>
+ <string name="page_app_summary">Idioma</string>
+ <string name="page_about_summary">Versión, permisos, licencias y desarrollador</string>
+ <string name="playing_on">Reproduciendo en %1$s</string>
+ <string name="switching">Cambiando…</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index c10d261..4041e88 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -212,4 +212,16 @@
<string name="update_install">Installer</string>
<string name="download_get_app">Installer YTDLnis</string>
<string name="download_with">Télécharger avec YTDLnis</string>
+ <string name="crossfade">Fondu enchaîné</string>
+ <string name="crossfade_off">Désactivé</string>
+ <string name="crossfade_seconds">%1$d secondes</string>
+ <string name="crossfade_note">Un morceau se fond dans le suivant. Seulement quand il se termine seul, pas quand vous passez au suivant.</string>
+ <string name="page_playback">Lecture</string>
+ <string name="page_app">Application</string>
+ <string name="page_account_summary">Votre compte, l’application Web API et la déconnexion</string>
+ <string name="page_playback_summary">D’où vient la musique, qualité et fondu enchaîné</string>
+ <string name="page_app_summary">Langue</string>
+ <string name="page_about_summary">Version, autorisations, licences et développeur</string>
+ <string name="playing_on">Lecture sur %1$s</string>
+ <string name="switching">Transfert…</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 4c20984..0fb744c 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -213,4 +213,16 @@
<string name="update_install">Installa</string>
<string name="download_get_app">Installa YTDLnis</string>
<string name="download_with">Scarica con YTDLnis</string>
+ <string name="crossfade">Dissolvenza</string>
+ <string name="crossfade_off">Spenta</string>
+ <string name="crossfade_seconds">%1$d secondi</string>
+ <string name="crossfade_note">Una canzone si dissolve nella successiva. Solo quando finisce da sola, non quando la salti.</string>
+ <string name="page_playback">Riproduzione</string>
+ <string name="page_app">App</string>
+ <string name="page_account_summary">Il tuo account, l’applicazione Web API e la disconnessione</string>
+ <string name="page_playback_summary">Da dove arriva la musica, qualità e dissolvenza</string>
+ <string name="page_app_summary">Lingua</string>
+ <string name="page_about_summary">Versione, permessi, licenze e sviluppatore</string>
+ <string name="playing_on">In riprod. su %1$s</string>
+ <string name="switching">Passaggio in corso…</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 4b75ad1..459ce25 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -212,4 +212,16 @@
<string name="update_install">Instalar</string>
<string name="download_get_app">Instalar YTDLnis</string>
<string name="download_with">Transferir com YTDLnis</string>
+ <string name="crossfade">Transição</string>
+ <string name="crossfade_off">Desligada</string>
+ <string name="crossfade_seconds">%1$d segundos</string>
+ <string name="crossfade_note">Uma música se dissolve na seguinte. Só quando ela termina sozinha, não ao pular.</string>
+ <string name="page_playback">Reprodução</string>
+ <string name="page_app">Aplicativo</string>
+ <string name="page_account_summary">Sua conta, o aplicativo da Web API e sair</string>
+ <string name="page_playback_summary">De onde vem a música, qualidade e transição</string>
+ <string name="page_app_summary">Idioma</string>
+ <string name="page_about_summary">Versão, permissões, licenças e desenvolvedor</string>
+ <string name="playing_on">Reproduzindo em %1$s</string>
+ <string name="switching">Trocando…</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 146c11d..f0bc6f8 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -233,4 +233,16 @@
<string name="update_install">Install</string>
<string name="download_get_app">Get YTDLnis</string>
<string name="download_with">Download with YTDLnis</string>
+ <string name="crossfade">Crossfade</string>
+ <string name="crossfade_off">Off</string>
+ <string name="crossfade_seconds">%1$d seconds</string>
+ <string name="crossfade_note">One track dissolves into the next. Only where a track ends on its own, not when you skip.</string>
+ <string name="page_playback">Playback</string>
+ <string name="page_app">App</string>
+ <string name="page_account_summary">Your account, the Web API application and signing out</string>
+ <string name="page_playback_summary">Where music comes from, quality and crossfade</string>
+ <string name="page_app_summary">Language</string>
+ <string name="page_about_summary">Version, permissions, licences and the developer</string>
+ <string name="playing_on">Playing on %1$s</string>
+ <string name="switching">Switching…</string>
</resources>
diff --git a/native/Cargo.lock b/native/Cargo.lock
index b360487..dea94e6 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -1132,8 +1132,6 @@ dependencies = [
[[package]]
name = "librespot-connect"
version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b2a21e9e19b906c6676b1a515fc5529d5414f69049f5a167dfb2ea3206e5a27"
dependencies = [
"futures-util",
"librespot-core",
@@ -1239,8 +1237,6 @@ dependencies = [
[[package]]
name = "librespot-playback"
version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88258620bf3e6808ea1fadd11639648d77c06280b9f5a4c9d14ea79f6f998af6"
dependencies = [
"form_urlencoded",
"futures-util",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index 84ddab4..66c95e6 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -41,6 +41,8 @@ android_logger = "0.14"
# the patched copy too.
[patch.crates-io]
librespot-core = { path = "vendor/librespot-core" }
+librespot-playback = { path = "vendor/librespot-playback" }
+librespot-connect = { path = "vendor/librespot-connect" }
[profile.release]
opt-level = 3
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 0041031..84f0cce 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -195,6 +195,8 @@ struct Recipe {
enum Pump {
Event(PlayerEvent),
Session(Session),
+ /// Something changed on another of the account's devices; see `remote`.
+ Cluster,
}
/// Errors are flattened to a string because they cross the JNI boundary and the
@@ -273,11 +275,13 @@ pub fn init_android_context(context: &JObject) -> EngineResult<()> {
pub fn start(
client_id: &str,
device_name: &str,
+ device_id: &str,
access_token: &str,
credentials_dir: &str,
cache_dir: &str,
language: &str,
bitrate_kbps: i32,
+ crossfade_ms: i32,
listener: GlobalRef,
) -> EngineResult<()> {
let mut guard = ENGINE.lock().map_err(|_| "engine mutex poisoned")?;
@@ -308,6 +312,16 @@ pub fn start(
if !client_id.is_empty() {
session_config.client_id = client_id.to_string();
}
+ // The same id on every launch, chosen by the app and kept by it.
+ //
+ // librespot's default is a fresh uuid per session, which is right for a
+ // daemon started once and wrong for a phone: the account saw a new "A059"
+ // every time the engine came up, the list filled with ghosts of this same
+ // device, and nothing could recognise the phone it had been playing on an
+ // hour earlier.
+ if !device_id.is_empty() {
+ session_config.device_id = device_id.to_string();
+ }
let credentials = Credentials::with_access_token(access_token);
@@ -350,6 +364,12 @@ pub fn start(
// Every update crosses JNI and rebuilds the Media3 state on the main
// thread; once a second is plenty for a seek bar.
position_update_interval: Some(Duration::from_secs(1)),
+ // How long one track dissolves into the next, chosen by the user. See
+ // the patch notes in native/vendor/README.md: the player asks for the
+ // next track a fade early and mixes the one going out underneath it.
+ // Fixed for the life of the player, like the bitrate, so the service
+ // builds a new engine when the setting changes.
+ crossfade_duration_ms: crossfade_ms.max(0) as u32,
..PlayerConfig::default()
};
@@ -456,6 +476,16 @@ fn build_bundle(
let connect_config = recipe.connect_config.clone();
let credentials = recipe.credentials.clone();
+ // The account's other devices, watched over the same dealer.
+ //
+ // Subscribed before the session connects, which is the whole point of doing
+ // it here rather than after the device is built: Spotify pushes a cluster
+ // update when this device appears, and that push is the only one that
+ // arrives without something changing later. Subscribing afterwards meant
+ // opening the app next to a speaker that was already playing and being told
+ // nothing until the speaker's track ended.
+ let watch_tx = events_tx.clone();
+
let (session, player, spirc, spirc_task) = rt.block_on(async move {
// Seed the cache with the OAuth credentials, then hand the cached copy
// to `connect` with storing switched off. Letting `connect` store
@@ -469,6 +499,10 @@ fn build_bundle(
.and_then(|cache| cache.credentials())
.unwrap_or(credentials);
+ crate::remote::watch(&session, move || {
+ let _ = watch_tx.send(Pump::Cluster);
+ });
+
// No `session.connect` here: `Spirc::new` registers its dealer
// listeners and then connects the session itself. Connecting first
// authenticated twice and left the second attempt reporting "Session is
@@ -578,6 +612,14 @@ fn spawn_event_forwarder(
break;
}
+ match &event {
+ PlayerEvent::Playing { .. } => LOCAL_PLAYING.store(true, Ordering::SeqCst),
+ PlayerEvent::Paused { .. } | PlayerEvent::Stopped { .. } => {
+ LOCAL_PLAYING.store(false, Ordering::SeqCst)
+ }
+ _ => {}
+ }
+
// The track the app asked for is on its way: let it be heard.
// `Loading` rather than `Playing`, so nothing of its opening is lost
// while the two sides agree the silence is over.
@@ -642,6 +684,7 @@ pub fn reconnect() -> EngineResult<()> {
// would go on publishing state for a player nobody is listening to.
if let Some(old) = engine.bundle.take() {
log::info!("discarding the old session");
+ crate::remote::clear();
let _ = old.spirc.disconnect(true);
let _ = old.spirc.shutdown();
old.player.stop();
@@ -702,6 +745,15 @@ fn spawn_event_pump(
while let Ok(message) = events.recv() {
let event = match message {
Pump::Event(event) => event,
+ // Carries nothing: the Kotlin side reads the state it wants
+ // when it hears there is a new one, rather than having every
+ // field of it pushed through this boundary.
+ Pump::Cluster => {
+ if let Err(e) = emit(&listener, "cluster", "", 0) {
+ log::warn!("dropping a cluster update: {e}");
+ }
+ continue;
+ }
Pump::Session(session) => {
match history.as_mut() {
// The listen in progress survives: the same person
@@ -1219,10 +1271,39 @@ pub fn load_queue(
..options
},
)
+ } else if !context.is_empty() {
+ // The tracks in the order on screen, published under the playlist they
+ // came from.
+ //
+ // Shuffling a playlist, or adding a track to it, makes a queue that is
+ // the playlist without being the playlist's order, and upstream has no
+ // shape for that: either the context, whose order is Spotify's, or a
+ // list of tracks, published as `spotify:web-api`. The second is what
+ // this app sent nearly always, and it is a context no other device can
+ // resolve: handing playback to one gave it a queue that would not play,
+ // and taking it back arrived with a track that could not be found. See
+ // native/vendor/README.md.
+ LoadRequest::from_tracks_in(context, uris, options)
} else {
LoadRequest::from_tracks(uris, options)
};
+ // A queue that nobody asked to hear does not go out while the account is
+ // playing somewhere else.
+ //
+ // A load activates this device, which is right when the listener has just
+ // tapped a track and wrong every other time. Opening the app restores the
+ // last queue, paused, and that restore was taking the session away from
+ // whatever was playing in the other room: Square went silent-but-active and
+ // the music stopped mid-track.
+ //
+ // Refused rather than quietly dropped, so the caller keeps its queue marked
+ // as one the engine has never seen and hands it over again the moment the
+ // listener really does ask for it.
+ if !start_playing && elsewhere_active() {
+ return Err("another device has playback".into());
+ }
+
// Nothing but this track may be heard until it starts; see PLAYBACK_ARMED.
if !wanted.is_empty() {
shut(Gate::Expect(wanted.clone()));
@@ -1270,6 +1351,23 @@ fn transport(
// an error: the channel still accepts the message and nobody ever reads it.
// Waiting for a failure meant the fallback almost never ran, which is why
// pause went on doing nothing with the network gone.
+ // Another device has the account's playback: this one must not reach for it.
+ //
+ // Every command here activates the device first, which is right when the
+ // listener is asking this phone to play and catastrophic when they are not.
+ // A pause sent while a speaker was playing took the session away from the
+ // speaker and then stopped it, which is what closing the app did to the
+ // music in the other room, and what opening it did on the way in.
+ //
+ // The player is still told, because the point of a pause is silence here.
+ // Spirc is not, so nothing is taken from anyone.
+ if elsewhere_active() {
+ return with_bundle(|engine| {
+ log::info!("{what}: another device has playback, keeping this one to itself");
+ via_player(engine);
+ });
+ }
+
if spirc_lost() {
return with_bundle(|engine| {
log::warn!("{what}: the connect device is gone, going straight to the player");
@@ -1299,7 +1397,51 @@ fn transport(
})?
}
+/// Whether this device is decoding audio right now.
+///
+/// The plainest fact available, and the one that settles the argument when the
+/// other two sources disagree; see [`elsewhere_active`].
+static LOCAL_PLAYING: AtomicBool = AtomicBool::new(false);
+
+/// Whether the account's playback belongs to another device.
+///
+/// Asked of librespot rather than of the cluster, because the two disagree for
+/// as long as it takes the previous device to let go. After playback is
+/// transferred *to* this phone, the account can go on naming the device it came
+/// from: trusting that meant refusing to play on a device that was already
+/// playing, and every guard in here reading the wrong answer at once.
+///
+/// The cluster is still the fallback, for the moment before there is a device
+/// at all.
+pub fn elsewhere_active() -> bool {
+ // Sound coming out of this phone settles it.
+ //
+ // The other two answers can both be wrong at once, and were: after
+ // playback was taken back here, the account still named the device it came
+ // from and the Connect state had not caught up either, so a pause pressed
+ // on a phone that was playing went out to a laptop that was not. Whatever
+ // the bookkeeping says, the device making the sound is the device the
+ // buttons belong to.
+ if LOCAL_PLAYING.load(Ordering::SeqCst) {
+ return false;
+ }
+
+ match with_bundle(|bundle| bundle.spirc.is_active()) {
+ Ok(true) => false,
+ Ok(false) => crate::remote::elsewhere_active(),
+ Err(_) => crate::remote::elsewhere_active(),
+ }
+}
+
pub fn play() -> EngineResult<()> {
+ // Nothing happens here while the music is somewhere else. A play that
+ // arrives then is Android's, not the listener's: focus coming back, a
+ // service waking. The listener's own play is sent to the device that is
+ // actually playing, by the app, and never reaches this.
+ if elsewhere_active() {
+ log::info!("play: another device has playback, ignoring");
+ return Ok(());
+ }
transport("play", |e| e.spirc.play(), |e| e.player.play())
}
@@ -1348,6 +1490,117 @@ fn leaving() {
}
}
+/// Republishes what is playing as the context it came from.
+///
+/// Only useful in one moment, just before playback is handed to another device.
+///
+/// A queue that is not a playlist in its own order goes to the engine as a bare
+/// list of URIs, and librespot has to invent a context for it: `spotify:web-api`,
+/// which is what the logs call `type: Default`. That is fine here, where the
+/// order on screen is the order that plays, and useless to anyone else: a device
+/// receiving the handover gets a context it cannot resolve, so its bar moves and
+/// nothing comes out.
+///
+/// So the same music is loaded once more as the real playlist, at the same track
+/// and the same second, and only then is the handover sent. The cost is that a
+/// shuffled queue continues over there in Spotify's order rather than in the one
+/// that was on screen: the alternative is handing over something that does not
+/// play at all.
+pub fn publish_context(position_ms: u32) -> EngineResult<bool> {
+ let current = current_uri();
+ if current.is_empty() {
+ return Ok(false);
+ }
+
+ // Nothing to do in the ordinary case, which is what makes a handover quick.
+ //
+ // Loads now carry the playlist they came from even when the order is this
+ // app's own, so the state is already something another device can resolve.
+ // Reloading anyway cost a restart of the audio and a wait, on every single
+ // change of device, to republish what was published already.
+ if !current_context().is_empty() {
+ return Ok(false);
+ }
+
+ // The track itself, since there is no playlist behind this queue.
+ //
+ // A track is a context: it is what the official client publishes when a
+ // single song is played out of a search, and unlike `spotify:web-api` it is
+ // something the other end can resolve. Without this a queue with no
+ // playlist behind it, which is most of what a search produces, handed over
+ // as a context that answers 400 and left the receiving device with nothing
+ // to play.
+ let context = current.clone();
+
+ log::info!("republishing {current} as {context} before handing over");
+ let request = LoadRequest::from_context_uri(
+ context,
+ LoadRequestOptions {
+ start_playing: true,
+ seek_to: position_ms,
+ playing_track: Some(PlayingTrack::Uri(current)),
+ ..LoadRequestOptions::default()
+ },
+ );
+
+ with_bundle(|e| {
+ e.spirc.activate()?;
+ e.spirc.load(request)
+ })?
+ .map_err(|e| format!("could not republish the context: {e}"))?;
+ Ok(true)
+}
+
+/// Starts playing here, at the track and second another device was on.
+///
+/// The whole handover in one call, so it can happen before anything is
+/// resolved. The app used to fetch the entire context first, which for a long
+/// playlist is a second or two of nothing happening at all, with no way for the
+/// listener to tell the request from a request that was lost. The queue on
+/// screen catches up afterwards, from the state this load publishes.
+pub fn resume_here(context_uri: &str, track_uri: &str, position_ms: u32) -> EngineResult<()> {
+ if track_uri.is_empty() {
+ return Err("nothing to resume".into());
+ }
+
+ let context = if context_uri.is_empty() {
+ track_uri.to_string()
+ } else {
+ context_uri.to_string()
+ };
+ log::info!("resuming {track_uri} here, from {context} at {position_ms}ms");
+
+ // Anything the previous device was decoding stays out until this track
+ // starts; see PLAYBACK_ARMED.
+ shut(Gate::Expect(track_uri.to_string()));
+
+ let request = LoadRequest::from_context_uri(
+ context,
+ LoadRequestOptions {
+ start_playing: true,
+ seek_to: position_ms,
+ playing_track: Some(PlayingTrack::Uri(track_uri.to_string())),
+ ..LoadRequestOptions::default()
+ },
+ );
+
+ with_bundle(|e| {
+ e.spirc.activate()?;
+ e.spirc.load(request)
+ })?
+ .map_err(|e| format!("could not resume here: {e}"))
+}
+
+/// Takes the account's playback for this device.
+///
+/// The local half of the device picker. Choosing another device is a request to
+/// the server, addressed from here to there; choosing this one cannot be, since
+/// a command sent from a device to itself goes out to the access point and
+/// comes back refused. Activating is the same thing done directly.
+pub fn take_over() -> EngineResult<()> {
+ with_bundle(|e| e.spirc.activate())?.map_err(|e| format!("could not take over: {e}"))
+}
+
pub fn set_shuffle(shuffle: bool) -> EngineResult<()> {
with_bundle(|e| e.spirc.shuffle(shuffle))?.map_err(|e| format!("shuffle failed: {e}"))
}
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 5b36da0..8d68bb7 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -120,11 +120,13 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSta
_class: JClass,
client_id: JString,
device_name: JString,
+ device_id: JString,
access_token: JString,
credentials_dir: JString,
cache_dir: JString,
language: JString,
bitrate_kbps: jni::sys::jint,
+ crossfade_ms: jni::sys::jint,
listener: JObject,
) {
// Every argument is read before the guard: reading borrows `env`, and so
@@ -136,11 +138,13 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSta
String,
String,
String,
+ String,
jni::objects::GlobalRef,
)> = (|| {
Ok((
read_string(&mut env, &client_id)?,
read_string(&mut env, &device_name)?,
+ read_string(&mut env, &device_id).unwrap_or_default(),
read_string(&mut env, &access_token)?,
read_string(&mut env, &credentials_dir)?,
read_string(&mut env, &cache_dir)?,
@@ -151,16 +155,26 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSta
})();
guard(&mut env, "Start", || {
- let (client_id, device_name, access_token, credentials_dir, cache_dir, language, listener) =
- arguments?;
+ let (
+ client_id,
+ device_name,
+ device_id,
+ access_token,
+ credentials_dir,
+ cache_dir,
+ language,
+ listener,
+ ) = arguments?;
engine::start(
&client_id,
&device_name,
+ &device_id,
&access_token,
&credentials_dir,
&cache_dir,
&language,
bitrate_kbps,
+ crossfade_ms,
listener,
)
});
@@ -431,6 +445,109 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRec
guard(&mut env, "Reconnect", engine::reconnect);
}
+/// Whether the account is playing on a device that is not this one.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaybackElsewhere(
+ _env: JNIEnv,
+ _class: JClass,
+) -> jboolean {
+ engine::elsewhere_active() as jboolean
+}
+
+/// Republishes the queue as its real context, before handing playback over.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePublishContext(
+ mut env: JNIEnv,
+ _class: JClass,
+ position_ms: jint,
+) -> jboolean {
+ guard(&mut env, "PublishContext", || {
+ engine::publish_context(position_ms.max(0) as u32)
+ }) as jboolean
+}
+
+/// Starts playing here what another device was playing.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeResumeHere(
+ mut env: JNIEnv,
+ _class: JClass,
+ context_uri: JString,
+ track_uri: JString,
+ position_ms: jint,
+) {
+ let context = read_string(&mut env, &context_uri).unwrap_or_default();
+ let track = read_string(&mut env, &track_uri);
+ guard(&mut env, "ResumeHere", || {
+ engine::resume_here(&context, &track?, position_ms.max(0) as u32)
+ });
+}
+
+/// Takes the account's playback for this device.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeTakeOver(
+ mut env: JNIEnv,
+ _class: JClass,
+) {
+ guard(&mut env, "TakeOver", engine::take_over);
+}
+
+/// This device's own Connect id.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeDeviceId(
+ mut env: JNIEnv,
+ _class: JClass,
+) -> jstring {
+ guard_string(&mut env, "DeviceId", crate::remote::device_id)
+}
+
+/// What the account is playing, wherever it is playing it.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemoteState(
+ mut env: JNIEnv,
+ _class: JClass,
+) -> jstring {
+ guard_string(&mut env, "RemoteState", || Ok(crate::remote::state_json()))
+}
+
+/// Every Connect device the account can see, this one included.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemoteDevices(
+ mut env: JNIEnv,
+ _class: JClass,
+) -> jstring {
+ guard_string(&mut env, "RemoteDevices", || {
+ Ok(crate::remote::devices_json())
+ })
+}
+
+/// Sends one command, as Spotify's own clients word it, to another device.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemoteCommand(
+ mut env: JNIEnv,
+ _class: JClass,
+ device_id: JString,
+ body: JString,
+) {
+ let device_id = read_string(&mut env, &device_id);
+ let body = read_string(&mut env, &body);
+ guard(&mut env, "RemoteCommand", || {
+ crate::remote::command(&device_id?, body?)
+ });
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemoteVolume(
+ mut env: JNIEnv,
+ _class: JClass,
+ device_id: JString,
+ volume: jint,
+) {
+ let device_id = read_string(&mut env, &device_id);
+ guard(&mut env, "RemoteVolume", || {
+ crate::remote::set_volume(&device_id?, volume.clamp(0, u16::MAX as i32) as u16)
+ });
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeShutdown(
_env: JNIEnv,
diff --git a/native/src/lib.rs b/native/src/lib.rs
index eda7d5f..f98251e 100644
--- a/native/src/lib.rs
+++ b/native/src/lib.rs
@@ -9,6 +9,7 @@ mod catalog;
mod engine;
mod events;
mod ffi;
+mod remote;
mod sink;
use jni::sys::{jint, JNI_VERSION_1_6};
diff --git a/native/src/remote.rs b/native/src/remote.rs
new file mode 100644
index 0000000..9068d11
--- /dev/null
+++ b/native/src/remote.rs
@@ -0,0 +1,272 @@
+//! The rest of the account's Spotify devices, watched and driven.
+//!
+//! Square is a Connect device: it publishes what it is playing and obeys what
+//! the account tells it. This is the other half of the same protocol, the half
+//! the official client also implements: seeing what *another* device is playing
+//! and telling it what to do.
+//!
+//! Two channels, and they are not the same one.
+//!
+//! Reading is the dealer, the websocket the session already holds open. Spotify
+//! pushes a `ClusterUpdate` to every device of the account whenever anything
+//! changes: which device is active, what it is playing, where it is in the
+//! track, how loud it is. Nothing is polled, and the last one received is kept
+//! here for whoever asks.
+//!
+//! Writing is an HTTP request to the access point, addressed from this device to
+//! that one. Spotify relays it; the target device is what actually obeys, so a
+//! command that lands says nothing about whether the music changed. The next
+//! cluster update is what says that.
+
+use crate::engine;
+use librespot_core::Session;
+use librespot_protocol::connect::{Cluster, ClusterUpdate};
+use librespot_protocol::player::PlayerState;
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// The account's playback as Spotify last described it.
+///
+/// One value, replaced whole: a cluster update is a complete picture, not a
+/// diff, so keeping anything from the previous one would be inventing state.
+static CLUSTER: Mutex<Option<Cluster>> = Mutex::new(None);
+
+/// Whether a watcher is already running, so a reconnection does not stack them.
+static WATCHING: AtomicBool = AtomicBool::new(false);
+
+/// Forgets the last cluster. Called when the session it came from is discarded.
+pub fn clear() {
+ if let Ok(mut cluster) = CLUSTER.lock() {
+ *cluster = None;
+ }
+ WATCHING.store(false, Ordering::SeqCst);
+}
+
+/// Starts listening for cluster updates on `session`'s dealer.
+///
+/// Runs for the life of the session. The stream ends when the dealer goes, which
+/// is what a lost connection does to it, and the next session starts another.
+pub fn watch(session: &Session, notify: impl Fn() + Send + 'static) {
+ let updates = match session
+ .dealer()
+ .listen_for("hm://connect-state/v1/cluster", Message_from_raw)
+ {
+ Ok(updates) => updates,
+ Err(e) => {
+ log::warn!("cannot watch the other devices: {e}");
+ return;
+ }
+ };
+
+ WATCHING.store(true, Ordering::SeqCst);
+ // Spawned on whatever runtime is calling, which is the engine's own: this
+ // runs inside the block_on that builds a session.
+ tokio::spawn(async move {
+ use futures_util::StreamExt;
+ let mut updates = updates;
+ while let Some(update) = updates.next().await {
+ let mut update: ClusterUpdate = match update {
+ Ok(update) => update,
+ Err(e) => {
+ log::warn!("unreadable cluster update: {e}");
+ continue;
+ }
+ };
+ let Some(cluster) = update.cluster.take() else {
+ continue;
+ };
+ log::info!(
+ "cluster update: active {} of {} devices, own {}",
+ cluster.active_device_id,
+ cluster.device.len(),
+ device_id().unwrap_or_default(),
+ );
+ if let Ok(mut stored) = CLUSTER.lock() {
+ *stored = Some(cluster);
+ }
+ notify();
+ }
+ log::info!("cluster watch ended");
+ WATCHING.store(false, Ordering::SeqCst);
+ });
+}
+
+/// `Message::from_raw` by another name, so the turbofish has somewhere to live.
+#[allow(non_snake_case)]
+fn Message_from_raw(
+ message: librespot_core::dealer::protocol::Message,
+) -> Result<ClusterUpdate, librespot_core::Error> {
+ librespot_core::dealer::protocol::Message::from_raw(message)
+}
+
+/// Whether the account is playing on a device that is not this one.
+///
+/// The question every transport command has to ask before it does anything.
+/// Taking over is an act, and it is one the listener has to have asked for:
+/// go-librespot puts the same rule the other way round, stopping its own
+/// playback the moment a cluster update names someone else, and never taking it
+/// back on its own.
+pub fn elsewhere_active() -> bool {
+ let Ok(guard) = CLUSTER.lock() else {
+ return false;
+ };
+ let Some(cluster) = guard.as_ref() else {
+ return false;
+ };
+ if cluster.active_device_id.is_empty() {
+ return false;
+ }
+ device_id()
+ .map(|own| cluster.active_device_id != own)
+ .unwrap_or(false)
+}
+
+/// This device's own Connect id, so the caller can tell "here" from "there".
+pub fn device_id() -> engine::EngineResult<String> {
+ engine::with_session(|session| session.device_id().to_string())
+}
+
+/// What is playing on the account right now, as JSON, or `{}` if nothing is.
+///
+/// Includes this device: the caller decides what to do with that, because
+/// "playing here" and "playing there" are the same protocol and only the id
+/// tells them apart.
+pub fn state_json() -> String {
+ let Ok(guard) = CLUSTER.lock() else {
+ return "{}".into();
+ };
+ let Some(cluster) = guard.as_ref() else {
+ return "{}".into();
+ };
+
+ let player: &PlayerState = &cluster.player_state;
+ let track = player.track.as_ref();
+ let device = cluster.device.get(&cluster.active_device_id);
+
+ // Position has to be worked out, not read: Spotify sends where the track was
+ // at a given timestamp, and the device has been playing ever since. Without
+ // the arithmetic the bar would sit still until the next update arrived.
+ let elapsed = if player.is_playing && !player.is_paused {
+ (now_ms() as i64 - player.timestamp).max(0)
+ } else {
+ 0
+ };
+ let position = (player.position_as_of_timestamp + elapsed).max(0);
+
+ let escape = |value: &str| serde_json::to_string(value).unwrap_or_else(|_| "\"\"".into());
+ let metadata = |key: &str| {
+ track
+ .map(|track| track.metadata.get(key).cloned().unwrap_or_default())
+ .unwrap_or_default()
+ };
+
+ format!(
+ concat!(
+ "{{\"activeDevice\":{},\"deviceName\":{},\"uri\":{},\"title\":{},",
+ "\"artist\":{},\"album\":{},\"coverUri\":{},\"contextUri\":{},\"positionMs\":{},",
+ "\"durationMs\":{},\"playing\":{},\"shuffle\":{},\"repeatContext\":{},",
+ "\"repeatTrack\":{}}}"
+ ),
+ escape(&cluster.active_device_id),
+ escape(device.map(|device| device.name.as_str()).unwrap_or("")),
+ escape(track.map(|track| track.uri.as_str()).unwrap_or("")),
+ escape(&metadata("title")),
+ escape(&metadata("artist_name")),
+ escape(&metadata("album_title")),
+ escape(&metadata("image_url")),
+ escape(&player.context_uri),
+ position,
+ player.duration,
+ player.is_playing && !player.is_paused,
+ player.options.shuffling_context,
+ player.options.repeating_context,
+ player.options.repeating_track,
+ )
+}
+
+/// Every device the account can see, as a JSON array.
+pub fn devices_json() -> String {
+ let Ok(guard) = CLUSTER.lock() else {
+ return "[]".into();
+ };
+ let Some(cluster) = guard.as_ref() else {
+ return "[]".into();
+ };
+
+ let escape = |value: &str| serde_json::to_string(value).unwrap_or_else(|_| "\"\"".into());
+ let mut devices: Vec<String> = cluster
+ .device
+ .iter()
+ .map(|(id, device)| {
+ format!(
+ "{{\"id\":{},\"name\":{},\"type\":{},\"volume\":{},\"active\":{}}}",
+ escape(id),
+ escape(&device.name),
+ escape(&format!("{:?}", device.device_type.enum_value_or_default())),
+ device.volume,
+ *id == cluster.active_device_id,
+ )
+ })
+ .collect();
+ // A stable order, since a map has none and a list that reshuffles itself
+ // every update is unusable.
+ devices.sort();
+ format!("[{}]", devices.join(","))
+}
+
+/// Sends one command to another device.
+///
+/// `body` is the JSON Spotify's own clients send, so the caller names the
+/// endpoint and this only addresses the envelope. Blocking, and answered by the
+/// access point rather than by the device: a request that succeeds means the
+/// command was accepted for delivery.
+pub fn command(device_id: &str, body: String) -> engine::EngineResult<()> {
+ if device_id.is_empty() {
+ return Err("no device to command".into());
+ }
+
+ let handle = engine::runtime_handle()?;
+ let session = engine::with_session(|session| session.clone())?;
+ let from = session.device_id().to_string();
+ let endpoint = format!("/connect-state/v1/player/command/from/{from}/to/{device_id}");
+
+ handle
+ .block_on(async move {
+ session
+ .spclient()
+ .request(&http::Method::POST, &endpoint, None, Some(body.as_bytes()))
+ .await
+ })
+ .map(|_| ())
+ .map_err(|e| format!("command failed: {e}"))
+}
+
+/// Sets another device's volume, which is a different endpoint from the rest.
+pub fn set_volume(device_id: &str, volume: u16) -> engine::EngineResult<()> {
+ if device_id.is_empty() {
+ return Err("no device to command".into());
+ }
+
+ let handle = engine::runtime_handle()?;
+ let session = engine::with_session(|session| session.clone())?;
+ let from = session.device_id().to_string();
+ let endpoint = format!("/connect-state/v1/connect/volume/from/{from}/to/{device_id}");
+ let body = format!("{{\"volume\":{volume}}}");
+
+ handle
+ .block_on(async move {
+ session
+ .spclient()
+ .request(&http::Method::PUT, &endpoint, None, Some(body.as_bytes()))
+ .await
+ })
+ .map(|_| ())
+ .map_err(|e| format!("volume failed: {e}"))
+}
+
+fn now_ms() -> u128 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|since| since.as_millis())
+ .unwrap_or(0)
+}
diff --git a/native/vendor/README.md b/native/vendor/README.md
index 4f5a575..762f840 100644
--- a/native/vendor/README.md
+++ b/native/vendor/README.md
@@ -97,3 +97,62 @@ it is an error the caller can handle rather than a process exit.
Re-apply this patch when bumping `librespot-core`. If the whole file is replaced,
the marker to look for is `LOCAL PATCH` in `src/config.rs`.
+
+## librespot-playback
+
+Copy of [`librespot-playback` 0.8.0](https://github.com/librespot-org/librespot)
+(MIT, licence retained), wired in the same way.
+
+### The patch: crossfade
+
+Upstream plays one track at a time, start to finish, and the next one begins
+where the last one stopped. Overlapping them cannot be done from outside the
+crate: the player owns the decoder and the sink, and nothing it exposes lets a
+caller reach the samples of two tracks at once.
+
+`PlayerConfig` gains `crossfade_duration_ms`, zero by default, which leaves
+upstream behaviour exactly as it was.
+
+When it is set, the player announces `EndOfTrack` a fade's length before the
+track really ends. Whoever owns the queue answers with a load, as it always
+does, and that load is what starts the fade: instead of dropping the decoder of
+the track being replaced, `start_playback` hands it to `fade_out`, where it is
+read for the length of the fade and then dropped. Nothing in the player decides
+what plays next, so the Connect device stays the only thing that does.
+
+The mix is equal power, `cos` out and `sin` in, one gain per frame. Two straight
+ramps summed dip in the middle, where both tracks are at half; squared cosine
+and sine sum to one, so the loudness holds across the overlap. Both sides carry
+their own normalisation factor, since normalisation exists to make two masters
+sound alike and a fade is the one moment both are heard. The result is clamped
+to `32767/32768`, because full scale is asymmetric and a mix that reaches 1.0
+wraps to the bottom and is heard as a click.
+
+A track shorter than the fade simply drains early: the incoming track goes on
+rising, over silence rather than over music.
+
+### Maintenance
+
+The markers are `LOCAL PATCH` in `src/player.rs` and `src/config.rs`.
+
+## librespot-connect
+
+Copy of [`librespot-connect` 0.8.0](https://github.com/librespot-org/librespot)
+(MIT, licence retained), wired in the same way.
+
+### The patch: is this device the one playing?
+
+`ConnectState` knows, and nothing outside the event loop could ask. `Spirc` now
+carries an `AtomicBool` that the loop republishes every turn, and a
+`Spirc::is_active()` that reads it.
+
+The alternative was reading the cluster, which is a different question wearing
+the same clothes. When another client hands playback to this device, Spotify
+sends the transfer and this device starts playing immediately, but the account
+goes on naming the previous device as active for as long as that device takes to
+let go. A web player holds on for tens of seconds. Every guard in the engine that
+asked the cluster therefore got "somebody else is playing" while this phone was
+the one making the sound, and refused to do its job.
+
+go-librespot keeps the same answer as a single boolean it owns and gates
+everything on it; this is that boolean, borrowed back out of librespot.
diff --git a/native/vendor/librespot-connect/.cargo_vcs_info.json b/native/vendor/librespot-connect/.cargo_vcs_info.json
new file mode 100644
index 0000000..0a2388d
--- /dev/null
+++ b/native/vendor/librespot-connect/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "d36f9f1907e8cc9d68a93f8ebc6b627b1bf7267d"
+ },
+ "path_in_vcs": "connect"
+}
\ No newline at end of file
diff --git a/native/vendor/librespot-connect/Cargo.toml b/native/vendor/librespot-connect/Cargo.toml
new file mode 100644
index 0000000..c8dd201
--- /dev/null
+++ b/native/vendor/librespot-connect/Cargo.toml
@@ -0,0 +1,87 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+rust-version = "1.85"
+name = "librespot-connect"
+version = "0.8.0"
+authors = ["Paul Lietar <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "The Spotify Connect logic for librespot"
+readme = "README.md"
+license = "MIT"
+repository = "https://github.com/librespot-org/librespot"
+
+[features]
+default = ["native-tls"]
+native-tls = ["librespot-core/native-tls"]
+rustls-tls-native-roots = ["librespot-core/rustls-tls-native-roots"]
+rustls-tls-webpki-roots = ["librespot-core/rustls-tls-webpki-roots"]
+
+[lib]
+name = "librespot_connect"
+path = "src/lib.rs"
+
+[dependencies.futures-util]
+version = "0.3"
+features = ["std"]
+default-features = false
+
+[dependencies.librespot-core]
+version = "0.8.0"
+default-features = false
+
+[dependencies.librespot-playback]
+version = "0.8.0"
+default-features = false
+
+[dependencies.librespot-protocol]
+version = "0.8.0"
+default-features = false
+
+[dependencies.log]
+version = "0.4"
+
+[dependencies.protobuf]
+version = "3.7"
+
+[dependencies.rand]
+version = "0.9"
+features = ["small_rng"]
+default-features = false
+
+[dependencies.serde_json]
+version = "1.0"
+
+[dependencies.thiserror]
+version = "2"
+
+[dependencies.tokio]
+version = "1"
+features = [
+ "macros",
+ "sync",
+]
+
+[dependencies.tokio-stream]
+version = "0.1"
+default-features = false
+
+[dependencies.uuid]
+version = "1.18"
+features = ["v4"]
+default-features = false
diff --git a/native/vendor/librespot-connect/Cargo.toml.orig b/native/vendor/librespot-connect/Cargo.toml.orig
new file mode 100644
index 0000000..95f0e74
--- /dev/null
+++ b/native/vendor/librespot-connect/Cargo.toml.orig
@@ -0,0 +1,33 @@
+[package]
+name = "librespot-connect"
+version = "0.8.0"
+rust-version.workspace = true
+authors = ["Paul Lietar <[email protected]>"]
+license.workspace = true
+description = "The Spotify Connect logic for librespot"
+repository.workspace = true
+edition.workspace = true
+
+[features]
+# Refer to the workspace Cargo.toml for the list of features
+default = ["native-tls"]
+
+# TLS backend propagation
+native-tls = ["librespot-core/native-tls"]
+rustls-tls-native-roots = ["librespot-core/rustls-tls-native-roots"]
+rustls-tls-webpki-roots = ["librespot-core/rustls-tls-webpki-roots"]
+
+[dependencies]
+librespot-core = { version = "0.8.0", path = "../core", default-features = false }
+librespot-playback = { version = "0.8.0", path = "../playback", default-features = false }
+librespot-protocol = { version = "0.8.0", path = "../protocol", default-features = false }
+
+futures-util = { version = "0.3", default-features = false, features = ["std"] }
+log = "0.4"
+protobuf = "3.7"
+rand = { version = "0.9", default-features = false, features = ["small_rng"] }
+serde_json = "1.0"
+thiserror = "2"
+tokio = { version = "1", features = ["macros", "sync"] }
+tokio-stream = { version = "0.1", default-features = false }
+uuid = { version = "1.18", default-features = false, features = ["v4"] }
diff --git a/native/vendor/librespot-connect/README.md b/native/vendor/librespot-connect/README.md
new file mode 100644
index 0000000..015cce3
--- /dev/null
+++ b/native/vendor/librespot-connect/README.md
@@ -0,0 +1,63 @@
+[//]: # (This readme is optimized for inline rustdoc, if some links don't work, they will when included in lib.rs)
+
+# Connect
+
+The connect module of librespot. Provides the option to create your own connect device
+and stream to it like any other official spotify client.
+
+The [`Spirc`] is the entrypoint to creating your own connect device. It can be
+configured with the given [`ConnectConfig`] options and requires some additional data
+to start up the device.
+
+When creating a new [`Spirc`] it returns two items. The [`Spirc`] itself, which is can
+be used as to control the local connect device. And a [`Future`](std::future::Future),
+lets name it `SpircTask`, that starts and executes the event loop of the connect device
+when awaited.
+
+A basic example in which the `Spirc` and `SpircTask` is used can be found here:
+[`examples/play_connect.rs`](../examples/play_connect.rs).
+
+# Example
+
+```rust
+use std::{future::Future, thread};
+
+use librespot_connect::{ConnectConfig, Spirc};
+use librespot_core::{authentication::Credentials, Error, Session, SessionConfig};
+use librespot_playback::{
+ audio_backend, mixer,
+ config::{AudioFormat, PlayerConfig},
+ mixer::{MixerConfig, NoOpVolume},
+ player::Player
+};
+
+async fn create_basic_spirc() -> Result<(), Error> {
+ let credentials = Credentials::with_access_token("access-token-here");
+ let session = Session::new(SessionConfig::default(), None);
+
+ let backend = audio_backend::find(None).expect("will default to rodio");
+
+ let player = Player::new(
+ PlayerConfig::default(),
+ session.clone(),
+ Box::new(NoOpVolume),
+ move || {
+ let format = AudioFormat::default();
+ let device = None;
+ backend(device, format)
+ },
+ );
+
+ let mixer = mixer::find(None).expect("will default to SoftMixer");
+
+ let (spirc, spirc_task): (Spirc, _) = Spirc::new(
+ ConnectConfig::default(),
+ session,
+ credentials,
+ player,
+ mixer(MixerConfig::default())?
+ ).await?;
+
+ Ok(())
+}
+```
\ No newline at end of file
diff --git a/native/vendor/librespot-connect/src/context_resolver.rs b/native/vendor/librespot-connect/src/context_resolver.rs
new file mode 100644
index 0000000..1bc0c16
--- /dev/null
+++ b/native/vendor/librespot-connect/src/context_resolver.rs
@@ -0,0 +1,346 @@
+use crate::{
+ core::{Error, Session},
+ protocol::{
+ autoplay_context_request::AutoplayContextRequest, context::Context,
+ transfer_state::TransferState,
+ },
+ state::{ConnectState, context::ContextType},
+};
+use std::{
+ cmp::PartialEq,
+ collections::{HashMap, VecDeque},
+ fmt::{Display, Formatter},
+ hash::Hash,
+ time::Duration,
+};
+use thiserror::Error as ThisError;
+use tokio::time::Instant;
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+enum Resolve {
+ Uri(String),
+ Context(Context),
+}
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub(super) enum ContextAction {
+ Append,
+ Replace,
+}
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub(super) struct ResolveContext {
+ resolve: Resolve,
+ fallback: Option<String>,
+ update: ContextType,
+ action: ContextAction,
+}
+
+impl ResolveContext {
+ fn append_context(uri: impl Into<String>) -> Self {
+ Self {
+ resolve: Resolve::Uri(uri.into()),
+ fallback: None,
+ update: ContextType::Default,
+ action: ContextAction::Append,
+ }
+ }
+
+ pub fn from_uri(
+ uri: impl Into<String>,
+ fallback: impl Into<String>,
+ update: ContextType,
+ action: ContextAction,
+ ) -> Self {
+ let fallback_uri = fallback.into();
+ Self {
+ resolve: Resolve::Uri(uri.into()),
+ fallback: (!fallback_uri.is_empty()).then_some(fallback_uri),
+ update,
+ action,
+ }
+ }
+
+ pub fn from_context(context: Context, update: ContextType, action: ContextAction) -> Self {
+ Self {
+ resolve: Resolve::Context(context),
+ fallback: None,
+ update,
+ action,
+ }
+ }
+
+ /// the uri which should be used to resolve the context, might not be the context uri
+ fn resolve_uri(&self) -> Option<&str> {
+ // it's important to call this always, or at least for every ResolveContext
+ // otherwise we might not even check if we need to fallback and just use the fallback uri
+ match self.resolve {
+ Resolve::Uri(ref uri) => ConnectState::valid_resolve_uri(uri),
+ Resolve::Context(ref ctx) => {
+ ConnectState::find_valid_uri(ctx.uri.as_deref(), ctx.pages.first())
+ }
+ }
+ .or(self.fallback.as_deref())
+ }
+
+ /// the actual context uri
+ fn context_uri(&self) -> &str {
+ match self.resolve {
+ Resolve::Uri(ref uri) => uri,
+ Resolve::Context(ref ctx) => ctx.uri.as_deref().unwrap_or_default(),
+ }
+ }
+}
+
+impl Display for ResolveContext {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "resolve_uri: <{:?}>, context_uri: <{}>, update: <{:?}>",
+ self.resolve_uri(),
+ self.context_uri(),
+ self.update,
+ )
+ }
+}
+
+#[derive(Debug, ThisError)]
+enum ContextResolverError {
+ #[error("no next context to resolve")]
+ NoNext,
+ #[error("tried appending context with {0} pages")]
+ UnexpectedPagesSize(usize),
+ #[error("tried resolving not allowed context: {0:?}")]
+ NotAllowedContext(String),
+}
+
+impl From<ContextResolverError> for Error {
+ fn from(value: ContextResolverError) -> Self {
+ Error::failed_precondition(value)
+ }
+}
+
+pub struct ContextResolver {
+ session: Session,
+ queue: VecDeque<ResolveContext>,
+ unavailable_contexts: HashMap<ResolveContext, Instant>,
+}
+
+// time after which an unavailable context is retried
+const RETRY_UNAVAILABLE: Duration = Duration::from_secs(3600);
+
+impl ContextResolver {
+ pub fn new(session: Session) -> Self {
+ Self {
+ session,
+ queue: VecDeque::new(),
+ unavailable_contexts: HashMap::new(),
+ }
+ }
+
+ pub fn add(&mut self, resolve: ResolveContext) {
+ let last_try = self
+ .unavailable_contexts
+ .get(&resolve)
+ .map(|i| i.duration_since(Instant::now()));
+
+ let last_try = if matches!(last_try, Some(last_try) if last_try > RETRY_UNAVAILABLE) {
+ let _ = self.unavailable_contexts.remove(&resolve);
+ debug!(
+ "context was requested {}s ago, trying again to resolve the requested context",
+ last_try.expect("checked by condition").as_secs()
+ );
+ None
+ } else {
+ last_try
+ };
+
+ if last_try.is_some() {
+ debug!("tried loading unavailable context: {resolve}");
+ return;
+ } else if self.queue.contains(&resolve) {
+ debug!("update for {resolve} is already added");
+ return;
+ } else {
+ trace!(
+ "added {} to resolver queue",
+ resolve.resolve_uri().unwrap_or(resolve.context_uri())
+ )
+ }
+
+ self.queue.push_back(resolve)
+ }
+
+ pub fn add_list(&mut self, resolve: Vec<ResolveContext>) {
+ for resolve in resolve {
+ self.add(resolve)
+ }
+ }
+
+ pub fn remove_used_and_invalid(&mut self) {
+ if let Some((_, _, remove)) = self.find_next() {
+ let _ = self.queue.drain(0..remove); // remove invalid
+ }
+ self.queue.pop_front(); // remove used
+ }
+
+ pub fn clear(&mut self) {
+ self.queue = VecDeque::new()
+ }
+
+ fn find_next(&self) -> Option<(&ResolveContext, &str, usize)> {
+ for idx in 0..self.queue.len() {
+ let next = self.queue.get(idx)?;
+ match next.resolve_uri() {
+ None => {
+ warn!("skipped {idx} because of invalid resolve_uri: {next}");
+ continue;
+ }
+ Some(uri) => return Some((next, uri, idx)),
+ }
+ }
+ None
+ }
+
+ pub fn has_next(&self) -> bool {
+ self.find_next().is_some()
+ }
+
+ pub async fn get_next_context(
+ &self,
+ recent_track_uri: impl Fn() -> Vec<String>,
+ ) -> Result<Context, Error> {
+ let (next, resolve_uri, _) = self.find_next().ok_or(ContextResolverError::NoNext)?;
+
+ match next.update {
+ ContextType::Default => {
+ let mut ctx = self.session.spclient().get_context(resolve_uri).await;
+ if let Ok(ctx) = ctx.as_mut() {
+ ctx.uri = Some(next.context_uri().to_string());
+ ctx.url = ctx.uri.as_ref().map(|s| format!("context://{s}"));
+ }
+
+ ctx
+ }
+ ContextType::Autoplay => {
+ if resolve_uri.contains("spotify:show:") || resolve_uri.contains("spotify:episode:")
+ {
+ // autoplay is not supported for podcasts
+ Err(ContextResolverError::NotAllowedContext(
+ resolve_uri.to_string(),
+ ))?
+ }
+
+ let request = AutoplayContextRequest {
+ context_uri: Some(resolve_uri.to_string()),
+ recent_track_uri: recent_track_uri(),
+ ..Default::default()
+ };
+ self.session.spclient().get_autoplay_context(&request).await
+ }
+ }
+ }
+
+ pub fn mark_next_unavailable(&mut self) {
+ if let Some((next, _, _)) = self.find_next() {
+ self.unavailable_contexts
+ .insert(next.clone(), Instant::now());
+ }
+ }
+
+ pub fn apply_next_context(
+ &self,
+ state: &mut ConnectState,
+ mut context: Context,
+ ) -> Result<Option<Vec<ResolveContext>>, Error> {
+ let (next, _, _) = self.find_next().ok_or(ContextResolverError::NoNext)?;
+
+ let remaining = match next.action {
+ ContextAction::Append if context.pages.len() == 1 => state
+ .fill_context_from_page(context.pages.remove(0))
+ .map(|_| None),
+ ContextAction::Replace => {
+ let remaining = state.update_context(context, next.update);
+ if let Resolve::Context(ref ctx) = next.resolve {
+ state.merge_context(ctx.pages.clone().pop());
+ }
+
+ remaining
+ }
+ ContextAction::Append => {
+ warn!("unexpected page size: {context:#?}");
+ Err(ContextResolverError::UnexpectedPagesSize(context.pages.len()).into())
+ }
+ }?;
+
+ Ok(remaining.map(|remaining| {
+ remaining
+ .into_iter()
+ .map(ResolveContext::append_context)
+ .collect::<Vec<_>>()
+ }))
+ }
+
+ pub fn try_finish(
+ &self,
+ state: &mut ConnectState,
+ transfer_state: &mut Option<TransferState>,
+ ) -> bool {
+ let (next, _, _) = match self.find_next() {
+ None => return false,
+ Some(next) => next,
+ };
+
+ // when there is only one update type, we are the last of our kind, so we should update the state
+ if self
+ .queue
+ .iter()
+ .filter(|resolve| resolve.update == next.update)
+ .count()
+ != 1
+ {
+ return false;
+ }
+
+ match (next.update, state.active_context) {
+ (ContextType::Default, ContextType::Default) | (ContextType::Autoplay, _) => {
+ debug!(
+ "last item of type <{:?}>, finishing state setup",
+ next.update
+ );
+ }
+ (ContextType::Default, _) => {
+ debug!("skipped finishing default, because it isn't the active context");
+ return false;
+ }
+ }
+
+ let active_ctx = state.get_context(state.active_context);
+ let res = if let Some(transfer_state) = transfer_state.take() {
+ state.finish_transfer(transfer_state)
+ } else if state.shuffling_context() && next.update == ContextType::Default {
+ state.shuffle_new()
+ } else if matches!(active_ctx, Ok(ctx) if ctx.index.track == 0) {
+ // has context, and context is not touched
+ // when the index is not zero, the next index was already evaluated elsewhere
+ let ctx = active_ctx.expect("checked by precondition");
+ let idx = ConnectState::find_index_in_context(ctx, |t| {
+ state.current_track(|c| t.uri == c.uri)
+ })
+ .ok();
+
+ state.reset_playback_to_position(idx)
+ } else {
+ state.fill_up_next_tracks()
+ };
+
+ if let Err(why) = res {
+ error!("setup of state failed: {why}, last used resolve {next:#?}")
+ }
+
+ state.update_restrictions();
+ state.update_queue_revision();
+
+ true
+ }
+}
diff --git a/native/vendor/librespot-connect/src/lib.rs b/native/vendor/librespot-connect/src/lib.rs
new file mode 100644
index 0000000..ba00aa4
--- /dev/null
+++ b/native/vendor/librespot-connect/src/lib.rs
@@ -0,0 +1,19 @@
+#![warn(missing_docs)]
+#![doc=include_str!("../README.md")]
+
+#[macro_use]
+extern crate log;
+
+use librespot_core as core;
+use librespot_playback as playback;
+use librespot_protocol as protocol;
+
+mod context_resolver;
+mod model;
+mod shuffle_vec;
+mod spirc;
+mod state;
+
+pub use model::*;
+pub use spirc::*;
+pub use state::*;
diff --git a/native/vendor/librespot-connect/src/model.rs b/native/vendor/librespot-connect/src/model.rs
new file mode 100644
index 0000000..7b7fa11
--- /dev/null
+++ b/native/vendor/librespot-connect/src/model.rs
@@ -0,0 +1,199 @@
+use crate::{
+ core::dealer::protocol::SkipTo, protocol::context_player_options::ContextPlayerOptionOverrides,
+};
+
+use std::ops::Deref;
+
+/// Request for loading playback
+#[derive(Debug, Clone)]
+pub struct LoadRequest {
+ pub(super) context: PlayContext,
+ pub(super) options: LoadRequestOptions,
+}
+
+impl Deref for LoadRequest {
+ type Target = LoadRequestOptions;
+
+ fn deref(&self) -> &Self::Target {
+ &self.options
+ }
+}
+
+#[derive(Debug, Clone)]
+pub(super) enum PlayContext {
+ Uri(String),
+ Tracks(Vec<String>),
+ /// LOCAL PATCH: an explicit list of tracks, published under a real context.
+ ///
+ /// Upstream has the two apart: a context uri, where the order is Spotify's,
+ /// or a list of tracks, which is published as `spotify:web-api` because
+ /// there is nothing better to call it. Neither fits a queue that *is* a
+ /// playlist but not in the playlist's order, which is what shuffling one or
+ /// adding a track to it produces, and that is most queues.
+ ///
+ /// The consequence of calling such a queue `spotify:web-api` is not
+ /// cosmetic: no other device can resolve that context, so handing playback
+ /// to one gives it a queue that does not play, and handing it back arrives
+ /// with a state whose current track cannot be found.
+ TracksIn {
+ context_uri: String,
+ tracks: Vec<String>,
+ },
+}
+
+/// The parameters for creating a load request
+#[derive(Debug, Default, Clone)]
+pub struct LoadRequestOptions {
+ /// Whether the given tracks should immediately start playing, or just be initially loaded.
+ pub start_playing: bool,
+ /// Start the playback at a specific point of the track.
+ ///
+ /// The provided value is used as milliseconds. Providing a value greater
+ /// than the track duration will start the track at the beginning.
+ pub seek_to: u32,
+ /// Options that decide how the context starts playing
+ pub context_options: Option<LoadContextOptions>,
+ /// Decides the starting position in the given context.
+ ///
+ /// If the provided item doesn't exist or is out of range,
+ /// the playback starts at the beginning of the context.
+ ///
+ /// If `None` is provided and `shuffle` is `true`, a random track is played, otherwise the first
+ pub playing_track: Option<PlayingTrack>,
+}
+
+/// The options which decide how the playback is started
+///
+/// Separated into an `enum` to exclude the other variants from being used
+/// simultaneously, as they are not compatible.
+#[derive(Debug, Clone)]
+pub enum LoadContextOptions {
+ /// Starts the context with options
+ Options(Options),
+ /// Starts the playback as the autoplay variant of the context
+ ///
+ /// This is the same as finishing a context and
+ /// automatically continuing playback of similar tracks
+ Autoplay,
+}
+
+/// The available options that indicate how to start the context
+#[derive(Debug, Default, Clone)]
+pub struct Options {
+ /// Start the context in shuffle mode
+ pub shuffle: bool,
+ /// Start the context in repeat mode
+ pub repeat: bool,
+ /// Start the context, repeating the first track until skipped or manually disabled
+ pub repeat_track: bool,
+}
+
+impl From<ContextPlayerOptionOverrides> for Options {
+ fn from(value: ContextPlayerOptionOverrides) -> Self {
+ Self {
+ shuffle: value.shuffling_context.unwrap_or_default(),
+ repeat: value.repeating_context.unwrap_or_default(),
+ repeat_track: value.repeating_track.unwrap_or_default(),
+ }
+ }
+}
+
+impl LoadRequest {
+ /// Create a load request from a `context_uri`
+ ///
+ /// For supported `context_uri` see [`SpClient::get_context`](librespot_core::spclient::SpClient::get_context)
+ ///
+ /// Equivalent to using [`/me/player/play`](https://developer.spotify.com/documentation/web-api/reference/start-a-users-playback)
+ /// and providing `context_uri`
+ pub fn from_context_uri(context_uri: String, options: LoadRequestOptions) -> Self {
+ Self {
+ context: PlayContext::Uri(context_uri),
+ options,
+ }
+ }
+
+ /// LOCAL PATCH: create a load request from a set of `tracks` that belong to
+ /// a real context, keeping the caller's order and publishing the context.
+ pub fn from_tracks_in(
+ context_uri: String,
+ tracks: Vec<String>,
+ options: LoadRequestOptions,
+ ) -> Self {
+ Self {
+ context: PlayContext::TracksIn {
+ context_uri,
+ tracks,
+ },
+ options,
+ }
+ }
+
+ /// Create a load request from a set of `tracks`
+ ///
+ /// Equivalent to using [`/me/player/play`](https://developer.spotify.com/documentation/web-api/reference/start-a-users-playback)
+ /// and providing `uris`
+ pub fn from_tracks(tracks: Vec<String>, options: LoadRequestOptions) -> Self {
+ Self {
+ context: PlayContext::Tracks(tracks),
+ options,
+ }
+ }
+}
+
+/// An item that represent a track to play
+#[derive(Debug, Clone)]
+pub enum PlayingTrack {
+ /// Represent the track at a given index.
+ Index(u32),
+ /// Represent the uri of a track.
+ Uri(String),
+ #[doc(hidden)]
+ /// Represent an internal identifier from spotify.
+ ///
+ /// The internal identifier is not the id contained in the uri. And rather
+ /// an unrelated id probably unique in spotify's internal database. But that's
+ /// just speculation.
+ ///
+ /// This identifier is not available by any public api. It's used for varies in
+ /// any spotify client, like sorting, displaying which track is currently played
+ /// and skipping to a track. Mobile uses it pretty intensively but also web and
+ /// desktop seem to make use of it.
+ Uid(String),
+}
+
+impl TryFrom<SkipTo> for PlayingTrack {
+ type Error = ();
+
+ fn try_from(value: SkipTo) -> Result<Self, Self::Error> {
+ // order of checks is important, as the index can be 0, but still has an uid or uri provided,
+ // so we only use the index as last resort
+ if let Some(uri) = value.track_uri {
+ Ok(PlayingTrack::Uri(uri))
+ } else if let Some(uid) = value.track_uid {
+ Ok(PlayingTrack::Uid(uid))
+ } else if let Some(index) = value.track_index {
+ Ok(PlayingTrack::Index(index))
+ } else {
+ Err(())
+ }
+ }
+}
+
+#[derive(Debug)]
+pub(super) enum SpircPlayStatus {
+ Stopped,
+ LoadingPlay {
+ position_ms: u32,
+ },
+ LoadingPause {
+ position_ms: u32,
+ },
+ Playing {
+ nominal_start_time: i64,
+ preloading_of_next_track_triggered: bool,
+ },
+ Paused {
+ position_ms: u32,
+ preloading_of_next_track_triggered: bool,
+ },
+}
diff --git a/native/vendor/librespot-connect/src/shuffle_vec.rs b/native/vendor/librespot-connect/src/shuffle_vec.rs
new file mode 100644
index 0000000..595a392
--- /dev/null
+++ b/native/vendor/librespot-connect/src/shuffle_vec.rs
@@ -0,0 +1,198 @@
+use rand::{Rng, SeedableRng, rngs::SmallRng};
+use std::{
+ ops::{Deref, DerefMut},
+ vec::IntoIter,
+};
+
+#[derive(Debug, Clone, Default)]
+pub struct ShuffleVec<T> {
+ vec: Vec<T>,
+ indices: Option<Vec<usize>>,
+ /// This is primarily necessary to ensure that shuffle does not behave out of place.
+ ///
+ /// For that reason we swap the first track with the currently playing track. By that we ensure
+ /// that the shuffle state is consistent between resets of the state because the first track is
+ /// always the track with which we started playing when switching to shuffle.
+ original_first_position: Option<usize>,
+}
+
+impl<T: PartialEq> PartialEq for ShuffleVec<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.vec == other.vec
+ }
+}
+
+impl<T> Deref for ShuffleVec<T> {
+ type Target = Vec<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.vec
+ }
+}
+
+impl<T> DerefMut for ShuffleVec<T> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.vec.as_mut()
+ }
+}
+
+impl<T> IntoIterator for ShuffleVec<T> {
+ type Item = T;
+ type IntoIter = IntoIter<T>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.vec.into_iter()
+ }
+}
+
+impl<T> From<Vec<T>> for ShuffleVec<T> {
+ fn from(vec: Vec<T>) -> Self {
+ Self {
+ vec,
+ original_first_position: None,
+ indices: None,
+ }
+ }
+}
+
+impl<T> ShuffleVec<T> {
+ pub fn shuffle_with_seed<F: Fn(&T) -> bool>(&mut self, seed: u64, is_first: F) {
+ self.shuffle_with_rng(SmallRng::seed_from_u64(seed), is_first)
+ }
+
+ pub fn shuffle_with_rng<F: Fn(&T) -> bool>(&mut self, mut rng: impl Rng, is_first: F) {
+ if self.vec.len() <= 1 {
+ info!("skipped shuffling for less or equal one item");
+ return;
+ }
+
+ if self.indices.is_some() {
+ self.unshuffle()
+ }
+
+ let indices: Vec<_> = {
+ (1..self.vec.len())
+ .rev()
+ .map(|i| rng.random_range(0..i + 1))
+ .collect()
+ };
+
+ for (i, &rnd_ind) in (1..self.vec.len()).rev().zip(&indices) {
+ self.vec.swap(i, rnd_ind);
+ }
+
+ self.indices = Some(indices);
+
+ self.original_first_position = self.vec.iter().position(is_first);
+ if let Some(first_pos) = self.original_first_position {
+ self.vec.swap(0, first_pos)
+ }
+ }
+
+ pub fn unshuffle(&mut self) {
+ let indices = match self.indices.take() {
+ Some(indices) => indices,
+ None => return,
+ };
+
+ if let Some(first_pos) = self.original_first_position {
+ self.vec.swap(0, first_pos);
+ self.original_first_position = None;
+ }
+
+ for i in 1..self.vec.len() {
+ match indices.get(self.vec.len() - i - 1) {
+ None => return,
+ Some(n) => self.vec.swap(*n, i),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use rand::Rng;
+ use std::ops::Range;
+
+ fn base(range: Range<usize>) -> (ShuffleVec<usize>, u64) {
+ let seed = rand::rng().random_range(0..10_000_000_000_000);
+
+ let vec = range.collect::<Vec<_>>();
+ (vec.into(), seed)
+ }
+
+ #[test]
+ fn test_shuffle_without_first() {
+ let (base_vec, seed) = base(0..100);
+
+ let mut shuffled_vec = base_vec.clone();
+ shuffled_vec.shuffle_with_seed(seed, |_| false);
+
+ let mut different_shuffled_vec = base_vec.clone();
+ different_shuffled_vec.shuffle_with_seed(seed, |_| false);
+
+ assert_eq!(
+ shuffled_vec, different_shuffled_vec,
+ "shuffling with the same seed has the same result"
+ );
+
+ let mut unshuffled_vec = shuffled_vec.clone();
+ unshuffled_vec.unshuffle();
+
+ assert_eq!(
+ base_vec, unshuffled_vec,
+ "unshuffle restores the original state"
+ );
+ }
+
+ #[test]
+ fn test_shuffle_with_first() {
+ const MAX_RANGE: usize = 200;
+
+ let (base_vec, seed) = base(0..MAX_RANGE);
+ let rand_first = rand::rng().random_range(0..MAX_RANGE);
+
+ let mut shuffled_with_first = base_vec.clone();
+ shuffled_with_first.shuffle_with_seed(seed, |i| i == &rand_first);
+
+ assert_eq!(
+ Some(&rand_first),
+ shuffled_with_first.first(),
+ "after shuffling the first is expected to be the given item"
+ );
+
+ let mut shuffled_without_first = base_vec.clone();
+ shuffled_without_first.shuffle_with_seed(seed, |_| false);
+
+ let mut switched_positions = Vec::with_capacity(2);
+ for (i, without_first_value) in shuffled_without_first.iter().enumerate() {
+ if without_first_value != &shuffled_with_first[i] {
+ switched_positions.push(i);
+ } else {
+ assert_eq!(
+ without_first_value, &shuffled_with_first[i],
+ "shuffling with the same seed has the same result"
+ );
+ }
+ }
+
+ assert_eq!(
+ switched_positions.len(),
+ 2,
+ "only the switched positions should be different"
+ );
+
+ assert_eq!(
+ shuffled_with_first[switched_positions[0]],
+ shuffled_without_first[switched_positions[1]],
+ "the switched values should be equal"
+ );
+
+ assert_eq!(
+ shuffled_with_first[switched_positions[1]],
+ shuffled_without_first[switched_positions[0]],
+ "the switched values should be equal"
+ )
+ }
+}
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
new file mode 100644
index 0000000..3d29445
--- /dev/null
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -0,0 +1,1886 @@
+use crate::{
+ LoadContextOptions, LoadRequestOptions, PlayContext,
+ context_resolver::{ContextAction, ContextResolver, ResolveContext},
+ core::{
+ Error, Session, SpotifyUri,
+ authentication::Credentials,
+ dealer::{
+ manager::{BoxedStream, BoxedStreamResult, Reply, RequestReply},
+ protocol::{Command, FallbackWrapper, Message, Request},
+ },
+ session::UserAttributes,
+ spclient::TransferRequest,
+ },
+ model::{LoadRequest, PlayingTrack, SpircPlayStatus},
+ playback::{
+ mixer::Mixer,
+ player::{Player, PlayerEvent, PlayerEventChannel},
+ },
+ protocol::{
+ connect::{Cluster, ClusterUpdate, LogoutCommand, SetVolumeCommand},
+ context::Context,
+ explicit_content_pubsub::UserAttributesUpdate,
+ playlist4_external::PlaylistModificationInfo,
+ social_connect_v2::SessionUpdate,
+ transfer_state::TransferState,
+ user_attributes::UserAttributesMutation,
+ },
+ state::{
+ context::{ContextType, ResetContext},
+ provider::IsProvider,
+ {ConnectConfig, ConnectState},
+ },
+};
+use futures_util::StreamExt;
+use librespot_protocol::context_page::ContextPage;
+use protobuf::MessageField;
+use std::{
+ future::Future,
+ sync::Arc,
+ sync::atomic::{AtomicUsize, Ordering},
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
+use thiserror::Error;
+use tokio::{sync::mpsc, time::sleep};
+
+#[derive(Debug, Error)]
+enum SpircError {
+ #[error("response payload empty")]
+ NoData,
+ #[error("{0} had no uri")]
+ NoUri(&'static str),
+ #[error("message pushed for another URI")]
+ InvalidUri(String),
+ #[error("failed to put connect state for new device")]
+ FailedDealerSetup,
+ #[error("unknown endpoint: {0:#?}")]
+ UnknownEndpoint(serde_json::Value),
+}
+
+impl From<SpircError> for Error {
+ fn from(err: SpircError) -> Self {
+ use SpircError::*;
+ match err {
+ NoData | NoUri(_) => Error::unavailable(err),
+ InvalidUri(_) | FailedDealerSetup => Error::aborted(err),
+ UnknownEndpoint(_) => Error::unimplemented(err),
+ }
+ }
+}
+
+struct SpircTask {
+ player: Arc<Player>,
+ mixer: Arc<dyn Mixer>,
+
+ /// the state management object
+ connect_state: ConnectState,
+ /// LOCAL PATCH: kept in step with `connect_state.is_active()`; see [`Spirc`].
+ active: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ connect_established: bool,
+
+ play_request_id: Option<u64>,
+ play_status: SpircPlayStatus,
+
+ connection_id_update: BoxedStreamResult<String>,
+ connect_state_update: BoxedStreamResult<ClusterUpdate>,
+ connect_state_volume_update: BoxedStreamResult<SetVolumeCommand>,
+ connect_state_logout_request: BoxedStreamResult<LogoutCommand>,
+ playlist_update: BoxedStreamResult<PlaylistModificationInfo>,
+ session_update: BoxedStreamResult<FallbackWrapper<SessionUpdate>>,
+ connect_state_command: BoxedStream<RequestReply>,
+ user_attributes_update: BoxedStreamResult<UserAttributesUpdate>,
+ user_attributes_mutation: BoxedStreamResult<UserAttributesMutation>,
+
+ commands: Option<mpsc::UnboundedReceiver<SpircCommand>>,
+ player_events: Option<PlayerEventChannel>,
+
+ context_resolver: ContextResolver,
+
+ shutdown: bool,
+ session: Session,
+
+ /// is set when transferring, and used after resolving the contexts to finish the transfer
+ pub transfer_state: Option<TransferState>,
+
+ /// when set to true, it will update the volume after [VOLUME_UPDATE_DELAY],
+ /// when no other future resolves, otherwise resets the delay
+ update_volume: bool,
+
+ /// when set to true, it will update the volume after [UPDATE_STATE_DELAY],
+ /// when no other future resolves, otherwise resets the delay
+ update_state: bool,
+
+ spirc_id: usize,
+}
+
+static SPIRC_COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+#[derive(Debug)]
+enum SpircCommand {
+ Play,
+ PlayPause,
+ Pause,
+ Prev,
+ Next,
+ VolumeUp,
+ VolumeDown,
+ Shutdown,
+ Shuffle(bool),
+ Repeat(bool),
+ RepeatTrack(bool),
+ Disconnect { pause: bool },
+ SetPosition(u32),
+ SetVolume(u16),
+ Activate,
+ Transfer(Option<TransferRequest>),
+ Load(LoadRequest),
+}
+
+const CONTEXT_FETCH_THRESHOLD: usize = 2;
+
+// delay to update volume after a certain amount of time, instead on each update request
+const VOLUME_UPDATE_DELAY: Duration = Duration::from_millis(500);
+// to reduce updates to remote, we group some request by waiting for a set amount of time
+const UPDATE_STATE_DELAY: Duration = Duration::from_millis(200);
+
+/// The spotify connect handle
+pub struct Spirc {
+ commands: mpsc::UnboundedSender<SpircCommand>,
+ /// LOCAL PATCH: mirrors `ConnectState::is_active` for the handle's owner.
+ ///
+ /// Whether this device is the one the account is playing on is the question
+ /// every caller has to answer before it does anything, and until now only
+ /// the event loop could answer it. Reading the cluster instead is not the
+ /// same question: after playback is transferred *to* this device the
+ /// account can go on naming the previous one for a while, and it does, so a
+ /// caller trusting the cluster refuses to play on a device that is already
+ /// playing.
+ active: std::sync::Arc<std::sync::atomic::AtomicBool>,
+}
+
+impl Spirc {
+ /// LOCAL PATCH: whether this device currently holds the account's playback.
+ pub fn is_active(&self) -> bool {
+ self.active.load(std::sync::atomic::Ordering::SeqCst)
+ }
+}
+
+impl Spirc {
+ /// Initializes a new spotify connect device
+ ///
+ /// The returned tuple consists out of a handle to the [`Spirc`] that
+ /// can control the local connect device when active. And a [`Future`]
+ /// which represents the [`Spirc`] event loop that processes the whole
+ /// connect device logic.
+ pub async fn new(
+ config: ConnectConfig,
+ session: Session,
+ credentials: Credentials,
+ player: Arc<Player>,
+ mixer: Arc<dyn Mixer>,
+ ) -> Result<(Spirc, impl Future<Output = ()>), Error> {
+ fn extract_connection_id(msg: Message) -> Result<String, Error> {
+ let connection_id = msg
+ .headers
+ .get("Spotify-Connection-Id")
+ .ok_or_else(|| SpircError::InvalidUri(msg.uri.clone()))?;
+ Ok(connection_id.to_owned())
+ }
+
+ let spirc_id = SPIRC_COUNTER.fetch_add(1, Ordering::AcqRel);
+ debug!("new Spirc[{spirc_id}]");
+
+ let connect_state = ConnectState::new(config, &session);
+
+ let connection_id_update = session
+ .dealer()
+ .listen_for("hm://pusher/v1/connections/", extract_connection_id)?;
+
+ let connect_state_update = session
+ .dealer()
+ .listen_for("hm://connect-state/v1/cluster", Message::from_raw)?;
+
+ let connect_state_volume_update = session
+ .dealer()
+ .listen_for("hm://connect-state/v1/connect/volume", Message::from_raw)?;
+
+ let connect_state_logout_request = session
+ .dealer()
+ .listen_for("hm://connect-state/v1/connect/logout", Message::from_raw)?;
+
+ let playlist_update = session
+ .dealer()
+ .listen_for("hm://playlist/v2/playlist/", Message::from_raw)?;
+
+ let session_update = session
+ .dealer()
+ .listen_for("social-connect/v2/session_update", Message::try_from_json)?;
+
+ let user_attributes_update = session
+ .dealer()
+ .listen_for("spotify:user:attributes:update", Message::from_raw)?;
+
+ // can be trigger by toggling autoplay in a desktop client
+ let user_attributes_mutation = session
+ .dealer()
+ .listen_for("spotify:user:attributes:mutated", Message::from_raw)?;
+
+ let connect_state_command = session
+ .dealer()
+ .handle_for("hm://connect-state/v1/player/command")?;
+
+ // pre-acquire client_token, preventing multiple request while running
+ let _ = session.spclient().client_token().await?;
+
+ // Connect *after* all message listeners are registered
+ session.connect(credentials, true).await?;
+
+ // pre-acquire access_token (we need to be authenticated to retrieve a token)
+ let _ = session.login5().auth_token().await?;
+
+ let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
+
+ let player_events = player.get_player_event_channel();
+
+ let mut task = SpircTask {
+ player,
+ mixer,
+
+ connect_state,
+ connect_established: false,
+
+ play_request_id: None,
+ play_status: SpircPlayStatus::Stopped,
+
+ connection_id_update,
+ connect_state_update,
+ connect_state_volume_update,
+ connect_state_logout_request,
+ playlist_update,
+ session_update,
+ connect_state_command,
+ user_attributes_update,
+ user_attributes_mutation,
+ commands: Some(cmd_rx),
+ player_events: Some(player_events),
+
+ context_resolver: ContextResolver::new(session.clone()),
+
+ shutdown: false,
+ session,
+
+ transfer_state: None,
+ update_volume: false,
+ update_state: false,
+ // LOCAL PATCH: replaced with the handle's own the moment it exists.
+ active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+
+ spirc_id,
+ };
+
+ let active = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ task.active = active.clone();
+
+ let spirc = Spirc {
+ commands: cmd_tx,
+ active,
+ };
+
+ let initial_volume = task.connect_state.device_info().volume;
+ task.connect_state.set_volume(0);
+
+ match initial_volume.try_into() {
+ Ok(volume) => {
+ task.set_volume(volume);
+ // we don't want to update the volume initially,
+ // we just want to set the mixer to the correct volume
+ task.update_volume = false;
+ }
+ Err(why) => error!("failed to update initial volume: {why}"),
+ };
+
+ Ok((spirc, task.run()))
+ }
+
+ /// Safely shutdowns the spirc.
+ ///
+ /// This pauses the playback, disconnects the connect device and
+ /// bring the future initially returned to an end.
+ pub fn shutdown(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Shutdown)?)
+ }
+
+ /// Resumes the playback
+ ///
+ /// Does nothing if we are not the active device, or it isn't paused.
+ pub fn play(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Play)?)
+ }
+
+ /// Resumes or pauses the playback
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn play_pause(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::PlayPause)?)
+ }
+
+ /// Pauses the playback
+ ///
+ /// Does nothing if we are not the active device, or if it isn't playing.
+ pub fn pause(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Pause)?)
+ }
+
+ /// Seeks to the beginning or skips to the previous track.
+ ///
+ /// Seeks to the beginning when the current track position
+ /// is greater than 3 seconds.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn prev(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Prev)?)
+ }
+
+ /// Skips to the next track.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn next(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Next)?)
+ }
+
+ /// Increases the volume by configured steps of [ConnectConfig].
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn volume_up(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::VolumeUp)?)
+ }
+
+ /// Decreases the volume by configured steps of [ConnectConfig].
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn volume_down(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::VolumeDown)?)
+ }
+
+ /// Shuffles the playback according to the value.
+ ///
+ /// If true shuffles/reshuffles the playback. Otherwise, does
+ /// nothing (if not shuffled) or unshuffles the playback while
+ /// resuming at the position of the current track.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn shuffle(&self, shuffle: bool) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Shuffle(shuffle))?)
+ }
+
+ /// Repeats the playback context according to the value.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn repeat(&self, repeat: bool) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Repeat(repeat))?)
+ }
+
+ /// Repeats the current track if true.
+ ///
+ /// Does nothing if we are not the active device.
+ ///
+ /// Skipping to the next track disables the repeating.
+ pub fn repeat_track(&self, repeat: bool) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::RepeatTrack(repeat))?)
+ }
+
+ /// Update the volume to the given value.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn set_volume(&self, volume: u16) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::SetVolume(volume))?)
+ }
+
+ /// Updates the position to the given value.
+ ///
+ /// Does nothing if we are not the active device.
+ ///
+ /// If value is greater than the track duration,
+ /// the update is ignored.
+ pub fn set_position_ms(&self, position_ms: u32) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::SetPosition(position_ms))?)
+ }
+
+ /// Load a new context and replace the current.
+ ///
+ /// Does nothing if we are not the active device.
+ ///
+ /// Does not overwrite the queue.
+ pub fn load(&self, command: LoadRequest) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Load(command))?)
+ }
+
+ /// Disconnects the current device and pauses the playback according the value.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn disconnect(&self, pause: bool) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Disconnect { pause })?)
+ }
+
+ /// Acquires the control as active connect device.
+ ///
+ /// Does not [Spirc::transfer] the playback. Does nothing if we are not the active device.
+ pub fn activate(&self) -> Result<(), Error> {
+ Ok(self.commands.send(SpircCommand::Activate)?)
+ }
+
+ /// Acquires the control as active connect device over the transfer flow.
+ ///
+ /// Does nothing if we are not the active device.
+ pub fn transfer(&self, transfer_request: Option<TransferRequest>) -> Result<(), Error> {
+ Ok(self
+ .commands
+ .send(SpircCommand::Transfer(transfer_request))?)
+ }
+}
+
+impl SpircTask {
+ async fn run(mut self) {
+ // simplify unwrapping of received item or parsed result
+ macro_rules! unwrap {
+ ( $next:expr, |$some:ident| $use_some:expr ) => {
+ match $next {
+ Some($some) => $use_some,
+ None => {
+ error!("{} selected, but none received", stringify!($next));
+ break;
+ }
+ }
+ };
+ ( $next:expr, match |$ok:ident| $use_ok:expr ) => {
+ unwrap!($next, |$ok| match $ok {
+ Ok($ok) => $use_ok,
+ Err(why) => error!("could not parse {}: {}", stringify!($ok), why),
+ })
+ };
+ }
+
+ if let Err(why) = self.session.dealer().start().await {
+ error!("starting dealer failed: {why}");
+ return;
+ }
+
+ while !self.session.is_invalid() && !self.shutdown {
+ // LOCAL PATCH: published every turn, so a caller outside the loop can
+ // ask whether this device holds playback without guessing from the
+ // cluster; see [`Spirc`].
+ self.active.store(
+ self.connect_state.is_active(),
+ std::sync::atomic::Ordering::SeqCst,
+ );
+
+ let commands = self.commands.as_mut();
+ let player_events = self.player_events.as_mut();
+
+ // when state and volume update have a higher priority than context resolving
+ // because of that the context resolving has to wait, so that the other tasks can finish
+ let allow_context_resolving = !self.update_state && !self.update_volume;
+
+ tokio::select! {
+ // startup of the dealer requires a connection_id, which is retrieved at the very beginning
+ connection_id_update = self.connection_id_update.next() => unwrap! {
+ connection_id_update,
+ match |connection_id| if let Err(why) = self.handle_connection_id_update(connection_id).await {
+ error!("failed handling connection id update: {why}");
+ break;
+ }
+ },
+ // main dealer update of any remote device updates
+ cluster_update = self.connect_state_update.next() => unwrap! {
+ cluster_update,
+ match |cluster_update| if let Err(e) = self.handle_cluster_update(cluster_update).await {
+ error!("could not dispatch connect state update: {e}");
+ }
+ },
+ // main dealer request handling (dealer expects an answer)
+ request = self.connect_state_command.next() => unwrap! {
+ request,
+ |request| if let Err(e) = self.handle_connect_state_request(request).await {
+ error!("couldn't handle connect state command: {e}");
+ }
+ },
+ // volume request handling is send separately (it's more like a fire forget)
+ volume_update = self.connect_state_volume_update.next() => unwrap! {
+ volume_update,
+ match |volume_update| match volume_update.volume.try_into() {
+ Ok(volume) => self.set_volume(volume),
+ Err(why) => error!("can't update volume, failed to parse i32 to u16: {why}")
+ }
+ },
+ logout_request = self.connect_state_logout_request.next() => unwrap! {
+ logout_request,
+ |logout_request| {
+ error!("received logout request, currently not supported: {logout_request:#?}");
+ // todo: call logout handling
+ }
+ },
+ playlist_update = self.playlist_update.next() => unwrap! {
+ playlist_update,
+ match |playlist_update| if let Err(why) = self.handle_playlist_modification(playlist_update) {
+ error!("failed to handle playlist modification: {why}")
+ }
+ },
+ user_attributes_update = self.user_attributes_update.next() => unwrap! {
+ user_attributes_update,
+ match |attributes| self.handle_user_attributes_update(attributes)
+ },
+ user_attributes_mutation = self.user_attributes_mutation.next() => unwrap! {
+ user_attributes_mutation,
+ match |attributes| self.handle_user_attributes_mutation(attributes)
+ },
+ session_update = self.session_update.next() => unwrap! {
+ session_update,
+ match |session_update| self.handle_session_update(session_update)
+ },
+ cmd = async { commands?.recv().await }, if commands.is_some() && self.connect_established => if let Some(cmd) = cmd {
+ if let Err(e) = self.handle_command(cmd).await {
+ debug!("could not dispatch command: {e}");
+ }
+ },
+ event = async { player_events?.recv().await }, if player_events.is_some() => if let Some(event) = event {
+ if let Err(e) = self.handle_player_event(event) {
+ error!("could not dispatch player event: {e}");
+ }
+ },
+ _ = async { sleep(UPDATE_STATE_DELAY).await }, if self.update_state => {
+ self.update_state = false;
+
+ if let Err(why) = self.notify().await {
+ error!("state update: {why}")
+ }
+ },
+ _ = async { sleep(VOLUME_UPDATE_DELAY).await }, if self.update_volume => {
+ self.update_volume = false;
+
+ info!("delayed volume update for all devices: volume is now {}", self.connect_state.device_info().volume);
+ if let Err(why) = self.connect_state.notify_volume_changed(&self.session).await {
+ error!("error updating connect state for volume update: {why}")
+ }
+
+ // for some reason the web-player does need two separate updates, so that the
+ // position of the current track is retained, other clients also send a state
+ // update before they send the volume update
+ if let Err(why) = self.notify().await {
+ error!("error updating connect state for volume update: {why}")
+ }
+ },
+ // context resolver handling, the idea/reason behind it the following:
+ //
+ // when we request a context that has multiple pages (for example an artist)
+ // resolving all pages at once can take around ~1-30sec, when we resolve
+ // everything at once that would block our main loop for that time
+ //
+ // to circumvent this behavior, we request each context separately here and
+ // finish after we received our last item of a type
+ next_context = async {
+ self.context_resolver.get_next_context(|| {
+ // Sending local file URIs to this endpoint results in a Bad Request status.
+ // It's likely appropriate to filter them out anyway; Spotify's backend
+ // has no knowledge about these tracks and so can't do anything with them.
+ self.connect_state.recent_track_uris()
+ .into_iter()
+ .filter(|t| !t.starts_with("spotify:local"))
+ .collect::<Vec<_>>()
+ }).await
+ }, if allow_context_resolving && self.context_resolver.has_next() => {
+ let update_state = self.handle_next_context(next_context);
+ if update_state {
+ if let Err(why) = self.notify().await {
+ error!("update after context resolving failed: {why}")
+ }
+ }
+ },
+ else => break
+ }
+
+ // LOCAL PATCH: the flag again, now that this turn's event has been
+ // handled. Publishing it only before the wait meant it was one
+ // event stale for as long as nothing else happened, which is
+ // exactly the case after a handover: the device had taken playback
+ // and still answered that it had not.
+ self.active.store(
+ self.connect_state.is_active(),
+ std::sync::atomic::Ordering::SeqCst,
+ );
+ }
+
+ if !self.shutdown && self.connect_state.is_active() {
+ warn!("unexpected shutdown");
+ if let Err(why) = self.handle_disconnect().await {
+ error!("error during disconnecting: {why}")
+ }
+ }
+
+ // this should clear the active session id, leaving an empty state
+ if let Err(why) = self.session.spclient().delete_connect_state_request().await {
+ error!("error during connect state deletion: {why}")
+ };
+
+ self.session.dealer().close().await;
+ }
+
+ fn handle_next_context(&mut self, next_context: Result<Context, Error>) -> bool {
+ let next_context = match next_context {
+ Err(why) => {
+ self.context_resolver.mark_next_unavailable();
+ self.context_resolver.remove_used_and_invalid();
+ error!("{why}");
+ return false;
+ }
+ Ok(ctx) => ctx,
+ };
+
+ debug!("handling next context {:?}", next_context.uri);
+
+ match self
+ .context_resolver
+ .apply_next_context(&mut self.connect_state, next_context)
+ {
+ Ok(remaining) => {
+ if let Some(remaining) = remaining {
+ self.context_resolver.add_list(remaining)
+ }
+ }
+ Err(why) => {
+ error!("{why}")
+ }
+ }
+
+ let update_state = if self
+ .context_resolver
+ .try_finish(&mut self.connect_state, &mut self.transfer_state)
+ {
+ self.add_autoplay_resolving_when_required();
+ true
+ } else {
+ false
+ };
+
+ self.context_resolver.remove_used_and_invalid();
+ update_state
+ }
+
+ // todo: is the time_delta still necessary?
+ fn now_ms(&self) -> i64 {
+ let dur = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|err| err.duration());
+
+ dur.as_millis() as i64 + 1000 * self.session.time_delta()
+ }
+
+ async fn handle_command(&mut self, cmd: SpircCommand) -> Result<(), Error> {
+ trace!("Received SpircCommand::{cmd:?}");
+ match cmd {
+ SpircCommand::Shutdown => {
+ trace!("Received SpircCommand::Shutdown");
+ self.handle_pause();
+ self.handle_disconnect().await?;
+ self.shutdown = true;
+ if let Some(rx) = self.commands.as_mut() {
+ rx.close()
+ }
+ }
+ SpircCommand::Transfer(request) if !self.connect_state.is_active() => {
+ let device_id = self.session.device_id();
+ self.session
+ .spclient()
+ .transfer(device_id, device_id, request.as_ref())
+ .await?;
+ return Ok(());
+ }
+ SpircCommand::Activate if !self.connect_state.is_active() => {
+ trace!("Received SpircCommand::{cmd:?}");
+ self.handle_activate();
+ return self.notify().await;
+ }
+ SpircCommand::Transfer(..) | SpircCommand::Activate => {
+ warn!("SpircCommand::{cmd:?} will be ignored while already active")
+ }
+ _ if !self.connect_state.is_active() => {
+ warn!("SpircCommand::{cmd:?} will be ignored while Not Active")
+ }
+ SpircCommand::Disconnect { pause } => {
+ if pause {
+ self.handle_pause()
+ }
+ return self.handle_disconnect().await;
+ }
+ SpircCommand::Play => self.handle_play(),
+ SpircCommand::PlayPause => self.handle_play_pause(),
+ SpircCommand::Pause => self.handle_pause(),
+ SpircCommand::Prev => self.handle_prev()?,
+ SpircCommand::Next => self.handle_next(None)?,
+ SpircCommand::VolumeUp => self.handle_volume_up(),
+ SpircCommand::VolumeDown => self.handle_volume_down(),
+ SpircCommand::Shuffle(shuffle) => self.handle_shuffle(shuffle)?,
+ SpircCommand::Repeat(repeat) => self.handle_repeat_context(repeat)?,
+ SpircCommand::RepeatTrack(repeat) => self.handle_repeat_track(repeat),
+ SpircCommand::SetPosition(position) => self.handle_seek(position),
+ SpircCommand::SetVolume(volume) => self.set_volume(volume),
+ SpircCommand::Load(command) => self.handle_load(command, None, None).await?,
+ };
+
+ self.notify().await
+ }
+
+ fn handle_player_event(&mut self, event: PlayerEvent) -> Result<(), Error> {
+ if let PlayerEvent::TrackChanged { audio_item } = event {
+ self.connect_state.update_duration(audio_item.duration_ms);
+ self.update_state = true;
+ return Ok(());
+ }
+
+ // update play_request_id
+ if let PlayerEvent::PlayRequestIdChanged { play_request_id } = event {
+ self.play_request_id = Some(play_request_id);
+ return Ok(());
+ }
+
+ let is_current_track = matches! {
+ (event.get_play_request_id(), self.play_request_id),
+ (Some(event_id), Some(current_id)) if event_id == current_id
+ };
+
+ // we only process events if the play_request_id matches. If it doesn't, it is
+ // an event that belongs to a previous track and only arrives now due to a race
+ // condition. In this case we have updated the state already and don't want to
+ // mess with it.
+ if !is_current_track {
+ return Ok(());
+ }
+
+ match event {
+ PlayerEvent::EndOfTrack { .. } => {
+ let next_track = self
+ .connect_state
+ .repeat_track()
+ .then(|| self.connect_state.current_track(|t| t.uri.clone()));
+
+ self.handle_next(next_track)?
+ }
+ PlayerEvent::Loading { .. } => match self.play_status {
+ SpircPlayStatus::LoadingPlay { position_ms } => {
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ trace!("==> LoadingPlay");
+ }
+ SpircPlayStatus::LoadingPause { position_ms } => {
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ trace!("==> LoadingPause");
+ }
+ _ => {
+ self.connect_state.update_position(0, self.now_ms());
+ trace!("==> Loading");
+ }
+ },
+ PlayerEvent::Seeked { position_ms, .. } => {
+ trace!("==> Seeked");
+ self.connect_state
+ .update_position(position_ms, self.now_ms())
+ }
+ PlayerEvent::Playing { position_ms, .. }
+ | PlayerEvent::PositionCorrection { position_ms, .. } => {
+ trace!("==> Playing");
+ let new_nominal_start_time = self.now_ms() - position_ms as i64;
+ match self.play_status {
+ SpircPlayStatus::Playing {
+ ref mut nominal_start_time,
+ ..
+ } => {
+ if (*nominal_start_time - new_nominal_start_time).abs() > 100 {
+ *nominal_start_time = new_nominal_start_time;
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ } else {
+ return Ok(());
+ }
+ }
+ SpircPlayStatus::LoadingPlay { .. } | SpircPlayStatus::LoadingPause { .. } => {
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ self.play_status = SpircPlayStatus::Playing {
+ nominal_start_time: new_nominal_start_time,
+ preloading_of_next_track_triggered: false,
+ };
+ }
+ _ => return Ok(()),
+ }
+ }
+ PlayerEvent::Paused {
+ position_ms: new_position_ms,
+ ..
+ } => {
+ trace!("==> Paused");
+ match self.play_status {
+ SpircPlayStatus::Paused { .. } | SpircPlayStatus::Playing { .. } => {
+ self.connect_state
+ .update_position(new_position_ms, self.now_ms());
+ self.play_status = SpircPlayStatus::Paused {
+ position_ms: new_position_ms,
+ preloading_of_next_track_triggered: false,
+ };
+ }
+ SpircPlayStatus::LoadingPlay { .. } | SpircPlayStatus::LoadingPause { .. } => {
+ self.connect_state
+ .update_position(new_position_ms, self.now_ms());
+ self.play_status = SpircPlayStatus::Paused {
+ position_ms: new_position_ms,
+ preloading_of_next_track_triggered: false,
+ };
+ }
+ _ => return Ok(()),
+ }
+ }
+ PlayerEvent::Stopped { .. } => {
+ trace!("==> Stopped");
+ match self.play_status {
+ SpircPlayStatus::Stopped => return Ok(()),
+ _ => self.play_status = SpircPlayStatus::Stopped,
+ }
+ }
+ PlayerEvent::TimeToPreloadNextTrack { .. } => {
+ self.handle_preload_next_track();
+ return Ok(());
+ }
+ PlayerEvent::Unavailable { track_id, .. } => {
+ self.handle_unavailable(&track_id)?;
+ if self.connect_state.current_track(|t| &t.uri) == &track_id.to_uri()? {
+ self.handle_next(None)?
+ }
+ }
+ _ => return Ok(()),
+ }
+
+ self.update_state = true;
+ Ok(())
+ }
+
+ async fn handle_connection_id_update(&mut self, connection_id: String) -> Result<(), Error> {
+ trace!("Received connection ID update: {connection_id:?}");
+ self.session.set_connection_id(&connection_id);
+
+ let cluster = match self
+ .connect_state
+ .notify_new_device_appeared(&self.session)
+ .await
+ {
+ Ok(res) => Cluster::parse_from_bytes(&res).ok(),
+ Err(why) => {
+ error!("{why:?}");
+ None
+ }
+ }
+ .ok_or(SpircError::FailedDealerSetup)?;
+
+ debug!(
+ "successfully put connect state for {} with connection-id {connection_id}",
+ self.session.device_id()
+ );
+
+ self.connect_established = true;
+
+ let same_session = cluster.player_state.session_id == self.session.session_id()
+ || cluster.player_state.session_id.is_empty();
+ if !cluster.active_device_id.is_empty() || !same_session {
+ info!(
+ "active device is <{}> with session <{}>",
+ cluster.active_device_id, cluster.player_state.session_id
+ );
+ return Ok(());
+ } else if cluster.transfer_data.is_empty() {
+ debug!("got empty transfer state, do nothing");
+ return Ok(());
+ } else {
+ info!(
+ "trying to take over control automatically, session_id: {}",
+ cluster.player_state.session_id
+ )
+ }
+
+ use protobuf::Message;
+
+ match TransferState::parse_from_bytes(&cluster.transfer_data) {
+ Ok(transfer_state) => self.handle_transfer(transfer_state)?,
+ Err(why) => error!("failed to take over control: {why}"),
+ }
+
+ Ok(())
+ }
+
+ fn handle_user_attributes_update(&mut self, update: UserAttributesUpdate) {
+ trace!("Received attributes update: {update:#?}");
+ let attributes: UserAttributes = update
+ .pairs
+ .iter()
+ .map(|(key, value)| (key.to_owned(), value.to_owned()))
+ .collect();
+ self.session.set_user_attributes(attributes)
+ }
+
+ fn handle_user_attributes_mutation(&mut self, mutation: UserAttributesMutation) {
+ for attribute in mutation.fields.iter() {
+ let key = &attribute.name;
+
+ if key == "autoplay" && self.session.config().autoplay.is_some() {
+ trace!("Autoplay override active. Ignoring mutation.");
+ continue;
+ }
+
+ if let Some(old_value) = self.session.user_data().attributes.get(key) {
+ let new_value = match old_value.as_ref() {
+ "0" => "1",
+ "1" => "0",
+ _ => old_value,
+ };
+ self.session.set_user_attribute(key, new_value);
+
+ trace!("Received attribute mutation, {key} was {old_value} is now {new_value}");
+
+ if key == "filter-explicit-content" && new_value == "1" {
+ self.player
+ .emit_filter_explicit_content_changed_event(matches!(new_value, "1"));
+ }
+
+ if key == "autoplay" && old_value != new_value {
+ self.player
+ .emit_auto_play_changed_event(matches!(new_value, "1"));
+
+ self.add_autoplay_resolving_when_required()
+ }
+ } else {
+ trace!("Received attribute mutation for {key} but key was not found!");
+ }
+ }
+ }
+
+ async fn handle_cluster_update(
+ &mut self,
+ mut cluster_update: ClusterUpdate,
+ ) -> Result<(), Error> {
+ let reason = cluster_update.update_reason.enum_value();
+
+ let device_ids = cluster_update.devices_that_changed.join(", ");
+ debug!(
+ "cluster update: {reason:?} from {device_ids}, active device: {}",
+ cluster_update.cluster.active_device_id
+ );
+
+ if let Some(cluster) = cluster_update.cluster.take() {
+ let became_inactive = self.connect_state.is_active()
+ && cluster.active_device_id != self.session.device_id();
+ if became_inactive {
+ info!("device became inactive");
+ self.handle_disconnect().await?;
+ self.handle_stop();
+ } else if self.connect_state.is_active() {
+ // fixme: workaround fix, because of missing information why it behaves like it does
+ // background: when another device sends a connect-state update, some player's position de-syncs
+ // tried: providing session_id, playback_id, track-metadata "track_player"
+ self.update_state = true;
+ }
+ } else if self.connect_state.is_active() {
+ self.connect_state.became_inactive(&self.session).await?;
+ }
+
+ Ok(())
+ }
+
+ async fn handle_connect_state_request(
+ &mut self,
+ (request, sender): RequestReply,
+ ) -> Result<(), Error> {
+ self.connect_state.set_last_command(request.clone());
+
+ debug!(
+ "handling: '{}' from {}",
+ request.command, request.sent_by_device_id
+ );
+
+ let response = match self.handle_request(request).await {
+ Ok(_) => Reply::Success,
+ Err(why) => {
+ error!("failed to handle request: {why}");
+ Reply::Failure
+ }
+ };
+
+ sender.send(response).map_err(Into::into)
+ }
+
+ async fn handle_request(&mut self, request: Request) -> Result<(), Error> {
+ use Command::*;
+
+ match request.command {
+ // errors and unknown commands
+ Transfer(transfer) if transfer.data.is_none() => {
+ warn!("transfer endpoint didn't contain any data to transfer");
+ Err(SpircError::NoData)?
+ }
+ Unknown(unknown) => Err(SpircError::UnknownEndpoint(unknown))?,
+ // implicit update of the connect_state
+ UpdateContext(update_context) => {
+ if matches!(update_context.context.uri, Some(ref uri) if uri != self.connect_state.context_uri())
+ {
+ debug!(
+ "ignoring context update for <{:?}>, because it isn't the current context <{}>",
+ update_context.context.uri,
+ self.connect_state.context_uri()
+ )
+ } else {
+ self.context_resolver.add(ResolveContext::from_context(
+ update_context.context,
+ ContextType::Default,
+ ContextAction::Replace,
+ ))
+ }
+ return Ok(());
+ }
+ // modification and update of the connect_state
+ Transfer(transfer) => {
+ self.handle_transfer(transfer.data.expect("by condition checked"))?;
+ return self.notify().await;
+ }
+ Play(mut play) => {
+ if !self.connect_state.is_active() {
+ self.handle_activate()
+ }
+
+ let context = match play.context.uri {
+ Some(s) => PlayContext::Uri(s),
+ None if !play.context.pages.is_empty() => PlayContext::Tracks(
+ play.context
+ .pages
+ .iter()
+ .cloned()
+ .flat_map(|p| p.tracks)
+ .flat_map(|t| t.uri)
+ .collect(),
+ ),
+ None => Err(SpircError::NoUri("context"))?,
+ };
+
+ let context_options = play
+ .options
+ .player_options_override
+ .map(Into::into)
+ .map(LoadContextOptions::Options);
+
+ let fallback_index = play
+ .options
+ .skip_to
+ .as_ref()
+ .and_then(|s| s.track_index)
+ .map(|i| i as usize);
+
+ self.handle_load(
+ LoadRequest {
+ context,
+ options: LoadRequestOptions {
+ start_playing: true,
+ seek_to: play.options.seek_to.unwrap_or_default(),
+ playing_track: play.options.skip_to.and_then(|s| s.try_into().ok()),
+ context_options,
+ },
+ },
+ play.context.pages.pop(),
+ fallback_index,
+ )
+ .await?;
+
+ self.connect_state.set_origin(play.play_origin)
+ }
+ Pause(_) => self.handle_pause(),
+ SeekTo(seek_to) => {
+ // for some reason the position is stored in value, not in position
+ trace!("seek to {seek_to:?}");
+ self.handle_seek(seek_to.value)
+ }
+ SetShufflingContext(shuffle) => self.handle_shuffle(shuffle.value)?,
+ SetRepeatingContext(repeat_context) => {
+ self.handle_repeat_context(repeat_context.value)?
+ }
+ SetRepeatingTrack(repeat_track) => self.handle_repeat_track(repeat_track.value),
+ AddToQueue(add_to_queue) => self.connect_state.add_to_queue(add_to_queue.track, true),
+ SetQueue(set_queue) => self.connect_state.handle_set_queue(set_queue),
+ SetOptions(set_options) => {
+ if let Some(repeat_context) = set_options.repeating_context {
+ self.handle_repeat_context(repeat_context)?
+ }
+
+ if let Some(repeat_track) = set_options.repeating_track {
+ self.handle_repeat_track(repeat_track)
+ }
+
+ let shuffle = set_options.shuffling_context;
+ if let Some(shuffle) = shuffle {
+ self.handle_shuffle(shuffle)?;
+ }
+ }
+ SkipNext(skip_next) => self.handle_next(skip_next.track.map(|t| t.uri))?,
+ SkipPrev(_) => self.handle_prev()?,
+ Resume(_) if matches!(self.play_status, SpircPlayStatus::Stopped) => {
+ self.load_track(true, 0)?
+ }
+ Resume(_) => self.handle_play(),
+ }
+
+ self.update_state = true;
+ Ok(())
+ }
+
+ fn handle_transfer(&mut self, mut transfer: TransferState) -> Result<(), Error> {
+ let mut ctx_uri = match transfer.current_session.context.uri {
+ None => Err(SpircError::NoUri("transfer context"))?,
+ // can apparently happen when a state is transferred and was started with "uris" via the api
+ Some(ref uri) if uri == "-" || uri.is_empty() => None,
+ Some(ref uri) => Some(uri.clone()),
+ };
+
+ self.connect_state.reset_context(
+ ctx_uri
+ .as_deref()
+ .map(ResetContext::WhenDifferent)
+ .unwrap_or(ResetContext::Completely),
+ );
+
+ match self.connect_state.current_track_from_transfer(&transfer) {
+ Err(why) => warn!("didn't find initial track: {why}"),
+ Ok(track) => {
+ debug!("found initial track <{}>", track.uri);
+ self.connect_state.set_track(track)
+ }
+ };
+
+ let autoplay = self.connect_state.current_track(|t| t.is_autoplay());
+ if autoplay {
+ ctx_uri = ctx_uri.map(|c| c.replace("station:", ""));
+ }
+
+ let fallback = self.connect_state.current_track(|t| &t.uri).clone();
+ let load_from_context_uri = ctx_uri.is_some();
+
+ match ctx_uri {
+ Some(ref uri) => {
+ self.context_resolver.add(ResolveContext::from_uri(
+ uri.clone(),
+ &fallback,
+ ContextType::Default,
+ ContextAction::Replace,
+ ));
+ }
+ None => {
+ let all_tracks = transfer
+ .current_session
+ .context
+ .pages
+ .iter()
+ .cloned()
+ .flat_map(|p| p.tracks)
+ .collect::<Vec<_>>();
+
+ if !all_tracks.is_empty() {
+ self.load_context_from_tracks(all_tracks, None)?;
+ } else {
+ warn!(
+ "tried to transfer with an invalid state, using fallback as ctx_uri ({fallback})"
+ );
+ ctx_uri = Some(fallback.clone())
+ }
+ }
+ };
+
+ self.handle_activate();
+
+ let timestamp = self.now_ms();
+ let state = &mut self.connect_state;
+ state.handle_initial_transfer(&mut transfer, ctx_uri.clone());
+
+ // adjust active context, so resolve knows for which context it should set up the state
+ state.active_context = if autoplay {
+ ContextType::Autoplay
+ } else {
+ ContextType::Default
+ };
+
+ // update position if the track continued playing
+ let transfer_timestamp = transfer.playback.timestamp.unwrap_or_default();
+ let position = match transfer.playback.position_as_of_timestamp {
+ Some(position) if transfer.playback.is_paused.unwrap_or_default() => position.into(),
+ // update position if the track continued playing
+ Some(position) if position > 0 => {
+ let time_since_position_update = timestamp - transfer_timestamp;
+ i64::from(position) + time_since_position_update
+ }
+ _ => 0,
+ };
+
+ let is_playing = !transfer.playback.is_paused();
+
+ if self.connect_state.current_track(|t| t.is_autoplay()) || autoplay {
+ if let Some(ctx_uri) = ctx_uri {
+ debug!("currently in autoplay context, async resolving autoplay for {ctx_uri}");
+ self.context_resolver.add(ResolveContext::from_uri(
+ ctx_uri,
+ fallback,
+ ContextType::Autoplay,
+ ContextAction::Replace,
+ ))
+ } else {
+ warn!("couldn't resolve autoplay context without a context uri");
+ }
+ }
+
+ if load_from_context_uri {
+ self.transfer_state = Some(transfer);
+ } else {
+ match self.connect_state.get_context(ContextType::Default) {
+ Err(why) => {
+ warn!("continuing transfer in an unknown state. {why}");
+ self.transfer_state = Some(transfer);
+ }
+ Ok(ctx) => {
+ let idx = ConnectState::find_index_in_context(ctx, |pt| {
+ self.connect_state.current_track(|t| pt.uri == t.uri)
+ })?;
+ self.connect_state.reset_playback_to_position(Some(idx))?;
+ }
+ }
+ }
+
+ self.load_track(is_playing, position.try_into()?)
+ }
+
+ async fn handle_disconnect(&mut self) -> Result<(), Error> {
+ self.context_resolver.clear();
+
+ self.play_status = SpircPlayStatus::Stopped {};
+ self.connect_state
+ .update_position_in_relation(self.now_ms());
+ self.notify().await?;
+
+ self.connect_state.became_inactive(&self.session).await?;
+
+ self.player
+ .emit_session_disconnected_event(self.session.connection_id(), self.session.username());
+
+ Ok(())
+ }
+
+ fn handle_stop(&mut self) {
+ self.player.stop();
+ self.connect_state.update_position(0, self.now_ms());
+ self.connect_state.clear_next_tracks();
+
+ if let Err(why) = self.connect_state.reset_playback_to_position(None) {
+ warn!("failed filling up next_track during stopping: {why}")
+ }
+ }
+
+ fn handle_activate(&mut self) {
+ self.connect_state.set_active(true);
+ self.player
+ .emit_session_connected_event(self.session.connection_id(), self.session.username());
+ self.player.emit_session_client_changed_event(
+ self.session.client_id(),
+ self.session.client_name(),
+ self.session.client_brand_name(),
+ self.session.client_model_name(),
+ );
+
+ self.player
+ .emit_volume_changed_event(self.connect_state.device_info().volume as u16);
+
+ self.player
+ .emit_auto_play_changed_event(self.session.autoplay());
+
+ self.player
+ .emit_filter_explicit_content_changed_event(self.session.filter_explicit_content());
+
+ self.player
+ .emit_shuffle_changed_event(self.connect_state.shuffling_context());
+
+ self.player.emit_repeat_changed_event(
+ self.connect_state.repeat_context(),
+ self.connect_state.repeat_track(),
+ );
+ }
+
+ async fn handle_load(
+ &mut self,
+ cmd: LoadRequest,
+ page: Option<ContextPage>,
+ fallback_index: Option<usize>,
+ ) -> Result<(), Error> {
+ self.connect_state
+ .reset_context(if let PlayContext::Uri(ref uri) = cmd.context {
+ ResetContext::WhenDifferent(uri)
+ } else {
+ ResetContext::Completely
+ });
+
+ self.connect_state.reset_options();
+
+ let autoplay = matches!(cmd.context_options, Some(LoadContextOptions::Autoplay));
+ match cmd.context {
+ PlayContext::Uri(uri) => {
+ self.load_context_from_uri(uri, page.as_ref(), autoplay)
+ .await?
+ }
+ PlayContext::Tracks(tracks) => self.load_context_from_tracks(tracks, None)?,
+ PlayContext::TracksIn {
+ context_uri,
+ tracks,
+ } => self.load_context_from_tracks(tracks, Some(context_uri))?,
+ }
+
+ let cmd_options = cmd.options;
+
+ self.connect_state.set_active_context(ContextType::Default);
+
+ // for play commands with skip by uid, the context of the command contains
+ // tracks with uri and uid, so we merge the new context with the resolved/existing context
+ self.connect_state.merge_context(page);
+
+ // load here, so that we clear the queue only after we definitely retrieved a new context
+ self.connect_state.clear_next_tracks();
+ self.connect_state.clear_restrictions();
+
+ debug!("play track <{:?}>", cmd_options.playing_track);
+
+ let index = match cmd_options.playing_track {
+ None => None,
+ Some(ref playing_track) => Some(match playing_track {
+ PlayingTrack::Index(i) => Ok(*i as usize),
+ PlayingTrack::Uri(uri) => {
+ let ctx = self.connect_state.get_context(ContextType::Default)?;
+ ConnectState::find_index_in_context(ctx, |t| &t.uri == uri)
+ }
+ PlayingTrack::Uid(uid) => {
+ let ctx = self.connect_state.get_context(ContextType::Default)?;
+ ConnectState::find_index_in_context(ctx, |t| &t.uid == uid)
+ }
+ }),
+ }
+ .map(|i| {
+ i.unwrap_or_else(|why| {
+ warn!(
+ "Failed to resolve index by {:?}, using fallback index: {:?} (Error: {why})",
+ cmd_options.playing_track, fallback_index
+ );
+ fallback_index.unwrap_or_default()
+ })
+ });
+
+ if let Some(LoadContextOptions::Options(ref options)) = cmd_options.context_options {
+ debug!(
+ "loading with shuffle: <{}>, repeat track: <{}> context: <{}>",
+ options.shuffle, options.repeat, options.repeat_track
+ );
+
+ self.connect_state.set_shuffle(options.shuffle);
+ self.connect_state.set_repeat_context(options.repeat);
+ self.connect_state.set_repeat_track(options.repeat_track);
+ }
+
+ if matches!(cmd_options.context_options, Some(LoadContextOptions::Options(ref o)) if o.shuffle)
+ {
+ if let Some(index) = index {
+ self.connect_state.set_current_track(index)?;
+ } else {
+ self.connect_state.set_current_track_random()?;
+ }
+
+ if self.context_resolver.has_next() {
+ self.connect_state.update_queue_revision()
+ } else {
+ self.connect_state.shuffle_new()?;
+ self.add_autoplay_resolving_when_required();
+ }
+ } else {
+ self.connect_state
+ .set_current_track(index.unwrap_or_default())?;
+ self.connect_state.reset_playback_to_position(index)?;
+ self.add_autoplay_resolving_when_required();
+ }
+
+ if self.connect_state.current_track(MessageField::is_some) {
+ self.load_track(cmd_options.start_playing, cmd_options.seek_to)?;
+ } else {
+ info!("No active track, stopping");
+ self.handle_stop()
+ }
+
+ Ok(())
+ }
+
+ async fn load_context_from_uri(
+ &mut self,
+ context_uri: String,
+ page: Option<&ContextPage>,
+ autoplay: bool,
+ ) -> Result<(), Error> {
+ if !self.connect_state.is_active() {
+ self.handle_activate();
+ }
+
+ let update_context = if autoplay {
+ ContextType::Autoplay
+ } else {
+ ContextType::Default
+ };
+
+ self.connect_state.set_active_context(update_context);
+
+ let fallback = match page {
+ // check that the uri is valid or the page has a valid uri that can be used
+ Some(page) => match ConnectState::find_valid_uri(Some(&context_uri), Some(page)) {
+ Some(ctx_uri) => ctx_uri,
+ None => return Err(SpircError::InvalidUri(context_uri).into()),
+ },
+ // when there is no page, the uri should be valid
+ None => &context_uri,
+ };
+
+ let current_context_uri = self.connect_state.context_uri();
+
+ if current_context_uri == &context_uri && fallback == context_uri {
+ debug!("context <{current_context_uri}> didn't change, no resolving required")
+ } else {
+ debug!("resolving context for load command");
+ self.context_resolver.clear();
+ self.context_resolver.add(ResolveContext::from_uri(
+ &context_uri,
+ fallback,
+ update_context,
+ ContextAction::Replace,
+ ));
+ let context = self.context_resolver.get_next_context(Vec::new).await;
+ self.handle_next_context(context);
+ }
+
+ Ok(())
+ }
+
+ fn load_context_from_tracks(
+ &mut self,
+ tracks: impl Into<ContextPage>,
+ // LOCAL PATCH: the real context these tracks came from, when there is
+ // one. See `PlayContext::TracksIn`.
+ context_uri: Option<String>,
+ ) -> Result<(), Error> {
+ const WEB_API_URI: &str = "spotify:web-api";
+ let uri = context_uri.unwrap_or_else(|| WEB_API_URI.to_string());
+ let ctx = Context {
+ // by providing values for uri/url the player in the official client's isn't frozen
+ url: Some(format!("context://{uri}")),
+ uri: Some(uri),
+ pages: vec![tracks.into()],
+ ..Default::default()
+ };
+
+ let _ = self
+ .connect_state
+ .update_context(ctx, ContextType::Default)?;
+
+ Ok(())
+ }
+
+ fn handle_play(&mut self) {
+ match self.play_status {
+ SpircPlayStatus::Paused {
+ position_ms,
+ preloading_of_next_track_triggered,
+ } => {
+ self.player.play();
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ self.play_status = SpircPlayStatus::Playing {
+ nominal_start_time: self.now_ms() - position_ms as i64,
+ preloading_of_next_track_triggered,
+ };
+ }
+ SpircPlayStatus::LoadingPause { position_ms } => {
+ self.player.play();
+ self.play_status = SpircPlayStatus::LoadingPlay { position_ms };
+ }
+ _ => return,
+ }
+
+ // Synchronize the volume from the mixer. This is useful on
+ // systems that can switch sources from and back to librespot.
+ let current_volume = self.mixer.volume();
+ self.set_volume(current_volume);
+ }
+
+ fn handle_play_pause(&mut self) {
+ match self.play_status {
+ SpircPlayStatus::Paused { .. } | SpircPlayStatus::LoadingPause { .. } => {
+ self.handle_play()
+ }
+ SpircPlayStatus::Playing { .. } | SpircPlayStatus::LoadingPlay { .. } => {
+ self.handle_pause()
+ }
+ _ => (),
+ }
+ }
+
+ fn handle_pause(&mut self) {
+ match self.play_status {
+ SpircPlayStatus::Playing {
+ nominal_start_time,
+ preloading_of_next_track_triggered,
+ } => {
+ self.player.pause();
+ let position_ms = (self.now_ms() - nominal_start_time) as u32;
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ self.play_status = SpircPlayStatus::Paused {
+ position_ms,
+ preloading_of_next_track_triggered,
+ };
+ }
+ SpircPlayStatus::LoadingPlay { position_ms } => {
+ self.player.pause();
+ self.play_status = SpircPlayStatus::LoadingPause { position_ms };
+ }
+ _ => (),
+ }
+ }
+
+ fn handle_seek(&mut self, position_ms: u32) {
+ let duration = self.connect_state.player().duration;
+ if i64::from(position_ms) > duration {
+ warn!("tried to seek to {position_ms}ms of {duration}ms");
+ return;
+ }
+
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ self.player.seek(position_ms);
+ let now = self.now_ms();
+ match self.play_status {
+ SpircPlayStatus::Stopped => (),
+ SpircPlayStatus::LoadingPause {
+ position_ms: ref mut position,
+ }
+ | SpircPlayStatus::LoadingPlay {
+ position_ms: ref mut position,
+ }
+ | SpircPlayStatus::Paused {
+ position_ms: ref mut position,
+ ..
+ } => *position = position_ms,
+ SpircPlayStatus::Playing {
+ ref mut nominal_start_time,
+ ..
+ } => *nominal_start_time = now - position_ms as i64,
+ };
+ }
+
+ fn handle_shuffle(&mut self, shuffle: bool) -> Result<(), Error> {
+ self.player.emit_shuffle_changed_event(shuffle);
+ self.connect_state.handle_shuffle(shuffle)
+ }
+
+ fn handle_repeat_context(&mut self, repeat: bool) -> Result<(), Error> {
+ self.player
+ .emit_repeat_changed_event(repeat, self.connect_state.repeat_track());
+ self.connect_state.handle_set_repeat_context(repeat)
+ }
+
+ fn handle_repeat_track(&mut self, repeat: bool) {
+ self.player
+ .emit_repeat_changed_event(self.connect_state.repeat_context(), repeat);
+ self.connect_state.set_repeat_track(repeat);
+ }
+
+ fn handle_preload_next_track(&mut self) {
+ // Requests the player thread to preload the next track
+ match self.play_status {
+ SpircPlayStatus::Paused {
+ ref mut preloading_of_next_track_triggered,
+ ..
+ }
+ | SpircPlayStatus::Playing {
+ ref mut preloading_of_next_track_triggered,
+ ..
+ } => {
+ *preloading_of_next_track_triggered = true;
+ }
+ _ => (),
+ }
+
+ if let Some(track_id) = self.connect_state.preview_next_track() {
+ self.player.preload(track_id);
+ }
+ }
+
+ // Mark unavailable tracks so we can skip them later
+ fn handle_unavailable(&mut self, track_id: &SpotifyUri) -> Result<(), Error> {
+ self.connect_state.mark_unavailable(track_id)?;
+ self.handle_preload_next_track();
+
+ Ok(())
+ }
+
+ fn add_autoplay_resolving_when_required(&mut self) {
+ let require_load_new = !self
+ .connect_state
+ .has_next_tracks(Some(CONTEXT_FETCH_THRESHOLD))
+ && self.session.autoplay()
+ && !self.connect_state.context_uri().is_empty();
+
+ if !require_load_new {
+ return;
+ }
+
+ let current_context = self.connect_state.context_uri();
+ let fallback = self.connect_state.current_track(|t| &t.uri);
+
+ let has_tracks = self
+ .connect_state
+ .get_context(ContextType::Autoplay)
+ .map(|c| !c.tracks.is_empty())
+ .unwrap_or_default();
+
+ let resolve = ResolveContext::from_uri(
+ current_context,
+ fallback,
+ ContextType::Autoplay,
+ if has_tracks {
+ ContextAction::Append
+ } else {
+ ContextAction::Replace
+ },
+ );
+
+ self.context_resolver.add(resolve);
+ }
+
+ fn handle_next(&mut self, track_uri: Option<String>) -> Result<(), Error> {
+ let continue_playing = self.connect_state.is_playing();
+
+ let current_uri = self.connect_state.current_track(|t| &t.uri);
+ let mut has_next_track =
+ matches!(track_uri, Some(ref track_uri) if current_uri == track_uri);
+
+ if !has_next_track {
+ has_next_track = loop {
+ let index = self.connect_state.next_track()?;
+
+ let current_uri = self.connect_state.current_track(|t| &t.uri);
+ if matches!(track_uri, Some(ref track_uri) if current_uri != track_uri) {
+ continue;
+ } else {
+ break index.is_some();
+ }
+ };
+ };
+
+ if has_next_track {
+ self.add_autoplay_resolving_when_required();
+ self.load_track(continue_playing, 0)
+ } else {
+ info!("Not playing next track because there are no more tracks left in queue.");
+ self.handle_stop();
+ Ok(())
+ }
+ }
+
+ fn handle_prev(&mut self) -> Result<(), Error> {
+ // Previous behaves differently based on the position
+ // Under 3s it goes to the previous song (starts playing)
+ // Over 3s it seeks to zero (retains previous play status)
+ if self.position() < 3000 {
+ let repeat_context = self.connect_state.repeat_context();
+ match self.connect_state.prev_track()? {
+ None if repeat_context => self.connect_state.reset_playback_to_position(None)?,
+ None => {
+ self.connect_state.reset_playback_to_position(None)?;
+ self.handle_stop()
+ }
+ Some(_) => self.load_track(self.connect_state.is_playing(), 0)?,
+ }
+ } else {
+ self.handle_seek(0);
+ }
+
+ Ok(())
+ }
+
+ fn handle_volume_up(&mut self) {
+ let volume = (self.connect_state.device_info().volume as u16)
+ .saturating_add(self.connect_state.volume_step_size);
+
+ self.set_volume(volume);
+ }
+
+ fn handle_volume_down(&mut self) {
+ let volume = (self.connect_state.device_info().volume as u16)
+ .saturating_sub(self.connect_state.volume_step_size);
+
+ self.set_volume(volume);
+ }
+
+ fn handle_playlist_modification(
+ &mut self,
+ playlist_modification_info: PlaylistModificationInfo,
+ ) -> Result<(), Error> {
+ let uri = playlist_modification_info
+ .uri
+ .ok_or(SpircError::NoUri("playlist modification"))?;
+ let uri = String::from_utf8(uri)?;
+
+ if self.connect_state.context_uri() != &uri {
+ debug!(
+ "ignoring playlist modification update for playlist <{uri}>, because it isn't the current context"
+ );
+ return Ok(());
+ }
+
+ debug!("playlist modification for current context: {uri}");
+ self.context_resolver.add(ResolveContext::from_uri(
+ uri,
+ self.connect_state.current_track(|t| &t.uri),
+ ContextType::Default,
+ ContextAction::Replace,
+ ));
+
+ Ok(())
+ }
+
+ fn handle_session_update(&mut self, session_update: FallbackWrapper<SessionUpdate>) {
+ // we know that this enum value isn't present in our current proto definitions, by that
+ // the json parsing fails because the enum isn't known as proto representation
+ const WBC: &str = "WIFI_BROADCAST_CHANGED";
+
+ let mut session_update = match session_update {
+ FallbackWrapper::Inner(update) => update,
+ FallbackWrapper::Fallback(value) => {
+ let fallback_inner = value.to_string();
+ if fallback_inner.contains(WBC) {
+ log::debug!("Received SessionUpdate::{WBC}");
+ } else {
+ log::warn!("SessionUpdate couldn't be parse correctly: {value:?}");
+ }
+ return;
+ }
+ };
+
+ let reason = session_update.reason.enum_value();
+
+ let mut session = match session_update.session.take() {
+ None => return,
+ Some(session) => session,
+ };
+
+ let active_device = session.host_active_device_id.take();
+ if matches!(active_device, Some(ref device) if device == self.session.device_id()) {
+ info!(
+ "session update: <{:?}> for self, current session_id {}, new session_id {}",
+ reason,
+ self.session.session_id(),
+ session.session_id
+ );
+
+ if self.session.session_id() != session.session_id {
+ self.session.set_session_id(&session.session_id);
+ self.connect_state.set_session_id(session.session_id);
+ }
+ } else {
+ debug!("session update: <{reason:?}> from active session host: <{active_device:?}>");
+ }
+
+ // this seems to be used for jams or handling the current session_id
+ //
+ // handling this event was intended to keep the playback when other clients (primarily
+ // mobile) connects, otherwise they would steel the current playback when there was no
+ // session_id provided on the initial PutStateReason::NEW_DEVICE state update
+ //
+ // by generating an initial session_id from the get-go we prevent that behavior and
+ // currently don't need to handle this event, might still be useful for later "jam" support
+ }
+
+ fn position(&mut self) -> u32 {
+ match self.play_status {
+ SpircPlayStatus::Stopped => 0,
+ SpircPlayStatus::LoadingPlay { position_ms }
+ | SpircPlayStatus::LoadingPause { position_ms }
+ | SpircPlayStatus::Paused { position_ms, .. } => position_ms,
+ SpircPlayStatus::Playing {
+ nominal_start_time, ..
+ } => (self.now_ms() - nominal_start_time) as u32,
+ }
+ }
+
+ fn load_track(&mut self, start_playing: bool, position_ms: u32) -> Result<(), Error> {
+ if self.connect_state.current_track(MessageField::is_none) {
+ debug!("current track is none, stopping playback");
+ self.handle_stop();
+ return Ok(());
+ }
+
+ let current_uri = self.connect_state.current_track(|t| &t.uri);
+ let id = SpotifyUri::from_uri(current_uri)?;
+ self.player.load(id, start_playing, position_ms);
+
+ self.connect_state
+ .update_position(position_ms, self.now_ms());
+ if start_playing {
+ self.play_status = SpircPlayStatus::LoadingPlay { position_ms };
+ } else {
+ self.play_status = SpircPlayStatus::LoadingPause { position_ms };
+ }
+ self.connect_state.set_status(&self.play_status);
+
+ Ok(())
+ }
+
+ async fn notify(&mut self) -> Result<(), Error> {
+ self.connect_state.set_status(&self.play_status);
+
+ if self.connect_state.is_playing() {
+ self.connect_state
+ .update_position_in_relation(self.now_ms());
+ }
+
+ self.connect_state.set_now(self.now_ms() as u64);
+
+ self.connect_state
+ .send_state(&self.session)
+ .await
+ .map(|_| ())
+ }
+
+ fn set_volume(&mut self, volume: u16) {
+ debug!("SpircTask::set_volume({volume})");
+
+ let old_volume = self.connect_state.device_info().volume;
+ let new_volume = volume as u32;
+ if old_volume != new_volume || self.mixer.volume() != volume {
+ self.update_volume = true;
+
+ self.connect_state.set_volume(new_volume);
+ self.mixer.set_volume(volume);
+ if let Some(cache) = self.session.cache() {
+ cache.save_volume(volume)
+ }
+ if self.connect_state.is_active() {
+ self.player.emit_volume_changed_event(volume);
+ }
+ }
+ }
+}
+
+impl Drop for SpircTask {
+ fn drop(&mut self) {
+ debug!("drop Spirc[{}]", self.spirc_id);
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state.rs b/native/vendor/librespot-connect/src/state.rs
new file mode 100644
index 0000000..b4ee61b
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state.rs
@@ -0,0 +1,499 @@
+pub(super) mod context;
+mod handle;
+mod metadata;
+mod options;
+pub(super) mod provider;
+mod restrictions;
+mod tracks;
+mod transfer;
+
+use crate::{
+ core::{
+ Error, Session, config::DeviceType, date::Date, dealer::protocol::Request,
+ spclient::SpClientResult, version,
+ },
+ model::SpircPlayStatus,
+ protocol::{
+ connect::{Capabilities, Device, DeviceInfo, MemberType, PutStateReason, PutStateRequest},
+ media::AudioQuality,
+ player::{
+ ContextIndex, ContextPlayerOptions, PlayOrigin, PlayerState, ProvidedTrack,
+ Suppressions,
+ },
+ },
+ state::{
+ context::{ContextType, ResetContext, StateContext},
+ options::ShuffleState,
+ provider::{IsProvider, Provider},
+ },
+};
+use log::LevelFilter;
+use protobuf::{EnumOrUnknown, MessageField};
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
+use thiserror::Error;
+
+// these limitations are essential, otherwise to many tracks will overload the web-player
+const SPOTIFY_MAX_PREV_TRACKS_SIZE: usize = 10;
+const SPOTIFY_MAX_NEXT_TRACKS_SIZE: usize = 80;
+
+#[derive(Debug, Error)]
+pub(super) enum StateError {
+ #[error("the current track couldn't be resolved from the transfer state")]
+ CouldNotResolveTrackFromTransfer,
+ #[error("context is not available. type: {0:?}")]
+ NoContext(ContextType),
+ #[error("could not find track {0:?} in context of {1}")]
+ CanNotFindTrackInContext(Option<usize>, usize),
+ #[error("currently {action} is not allowed because {reason}")]
+ CurrentlyDisallowed {
+ action: &'static str,
+ reason: String,
+ },
+ #[error("the provided context has no tracks")]
+ ContextHasNoTracks,
+ #[error("playback of local files is not supported")]
+ UnsupportedLocalPlayback,
+ #[error("track uri <{0:?}> contains invalid characters")]
+ InvalidTrackUri(Option<String>),
+}
+
+impl From<StateError> for Error {
+ fn from(err: StateError) -> Self {
+ use StateError::*;
+ match err {
+ CouldNotResolveTrackFromTransfer
+ | NoContext(_)
+ | CanNotFindTrackInContext(_, _)
+ | ContextHasNoTracks
+ | InvalidTrackUri(_) => Error::failed_precondition(err),
+ CurrentlyDisallowed { .. } | UnsupportedLocalPlayback => Error::unavailable(err),
+ }
+ }
+}
+
+/// Configuration of the connect device
+#[derive(Debug, Clone)]
+pub struct ConnectConfig {
+ /// The name of the connect device (default: librespot)
+ pub name: String,
+ /// The icon type of the connect device (default: [DeviceType::Speaker])
+ pub device_type: DeviceType,
+ /// Displays the [DeviceType] twice in the ui to show up as a group (default: false)
+ pub is_group: bool,
+ /// The volume with which the connect device will be initialized (default: 50%)
+ pub initial_volume: u16,
+ /// Disables the option to control the volume remotely (default: false)
+ pub disable_volume: bool,
+ /// Number of incremental steps (default: 64)
+ pub volume_steps: u16,
+}
+
+impl Default for ConnectConfig {
+ fn default() -> Self {
+ Self {
+ name: "librespot".to_string(),
+ device_type: DeviceType::Speaker,
+ is_group: false,
+ initial_volume: u16::MAX / 2,
+ disable_volume: false,
+ volume_steps: 64,
+ }
+ }
+}
+
+#[derive(Default, Debug)]
+pub(super) struct ConnectState {
+ /// the entire state that is updated to the remote server
+ request: PutStateRequest,
+
+ unavailable_uri: Vec<String>,
+
+ active_since: Option<SystemTime>,
+ queue_count: u64,
+
+ // separation is necessary because we could have already loaded
+ // the autoplay context but are still playing from the default context
+ /// to update the active context use [switch_active_context](ConnectState::set_active_context)
+ pub active_context: ContextType,
+ fill_up_context: ContextType,
+
+ /// the context from which we play, is used to top up prev and next tracks
+ context: Option<StateContext>,
+ /// seed extracted in [ConnectState::handle_initial_transfer] and used in [ConnectState::finish_transfer]
+ transfer_shuffle: Option<ShuffleState>,
+
+ /// a context to keep track of the autoplay context
+ autoplay_context: Option<StateContext>,
+
+ /// The volume adjustment per step when handling individual volume adjustments.
+ pub volume_step_size: u16,
+}
+
+impl ConnectState {
+ pub fn new(cfg: ConnectConfig, session: &Session) -> Self {
+ let volume_step_size = u16::MAX.checked_div(cfg.volume_steps).unwrap_or(1024);
+
+ let device_info = DeviceInfo {
+ can_play: true,
+ volume: cfg.initial_volume.into(),
+ name: cfg.name,
+ device_id: session.device_id().to_string(),
+ device_type: EnumOrUnknown::new(cfg.device_type.into()),
+ device_software_version: version::SEMVER.to_string(),
+ spirc_version: version::SPOTIFY_SPIRC_VERSION.to_string(),
+ client_id: session.client_id(),
+ is_group: cfg.is_group,
+ capabilities: MessageField::some(Capabilities {
+ volume_steps: cfg.volume_steps.into(),
+ disable_volume: cfg.disable_volume,
+
+ gaia_eq_connect_id: true,
+ can_be_player: true,
+ needs_full_player_state: true,
+ is_observable: true,
+ is_controllable: true,
+ hidden: false,
+
+ supports_gzip_pushes: true,
+ // todo: enable after logout handling is implemented, see spirc logout_request
+ supports_logout: false,
+ supported_types: vec![
+ "audio/episode".into(),
+ "audio/track".into(),
+ "audio/local".into(),
+ ],
+ supports_playlist_v2: true,
+ supports_transfer_command: true,
+ supports_command_request: true,
+ supports_set_options_command: true,
+
+ is_voice_enabled: false,
+ restrict_to_local: false,
+ connect_disabled: false,
+ supports_rename: false,
+ supports_external_episodes: false,
+ supports_set_backend_metadata: false,
+ supports_hifi: MessageField::none(),
+ // that "AI" dj thingy only available to specific regions/users
+ supports_dj: false,
+ supports_rooms: false,
+ // AudioQuality::HIFI is available, further investigation necessary
+ supported_audio_quality: EnumOrUnknown::new(AudioQuality::VERY_HIGH),
+
+ command_acks: true,
+
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ let mut state = Self {
+ request: PutStateRequest {
+ member_type: EnumOrUnknown::new(MemberType::CONNECT_STATE),
+ put_state_reason: EnumOrUnknown::new(PutStateReason::PLAYER_STATE_CHANGED),
+ device: MessageField::some(Device {
+ device_info: MessageField::some(device_info),
+ player_state: MessageField::some(PlayerState {
+ session_id: session.session_id(),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ },
+ volume_step_size,
+ ..Default::default()
+ };
+ state.reset();
+ state
+ }
+
+ fn reset(&mut self) {
+ self.set_active(false);
+ self.queue_count = 0;
+
+ // preserve the session_id
+ let session_id = self.player().session_id.clone();
+
+ self.device_mut().player_state = MessageField::some(PlayerState {
+ session_id,
+ is_system_initiated: true,
+ playback_speed: 1.,
+ play_origin: MessageField::some(PlayOrigin::new()),
+ suppressions: MessageField::some(Suppressions::new()),
+ options: MessageField::some(ContextPlayerOptions::new()),
+ // + 1, so that we have a buffer where we can swap elements
+ prev_tracks: Vec::with_capacity(SPOTIFY_MAX_PREV_TRACKS_SIZE + 1),
+ next_tracks: Vec::with_capacity(SPOTIFY_MAX_NEXT_TRACKS_SIZE + 1),
+ ..Default::default()
+ });
+ }
+
+ fn device_mut(&mut self) -> &mut Device {
+ self.request
+ .device
+ .as_mut()
+ .expect("the request is always available")
+ }
+
+ fn player_mut(&mut self) -> &mut PlayerState {
+ self.device_mut()
+ .player_state
+ .as_mut()
+ .expect("the player_state has to be always given")
+ }
+
+ pub fn device_info(&self) -> &DeviceInfo {
+ &self.request.device.device_info
+ }
+
+ pub fn player(&self) -> &PlayerState {
+ &self.request.device.player_state
+ }
+
+ pub fn is_active(&self) -> bool {
+ self.request.is_active
+ }
+
+ /// Returns the `is_playing` value as perceived by other connect devices
+ ///
+ /// see [ConnectState::set_status]
+ pub fn is_playing(&self) -> bool {
+ let player = self.player();
+ player.is_playing && !player.is_paused
+ }
+
+ /// Returns the `is_paused` state value as perceived by other connect devices
+ ///
+ /// see [ConnectState::set_status]
+ pub fn is_pause(&self) -> bool {
+ let player = self.player();
+ player.is_playing && player.is_paused && player.is_buffering
+ }
+
+ pub fn set_volume(&mut self, volume: u32) {
+ self.device_mut()
+ .device_info
+ .as_mut()
+ .expect("the device_info has to be always given")
+ .volume = volume;
+ }
+
+ pub fn set_last_command(&mut self, command: Request) {
+ self.request.last_command_message_id = command.message_id;
+ self.request.last_command_sent_by_device_id = command.sent_by_device_id;
+ }
+
+ pub fn set_now(&mut self, now: u64) {
+ self.request.client_side_timestamp = now;
+
+ if let Some(active_since) = self.active_since {
+ if let Ok(active_since_duration) = active_since.duration_since(UNIX_EPOCH) {
+ match active_since_duration.as_millis().try_into() {
+ Ok(active_since_ms) => self.request.started_playing_at = active_since_ms,
+ Err(why) => warn!("couldn't update active since because {why}"),
+ }
+ }
+ }
+ }
+
+ pub fn set_active(&mut self, value: bool) {
+ if value {
+ if self.request.is_active {
+ return;
+ }
+
+ self.request.is_active = true;
+ self.active_since = Some(SystemTime::now())
+ } else {
+ self.request.is_active = false;
+ self.active_since = None
+ }
+ }
+
+ pub fn set_origin(&mut self, origin: PlayOrigin) {
+ self.player_mut().play_origin = MessageField::some(origin)
+ }
+
+ pub fn set_session_id(&mut self, session_id: String) {
+ self.player_mut().session_id = session_id;
+ }
+
+ pub(crate) fn set_status(&mut self, status: &SpircPlayStatus) {
+ let player = self.player_mut();
+ player.is_paused = matches!(
+ status,
+ SpircPlayStatus::LoadingPause { .. }
+ | SpircPlayStatus::Paused { .. }
+ | SpircPlayStatus::Stopped
+ );
+
+ if player.is_paused {
+ player.playback_speed = 0.;
+ } else {
+ player.playback_speed = 1.;
+ }
+
+ // desktop and mobile require all 'states' set to true, when we are paused,
+ // otherwise the play button (desktop) is grayed out or the preview (mobile) can't be opened
+ player.is_buffering = player.is_paused
+ || matches!(
+ status,
+ SpircPlayStatus::LoadingPause { .. } | SpircPlayStatus::LoadingPlay { .. }
+ );
+ player.is_playing = player.is_paused
+ || matches!(
+ status,
+ SpircPlayStatus::LoadingPlay { .. } | SpircPlayStatus::Playing { .. }
+ );
+
+ debug!(
+ "updated connect play status playing: {}, paused: {}, buffering: {}",
+ player.is_playing, player.is_paused, player.is_buffering
+ );
+
+ self.update_restrictions()
+ }
+
+ /// index is 0 based, so the first track is index 0
+ pub fn update_current_index(&mut self, f: impl Fn(&mut ContextIndex)) {
+ match self.player_mut().index.as_mut() {
+ Some(player_index) => f(player_index),
+ None => {
+ let mut new_index = ContextIndex::new();
+ f(&mut new_index);
+ self.player_mut().index = MessageField::some(new_index)
+ }
+ }
+ }
+
+ pub fn update_position(&mut self, position_ms: u32, timestamp: i64) {
+ let player = self.player_mut();
+ player.position_as_of_timestamp = position_ms.into();
+ player.timestamp = timestamp;
+ }
+
+ pub fn update_duration(&mut self, duration: u32) {
+ self.player_mut().duration = duration.into()
+ }
+
+ pub fn update_queue_revision(&mut self) {
+ let mut state = DefaultHasher::new();
+ self.next_tracks()
+ .iter()
+ .for_each(|t| t.uri.hash(&mut state));
+ self.player_mut().queue_revision = state.finish().to_string()
+ }
+
+ pub fn reset_playback_to_position(&mut self, new_index: Option<usize>) -> Result<(), Error> {
+ debug!(
+ "reset_playback with active ctx <{:?}> fill_up ctx <{:?}>",
+ self.active_context, self.fill_up_context
+ );
+
+ let new_index = new_index.unwrap_or(0);
+ self.update_current_index(|i| i.track = new_index as u32);
+ self.update_context_index(self.active_context, new_index + 1)?;
+ self.fill_up_context = self.active_context;
+
+ if !self.current_track(|t| t.is_queue() || self.is_skip_track(t, None)) {
+ self.set_current_track(new_index)?;
+ }
+
+ self.clear_prev_track();
+
+ if new_index > 0 {
+ let context = self.get_context(self.active_context)?;
+
+ let before_new_track = context.tracks.len() - new_index;
+ self.player_mut().prev_tracks = context
+ .tracks
+ .iter()
+ .rev()
+ .skip(before_new_track)
+ .take(SPOTIFY_MAX_PREV_TRACKS_SIZE)
+ .rev()
+ .cloned()
+ .collect();
+ debug!("has {} prev tracks", self.prev_tracks().len())
+ }
+
+ self.clear_next_tracks();
+ self.fill_up_next_tracks()?;
+ self.update_restrictions();
+
+ Ok(())
+ }
+
+ fn mark_as_unavailable_for_match(track: &mut ProvidedTrack, uri: &str) {
+ if track.uri == uri {
+ debug!("Marked <{}:{}> as unavailable", track.provider, track.uri);
+ track.set_provider(Provider::Unavailable);
+ }
+ }
+
+ pub fn update_position_in_relation(&mut self, timestamp: i64) {
+ let player = self.player_mut();
+
+ let diff = timestamp - player.timestamp;
+ player.position_as_of_timestamp += diff;
+
+ if log::max_level() >= LevelFilter::Debug {
+ let pos = Duration::from_millis(player.position_as_of_timestamp as u64);
+ let time = Date::from_timestamp_ms(timestamp)
+ .map(|d| d.time().to_string())
+ .unwrap_or_else(|_| timestamp.to_string());
+
+ let sec = pos.as_secs();
+ let (min, sec) = (sec / 60, sec % 60);
+ debug!("update position to {min}:{sec:0>2} at {time}");
+ }
+
+ player.timestamp = timestamp;
+ }
+
+ pub async fn became_inactive(&mut self, session: &Session) -> SpClientResult {
+ self.reset();
+ self.reset_context(ResetContext::Completely);
+
+ session.spclient().put_connect_state_inactive(false).await
+ }
+
+ async fn send_with_reason(
+ &mut self,
+ session: &Session,
+ reason: PutStateReason,
+ ) -> SpClientResult {
+ let prev_reason = self.request.put_state_reason;
+
+ self.request.put_state_reason = EnumOrUnknown::new(reason);
+ let res = self.send_state(session).await;
+
+ self.request.put_state_reason = prev_reason;
+ res
+ }
+
+ /// Notifies the remote server about a new device
+ pub async fn notify_new_device_appeared(&mut self, session: &Session) -> SpClientResult {
+ self.send_with_reason(session, PutStateReason::NEW_DEVICE)
+ .await
+ }
+
+ /// Notifies the remote server about a new volume
+ pub async fn notify_volume_changed(&mut self, session: &Session) -> SpClientResult {
+ self.send_with_reason(session, PutStateReason::VOLUME_CHANGED)
+ .await
+ }
+
+ /// Sends the connect state for the connect session to the remote server
+ pub async fn send_state(&self, session: &Session) -> SpClientResult {
+ session
+ .spclient()
+ .put_connect_state_request(&self.request)
+ .await
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/context.rs b/native/vendor/librespot-connect/src/state/context.rs
new file mode 100644
index 0000000..838b104
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/context.rs
@@ -0,0 +1,520 @@
+use crate::{
+ core::{Error, SpotifyId, SpotifyUri},
+ protocol::{
+ context::Context,
+ context_page::ContextPage,
+ context_track::ContextTrack,
+ player::{ContextIndex, ProvidedTrack},
+ restrictions::Restrictions,
+ },
+ shuffle_vec::ShuffleVec,
+ state::{
+ ConnectState, SPOTIFY_MAX_NEXT_TRACKS_SIZE, StateError,
+ metadata::Metadata,
+ provider::{IsProvider, Provider},
+ },
+};
+use protobuf::MessageField;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+const LOCAL_FILES_IDENTIFIER: &str = "spotify:local-files";
+const SEARCH_IDENTIFIER: &str = "spotify:search";
+
+#[derive(Debug)]
+pub struct StateContext {
+ pub tracks: ShuffleVec<ProvidedTrack>,
+ pub metadata: HashMap<String, String>,
+ pub restrictions: Option<Restrictions>,
+ /// is used to keep track which tracks are already loaded into the next_tracks
+ pub index: ContextIndex,
+}
+
+#[derive(Default, Debug, Copy, Clone, PartialEq, Hash, Eq)]
+pub enum ContextType {
+ #[default]
+ Default,
+ Autoplay,
+}
+
+pub enum ResetContext<'s> {
+ Completely,
+ DefaultIndex,
+ WhenDifferent(&'s str),
+}
+
+/// Extracts the spotify uri from a given page_url
+///
+/// Just extracts "spotify/album/5LFzwirfFwBKXJQGfwmiMY" and replaces the slash's with colon's
+///
+/// Expected `page_url` should look something like the following:
+/// `hm://artistplaycontext/v1/page/spotify/album/5LFzwirfFwBKXJQGfwmiMY/km_artist`
+fn page_url_to_uri(page_url: &str) -> String {
+ let split = if let Some(rest) = page_url.strip_prefix("hm://") {
+ rest.split('/')
+ } else {
+ warn!("page_url didn't start with hm://. got page_url: {page_url}");
+ page_url.split('/')
+ };
+
+ split
+ .skip_while(|s| s != &"spotify")
+ .take(3)
+ .collect::<Vec<&str>>()
+ .join(":")
+}
+
+impl ConnectState {
+ pub fn find_index_in_context<F: Fn(&ProvidedTrack) -> bool>(
+ ctx: &StateContext,
+ f: F,
+ ) -> Result<usize, StateError> {
+ ctx.tracks
+ .iter()
+ .position(f)
+ .ok_or(StateError::CanNotFindTrackInContext(None, ctx.tracks.len()))
+ }
+
+ pub fn get_context(&self, ty: ContextType) -> Result<&StateContext, StateError> {
+ match ty {
+ ContextType::Default => self.context.as_ref(),
+ ContextType::Autoplay => self.autoplay_context.as_ref(),
+ }
+ .ok_or(StateError::NoContext(ty))
+ }
+
+ pub fn get_context_mut(&mut self, ty: ContextType) -> Result<&mut StateContext, StateError> {
+ match ty {
+ ContextType::Default => self.context.as_mut(),
+ ContextType::Autoplay => self.autoplay_context.as_mut(),
+ }
+ .ok_or(StateError::NoContext(ty))
+ }
+
+ pub fn context_uri(&self) -> &String {
+ &self.player().context_uri
+ }
+
+ fn different_context_uri(&self, uri: &str) -> bool {
+ // search identifier is always different
+ self.context_uri() != uri || uri.starts_with(SEARCH_IDENTIFIER)
+ }
+
+ pub fn reset_context(&mut self, mut reset_as: ResetContext) {
+ if matches!(reset_as, ResetContext::WhenDifferent(ctx) if self.different_context_uri(ctx)) {
+ reset_as = ResetContext::Completely
+ }
+
+ if let Ok(ctx) = self.get_context_mut(ContextType::Default) {
+ ctx.remove_shuffle_seed();
+ ctx.remove_initial_track();
+ ctx.tracks.unshuffle()
+ }
+
+ match reset_as {
+ ResetContext::WhenDifferent(_) => debug!("context didn't change, no reset"),
+ ResetContext::Completely => {
+ self.context = None;
+ self.autoplay_context = None;
+
+ let player = self.player_mut();
+ player.context_uri.clear();
+ player.context_url.clear();
+ }
+ ResetContext::DefaultIndex => {
+ for ctx in [self.context.as_mut(), self.autoplay_context.as_mut()]
+ .into_iter()
+ .flatten()
+ {
+ ctx.index.track = 0;
+ ctx.index.page = 0;
+ }
+ }
+ }
+
+ self.fill_up_context = ContextType::Default;
+ self.set_active_context(ContextType::Default);
+ self.update_restrictions()
+ }
+
+ pub fn valid_resolve_uri(uri: &str) -> Option<&str> {
+ if uri.is_empty() || uri.starts_with(SEARCH_IDENTIFIER) {
+ None
+ } else {
+ Some(uri)
+ }
+ }
+
+ pub fn find_valid_uri<'s>(
+ context_uri: Option<&'s str>,
+ first_page: Option<&'s ContextPage>,
+ ) -> Option<&'s str> {
+ context_uri
+ .and_then(Self::valid_resolve_uri)
+ .or_else(|| first_page.and_then(|p| p.tracks.first().and_then(|t| t.uri.as_deref())))
+ }
+
+ pub fn set_active_context(&mut self, new_context: ContextType) {
+ self.active_context = new_context;
+
+ let player = self.player_mut();
+
+ player.context_metadata = Default::default();
+ player.context_restrictions = MessageField::some(Default::default());
+ player.restrictions = MessageField::some(Default::default());
+
+ let ctx = match self.get_context(new_context) {
+ Err(why) => {
+ warn!("couldn't load context info because: {why}");
+ return;
+ }
+ Ok(ctx) => ctx,
+ };
+
+ let mut restrictions = ctx.restrictions.clone();
+ let metadata = ctx.metadata.clone();
+
+ let player = self.player_mut();
+
+ if let Some(restrictions) = restrictions.take() {
+ player.restrictions = MessageField::some(restrictions.into());
+ }
+
+ for (key, value) in metadata {
+ player.context_metadata.insert(key, value);
+ }
+ }
+
+ pub fn update_context(
+ &mut self,
+ mut context: Context,
+ ty: ContextType,
+ ) -> Result<Option<Vec<String>>, Error> {
+ if context.pages.iter().all(|p| p.tracks.is_empty()) {
+ error!("context didn't have any tracks: {context:#?}");
+ Err(StateError::ContextHasNoTracks)?;
+ } else if matches!(context.uri, Some(ref uri) if uri.starts_with(LOCAL_FILES_IDENTIFIER)) {
+ Err(StateError::UnsupportedLocalPlayback)?;
+ }
+
+ let mut next_contexts = Vec::new();
+ let mut first_page = None;
+ for page in context.pages {
+ if first_page.is_none() && !page.tracks.is_empty() {
+ first_page = Some(page);
+ } else {
+ next_contexts.push(page)
+ }
+ }
+
+ let page = match first_page {
+ None => Err(StateError::ContextHasNoTracks)?,
+ Some(p) => p,
+ };
+
+ debug!(
+ "updated context {ty:?} to <{:?}> ({} tracks)",
+ context.uri,
+ page.tracks.len()
+ );
+
+ match ty {
+ ContextType::Default => {
+ let mut new_context = self.state_context_from_page(
+ page,
+ context.metadata,
+ context.restrictions.take(),
+ context.uri.as_deref(),
+ Some(0),
+ None,
+ );
+
+ // when we update the same context, we should try to preserve the previous position
+ // otherwise we might load the entire context twice, unless it's the search context
+ if !self.context_uri().starts_with(SEARCH_IDENTIFIER)
+ && matches!(context.uri, Some(ref uri) if uri == self.context_uri())
+ {
+ if let Some(new_index) = self.find_last_index_in_new_context(&new_context) {
+ new_context.index.track = match new_index {
+ Ok(i) => i,
+ Err(i) => {
+ self.player_mut().index = MessageField::none();
+ i
+ }
+ };
+
+ // enforce reloading the context
+ if let Ok(autoplay_ctx) = self.get_context_mut(ContextType::Autoplay) {
+ autoplay_ctx.index.track = 0
+ }
+ self.clear_next_tracks();
+ }
+ }
+
+ self.context = Some(new_context);
+
+ if !matches!(context.url, Some(ref url) if url.contains(SEARCH_IDENTIFIER)) {
+ self.player_mut().context_url = context.url.take().unwrap_or_default();
+ } else {
+ self.player_mut().context_url.clear()
+ }
+ self.player_mut().context_uri = context.uri.take().unwrap_or_default();
+ }
+ ContextType::Autoplay => {
+ self.autoplay_context = Some(self.state_context_from_page(
+ page,
+ context.metadata,
+ context.restrictions.take(),
+ context.uri.as_deref(),
+ None,
+ Some(Provider::Autoplay),
+ ))
+ }
+ }
+
+ if next_contexts.is_empty() {
+ return Ok(None);
+ }
+
+ // load remaining contexts
+ let next_contexts = next_contexts
+ .into_iter()
+ .flat_map(|page| {
+ if !page.tracks.is_empty() {
+ self.fill_context_from_page(page).ok()?;
+ None
+ } else if matches!(page.page_url, Some(ref url) if !url.is_empty()) {
+ Some(page_url_to_uri(
+ &page.page_url.expect("checked by precondition"),
+ ))
+ } else {
+ warn!("unhandled context page: {page:#?}");
+ None
+ }
+ })
+ .collect();
+
+ Ok(Some(next_contexts))
+ }
+
+ fn find_first_prev_track_index(&self, ctx: &StateContext) -> Option<usize> {
+ let prev_tracks = self.prev_tracks();
+ for i in (0..prev_tracks.len()).rev() {
+ let prev_track = prev_tracks.get(i)?;
+ if let Ok(idx) = Self::find_index_in_context(ctx, |t| prev_track.uri == t.uri) {
+ return Some(idx);
+ }
+ }
+ None
+ }
+
+ fn find_last_index_in_new_context(
+ &self,
+ new_context: &StateContext,
+ ) -> Option<Result<u32, u32>> {
+ let ctx = self.context.as_ref()?;
+
+ let is_queued_item = self.current_track(|t| t.is_queue() || t.is_from_queue());
+
+ let new_index = if ctx.index.track as usize >= SPOTIFY_MAX_NEXT_TRACKS_SIZE {
+ Some(ctx.index.track as usize - SPOTIFY_MAX_NEXT_TRACKS_SIZE)
+ } else if is_queued_item {
+ self.find_first_prev_track_index(new_context)
+ } else {
+ Self::find_index_in_context(new_context, |current| {
+ self.current_track(|t| t.uri == current.uri)
+ })
+ .ok()
+ }
+ .map(|i| i as u32 + 1);
+
+ Some(new_index.ok_or_else(|| {
+ info!(
+ "couldn't distinguish index from current or previous tracks in the updated context"
+ );
+ let fallback_index = self
+ .player()
+ .index
+ .as_ref()
+ .map(|i| i.track)
+ .unwrap_or_default();
+ info!("falling back to index {fallback_index}");
+ fallback_index
+ }))
+ }
+
+ fn state_context_from_page(
+ &mut self,
+ page: ContextPage,
+ metadata: HashMap<String, String>,
+ restrictions: Option<Restrictions>,
+ new_context_uri: Option<&str>,
+ context_length: Option<usize>,
+ provider: Option<Provider>,
+ ) -> StateContext {
+ let new_context_uri = new_context_uri.unwrap_or(self.context_uri());
+
+ let tracks = page
+ .tracks
+ .iter()
+ .enumerate()
+ .flat_map(|(i, track)| {
+ match self.context_to_provided_track(
+ track,
+ Some(new_context_uri),
+ context_length.map(|l| l + i),
+ Some(&page.metadata),
+ provider.clone(),
+ ) {
+ Ok(t) => Some(t),
+ Err(why) => {
+ error!("couldn't convert {track:#?} into ProvidedTrack: {why}");
+ None
+ }
+ }
+ })
+ .collect::<Vec<_>>();
+
+ StateContext {
+ tracks: tracks.into(),
+ restrictions,
+ metadata,
+ index: ContextIndex::new(),
+ }
+ }
+
+ pub fn is_skip_track(&self, track: &ProvidedTrack, iteration: Option<u32>) -> bool {
+ let ctx = match self.get_context(self.active_context).ok() {
+ None => return false,
+ Some(ctx) => ctx,
+ };
+
+ if ctx.get_initial_track().is_none_or(|uri| uri != &track.uri) {
+ return false;
+ }
+
+ iteration.is_none_or(|i| i == 0)
+ }
+
+ pub fn merge_context(&mut self, new_page: Option<ContextPage>) -> Option<()> {
+ let current_context = self.get_context_mut(ContextType::Default).ok()?;
+
+ for new_track in new_page?.tracks {
+ if new_track.uri.is_none() || matches!(new_track.uri, Some(ref uri) if uri.is_empty()) {
+ continue;
+ }
+
+ let new_track_uri = new_track.uri.unwrap_or_default();
+ if let Ok(position) =
+ Self::find_index_in_context(current_context, |t| t.uri == new_track_uri)
+ {
+ let context_track = current_context.tracks.get_mut(position)?;
+
+ for (key, value) in new_track.metadata {
+ context_track.metadata.insert(key, value);
+ }
+
+ // the uid provided from another context might be actual uid of an item
+ if new_track.uid.is_some()
+ || matches!(new_track.uid, Some(ref uid) if uid.is_empty())
+ {
+ context_track.uid = new_track.uid.unwrap_or_default();
+ }
+ }
+ }
+
+ Some(())
+ }
+
+ pub(super) fn update_context_index(
+ &mut self,
+ ty: ContextType,
+ new_index: usize,
+ ) -> Result<(), StateError> {
+ let context = self.get_context_mut(ty)?;
+
+ context.index.track = new_index as u32;
+ Ok(())
+ }
+
+ pub fn context_to_provided_track(
+ &self,
+ ctx_track: &ContextTrack,
+ context_uri: Option<&str>,
+ context_index: Option<usize>,
+ page_metadata: Option<&HashMap<String, String>>,
+ provider: Option<Provider>,
+ ) -> Result<ProvidedTrack, Error> {
+ let id = match (ctx_track.uri.as_ref(), ctx_track.gid.as_ref()) {
+ (Some(uri), _) if uri.contains(['?']) => {
+ Err(StateError::InvalidTrackUri(Some(uri.clone())))?
+ }
+ (Some(uri), _) if !uri.is_empty() => SpotifyUri::from_uri(uri)?,
+ (_, Some(gid)) if !gid.is_empty() => SpotifyUri::Track {
+ id: SpotifyId::from_raw(gid)?,
+ },
+ _ => Err(StateError::InvalidTrackUri(None))?,
+ };
+
+ let uri = id.to_uri()?.replace("unknown", "track");
+
+ let provider = if self.unavailable_uri.contains(&uri) {
+ Provider::Unavailable
+ } else {
+ provider.unwrap_or(Provider::Context)
+ };
+
+ // assumption: the uid is used as unique-id of any item
+ // - queue resorting is done by each client and orients itself by the given uid
+ // - if no uid is present, resorting doesn't work or behaves not as intended
+ let uid = match ctx_track.uid.as_ref() {
+ Some(uid) if !uid.is_empty() => uid.to_string(),
+ // so providing a unique id should allow to resort the queue
+ _ => Uuid::new_v4().as_simple().to_string(),
+ };
+
+ let mut metadata = page_metadata.cloned().unwrap_or_default();
+ for (k, v) in &ctx_track.metadata {
+ metadata.insert(k.to_string(), v.to_string());
+ }
+
+ let mut track = ProvidedTrack {
+ uri,
+ uid,
+ metadata,
+ provider: provider.to_string(),
+ ..Default::default()
+ };
+
+ if let Some(context_uri) = context_uri {
+ track.set_entity_uri(context_uri);
+ track.set_context_uri(context_uri);
+ }
+
+ if let Some(index) = context_index {
+ track.set_context_index(index);
+ }
+
+ if matches!(provider, Provider::Autoplay) {
+ track.set_from_autoplay(true)
+ }
+
+ Ok(track)
+ }
+
+ pub fn fill_context_from_page(&mut self, page: ContextPage) -> Result<(), Error> {
+ let ctx_len = self.context.as_ref().map(|c| c.tracks.len());
+ let context = self.state_context_from_page(page, HashMap::new(), None, None, ctx_len, None);
+
+ let ctx = self
+ .context
+ .as_mut()
+ .ok_or(StateError::NoContext(ContextType::Default))?;
+
+ for t in context.tracks {
+ ctx.tracks.push(t)
+ }
+
+ Ok(())
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/handle.rs b/native/vendor/librespot-connect/src/state/handle.rs
new file mode 100644
index 0000000..e031410
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/handle.rs
@@ -0,0 +1,57 @@
+use crate::{
+ core::{Error, dealer::protocol::SetQueueCommand},
+ state::{
+ ConnectState,
+ context::{ContextType, ResetContext},
+ metadata::Metadata,
+ },
+};
+use protobuf::MessageField;
+
+impl ConnectState {
+ pub fn handle_shuffle(&mut self, shuffle: bool) -> Result<(), Error> {
+ self.set_shuffle(shuffle);
+
+ if shuffle {
+ return self.shuffle_new();
+ }
+
+ self.reset_context(ResetContext::DefaultIndex);
+
+ if self.current_track(MessageField::is_none) {
+ return Ok(());
+ }
+
+ match self.current_track(|t| t.get_context_index()) {
+ Some(current_index) => self.reset_playback_to_position(Some(current_index)),
+ None => {
+ let ctx = self.get_context(ContextType::Default)?;
+ let current_index = ConnectState::find_index_in_context(ctx, |c| {
+ self.current_track(|t| c.uri == t.uri)
+ })?;
+ self.reset_playback_to_position(Some(current_index))
+ }
+ }
+ }
+
+ pub fn handle_set_queue(&mut self, set_queue: SetQueueCommand) {
+ self.set_next_tracks(set_queue.next_tracks);
+ self.set_prev_tracks(set_queue.prev_tracks);
+ self.update_queue_revision();
+ }
+
+ pub fn handle_set_repeat_context(&mut self, repeat: bool) -> Result<(), Error> {
+ self.set_repeat_context(repeat);
+
+ if repeat {
+ if let ContextType::Autoplay = self.fill_up_context {
+ self.fill_up_context = ContextType::Default;
+ }
+ }
+
+ let ctx = self.get_context(ContextType::Default)?;
+ let current_track =
+ ConnectState::find_index_in_context(ctx, |t| self.current_track(|t| &t.uri) == &t.uri)?;
+ self.reset_playback_to_position(Some(current_track))
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/metadata.rs b/native/vendor/librespot-connect/src/state/metadata.rs
new file mode 100644
index 0000000..82318da
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/metadata.rs
@@ -0,0 +1,87 @@
+use crate::{
+ protocol::{context::Context, context_track::ContextTrack, player::ProvidedTrack},
+ state::context::StateContext,
+};
+use std::collections::HashMap;
+use std::fmt::Display;
+
+const CONTEXT_URI: &str = "context_uri";
+const ENTITY_URI: &str = "entity_uri";
+const IS_QUEUED: &str = "is_queued";
+const IS_AUTOPLAY: &str = "autoplay.is_autoplay";
+const HIDDEN: &str = "hidden";
+const ITERATION: &str = "iteration";
+
+const CUSTOM_CONTEXT_INDEX: &str = "context_index";
+const CUSTOM_SHUFFLE_SEED: &str = "shuffle_seed";
+const CUSTOM_INITIAL_TRACK: &str = "initial_track";
+
+macro_rules! metadata_entry {
+ ( $get:ident, $set:ident, $clear:ident ($key:ident: $entry:ident)) => {
+ metadata_entry!( $get use get, $set, $clear ($key: $entry) -> Option<&String> );
+ };
+ ( $get_key:ident use $get:ident, $set:ident, $clear:ident ($key:ident: $entry:ident) -> $ty:ty ) => {
+ fn $get_key (&self) -> $ty {
+ self.$get($entry)
+ }
+
+
+ fn $set (&mut self, $key: impl Display) {
+ self.metadata_mut().insert($entry.to_string(), $key.to_string());
+ }
+
+ fn $clear(&mut self) {
+ self.metadata_mut().remove($entry);
+ }
+ };
+}
+
+/// Allows easy access of known metadata fields
+#[allow(dead_code)]
+pub(super) trait Metadata {
+ fn metadata(&self) -> &HashMap<String, String>;
+
+ fn metadata_mut(&mut self) -> &mut HashMap<String, String>;
+
+ fn get_bool(&self, entry: &str) -> bool {
+ matches!(self.metadata().get(entry), Some(entry) if entry.eq("true"))
+ }
+
+ fn get_usize(&self, entry: &str) -> Option<usize> {
+ self.metadata().get(entry)?.parse().ok()
+ }
+
+ fn get(&self, entry: &str) -> Option<&String> {
+ self.metadata().get(entry)
+ }
+
+ metadata_entry!(is_from_queue use get_bool, set_from_queue, remove_from_queue (is_queued: IS_QUEUED) -> bool);
+ metadata_entry!(is_from_autoplay use get_bool, set_from_autoplay, remove_from_autoplay (is_autoplay: IS_AUTOPLAY) -> bool);
+ metadata_entry!(is_hidden use get_bool, set_hidden, remove_hidden (is_hidden: HIDDEN) -> bool);
+
+ metadata_entry!(get_context_index use get_usize, set_context_index, remove_context_index (context_index: CUSTOM_CONTEXT_INDEX) -> Option<usize>);
+ metadata_entry!(get_context_uri, set_context_uri, remove_context_uri (context_uri: CONTEXT_URI));
+ metadata_entry!(get_entity_uri, set_entity_uri, remove_entity_uri (entity_uri: ENTITY_URI));
+ metadata_entry!(get_iteration, set_iteration, remove_iteration (iteration: ITERATION));
+ metadata_entry!(get_shuffle_seed, set_shuffle_seed, remove_shuffle_seed (shuffle_seed: CUSTOM_SHUFFLE_SEED));
+ metadata_entry!(get_initial_track, set_initial_track, remove_initial_track (initial_track: CUSTOM_INITIAL_TRACK));
+}
+
+macro_rules! impl_metadata {
+ ($impl_for:ident) => {
+ impl Metadata for $impl_for {
+ fn metadata(&self) -> &HashMap<String, String> {
+ &self.metadata
+ }
+
+ fn metadata_mut(&mut self) -> &mut HashMap<String, String> {
+ &mut self.metadata
+ }
+ }
+ };
+}
+
+impl_metadata!(ContextTrack);
+impl_metadata!(ProvidedTrack);
+impl_metadata!(Context);
+impl_metadata!(StateContext);
diff --git a/native/vendor/librespot-connect/src/state/options.rs b/native/vendor/librespot-connect/src/state/options.rs
new file mode 100644
index 0000000..efb8376
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/options.rs
@@ -0,0 +1,113 @@
+use crate::{
+ core::Error,
+ protocol::player::ContextPlayerOptions,
+ state::{
+ ConnectState, StateError,
+ context::{ContextType, ResetContext},
+ metadata::Metadata,
+ },
+};
+use protobuf::MessageField;
+use rand::Rng;
+
+#[derive(Default, Debug)]
+pub(crate) struct ShuffleState {
+ pub seed: u64,
+ pub initial_track: String,
+}
+
+impl ConnectState {
+ fn add_options_if_empty(&mut self) {
+ if self.player().options.is_none() {
+ self.player_mut().options = MessageField::some(ContextPlayerOptions::new())
+ }
+ }
+
+ pub fn set_repeat_context(&mut self, repeat: bool) {
+ self.add_options_if_empty();
+ if let Some(options) = self.player_mut().options.as_mut() {
+ options.repeating_context = repeat;
+ }
+ }
+
+ pub fn set_repeat_track(&mut self, repeat: bool) {
+ self.add_options_if_empty();
+ if let Some(options) = self.player_mut().options.as_mut() {
+ options.repeating_track = repeat;
+ }
+ }
+
+ pub fn set_shuffle(&mut self, shuffle: bool) {
+ self.add_options_if_empty();
+ if let Some(options) = self.player_mut().options.as_mut() {
+ options.shuffling_context = shuffle;
+ }
+ }
+
+ pub fn reset_options(&mut self) {
+ self.set_shuffle(false);
+ self.set_repeat_track(false);
+ self.set_repeat_context(false);
+ }
+
+ fn validate_shuffle_allowed(&self) -> Result<(), Error> {
+ if let Some(reason) = self
+ .player()
+ .restrictions
+ .disallow_toggling_shuffle_reasons
+ .first()
+ {
+ Err(StateError::CurrentlyDisallowed {
+ action: "shuffle",
+ reason: reason.clone(),
+ })?
+ } else {
+ Ok(())
+ }
+ }
+
+ pub fn shuffle_restore(&mut self, shuffle_state: ShuffleState) -> Result<(), Error> {
+ self.validate_shuffle_allowed()?;
+
+ self.shuffle(shuffle_state.seed, &shuffle_state.initial_track)
+ }
+
+ pub fn shuffle_new(&mut self) -> Result<(), Error> {
+ self.validate_shuffle_allowed()?;
+
+ let new_seed = rand::rng().random_range(100_000_000_000..1_000_000_000_000);
+ let current_track = self.current_track(|t| t.uri.clone());
+
+ self.shuffle(new_seed, &current_track)
+ }
+
+ fn shuffle(&mut self, seed: u64, initial_track: &str) -> Result<(), Error> {
+ self.clear_prev_track();
+ self.clear_next_tracks();
+
+ self.reset_context(ResetContext::DefaultIndex);
+
+ let ctx = self.get_context_mut(ContextType::Default)?;
+ ctx.tracks
+ .shuffle_with_seed(seed, |f| f.uri == initial_track);
+
+ ctx.set_initial_track(initial_track);
+ ctx.set_shuffle_seed(seed);
+
+ self.fill_up_next_tracks()?;
+
+ Ok(())
+ }
+
+ pub fn shuffling_context(&self) -> bool {
+ self.player().options.shuffling_context
+ }
+
+ pub fn repeat_context(&self) -> bool {
+ self.player().options.repeating_context
+ }
+
+ pub fn repeat_track(&self) -> bool {
+ self.player().options.repeating_track
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/provider.rs b/native/vendor/librespot-connect/src/state/provider.rs
new file mode 100644
index 0000000..97eb7aa
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/provider.rs
@@ -0,0 +1,66 @@
+use librespot_protocol::player::ProvidedTrack;
+use std::fmt::{Display, Formatter};
+
+// providers used by spotify
+const PROVIDER_CONTEXT: &str = "context";
+const PROVIDER_QUEUE: &str = "queue";
+const PROVIDER_AUTOPLAY: &str = "autoplay";
+
+// custom providers, used to identify certain states that we can't handle preemptively, yet
+/// it seems like spotify just knows that the track isn't available, currently we don't have an
+/// option to do the same, so we stay with the old solution for now
+const PROVIDER_UNAVAILABLE: &str = "unavailable";
+
+#[derive(Debug, Clone)]
+pub enum Provider {
+ Context,
+ Queue,
+ Autoplay,
+ Unavailable,
+}
+
+impl Display for Provider {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "{}",
+ match self {
+ Provider::Context => PROVIDER_CONTEXT,
+ Provider::Queue => PROVIDER_QUEUE,
+ Provider::Autoplay => PROVIDER_AUTOPLAY,
+ Provider::Unavailable => PROVIDER_UNAVAILABLE,
+ }
+ )
+ }
+}
+
+pub trait IsProvider {
+ fn is_autoplay(&self) -> bool;
+ fn is_context(&self) -> bool;
+ fn is_queue(&self) -> bool;
+ fn is_unavailable(&self) -> bool;
+
+ fn set_provider(&mut self, provider: Provider);
+}
+
+impl IsProvider for ProvidedTrack {
+ fn is_autoplay(&self) -> bool {
+ self.provider == PROVIDER_AUTOPLAY
+ }
+
+ fn is_context(&self) -> bool {
+ self.provider == PROVIDER_CONTEXT
+ }
+
+ fn is_queue(&self) -> bool {
+ self.provider == PROVIDER_QUEUE
+ }
+
+ fn is_unavailable(&self) -> bool {
+ self.provider == PROVIDER_UNAVAILABLE
+ }
+
+ fn set_provider(&mut self, provider: Provider) {
+ self.provider = provider.to_string()
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/restrictions.rs b/native/vendor/librespot-connect/src/state/restrictions.rs
new file mode 100644
index 0000000..29d8d47
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/restrictions.rs
@@ -0,0 +1,62 @@
+use crate::state::ConnectState;
+use crate::state::provider::IsProvider;
+use librespot_protocol::player::Restrictions;
+use protobuf::MessageField;
+
+impl ConnectState {
+ pub fn clear_restrictions(&mut self) {
+ let player = self.player_mut();
+
+ player.context_restrictions = Some(Default::default()).into();
+ player.restrictions = Some(Default::default()).into();
+ }
+
+ pub fn update_restrictions(&mut self) {
+ const NO_PREV: &str = "no previous tracks";
+ const AUTOPLAY: &str = "autoplay";
+
+ let prev_tracks_is_empty = self.prev_tracks().is_empty();
+
+ let is_paused = self.is_pause();
+ let is_playing = self.is_playing();
+
+ let player = self.player_mut();
+ if let Some(restrictions) = player.restrictions.as_mut() {
+ if is_playing {
+ restrictions.disallow_pausing_reasons.clear();
+ restrictions.disallow_resuming_reasons = vec!["not_paused".to_string()]
+ }
+
+ if is_paused {
+ restrictions.disallow_resuming_reasons.clear();
+ restrictions.disallow_pausing_reasons = vec!["not_playing".to_string()]
+ }
+ }
+
+ if player.restrictions.is_none() {
+ player.restrictions = MessageField::some(Restrictions::new())
+ }
+
+ if let Some(restrictions) = player.restrictions.as_mut() {
+ if prev_tracks_is_empty {
+ restrictions.disallow_peeking_prev_reasons = vec![NO_PREV.to_string()];
+ restrictions.disallow_skipping_prev_reasons = vec![NO_PREV.to_string()];
+ } else {
+ restrictions.disallow_peeking_prev_reasons.clear();
+ restrictions.disallow_skipping_prev_reasons.clear();
+ }
+
+ if player.track.is_autoplay() {
+ restrictions.disallow_toggling_shuffle_reasons = vec![AUTOPLAY.to_string()];
+ restrictions.disallow_toggling_repeat_context_reasons = vec![AUTOPLAY.to_string()];
+ restrictions.disallow_toggling_repeat_track_reasons = vec![AUTOPLAY.to_string()];
+ } else {
+ restrictions.disallow_toggling_shuffle_reasons.clear();
+ restrictions
+ .disallow_toggling_repeat_context_reasons
+ .clear();
+ restrictions.disallow_toggling_repeat_track_reasons.clear();
+ }
+ }
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/tracks.rs b/native/vendor/librespot-connect/src/state/tracks.rs
new file mode 100644
index 0000000..8619035
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/tracks.rs
@@ -0,0 +1,439 @@
+use crate::{
+ core::{Error, SpotifyUri},
+ protocol::player::ProvidedTrack,
+ state::{
+ ConnectState, SPOTIFY_MAX_NEXT_TRACKS_SIZE, SPOTIFY_MAX_PREV_TRACKS_SIZE, StateError,
+ context::ContextType,
+ metadata::Metadata,
+ provider::{IsProvider, Provider},
+ },
+};
+use protobuf::MessageField;
+use rand::Rng;
+
+// identifier used as part of the uid
+pub const IDENTIFIER_DELIMITER: &str = "delimiter";
+
+impl<'ct> ConnectState {
+ fn new_delimiter(iteration: i64) -> ProvidedTrack {
+ let mut delimiter = ProvidedTrack {
+ uri: format!("spotify:{IDENTIFIER_DELIMITER}"),
+ uid: format!("{IDENTIFIER_DELIMITER}{iteration}"),
+ provider: Provider::Context.to_string(),
+ ..Default::default()
+ };
+ delimiter.set_hidden(true);
+ delimiter.set_iteration(iteration);
+
+ delimiter
+ }
+
+ fn push_prev(&mut self, prev: ProvidedTrack) {
+ let prev_tracks = self.prev_tracks_mut();
+ // add prev track, while preserving a length of 10
+ if prev_tracks.len() >= SPOTIFY_MAX_PREV_TRACKS_SIZE {
+ // todo: O(n), but technically only maximal O(SPOTIFY_MAX_PREV_TRACKS_SIZE) aka O(10)
+ let _ = prev_tracks.remove(0);
+ }
+ prev_tracks.push(prev)
+ }
+
+ fn get_next_track(&mut self) -> Option<ProvidedTrack> {
+ if self.next_tracks().is_empty() {
+ None
+ } else {
+ // todo: O(n), but technically only maximal O(SPOTIFY_MAX_NEXT_TRACKS_SIZE) aka O(80)
+ Some(self.next_tracks_mut().remove(0))
+ }
+ }
+
+ /// bottom => top, aka the last track of the list is the prev track
+ fn prev_tracks_mut(&mut self) -> &mut Vec<ProvidedTrack> {
+ &mut self.player_mut().prev_tracks
+ }
+
+ /// bottom => top, aka the last track of the list is the prev track
+ pub(super) fn prev_tracks(&self) -> &Vec<ProvidedTrack> {
+ &self.player().prev_tracks
+ }
+
+ /// top => bottom, aka the first track of the list is the next track
+ fn next_tracks_mut(&mut self) -> &mut Vec<ProvidedTrack> {
+ &mut self.player_mut().next_tracks
+ }
+
+ /// top => bottom, aka the first track of the list is the next track
+ pub(super) fn next_tracks(&self) -> &Vec<ProvidedTrack> {
+ &self.player().next_tracks
+ }
+
+ pub fn set_current_track_random(&mut self) -> Result<(), Error> {
+ let max_tracks = self.get_context(self.active_context)?.tracks.len();
+ let rng_track = rand::rng().random_range(0..max_tracks);
+ self.set_current_track(rng_track)
+ }
+
+ pub fn set_current_track(&mut self, index: usize) -> Result<(), Error> {
+ let context = self.get_context(self.active_context)?;
+
+ let new_track = context
+ .tracks
+ .get(index)
+ .ok_or(StateError::CanNotFindTrackInContext(
+ Some(index),
+ context.tracks.len(),
+ ))?;
+
+ debug!(
+ "set track to: {} at {} of {} tracks",
+ new_track.uri,
+ index,
+ context.tracks.len()
+ );
+
+ self.set_track(new_track.clone());
+
+ self.update_current_index(|i| i.track = index as u32);
+
+ Ok(())
+ }
+
+ /// Move to the next track
+ ///
+ /// Updates the current track to the next track. Adds the old track
+ /// to prev tracks and fills up the next tracks from the current context
+ pub fn next_track(&mut self) -> Result<Option<u32>, Error> {
+ // when we skip in repeat track, we don't repeat the current track anymore
+ if self.repeat_track() {
+ self.set_repeat_track(false);
+ }
+
+ let old_track = self.player_mut().track.take();
+
+ if let Some(old_track) = old_track {
+ // only add songs from our context to our previous tracks
+ if old_track.is_context() || old_track.is_autoplay() {
+ self.push_prev(old_track)
+ }
+ }
+
+ let new_track = loop {
+ match self.get_next_track() {
+ Some(next) if next.uid.starts_with(IDENTIFIER_DELIMITER) => {
+ self.push_prev(next);
+ continue;
+ }
+ Some(next) if next.is_unavailable() => continue,
+ other => break other,
+ };
+ };
+
+ let new_track = match new_track {
+ None => return Ok(None),
+ Some(t) => t,
+ };
+
+ self.fill_up_next_tracks()?;
+
+ let update_index = if new_track.is_queue() {
+ None
+ } else if new_track.is_autoplay() {
+ self.set_active_context(ContextType::Autoplay);
+ None
+ } else {
+ match new_track.get_context_index() {
+ Some(new_index) => Some(new_index as u32),
+ None => {
+ error!("the given context track had no set context_index");
+ None
+ }
+ }
+ };
+
+ if let Some(update_index) = update_index {
+ self.update_current_index(|i| i.track = update_index)
+ } else {
+ self.player_mut().index.clear()
+ }
+
+ self.set_track(new_track);
+ self.update_restrictions();
+
+ Ok(Some(self.player().index.track))
+ }
+
+ /// Move to the prev track
+ ///
+ /// Updates the current track to the prev track. Adds the old track
+ /// to next tracks (when from the context) and fills up the prev tracks from the
+ /// current context
+ pub fn prev_track(&mut self) -> Result<Option<&MessageField<ProvidedTrack>>, Error> {
+ let old_track = self.player_mut().track.take();
+
+ if let Some(old_track) = old_track {
+ if old_track.is_context() || old_track.is_autoplay() {
+ // todo: O(n)
+ self.next_tracks_mut().insert(0, old_track);
+ }
+ }
+
+ // handle possible delimiter
+ if matches!(self.prev_tracks().last(), Some(prev) if prev.uid.starts_with(IDENTIFIER_DELIMITER))
+ {
+ let delimiter = self
+ .prev_tracks_mut()
+ .pop()
+ .expect("item that was prechecked");
+
+ let next_tracks = self.next_tracks_mut();
+ if next_tracks.len() >= SPOTIFY_MAX_NEXT_TRACKS_SIZE {
+ let _ = next_tracks.pop();
+ }
+ // todo: O(n)
+ next_tracks.insert(0, delimiter)
+ }
+
+ while self.next_tracks().len() > SPOTIFY_MAX_NEXT_TRACKS_SIZE {
+ let _ = self.next_tracks_mut().pop();
+ }
+
+ let new_track = match self.prev_tracks_mut().pop() {
+ None => return Ok(None),
+ Some(t) => t,
+ };
+
+ if matches!(self.active_context, ContextType::Autoplay if new_track.is_context()) {
+ // transition back to default context
+ self.set_active_context(ContextType::Default);
+ }
+
+ self.fill_up_next_tracks()?;
+ self.set_track(new_track);
+
+ if self.player().index.track == 0 {
+ warn!("prev: trying to skip into negative, index update skipped")
+ } else {
+ self.update_current_index(|i| i.track -= 1)
+ }
+
+ self.update_restrictions();
+
+ Ok(Some(self.current_track(|t| t)))
+ }
+
+ pub fn current_track<F: Fn(&'ct MessageField<ProvidedTrack>) -> R, R>(
+ &'ct self,
+ access: F,
+ ) -> R {
+ access(&self.player().track)
+ }
+
+ pub fn set_track(&mut self, track: ProvidedTrack) {
+ self.player_mut().track = MessageField::some(track)
+ }
+
+ pub fn set_next_tracks(&mut self, mut tracks: Vec<ProvidedTrack>) {
+ // mobile only sends a set_queue command instead of an add_to_queue command
+ // in addition to handling the mobile add_to_queue handling, this should also handle
+ // a mass queue addition
+ tracks
+ .iter_mut()
+ .filter(|t| t.is_from_queue())
+ .for_each(|t| {
+ t.set_provider(Provider::Queue);
+ // technically we could preserve the queue-uid here,
+ // but it seems to work without that, so we just override it
+ t.uid = format!("q{}", self.queue_count);
+ self.queue_count += 1;
+ });
+
+ // when you drag 'n drop the current track in the queue view into the "Next from: ..."
+ // section, it is only send as an empty item with just the provider and metadata, so we have
+ // to provide set the uri from the current track manually
+ tracks
+ .iter_mut()
+ .filter(|t| t.uri.is_empty())
+ .for_each(|t| t.uri = self.current_track(|ct| ct.uri.clone()));
+
+ self.player_mut().next_tracks = tracks;
+ }
+
+ pub fn set_prev_tracks(&mut self, tracks: Vec<ProvidedTrack>) {
+ self.player_mut().prev_tracks = tracks;
+ }
+
+ pub fn clear_prev_track(&mut self) {
+ self.prev_tracks_mut().clear()
+ }
+
+ pub fn clear_next_tracks(&mut self) {
+ // respect queued track and don't throw them out of our next played tracks
+ let first_non_queued_track = self
+ .next_tracks()
+ .iter()
+ .enumerate()
+ .find(|(_, track)| !track.is_queue());
+
+ if let Some((non_queued_track, _)) = first_non_queued_track {
+ while self.next_tracks().len() > non_queued_track
+ && self.next_tracks_mut().pop().is_some()
+ {}
+ }
+ }
+
+ pub fn fill_up_next_tracks(&mut self) -> Result<(), Error> {
+ let ctx = self.get_context(self.fill_up_context)?;
+ let mut new_index = ctx.index.track as usize;
+ let mut iteration = ctx.index.page;
+
+ while self.next_tracks().len() < SPOTIFY_MAX_NEXT_TRACKS_SIZE {
+ let ctx = self.get_context(self.fill_up_context)?;
+ let track = match ctx.tracks.get(new_index) {
+ None if self.repeat_context() => {
+ let delimiter = Self::new_delimiter(iteration.into());
+ iteration += 1;
+ new_index = 0;
+ delimiter
+ }
+ None if !matches!(self.fill_up_context, ContextType::Autoplay)
+ && self.autoplay_context.is_some()
+ && !self.repeat_context() =>
+ {
+ self.update_context_index(self.fill_up_context, new_index)?;
+
+ // transition to autoplay as fill up context
+ self.fill_up_context = ContextType::Autoplay;
+ new_index = self.get_context(ContextType::Autoplay)?.index.track as usize;
+
+ // add delimiter to only display the current context
+ Self::new_delimiter(iteration.into())
+ }
+ None if self.autoplay_context.is_some() => {
+ match self
+ .get_context(ContextType::Autoplay)?
+ .tracks
+ .get(new_index)
+ {
+ None => break,
+ Some(ct) => {
+ new_index += 1;
+ ct.clone()
+ }
+ }
+ }
+ None => break,
+ Some(ct) if ct.is_unavailable() || self.is_skip_track(ct, Some(iteration)) => {
+ debug!(
+ "skipped track {} during fillup as it's unavailable or should be skipped",
+ ct.uri
+ );
+ new_index += 1;
+ continue;
+ }
+ Some(ct) => {
+ new_index += 1;
+ ct.clone()
+ }
+ };
+
+ self.next_tracks_mut().push(track);
+ }
+
+ debug!(
+ "finished filling up next_tracks ({})",
+ self.next_tracks().len()
+ );
+
+ self.update_context_index(self.fill_up_context, new_index)?;
+
+ // the web-player needs a revision update, otherwise the queue isn't updated in the ui
+ self.update_queue_revision();
+
+ Ok(())
+ }
+
+ pub fn preview_next_track(&mut self) -> Option<SpotifyUri> {
+ let next = if self.repeat_track() {
+ self.current_track(|t| &t.uri)
+ } else {
+ &self.next_tracks().first()?.uri
+ };
+
+ SpotifyUri::from_uri(next).ok()
+ }
+
+ pub fn has_next_tracks(&self, min: Option<usize>) -> bool {
+ if let Some(min) = min {
+ self.next_tracks().len() >= min
+ } else {
+ !self.next_tracks().is_empty()
+ }
+ }
+
+ pub fn recent_track_uris(&self) -> Vec<String> {
+ let mut prev = self
+ .prev_tracks()
+ .iter()
+ .map(|t| t.uri.clone())
+ .collect::<Vec<_>>();
+
+ prev.push(self.current_track(|t| t.uri.clone()));
+ prev
+ }
+
+ pub fn mark_unavailable(&mut self, id: &SpotifyUri) -> Result<(), Error> {
+ let uri = id.to_uri()?;
+
+ debug!("marking {uri} as unavailable");
+
+ let next_tracks = self.next_tracks_mut();
+ while let Some(pos) = next_tracks.iter().position(|t| t.uri == uri) {
+ let _ = next_tracks.remove(pos);
+ }
+
+ for next_track in next_tracks {
+ Self::mark_as_unavailable_for_match(next_track, &uri)
+ }
+
+ let prev_tracks = self.prev_tracks_mut();
+ while let Some(pos) = prev_tracks.iter().position(|t| t.uri == uri) {
+ let _ = prev_tracks.remove(pos);
+ }
+
+ for prev_track in prev_tracks {
+ Self::mark_as_unavailable_for_match(prev_track, &uri)
+ }
+
+ self.unavailable_uri.push(uri);
+ self.fill_up_next_tracks()?;
+ self.update_queue_revision();
+
+ Ok(())
+ }
+
+ pub fn add_to_queue(&mut self, mut track: ProvidedTrack, rev_update: bool) {
+ track.uid = format!("q{}", self.queue_count);
+ self.queue_count += 1;
+
+ track.set_provider(Provider::Queue);
+ if !track.is_from_queue() {
+ track.set_from_queue(true);
+ }
+
+ let next_tracks = self.next_tracks_mut();
+ if let Some(next_not_queued_track) = next_tracks.iter().position(|t| !t.is_queue()) {
+ next_tracks.insert(next_not_queued_track, track);
+ } else {
+ next_tracks.push(track)
+ }
+
+ while next_tracks.len() > SPOTIFY_MAX_NEXT_TRACKS_SIZE {
+ next_tracks.pop();
+ }
+
+ if rev_update {
+ self.update_queue_revision();
+ }
+ self.update_restrictions();
+ }
+}
diff --git a/native/vendor/librespot-connect/src/state/transfer.rs b/native/vendor/librespot-connect/src/state/transfer.rs
new file mode 100644
index 0000000..e91ec5f
--- /dev/null
+++ b/native/vendor/librespot-connect/src/state/transfer.rs
@@ -0,0 +1,199 @@
+use crate::{
+ core::Error,
+ protocol::{player::ProvidedTrack, transfer_state::TransferState},
+ state::{
+ context::ContextType,
+ metadata::Metadata,
+ options::ShuffleState,
+ provider::{IsProvider, Provider},
+ {ConnectState, StateError},
+ },
+};
+use protobuf::MessageField;
+
+impl ConnectState {
+ pub fn current_track_from_transfer(
+ &self,
+ transfer: &TransferState,
+ ) -> Result<ProvidedTrack, Error> {
+ let track = if transfer.queue.is_playing_queue.unwrap_or_default() {
+ debug!("transfer track was used from the queue");
+ transfer.queue.tracks.first()
+ } else {
+ debug!("transfer track was the current track");
+ transfer.playback.current_track.as_ref()
+ }
+ .ok_or(StateError::CouldNotResolveTrackFromTransfer)?;
+
+ self.context_to_provided_track(
+ track,
+ transfer.current_session.context.uri.as_deref(),
+ None,
+ None,
+ transfer
+ .queue
+ .is_playing_queue
+ .unwrap_or_default()
+ .then_some(Provider::Queue),
+ )
+ }
+
+ /// handles the initially transferable data
+ pub fn handle_initial_transfer(
+ &mut self,
+ transfer: &mut TransferState,
+ ctx_uri: Option<String>,
+ ) {
+ let current_context_metadata = self.context.as_ref().map(|c| c.metadata.clone());
+ let player = self.player_mut();
+
+ player.is_buffering = false;
+
+ if let Some(options) = transfer.options.take() {
+ player.options = MessageField::some(options.into());
+ }
+ player.is_paused = transfer.playback.is_paused.unwrap_or_default();
+ player.is_playing = !player.is_paused;
+
+ match transfer.playback.playback_speed {
+ Some(speed) if speed != 0. => player.playback_speed = speed,
+ _ => player.playback_speed = 1.,
+ }
+
+ let mut shuffle_seed = None;
+ let mut initial_track = None;
+ if let Some(session) = transfer.current_session.as_mut() {
+ player.play_origin = session.play_origin.take().map(Into::into).into();
+ player.suppressions = session.suppressions.take().map(Into::into).into();
+
+ // maybe at some point we can use the shuffle seed provided by spotify,
+ // but I doubt it, as spotify doesn't use true randomness but rather an algorithm
+ // based shuffle
+ trace!(
+ "shuffle_seed: <{:?}> (spotify), <{:?}> (own)",
+ session.shuffle_seed,
+ session.context.get_shuffle_seed()
+ );
+
+ shuffle_seed = session
+ .context
+ .get_shuffle_seed()
+ .and_then(|seed| seed.parse().ok());
+
+ initial_track = session.context.get_initial_track().cloned();
+
+ if let Some(mut ctx) = session.context.take() {
+ player.restrictions = ctx.restrictions.take().map(Into::into).into();
+ for (key, value) in ctx.metadata {
+ player.context_metadata.insert(key, value);
+ }
+ }
+ }
+
+ const UNKNOWN_URI: &str = "spotify:unknown";
+ // it's important to always set the url/uri to a value
+ // so that the player doesn't go into an inactive state
+ let uri = ctx_uri.unwrap_or(UNKNOWN_URI.into());
+
+ player.context_url = format!("context://{uri}");
+ player.context_uri = uri;
+
+ if let Some(metadata) = current_context_metadata {
+ for (key, value) in metadata {
+ player.context_metadata.insert(key, value);
+ }
+ }
+
+ self.transfer_shuffle = match (shuffle_seed, initial_track) {
+ (Some(seed), Some(initial_track)) => Some(ShuffleState {
+ seed,
+ initial_track,
+ }),
+ _ => None,
+ };
+
+ self.clear_prev_track();
+ self.clear_next_tracks();
+ self.update_queue_revision()
+ }
+
+ /// completes the transfer, loading the queue and updating metadata
+ pub fn finish_transfer(&mut self, transfer: TransferState) -> Result<(), Error> {
+ let track = match self.player().track.as_ref() {
+ None => self.current_track_from_transfer(&transfer)?,
+ Some(track) => track.clone(),
+ };
+
+ let context_ty = if self.current_track(|t| t.is_from_autoplay()) {
+ ContextType::Autoplay
+ } else {
+ ContextType::Default
+ };
+
+ self.set_active_context(context_ty);
+ self.fill_up_context = context_ty;
+
+ let ctx = self.get_context(self.active_context)?;
+
+ let current_index = match transfer.current_session.current_uid.as_ref() {
+ Some(uid) if track.is_queue() => Self::find_index_in_context(ctx, |c| &c.uid == uid)
+ .map(|i| if i > 0 { i - 1 } else { i }),
+ _ => Self::find_index_in_context(ctx, |c| c.uri == track.uri || c.uid == track.uid),
+ };
+
+ debug!(
+ "active track is <{}> with index {current_index:?} in {:?} context, has {} tracks",
+ track.uri,
+ self.active_context,
+ ctx.tracks.len()
+ );
+
+ if self.player().track.is_none() {
+ self.set_track(track);
+ }
+
+ let current_index = current_index.ok();
+ if let Some(current_index) = current_index {
+ self.update_current_index(|i| i.track = current_index as u32);
+ }
+
+ debug!(
+ "setting up next and prev: index is at {current_index:?} while shuffle {}",
+ self.shuffling_context()
+ );
+
+ for (i, track) in transfer.queue.tracks.iter().enumerate() {
+ if transfer.queue.is_playing_queue.unwrap_or_default() && i == 0 {
+ // if we are currently playing from the queue,
+ // don't add the first queued item, because we are currently playing that item
+ continue;
+ }
+
+ if let Ok(queued_track) = self.context_to_provided_track(
+ track,
+ Some(self.context_uri()),
+ None,
+ None,
+ Some(Provider::Queue),
+ ) {
+ self.add_to_queue(queued_track, false);
+ }
+ }
+
+ if self.shuffling_context() {
+ self.set_current_track(current_index.unwrap_or_default())?;
+ self.set_shuffle(true);
+
+ match self.transfer_shuffle.take() {
+ None => self.shuffle_new(),
+ Some(state) => self.shuffle_restore(state),
+ }?
+ } else {
+ self.reset_playback_to_position(current_index)?;
+ }
+
+ self.update_restrictions();
+
+ Ok(())
+ }
+}
diff --git a/native/vendor/librespot-playback/.cargo_vcs_info.json b/native/vendor/librespot-playback/.cargo_vcs_info.json
new file mode 100644
index 0000000..4b4a666
--- /dev/null
+++ b/native/vendor/librespot-playback/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "d36f9f1907e8cc9d68a93f8ebc6b627b1bf7267d"
+ },
+ "path_in_vcs": "playback"
+}
\ No newline at end of file
diff --git a/native/vendor/librespot-playback/Cargo.toml b/native/vendor/librespot-playback/Cargo.toml
new file mode 100644
index 0000000..4de3abe
--- /dev/null
+++ b/native/vendor/librespot-playback/Cargo.toml
@@ -0,0 +1,187 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+rust-version = "1.85"
+name = "librespot-playback"
+version = "0.8.0"
+authors = ["Sasha Hilton <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "The audio playback logic for librespot"
+readme = false
+license = "MIT"
+repository = "https://github.com/librespot-org/librespot"
+
+[features]
+alsa-backend = ["dep:alsa"]
+default = [
+ "rodio-backend",
+ "native-tls",
+]
+gstreamer-backend = [
+ "dep:gstreamer",
+ "dep:gstreamer-app",
+ "dep:gstreamer-audio",
+]
+jackaudio-backend = ["dep:jack"]
+native-tls = [
+ "librespot-core/native-tls",
+ "librespot-audio/native-tls",
+ "librespot-metadata/native-tls",
+]
+passthrough-decoder = ["dep:ogg"]
+portaudio-backend = ["dep:portaudio-rs"]
+pulseaudio-backend = [
+ "dep:libpulse-binding",
+ "dep:libpulse-simple-binding",
+]
+rodio-backend = [
+ "dep:cpal",
+ "dep:rodio",
+]
+rodiojack-backend = [
+ "dep:rodio",
+ "cpal/jack",
+]
+rustls-tls-native-roots = [
+ "librespot-core/rustls-tls-native-roots",
+ "librespot-audio/rustls-tls-native-roots",
+ "librespot-metadata/rustls-tls-native-roots",
+]
+rustls-tls-webpki-roots = [
+ "librespot-core/rustls-tls-webpki-roots",
+ "librespot-audio/rustls-tls-webpki-roots",
+ "librespot-metadata/rustls-tls-webpki-roots",
+]
+sdl-backend = ["dep:sdl2"]
+
+[lib]
+name = "librespot_playback"
+path = "src/lib.rs"
+
+[dependencies.alsa]
+version = "0.10"
+optional = true
+
+[dependencies.cpal]
+version = "0.16"
+optional = true
+
+[dependencies.form_urlencoded]
+version = "1.2.2"
+
+[dependencies.futures-util]
+version = "0.3"
+features = ["std"]
+default-features = false
+
+[dependencies.gstreamer]
+version = "0.24"
+optional = true
+
+[dependencies.gstreamer-app]
+version = "0.24"
+optional = true
+
+[dependencies.gstreamer-audio]
+version = "0.24"
+optional = true
+
+[dependencies.jack]
+version = "0.13"
+optional = true
+
+[dependencies.libpulse-binding]
+version = "2"
+optional = true
+default-features = false
+
+[dependencies.libpulse-simple-binding]
+version = "2"
+optional = true
+default-features = false
+
+[dependencies.librespot-audio]
+version = "0.8.0"
+default-features = false
+
+[dependencies.librespot-core]
+version = "0.8.0"
+default-features = false
+
+[dependencies.librespot-metadata]
+version = "0.8.0"
+default-features = false
+
+[dependencies.log]
+version = "0.4"
+
+[dependencies.ogg]
+version = "0.9"
+optional = true
+
+[dependencies.portable-atomic]
+version = "1"
+
+[dependencies.portaudio-rs]
+version = "0.3"
+optional = true
+
+[dependencies.rand]
+version = "0.9"
+features = ["small_rng"]
+default-features = false
+
+[dependencies.rand_distr]
+version = "0.5"
+
+[dependencies.rodio]
+version = "0.21"
+features = ["playback"]
+optional = true
+default-features = false
+
+[dependencies.sdl2]
+version = "0.38"
+optional = true
+
+[dependencies.shell-words]
+version = "1.1"
+
+[dependencies.symphonia]
+version = "0.5"
+features = [
+ "mp3",
+ "ogg",
+ "vorbis",
+ "flac",
+]
+default-features = false
+
+[dependencies.thiserror]
+version = "2"
+
+[dependencies.tokio]
+version = "1"
+features = [
+ "rt-multi-thread",
+ "sync",
+]
+
+[dependencies.zerocopy]
+version = "0.8"
+features = ["derive"]
diff --git a/native/vendor/librespot-playback/Cargo.toml.orig b/native/vendor/librespot-playback/Cargo.toml.orig
new file mode 100644
index 0000000..e5656ad
--- /dev/null
+++ b/native/vendor/librespot-playback/Cargo.toml.orig
@@ -0,0 +1,99 @@
+[package]
+name = "librespot-playback"
+version = "0.8.0"
+rust-version.workspace = true
+authors = ["Sasha Hilton <[email protected]>"]
+license.workspace = true
+description = "The audio playback logic for librespot"
+repository.workspace = true
+edition.workspace = true
+
+[features]
+# Refer to the workspace Cargo.toml for the list of features
+default = ["rodio-backend", "native-tls"]
+
+# Audio backends
+alsa-backend = ["dep:alsa"]
+gstreamer-backend = [
+ "dep:gstreamer",
+ "dep:gstreamer-app",
+ "dep:gstreamer-audio",
+]
+jackaudio-backend = ["dep:jack"]
+portaudio-backend = ["dep:portaudio-rs"]
+pulseaudio-backend = ["dep:libpulse-binding", "dep:libpulse-simple-binding"]
+rodio-backend = ["dep:cpal", "dep:rodio"]
+rodiojack-backend = ["dep:rodio", "cpal/jack"]
+sdl-backend = ["dep:sdl2"]
+
+# Audio processing features
+passthrough-decoder = ["dep:ogg"]
+
+# TLS backend propagation
+native-tls = [
+ "librespot-core/native-tls",
+ "librespot-audio/native-tls",
+ "librespot-metadata/native-tls",
+]
+rustls-tls-native-roots = [
+ "librespot-core/rustls-tls-native-roots",
+ "librespot-audio/rustls-tls-native-roots",
+ "librespot-metadata/rustls-tls-native-roots",
+]
+rustls-tls-webpki-roots = [
+ "librespot-core/rustls-tls-webpki-roots",
+ "librespot-audio/rustls-tls-webpki-roots",
+ "librespot-metadata/rustls-tls-webpki-roots",
+]
+
+[dependencies]
+librespot-audio = { version = "0.8.0", path = "../audio", default-features = false }
+librespot-core = { version = "0.8.0", path = "../core", default-features = false }
+librespot-metadata = { version = "0.8.0", path = "../metadata", default-features = false }
+
+futures-util = { version = "0.3", default-features = false, features = ["std"] }
+log = "0.4"
+portable-atomic = "1"
+shell-words = "1.1"
+thiserror = "2"
+tokio = { version = "1", features = ["rt-multi-thread", "sync"] }
+zerocopy = { version = "0.8", features = ["derive"] }
+
+# Backends
+alsa = { version = "0.10", optional = true }
+jack = { version = "0.13", optional = true }
+portaudio-rs = { version = "0.3", optional = true }
+sdl2 = { version = "0.38", optional = true }
+
+# GStreamer dependencies
+gstreamer = { version = "0.24", optional = true }
+gstreamer-app = { version = "0.24", optional = true }
+gstreamer-audio = { version = "0.24", optional = true }
+
+# PulseAudio dependencies
+libpulse-binding = { version = "2", optional = true, default-features = false }
+libpulse-simple-binding = { version = "2", optional = true, default-features = false }
+
+# Rodio dependencies
+cpal = { version = "0.16", optional = true }
+rodio = { version = "0.21", optional = true, default-features = false, features = [
+ "playback",
+] }
+
+# Container and audio decoder
+symphonia = { version = "0.5", default-features = false, features = [
+ "mp3",
+ "ogg",
+ "vorbis",
+ "flac"
+] }
+
+# Legacy Ogg container decoder for the passthrough decoder
+ogg = { version = "0.9", optional = true }
+
+# Dithering
+rand = { version = "0.9", default-features = false, features = ["small_rng"] }
+rand_distr = "0.5"
+
+# Local file handling
+form_urlencoded = "1.2.2"
diff --git a/native/vendor/librespot-playback/src/audio_backend/alsa.rs b/native/vendor/librespot-playback/src/audio_backend/alsa.rs
new file mode 100644
index 0000000..bd2b4bf
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/alsa.rs
@@ -0,0 +1,512 @@
+use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use crate::{NUM_CHANNELS, SAMPLE_RATE};
+use alsa::device_name::HintIter;
+use alsa::pcm::{Access, Format, Frames, HwParams, PCM};
+use alsa::{Direction, ValueOr};
+use std::process::exit;
+use thiserror::Error;
+
+const MAX_BUFFER: Frames = (SAMPLE_RATE / 2) as Frames;
+const MIN_BUFFER: Frames = (SAMPLE_RATE / 10) as Frames;
+const ZERO_FRAMES: Frames = 0;
+
+const MAX_PERIOD_DIVISOR: Frames = 4;
+const MIN_PERIOD_DIVISOR: Frames = 10;
+
+#[derive(Debug, Error)]
+enum AlsaError {
+ #[error("<AlsaSink> Device {device} Unsupported Format {alsa_format:?} ({format:?}), {e}")]
+ UnsupportedFormat {
+ device: String,
+ alsa_format: Format,
+ format: AudioFormat,
+ e: alsa::Error,
+ },
+
+ #[error("<AlsaSink> Device {device} Unsupported Channel Count {channel_count}, {e}")]
+ UnsupportedChannelCount {
+ device: String,
+ channel_count: u8,
+ e: alsa::Error,
+ },
+
+ #[error("<AlsaSink> Device {device} Unsupported Sample Rate {samplerate}, {e}")]
+ UnsupportedSampleRate {
+ device: String,
+ samplerate: u32,
+ e: alsa::Error,
+ },
+
+ #[error("<AlsaSink> Device {device} Unsupported Access Type RWInterleaved, {e}")]
+ UnsupportedAccessType { device: String, e: alsa::Error },
+
+ #[error("<AlsaSink> Device {device} May be Invalid, Busy, or Already in Use, {e}")]
+ PcmSetUp { device: String, e: alsa::Error },
+
+ #[error("<AlsaSink> Failed to Drain PCM Buffer, {0}")]
+ DrainFailure(alsa::Error),
+
+ #[error("<AlsaSink> {0}")]
+ OnWrite(alsa::Error),
+
+ #[error("<AlsaSink> Hardware, {0}")]
+ HwParams(alsa::Error),
+
+ #[error("<AlsaSink> Software, {0}")]
+ SwParams(alsa::Error),
+
+ #[error("<AlsaSink> PCM, {0}")]
+ Pcm(alsa::Error),
+
+ #[error("<AlsaSink> Could Not Parse Output Name(s) and/or Description(s), {0}")]
+ Parsing(alsa::Error),
+
+ #[error("<AlsaSink>")]
+ NotConnected,
+}
+
+impl From<AlsaError> for SinkError {
+ fn from(e: AlsaError) -> SinkError {
+ use AlsaError::*;
+ let es = e.to_string();
+ match e {
+ DrainFailure(_) | OnWrite(_) => SinkError::OnWrite(es),
+ PcmSetUp { .. } => SinkError::ConnectionRefused(es),
+ NotConnected => SinkError::NotConnected(es),
+ _ => SinkError::InvalidParams(es),
+ }
+ }
+}
+
+impl From<AudioFormat> for Format {
+ fn from(f: AudioFormat) -> Format {
+ use AudioFormat::*;
+ match f {
+ F64 => Format::float64(),
+ F32 => Format::float(),
+ S32 => Format::s32(),
+ S24 => Format::s24(),
+ S24_3 => Format::s24_3(),
+ S16 => Format::s16(),
+ }
+ }
+}
+
+pub struct AlsaSink {
+ pcm: Option<PCM>,
+ format: AudioFormat,
+ device: String,
+ period_buffer: Vec<u8>,
+}
+
+fn list_compatible_devices() -> SinkResult<()> {
+ let i = HintIter::new_str(None, "pcm").map_err(AlsaError::Parsing)?;
+
+ println!("\n\n\tCompatible alsa device(s):\n");
+ println!("\t------------------------------------------------------\n");
+
+ for a in i {
+ if let Some(Direction::Playback) = a.direction {
+ if let Some(name) = a.name {
+ if let Ok(pcm) = PCM::new(&name, Direction::Playback, false) {
+ if let Ok(hwp) = HwParams::any(&pcm) {
+ // Only show devices that support
+ // 2 ch 44.1 Interleaved.
+
+ if hwp.set_access(Access::RWInterleaved).is_ok()
+ && hwp.set_rate(SAMPLE_RATE, ValueOr::Nearest).is_ok()
+ && hwp.set_channels(NUM_CHANNELS as u32).is_ok()
+ {
+ let mut supported_formats = vec![];
+
+ for f in &[
+ AudioFormat::S16,
+ AudioFormat::S24,
+ AudioFormat::S24_3,
+ AudioFormat::S32,
+ AudioFormat::F32,
+ AudioFormat::F64,
+ ] {
+ if hwp.test_format(Format::from(*f)).is_ok() {
+ supported_formats.push(format!("{f:?}"));
+ }
+ }
+
+ if !supported_formats.is_empty() {
+ println!("\tDevice:\n\n\t\t{name}\n");
+
+ println!(
+ "\tDescription:\n\n\t\t{}\n",
+ a.desc.unwrap_or_default().replace('\n', "\n\t\t")
+ );
+
+ println!(
+ "\tSupported Format(s):\n\n\t\t{}\n",
+ supported_formats.join(" ")
+ );
+
+ println!(
+ "\t------------------------------------------------------\n"
+ );
+ }
+ }
+ };
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn open_device(dev_name: &str, format: AudioFormat) -> SinkResult<(PCM, usize)> {
+ let pcm = PCM::new(dev_name, Direction::Playback, false).map_err(|e| AlsaError::PcmSetUp {
+ device: dev_name.to_string(),
+ e,
+ })?;
+
+ let bytes_per_period = {
+ let hwp = HwParams::any(&pcm).map_err(AlsaError::HwParams)?;
+
+ hwp.set_access(Access::RWInterleaved)
+ .map_err(|e| AlsaError::UnsupportedAccessType {
+ device: dev_name.to_string(),
+ e,
+ })?;
+
+ let alsa_format = Format::from(format);
+
+ hwp.set_format(alsa_format)
+ .map_err(|e| AlsaError::UnsupportedFormat {
+ device: dev_name.to_string(),
+ alsa_format,
+ format,
+ e,
+ })?;
+
+ hwp.set_rate(SAMPLE_RATE, ValueOr::Nearest).map_err(|e| {
+ AlsaError::UnsupportedSampleRate {
+ device: dev_name.to_string(),
+ samplerate: SAMPLE_RATE,
+ e,
+ }
+ })?;
+
+ hwp.set_channels(NUM_CHANNELS as u32)
+ .map_err(|e| AlsaError::UnsupportedChannelCount {
+ device: dev_name.to_string(),
+ channel_count: NUM_CHANNELS,
+ e,
+ })?;
+
+ // Clone the hwp while it's in
+ // a good working state so that
+ // in the event of an error setting
+ // the buffer and period sizes
+ // we can use the good working clone
+ // instead of the hwp that's in an
+ // error state.
+ let hwp_clone = hwp.clone();
+
+ // At a sampling rate of 44100:
+ // The largest buffer is 22050 Frames (500ms) with 5512 Frame periods (125ms).
+ // The smallest buffer is 4410 Frames (100ms) with 441 Frame periods (10ms).
+ // Actual values may vary.
+ //
+ // Larger buffer and period sizes are preferred as extremely small values
+ // will cause high CPU useage.
+ //
+ // If no buffer or period size is in those ranges or an error happens
+ // trying to set the buffer or period size use the device's defaults
+ // which may not be ideal but are *hopefully* serviceable.
+
+ let buffer_size = {
+ let max = match hwp.get_buffer_size_max() {
+ Err(e) => {
+ trace!("Error getting the device's max Buffer size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ };
+
+ let min = match hwp.get_buffer_size_min() {
+ Err(e) => {
+ trace!("Error getting the device's min Buffer size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ };
+
+ let buffer_size = if min < max {
+ match (MIN_BUFFER..=MAX_BUFFER)
+ .rev()
+ .find(|f| (min..=max).contains(f))
+ {
+ Some(size) => {
+ trace!("Desired Frames per Buffer: {size:?}");
+
+ match hwp.set_buffer_size_near(size) {
+ Err(e) => {
+ trace!("Error setting the device's Buffer size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ }
+ }
+ None => {
+ trace!("No Desired Buffer size in range reported by the device.");
+ ZERO_FRAMES
+ }
+ }
+ } else {
+ trace!(
+ "The device's min reported Buffer size was greater than or equal to its max reported Buffer size."
+ );
+ ZERO_FRAMES
+ };
+
+ if buffer_size == ZERO_FRAMES {
+ trace!("Desired Buffer Frame range: {MIN_BUFFER:?} - {MAX_BUFFER:?}",);
+
+ trace!("Actual Buffer Frame range as reported by the device: {min:?} - {max:?}",);
+ }
+
+ buffer_size
+ };
+
+ let period_size = {
+ if buffer_size == ZERO_FRAMES {
+ ZERO_FRAMES
+ } else {
+ let max = match hwp.get_period_size_max() {
+ Err(e) => {
+ trace!("Error getting the device's max Period size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ };
+
+ let min = match hwp.get_period_size_min() {
+ Err(e) => {
+ trace!("Error getting the device's min Period size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ };
+
+ let max_period = buffer_size / MAX_PERIOD_DIVISOR;
+ let min_period = buffer_size / MIN_PERIOD_DIVISOR;
+
+ let period_size = if min < max && min_period < max_period {
+ match (min_period..=max_period)
+ .rev()
+ .find(|f| (min..=max).contains(f))
+ {
+ Some(size) => {
+ trace!("Desired Frames per Period: {size:?}");
+
+ match hwp.set_period_size_near(size, ValueOr::Nearest) {
+ Err(e) => {
+ trace!("Error setting the device's Period size: {e}");
+ ZERO_FRAMES
+ }
+ Ok(s) => s,
+ }
+ }
+ None => {
+ trace!("No Desired Period size in range reported by the device.");
+ ZERO_FRAMES
+ }
+ }
+ } else {
+ trace!(
+ "The device's min reported Period size was greater than or equal to its max reported Period size,"
+ );
+ trace!(
+ "or the desired min Period size was greater than or equal to the desired max Period size."
+ );
+ ZERO_FRAMES
+ };
+
+ if period_size == ZERO_FRAMES {
+ trace!("Buffer size: {buffer_size:?}");
+
+ trace!(
+ "Desired Period Frame range: {min_period:?} (Buffer size / {MIN_PERIOD_DIVISOR:?}) - {max_period:?} (Buffer size / {MAX_PERIOD_DIVISOR:?})",
+ );
+
+ trace!(
+ "Actual Period Frame range as reported by the device: {min:?} - {max:?}",
+ );
+ }
+
+ period_size
+ }
+ };
+
+ if buffer_size == ZERO_FRAMES || period_size == ZERO_FRAMES {
+ trace!(
+ "Failed to set Buffer and/or Period size, falling back to the device's defaults."
+ );
+
+ trace!("You may experience higher than normal CPU usage and/or audio issues.");
+
+ pcm.hw_params(&hwp_clone).map_err(AlsaError::Pcm)?;
+ } else {
+ pcm.hw_params(&hwp).map_err(AlsaError::Pcm)?;
+ }
+
+ let hwp = pcm.hw_params_current().map_err(AlsaError::Pcm)?;
+
+ // Don't assume we got what we wanted. Ask to make sure.
+ let frames_per_period = hwp.get_period_size().map_err(AlsaError::HwParams)?;
+
+ let frames_per_buffer = hwp.get_buffer_size().map_err(AlsaError::HwParams)?;
+
+ let swp = pcm.sw_params_current().map_err(AlsaError::Pcm)?;
+
+ swp.set_start_threshold(frames_per_buffer - frames_per_period)
+ .map_err(AlsaError::SwParams)?;
+
+ pcm.sw_params(&swp).map_err(AlsaError::Pcm)?;
+
+ trace!("Actual Frames per Buffer: {frames_per_buffer:?}");
+ trace!("Actual Frames per Period: {frames_per_period:?}");
+
+ // Let ALSA do the math for us.
+ pcm.frames_to_bytes(frames_per_period) as usize
+ };
+
+ trace!("Period Buffer size in bytes: {bytes_per_period:?}");
+
+ Ok((pcm, bytes_per_period))
+}
+
+impl Open for AlsaSink {
+ fn open(device: Option<String>, format: AudioFormat) -> Self {
+ let name = match device.as_deref() {
+ Some("?") => match list_compatible_devices() {
+ Ok(_) => {
+ exit(0);
+ }
+ Err(e) => {
+ error!("{e}");
+ exit(1);
+ }
+ },
+ Some(device) => device,
+ None => "default",
+ }
+ .to_string();
+
+ info!("Using AlsaSink with format: {format:?}");
+
+ Self {
+ pcm: None,
+ format,
+ device: name,
+ period_buffer: vec![],
+ }
+ }
+}
+
+impl Sink for AlsaSink {
+ fn start(&mut self) -> SinkResult<()> {
+ if self.pcm.is_none() {
+ let (pcm, bytes_per_period) = open_device(&self.device, self.format)?;
+ self.pcm = Some(pcm);
+
+ if self.period_buffer.capacity() != bytes_per_period {
+ self.period_buffer = Vec::with_capacity(bytes_per_period);
+ }
+
+ // Should always match the "Period Buffer size in bytes: " trace! message.
+ trace!(
+ "Period Buffer capacity: {:?}",
+ self.period_buffer.capacity()
+ );
+ }
+
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ if self.pcm.is_some() {
+ // Zero fill the remainder of the period buffer and
+ // write any leftover data before draining the actual PCM buffer.
+ self.period_buffer.resize(self.period_buffer.capacity(), 0);
+ self.write_buf()?;
+
+ let pcm = self.pcm.take().ok_or(AlsaError::NotConnected)?;
+
+ pcm.drain().map_err(AlsaError::DrainFailure)?;
+ }
+
+ Ok(())
+ }
+
+ sink_as_bytes!();
+}
+
+impl SinkAsBytes for AlsaSink {
+ #[inline]
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
+ let mut start_index = 0;
+ let data_len = data.len();
+ let capacity = self.period_buffer.capacity();
+
+ loop {
+ let data_left = data_len - start_index;
+ let space_left = capacity - self.period_buffer.len();
+ let data_to_buffer = data_left.min(space_left);
+ let end_index = start_index + data_to_buffer;
+
+ self.period_buffer
+ .extend_from_slice(&data[start_index..end_index]);
+
+ if self.period_buffer.len() == capacity {
+ self.write_buf()?;
+ }
+
+ if end_index == data_len {
+ break Ok(());
+ }
+
+ start_index = end_index;
+ }
+ }
+}
+
+impl AlsaSink {
+ pub const NAME: &'static str = "alsa";
+
+ fn write_buf(&mut self) -> SinkResult<()> {
+ if self.pcm.is_some() {
+ let write_result = {
+ let pcm = self.pcm.as_mut().ok_or(AlsaError::NotConnected)?;
+
+ match pcm.io_bytes().writei(&self.period_buffer) {
+ Ok(_) => Ok(()),
+ Err(e) => {
+ // Capture and log the original error as a warning, and then try to recover.
+ // If recovery fails then forward that error back to player.
+ warn!("Error writing from AlsaSink buffer to PCM, trying to recover, {e}");
+
+ pcm.try_recover(e, false).map_err(AlsaError::OnWrite)
+ }
+ }
+ };
+
+ if let Err(e) = write_result {
+ self.pcm = None;
+ return Err(e.into());
+ }
+ }
+
+ self.period_buffer.clear();
+ Ok(())
+ }
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/gstreamer.rs b/native/vendor/librespot-playback/src/audio_backend/gstreamer.rs
new file mode 100644
index 0000000..f41d433
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/gstreamer.rs
@@ -0,0 +1,216 @@
+use std::sync::{Arc, Mutex};
+
+use gstreamer::{
+ State,
+ event::{FlushStart, FlushStop},
+ prelude::*,
+};
+
+use gstreamer as gst;
+use gstreamer_app as gst_app;
+use gstreamer_audio as gst_audio;
+
+const GSTREAMER_ASYNC_ERROR_POISON_MSG: &str = "gstreamer async error mutex should not be poisoned";
+
+use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
+
+use crate::{
+ NUM_CHANNELS, SAMPLE_RATE, config::AudioFormat, convert::Converter, decoder::AudioPacket,
+};
+
+pub struct GstreamerSink {
+ appsrc: gst_app::AppSrc,
+ bufferpool: gst::BufferPool,
+ pipeline: gst::Pipeline,
+ format: AudioFormat,
+ async_error: Arc<Mutex<Option<String>>>,
+}
+
+impl Open for GstreamerSink {
+ fn open(device: Option<String>, format: AudioFormat) -> Self {
+ info!("Using GStreamer sink with format: {format:?}");
+ gst::init().expect("failed to init GStreamer!");
+
+ let gst_format = match format {
+ AudioFormat::F64 => gst_audio::AUDIO_FORMAT_F64,
+ AudioFormat::F32 => gst_audio::AUDIO_FORMAT_F32,
+ AudioFormat::S32 => gst_audio::AUDIO_FORMAT_S32,
+ AudioFormat::S24 => gst_audio::AUDIO_FORMAT_S2432,
+ AudioFormat::S24_3 => gst_audio::AUDIO_FORMAT_S24,
+ AudioFormat::S16 => gst_audio::AUDIO_FORMAT_S16,
+ };
+
+ let gst_info = gst_audio::AudioInfo::builder(gst_format, SAMPLE_RATE, NUM_CHANNELS as u32)
+ .build()
+ .expect("Failed to create GStreamer audio format");
+ let gst_caps = gst_info.to_caps().expect("Failed to create GStreamer caps");
+
+ let sample_size = format.size();
+ let gst_bytes = NUM_CHANNELS as usize * 2048 * sample_size;
+
+ let pipeline = gst::Pipeline::new();
+ let appsrc = gst::ElementFactory::make("appsrc")
+ .build()
+ .expect("Failed to create GStreamer appsrc element")
+ .downcast::<gst_app::AppSrc>()
+ .expect("couldn't cast AppSrc element at runtime!");
+ appsrc.set_caps(Some(&gst_caps));
+ appsrc.set_max_bytes(gst_bytes as u64);
+ appsrc.set_block(true);
+
+ let sink = match device {
+ None => {
+ // no need to dither twice; use librespot dithering instead
+ gst::parse::bin_from_description(
+ "audioconvert dithering=none ! audioresample ! autoaudiosink",
+ true,
+ )
+ .expect("Failed to create default GStreamer sink")
+ }
+ Some(ref x) => gst::parse::bin_from_description(x, true)
+ .expect("Failed to create custom GStreamer sink"),
+ };
+ pipeline
+ .add(&appsrc)
+ .expect("Failed to add GStreamer appsrc to pipeline");
+ pipeline
+ .add(&sink)
+ .expect("Failed to add GStreamer sink to pipeline");
+ appsrc
+ .link(&sink)
+ .expect("Failed to link GStreamer source to sink");
+
+ let bus = pipeline.bus().expect("couldn't get bus from pipeline");
+
+ let bufferpool = gst::BufferPool::new();
+
+ let mut conf = bufferpool.config();
+ conf.set_params(Some(&gst_caps), gst_bytes as u32, 0, 0);
+ bufferpool
+ .set_config(conf)
+ .expect("couldn't configure the buffer pool");
+
+ let async_error = Arc::new(Mutex::new(None));
+ let async_error_clone = async_error.clone();
+
+ bus.set_sync_handler(move |_bus, msg| {
+ match msg.view() {
+ gst::MessageView::Eos(_) => {
+ println!("gst signaled end of stream");
+
+ let mut async_error_storage = async_error_clone
+ .lock()
+ .expect(GSTREAMER_ASYNC_ERROR_POISON_MSG);
+ *async_error_storage = Some(String::from("gst signaled end of stream"));
+ }
+ gst::MessageView::Error(err) => {
+ println!(
+ "Error from {:?}: {} ({:?})",
+ err.src().map(|s| s.path_string()),
+ err.error(),
+ err.debug()
+ );
+
+ let mut async_error_storage = async_error_clone
+ .lock()
+ .expect(GSTREAMER_ASYNC_ERROR_POISON_MSG);
+ *async_error_storage = Some(format!(
+ "Error from {:?}: {} ({:?})",
+ err.src().map(|s| s.path_string()),
+ err.error(),
+ err.debug()
+ ));
+ }
+ _ => (),
+ }
+
+ gst::BusSyncReply::Drop
+ });
+
+ pipeline
+ .set_state(State::Ready)
+ .expect("unable to set the pipeline to the `Ready` state");
+
+ Self {
+ appsrc,
+ bufferpool,
+ pipeline,
+ format,
+ async_error,
+ }
+ }
+}
+
+impl Sink for GstreamerSink {
+ fn start(&mut self) -> SinkResult<()> {
+ *self
+ .async_error
+ .lock()
+ .expect(GSTREAMER_ASYNC_ERROR_POISON_MSG) = None;
+ self.appsrc.send_event(FlushStop::new(true));
+ self.bufferpool
+ .set_active(true)
+ .map_err(|e| SinkError::StateChange(e.to_string()))?;
+ self.pipeline
+ .set_state(State::Playing)
+ .map_err(|e| SinkError::StateChange(e.to_string()))?;
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ *self
+ .async_error
+ .lock()
+ .expect(GSTREAMER_ASYNC_ERROR_POISON_MSG) = None;
+ self.appsrc.send_event(FlushStart::new());
+ self.pipeline
+ .set_state(State::Paused)
+ .map_err(|e| SinkError::StateChange(e.to_string()))?;
+ self.bufferpool
+ .set_active(false)
+ .map_err(|e| SinkError::StateChange(e.to_string()))?;
+ Ok(())
+ }
+
+ sink_as_bytes!();
+}
+
+impl Drop for GstreamerSink {
+ fn drop(&mut self) {
+ let _ = self.pipeline.set_state(State::Null);
+ }
+}
+
+impl SinkAsBytes for GstreamerSink {
+ #[inline]
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
+ if let Some(async_error) = &*self
+ .async_error
+ .lock()
+ .expect(GSTREAMER_ASYNC_ERROR_POISON_MSG)
+ {
+ return Err(SinkError::OnWrite(async_error.to_string()));
+ }
+
+ let mut buffer = self
+ .bufferpool
+ .acquire_buffer(None)
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+
+ let mutbuf = buffer.make_mut();
+ mutbuf.set_size(data.len());
+ mutbuf
+ .copy_from_slice(0, data)
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+
+ self.appsrc
+ .push_buffer(buffer)
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+
+ Ok(())
+ }
+}
+
+impl GstreamerSink {
+ pub const NAME: &'static str = "gstreamer";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/jackaudio.rs b/native/vendor/librespot-playback/src/audio_backend/jackaudio.rs
new file mode 100644
index 0000000..84b13b6
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/jackaudio.rs
@@ -0,0 +1,87 @@
+use super::{Open, Sink, SinkError, SinkResult};
+use crate::NUM_CHANNELS;
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use jack::{
+ AsyncClient, AudioOut, Client, ClientOptions, Control, Port, ProcessHandler, ProcessScope,
+};
+use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
+
+pub struct JackSink {
+ send: SyncSender<f32>,
+ // We have to keep hold of this object, or the Sink can't play...
+ #[allow(dead_code)]
+ active_client: AsyncClient<(), JackData>,
+}
+
+pub struct JackData {
+ rec: Receiver<f32>,
+ port_l: Port<AudioOut>,
+ port_r: Port<AudioOut>,
+}
+
+impl ProcessHandler for JackData {
+ fn process(&mut self, _: &Client, ps: &ProcessScope) -> Control {
+ // get output port buffers
+ let buf_r: &mut [f32] = self.port_r.as_mut_slice(ps);
+ let buf_l: &mut [f32] = self.port_l.as_mut_slice(ps);
+ // get queue iterator
+ let mut queue_iter = self.rec.try_iter();
+
+ for i in 0..buf_r.len() {
+ buf_r[i] = queue_iter.next().unwrap_or(0.0);
+ buf_l[i] = queue_iter.next().unwrap_or(0.0);
+ }
+ Control::Continue
+ }
+}
+
+impl Open for JackSink {
+ fn open(client_name: Option<String>, format: AudioFormat) -> Self {
+ if format != AudioFormat::F32 {
+ warn!("JACK currently does not support {format:?} output");
+ }
+ info!("Using JACK sink with format {:?}", AudioFormat::F32);
+
+ let client_name = client_name.unwrap_or_else(|| "librespot".to_string());
+ let (client, _status) =
+ Client::new(&client_name[..], ClientOptions::NO_START_SERVER).unwrap();
+ let ch_r = client.register_port("out_0", AudioOut::default()).unwrap();
+ let ch_l = client.register_port("out_1", AudioOut::default()).unwrap();
+ // buffer for samples from librespot (~10ms)
+ let (tx, rx) = sync_channel::<f32>(NUM_CHANNELS as usize * 1024 * AudioFormat::F32.size());
+ let jack_data = JackData {
+ rec: rx,
+ port_l: ch_l,
+ port_r: ch_r,
+ };
+ let active_client = AsyncClient::new(client, (), jack_data).unwrap();
+
+ Self {
+ send: tx,
+ active_client,
+ }
+ }
+}
+
+impl Sink for JackSink {
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
+ let samples = packet
+ .samples()
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+
+ let samples_f32: &[f32] = &converter.f64_to_f32(samples);
+ for sample in samples_f32.iter() {
+ let res = self.send.send(*sample);
+ if res.is_err() {
+ error!("cannot write to channel");
+ }
+ }
+ Ok(())
+ }
+}
+
+impl JackSink {
+ pub const NAME: &'static str = "jackaudio";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/mod.rs b/native/vendor/librespot-playback/src/audio_backend/mod.rs
new file mode 100644
index 0000000..f8f43e3
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/mod.rs
@@ -0,0 +1,154 @@
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum SinkError {
+ #[error("Audio Sink Error Not Connected: {0}")]
+ NotConnected(String),
+ #[error("Audio Sink Error Connection Refused: {0}")]
+ ConnectionRefused(String),
+ #[error("Audio Sink Error On Write: {0}")]
+ OnWrite(String),
+ #[error("Audio Sink Error Invalid Parameters: {0}")]
+ InvalidParams(String),
+ #[error("Audio Sink Error Changing State: {0}")]
+ StateChange(String),
+}
+
+pub type SinkResult<T> = Result<T, SinkError>;
+
+pub trait Open {
+ fn open(_: Option<String>, format: AudioFormat) -> Self;
+}
+
+pub trait Sink {
+ fn start(&mut self) -> SinkResult<()> {
+ Ok(())
+ }
+ fn stop(&mut self) -> SinkResult<()> {
+ Ok(())
+ }
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()>;
+}
+
+pub type SinkBuilder = fn(Option<String>, AudioFormat) -> Box<dyn Sink>;
+
+pub trait SinkAsBytes {
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()>;
+}
+
+fn mk_sink<S: Sink + Open + 'static>(device: Option<String>, format: AudioFormat) -> Box<dyn Sink> {
+ Box::new(S::open(device, format))
+}
+
+// reuse code for various backends
+macro_rules! sink_as_bytes {
+ () => {
+ #[inline]
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
+ use crate::convert::i24;
+ use zerocopy::IntoBytes;
+ match packet {
+ AudioPacket::Samples(samples) => match self.format {
+ AudioFormat::F64 => self.write_bytes(samples.as_bytes()),
+ AudioFormat::F32 => {
+ let samples_f32: &[f32] = &converter.f64_to_f32(&samples);
+ self.write_bytes(samples_f32.as_bytes())
+ }
+ AudioFormat::S32 => {
+ let samples_s32: &[i32] = &converter.f64_to_s32(&samples);
+ self.write_bytes(samples_s32.as_bytes())
+ }
+ AudioFormat::S24 => {
+ let samples_s24: &[i32] = &converter.f64_to_s24(&samples);
+ self.write_bytes(samples_s24.as_bytes())
+ }
+ AudioFormat::S24_3 => {
+ let samples_s24_3: &[i24] = &converter.f64_to_s24_3(&samples);
+ self.write_bytes(samples_s24_3.as_bytes())
+ }
+ AudioFormat::S16 => {
+ let samples_s16: &[i16] = &converter.f64_to_s16(&samples);
+ self.write_bytes(samples_s16.as_bytes())
+ }
+ },
+ AudioPacket::Raw(samples) => self.write_bytes(&samples),
+ }
+ }
+ };
+}
+
+#[cfg(feature = "alsa-backend")]
+mod alsa;
+#[cfg(feature = "alsa-backend")]
+use self::alsa::AlsaSink;
+
+#[cfg(feature = "portaudio-backend")]
+mod portaudio;
+#[cfg(feature = "portaudio-backend")]
+use self::portaudio::PortAudioSink;
+
+#[cfg(feature = "pulseaudio-backend")]
+mod pulseaudio;
+#[cfg(feature = "pulseaudio-backend")]
+use self::pulseaudio::PulseAudioSink;
+
+#[cfg(feature = "jackaudio-backend")]
+mod jackaudio;
+#[cfg(feature = "jackaudio-backend")]
+use self::jackaudio::JackSink;
+
+#[cfg(feature = "gstreamer-backend")]
+mod gstreamer;
+#[cfg(feature = "gstreamer-backend")]
+use self::gstreamer::GstreamerSink;
+
+#[cfg(any(feature = "rodio-backend", feature = "rodiojack-backend"))]
+mod rodio;
+#[cfg(feature = "rodio-backend")]
+use self::rodio::RodioSink;
+
+#[cfg(feature = "sdl-backend")]
+mod sdl;
+#[cfg(feature = "sdl-backend")]
+use self::sdl::SdlSink;
+
+mod pipe;
+use self::pipe::StdoutSink;
+
+mod subprocess;
+use self::subprocess::SubprocessSink;
+
+pub const BACKENDS: &[(&str, SinkBuilder)] = &[
+ #[cfg(feature = "rodio-backend")]
+ (RodioSink::NAME, rodio::mk_rodio), // default goes first
+ #[cfg(feature = "alsa-backend")]
+ (AlsaSink::NAME, mk_sink::<AlsaSink>),
+ #[cfg(feature = "portaudio-backend")]
+ (PortAudioSink::NAME, mk_sink::<PortAudioSink<'_>>),
+ #[cfg(feature = "pulseaudio-backend")]
+ (PulseAudioSink::NAME, mk_sink::<PulseAudioSink>),
+ #[cfg(feature = "jackaudio-backend")]
+ (JackSink::NAME, mk_sink::<JackSink>),
+ #[cfg(feature = "gstreamer-backend")]
+ (GstreamerSink::NAME, mk_sink::<GstreamerSink>),
+ #[cfg(feature = "rodiojack-backend")]
+ ("rodiojack", rodio::mk_rodiojack),
+ #[cfg(feature = "sdl-backend")]
+ (SdlSink::NAME, mk_sink::<SdlSink>),
+ (StdoutSink::NAME, mk_sink::<StdoutSink>),
+ (SubprocessSink::NAME, mk_sink::<SubprocessSink>),
+];
+
+pub fn find(name: Option<String>) -> Option<SinkBuilder> {
+ if let Some(name) = name {
+ BACKENDS
+ .iter()
+ .find(|backend| name == backend.0)
+ .map(|backend| backend.1)
+ } else {
+ BACKENDS.first().map(|backend| backend.1)
+ }
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/pipe.rs b/native/vendor/librespot-playback/src/audio_backend/pipe.rs
new file mode 100644
index 0000000..8dfd21e
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/pipe.rs
@@ -0,0 +1,113 @@
+use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+
+use std::fs::OpenOptions;
+use std::io::{self, Write};
+use std::process::exit;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+enum StdoutError {
+ #[error("<StdoutSink> {0}")]
+ OnWrite(std::io::Error),
+
+ #[error("<StdoutSink> File Path {file} Can Not be Opened and/or Created, {e}")]
+ OpenFailure { file: String, e: std::io::Error },
+
+ #[error("<StdoutSink> Failed to Flush the Output Stream, {0}")]
+ FlushFailure(std::io::Error),
+
+ #[error("<StdoutSink> The Output Stream is None")]
+ NoOutput,
+}
+
+impl From<StdoutError> for SinkError {
+ fn from(e: StdoutError) -> SinkError {
+ use StdoutError::*;
+ let es = e.to_string();
+ match e {
+ FlushFailure(_) | OnWrite(_) => SinkError::OnWrite(es),
+ OpenFailure { .. } => SinkError::ConnectionRefused(es),
+ NoOutput => SinkError::NotConnected(es),
+ }
+ }
+}
+
+pub struct StdoutSink {
+ output: Option<Box<dyn Write>>,
+ file: Option<String>,
+ format: AudioFormat,
+}
+
+impl Open for StdoutSink {
+ fn open(file: Option<String>, format: AudioFormat) -> Self {
+ if let Some("?") = file.as_deref() {
+ println!(
+ "\nUsage:\n\nOutput to stdout:\n\n\t--backend pipe\n\nOutput to file:\n\n\t--backend pipe --device {{filename}}\n"
+ );
+ exit(0);
+ }
+
+ info!("Using StdoutSink (pipe) with format: {format:?}");
+
+ Self {
+ output: None,
+ file,
+ format,
+ }
+ }
+}
+
+impl Sink for StdoutSink {
+ fn start(&mut self) -> SinkResult<()> {
+ self.output.get_or_insert({
+ match self.file.as_deref() {
+ Some(file) => Box::new(
+ OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(file)
+ .map_err(|e| StdoutError::OpenFailure {
+ file: file.to_string(),
+ e,
+ })?,
+ ),
+ None => Box::new(io::stdout()),
+ }
+ });
+
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ self.output
+ .take()
+ .ok_or(StdoutError::NoOutput)?
+ .flush()
+ .map_err(StdoutError::FlushFailure)?;
+
+ Ok(())
+ }
+
+ sink_as_bytes!();
+}
+
+impl SinkAsBytes for StdoutSink {
+ #[inline]
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
+ self.output
+ .as_deref_mut()
+ .ok_or(StdoutError::NoOutput)?
+ .write_all(data)
+ .map_err(StdoutError::OnWrite)?;
+
+ Ok(())
+ }
+}
+
+impl StdoutSink {
+ pub const NAME: &'static str = "pipe";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/portaudio.rs b/native/vendor/librespot-playback/src/audio_backend/portaudio.rs
new file mode 100644
index 0000000..f8b284f
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/portaudio.rs
@@ -0,0 +1,186 @@
+use super::{Open, Sink, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use crate::{NUM_CHANNELS, SAMPLE_RATE};
+use portaudio_rs::device::{DeviceIndex, DeviceInfo, get_default_output_index};
+use portaudio_rs::stream::*;
+use std::process::exit;
+use std::time::Duration;
+
+pub enum PortAudioSink<'a> {
+ F32(
+ Option<portaudio_rs::stream::Stream<'a, f32, f32>>,
+ StreamParameters<f32>,
+ ),
+ S32(
+ Option<portaudio_rs::stream::Stream<'a, i32, i32>>,
+ StreamParameters<i32>,
+ ),
+ S16(
+ Option<portaudio_rs::stream::Stream<'a, i16, i16>>,
+ StreamParameters<i16>,
+ ),
+}
+
+fn output_devices() -> Box<dyn Iterator<Item = (DeviceIndex, DeviceInfo)>> {
+ let count = portaudio_rs::device::get_count().unwrap();
+ let devices = (0..count)
+ .filter_map(|idx| portaudio_rs::device::get_info(idx).map(|info| (idx, info)))
+ .filter(|(_, info)| info.max_output_channels > 0);
+
+ Box::new(devices)
+}
+
+fn list_outputs() {
+ let default = get_default_output_index();
+
+ for (idx, info) in output_devices() {
+ if Some(idx) == default {
+ println!("- {} (default)", info.name);
+ } else {
+ println!("- {}", info.name)
+ }
+ }
+}
+
+fn find_output(device: &str) -> Option<DeviceIndex> {
+ output_devices()
+ .find(|(_, info)| info.name == device)
+ .map(|(idx, _)| idx)
+}
+
+impl<'a> Open for PortAudioSink<'a> {
+ fn open(device: Option<String>, format: AudioFormat) -> PortAudioSink<'a> {
+ info!("Using PortAudio sink with format: {format:?}");
+
+ portaudio_rs::initialize().unwrap();
+
+ let device_idx = match device.as_deref() {
+ Some("?") => {
+ list_outputs();
+ exit(0)
+ }
+ Some(device) => find_output(device),
+ None => get_default_output_index(),
+ }
+ .expect("could not find device");
+
+ let info = portaudio_rs::device::get_info(device_idx);
+ let latency = match info {
+ Some(info) => info.default_high_output_latency,
+ None => Duration::new(0, 0),
+ };
+
+ macro_rules! open_sink {
+ ($sink: expr, $type: ty) => {{
+ let params = StreamParameters {
+ device: device_idx,
+ channel_count: NUM_CHANNELS as u32,
+ suggested_latency: latency,
+ data: 0.0 as $type,
+ };
+ $sink(None, params)
+ }};
+ }
+ match format {
+ AudioFormat::F32 => open_sink!(Self::F32, f32),
+ AudioFormat::S32 => open_sink!(Self::S32, i32),
+ AudioFormat::S16 => open_sink!(Self::S16, i16),
+ _ => {
+ unimplemented!("PortAudio currently does not support {format:?} output")
+ }
+ }
+ }
+}
+
+impl Sink for PortAudioSink<'_> {
+ fn start(&mut self) -> SinkResult<()> {
+ macro_rules! start_sink {
+ (ref mut $stream: ident, ref $parameters: ident) => {{
+ if $stream.is_none() {
+ *$stream = Some(
+ Stream::open(
+ None,
+ Some(*$parameters),
+ SAMPLE_RATE as f64,
+ FRAMES_PER_BUFFER_UNSPECIFIED,
+ StreamFlags::DITHER_OFF, // no need to dither twice; use librespot dithering instead
+ None,
+ )
+ .unwrap(),
+ );
+ }
+ $stream.as_mut().unwrap().start().unwrap()
+ }};
+ }
+
+ match self {
+ Self::F32(stream, parameters) => start_sink!(ref mut stream, ref parameters),
+ Self::S32(stream, parameters) => start_sink!(ref mut stream, ref parameters),
+ Self::S16(stream, parameters) => start_sink!(ref mut stream, ref parameters),
+ };
+
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ macro_rules! stop_sink {
+ (ref mut $stream: ident) => {{
+ $stream.as_mut().unwrap().stop().unwrap();
+ *$stream = None;
+ }};
+ }
+ match self {
+ Self::F32(stream, _) => stop_sink!(ref mut stream),
+ Self::S32(stream, _) => stop_sink!(ref mut stream),
+ Self::S16(stream, _) => stop_sink!(ref mut stream),
+ };
+
+ Ok(())
+ }
+
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
+ macro_rules! write_sink {
+ (ref mut $stream: expr, $samples: expr) => {
+ $stream.as_mut().unwrap().write($samples)
+ };
+ }
+
+ let samples = packet
+ .samples()
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+
+ let result = match self {
+ Self::F32(stream, _parameters) => {
+ let samples_f32: &[f32] = &converter.f64_to_f32(samples);
+ write_sink!(ref mut stream, samples_f32)
+ }
+ Self::S32(stream, _parameters) => {
+ let samples_s32: &[i32] = &converter.f64_to_s32(samples);
+ write_sink!(ref mut stream, samples_s32)
+ }
+ Self::S16(stream, _parameters) => {
+ let samples_s16: &[i16] = &converter.f64_to_s16(samples);
+ write_sink!(ref mut stream, samples_s16)
+ }
+ };
+ match result {
+ Ok(_) => (),
+ Err(portaudio_rs::PaError::OutputUnderflowed) => error!("PortAudio write underflow"),
+ Err(e) => panic!("PortAudio error {e}"),
+ };
+
+ Ok(())
+ }
+}
+
+impl Drop for PortAudioSink<'_> {
+ fn drop(&mut self) {
+ portaudio_rs::terminate().unwrap();
+ }
+}
+
+impl PortAudioSink<'_> {
+ pub const NAME: &'static str = "portaudio";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/pulseaudio.rs b/native/vendor/librespot-playback/src/audio_backend/pulseaudio.rs
new file mode 100644
index 0000000..0cc0850
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/pulseaudio.rs
@@ -0,0 +1,152 @@
+use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use crate::{NUM_CHANNELS, SAMPLE_RATE};
+use libpulse_binding::{self as pulse, error::PAErr, stream::Direction};
+use libpulse_simple_binding::Simple;
+use std::env;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+enum PulseError {
+ #[error(
+ "<PulseAudioSink> Unsupported Pulseaudio Sample Spec, Format {pulse_format:?} ({format:?}), Channels {channels}, Rate {rate}"
+ )]
+ InvalidSampleSpec {
+ pulse_format: pulse::sample::Format,
+ format: AudioFormat,
+ channels: u8,
+ rate: u32,
+ },
+
+ #[error("<PulseAudioSink> {0}")]
+ ConnectionRefused(PAErr),
+
+ #[error("<PulseAudioSink> Failed to Drain Pulseaudio Buffer, {0}")]
+ DrainFailure(PAErr),
+
+ #[error("<PulseAudioSink>")]
+ NotConnected,
+
+ #[error("<PulseAudioSink> {0}")]
+ OnWrite(PAErr),
+}
+
+impl From<PulseError> for SinkError {
+ fn from(e: PulseError) -> SinkError {
+ use PulseError::*;
+ let es = e.to_string();
+ match e {
+ DrainFailure(_) | OnWrite(_) => SinkError::OnWrite(es),
+ ConnectionRefused(_) => SinkError::ConnectionRefused(es),
+ NotConnected => SinkError::NotConnected(es),
+ InvalidSampleSpec { .. } => SinkError::InvalidParams(es),
+ }
+ }
+}
+
+pub struct PulseAudioSink {
+ sink: Option<Simple>,
+ device: Option<String>,
+ app_name: String,
+ stream_desc: String,
+ format: AudioFormat,
+}
+
+impl Open for PulseAudioSink {
+ fn open(device: Option<String>, format: AudioFormat) -> Self {
+ let app_name = env::var("PULSE_PROP_application.name").unwrap_or_default();
+ let stream_desc = env::var("PULSE_PROP_stream.description").unwrap_or_default();
+
+ let mut actual_format = format;
+
+ if actual_format == AudioFormat::F64 {
+ warn!("PulseAudio currently does not support F64 output");
+ actual_format = AudioFormat::F32;
+ }
+
+ info!("Using PulseAudioSink with format: {actual_format:?}");
+
+ Self {
+ sink: None,
+ device,
+ app_name,
+ stream_desc,
+ format: actual_format,
+ }
+ }
+}
+
+impl Sink for PulseAudioSink {
+ fn start(&mut self) -> SinkResult<()> {
+ if self.sink.is_none() {
+ // PulseAudio calls S24 and S24_3 different from the rest of the world
+ let pulse_format = match self.format {
+ AudioFormat::F32 => pulse::sample::Format::FLOAT32NE,
+ AudioFormat::S32 => pulse::sample::Format::S32NE,
+ AudioFormat::S24 => pulse::sample::Format::S24_32NE,
+ AudioFormat::S24_3 => pulse::sample::Format::S24NE,
+ AudioFormat::S16 => pulse::sample::Format::S16NE,
+ _ => unreachable!(),
+ };
+
+ let sample_spec = pulse::sample::Spec {
+ format: pulse_format,
+ channels: NUM_CHANNELS,
+ rate: SAMPLE_RATE,
+ };
+
+ if !sample_spec.is_valid() {
+ let pulse_error = PulseError::InvalidSampleSpec {
+ pulse_format,
+ format: self.format,
+ channels: NUM_CHANNELS,
+ rate: SAMPLE_RATE,
+ };
+
+ return Err(SinkError::from(pulse_error));
+ }
+
+ let sink = Simple::new(
+ None, // Use the default server.
+ &self.app_name, // Our application's name.
+ Direction::Playback, // Direction.
+ self.device.as_deref(), // Our device (sink) name.
+ &self.stream_desc, // Description of our stream.
+ &sample_spec, // Our sample format.
+ None, // Use default channel map.
+ None, // Use default buffering attributes.
+ )
+ .map_err(PulseError::ConnectionRefused)?;
+
+ self.sink = Some(sink);
+ }
+
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ let sink = self.sink.take().ok_or(PulseError::NotConnected)?;
+
+ sink.drain().map_err(PulseError::DrainFailure)?;
+ Ok(())
+ }
+
+ sink_as_bytes!();
+}
+
+impl SinkAsBytes for PulseAudioSink {
+ #[inline]
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
+ let sink = self.sink.as_mut().ok_or(PulseError::NotConnected)?;
+
+ sink.write(data).map_err(PulseError::OnWrite)?;
+
+ Ok(())
+ }
+}
+
+impl PulseAudioSink {
+ pub const NAME: &'static str = "pulseaudio";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/rodio.rs b/native/vendor/librespot-playback/src/audio_backend/rodio.rs
new file mode 100644
index 0000000..b6cd346
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/rodio.rs
@@ -0,0 +1,269 @@
+use std::process::exit;
+use std::thread;
+use std::time::Duration;
+
+use cpal::traits::{DeviceTrait, HostTrait};
+use thiserror::Error;
+
+use super::{Sink, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use crate::{NUM_CHANNELS, SAMPLE_RATE};
+
+#[cfg(all(
+ feature = "rodiojack-backend",
+ not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"))
+))]
+compile_error!("Rodio JACK backend is currently only supported on linux.");
+
+#[cfg(feature = "rodio-backend")]
+pub fn mk_rodio(device: Option<String>, format: AudioFormat) -> Box<dyn Sink> {
+ Box::new(open(cpal::default_host(), device, format))
+}
+
+#[cfg(feature = "rodiojack-backend")]
+pub fn mk_rodiojack(device: Option<String>, format: AudioFormat) -> Box<dyn Sink> {
+ Box::new(open(
+ cpal::host_from_id(cpal::HostId::Jack).unwrap(),
+ device,
+ format,
+ ))
+}
+
+#[derive(Debug, Error)]
+pub enum RodioError {
+ #[error("<RodioSink> No Device Available")]
+ NoDeviceAvailable,
+ #[error("<RodioSink> device \"{0}\" is Not Available")]
+ DeviceNotAvailable(String),
+ #[error("<RodioSink> Play Error: {0}")]
+ PlayError(#[from] rodio::PlayError),
+ #[error("<RodioSink> Stream Error: {0}")]
+ StreamError(#[from] rodio::StreamError),
+ #[error("<RodioSink> Cannot Get Audio Devices: {0}")]
+ DevicesError(#[from] cpal::DevicesError),
+ #[error("<RodioSink> {0}")]
+ Samples(String),
+}
+
+impl From<RodioError> for SinkError {
+ fn from(e: RodioError) -> SinkError {
+ use RodioError::*;
+ let es = e.to_string();
+ match e {
+ StreamError(_) | PlayError(_) | Samples(_) => SinkError::OnWrite(es),
+ NoDeviceAvailable | DeviceNotAvailable(_) => SinkError::ConnectionRefused(es),
+ DevicesError(_) => SinkError::InvalidParams(es),
+ }
+ }
+}
+
+impl From<cpal::DefaultStreamConfigError> for RodioError {
+ fn from(_: cpal::DefaultStreamConfigError) -> RodioError {
+ RodioError::NoDeviceAvailable
+ }
+}
+
+impl From<cpal::SupportedStreamConfigsError> for RodioError {
+ fn from(_: cpal::SupportedStreamConfigsError) -> RodioError {
+ RodioError::NoDeviceAvailable
+ }
+}
+
+pub struct RodioSink {
+ rodio_sink: rodio::Sink,
+ _stream: rodio::OutputStream,
+}
+
+fn list_formats(device: &cpal::Device) {
+ match device.default_output_config() {
+ Ok(cfg) => {
+ debug!(" Default config:");
+ debug!(" {cfg:?}");
+ }
+ Err(e) => {
+ // Use loglevel debug, since even the output is only debug
+ debug!("Error getting default rodio::Sink config: {e}");
+ }
+ };
+
+ match device.supported_output_configs() {
+ Ok(mut cfgs) => {
+ if let Some(first) = cfgs.next() {
+ debug!(" Available configs:");
+ debug!(" {first:?}");
+ } else {
+ return;
+ }
+
+ for cfg in cfgs {
+ debug!(" {cfg:?}");
+ }
+ }
+ Err(e) => {
+ debug!("Error getting supported rodio::Sink configs: {e}");
+ }
+ }
+}
+
+fn list_outputs(host: &cpal::Host) -> Result<(), cpal::DevicesError> {
+ let mut default_device_name = None;
+
+ if let Some(default_device) = host.default_output_device() {
+ default_device_name = default_device.name().ok();
+ println!(
+ "Default Audio Device:\n {}",
+ default_device_name.as_deref().unwrap_or("[unknown name]")
+ );
+
+ list_formats(&default_device);
+
+ println!("Other Available Audio Devices:");
+ } else {
+ warn!("No default device was found");
+ }
+
+ for device in host.output_devices()? {
+ match device.name() {
+ Ok(name) if Some(&name) == default_device_name.as_ref() => (),
+ Ok(name) => {
+ println!(" {name}");
+ list_formats(&device);
+ }
+ Err(e) => {
+ warn!("Cannot get device name: {e}");
+ println!(" [unknown name]");
+ list_formats(&device);
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn create_sink(
+ host: &cpal::Host,
+ device: Option<String>,
+ format: AudioFormat,
+) -> Result<(rodio::Sink, rodio::OutputStream), RodioError> {
+ let cpal_device = match device.as_deref() {
+ Some("?") => match list_outputs(host) {
+ Ok(()) => exit(0),
+ Err(e) => {
+ error!("{e}");
+ exit(1);
+ }
+ },
+ Some(device_name) => {
+ // Ignore devices for which getting name fails, or format doesn't match
+ host.output_devices()?
+ .find(|d| d.name().ok().is_some_and(|name| name == device_name)) // Ignore devices for which getting name fails
+ .ok_or_else(|| RodioError::DeviceNotAvailable(device_name.to_string()))?
+ }
+ None => host
+ .default_output_device()
+ .ok_or(RodioError::NoDeviceAvailable)?,
+ };
+
+ let name = cpal_device.name().ok();
+ info!(
+ "Using audio device: {}",
+ name.as_deref().unwrap_or("[unknown name]")
+ );
+
+ // First try native stereo 44.1 kHz playback, then fall back to the device default sample rate
+ // (some devices only support 48 kHz and Rodio will resample linearly), then fall back to
+ // whatever the default device config is (like mono).
+ let default_config = cpal_device.default_output_config()?;
+ let config = cpal_device
+ .supported_output_configs()?
+ .find(|c| c.channels() == NUM_CHANNELS as cpal::ChannelCount)
+ .and_then(|c| {
+ c.try_with_sample_rate(cpal::SampleRate(SAMPLE_RATE))
+ .or_else(|| c.try_with_sample_rate(default_config.sample_rate()))
+ })
+ .unwrap_or(default_config);
+
+ let sample_format = match format {
+ AudioFormat::F64 => cpal::SampleFormat::F64,
+ AudioFormat::F32 => cpal::SampleFormat::F32,
+ AudioFormat::S32 => cpal::SampleFormat::I32,
+ AudioFormat::S24 | AudioFormat::S24_3 => cpal::SampleFormat::I24,
+ AudioFormat::S16 => cpal::SampleFormat::I16,
+ };
+
+ let mut stream = match rodio::OutputStreamBuilder::default()
+ .with_device(cpal_device.clone())
+ .with_config(&config.config())
+ .with_sample_format(sample_format)
+ .open_stream()
+ {
+ Ok(exact_stream) => exact_stream,
+ Err(e) => {
+ warn!("unable to create Rodio output, falling back to default: {e}");
+ rodio::OutputStreamBuilder::from_device(cpal_device)?.open_stream_or_fallback()?
+ }
+ };
+
+ // disable logging on stream drop
+ stream.log_on_drop(false);
+
+ let sink = rodio::Sink::connect_new(stream.mixer());
+ Ok((sink, stream))
+}
+
+pub fn open(host: cpal::Host, device: Option<String>, format: AudioFormat) -> RodioSink {
+ info!(
+ "Using Rodio sink with format {format:?} and cpal host: {}",
+ host.id().name()
+ );
+
+ let (sink, stream) = create_sink(&host, device, format).unwrap();
+
+ debug!("Rodio sink was created");
+ RodioSink {
+ rodio_sink: sink,
+ _stream: stream,
+ }
+}
+
+impl Sink for RodioSink {
+ fn start(&mut self) -> SinkResult<()> {
+ self.rodio_sink.play();
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ self.rodio_sink.sleep_until_end();
+ self.rodio_sink.pause();
+ Ok(())
+ }
+
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
+ let samples = packet
+ .samples()
+ .map_err(|e| RodioError::Samples(e.to_string()))?;
+ let samples_f32: &[f32] = &converter.f64_to_f32(samples);
+ let source = rodio::buffer::SamplesBuffer::new(
+ NUM_CHANNELS as cpal::ChannelCount,
+ SAMPLE_RATE,
+ samples_f32,
+ );
+ self.rodio_sink.append(source);
+
+ // Chunk sizes seem to be about 256 to 3000 ish items long.
+ // Assuming they're on average 1628 then a half second buffer is:
+ // 44100 elements --> about 27 chunks
+ while self.rodio_sink.len() > 26 {
+ // sleep and wait for rodio to drain a bit
+ thread::sleep(Duration::from_millis(10));
+ }
+ Ok(())
+ }
+}
+
+impl RodioSink {
+ #[allow(dead_code)]
+ pub const NAME: &'static str = "rodio";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/sdl.rs b/native/vendor/librespot-playback/src/audio_backend/sdl.rs
new file mode 100644
index 0000000..0d22092
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/sdl.rs
@@ -0,0 +1,121 @@
+use super::{Open, Sink, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use crate::{NUM_CHANNELS, SAMPLE_RATE};
+use sdl2::audio::{AudioQueue, AudioSpecDesired};
+use std::thread;
+use std::time::Duration;
+
+pub enum SdlSink {
+ F32(AudioQueue<f32>),
+ S32(AudioQueue<i32>),
+ S16(AudioQueue<i16>),
+}
+
+impl Open for SdlSink {
+ fn open(device: Option<String>, format: AudioFormat) -> Self {
+ info!("Using SDL sink with format: {:?}", format);
+
+ if device.is_some() {
+ warn!("SDL sink does not support specifying a device name");
+ }
+
+ let ctx = sdl2::init().expect("could not initialize SDL");
+ let audio = ctx
+ .audio()
+ .expect("could not initialize SDL audio subsystem");
+
+ let desired_spec = AudioSpecDesired {
+ freq: Some(SAMPLE_RATE as i32),
+ channels: Some(NUM_CHANNELS),
+ samples: None,
+ };
+
+ macro_rules! open_sink {
+ ($sink: expr, $type: ty) => {{
+ let queue: AudioQueue<$type> = audio
+ .open_queue(None, &desired_spec)
+ .expect("could not open SDL audio device");
+ $sink(queue)
+ }};
+ }
+ match format {
+ AudioFormat::F32 => open_sink!(Self::F32, f32),
+ AudioFormat::S32 => open_sink!(Self::S32, i32),
+ AudioFormat::S16 => open_sink!(Self::S16, i16),
+ _ => {
+ unimplemented!("SDL currently does not support {format:?} output")
+ }
+ }
+ }
+}
+
+impl Sink for SdlSink {
+ fn start(&mut self) -> SinkResult<()> {
+ macro_rules! start_sink {
+ ($queue: expr) => {{
+ $queue.clear();
+ $queue.resume();
+ }};
+ }
+ match self {
+ Self::F32(queue) => start_sink!(queue),
+ Self::S32(queue) => start_sink!(queue),
+ Self::S16(queue) => start_sink!(queue),
+ };
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ macro_rules! stop_sink {
+ ($queue: expr) => {{
+ $queue.pause();
+ $queue.clear();
+ }};
+ }
+ match self {
+ Self::F32(queue) => stop_sink!(queue),
+ Self::S32(queue) => stop_sink!(queue),
+ Self::S16(queue) => stop_sink!(queue),
+ };
+ Ok(())
+ }
+
+ fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()> {
+ macro_rules! drain_sink {
+ ($queue: expr, $size: expr) => {{
+ // sleep and wait for sdl thread to drain the queue a bit
+ while $queue.size() > (NUM_CHANNELS as u32 * $size as u32 * SAMPLE_RATE) {
+ thread::sleep(Duration::from_millis(10));
+ }
+ }};
+ }
+
+ let samples = packet
+ .samples()
+ .map_err(|e| SinkError::OnWrite(e.to_string()))?;
+ let result = match self {
+ Self::F32(queue) => {
+ let samples_f32: &[f32] = &converter.f64_to_f32(samples);
+ drain_sink!(queue, AudioFormat::F32.size());
+ queue.queue_audio(samples_f32)
+ }
+ Self::S32(queue) => {
+ let samples_s32: &[i32] = &converter.f64_to_s32(samples);
+ drain_sink!(queue, AudioFormat::S32.size());
+ queue.queue_audio(samples_s32)
+ }
+ Self::S16(queue) => {
+ let samples_s16: &[i16] = &converter.f64_to_s16(samples);
+ drain_sink!(queue, AudioFormat::S16.size());
+ queue.queue_audio(samples_s16)
+ }
+ };
+ result.map_err(SinkError::OnWrite)
+ }
+}
+
+impl SdlSink {
+ pub const NAME: &'static str = "sdl";
+}
diff --git a/native/vendor/librespot-playback/src/audio_backend/subprocess.rs b/native/vendor/librespot-playback/src/audio_backend/subprocess.rs
new file mode 100644
index 0000000..c624718
--- /dev/null
+++ b/native/vendor/librespot-playback/src/audio_backend/subprocess.rs
@@ -0,0 +1,207 @@
+use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult};
+use crate::config::AudioFormat;
+use crate::convert::Converter;
+use crate::decoder::AudioPacket;
+use shell_words::split;
+
+use std::io::{ErrorKind, Write};
+use std::process::{Child, Command, Stdio, exit};
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+enum SubprocessError {
+ #[error("<SubprocessSink> {0}")]
+ OnWrite(std::io::Error),
+
+ #[error("<SubprocessSink> Command {command} Can Not be Executed, {e}")]
+ SpawnFailure { command: String, e: std::io::Error },
+
+ #[error("<SubprocessSink> Failed to Parse Command args for {command}, {e}")]
+ InvalidArgs {
+ command: String,
+ e: shell_words::ParseError,
+ },
+
+ #[error("<SubprocessSink> Failed to Flush the Subprocess, {0}")]
+ FlushFailure(std::io::Error),
+
+ #[error("<SubprocessSink> Failed to Kill the Subprocess, {0}")]
+ KillFailure(std::io::Error),
+
+ #[error("<SubprocessSink> Failed to Wait for the Subprocess to Exit, {0}")]
+ WaitFailure(std::io::Error),
+
+ #[error("<SubprocessSink> The Subprocess is no longer able to accept Bytes")]
+ WriteZero,
+
+ #[error("<SubprocessSink> Missing Required Shell Command")]
+ MissingCommand,
+
+ #[error("<SubprocessSink> The Subprocess is None")]
+ NoChild,
+
+ #[error("<SubprocessSink> The Subprocess's stdin is None")]
+ NoStdin,
+}
+
+impl From<SubprocessError> for SinkError {
+ fn from(e: SubprocessError) -> SinkError {
+ use SubprocessError::*;
+ let es = e.to_string();
+ match e {
+ FlushFailure(_) | KillFailure(_) | WaitFailure(_) | OnWrite(_) | WriteZero => {
+ SinkError::OnWrite(es)
+ }
+ SpawnFailure { .. } => SinkError::ConnectionRefused(es),
+ MissingCommand | InvalidArgs { .. } => SinkError::InvalidParams(es),
+ NoChild | NoStdin => SinkError::NotConnected(es),
+ }
+ }
+}
+
+pub struct SubprocessSink {
+ shell_command: Option<String>,
+ child: Option<Child>,
+ format: AudioFormat,
+}
+
+impl Open for SubprocessSink {
+ fn open(shell_command: Option<String>, format: AudioFormat) -> Self {
+ if let Some("?") = shell_command.as_deref() {
+ println!(
+ "\nUsage:\n\nOutput to a Subprocess:\n\n\t--backend subprocess --device {{shell_command}}\n"
+ );
+ exit(0);
+ }
+
+ info!("Using SubprocessSink with format: {format:?}");
+
+ Self {
+ shell_command,
+ child: None,
+ format,
+ }
+ }
+}
+
+impl Sink for SubprocessSink {
+ fn start(&mut self) -> SinkResult<()> {
+ self.child.get_or_insert({
+ match self.shell_command.as_deref() {
+ Some(command) => {
+ let args = split(command).map_err(|e| SubprocessError::InvalidArgs {
+ command: command.to_string(),
+ e,
+ })?;
+
+ Command::new(&args[0])
+ .args(&args[1..])
+ .stdin(Stdio::piped())
+ .spawn()
+ .map_err(|e| SubprocessError::SpawnFailure {
+ command: command.to_string(),
+ e,
+ })?
+ }
+ None => return Err(SubprocessError::MissingCommand.into()),
+ }
+ });
+
+ Ok(())
+ }
+
+ fn stop(&mut self) -> SinkResult<()> {
+ let child = &mut self.child.take().ok_or(SubprocessError::NoChild)?;
+
+ match child.try_wait() {
+ // The process has already exited
+ // nothing to do.
+ Ok(Some(_)) => Ok(()),
+ Ok(_) => {
+ // The process Must DIE!!!
+ child
+ .stdin
+ .take()
+ .ok_or(SubprocessError::NoStdin)?
+ .flush()
+ .map_err(SubprocessError::FlushFailure)?;
+
+ child.kill().map_err(SubprocessError::KillFailure)?;
+ child.wait().map_err(SubprocessError::WaitFailure)?;
+
+ Ok(())
+ }
+ Err(e) => Err(SubprocessError::WaitFailure(e).into()),
+ }
+ }
+
+ sink_as_bytes!();
+}
+
+impl SinkAsBytes for SubprocessSink {
+ #[inline]
+ fn write_bytes(&mut self, data: &[u8]) -> SinkResult<()> {
+ // We get one attempted restart per write.
+ // We don't want to get stuck in a restart loop.
+ let mut restarted = false;
+ let mut start_index = 0;
+ let data_len = data.len();
+ let mut end_index = data_len;
+
+ loop {
+ match self
+ .child
+ .as_ref()
+ .ok_or(SubprocessError::NoChild)?
+ .stdin
+ .as_ref()
+ .ok_or(SubprocessError::NoStdin)?
+ .write(&data[start_index..end_index])
+ {
+ Ok(0) => {
+ // Potentially fatal.
+ // As per the docs a return value of 0
+ // means we shouldn't try to write to the
+ // process anymore so let's try a restart
+ // if we haven't already.
+ self.try_restart(SubprocessError::WriteZero, &mut restarted)?;
+
+ continue;
+ }
+ Ok(bytes_written) => {
+ // What we want, a successful write.
+ start_index = data_len.min(start_index + bytes_written);
+ end_index = data_len.min(start_index + bytes_written);
+
+ if end_index == data_len {
+ break Ok(());
+ }
+ }
+ // Non-fatal, retry the write.
+ Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
+ Err(e) => {
+ // Very possibly fatal,
+ // but let's try a restart anyway if we haven't already.
+ self.try_restart(SubprocessError::OnWrite(e), &mut restarted)?;
+
+ continue;
+ }
+ }
+ }
+ }
+}
+
+impl SubprocessSink {
+ pub const NAME: &'static str = "subprocess";
+
+ fn try_restart(&mut self, e: SubprocessError, restarted: &mut bool) -> SinkResult<()> {
+ // If the restart fails throw the original error back.
+ if !*restarted && self.stop().is_ok() && self.start().is_ok() {
+ *restarted = true;
+
+ Ok(())
+ } else {
+ Err(e.into())
+ }
+ }
+}
diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rs
new file mode 100644
index 0000000..057442a
--- /dev/null
+++ b/native/vendor/librespot-playback/src/config.rs
@@ -0,0 +1,195 @@
+use std::{mem, path::PathBuf, str::FromStr, time::Duration};
+
+pub use crate::dither::{DithererBuilder, TriangularDitherer, mk_ditherer};
+use crate::{convert::i24, player::duration_to_coefficient};
+
+#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Default)]
+pub enum Bitrate {
+ Bitrate96,
+ #[default]
+ Bitrate160,
+ Bitrate320,
+}
+
+impl FromStr for Bitrate {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "96" => Ok(Self::Bitrate96),
+ "160" => Ok(Self::Bitrate160),
+ "320" => Ok(Self::Bitrate320),
+ _ => Err(()),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Default)]
+pub enum AudioFormat {
+ F64,
+ F32,
+ S32,
+ S24,
+ S24_3,
+ #[default]
+ S16,
+}
+
+impl FromStr for AudioFormat {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_uppercase().as_ref() {
+ "F64" => Ok(Self::F64),
+ "F32" => Ok(Self::F32),
+ "S32" => Ok(Self::S32),
+ "S24" => Ok(Self::S24),
+ "S24_3" => Ok(Self::S24_3),
+ "S16" => Ok(Self::S16),
+ _ => Err(()),
+ }
+ }
+}
+
+impl AudioFormat {
+ // not used by all backends
+ #[allow(dead_code)]
+ pub fn size(&self) -> usize {
+ match self {
+ Self::F64 => mem::size_of::<f64>(),
+ Self::F32 => mem::size_of::<f32>(),
+ Self::S24_3 => mem::size_of::<i24>(),
+ Self::S16 => mem::size_of::<i16>(),
+ _ => mem::size_of::<i32>(), // S32 and S24 are both stored in i32
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum NormalisationType {
+ Album,
+ Track,
+ #[default]
+ Auto,
+}
+
+impl FromStr for NormalisationType {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_lowercase().as_ref() {
+ "album" => Ok(Self::Album),
+ "track" => Ok(Self::Track),
+ "auto" => Ok(Self::Auto),
+ _ => Err(()),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum NormalisationMethod {
+ Basic,
+ #[default]
+ Dynamic,
+}
+
+impl FromStr for NormalisationMethod {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_lowercase().as_ref() {
+ "basic" => Ok(Self::Basic),
+ "dynamic" => Ok(Self::Dynamic),
+ _ => Err(()),
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct PlayerConfig {
+ pub bitrate: Bitrate,
+ pub gapless: bool,
+ pub passthrough: bool,
+
+ pub normalisation: bool,
+ pub normalisation_type: NormalisationType,
+ pub normalisation_method: NormalisationMethod,
+ pub normalisation_pregain_db: f64,
+ pub normalisation_threshold_dbfs: f64,
+ pub normalisation_attack_cf: f64,
+ pub normalisation_release_cf: f64,
+ pub normalisation_knee_db: f64,
+
+ pub local_file_directories: Vec<PathBuf>,
+
+ // pass function pointers so they can be lazily instantiated *after* spawning a thread
+ // (thereby circumventing Send bounds that they might not satisfy)
+ pub ditherer: Option<DithererBuilder>,
+ /// Setting this will enable periodically sending events during playback informing about the playback position
+ /// To consume the PlayerEvent::PositionChanged event, listen to events via `Player::get_player_event_channel()``
+ pub position_update_interval: Option<Duration>,
+
+ /// LOCAL PATCH: how long one track dissolves into the next, in milliseconds.
+ ///
+ /// Zero, the default, is upstream behaviour: tracks follow one another with
+ /// nothing between them. See `player.rs`.
+ pub crossfade_duration_ms: u32,
+}
+
+impl Default for PlayerConfig {
+ fn default() -> Self {
+ Self {
+ bitrate: Bitrate::default(),
+ gapless: true,
+ normalisation: false,
+ normalisation_type: NormalisationType::default(),
+ normalisation_method: NormalisationMethod::default(),
+ normalisation_pregain_db: 0.0,
+ normalisation_threshold_dbfs: -2.0,
+ normalisation_attack_cf: duration_to_coefficient(Duration::from_millis(5)),
+ normalisation_release_cf: duration_to_coefficient(Duration::from_millis(100)),
+ normalisation_knee_db: 5.0,
+ passthrough: false,
+ ditherer: Some(mk_ditherer::<TriangularDitherer>),
+ position_update_interval: None,
+ local_file_directories: Vec::new(),
+ crossfade_duration_ms: 0,
+ }
+ }
+}
+
+// fields are intended for volume control range in dB
+#[derive(Clone, Copy, Debug)]
+pub enum VolumeCtrl {
+ Cubic(f64),
+ Fixed,
+ Linear,
+ Log(f64),
+}
+
+impl FromStr for VolumeCtrl {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Self::from_str_with_range(s, Self::DEFAULT_DB_RANGE)
+ }
+}
+
+impl Default for VolumeCtrl {
+ fn default() -> VolumeCtrl {
+ VolumeCtrl::Log(Self::DEFAULT_DB_RANGE)
+ }
+}
+
+impl VolumeCtrl {
+ pub const MAX_VOLUME: u16 = u16::MAX;
+
+ // Taken from: https://www.dr-lex.be/info-stuff/volumecontrols.html
+ pub const DEFAULT_DB_RANGE: f64 = 60.0;
+
+ pub fn from_str_with_range(s: &str, db_range: f64) -> Result<Self, <Self as FromStr>::Err> {
+ use self::VolumeCtrl::*;
+ match s.to_lowercase().as_ref() {
+ "cubic" => Ok(Cubic(db_range)),
+ "fixed" => Ok(Fixed),
+ "linear" => Ok(Linear),
+ "log" => Ok(Log(db_range)),
+ _ => Err(()),
+ }
+ }
+}
diff --git a/native/vendor/librespot-playback/src/convert.rs b/native/vendor/librespot-playback/src/convert.rs
new file mode 100644
index 0000000..31e710d
--- /dev/null
+++ b/native/vendor/librespot-playback/src/convert.rs
@@ -0,0 +1,133 @@
+use crate::dither::{Ditherer, DithererBuilder};
+use zerocopy::{Immutable, IntoBytes};
+
+#[derive(Immutable, IntoBytes, Copy, Clone, Debug)]
+#[allow(non_camel_case_types)]
+#[repr(transparent)]
+pub struct i24([u8; 3]);
+impl i24 {
+ fn from_s24(sample: i32) -> Self {
+ // trim the padding in the most significant byte
+ #[allow(unused_variables)]
+ let [a, b, c, d] = sample.to_ne_bytes();
+ #[cfg(target_endian = "little")]
+ return Self([a, b, c]);
+ #[cfg(target_endian = "big")]
+ return Self([b, c, d]);
+ }
+}
+
+pub struct Converter {
+ ditherer: Option<Box<dyn Ditherer>>,
+}
+
+impl Converter {
+ pub fn new(dither_config: Option<DithererBuilder>) -> Self {
+ match dither_config {
+ Some(ditherer_builder) => {
+ let ditherer = (ditherer_builder)();
+ info!("Converting with ditherer: {}", ditherer.name());
+ Self {
+ ditherer: Some(ditherer),
+ }
+ }
+ None => Self { ditherer: None },
+ }
+ }
+
+ /// Base bit positions for PCM format scaling. These represent the position
+ /// of the most significant bit in each format's full-scale representation.
+ /// For signed integers in two's complement, full scale is 2^(bits-1).
+ const SHIFT_S16: u8 = 15; // 16-bit: 2^15 = 32768
+ const SHIFT_S24: u8 = 23; // 24-bit: 2^23 = 8388608
+ const SHIFT_S32: u8 = 31; // 32-bit: 2^31 = 2147483648
+
+ /// Additional bit shifts needed to scale from 16-bit to higher bit depths.
+ /// These are the differences between the base shift amounts above.
+ const SHIFT_16_TO_24: u8 = Self::SHIFT_S24 - Self::SHIFT_S16; // 23 - 15 = 8
+ const SHIFT_16_TO_32: u8 = Self::SHIFT_S32 - Self::SHIFT_S16; // 31 - 15 = 16
+
+ /// Pre-calculated scale factor for 24-bit clamping bounds
+ const SCALE_S24: f64 = (1_u64 << Self::SHIFT_S24) as f64;
+
+ /// Scale audio samples with optimal dithering strategy for Spotify's 16-bit source material.
+ ///
+ /// Since Spotify audio is always 16-bit depth, this function:
+ /// 1. When dithering: applies noise at 16-bit level, preserves fractional precision,
+ /// then scales to target format and rounds once at the end
+ /// 2. When not dithering: scales directly from normalized float to target format
+ ///
+ /// The `shift` parameter specifies how many extra bits to shift beyond
+ /// the base 16-bit scaling (0 for 16-bit, 8 for 24-bit, 16 for 32-bit).
+ #[inline]
+ pub fn scale(&mut self, sample: f64, shift: u8) -> f64 {
+ match self.ditherer.as_mut() {
+ Some(d) => {
+ // With dithering: Apply noise at 16-bit level to address original quantization,
+ // then scale up to target format while preserving sub-LSB information
+ let dithered_16bit = sample * (1_u64 << Self::SHIFT_S16) as f64 + d.noise();
+ let scaled = dithered_16bit * (1_u64 << shift) as f64;
+ scaled.round()
+ }
+ None => {
+ // No dithering: Scale directly from normalized float to target format
+ // using a single bit shift operation (base 16-bit shift + additional shift)
+ let total_shift = Self::SHIFT_S16 + shift;
+ (sample * (1_u64 << total_shift) as f64).round()
+ }
+ }
+ }
+
+ /// Clamping scale specifically for 24-bit output to prevent MSB overflow.
+ /// Only used for S24 formats where samples are packed in 32-bit words.
+ /// Ensures the most significant byte is zero to prevent overflow during dithering.
+ #[inline]
+ pub fn clamping_scale_s24(&mut self, sample: f64) -> f64 {
+ let int_value = self.scale(sample, Self::SHIFT_16_TO_24);
+
+ // In two's complement, there are more negative than positive values.
+ let min = -Self::SCALE_S24;
+ let max = Self::SCALE_S24 - 1.0;
+
+ int_value.clamp(min, max)
+ }
+
+ #[inline]
+ pub fn f64_to_f32(&mut self, samples: &[f64]) -> Vec<f32> {
+ samples.iter().map(|sample| *sample as f32).collect()
+ }
+
+ #[inline]
+ pub fn f64_to_s32(&mut self, samples: &[f64]) -> Vec<i32> {
+ samples
+ .iter()
+ .map(|sample| self.scale(*sample, Self::SHIFT_16_TO_32) as i32)
+ .collect()
+ }
+
+ /// S24 is 24-bit PCM packed in an upper 32-bit word
+ #[inline]
+ pub fn f64_to_s24(&mut self, samples: &[f64]) -> Vec<i32> {
+ samples
+ .iter()
+ .map(|sample| self.clamping_scale_s24(*sample) as i32)
+ .collect()
+ }
+
+ /// S24_3 is 24-bit PCM in a 3-byte array
+ #[inline]
+ pub fn f64_to_s24_3(&mut self, samples: &[f64]) -> Vec<i24> {
+ samples
+ .iter()
+ .map(|sample| i24::from_s24(self.clamping_scale_s24(*sample) as i32))
+ .collect()
+ }
+
+ #[inline]
+ pub fn f64_to_s16(&mut self, samples: &[f64]) -> Vec<i16> {
+ samples
+ .iter()
+ .map(|sample| self.scale(*sample, 0) as i16)
+ .collect()
+ }
+}
diff --git a/native/vendor/librespot-playback/src/decoder/mod.rs b/native/vendor/librespot-playback/src/decoder/mod.rs
new file mode 100644
index 0000000..e77d6e9
--- /dev/null
+++ b/native/vendor/librespot-playback/src/decoder/mod.rs
@@ -0,0 +1,92 @@
+use std::ops::Deref;
+
+use thiserror::Error;
+
+#[cfg(feature = "passthrough-decoder")]
+mod passthrough_decoder;
+#[cfg(feature = "passthrough-decoder")]
+pub use passthrough_decoder::PassthroughDecoder;
+
+mod symphonia_decoder;
+pub use symphonia_decoder::SymphoniaDecoder;
+
+#[derive(Error, Debug)]
+pub enum DecoderError {
+ #[error("Passthrough Decoder Error: {0}")]
+ PassthroughDecoder(String),
+ #[error("Symphonia Decoder Error: {0}")]
+ SymphoniaDecoder(String),
+}
+
+pub type DecoderResult<T> = Result<T, DecoderError>;
+
+#[derive(Error, Debug)]
+pub enum AudioPacketError {
+ #[error("Decoder Raw Error: Can't return Raw on Samples")]
+ Raw,
+ #[error("Decoder Samples Error: Can't return Samples on Raw")]
+ Samples,
+}
+
+pub type AudioPacketResult<T> = Result<T, AudioPacketError>;
+
+pub enum AudioPacket {
+ Samples(Vec<f64>),
+ Raw(Vec<u8>),
+}
+
+impl AudioPacket {
+ #[inline]
+ pub fn samples(&self) -> AudioPacketResult<&[f64]> {
+ match self {
+ AudioPacket::Samples(s) => Ok(s),
+ AudioPacket::Raw(_) => Err(AudioPacketError::Raw),
+ }
+ }
+
+ #[inline]
+ pub fn raw(&self) -> AudioPacketResult<&[u8]> {
+ match self {
+ AudioPacket::Raw(d) => Ok(d),
+ AudioPacket::Samples(_) => Err(AudioPacketError::Samples),
+ }
+ }
+
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ match self {
+ AudioPacket::Samples(s) => s.is_empty(),
+ AudioPacket::Raw(d) => d.is_empty(),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct AudioPacketPosition {
+ pub position_ms: u32,
+ pub skipped: bool,
+}
+
+impl Deref for AudioPacketPosition {
+ type Target = u32;
+ fn deref(&self) -> &Self::Target {
+ &self.position_ms
+ }
+}
+
+pub trait AudioDecoder {
+ fn seek(&mut self, position_ms: u32) -> Result<u32, DecoderError>;
+ fn next_packet(&mut self) -> DecoderResult<Option<(AudioPacketPosition, AudioPacket)>>;
+}
+
+impl From<DecoderError> for librespot_core::error::Error {
+ fn from(err: DecoderError) -> Self {
+ librespot_core::error::Error::aborted(err)
+ }
+}
+
+impl From<symphonia::core::errors::Error> for DecoderError {
+ fn from(err: symphonia::core::errors::Error) -> Self {
+ Self::SymphoniaDecoder(err.to_string())
+ }
+}
diff --git a/native/vendor/librespot-playback/src/decoder/passthrough_decoder.rs b/native/vendor/librespot-playback/src/decoder/passthrough_decoder.rs
new file mode 100644
index 0000000..ec05f71
--- /dev/null
+++ b/native/vendor/librespot-playback/src/decoder/passthrough_decoder.rs
@@ -0,0 +1,221 @@
+// Passthrough decoder for librespot
+use std::{
+ io::{Read, Seek},
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+// TODO: move this to the Symphonia Ogg demuxer
+use ogg::{OggReadError, Packet, PacketReader, PacketWriteEndInfo, PacketWriter};
+
+use super::{AudioDecoder, AudioPacket, AudioPacketPosition, DecoderError, DecoderResult};
+
+use crate::{
+ MS_PER_PAGE, PAGES_PER_MS,
+ metadata::audio::{AudioFileFormat, AudioFiles},
+};
+
+fn get_header<T>(code: u8, rdr: &mut PacketReader<T>) -> DecoderResult<Vec<u8>>
+where
+ T: Read + Seek,
+{
+ let pck: Packet = rdr
+ .read_packet_expected()
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+
+ let pkt_type = pck.data[0];
+ debug!("Vorbis header type {}", &pkt_type);
+
+ if pkt_type != code {
+ return Err(DecoderError::PassthroughDecoder("Invalid Data".into()));
+ }
+
+ Ok(pck.data)
+}
+
+pub struct PassthroughDecoder<R: Read + Seek> {
+ rdr: PacketReader<R>,
+ wtr: PacketWriter<'static, Vec<u8>>,
+ eos: bool,
+ bos: bool,
+ ofsgp_page: u64,
+ stream_serial: u32,
+ ident: Vec<u8>,
+ comment: Vec<u8>,
+ setup: Vec<u8>,
+}
+
+impl<R: Read + Seek> PassthroughDecoder<R> {
+ /// Constructs a new Decoder from a given implementation of `Read + Seek`.
+ pub fn new(rdr: R, format: AudioFileFormat) -> DecoderResult<Self> {
+ if !AudioFiles::is_ogg_vorbis(format) {
+ return Err(DecoderError::PassthroughDecoder(format!(
+ "Passthrough decoder is not implemented for format {format:?}"
+ )));
+ }
+
+ let mut rdr = PacketReader::new(rdr);
+ let since_epoch = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ let stream_serial = since_epoch.as_millis() as u32;
+
+ info!("Starting passthrough track with serial {stream_serial}");
+
+ // search for ident, comment, setup
+ let ident = get_header(1, &mut rdr)?;
+ let comment = get_header(3, &mut rdr)?;
+ let setup = get_header(5, &mut rdr)?;
+
+ // remove un-needed packets
+ rdr.delete_unread_packets();
+
+ Ok(PassthroughDecoder {
+ rdr,
+ wtr: PacketWriter::new(Vec::new()),
+ ofsgp_page: 0,
+ stream_serial,
+ ident,
+ comment,
+ setup,
+ eos: false,
+ bos: false,
+ })
+ }
+
+ fn position_pcm_to_ms(position_pcm: u64) -> u32 {
+ (position_pcm as f64 * MS_PER_PAGE) as u32
+ }
+}
+
+impl<R: Read + Seek> AudioDecoder for PassthroughDecoder<R> {
+ fn seek(&mut self, position_ms: u32) -> Result<u32, DecoderError> {
+ let absgp = (position_ms as f64 * PAGES_PER_MS) as u64;
+
+ // add an eos to previous stream if missing
+ if self.bos && !self.eos {
+ match self.rdr.read_packet() {
+ Ok(Some(pck)) => {
+ let absgp_page = pck.absgp_page() - self.ofsgp_page;
+ self.wtr
+ .write_packet(
+ pck.data,
+ self.stream_serial,
+ PacketWriteEndInfo::EndStream,
+ absgp_page,
+ )
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ }
+ _ => warn! {"Cannot write EoS after seeking"},
+ };
+ }
+
+ self.eos = false;
+ self.bos = false;
+ self.ofsgp_page = 0;
+ self.stream_serial += 1;
+
+ match self.rdr.seek_absgp(None, absgp) {
+ Ok(_) => {
+ // need to set some offset for next_page()
+ let pck = self
+ .rdr
+ .read_packet()
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ match pck {
+ Some(pck) => {
+ let new_page = pck.absgp_page();
+ self.ofsgp_page = new_page;
+ debug!("Seek to offset page {}", new_page);
+ let new_position_ms = Self::position_pcm_to_ms(new_page);
+ Ok(new_position_ms)
+ }
+ None => Err(DecoderError::PassthroughDecoder("Packet is None".into())),
+ }
+ }
+ Err(e) => Err(DecoderError::PassthroughDecoder(e.to_string())),
+ }
+ }
+
+ fn next_packet(&mut self) -> DecoderResult<Option<(AudioPacketPosition, AudioPacket)>> {
+ // write headers if we are (re)starting
+ if !self.bos {
+ self.wtr
+ .write_packet(
+ self.ident.clone(),
+ self.stream_serial,
+ PacketWriteEndInfo::EndPage,
+ 0,
+ )
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ self.wtr
+ .write_packet(
+ self.comment.clone(),
+ self.stream_serial,
+ PacketWriteEndInfo::NormalPacket,
+ 0,
+ )
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ self.wtr
+ .write_packet(
+ self.setup.clone(),
+ self.stream_serial,
+ PacketWriteEndInfo::EndPage,
+ 0,
+ )
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+ self.bos = true;
+ debug!("Wrote Ogg headers");
+ }
+
+ loop {
+ let pck = match self.rdr.read_packet() {
+ Ok(Some(pck)) => pck,
+ Ok(None) | Err(OggReadError::NoCapturePatternFound) => {
+ info!("end of streaming");
+ return Ok(None);
+ }
+ Err(e) => return Err(DecoderError::PassthroughDecoder(e.to_string())),
+ };
+
+ let pckgp_page = pck.absgp_page();
+
+ // skip till we have audio and a calculable granule position
+ if pckgp_page == 0 || pckgp_page == self.ofsgp_page {
+ continue;
+ }
+
+ // set packet type
+ let inf = if pck.last_in_stream() {
+ self.eos = true;
+ PacketWriteEndInfo::EndStream
+ } else if pck.last_in_page() {
+ PacketWriteEndInfo::EndPage
+ } else {
+ PacketWriteEndInfo::NormalPacket
+ };
+
+ self.wtr
+ .write_packet(
+ pck.data,
+ self.stream_serial,
+ inf,
+ pckgp_page - self.ofsgp_page,
+ )
+ .map_err(|e| DecoderError::PassthroughDecoder(e.to_string()))?;
+
+ let data = self.wtr.inner_mut();
+
+ if !data.is_empty() {
+ let position_ms = Self::position_pcm_to_ms(pckgp_page);
+ let packet_position = AudioPacketPosition {
+ position_ms,
+ skipped: false,
+ };
+
+ let ogg_data = AudioPacket::Raw(std::mem::take(data));
+
+ return Ok(Some((packet_position, ogg_data)));
+ }
+ }
+ }
+}
diff --git a/native/vendor/librespot-playback/src/decoder/symphonia_decoder.rs b/native/vendor/librespot-playback/src/decoder/symphonia_decoder.rs
new file mode 100644
index 0000000..56561bb
--- /dev/null
+++ b/native/vendor/librespot-playback/src/decoder/symphonia_decoder.rs
@@ -0,0 +1,271 @@
+use std::{io, time::Duration};
+
+use symphonia::core::{
+ audio::SampleBuffer,
+ codecs::{Decoder, DecoderOptions},
+ errors::Error,
+ formats::{FormatOptions, SeekMode, SeekTo},
+ io::{MediaSource, MediaSourceStream, MediaSourceStreamOptions},
+ meta::{MetadataOptions, StandardTagKey, Value},
+ probe::{Hint, ProbeResult},
+};
+
+use super::{AudioDecoder, AudioPacket, AudioPacketPosition, DecoderError, DecoderResult};
+
+use crate::{NUM_CHANNELS, PAGES_PER_MS, SAMPLE_RATE, player::NormalisationData, symphonia_util};
+
+pub struct SymphoniaDecoder {
+ probe_result: ProbeResult,
+ decoder: Box<dyn Decoder>,
+ sample_buffer: Option<SampleBuffer<f64>>,
+}
+
+#[derive(Default)]
+pub(crate) struct LocalFileMetadata {
+ pub name: Option<String>,
+ pub language: Option<String>,
+ pub album: Option<String>,
+ pub artists: Option<String>,
+ pub album_artists: Option<String>,
+ pub number: Option<u32>,
+ pub disc_number: Option<u32>,
+}
+
+impl SymphoniaDecoder {
+ pub fn new<R>(input: R, hint: Hint) -> DecoderResult<Self>
+ where
+ R: MediaSource + 'static,
+ {
+ let mss_opts = MediaSourceStreamOptions {
+ buffer_len: librespot_audio::AudioFetchParams::get().minimum_download_size,
+ };
+ let mss = MediaSourceStream::new(Box::new(input), mss_opts);
+
+ let format_opts = FormatOptions {
+ enable_gapless: true,
+ ..Default::default()
+ };
+ let metadata_opts: MetadataOptions = Default::default();
+
+ let probe_result =
+ symphonia::default::get_probe().format(&hint, mss, &format_opts, &metadata_opts)?;
+
+ let format = &probe_result.format;
+
+ let track = format.default_track().ok_or_else(|| {
+ DecoderError::SymphoniaDecoder("Could not retrieve default track".into())
+ })?;
+
+ let decoder_opts: DecoderOptions = Default::default();
+
+ let decoder = symphonia::default::get_codecs().make(&track.codec_params, &decoder_opts)?;
+
+ let rate = decoder.codec_params().sample_rate.ok_or_else(|| {
+ DecoderError::SymphoniaDecoder("Could not retrieve sample rate".into())
+ })?;
+
+ // TODO: The official client supports local files with sample rates other than 44,100 kHz.
+ // To play these accurately, we need to either resample the input audio, or introduce a way
+ // to change the player's current sample rate (likely by closing and re-opening the sink
+ // with new parameters).
+ if rate != SAMPLE_RATE {
+ return Err(DecoderError::SymphoniaDecoder(format!(
+ "Unsupported sample rate: {rate}"
+ )));
+ }
+
+ let channels = decoder.codec_params().channels.ok_or_else(|| {
+ DecoderError::SymphoniaDecoder("Could not retrieve channel configuration".into())
+ })?;
+ if channels.count() != NUM_CHANNELS as usize {
+ return Err(DecoderError::SymphoniaDecoder(format!(
+ "Unsupported number of channels: {channels}"
+ )));
+ }
+
+ Ok(Self {
+ probe_result,
+ decoder,
+ // We set the sample buffer when decoding the first full packet,
+ // whose duration is also the ideal sample buffer size.
+ sample_buffer: None,
+ })
+ }
+
+ pub fn normalisation_data(&mut self) -> Option<NormalisationData> {
+ let metadata = symphonia_util::get_latest_metadata(&mut self.probe_result)?;
+ let tags = metadata.current()?.tags();
+
+ if tags.is_empty() {
+ None
+ } else {
+ let mut data = NormalisationData::default();
+
+ for tag in tags {
+ if let Value::Float(value) = tag.value {
+ match tag.std_key {
+ Some(StandardTagKey::ReplayGainAlbumGain) => data.album_gain_db = value,
+ Some(StandardTagKey::ReplayGainAlbumPeak) => data.album_peak = value,
+ Some(StandardTagKey::ReplayGainTrackGain) => data.track_gain_db = value,
+ Some(StandardTagKey::ReplayGainTrackPeak) => data.track_peak = value,
+ _ => (),
+ }
+ }
+ }
+
+ Some(data)
+ }
+ }
+
+ pub(crate) fn local_file_metadata(&mut self) -> Option<LocalFileMetadata> {
+ let metadata = symphonia_util::get_latest_metadata(&mut self.probe_result)?;
+ let tags = metadata.current()?.tags();
+ let mut metadata = LocalFileMetadata::default();
+
+ for tag in tags {
+ if let Value::String(value) = &tag.value {
+ match tag.std_key {
+ // We could possibly use mem::take here to avoid cloning, but that risks leaving
+ // the audio item metadata in a bad state.
+ Some(StandardTagKey::TrackTitle) => metadata.name = Some(value.clone()),
+ Some(StandardTagKey::Language) => metadata.language = Some(value.clone()),
+ Some(StandardTagKey::Artist) => metadata.artists = Some(value.clone()),
+ Some(StandardTagKey::AlbumArtist) => {
+ metadata.album_artists = Some(value.clone())
+ }
+ Some(StandardTagKey::Album) => metadata.album = Some(value.clone()),
+ Some(StandardTagKey::TrackNumber) => {
+ metadata.number = match value.parse::<u32>() {
+ Ok(value) => Some(value),
+ Err(e) => {
+ warn!(
+ "Failed to parse local file's track number tag '{value}': {e}"
+ );
+ None
+ }
+ }
+ }
+ Some(StandardTagKey::DiscNumber) => {
+ metadata.disc_number = match value.parse::<u32>() {
+ Ok(value) => Some(value),
+ Err(e) => {
+ warn!(
+ "Failed to parse local file's disc number tag '{value}': {e}"
+ );
+ None
+ }
+ }
+ }
+ _ => (),
+ }
+ } else if let Value::UnsignedInt(value) = &tag.value {
+ match tag.std_key {
+ Some(StandardTagKey::TrackNumber) => metadata.number = Some(*value as u32),
+ Some(StandardTagKey::DiscNumber) => metadata.disc_number = Some(*value as u32),
+ _ => (),
+ }
+ } else if let Value::SignedInt(value) = &tag.value {
+ match tag.std_key {
+ Some(StandardTagKey::TrackNumber) => metadata.number = Some(*value as u32),
+ Some(StandardTagKey::DiscNumber) => metadata.disc_number = Some(*value as u32),
+ _ => (),
+ }
+ }
+ }
+
+ Some(metadata)
+ }
+
+ #[inline]
+ fn ts_to_ms(&self, ts: u64) -> u32 {
+ match self.decoder.codec_params().time_base {
+ Some(time_base) => {
+ let time = Duration::from(time_base.calc_time(ts));
+ time.as_millis() as u32
+ }
+ // Fallback in the unexpected case that the format has no base time set.
+ None => (ts as f64 * PAGES_PER_MS) as u32,
+ }
+ }
+}
+
+impl AudioDecoder for SymphoniaDecoder {
+ fn seek(&mut self, position_ms: u32) -> Result<u32, DecoderError> {
+ // "Saturate" the position_ms to the duration of the track if it exceeds it.
+ let mut target = Duration::from_millis(position_ms.into());
+ let codec_params = self.decoder.codec_params();
+ if let (Some(time_base), Some(n_frames)) = (codec_params.time_base, codec_params.n_frames) {
+ let duration = Duration::from(time_base.calc_time(n_frames));
+ if target > duration {
+ target = duration;
+ }
+ }
+
+ // `track_id: None` implies the default track ID (of the container, not of Spotify).
+ let seeked_to_ts = self.probe_result.format.seek(
+ SeekMode::Accurate,
+ SeekTo::Time {
+ time: target.into(),
+ track_id: None,
+ },
+ )?;
+
+ // Seeking is a `FormatReader` operation, so the decoder cannot reliably
+ // know when a seek took place. Reset it to avoid audio glitches.
+ self.decoder.reset();
+
+ Ok(self.ts_to_ms(seeked_to_ts.actual_ts))
+ }
+
+ fn next_packet(&mut self) -> DecoderResult<Option<(AudioPacketPosition, AudioPacket)>> {
+ let mut skipped = false;
+
+ loop {
+ let packet = match self.probe_result.format.next_packet() {
+ Ok(packet) => packet,
+ Err(Error::IoError(err)) => {
+ if err.kind() == io::ErrorKind::UnexpectedEof {
+ return Ok(None);
+ } else {
+ return Err(DecoderError::SymphoniaDecoder(err.to_string()));
+ }
+ }
+ Err(err) => {
+ return Err(err.into());
+ }
+ };
+
+ let position_ms = self.ts_to_ms(packet.ts());
+ let packet_position = AudioPacketPosition {
+ position_ms,
+ skipped,
+ };
+
+ match self.decoder.decode(&packet) {
+ Ok(decoded) => {
+ let sample_buffer = match self.sample_buffer.as_mut() {
+ Some(buffer) => buffer,
+ None => {
+ let spec = *decoded.spec();
+ let duration = decoded.capacity() as u64;
+ self.sample_buffer.insert(SampleBuffer::new(duration, spec))
+ }
+ };
+
+ sample_buffer.copy_interleaved_ref(decoded);
+ let samples = AudioPacket::Samples(sample_buffer.samples().to_vec());
+
+ return Ok(Some((packet_position, samples)));
+ }
+ Err(Error::DecodeError(_)) => {
+ // The packet failed to decode due to corrupted or invalid data, get a new
+ // packet and try again.
+ warn!("Skipping malformed audio packet at {position_ms} ms");
+ skipped = true;
+ continue;
+ }
+ Err(err) => return Err(err.into()),
+ }
+ }
+ }
+}
diff --git a/native/vendor/librespot-playback/src/dither.rs b/native/vendor/librespot-playback/src/dither.rs
new file mode 100644
index 0000000..d082558
--- /dev/null
+++ b/native/vendor/librespot-playback/src/dither.rs
@@ -0,0 +1,162 @@
+use rand::SeedableRng;
+use rand::rngs::SmallRng;
+use rand_distr::{Distribution, Normal, Triangular, Uniform};
+use std::fmt;
+
+use crate::NUM_CHANNELS;
+
+// Dithering lowers digital-to-analog conversion ("requantization") error,
+// linearizing output, lowering distortion and replacing it with a constant,
+// fixed noise level, which is more pleasant to the ear than the distortion.
+//
+// Guidance:
+//
+// * On S24, S24_3 and S24, the default is to use triangular dithering.
+// Depending on personal preference you may use Gaussian dithering instead;
+// it's not as good objectively, but it may be preferred subjectively if
+// you are looking for a more "analog" sound akin to tape hiss.
+//
+// * Advanced users who know that they have a DAC without noise shaping have
+// a third option: high-passed dithering, which is like triangular dithering
+// except that it moves dithering noise up in frequency where it is less
+// audible. Note: 99% of DACs are of delta-sigma design with noise shaping,
+// so unless you have a multibit / R2R DAC, or otherwise know what you are
+// doing, this is not for you.
+//
+// * Don't dither or shape noise on S32 or F32. On F32 it's not supported
+// anyway (there are no integer conversions and so no rounding errors) and
+// on S32 the noise level is so far down that it is simply inaudible even
+// after volume normalisation and control.
+//
+pub trait Ditherer {
+ fn new() -> Self
+ where
+ Self: Sized;
+ fn name(&self) -> &'static str;
+ fn noise(&mut self) -> f64;
+}
+
+impl fmt::Display for dyn Ditherer {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.name())
+ }
+}
+
+fn create_rng() -> SmallRng {
+ SmallRng::from_os_rng()
+}
+
+pub struct TriangularDitherer {
+ cached_rng: SmallRng,
+ distribution: Triangular<f64>,
+}
+
+impl Ditherer for TriangularDitherer {
+ fn new() -> Self {
+ Self {
+ cached_rng: create_rng(),
+ // 2 LSB peak-to-peak needed to linearize the response:
+ distribution: Triangular::new(-1.0, 1.0, 0.0).unwrap(),
+ }
+ }
+
+ fn name(&self) -> &'static str {
+ Self::NAME
+ }
+
+ #[inline]
+ fn noise(&mut self) -> f64 {
+ self.distribution.sample(&mut self.cached_rng)
+ }
+}
+
+impl TriangularDitherer {
+ pub const NAME: &'static str = "tpdf";
+}
+
+pub struct GaussianDitherer {
+ cached_rng: SmallRng,
+ distribution: Normal<f64>,
+}
+
+impl Ditherer for GaussianDitherer {
+ fn new() -> Self {
+ Self {
+ cached_rng: create_rng(),
+ // For Gaussian to achieve equivalent decorrelation to triangular dithering, it needs
+ // 3-4 dB higher amplitude than TPDF's optimal 0.408 LSB. If optimizing:
+ // - minimum correlation: σ ≈ 0.58
+ // - perceptual equivalence: σ ≈ 0.65
+ // - worst-case performance: σ ≈ 0.70
+ //
+ // σ = 0.6 LSB is a reasonable compromise that balances mathematical theory with
+ // empirical performance across various signal types.
+ distribution: Normal::new(0.0, 0.6).unwrap(),
+ }
+ }
+
+ fn name(&self) -> &'static str {
+ Self::NAME
+ }
+
+ #[inline]
+ fn noise(&mut self) -> f64 {
+ self.distribution.sample(&mut self.cached_rng)
+ }
+}
+
+impl GaussianDitherer {
+ pub const NAME: &'static str = "gpdf";
+}
+
+pub struct HighPassDitherer {
+ active_channel: usize,
+ previous_noises: [f64; NUM_CHANNELS as usize],
+ cached_rng: SmallRng,
+ distribution: Uniform<f64>,
+}
+
+impl Ditherer for HighPassDitherer {
+ fn new() -> Self {
+ Self {
+ active_channel: 0,
+ previous_noises: [0.0; NUM_CHANNELS as usize],
+ cached_rng: create_rng(),
+ // 1 LSB +/- 1 LSB (previous) = 2 LSB
+ distribution: Uniform::new_inclusive(-0.5, 0.5)
+ .expect("Failed to create uniform distribution"),
+ }
+ }
+
+ fn name(&self) -> &'static str {
+ Self::NAME
+ }
+
+ #[inline]
+ fn noise(&mut self) -> f64 {
+ let new_noise = self.distribution.sample(&mut self.cached_rng);
+ let high_passed_noise = new_noise - self.previous_noises[self.active_channel];
+ self.previous_noises[self.active_channel] = new_noise;
+ self.active_channel ^= 1;
+ high_passed_noise
+ }
+}
+
+impl HighPassDitherer {
+ pub const NAME: &'static str = "tpdf_hp";
+}
+
+pub fn mk_ditherer<D: Ditherer + 'static>() -> Box<dyn Ditherer> {
+ Box::new(D::new())
+}
+
+pub type DithererBuilder = fn() -> Box<dyn Ditherer>;
+
+pub fn find_ditherer(name: Option<String>) -> Option<DithererBuilder> {
+ match name.as_deref() {
+ Some(TriangularDitherer::NAME) => Some(mk_ditherer::<TriangularDitherer>),
+ Some(GaussianDitherer::NAME) => Some(mk_ditherer::<GaussianDitherer>),
+ Some(HighPassDitherer::NAME) => Some(mk_ditherer::<HighPassDitherer>),
+ _ => None,
+ }
+}
diff --git a/native/vendor/librespot-playback/src/lib.rs b/native/vendor/librespot-playback/src/lib.rs
new file mode 100644
index 0000000..a637f00
--- /dev/null
+++ b/native/vendor/librespot-playback/src/lib.rs
@@ -0,0 +1,22 @@
+#[macro_use]
+extern crate log;
+
+use librespot_audio as audio;
+use librespot_core as core;
+use librespot_metadata as metadata;
+
+pub mod audio_backend;
+pub mod config;
+pub mod convert;
+pub mod decoder;
+pub mod dither;
+mod local_file;
+pub mod mixer;
+pub mod player;
+mod symphonia_util;
+
+pub const SAMPLE_RATE: u32 = 44100;
+pub const NUM_CHANNELS: u8 = 2;
+pub const SAMPLES_PER_SECOND: u32 = SAMPLE_RATE * NUM_CHANNELS as u32;
+pub const PAGES_PER_MS: f64 = SAMPLE_RATE as f64 / 1000.0;
+pub const MS_PER_PAGE: f64 = 1000.0 / SAMPLE_RATE as f64;
diff --git a/native/vendor/librespot-playback/src/local_file.rs b/native/vendor/librespot-playback/src/local_file.rs
new file mode 100644
index 0000000..f25c658
--- /dev/null
+++ b/native/vendor/librespot-playback/src/local_file.rs
@@ -0,0 +1,167 @@
+use crate::symphonia_util;
+use librespot_core::{Error, SpotifyUri};
+use std::{
+ collections::HashMap,
+ fs,
+ fs::File,
+ io,
+ path::{Path, PathBuf},
+ time::Duration,
+};
+use symphonia::core::{
+ formats::FormatOptions,
+ io::MediaSourceStream,
+ meta::{MetadataOptions, StandardTagKey, Tag},
+ probe::{Hint, ProbeResult},
+};
+
+// "Spotify supports .mp3, .mp4, and .m4p files. It doesn’t support .mp4 files that contain video,
+// or the iTunes lossless format (M4A)."
+// https://community.spotify.com/t5/FAQs/Local-Files/ta-p/5186118
+//
+// There are some indications online that FLAC is supported, so check for this as well.
+const SUPPORTED_FILE_EXTENSIONS: &[&str; 4] = &["mp3", "mp4", "m4p", "flac"];
+
+#[derive(Default)]
+pub struct LocalFileLookup(HashMap<SpotifyUri, PathBuf>);
+
+impl LocalFileLookup {
+ pub fn get(&self, uri: &SpotifyUri) -> Option<&Path> {
+ self.0.get(uri).map(|p| p.as_path())
+ }
+}
+
+pub fn create_local_file_lookup(directories: &[PathBuf]) -> LocalFileLookup {
+ let mut lookup = LocalFileLookup(HashMap::new());
+
+ for path in directories {
+ if !path.is_dir() {
+ warn!(
+ "Ignoring local file source {}: not a directory",
+ path.display()
+ );
+ continue;
+ }
+
+ if let Err(e) = visit_dir(path, &mut lookup) {
+ warn!(
+ "Failed to load entries from local file source {}: {}",
+ path.display(),
+ e
+ );
+ }
+ }
+
+ lookup
+}
+
+fn visit_dir(dir: &Path, accumulator: &mut LocalFileLookup) -> io::Result<()> {
+ for entry in fs::read_dir(dir)? {
+ let path = entry?.path();
+ if path.is_dir() {
+ visit_dir(&path, accumulator)?;
+ } else {
+ let Some(file_extension) = path.extension().and_then(|e| e.to_str()) else {
+ continue;
+ };
+
+ let lowercase_extension = file_extension.to_lowercase();
+
+ if SUPPORTED_FILE_EXTENSIONS.contains(&lowercase_extension.as_str()) {
+ let uri = match get_uri_from_file(path.as_path(), file_extension) {
+ Ok(uri) => uri,
+ Err(e) => {
+ warn!(
+ "Failed to determine URI of local file {}: {}",
+ path.display(),
+ e
+ );
+ continue;
+ }
+ };
+
+ accumulator.0.insert(uri, path);
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn get_uri_from_file(audio_path: &Path, file_extension: &str) -> Result<SpotifyUri, Error> {
+ let src = File::open(audio_path)?;
+ let mss = MediaSourceStream::new(Box::new(src), Default::default());
+
+ let mut hint = Hint::new();
+ hint.with_extension(file_extension);
+
+ let meta_opts: MetadataOptions = Default::default();
+ let fmt_opts: FormatOptions = Default::default();
+
+ let mut probed = symphonia::default::get_probe()
+ .format(&hint, mss, &fmt_opts, &meta_opts)
+ .map_err(|_| Error::internal("Failed to probe file"))?;
+
+ let mut artist: Option<String> = None;
+ let mut album_title: Option<String> = None;
+ let mut track_title: Option<String> = None;
+
+ fn get_tags(probed: &mut ProbeResult) -> Option<Vec<Tag>> {
+ let metadata = symphonia_util::get_latest_metadata(probed)?;
+ let metadata_rev = metadata.current()?;
+ Some(metadata_rev.tags().to_vec())
+ }
+
+ for tag in get_tags(&mut probed).ok_or(Error::internal("Failed to probe audio tags"))? {
+ if let Some(std_key) = tag.std_key {
+ match std_key {
+ StandardTagKey::Album => {
+ album_title.replace(tag.value.to_string());
+ }
+ StandardTagKey::Artist => {
+ artist.replace(tag.value.to_string());
+ }
+ StandardTagKey::TrackTitle => {
+ track_title.replace(tag.value.to_string());
+ }
+ _ => {
+ continue;
+ }
+ }
+ }
+ }
+
+ let first_track = probed
+ .format
+ .default_track()
+ .ok_or(Error::internal("Failed to find an audio track"))?;
+
+ let time_base = first_track
+ .codec_params
+ .time_base
+ .ok_or(Error::internal("Failed to calculate track duration"))?;
+
+ let num_frames = first_track
+ .codec_params
+ .n_frames
+ .ok_or(Error::internal("Failed to calculate track duration"))?;
+
+ let time = time_base.calc_time(num_frames);
+
+ fn format_uri_part(input: Option<String>) -> String {
+ input
+ .map(|s| {
+ let bytes = s.into_bytes();
+ let encoded = form_urlencoded::byte_serialize(bytes.as_slice());
+ encoded.collect::<String>()
+ })
+ .unwrap_or("".to_owned())
+ }
+
+ Ok(SpotifyUri::Local {
+ artist: format_uri_part(artist),
+ album_title: format_uri_part(album_title),
+ track_title: format_uri_part(track_title),
+ duration: Duration::from_secs(time.seconds),
+ })
+}
diff --git a/native/vendor/librespot-playback/src/mixer/alsamixer.rs b/native/vendor/librespot-playback/src/mixer/alsamixer.rs
new file mode 100644
index 0000000..90daaf1
--- /dev/null
+++ b/native/vendor/librespot-playback/src/mixer/alsamixer.rs
@@ -0,0 +1,317 @@
+use crate::player::{db_to_ratio, ratio_to_db};
+
+use super::mappings::{LogMapping, MappedCtrl, VolumeMapping};
+use super::{Mixer, MixerConfig, VolumeCtrl};
+
+use alsa::Error as AlsaError;
+use alsa::ctl::{ElemId, ElemIface};
+use alsa::mixer::{MilliBel, SelemChannelId, SelemId};
+use alsa::{Ctl, Round};
+
+use librespot_core::Error;
+use std::ffi::{CString, NulError};
+use thiserror::Error;
+
+#[derive(Clone)]
+#[allow(dead_code)]
+pub struct AlsaMixer {
+ config: MixerConfig,
+ min: i64,
+ max: i64,
+ range: i64,
+ min_db: f64,
+ max_db: f64,
+ db_range: f64,
+ has_switch: bool,
+ is_softvol: bool,
+ use_linear_in_db: bool,
+}
+
+// min_db cannot be depended on to be mute. Also note that contrary to
+// its name copied verbatim from Alsa, this is in millibel scale.
+const SND_CTL_TLV_DB_GAIN_MUTE: MilliBel = MilliBel(-9999999);
+const ZERO_DB: MilliBel = MilliBel(0);
+
+#[derive(Debug, Error)]
+enum AlsaMixerError {
+ #[error("Could not open Alsa mixer. {0}")]
+ CouldNotOpen(AlsaError),
+ #[error("Could not find Alsa mixer control")]
+ CouldNotFindController,
+ #[error("Could not open Alsa softvol with that device. {0}")]
+ CouldNotOpenWithDevice(AlsaError),
+ #[error("Could not open Alsa softvol with that name. {0}")]
+ CouldNotOpenWithName(NulError),
+ #[error("Could not get Alsa softvol dB range. {0}")]
+ NoDbRange(AlsaError),
+ #[error("Could not convert Alsa raw volume to dB volume. {0}")]
+ CouldNotConvertRaw(AlsaError),
+}
+
+impl From<AlsaMixerError> for Error {
+ fn from(value: AlsaMixerError) -> Self {
+ Error::failed_precondition(value)
+ }
+}
+
+impl Mixer for AlsaMixer {
+ fn open(config: MixerConfig) -> Result<Self, Error> {
+ info!(
+ "Mixing with Alsa and volume control: {:?} for device: {} with mixer control: {},{}",
+ config.volume_ctrl, config.device, config.control, config.index,
+ );
+
+ let mut config = config; // clone
+
+ let mixer =
+ alsa::mixer::Mixer::new(&config.device, false).map_err(AlsaMixerError::CouldNotOpen)?;
+ let simple_element = mixer
+ .find_selem(&SelemId::new(&config.control, config.index))
+ .ok_or(AlsaMixerError::CouldNotFindController)?;
+
+ // Query capabilities
+ let has_switch = simple_element.has_playback_switch();
+ let is_softvol = simple_element
+ .get_playback_vol_db(SelemChannelId::mono())
+ .is_err();
+
+ // Query raw volume range
+ let (min, max) = simple_element.get_playback_volume_range();
+ let range = i64::abs(max - min);
+
+ // Query dB volume range -- note that Alsa exposes a different
+ // API for hardware and software mixers
+ let (min_millibel, max_millibel) = if is_softvol {
+ let control =
+ Ctl::new(&config.device, false).map_err(AlsaMixerError::CouldNotOpenWithDevice)?;
+ let mut element_id = ElemId::new(ElemIface::Mixer);
+ element_id.set_name(
+ &CString::new(config.control.as_str())
+ .map_err(AlsaMixerError::CouldNotOpenWithName)?,
+ );
+ element_id.set_index(config.index);
+ let (min_millibel, mut max_millibel) = control
+ .get_db_range(&element_id)
+ .map_err(AlsaMixerError::NoDbRange)?;
+
+ // Alsa can report incorrect maximum volumes due to rounding
+ // errors. e.g. Alsa rounds [-60.0..0.0] in range [0..255] to
+ // step size 0.23. Then multiplying 0.23 by 255 incorrectly
+ // returns a dB range of 58.65 instead of 60 dB, from
+ // [-60.00..-1.35]. This workaround checks the default case
+ // where the maximum dB volume is expected to be 0, and cannot
+ // cover all cases.
+ if max_millibel != ZERO_DB {
+ warn!("Alsa mixer reported maximum dB != 0, which is suspect");
+ let reported_step_size = (max_millibel - min_millibel).0 / range;
+ let assumed_step_size = (ZERO_DB - min_millibel).0 / range;
+ if reported_step_size == assumed_step_size {
+ warn!(
+ "Alsa rounding error detected, setting maximum dB to {:.2} instead of {:.2}",
+ ZERO_DB.to_db(),
+ max_millibel.to_db()
+ );
+ max_millibel = ZERO_DB;
+ } else {
+ warn!("Please manually set `--volume-range` if this is incorrect");
+ }
+ }
+ (min_millibel, max_millibel)
+ } else {
+ let (mut min_millibel, max_millibel) = simple_element.get_playback_db_range();
+
+ // Some controls report that their minimum volume is mute, instead
+ // of their actual lowest dB setting before that.
+ if min_millibel == SND_CTL_TLV_DB_GAIN_MUTE && min < max {
+ debug!("Alsa mixer reported minimum dB as mute, trying workaround");
+ min_millibel = simple_element
+ .ask_playback_vol_db(min + 1)
+ .map_err(AlsaMixerError::CouldNotConvertRaw)?;
+ }
+ (min_millibel, max_millibel)
+ };
+
+ let min_db = min_millibel.to_db() as f64;
+ let max_db = max_millibel.to_db() as f64;
+ let reported_db_range = f64::abs(max_db - min_db);
+
+ // Synchronize the volume control dB range with the mixer control,
+ // unless it was already set with a command line option.
+ let db_range = if config.volume_ctrl.range_ok() {
+ let db_range_override = config.volume_ctrl.db_range();
+ if db_range_override.is_normal() {
+ db_range_override
+ } else {
+ reported_db_range
+ }
+ } else {
+ config.volume_ctrl.set_db_range(reported_db_range);
+ reported_db_range
+ };
+
+ if reported_db_range == db_range {
+ debug!("Alsa dB volume range was reported as {}", reported_db_range);
+ if reported_db_range > 100.0 {
+ debug!("Alsa mixer reported dB range > 100, which is suspect");
+ debug!("Please manually set `--volume-range` if this is incorrect");
+ }
+ } else {
+ debug!(
+ "Alsa dB volume range was reported as {} but overridden to {}",
+ reported_db_range, db_range
+ );
+ }
+
+ // For hardware controls with a small range (24 dB or less),
+ // force using the dB API with a linear mapping.
+ let mut use_linear_in_db = false;
+ if !is_softvol && db_range <= 24.0 {
+ use_linear_in_db = true;
+ config.volume_ctrl = VolumeCtrl::Linear;
+ }
+
+ debug!("Alsa mixer control is softvol: {}", is_softvol);
+ debug!("Alsa support for playback (mute) switch: {}", has_switch);
+ debug!("Alsa raw volume range: [{}..{}] ({})", min, max, range);
+ debug!(
+ "Alsa dB volume range: [{:.2}..{:.2}] ({:.2})",
+ min_db, max_db, db_range
+ );
+ debug!("Alsa forcing linear dB mapping: {}", use_linear_in_db);
+
+ Ok(Self {
+ config,
+ min,
+ max,
+ range,
+ min_db,
+ max_db,
+ db_range,
+ has_switch,
+ is_softvol,
+ use_linear_in_db,
+ })
+ }
+
+ fn volume(&self) -> u16 {
+ let mixer =
+ alsa::mixer::Mixer::new(&self.config.device, false).expect("Could not open Alsa mixer");
+ let simple_element = mixer
+ .find_selem(&SelemId::new(&self.config.control, self.config.index))
+ .expect("Could not find Alsa mixer control");
+
+ if self.switched_off() {
+ return 0;
+ }
+
+ let mut mapped_volume = if self.is_softvol {
+ let raw_volume = simple_element
+ .get_playback_volume(SelemChannelId::mono())
+ .expect("Could not get raw Alsa volume");
+ raw_volume as f64 / self.range as f64 - self.min as f64
+ } else {
+ let db_volume = simple_element
+ .get_playback_vol_db(SelemChannelId::mono())
+ .expect("Could not get Alsa dB volume")
+ .to_db() as f64;
+
+ if self.use_linear_in_db {
+ (db_volume - self.min_db) / self.db_range
+ } else if f64::abs(db_volume - SND_CTL_TLV_DB_GAIN_MUTE.to_db() as f64) <= f64::EPSILON
+ {
+ 0.0
+ } else {
+ db_to_ratio(db_volume - self.max_db)
+ }
+ };
+
+ // see comment in `set_volume` why we are handling an antilog volume
+ if mapped_volume > 0.0 && self.is_some_linear() {
+ mapped_volume = LogMapping::linear_to_mapped(mapped_volume, self.db_range);
+ }
+
+ self.config.volume_ctrl.as_unmapped(mapped_volume)
+ }
+
+ fn set_volume(&self, volume: u16) {
+ let mixer =
+ alsa::mixer::Mixer::new(&self.config.device, false).expect("Could not open Alsa mixer");
+ let simple_element = mixer
+ .find_selem(&SelemId::new(&self.config.control, self.config.index))
+ .expect("Could not find Alsa mixer control");
+
+ if self.has_switch {
+ if volume == 0 {
+ debug!("Disabling playback (setting mute) on Alsa");
+ simple_element
+ .set_playback_switch_all(0)
+ .expect("Could not disable playback (set mute) on Alsa");
+ } else if self.switched_off() {
+ debug!("Enabling playback (unsetting mute) on Alsa");
+ simple_element
+ .set_playback_switch_all(1)
+ .expect("Could not enable playback (unset mute) on Alsa");
+ }
+ }
+
+ let mut mapped_volume = self.config.volume_ctrl.to_mapped(volume);
+
+ // Alsa's linear algorithms map everything onto log. Alsa softvol does
+ // this internally. In the case of `use_linear_in_db` this happens
+ // automatically by virtue of the dB scale. This means that linear
+ // controls become log, log becomes log-on-log, and so on. To make
+ // the controls work as expected, perform an antilog calculation to
+ // counteract what Alsa will be doing to the set volume.
+ if mapped_volume > 0.0 && self.is_some_linear() {
+ mapped_volume = LogMapping::mapped_to_linear(mapped_volume, self.db_range);
+ }
+
+ if self.is_softvol {
+ let scaled_volume = (self.min as f64 + mapped_volume * self.range as f64) as i64;
+ debug!("Setting Alsa raw volume to {}", scaled_volume);
+ simple_element
+ .set_playback_volume_all(scaled_volume)
+ .expect("Could not set Alsa raw volume");
+ return;
+ }
+
+ let db_volume = if self.use_linear_in_db {
+ self.min_db + mapped_volume * self.db_range
+ } else if volume == 0 {
+ // prevent ratio_to_db(0.0) from returning -inf
+ SND_CTL_TLV_DB_GAIN_MUTE.to_db() as f64
+ } else {
+ ratio_to_db(mapped_volume) + self.max_db
+ };
+
+ debug!("Setting Alsa volume to {:.2} dB", db_volume);
+ simple_element
+ .set_playback_db_all(MilliBel::from_db(db_volume as f32), Round::Floor)
+ .expect("Could not set Alsa dB volume");
+ }
+}
+
+impl AlsaMixer {
+ pub const NAME: &'static str = "alsa";
+
+ fn switched_off(&self) -> bool {
+ if !self.has_switch {
+ return false;
+ }
+
+ let mixer =
+ alsa::mixer::Mixer::new(&self.config.device, false).expect("Could not open Alsa mixer");
+ let simple_element = mixer
+ .find_selem(&SelemId::new(&self.config.control, self.config.index))
+ .expect("Could not find Alsa mixer control");
+
+ simple_element
+ .get_playback_switch(SelemChannelId::mono())
+ .map(|playback| playback == 0)
+ .unwrap_or(false)
+ }
+
+ fn is_some_linear(&self) -> bool {
+ self.is_softvol || self.use_linear_in_db
+ }
+}
diff --git a/native/vendor/librespot-playback/src/mixer/mappings.rs b/native/vendor/librespot-playback/src/mixer/mappings.rs
new file mode 100644
index 0000000..cb238a2
--- /dev/null
+++ b/native/vendor/librespot-playback/src/mixer/mappings.rs
@@ -0,0 +1,157 @@
+use super::VolumeCtrl;
+use crate::player::db_to_ratio;
+
+pub trait MappedCtrl {
+ fn to_mapped(&self, volume: u16) -> f64;
+ fn as_unmapped(&self, mapped_volume: f64) -> u16;
+
+ fn db_range(&self) -> f64;
+ fn set_db_range(&mut self, new_db_range: f64);
+ fn range_ok(&self) -> bool;
+}
+
+impl MappedCtrl for VolumeCtrl {
+ fn to_mapped(&self, volume: u16) -> f64 {
+ // More than just an optimization, this ensures that zero volume is
+ // really mute (both the log and cubic equations would otherwise not
+ // reach zero).
+ if volume == 0 {
+ return 0.0;
+ } else if volume == Self::MAX_VOLUME {
+ // And limit in case of rounding errors (as is the case for log).
+ return 1.0;
+ }
+
+ let normalized_volume = volume as f64 / Self::MAX_VOLUME as f64;
+ let mapped_volume = if self.range_ok() {
+ match *self {
+ Self::Cubic(db_range) => {
+ CubicMapping::linear_to_mapped(normalized_volume, db_range)
+ }
+ Self::Log(db_range) => LogMapping::linear_to_mapped(normalized_volume, db_range),
+ _ => normalized_volume,
+ }
+ } else {
+ // Ensure not to return -inf or NaN due to division by zero.
+ error!("{self:?} does not work with 0 dB range, using linear mapping instead");
+ normalized_volume
+ };
+
+ debug!(
+ "Input volume {} mapped to: {:.2}%",
+ volume,
+ mapped_volume * 100.0
+ );
+
+ mapped_volume
+ }
+
+ fn as_unmapped(&self, mapped_volume: f64) -> u16 {
+ // More than just an optimization, this ensures that zero mapped volume
+ // is unmapped to non-negative real numbers (otherwise the log and cubic
+ // equations would respectively return -inf and -1/9.)
+ if f64::abs(mapped_volume - 0.0) <= f64::EPSILON {
+ return 0;
+ } else if f64::abs(mapped_volume - 1.0) <= f64::EPSILON {
+ return Self::MAX_VOLUME;
+ }
+
+ let unmapped_volume = if self.range_ok() {
+ match *self {
+ Self::Cubic(db_range) => CubicMapping::mapped_to_linear(mapped_volume, db_range),
+ Self::Log(db_range) => LogMapping::mapped_to_linear(mapped_volume, db_range),
+ _ => mapped_volume,
+ }
+ } else {
+ // Ensure not to return -inf or NaN due to division by zero.
+ error!("{self:?} does not work with 0 dB range, using linear mapping instead");
+ mapped_volume
+ };
+
+ (unmapped_volume * Self::MAX_VOLUME as f64) as u16
+ }
+
+ fn db_range(&self) -> f64 {
+ match *self {
+ Self::Fixed => 0.0,
+ Self::Linear => Self::DEFAULT_DB_RANGE, // arbitrary, could be anything > 0
+ Self::Log(db_range) | Self::Cubic(db_range) => db_range,
+ }
+ }
+
+ fn set_db_range(&mut self, new_db_range: f64) {
+ match self {
+ Self::Cubic(db_range) | Self::Log(db_range) => *db_range = new_db_range,
+ _ => error!("Invalid to set dB range for volume control type {self:?}"),
+ }
+
+ debug!("Volume control is now {self:?}")
+ }
+
+ fn range_ok(&self) -> bool {
+ self.db_range() > 0.0 || matches!(self, Self::Fixed | Self::Linear)
+ }
+}
+
+pub trait VolumeMapping {
+ fn linear_to_mapped(unmapped_volume: f64, db_range: f64) -> f64;
+ fn mapped_to_linear(mapped_volume: f64, db_range: f64) -> f64;
+}
+
+// Volume conversion taken from: https://www.dr-lex.be/info-stuff/volumecontrols.html#ideal2
+//
+// As the human auditory system has a logarithmic sensitivity curve, this
+// mapping results in a near linear loudness experience with the listener.
+pub struct LogMapping {}
+impl VolumeMapping for LogMapping {
+ fn linear_to_mapped(normalized_volume: f64, db_range: f64) -> f64 {
+ let (db_ratio, ideal_factor) = Self::coefficients(db_range);
+ f64::exp(ideal_factor * normalized_volume) / db_ratio
+ }
+
+ fn mapped_to_linear(mapped_volume: f64, db_range: f64) -> f64 {
+ let (db_ratio, ideal_factor) = Self::coefficients(db_range);
+ f64::ln(db_ratio * mapped_volume) / ideal_factor
+ }
+}
+
+impl LogMapping {
+ fn coefficients(db_range: f64) -> (f64, f64) {
+ let db_ratio = db_to_ratio(db_range);
+ let ideal_factor = f64::ln(db_ratio);
+ (db_ratio, ideal_factor)
+ }
+}
+
+// Ported from: https://github.com/alsa-project/alsa-utils/blob/master/alsamixer/volume_mapping.c
+// which in turn was inspired by: https://www.robotplanet.dk/audio/audio_gui_design/
+//
+// Though this mapping is computationally less expensive than the logarithmic
+// mapping, it really does not matter as librespot memoizes the mapped value.
+// Use this mapping if you have some reason to mimic Alsa's native mixer or
+// prefer a more granular control in the upper volume range.
+//
+// Note: https://www.dr-lex.be/info-stuff/volumecontrols.html#ideal3 shows
+// better approximations to the logarithmic curve but because we only intend
+// to mimic Alsa here, we do not implement them. If your desire is to use a
+// logarithmic mapping, then use that volume control.
+pub struct CubicMapping {}
+impl VolumeMapping for CubicMapping {
+ fn linear_to_mapped(normalized_volume: f64, db_range: f64) -> f64 {
+ let min_norm = Self::min_norm(db_range);
+ f64::powi(normalized_volume * (1.0 - min_norm) + min_norm, 3)
+ }
+
+ fn mapped_to_linear(mapped_volume: f64, db_range: f64) -> f64 {
+ let min_norm = Self::min_norm(db_range);
+ (mapped_volume.powf(1.0 / 3.0) - min_norm) / (1.0 - min_norm)
+ }
+}
+
+impl CubicMapping {
+ fn min_norm(db_range: f64) -> f64 {
+ // Note that this 60.0 is unrelated to DEFAULT_DB_RANGE.
+ // Instead, it's the cubic voltage to dB ratio.
+ f64::powf(10.0, -db_range / 60.0)
+ }
+}
diff --git a/native/vendor/librespot-playback/src/mixer/mod.rs b/native/vendor/librespot-playback/src/mixer/mod.rs
new file mode 100644
index 0000000..89d0323
--- /dev/null
+++ b/native/vendor/librespot-playback/src/mixer/mod.rs
@@ -0,0 +1,82 @@
+use crate::config::VolumeCtrl;
+use librespot_core::Error;
+use std::sync::Arc;
+
+pub mod mappings;
+use self::mappings::MappedCtrl;
+
+pub struct NoOpVolume;
+
+pub trait Mixer: Send + Sync {
+ fn open(config: MixerConfig) -> Result<Self, Error>
+ where
+ Self: Sized;
+
+ fn volume(&self) -> u16;
+ fn set_volume(&self, volume: u16);
+
+ fn get_soft_volume(&self) -> Box<dyn VolumeGetter + Send> {
+ Box::new(NoOpVolume)
+ }
+}
+
+pub trait VolumeGetter {
+ fn attenuation_factor(&self) -> f64;
+}
+
+impl VolumeGetter for NoOpVolume {
+ #[inline]
+ fn attenuation_factor(&self) -> f64 {
+ 1.0
+ }
+}
+
+pub mod softmixer;
+use self::softmixer::SoftMixer;
+
+#[cfg(feature = "alsa-backend")]
+pub mod alsamixer;
+#[cfg(feature = "alsa-backend")]
+use self::alsamixer::AlsaMixer;
+
+#[derive(Debug, Clone)]
+pub struct MixerConfig {
+ pub device: String,
+ pub control: String,
+ pub index: u32,
+ pub volume_ctrl: VolumeCtrl,
+}
+
+impl Default for MixerConfig {
+ fn default() -> MixerConfig {
+ MixerConfig {
+ device: String::from("default"),
+ control: String::from("PCM"),
+ index: 0,
+ volume_ctrl: VolumeCtrl::default(),
+ }
+ }
+}
+
+pub type MixerFn = fn(MixerConfig) -> Result<Arc<dyn Mixer>, Error>;
+
+fn mk_sink<M: Mixer + 'static>(config: MixerConfig) -> Result<Arc<dyn Mixer>, Error> {
+ Ok(Arc::new(M::open(config)?))
+}
+
+pub const MIXERS: &[(&str, MixerFn)] = &[
+ (SoftMixer::NAME, mk_sink::<SoftMixer>), // default goes first
+ #[cfg(feature = "alsa-backend")]
+ (AlsaMixer::NAME, mk_sink::<AlsaMixer>),
+];
+
+pub fn find(name: Option<&str>) -> Option<MixerFn> {
+ if let Some(name) = name {
+ MIXERS
+ .iter()
+ .find(|mixer| name == mixer.0)
+ .map(|mixer| mixer.1)
+ } else {
+ MIXERS.first().map(|mixer| mixer.1)
+ }
+}
diff --git a/native/vendor/librespot-playback/src/mixer/softmixer.rs b/native/vendor/librespot-playback/src/mixer/softmixer.rs
new file mode 100644
index 0000000..189fc15
--- /dev/null
+++ b/native/vendor/librespot-playback/src/mixer/softmixer.rs
@@ -0,0 +1,55 @@
+use super::VolumeGetter;
+use super::{MappedCtrl, VolumeCtrl};
+use super::{Mixer, MixerConfig};
+use librespot_core::Error;
+use portable_atomic::AtomicU64;
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+#[derive(Clone)]
+pub struct SoftMixer {
+ // There is no AtomicF64, so we store the f64 as bits in a u64 field.
+ // It's much faster than a Mutex<f64>.
+ volume: Arc<AtomicU64>,
+ volume_ctrl: VolumeCtrl,
+}
+
+impl Mixer for SoftMixer {
+ fn open(config: MixerConfig) -> Result<Self, Error> {
+ let volume_ctrl = config.volume_ctrl;
+ info!("Mixing with softvol and volume control: {volume_ctrl:?}");
+
+ Ok(Self {
+ volume: Arc::new(AtomicU64::new(f64::to_bits(0.5))),
+ volume_ctrl,
+ })
+ }
+
+ fn volume(&self) -> u16 {
+ let mapped_volume = f64::from_bits(self.volume.load(Ordering::Relaxed));
+ self.volume_ctrl.as_unmapped(mapped_volume)
+ }
+
+ fn set_volume(&self, volume: u16) {
+ let mapped_volume = self.volume_ctrl.to_mapped(volume);
+ self.volume
+ .store(mapped_volume.to_bits(), Ordering::Relaxed)
+ }
+
+ fn get_soft_volume(&self) -> Box<dyn VolumeGetter + Send> {
+ Box::new(SoftVolume(self.volume.clone()))
+ }
+}
+
+impl SoftMixer {
+ pub const NAME: &'static str = "softvol";
+}
+
+struct SoftVolume(Arc<AtomicU64>);
+
+impl VolumeGetter for SoftVolume {
+ #[inline]
+ fn attenuation_factor(&self) -> f64 {
+ f64::from_bits(self.0.load(Ordering::Relaxed))
+ }
+}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
new file mode 100644
index 0000000..616c655
--- /dev/null
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -0,0 +1,2844 @@
+use std::{
+ collections::HashMap,
+ fmt, fs,
+ fs::File,
+ future::Future,
+ io::{self, Read, Seek, SeekFrom},
+ mem,
+ pin::Pin,
+ process::exit,
+ sync::Mutex,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+ task::{Context, Poll},
+ thread,
+ time::{Duration, Instant},
+};
+
+#[cfg(feature = "passthrough-decoder")]
+use crate::decoder::PassthroughDecoder;
+use crate::{
+ audio::{AudioDecrypt, AudioFetchParams, AudioFile, StreamLoaderController},
+ audio_backend::Sink,
+ config::{Bitrate, NormalisationMethod, NormalisationType, PlayerConfig},
+ convert::Converter,
+ core::{Error, Session, SpotifyId, SpotifyUri, util::SeqGenerator},
+ decoder::{AudioDecoder, AudioPacket, AudioPacketPosition, SymphoniaDecoder},
+ local_file::{LocalFileLookup, create_local_file_lookup},
+ metadata::audio::{AudioFileFormat, AudioFiles, AudioItem},
+ mixer::VolumeGetter,
+};
+use futures_util::{
+ StreamExt, TryFutureExt, future, future::FusedFuture,
+ stream::futures_unordered::FuturesUnordered,
+};
+use librespot_metadata::{audio::UniqueFields, track::Tracks};
+
+use symphonia::core::io::MediaSource;
+use symphonia::core::probe::Hint;
+use tokio::sync::{mpsc, oneshot};
+
+use crate::{NUM_CHANNELS, SAMPLE_RATE, SAMPLES_PER_SECOND};
+
+const PRELOAD_NEXT_TRACK_BEFORE_END_DURATION_MS: u32 = 30000;
+
+/// LOCAL PATCH: the largest value that survives conversion to signed 16 bit.
+///
+/// Full scale is asymmetric: -32768 exists, +32768 does not, so a mix that
+/// reaches 1.0 on the way up wraps around to the bottom and is heard as a click.
+const MAX_SAMPLE: f64 = 32767.0 / 32768.0;
+pub const DB_VOLTAGE_RATIO: f64 = 20.0;
+pub const PCM_AT_0DBFS: f64 = 1.0;
+
+// Spotify inserts a custom Ogg packet at the start with custom metadata values, that you would
+// otherwise expect in Vorbis comments. This packet isn't well-formed and players may balk at it.
+const SPOTIFY_OGG_HEADER_END: u64 = 0xa7;
+
+const LOAD_HANDLES_POISON_MSG: &str = "load handles mutex should not be poisoned";
+
+pub type PlayerResult = Result<(), Error>;
+
+pub struct Player {
+ commands: Option<mpsc::UnboundedSender<PlayerCommand>>,
+ thread_handle: Option<thread::JoinHandle<()>>,
+}
+
+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
+pub enum SinkStatus {
+ Running,
+ Closed,
+ TemporarilyClosed,
+}
+
+pub type SinkEventCallback = Box<dyn Fn(SinkStatus) + Send>;
+
+struct PlayerInternal {
+ session: Session,
+ config: PlayerConfig,
+ commands: mpsc::UnboundedReceiver<PlayerCommand>,
+ load_handles: Arc<Mutex<HashMap<thread::ThreadId, thread::JoinHandle<()>>>>,
+
+ state: PlayerState,
+ preload: PlayerPreload,
+ sink: Box<dyn Sink>,
+ sink_status: SinkStatus,
+ sink_event_callback: Option<SinkEventCallback>,
+ volume_getter: Box<dyn VolumeGetter + Send>,
+ event_senders: Vec<mpsc::UnboundedSender<PlayerEvent>>,
+ converter: Converter,
+
+ normalisation_integrators: [f64; 2],
+ normalisation_peaks: [f64; 2],
+ normalisation_channel: usize,
+ normalisation_knee_factor: f64,
+
+ auto_normalise_as_album: bool,
+
+ player_id: usize,
+ play_request_id_generator: SeqGenerator<u64>,
+ last_progress_update: Instant,
+
+ local_file_lookup: Arc<LocalFileLookup>,
+
+ /// LOCAL PATCH: the track being dissolved out of, if there is one.
+ fade_out: Option<FadeOut>,
+ /// LOCAL PATCH: the play request whose end has already been announced early.
+ early_end: Option<u64>,
+}
+
+/// LOCAL PATCH: the outgoing half of a crossfade.
+///
+/// A track that is on its way out is no longer the player's state: the state
+/// holds the track coming in. Its decoder is kept here instead and read for as
+/// long as the fade lasts, then dropped, which closes the stream behind it.
+struct FadeOut {
+ decoder: Decoder,
+ /// The gain the outgoing track was being played at.
+ ///
+ /// Its own factor, not the incoming track's: normalisation exists so that
+ /// two tracks mastered at different levels sound alike, and a fade is the
+ /// one moment both are audible at once.
+ normalisation_factor: f64,
+ /// Length of the fade in samples, so the gain curve knows its own scale.
+ total: usize,
+ /// How much of it has been mixed.
+ done: usize,
+ /// Decoded samples not yet used, since a packet rarely lands exactly on the
+ /// boundary of what the incoming packet needs.
+ spare: std::collections::VecDeque<f64>,
+ /// Set when the outgoing track runs out before the fade does.
+ drained: bool,
+}
+
+static PLAYER_COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+enum PlayerCommand {
+ Load {
+ track_id: SpotifyUri,
+ play: bool,
+ position_ms: u32,
+ },
+ Preload {
+ track_id: SpotifyUri,
+ },
+ Play,
+ Pause,
+ Stop,
+ Seek(u32),
+ SetSession(Session),
+ AddEventSender(mpsc::UnboundedSender<PlayerEvent>),
+ SetSinkEventCallback(Option<SinkEventCallback>),
+ EmitVolumeChangedEvent(u16),
+ SetAutoNormaliseAsAlbum(bool),
+ EmitSessionDisconnectedEvent {
+ connection_id: String,
+ user_name: String,
+ },
+ EmitSessionConnectedEvent {
+ connection_id: String,
+ user_name: String,
+ },
+ EmitSessionClientChangedEvent {
+ client_id: String,
+ client_name: String,
+ client_brand_name: String,
+ client_model_name: String,
+ },
+ EmitFilterExplicitContentChangedEvent(bool),
+ EmitShuffleChangedEvent(bool),
+ EmitRepeatChangedEvent {
+ context: bool,
+ track: bool,
+ },
+ EmitAutoPlayChangedEvent(bool),
+}
+
+#[derive(Debug, Clone)]
+pub enum PlayerEvent {
+ // Play request id changed
+ PlayRequestIdChanged {
+ play_request_id: u64,
+ },
+ // Fired when the player is stopped (e.g. by issuing a "stop" command to the player).
+ Stopped {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ },
+ // The player is delayed by loading a track.
+ Loading {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ // The player is preloading a track.
+ Preloading {
+ track_id: SpotifyUri,
+ },
+ // The player is playing a track.
+ // This event is issued at the start of playback of whenever the position must be communicated
+ // because it is out of sync. This includes:
+ // start of a track
+ // un-pausing
+ // after a seek
+ // after a buffer-underrun
+ Playing {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ // The player entered a paused state.
+ Paused {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ // The player thinks it's a good idea to issue a preload command for the next track now.
+ // This event is intended for use within spirc.
+ TimeToPreloadNextTrack {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ },
+ // The player reached the end of a track.
+ // This event is intended for use within spirc. Spirc will respond by issuing another command.
+ EndOfTrack {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ },
+ // The player was unable to load the requested track.
+ Unavailable {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ },
+ // The mixer volume was set to a new level.
+ VolumeChanged {
+ volume: u16,
+ },
+ PositionCorrection {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ /// Requires `PlayerConfig::position_update_interval` to be set to Some.
+ /// Once set this event will be sent periodically while playing the track to inform about the
+ /// current playback position
+ PositionChanged {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ Seeked {
+ play_request_id: u64,
+ track_id: SpotifyUri,
+ position_ms: u32,
+ },
+ TrackChanged {
+ audio_item: Box<AudioItem>,
+ },
+ SessionConnected {
+ connection_id: String,
+ user_name: String,
+ },
+ SessionDisconnected {
+ connection_id: String,
+ user_name: String,
+ },
+ SessionClientChanged {
+ client_id: String,
+ client_name: String,
+ client_brand_name: String,
+ client_model_name: String,
+ },
+ ShuffleChanged {
+ shuffle: bool,
+ },
+ RepeatChanged {
+ context: bool,
+ track: bool,
+ },
+ AutoPlayChanged {
+ auto_play: bool,
+ },
+ FilterExplicitContentChanged {
+ filter: bool,
+ },
+}
+
+impl PlayerEvent {
+ pub fn get_play_request_id(&self) -> Option<u64> {
+ use PlayerEvent::*;
+ match self {
+ Loading {
+ play_request_id, ..
+ }
+ | Unavailable {
+ play_request_id, ..
+ }
+ | Playing {
+ play_request_id, ..
+ }
+ | TimeToPreloadNextTrack {
+ play_request_id, ..
+ }
+ | EndOfTrack {
+ play_request_id, ..
+ }
+ | Paused {
+ play_request_id, ..
+ }
+ | Stopped {
+ play_request_id, ..
+ }
+ | PositionCorrection {
+ play_request_id, ..
+ }
+ | Seeked {
+ play_request_id, ..
+ } => Some(*play_request_id),
+ _ => None,
+ }
+ }
+}
+
+pub type PlayerEventChannel = mpsc::UnboundedReceiver<PlayerEvent>;
+
+#[inline]
+pub fn db_to_ratio(db: f64) -> f64 {
+ f64::powf(10.0, db / DB_VOLTAGE_RATIO)
+}
+
+#[inline]
+pub fn ratio_to_db(ratio: f64) -> f64 {
+ ratio.log10() * DB_VOLTAGE_RATIO
+}
+
+pub fn duration_to_coefficient(duration: Duration) -> f64 {
+ f64::exp(-1.0 / (duration.as_secs_f64() * SAMPLES_PER_SECOND as f64))
+}
+
+pub fn coefficient_to_duration(coefficient: f64) -> Duration {
+ Duration::from_secs_f64(-1.0 / f64::ln(coefficient) / SAMPLES_PER_SECOND as f64)
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct NormalisationData {
+ // Spotify provides these as `f32`, but audio metadata can contain up to `f64`.
+ // Also, this negates the need for casting during sample processing.
+ pub track_gain_db: f64,
+ pub track_peak: f64,
+ pub album_gain_db: f64,
+ pub album_peak: f64,
+}
+
+impl Default for NormalisationData {
+ fn default() -> Self {
+ Self {
+ track_gain_db: 0.0,
+ track_peak: 1.0,
+ album_gain_db: 0.0,
+ album_peak: 1.0,
+ }
+ }
+}
+
+impl NormalisationData {
+ fn parse_from_ogg<T: Read + Seek>(mut file: T) -> io::Result<NormalisationData> {
+ const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144;
+ const NORMALISATION_DATA_SIZE: usize = 16;
+
+ let newpos = file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET))?;
+ if newpos != SPOTIFY_NORMALIZATION_HEADER_START_OFFSET {
+ error!(
+ "NormalisationData::parse_from_file seeking to {SPOTIFY_NORMALIZATION_HEADER_START_OFFSET} but position is now {newpos}"
+ );
+
+ error!("Falling back to default (non-track and non-album) normalisation data.");
+
+ return Ok(NormalisationData::default());
+ }
+
+ let mut buf = [0u8; NORMALISATION_DATA_SIZE];
+
+ file.read_exact(&mut buf)?;
+
+ let track_gain_db = f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as f64;
+ let track_peak = f32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as f64;
+ let album_gain_db = f32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]) as f64;
+ let album_peak = f32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) as f64;
+
+ Ok(Self {
+ track_gain_db,
+ track_peak,
+ album_gain_db,
+ album_peak,
+ })
+ }
+
+ fn get_factor(config: &PlayerConfig, data: NormalisationData) -> f64 {
+ if !config.normalisation {
+ return 1.0;
+ }
+
+ let (gain_db, gain_peak) = if config.normalisation_type == NormalisationType::Album {
+ (data.album_gain_db, data.album_peak)
+ } else {
+ (data.track_gain_db, data.track_peak)
+ };
+
+ // As per the ReplayGain 1.0 & 2.0 (proposed) spec:
+ // https://wiki.hydrogenaud.io/index.php?title=ReplayGain_1.0_specification#Clipping_prevention
+ // https://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification#Clipping_prevention
+ let normalisation_factor = if config.normalisation_method == NormalisationMethod::Basic {
+ // For Basic Normalisation, factor = min(ratio of (ReplayGain + PreGain), 1.0 / peak level).
+ // https://wiki.hydrogenaud.io/index.php?title=ReplayGain_1.0_specification#Peak_amplitude
+ // https://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification#Peak_amplitude
+ // We then limit that to 1.0 as not to exceed dBFS (0.0 dB).
+ let factor = f64::min(
+ db_to_ratio(gain_db + config.normalisation_pregain_db),
+ PCM_AT_0DBFS / gain_peak,
+ );
+
+ if factor > PCM_AT_0DBFS {
+ info!(
+ "Lowering gain by {:.2} dB for the duration of this track to avoid potentially exceeding dBFS.",
+ ratio_to_db(factor)
+ );
+
+ PCM_AT_0DBFS
+ } else {
+ factor
+ }
+ } else {
+ // For Dynamic Normalisation it's up to the player to decide,
+ // factor = ratio of (ReplayGain + PreGain).
+ // We then let the dynamic limiter handle gain reduction.
+ let factor = db_to_ratio(gain_db + config.normalisation_pregain_db);
+ let threshold_ratio = db_to_ratio(config.normalisation_threshold_dbfs);
+
+ if factor > PCM_AT_0DBFS {
+ let factor_db = gain_db + config.normalisation_pregain_db;
+ let limiting_db = factor_db + config.normalisation_threshold_dbfs.abs();
+
+ warn!(
+ "This track may exceed dBFS by {factor_db:.2} dB and be subject to {limiting_db:.2} dB of dynamic limiting at its peak."
+ );
+ } else if factor > threshold_ratio {
+ let limiting_db = gain_db
+ + config.normalisation_pregain_db
+ + config.normalisation_threshold_dbfs.abs();
+
+ info!(
+ "This track may be subject to {limiting_db:.2} dB of dynamic limiting at its peak."
+ );
+ }
+
+ factor
+ };
+
+ debug!("Normalisation Data: {data:?}");
+ debug!(
+ "Calculated Normalisation Factor for {:?}: {:.2}%",
+ config.normalisation_type,
+ normalisation_factor * 100.0
+ );
+
+ normalisation_factor
+ }
+}
+
+impl Player {
+ pub fn new<F>(
+ config: PlayerConfig,
+ session: Session,
+ volume_getter: Box<dyn VolumeGetter + Send>,
+ sink_builder: F,
+ ) -> Arc<Self>
+ where
+ F: FnOnce() -> Box<dyn Sink> + Send + 'static,
+ {
+ let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
+
+ if config.normalisation {
+ debug!("Normalisation Type: {:?}", config.normalisation_type);
+ debug!(
+ "Normalisation Pregain: {:.1} dB",
+ config.normalisation_pregain_db
+ );
+ debug!(
+ "Normalisation Threshold: {:.1} dBFS",
+ config.normalisation_threshold_dbfs
+ );
+ debug!("Normalisation Method: {:?}", config.normalisation_method);
+
+ if config.normalisation_method == NormalisationMethod::Dynamic {
+ // as_millis() has rounding errors (truncates)
+ debug!(
+ "Normalisation Attack: {:.0} ms",
+ coefficient_to_duration(config.normalisation_attack_cf).as_secs_f64() * 1000.
+ );
+ debug!(
+ "Normalisation Release: {:.0} ms",
+ coefficient_to_duration(config.normalisation_release_cf).as_secs_f64() * 1000.
+ );
+ debug!("Normalisation Knee: {} dB", config.normalisation_knee_db);
+ }
+ }
+
+ let handle = thread::spawn(move || {
+ let player_id = PLAYER_COUNTER.fetch_add(1, Ordering::AcqRel);
+ debug!("new Player [{player_id}]");
+
+ let converter = Converter::new(config.ditherer);
+ let normalisation_knee_factor = 1.0 / (8.0 * config.normalisation_knee_db);
+
+ // TODO: it would be neat if we could watch for added or modified files in the
+ // specified directories, and dynamically update the lookup. Currently, a new player
+ // must be created for any new local files to be playable.
+ let local_file_lookup =
+ create_local_file_lookup(config.local_file_directories.as_slice());
+
+ let internal = PlayerInternal {
+ session,
+ config,
+ commands: cmd_rx,
+ load_handles: Arc::new(Mutex::new(HashMap::new())),
+
+ state: PlayerState::Stopped,
+ preload: PlayerPreload::None,
+ sink: sink_builder(),
+ sink_status: SinkStatus::Closed,
+ sink_event_callback: None,
+ volume_getter,
+ event_senders: vec![],
+ converter,
+
+ fade_out: None,
+ early_end: None,
+ normalisation_peaks: [0.0; 2],
+ normalisation_integrators: [0.0; 2],
+ normalisation_channel: 0,
+ normalisation_knee_factor,
+
+ auto_normalise_as_album: false,
+
+ player_id,
+ play_request_id_generator: SeqGenerator::new(0),
+ last_progress_update: Instant::now(),
+
+ local_file_lookup: Arc::new(local_file_lookup),
+ };
+
+ // While PlayerInternal is written as a future, it still contains blocking code.
+ // It must be run by using block_on() in a dedicated thread.
+ let runtime = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
+ runtime.block_on(internal);
+
+ debug!("PlayerInternal thread finished.");
+ });
+
+ Arc::new(Self {
+ commands: Some(cmd_tx),
+ thread_handle: Some(handle),
+ })
+ }
+
+ pub fn is_invalid(&self) -> bool {
+ if let Some(handle) = self.thread_handle.as_ref() {
+ return handle.is_finished();
+ }
+ true
+ }
+
+ fn command(&self, cmd: PlayerCommand) {
+ if let Some(commands) = self.commands.as_ref() {
+ if let Err(e) = commands.send(cmd) {
+ error!("Player Commands Error: {e}");
+ }
+ }
+ }
+
+ pub fn load(&self, track_id: SpotifyUri, start_playing: bool, position_ms: u32) {
+ self.command(PlayerCommand::Load {
+ track_id,
+ play: start_playing,
+ position_ms,
+ });
+ }
+
+ pub fn preload(&self, track_id: SpotifyUri) {
+ self.command(PlayerCommand::Preload { track_id });
+ }
+
+ pub fn play(&self) {
+ self.command(PlayerCommand::Play)
+ }
+
+ pub fn pause(&self) {
+ self.command(PlayerCommand::Pause)
+ }
+
+ pub fn stop(&self) {
+ self.command(PlayerCommand::Stop)
+ }
+
+ pub fn seek(&self, position_ms: u32) {
+ self.command(PlayerCommand::Seek(position_ms));
+ }
+
+ pub fn set_session(&self, session: Session) {
+ self.command(PlayerCommand::SetSession(session));
+ }
+
+ pub fn get_player_event_channel(&self) -> PlayerEventChannel {
+ let (event_sender, event_receiver) = mpsc::unbounded_channel();
+ self.command(PlayerCommand::AddEventSender(event_sender));
+ event_receiver
+ }
+
+ pub async fn await_end_of_track(&self) {
+ let mut channel = self.get_player_event_channel();
+ while let Some(event) = channel.recv().await {
+ if matches!(
+ event,
+ PlayerEvent::EndOfTrack { .. } | PlayerEvent::Stopped { .. }
+ ) {
+ return;
+ }
+ }
+ }
+
+ pub fn set_sink_event_callback(&self, callback: Option<SinkEventCallback>) {
+ self.command(PlayerCommand::SetSinkEventCallback(callback));
+ }
+
+ pub fn emit_volume_changed_event(&self, volume: u16) {
+ self.command(PlayerCommand::EmitVolumeChangedEvent(volume));
+ }
+
+ pub fn set_auto_normalise_as_album(&self, setting: bool) {
+ self.command(PlayerCommand::SetAutoNormaliseAsAlbum(setting));
+ }
+
+ pub fn emit_filter_explicit_content_changed_event(&self, filter: bool) {
+ self.command(PlayerCommand::EmitFilterExplicitContentChangedEvent(filter));
+ }
+
+ pub fn emit_session_connected_event(&self, connection_id: String, user_name: String) {
+ self.command(PlayerCommand::EmitSessionConnectedEvent {
+ connection_id,
+ user_name,
+ });
+ }
+
+ pub fn emit_session_disconnected_event(&self, connection_id: String, user_name: String) {
+ self.command(PlayerCommand::EmitSessionDisconnectedEvent {
+ connection_id,
+ user_name,
+ });
+ }
+
+ pub fn emit_session_client_changed_event(
+ &self,
+ client_id: String,
+ client_name: String,
+ client_brand_name: String,
+ client_model_name: String,
+ ) {
+ self.command(PlayerCommand::EmitSessionClientChangedEvent {
+ client_id,
+ client_name,
+ client_brand_name,
+ client_model_name,
+ });
+ }
+
+ pub fn emit_shuffle_changed_event(&self, shuffle: bool) {
+ self.command(PlayerCommand::EmitShuffleChangedEvent(shuffle));
+ }
+
+ pub fn emit_repeat_changed_event(&self, context: bool, track: bool) {
+ self.command(PlayerCommand::EmitRepeatChangedEvent { context, track });
+ }
+
+ pub fn emit_auto_play_changed_event(&self, auto_play: bool) {
+ self.command(PlayerCommand::EmitAutoPlayChangedEvent(auto_play));
+ }
+}
+
+impl Drop for Player {
+ fn drop(&mut self) {
+ debug!("Shutting down player thread ...");
+ self.commands = None;
+ if let Some(handle) = self.thread_handle.take() {
+ if let Err(e) = handle.join() {
+ error!("Player thread Error: {e:?}");
+ }
+ }
+ }
+}
+
+struct PlayerLoadedTrackData {
+ decoder: Decoder,
+ normalisation_data: NormalisationData,
+ stream_loader_controller: StreamLoaderController,
+ audio_item: AudioItem,
+ bytes_per_second: usize,
+ duration_ms: u32,
+ stream_position_ms: u32,
+ is_explicit: bool,
+}
+
+enum PlayerPreload {
+ None,
+ Loading {
+ track_id: SpotifyUri,
+ loader: Pin<Box<dyn FusedFuture<Output = Result<PlayerLoadedTrackData, ()>> + Send>>,
+ },
+ Ready {
+ track_id: SpotifyUri,
+ loaded_track: Box<PlayerLoadedTrackData>,
+ },
+}
+
+type Decoder = Box<dyn AudioDecoder + Send>;
+
+enum PlayerState {
+ Stopped,
+ Loading {
+ track_id: SpotifyUri,
+ play_request_id: u64,
+ start_playback: bool,
+ loader: Pin<Box<dyn FusedFuture<Output = Result<PlayerLoadedTrackData, ()>> + Send>>,
+ },
+ Paused {
+ track_id: SpotifyUri,
+ play_request_id: u64,
+ decoder: Decoder,
+ audio_item: AudioItem,
+ normalisation_data: NormalisationData,
+ normalisation_factor: f64,
+ stream_loader_controller: StreamLoaderController,
+ bytes_per_second: usize,
+ duration_ms: u32,
+ stream_position_ms: u32,
+ suggested_to_preload_next_track: bool,
+ is_explicit: bool,
+ },
+ Playing {
+ track_id: SpotifyUri,
+ play_request_id: u64,
+ decoder: Decoder,
+ normalisation_data: NormalisationData,
+ audio_item: AudioItem,
+ normalisation_factor: f64,
+ stream_loader_controller: StreamLoaderController,
+ bytes_per_second: usize,
+ duration_ms: u32,
+ stream_position_ms: u32,
+ reported_nominal_start_time: Option<Instant>,
+ suggested_to_preload_next_track: bool,
+ is_explicit: bool,
+ },
+ EndOfTrack {
+ track_id: SpotifyUri,
+ play_request_id: u64,
+ loaded_track: PlayerLoadedTrackData,
+ },
+ Invalid,
+}
+
+impl PlayerState {
+ fn is_playing(&self) -> bool {
+ use self::PlayerState::*;
+ match *self {
+ Stopped | EndOfTrack { .. } | Paused { .. } | Loading { .. } => false,
+ Playing { .. } => true,
+ Invalid => {
+ error!("PlayerState::is_playing in invalid state");
+ exit(1);
+ }
+ }
+ }
+
+ #[allow(dead_code)]
+ fn is_stopped(&self) -> bool {
+ use self::PlayerState::*;
+ matches!(self, Stopped)
+ }
+
+ #[allow(dead_code)]
+ fn is_loading(&self) -> bool {
+ use self::PlayerState::*;
+ matches!(self, Loading { .. })
+ }
+
+ fn decoder(&mut self) -> Option<&mut Decoder> {
+ use self::PlayerState::*;
+ match *self {
+ Stopped | EndOfTrack { .. } | Loading { .. } => None,
+ Paused {
+ ref mut decoder, ..
+ }
+ | Playing {
+ ref mut decoder, ..
+ } => Some(decoder),
+ Invalid => {
+ error!("PlayerState::decoder in invalid state");
+ exit(1);
+ }
+ }
+ }
+
+ fn playing_to_end_of_track(&mut self) {
+ use self::PlayerState::*;
+ let new_state = mem::replace(self, Invalid);
+ match new_state {
+ Playing {
+ track_id,
+ play_request_id,
+ decoder,
+ duration_ms,
+ bytes_per_second,
+ normalisation_data,
+ stream_loader_controller,
+ stream_position_ms,
+ is_explicit,
+ audio_item,
+ ..
+ } => {
+ *self = EndOfTrack {
+ track_id,
+ play_request_id,
+ loaded_track: PlayerLoadedTrackData {
+ decoder,
+ normalisation_data,
+ stream_loader_controller,
+ audio_item,
+ bytes_per_second,
+ duration_ms,
+ stream_position_ms,
+ is_explicit,
+ },
+ };
+ }
+ _ => {
+ error!("Called playing_to_end_of_track in non-playing state: {new_state:?}");
+ exit(1);
+ }
+ }
+ }
+
+ fn paused_to_playing(&mut self) {
+ use self::PlayerState::*;
+ let new_state = mem::replace(self, Invalid);
+ match new_state {
+ Paused {
+ track_id,
+ play_request_id,
+ decoder,
+ audio_item,
+ normalisation_data,
+ normalisation_factor,
+ stream_loader_controller,
+ duration_ms,
+ bytes_per_second,
+ stream_position_ms,
+ suggested_to_preload_next_track,
+ is_explicit,
+ } => {
+ *self = Playing {
+ track_id,
+ play_request_id,
+ decoder,
+ audio_item,
+ normalisation_data,
+ normalisation_factor,
+ stream_loader_controller,
+ duration_ms,
+ bytes_per_second,
+ stream_position_ms,
+ reported_nominal_start_time: Instant::now()
+ .checked_sub(Duration::from_millis(stream_position_ms as u64)),
+ suggested_to_preload_next_track,
+ is_explicit,
+ };
+ }
+ _ => {
+ error!("PlayerState::paused_to_playing in invalid state: {new_state:?}");
+ exit(1);
+ }
+ }
+ }
+
+ fn playing_to_paused(&mut self) {
+ use self::PlayerState::*;
+ let new_state = mem::replace(self, Invalid);
+ match new_state {
+ Playing {
+ track_id,
+ play_request_id,
+ decoder,
+ audio_item,
+ normalisation_data,
+ normalisation_factor,
+ stream_loader_controller,
+ duration_ms,
+ bytes_per_second,
+ stream_position_ms,
+ suggested_to_preload_next_track,
+ is_explicit,
+ ..
+ } => {
+ *self = Paused {
+ track_id,
+ play_request_id,
+ decoder,
+ audio_item,
+ normalisation_data,
+ normalisation_factor,
+ stream_loader_controller,
+ duration_ms,
+ bytes_per_second,
+ stream_position_ms,
+ suggested_to_preload_next_track,
+ is_explicit,
+ };
+ }
+ _ => {
+ error!("PlayerState::playing_to_paused in invalid state: {new_state:?}");
+ exit(1);
+ }
+ }
+ }
+}
+
+struct PlayerTrackLoader {
+ session: Session,
+ config: PlayerConfig,
+ local_file_lookup: Arc<LocalFileLookup>,
+}
+
+impl PlayerTrackLoader {
+ async fn find_available_alternative(&self, audio_item: AudioItem) -> Option<AudioItem> {
+ if let Err(e) = audio_item.availability {
+ error!("Track is unavailable: {e}");
+ None
+ } else if !audio_item.files.is_empty() {
+ Some(audio_item)
+ } else if let Some(alternatives) = audio_item.alternatives {
+ let Tracks(alternatives_vec) = alternatives; // required to make `into_iter` able to move
+
+ let alternatives: FuturesUnordered<_> = alternatives_vec
+ .into_iter()
+ .map(|alt_id| AudioItem::get_file(&self.session, alt_id))
+ .collect();
+
+ alternatives
+ .filter_map(|x| future::ready(x.ok()))
+ .filter(|x| future::ready(x.availability.is_ok()))
+ .next()
+ .await
+ } else {
+ error!("Track should be available, but no alternatives found.");
+ None
+ }
+ }
+
+ fn stream_data_rate(&self, format: AudioFileFormat) -> Option<usize> {
+ let kbps = match format {
+ AudioFileFormat::OGG_VORBIS_96 => 12.,
+ AudioFileFormat::OGG_VORBIS_160 => 20.,
+ AudioFileFormat::OGG_VORBIS_320 => 40.,
+ AudioFileFormat::MP3_256 => 32.,
+ AudioFileFormat::MP3_320 => 40.,
+ AudioFileFormat::MP3_160 => 20.,
+ AudioFileFormat::MP3_96 => 12.,
+ AudioFileFormat::MP3_160_ENC => 20.,
+ AudioFileFormat::AAC_24 => 3.,
+ AudioFileFormat::AAC_48 => 6.,
+ AudioFileFormat::AAC_160 => 20.,
+ AudioFileFormat::AAC_320 => 40.,
+ AudioFileFormat::MP4_128 => 16.,
+ AudioFileFormat::OTHER5 => 40.,
+ AudioFileFormat::FLAC_FLAC => 112., // assume 900 kbit/s on average
+ AudioFileFormat::XHE_AAC_12 => 1.5,
+ AudioFileFormat::XHE_AAC_16 => 2.,
+ AudioFileFormat::XHE_AAC_24 => 3.,
+ AudioFileFormat::FLAC_FLAC_24BIT => 3.,
+ };
+ let data_rate: f32 = kbps * 1024.;
+ Some(data_rate.ceil() as usize)
+ }
+
+ async fn load_track(
+ &self,
+ track_uri: SpotifyUri,
+ position_ms: u32,
+ ) -> Option<PlayerLoadedTrackData> {
+ match track_uri {
+ SpotifyUri::Track { .. } | SpotifyUri::Episode { .. } => {
+ self.load_remote_track(track_uri, position_ms).await
+ }
+ SpotifyUri::Local { .. } => self.load_local_track(track_uri, position_ms).await,
+ _ => {
+ error!("Cannot handle load of track with URI: <{track_uri}>",);
+ None
+ }
+ }
+ }
+
+ async fn load_remote_track(
+ &self,
+ track_uri: SpotifyUri,
+ position_ms: u32,
+ ) -> Option<PlayerLoadedTrackData> {
+ let track_id: SpotifyId = match (&track_uri).try_into() {
+ Ok(id) => id,
+ Err(_) => {
+ warn!("<{track_uri}> could not be converted to a base62 ID");
+ return None;
+ }
+ };
+
+ let audio_item = match AudioItem::get_file(&self.session, track_uri).await {
+ Ok(audio) => match self.find_available_alternative(audio).await {
+ Some(audio) => audio,
+ None => {
+ warn!(
+ "spotify:track:<{}> is not available",
+ track_id.to_base62().unwrap_or_default()
+ );
+ return None;
+ }
+ },
+ Err(e) => {
+ error!("Unable to load audio item: {e:?}");
+ return None;
+ }
+ };
+
+ info!(
+ "Loading <{}> with Spotify URI <{}>",
+ audio_item.name, audio_item.uri
+ );
+
+ // (Most) podcasts seem to support only 96 kbps Ogg Vorbis, so fall back to it
+ let formats = match self.config.bitrate {
+ Bitrate::Bitrate96 => [
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ ],
+ Bitrate::Bitrate160 => [
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ ],
+ Bitrate::Bitrate320 => [
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ ],
+ };
+
+ let (format, file_id) =
+ match formats
+ .iter()
+ .find_map(|format| match audio_item.files.get(format) {
+ Some(&file_id) => Some((*format, file_id)),
+ _ => None,
+ }) {
+ Some(t) => t,
+ None => {
+ warn!(
+ "<{}> is not available in any supported format",
+ audio_item.name
+ );
+ return None;
+ }
+ };
+
+ let bytes_per_second = self.stream_data_rate(format)?;
+
+ // This is only a loop to be able to reload the file if an error occurred
+ // while opening a cached file.
+ loop {
+ let encrypted_file = AudioFile::open(&self.session, file_id, bytes_per_second);
+
+ let encrypted_file = match encrypted_file.await {
+ Ok(encrypted_file) => encrypted_file,
+ Err(e) => {
+ error!("Unable to load encrypted file: {e:?}");
+ return None;
+ }
+ };
+
+ let is_cached = encrypted_file.is_cached();
+
+ let stream_loader_controller = encrypted_file.get_stream_loader_controller().ok()?;
+
+ // Not all audio files are encrypted. If we can't get a key, try loading the track
+ // without decryption. If the file was encrypted after all, the decoder will fail
+ // parsing and bail out, so we should be safe from outputting ear-piercing noise.
+ let key = match self.session.audio_key().request(track_id, file_id).await {
+ Ok(key) => Some(key),
+ Err(e) => {
+ warn!("Unable to load key, continuing without decryption: {e}");
+ None
+ }
+ };
+
+ let mut decrypted_file = AudioDecrypt::new(key, encrypted_file);
+
+ let is_ogg_vorbis = AudioFiles::is_ogg_vorbis(format);
+ let (offset, mut normalisation_data) = if is_ogg_vorbis {
+ // Spotify stores normalisation data in a custom Ogg packet instead of Vorbis comments.
+ let normalisation_data =
+ NormalisationData::parse_from_ogg(&mut decrypted_file).ok();
+ (SPOTIFY_OGG_HEADER_END, normalisation_data)
+ } else {
+ (0, None)
+ };
+
+ let audio_file = match Subfile::new(
+ decrypted_file,
+ offset,
+ stream_loader_controller.len() as u64,
+ ) {
+ Ok(audio_file) => audio_file,
+ Err(e) => {
+ error!("PlayerTrackLoader::load_track error opening subfile: {e}");
+ return None;
+ }
+ };
+
+ let mut symphonia_decoder = |audio_file, format| {
+ SymphoniaDecoder::new(audio_file, format).map(|mut decoder| {
+ // For formats other that Vorbis, we'll try getting normalisation data from
+ // ReplayGain metadata fields, if present.
+ if normalisation_data.is_none() {
+ normalisation_data = decoder.normalisation_data();
+ }
+ Box::new(decoder) as Decoder
+ })
+ };
+
+ let mut hint = Hint::new();
+ if let Some(mime_type) = AudioFiles::mime_type(format) {
+ hint.mime_type(mime_type);
+ }
+
+ #[cfg(feature = "passthrough-decoder")]
+ let decoder_type = if self.config.passthrough {
+ PassthroughDecoder::new(audio_file, format).map(|x| Box::new(x) as Decoder)
+ } else {
+ symphonia_decoder(audio_file, hint)
+ };
+
+ #[cfg(not(feature = "passthrough-decoder"))]
+ let decoder_type = { symphonia_decoder(audio_file, hint) };
+
+ let normalisation_data = normalisation_data.unwrap_or_else(|| {
+ warn!("Unable to get normalisation data, continuing with defaults.");
+ NormalisationData::default()
+ });
+
+ let mut decoder = match decoder_type {
+ Ok(decoder) => decoder,
+ Err(e) if is_cached => {
+ warn!("Unable to read cached audio file: {e}. Trying to download it.");
+
+ match self.session.cache() {
+ Some(cache) => {
+ if cache.remove_file(file_id).is_err() {
+ error!("Error removing file from cache");
+ return None;
+ }
+ }
+ None => {
+ error!("If the audio file is cached, a cache should exist");
+ return None;
+ }
+ }
+
+ // Just try it again
+ continue;
+ }
+ Err(e) => {
+ error!("Unable to read audio file: {e}");
+ return None;
+ }
+ };
+
+ let duration_ms = audio_item.duration_ms;
+ // Don't try to seek past the track's duration.
+ // If the position is invalid just start from
+ // the beginning of the track.
+ let position_ms = if position_ms > duration_ms {
+ warn!(
+ "Invalid start position of {position_ms} ms exceeds track's duration of {duration_ms} ms, starting track from the beginning"
+ );
+ 0
+ } else {
+ position_ms
+ };
+
+ // Ensure the starting position. Even when we want to play from the beginning,
+ // the cursor may have been moved by parsing normalisation data. This may not
+ // matter for playback (but won't hurt either), but may be useful for the
+ // passthrough decoder.
+ let stream_position_ms = match decoder.seek(position_ms) {
+ Ok(new_position_ms) => new_position_ms,
+ Err(e) => {
+ error!(
+ "PlayerTrackLoader::load_track error seeking to starting position {position_ms}: {e}"
+ );
+ return None;
+ }
+ };
+
+ // Ensure streaming mode now that we are ready to play from the requested position.
+ stream_loader_controller.set_stream_mode();
+
+ let is_explicit = audio_item.is_explicit;
+
+ info!("<{}> ({} ms) loaded", audio_item.name, duration_ms);
+
+ return Some(PlayerLoadedTrackData {
+ decoder,
+ normalisation_data,
+ stream_loader_controller,
+ audio_item,
+ bytes_per_second,
+ duration_ms,
+ stream_position_ms,
+ is_explicit,
+ });
+ }
+ }
+
+ async fn load_local_track(
+ &self,
+ track_uri: SpotifyUri,
+ position_ms: u32,
+ ) -> Option<PlayerLoadedTrackData> {
+ info!("Loading local file with Spotify URI <{}>", track_uri);
+
+ let SpotifyUri::Local { duration, .. } = track_uri else {
+ error!("Unable to determine track duration for local file: not a local file URI");
+ return None;
+ };
+
+ let entry = self.local_file_lookup.get(&track_uri);
+
+ let Some(path) = entry else {
+ error!("Unable to find file path for local file <{track_uri}>");
+ return None;
+ };
+
+ let src = match File::open(path) {
+ Ok(src) => src,
+ Err(e) => {
+ error!("Failed to open local file: {e}");
+ return None;
+ }
+ };
+
+ let mut hint = Hint::new();
+ if let Some(file_extension) = path.extension().and_then(|e| e.to_str()) {
+ hint.with_extension(file_extension);
+ }
+
+ let decoder = match SymphoniaDecoder::new(src, hint) {
+ Ok(decoder) => decoder,
+ Err(e) => {
+ error!("Error decoding local file: {e}");
+ return None;
+ }
+ };
+
+ let mut decoder = Box::new(decoder);
+ let normalisation_data = decoder.normalisation_data().unwrap_or_else(|| {
+ warn!("Unable to get normalisation data, continuing with defaults.");
+ NormalisationData::default()
+ });
+
+ let local_file_metadata = decoder.local_file_metadata().unwrap_or_default();
+
+ let stream_position_ms = match decoder.seek(position_ms) {
+ Ok(new_position_ms) => new_position_ms,
+ Err(e) => {
+ error!(
+ "PlayerTrackLoader::load_local_track error seeking to starting position {position_ms}: {e}"
+ );
+ return None;
+ }
+ };
+
+ let file_size = fs::metadata(path).ok()?.len();
+ let bytes_per_second = (file_size / duration.as_secs()) as usize;
+
+ let stream_loader_controller = StreamLoaderController::from_local_file(file_size);
+
+ let name = local_file_metadata.name.unwrap_or_default();
+
+ info!("Loaded <{name}> from path <{}>", path.display());
+
+ Some(PlayerLoadedTrackData {
+ decoder,
+ normalisation_data,
+ stream_loader_controller,
+ bytes_per_second,
+ duration_ms: duration.as_millis() as u32,
+ stream_position_ms,
+ is_explicit: false,
+ audio_item: AudioItem {
+ duration_ms: duration.as_millis() as u32,
+ uri: track_uri.to_uri().unwrap_or_default(),
+ track_id: track_uri,
+ files: Default::default(),
+ name,
+ // We can't get a CoverImage.URL for the track image, applications will have to parse the file metadata themselves using unique_fields.path
+ covers: vec![],
+ language: local_file_metadata
+ .language
+ .map(|val| vec![val])
+ .unwrap_or_default(),
+ is_explicit: false,
+ availability: Ok(()),
+ alternatives: None,
+ unique_fields: UniqueFields::Local {
+ artists: local_file_metadata.artists,
+ album: local_file_metadata.album,
+ album_artists: local_file_metadata.album_artists,
+ number: local_file_metadata.number,
+ disc_number: local_file_metadata.disc_number,
+ path: path.to_path_buf(),
+ },
+ },
+ })
+ }
+}
+
+impl Future for PlayerInternal {
+ type Output = ();
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
+ // While this is written as a future, it still contains blocking code.
+ // It must be run on its own thread.
+ let passthrough = self.config.passthrough;
+
+ loop {
+ let mut all_futures_completed_or_not_ready = true;
+
+ // process commands that were sent to us
+ let cmd = match self.commands.poll_recv(cx) {
+ Poll::Ready(None) => return Poll::Ready(()), // client has disconnected - shut down.
+ Poll::Ready(Some(cmd)) => {
+ all_futures_completed_or_not_ready = false;
+ Some(cmd)
+ }
+ _ => None,
+ };
+
+ if let Some(cmd) = cmd {
+ if let Err(e) = self.handle_command(cmd) {
+ error!("Error handling command: {e}");
+ }
+ }
+
+ // Handle loading of a new track to play
+ if let PlayerState::Loading {
+ ref mut loader,
+ ref track_id,
+ start_playback,
+ play_request_id,
+ } = self.state
+ {
+ // The loader may be terminated if we are trying to load the same track
+ // as before, and that track failed to open before.
+ let track_id = track_id.clone();
+
+ if !loader.as_mut().is_terminated() {
+ match loader.as_mut().poll(cx) {
+ Poll::Ready(Ok(loaded_track)) => {
+ self.start_playback(
+ track_id,
+ play_request_id,
+ loaded_track,
+ start_playback,
+ );
+ if let PlayerState::Loading { .. } = self.state {
+ error!("The state wasn't changed by start_playback()");
+ exit(1);
+ }
+ }
+ Poll::Ready(Err(e)) => {
+ error!(
+ "Skipping to next track, unable to load track <{track_id:?}>: {e:?}"
+ );
+ self.send_event(PlayerEvent::Unavailable {
+ track_id,
+ play_request_id,
+ })
+ }
+ Poll::Pending => (),
+ }
+ }
+ }
+
+ // handle pending preload requests.
+ if let PlayerPreload::Loading {
+ ref mut loader,
+ ref track_id,
+ } = self.preload
+ {
+ let track_id = track_id.clone();
+ match loader.as_mut().poll(cx) {
+ Poll::Ready(Ok(loaded_track)) => {
+ self.send_event(PlayerEvent::Preloading {
+ track_id: track_id.clone(),
+ });
+ self.preload = PlayerPreload::Ready {
+ track_id,
+ loaded_track: Box::new(loaded_track),
+ };
+ }
+ Poll::Ready(Err(_)) => {
+ debug!("Unable to preload {track_id:?}");
+ self.preload = PlayerPreload::None;
+ // Let Spirc know that the track was unavailable.
+ if let PlayerState::Playing {
+ play_request_id, ..
+ }
+ | PlayerState::Paused {
+ play_request_id, ..
+ } = self.state
+ {
+ self.send_event(PlayerEvent::Unavailable {
+ track_id,
+ play_request_id,
+ });
+ }
+ }
+ Poll::Pending => (),
+ }
+ }
+
+ if self.state.is_playing() {
+ self.ensure_sink_running();
+
+ if let PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ ref mut decoder,
+ normalisation_factor,
+ ref mut stream_position_ms,
+ ref mut reported_nominal_start_time,
+ ..
+ } = self.state
+ {
+ let track_id = track_id.clone();
+ match decoder.next_packet() {
+ Ok(result) => {
+ if let Some((ref packet_position, ref packet)) = result {
+ let new_stream_position_ms = packet_position.position_ms;
+ let expected_position_ms = std::mem::replace(
+ &mut *stream_position_ms,
+ new_stream_position_ms,
+ );
+
+ if !passthrough {
+ match packet.samples() {
+ Ok(_) => {
+ let new_stream_position = Duration::from_millis(
+ new_stream_position_ms as u64,
+ );
+
+ let now = Instant::now();
+
+ // Only notify if we're skipped some packets *or* we are behind.
+ // If we're ahead it's probably due to a buffer of the backend
+ // and we're actually in time.
+ let notify_about_position =
+ match *reported_nominal_start_time {
+ None => true,
+ Some(reported_nominal_start_time) => {
+ let mut notify = false;
+
+ if packet_position.skipped {
+ if let Some(ahead) = new_stream_position
+ .checked_sub(Duration::from_millis(
+ expected_position_ms as u64,
+ ))
+ {
+ notify |=
+ ahead >= Duration::from_secs(1)
+ }
+ }
+
+ if let Some(lag) = now
+ .checked_duration_since(
+ reported_nominal_start_time,
+ )
+ {
+ if let Some(lag) =
+ lag.checked_sub(new_stream_position)
+ {
+ notify |=
+ lag >= Duration::from_secs(1)
+ }
+ }
+
+ notify
+ }
+ };
+
+ if notify_about_position {
+ *reported_nominal_start_time =
+ now.checked_sub(new_stream_position);
+ self.send_event(PlayerEvent::PositionCorrection {
+ play_request_id,
+ track_id: track_id.clone(),
+ position_ms: new_stream_position_ms,
+ });
+ }
+
+ if let Some(interval) =
+ self.config.position_update_interval
+ {
+ let last_progress_update_since_ms =
+ now.duration_since(self.last_progress_update);
+
+ if last_progress_update_since_ms > interval {
+ self.last_progress_update = now;
+ self.send_event(PlayerEvent::PositionChanged {
+ play_request_id,
+ track_id,
+ position_ms: new_stream_position_ms,
+ });
+ }
+ }
+ }
+ Err(e) => {
+ error!(
+ "Skipping to next track, unable to decode samples for track <{track_id:?}>: {e:?}"
+ );
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id,
+ play_request_id,
+ })
+ }
+ }
+ }
+ }
+
+ self.handle_packet(result, normalisation_factor);
+ }
+ Err(e) => {
+ error!(
+ "Skipping to next track, unable to get next packet for track <{track_id:?}>: {e:?}"
+ );
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id,
+ play_request_id,
+ })
+ }
+ }
+ } else {
+ error!("PlayerInternal poll: Invalid PlayerState");
+ exit(1);
+ };
+ }
+
+ if let PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ duration_ms,
+ stream_position_ms,
+ ref mut stream_loader_controller,
+ ref mut suggested_to_preload_next_track,
+ ..
+ }
+ | PlayerState::Paused {
+ ref track_id,
+ play_request_id,
+ duration_ms,
+ stream_position_ms,
+ ref mut stream_loader_controller,
+ ref mut suggested_to_preload_next_track,
+ ..
+ } = self.state
+ {
+ let track_id = track_id.clone();
+
+ if (!*suggested_to_preload_next_track)
+ && ((duration_ms as i64 - stream_position_ms as i64)
+ < PRELOAD_NEXT_TRACK_BEFORE_END_DURATION_MS as i64)
+ && stream_loader_controller.range_to_end_available()
+ {
+ *suggested_to_preload_next_track = true;
+ self.send_event(PlayerEvent::TimeToPreloadNextTrack {
+ track_id: track_id.clone(),
+ play_request_id,
+ });
+ }
+
+ // LOCAL PATCH: ask for the next track early, so it is already
+ // playing while this one fades out.
+ //
+ // The end of a track is announced a crossfade's length before
+ // it arrives. Whoever owns the queue answers with a load, the
+ // usual way, and that load is what starts the fade: the decoder
+ // still reading this track is handed to `fade_out` instead of
+ // being dropped. Nothing here decides what plays next, which is
+ // what keeps the Connect device the only thing that does.
+ let crossfade_ms = self.config.crossfade_duration_ms as i64;
+ if crossfade_ms > 0
+ && self.early_end != Some(play_request_id)
+ && self.state.is_playing()
+ && duration_ms > 0
+ && (duration_ms as i64 - stream_position_ms as i64) <= crossfade_ms
+ {
+ self.early_end = Some(play_request_id);
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id,
+ play_request_id,
+ });
+ }
+ }
+
+ if (!self.state.is_playing()) && all_futures_completed_or_not_ready {
+ return Poll::Pending;
+ }
+ }
+ }
+}
+
+impl PlayerInternal {
+ fn ensure_sink_running(&mut self) {
+ if self.sink_status != SinkStatus::Running {
+ trace!("== Starting sink ==");
+ if let Some(callback) = &mut self.sink_event_callback {
+ callback(SinkStatus::Running);
+ }
+ match self.sink.start() {
+ Ok(()) => self.sink_status = SinkStatus::Running,
+ Err(e) => {
+ error!("{e}");
+ self.handle_pause();
+ }
+ }
+ }
+ }
+
+ fn ensure_sink_stopped(&mut self, temporarily: bool) {
+ match self.sink_status {
+ SinkStatus::Running => {
+ trace!("== Stopping sink ==");
+ match self.sink.stop() {
+ Ok(()) => {
+ self.sink_status = if temporarily {
+ SinkStatus::TemporarilyClosed
+ } else {
+ SinkStatus::Closed
+ };
+ if let Some(callback) = &mut self.sink_event_callback {
+ callback(self.sink_status);
+ }
+ }
+ Err(e) => {
+ error!("{e}");
+ exit(1);
+ }
+ }
+ }
+ SinkStatus::TemporarilyClosed => {
+ if !temporarily {
+ self.sink_status = SinkStatus::Closed;
+ if let Some(callback) = &mut self.sink_event_callback {
+ callback(SinkStatus::Closed);
+ }
+ }
+ }
+ SinkStatus::Closed => (),
+ }
+ }
+
+ /// LOCAL PATCH: how long a crossfade lasts, in interleaved samples.
+ fn crossfade_samples(&self) -> usize {
+ let ms = self.config.crossfade_duration_ms as usize;
+ if ms == 0 {
+ return 0;
+ }
+ let samples = ms * SAMPLE_RATE as usize / 1000 * NUM_CHANNELS as usize;
+ // Whole frames only: half a frame would swap the channels over for the
+ // rest of the fade.
+ samples - samples % NUM_CHANNELS as usize
+ }
+
+ /// LOCAL PATCH: moves the track being replaced into the outgoing half of a
+ /// crossfade, if there is one and crossfading is on.
+ fn begin_fade_out(&mut self) {
+ let total = self.crossfade_samples();
+ if total == 0 {
+ self.fade_out = None;
+ return;
+ }
+
+ // Only the track that announced its own end fades out.
+ //
+ // A fade is what the end of a track sounds like, and a skip is not the
+ // end of a track: it is a listener saying they have heard enough. Every
+ // load arrives here the same way, whoever asked for it, so the two are
+ // told apart by `early_end`, which names the one play request that was
+ // reported as finishing before it had.
+ let expected = self.early_end.take();
+ let previous = mem::replace(&mut self.state, PlayerState::Invalid);
+ match previous {
+ PlayerState::Playing {
+ decoder,
+ normalisation_factor,
+ play_request_id,
+ ..
+ } if expected == Some(play_request_id) => {
+ self.fade_out = Some(FadeOut {
+ decoder,
+ normalisation_factor,
+ total,
+ done: 0,
+ spare: std::collections::VecDeque::new(),
+ drained: false,
+ });
+ }
+ // Nothing was playing: put the state back and leave the caller to
+ // replace it as it would have anyway.
+ other => {
+ self.state = other;
+ self.fade_out = None;
+ }
+ }
+ }
+
+ /// LOCAL PATCH: mixes the outgoing track under `data` and fades `data` up.
+ ///
+ /// Equal power, not a straight line: two straight ramps summed dip in the
+ /// middle, where both tracks are at half, while cos and sin square to one
+ /// and hold the loudness steady across the whole overlap.
+ ///
+ /// The result is clamped just under full scale. Two tracks played at once
+ /// can exceed it between them, and what comes out of an overflow is a click
+ /// rather than a loud moment.
+ fn apply_fade(&mut self, data: &mut [f64]) {
+ let volume = self.volume_getter.attenuation_factor();
+ let channels = NUM_CHANNELS as usize;
+
+ let Some(fade) = self.fade_out.as_mut() else {
+ return;
+ };
+
+ let mut offset = 0;
+ while offset + channels <= data.len() && fade.done < fade.total {
+ // Enough of the outgoing track for this frame, decoded on demand.
+ while fade.spare.len() < channels && !fade.drained {
+ match fade.decoder.next_packet() {
+ Ok(Some((_, packet))) => match packet.samples() {
+ Ok(samples) => fade.spare.extend(samples.iter().copied()),
+ Err(_) => fade.drained = true,
+ },
+ // Ran out before the fade did: the incoming track goes on
+ // rising, over silence rather than over music.
+ Ok(None) => fade.drained = true,
+ Err(e) => {
+ debug!("crossfade: the outgoing track stopped early: {e}");
+ fade.drained = true;
+ }
+ }
+ }
+
+ let x = fade.done as f64 / fade.total as f64;
+ let gain_in = (x * std::f64::consts::FRAC_PI_2).sin();
+ let gain_out = (x * std::f64::consts::FRAC_PI_2).cos();
+
+ for sample in data.iter_mut().skip(offset).take(channels) {
+ let tail = fade.spare.pop_front().unwrap_or(0.0);
+ let mixed = *sample * gain_in
+ + tail * gain_out * fade.normalisation_factor * volume;
+ *sample = mixed.clamp(-1.0, MAX_SAMPLE);
+ }
+
+ fade.done += channels;
+ offset += channels;
+ }
+
+ if fade.done >= fade.total {
+ // Dropping it closes the outgoing stream.
+ self.fade_out = None;
+ }
+ }
+
+ fn handle_player_stop(&mut self) {
+ // LOCAL PATCH: nothing is being faded into any more.
+ self.fade_out = None;
+ match self.state {
+ PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ ..
+ }
+ | PlayerState::Paused {
+ ref track_id,
+ play_request_id,
+ ..
+ }
+ | PlayerState::EndOfTrack {
+ ref track_id,
+ play_request_id,
+ ..
+ }
+ | PlayerState::Loading {
+ ref track_id,
+ play_request_id,
+ ..
+ } => {
+ let track_id = track_id.clone();
+
+ self.ensure_sink_stopped(false);
+ self.send_event(PlayerEvent::Stopped {
+ track_id,
+ play_request_id,
+ });
+ self.state = PlayerState::Stopped;
+ }
+ PlayerState::Stopped => (),
+ PlayerState::Invalid => {
+ error!("PlayerInternal::handle_player_stop in invalid state");
+ exit(1);
+ }
+ }
+ }
+
+ fn handle_play(&mut self) {
+ match self.state {
+ PlayerState::Paused {
+ ref track_id,
+ play_request_id,
+ stream_position_ms,
+ ..
+ } => {
+ let track_id = track_id.clone();
+
+ self.state.paused_to_playing();
+ self.send_event(PlayerEvent::Playing {
+ track_id,
+ play_request_id,
+ position_ms: stream_position_ms,
+ });
+ self.ensure_sink_running();
+ }
+ PlayerState::Loading {
+ ref mut start_playback,
+ ..
+ } => {
+ *start_playback = true;
+ }
+ _ => error!("Player::play called from invalid state: {:?}", self.state),
+ }
+ }
+
+ fn handle_pause(&mut self) {
+ match self.state {
+ PlayerState::Paused { .. } => self.ensure_sink_stopped(false),
+ PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ stream_position_ms,
+ ..
+ } => {
+ let track_id = track_id.clone();
+
+ self.state.playing_to_paused();
+
+ self.ensure_sink_stopped(false);
+ self.send_event(PlayerEvent::Paused {
+ track_id,
+ play_request_id,
+ position_ms: stream_position_ms,
+ });
+ }
+ PlayerState::Loading {
+ ref mut start_playback,
+ ..
+ } => {
+ *start_playback = false;
+ }
+ _ => error!("Player::pause called from invalid state: {:?}", self.state),
+ }
+ }
+
+ fn handle_packet(
+ &mut self,
+ packet: Option<(AudioPacketPosition, AudioPacket)>,
+ normalisation_factor: f64,
+ ) {
+ match packet {
+ Some((_, mut packet)) => {
+ if !packet.is_empty() {
+ if let AudioPacket::Samples(ref mut data) = packet {
+ // Get the volume for the packet. In the case of hardware volume control
+ // this will always be 1.0 (no change).
+ let volume = self.volume_getter.attenuation_factor();
+
+ // For the basic normalisation method, a normalisation factor of 1.0
+ // indicates that there is nothing to normalise (all samples should pass
+ // unaltered). For the dynamic method, there may still be peaks that we
+ // want to shave off.
+ //
+ // No matter the case we apply volume attenuation last if there is any.
+ match (self.config.normalisation, self.config.normalisation_method) {
+ (false, _) => {
+ if volume < 1.0 {
+ for sample in data.iter_mut() {
+ *sample *= volume;
+ }
+ }
+ }
+ (true, NormalisationMethod::Dynamic) => {
+ // zero-cost shorthands
+ let threshold_db = self.config.normalisation_threshold_dbfs;
+ let knee_db = self.config.normalisation_knee_db;
+ let attack_cf = self.config.normalisation_attack_cf;
+ let release_cf = self.config.normalisation_release_cf;
+
+ for sample in data.iter_mut() {
+ // Feedforward limiter in the log domain
+ // After: Giannoulis, D., Massberg, M., & Reiss, J.D. (2012).
+ // Digital Dynamic Range Compressor Design—A Tutorial and
+ // Analysis. Journal of The Audio Engineering Society, 60,
+ // 399-408.
+
+ // This implementation assumes audio is stereo.
+
+ // step 0: apply gain stage
+ *sample *= normalisation_factor;
+
+ // step 1-4: half-wave rectification and conversion into dB, and
+ // gain computer with soft knee and subtractor
+ let limiter_db = {
+ // Add slight DC offset. Some samples are silence, which is
+ // -inf dB and gets the limiter stuck. Adding a small
+ // positive offset prevents this.
+ *sample += f64::MIN_POSITIVE;
+
+ let bias_db = ratio_to_db(sample.abs()) - threshold_db;
+ let knee_boundary_db = bias_db * 2.0;
+ if knee_boundary_db < -knee_db {
+ 0.0
+ } else if knee_boundary_db.abs() <= knee_db {
+ let term = knee_boundary_db + knee_db;
+ term * term * self.normalisation_knee_factor
+ } else {
+ bias_db
+ }
+ };
+
+ // track left/right channel
+ let channel = self.normalisation_channel;
+ self.normalisation_channel ^= 1;
+
+ // step 5: smooth, decoupled peak detector for each channel
+ // Use direct references to reduce repeated array indexing
+ let integrator = &mut self.normalisation_integrators[channel];
+ let peak = &mut self.normalisation_peaks[channel];
+
+ *integrator = f64::max(
+ limiter_db,
+ release_cf * *integrator + (1.0 - release_cf) * limiter_db,
+ );
+ *peak = attack_cf * *peak + (1.0 - attack_cf) * *integrator;
+
+ // steps 6-8: conversion into level and multiplication into gain
+ // stage. Find maximum peak across both channels to couple the
+ // gain and maintain stereo imaging.
+ let max_peak = f64::max(
+ self.normalisation_peaks[0],
+ self.normalisation_peaks[1],
+ );
+ *sample *= db_to_ratio(-max_peak) * volume;
+ }
+ }
+ (true, NormalisationMethod::Basic) => {
+ if normalisation_factor < 1.0 || volume < 1.0 {
+ for sample in data.iter_mut() {
+ *sample *= normalisation_factor * volume;
+ }
+ }
+ }
+ }
+ }
+
+ // LOCAL PATCH: the outgoing track, mixed under this one.
+ //
+ // Here rather than earlier because both sides have to be at the
+ // level they would have played at on their own: normalisation
+ // and volume are applied above, and a fade that ran before them
+ // would be a fade between two tracks nobody is hearing yet.
+ if self.fade_out.is_some() {
+ if let AudioPacket::Samples(ref mut data) = packet {
+ self.apply_fade(data);
+ }
+ }
+
+ if let Err(e) = self.sink.write(packet, &mut self.converter) {
+ error!("{e}");
+ self.handle_pause();
+ }
+ }
+ }
+
+ None => {
+ self.state.playing_to_end_of_track();
+ if let PlayerState::EndOfTrack {
+ ref track_id,
+ play_request_id,
+ ..
+ } = self.state
+ {
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id: track_id.clone(),
+ play_request_id,
+ })
+ } else {
+ error!("PlayerInternal handle_packet: Invalid PlayerState");
+ exit(1);
+ }
+ }
+ }
+ }
+
+ fn start_playback(
+ &mut self,
+ track_id: SpotifyUri,
+ play_request_id: u64,
+ loaded_track: PlayerLoadedTrackData,
+ start_playback: bool,
+ ) {
+ let audio_item = Box::new(loaded_track.audio_item.clone());
+
+ self.send_event(PlayerEvent::TrackChanged { audio_item });
+
+ let position_ms = loaded_track.stream_position_ms;
+
+ let mut config = self.config.clone();
+ if config.normalisation_type == NormalisationType::Auto {
+ if self.auto_normalise_as_album {
+ config.normalisation_type = NormalisationType::Album;
+ } else {
+ config.normalisation_type = NormalisationType::Track;
+ }
+ };
+ let normalisation_factor =
+ NormalisationData::get_factor(&config, loaded_track.normalisation_data);
+
+ // LOCAL PATCH: keep the track being replaced audible for the length of
+ // the crossfade. Only when one really is playing: a load from stopped,
+ // or a seek within the same track, has nothing to fade out of.
+ if start_playback {
+ self.begin_fade_out();
+ } else {
+ self.fade_out = None;
+ }
+
+ if start_playback {
+ self.ensure_sink_running();
+ self.send_event(PlayerEvent::Playing {
+ track_id: track_id.clone(),
+ play_request_id,
+ position_ms,
+ });
+
+ self.state = PlayerState::Playing {
+ track_id,
+ play_request_id,
+ decoder: loaded_track.decoder,
+ audio_item: loaded_track.audio_item,
+ normalisation_data: loaded_track.normalisation_data,
+ normalisation_factor,
+ stream_loader_controller: loaded_track.stream_loader_controller,
+ duration_ms: loaded_track.duration_ms,
+ bytes_per_second: loaded_track.bytes_per_second,
+ stream_position_ms: loaded_track.stream_position_ms,
+ reported_nominal_start_time: Instant::now()
+ .checked_sub(Duration::from_millis(position_ms as u64)),
+ suggested_to_preload_next_track: false,
+ is_explicit: loaded_track.is_explicit,
+ };
+ } else {
+ self.ensure_sink_stopped(false);
+
+ self.state = PlayerState::Paused {
+ track_id: track_id.clone(),
+ play_request_id,
+ decoder: loaded_track.decoder,
+ audio_item: loaded_track.audio_item,
+ normalisation_data: loaded_track.normalisation_data,
+ normalisation_factor,
+ stream_loader_controller: loaded_track.stream_loader_controller,
+ duration_ms: loaded_track.duration_ms,
+ bytes_per_second: loaded_track.bytes_per_second,
+ stream_position_ms: loaded_track.stream_position_ms,
+ suggested_to_preload_next_track: false,
+ is_explicit: loaded_track.is_explicit,
+ };
+
+ self.send_event(PlayerEvent::Paused {
+ track_id,
+ play_request_id,
+ position_ms,
+ });
+ }
+ }
+
+ fn handle_command_load(
+ &mut self,
+ track_id: SpotifyUri,
+ play_request_id_option: Option<u64>,
+ play: bool,
+ position_ms: u32,
+ ) -> PlayerResult {
+ let play_request_id =
+ play_request_id_option.unwrap_or(self.play_request_id_generator.get());
+
+ self.send_event(PlayerEvent::PlayRequestIdChanged { play_request_id });
+
+ if !self.config.gapless {
+ self.ensure_sink_stopped(play);
+ }
+
+ if matches!(self.state, PlayerState::Invalid) {
+ return Err(Error::internal(format!(
+ "Player::handle_command_load called from invalid state: {:?}",
+ self.state
+ )));
+ }
+
+ // Now we check at different positions whether we already have a pre-loaded version
+ // of this track somewhere. If so, use it and return.
+
+ // Check if there's a matching loaded track in the EndOfTrack player state.
+ // This is the case if we're repeating the same track again.
+ if let PlayerState::EndOfTrack {
+ track_id: previous_track_id,
+ ..
+ } = &self.state
+ {
+ if *previous_track_id == track_id {
+ let mut loaded_track = match mem::replace(&mut self.state, PlayerState::Invalid) {
+ PlayerState::EndOfTrack { loaded_track, .. } => loaded_track,
+ _ => {
+ return Err(Error::internal(format!(
+ "PlayerInternal::handle_command_load repeating the same track: invalid state: {:?}",
+ self.state
+ )));
+ }
+ };
+
+ if position_ms != loaded_track.stream_position_ms {
+ // This may be blocking.
+ loaded_track.stream_position_ms = loaded_track.decoder.seek(position_ms)?;
+ }
+ self.preload = PlayerPreload::None;
+ self.start_playback(track_id, play_request_id, loaded_track, play);
+ if let PlayerState::Invalid = self.state {
+ return Err(Error::internal(format!(
+ "PlayerInternal::handle_command_load repeating the same track: start_playback() did not transition to valid player state: {:?}",
+ self.state
+ )));
+ }
+ return Ok(());
+ }
+ }
+
+ // Check if we are already playing the track. If so, just do a seek and update our info.
+ if let PlayerState::Playing {
+ track_id: ref current_track_id,
+ ref mut stream_position_ms,
+ ref mut decoder,
+ ..
+ }
+ | PlayerState::Paused {
+ track_id: ref current_track_id,
+ ref mut stream_position_ms,
+ ref mut decoder,
+ ..
+ } = self.state
+ {
+ if *current_track_id == track_id {
+ // we can use the current decoder. Ensure it's at the correct position.
+ if position_ms != *stream_position_ms {
+ // This may be blocking.
+ *stream_position_ms = decoder.seek(position_ms)?;
+ }
+
+ // Move the info from the current state into a PlayerLoadedTrackData so we can use
+ // the usual code path to start playback.
+ let old_state = mem::replace(&mut self.state, PlayerState::Invalid);
+
+ if let PlayerState::Playing {
+ stream_position_ms,
+ decoder,
+ audio_item,
+ stream_loader_controller,
+ bytes_per_second,
+ duration_ms,
+ normalisation_data,
+ is_explicit,
+ ..
+ }
+ | PlayerState::Paused {
+ stream_position_ms,
+ decoder,
+ audio_item,
+ stream_loader_controller,
+ bytes_per_second,
+ duration_ms,
+ normalisation_data,
+ is_explicit,
+ ..
+ } = old_state
+ {
+ let loaded_track = PlayerLoadedTrackData {
+ decoder,
+ normalisation_data,
+ stream_loader_controller,
+ audio_item,
+ bytes_per_second,
+ duration_ms,
+ stream_position_ms,
+ is_explicit,
+ };
+
+ self.preload = PlayerPreload::None;
+ self.start_playback(track_id, play_request_id, loaded_track, play);
+
+ if let PlayerState::Invalid = self.state {
+ return Err(Error::internal(format!(
+ "PlayerInternal::handle_command_load already playing this track: start_playback() did not transition to valid player state: {:?}",
+ self.state
+ )));
+ }
+
+ return Ok(());
+ } else {
+ return Err(Error::internal(format!(
+ "PlayerInternal::handle_command_load already playing this track: invalid state: {:?}",
+ self.state
+ )));
+ }
+ }
+ }
+
+ // Check if the requested track has been preloaded already. If so use the preloaded data.
+ if let PlayerPreload::Ready {
+ track_id: loaded_track_id,
+ ..
+ } = &self.preload
+ {
+ if track_id == *loaded_track_id {
+ let preload = std::mem::replace(&mut self.preload, PlayerPreload::None);
+ if let PlayerPreload::Ready {
+ track_id,
+ mut loaded_track,
+ } = preload
+ {
+ if position_ms != loaded_track.stream_position_ms {
+ // This may be blocking
+ loaded_track.stream_position_ms = loaded_track.decoder.seek(position_ms)?;
+ }
+ self.start_playback(track_id, play_request_id, *loaded_track, play);
+ return Ok(());
+ } else {
+ return Err(Error::internal(format!(
+ "PlayerInternal::handle_command_loading preloaded track: invalid state: {:?}",
+ self.state
+ )));
+ }
+ }
+ }
+
+ self.send_event(PlayerEvent::Loading {
+ track_id: track_id.clone(),
+ play_request_id,
+ position_ms,
+ });
+
+ // Try to extract a pending loader from the preloading mechanism
+ let loader = if let PlayerPreload::Loading {
+ track_id: loaded_track_id,
+ ..
+ } = &self.preload
+ {
+ if (track_id == *loaded_track_id) && (position_ms == 0) {
+ let mut preload = PlayerPreload::None;
+ std::mem::swap(&mut preload, &mut self.preload);
+ if let PlayerPreload::Loading { loader, .. } = preload {
+ Some(loader)
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ self.preload = PlayerPreload::None;
+
+ // If we don't have a loader yet, create one from scratch.
+ let loader =
+ loader.unwrap_or_else(|| Box::pin(self.load_track(track_id.clone(), position_ms)));
+
+ // Set ourselves to a loading state.
+ self.state = PlayerState::Loading {
+ track_id,
+ play_request_id,
+ start_playback: play,
+ loader,
+ };
+
+ Ok(())
+ }
+
+ fn handle_command_preload(&mut self, track_id: SpotifyUri) {
+ debug!("Preloading track");
+ let mut preload_track = true;
+ // check whether the track is already loaded somewhere or being loaded.
+ if let PlayerPreload::Loading {
+ track_id: currently_loading,
+ ..
+ }
+ | PlayerPreload::Ready {
+ track_id: currently_loading,
+ ..
+ } = &self.preload
+ {
+ if *currently_loading == track_id {
+ // we're already preloading the requested track.
+ preload_track = false;
+ } else {
+ // we're preloading something else - cancel it.
+ self.preload = PlayerPreload::None;
+ }
+ }
+
+ if let PlayerState::Playing {
+ track_id: current_track_id,
+ ..
+ }
+ | PlayerState::Paused {
+ track_id: current_track_id,
+ ..
+ }
+ | PlayerState::EndOfTrack {
+ track_id: current_track_id,
+ ..
+ } = &self.state
+ {
+ if *current_track_id == track_id {
+ // we already have the requested track loaded.
+ preload_track = false;
+ }
+ }
+
+ // schedule the preload of the current track if desired.
+ if preload_track {
+ let loader = self.load_track(track_id.clone(), 0);
+ self.preload = PlayerPreload::Loading {
+ track_id,
+ loader: Box::pin(loader),
+ }
+ }
+ }
+
+ fn handle_command_seek(&mut self, position_ms: u32) -> PlayerResult {
+ // When we are still loading, the user may immediately ask to
+ // seek to another position yet the decoder won't be ready for
+ // that. In this case just restart the loading process but
+ // with the requested position.
+ if let PlayerState::Loading {
+ ref track_id,
+ play_request_id,
+ start_playback,
+ ..
+ } = self.state
+ {
+ return self.handle_command_load(
+ track_id.clone(),
+ Some(play_request_id),
+ start_playback,
+ position_ms,
+ );
+ }
+
+ if let Some(decoder) = self.state.decoder() {
+ match decoder.seek(position_ms) {
+ Ok(new_position_ms) => {
+ if let PlayerState::Playing {
+ ref mut stream_position_ms,
+ ref track_id,
+ play_request_id,
+ ..
+ }
+ | PlayerState::Paused {
+ ref mut stream_position_ms,
+ ref track_id,
+ play_request_id,
+ ..
+ } = self.state
+ {
+ *stream_position_ms = new_position_ms;
+
+ self.send_event(PlayerEvent::Seeked {
+ play_request_id,
+ track_id: track_id.clone(),
+ position_ms: new_position_ms,
+ });
+ }
+ }
+ Err(e) => error!("PlayerInternal::handle_command_seek error: {e}"),
+ }
+ } else {
+ error!("Player::seek called from invalid state: {:?}", self.state);
+ }
+
+ // ensure we have a bit of a buffer of downloaded data
+ self.preload_data_before_playback()?;
+
+ if let PlayerState::Playing {
+ ref mut reported_nominal_start_time,
+ ..
+ } = self.state
+ {
+ *reported_nominal_start_time =
+ Instant::now().checked_sub(Duration::from_millis(position_ms as u64));
+ }
+
+ Ok(())
+ }
+
+ fn handle_command(&mut self, cmd: PlayerCommand) -> PlayerResult {
+ debug!("command={cmd:?}");
+ match cmd {
+ PlayerCommand::Load {
+ track_id,
+ play,
+ position_ms,
+ } => self.handle_command_load(track_id, None, play, position_ms)?,
+
+ PlayerCommand::Preload { track_id } => self.handle_command_preload(track_id),
+
+ PlayerCommand::Seek(position_ms) => self.handle_command_seek(position_ms)?,
+
+ PlayerCommand::Play => self.handle_play(),
+
+ PlayerCommand::Pause => self.handle_pause(),
+
+ PlayerCommand::Stop => self.handle_player_stop(),
+
+ PlayerCommand::SetSession(session) => self.session = session,
+
+ PlayerCommand::AddEventSender(sender) => self.event_senders.push(sender),
+
+ PlayerCommand::SetSinkEventCallback(callback) => self.sink_event_callback = callback,
+
+ PlayerCommand::EmitVolumeChangedEvent(volume) => {
+ self.send_event(PlayerEvent::VolumeChanged { volume })
+ }
+
+ PlayerCommand::EmitRepeatChangedEvent { context, track } => {
+ self.send_event(PlayerEvent::RepeatChanged { context, track })
+ }
+
+ PlayerCommand::EmitShuffleChangedEvent(shuffle) => {
+ self.send_event(PlayerEvent::ShuffleChanged { shuffle })
+ }
+
+ PlayerCommand::EmitAutoPlayChangedEvent(auto_play) => {
+ self.send_event(PlayerEvent::AutoPlayChanged { auto_play })
+ }
+
+ PlayerCommand::EmitSessionClientChangedEvent {
+ client_id,
+ client_name,
+ client_brand_name,
+ client_model_name,
+ } => self.send_event(PlayerEvent::SessionClientChanged {
+ client_id,
+ client_name,
+ client_brand_name,
+ client_model_name,
+ }),
+
+ PlayerCommand::EmitSessionConnectedEvent {
+ connection_id,
+ user_name,
+ } => self.send_event(PlayerEvent::SessionConnected {
+ connection_id,
+ user_name,
+ }),
+
+ PlayerCommand::EmitSessionDisconnectedEvent {
+ connection_id,
+ user_name,
+ } => self.send_event(PlayerEvent::SessionDisconnected {
+ connection_id,
+ user_name,
+ }),
+
+ PlayerCommand::SetAutoNormaliseAsAlbum(setting) => {
+ self.auto_normalise_as_album = setting
+ }
+
+ PlayerCommand::EmitFilterExplicitContentChangedEvent(filter) => {
+ self.send_event(PlayerEvent::FilterExplicitContentChanged { filter });
+
+ if filter {
+ if let PlayerState::Playing {
+ ref track_id,
+ play_request_id,
+ is_explicit,
+ ..
+ }
+ | PlayerState::Paused {
+ ref track_id,
+ play_request_id,
+ is_explicit,
+ ..
+ } = self.state
+ {
+ let track_id = track_id.clone();
+
+ if is_explicit {
+ warn!(
+ "Currently loaded track is explicit, which client setting forbids -- skipping to next track."
+ );
+ self.send_event(PlayerEvent::EndOfTrack {
+ track_id,
+ play_request_id,
+ })
+ }
+ }
+ }
+ }
+ };
+
+ Ok(())
+ }
+
+ fn send_event(&mut self, event: PlayerEvent) {
+ self.event_senders
+ .retain(|sender| sender.send(event.clone()).is_ok());
+ }
+
+ fn load_track(
+ &mut self,
+ spotify_uri: SpotifyUri,
+ position_ms: u32,
+ ) -> impl FusedFuture<Output = Result<PlayerLoadedTrackData, ()>> + Send + 'static {
+ // This method creates a future that returns the loaded stream and associated info.
+ // Ideally all work should be done using asynchronous code. However, seek() on the
+ // audio stream is implemented in a blocking fashion. Thus, we can't turn it into future
+ // easily. Instead we spawn a thread to do the work and return a one-shot channel as the
+ // future to work with.
+
+ let loader = PlayerTrackLoader {
+ session: self.session.clone(),
+ config: self.config.clone(),
+ local_file_lookup: self.local_file_lookup.clone(),
+ };
+
+ let (result_tx, result_rx) = oneshot::channel();
+
+ let load_handles_clone = self.load_handles.clone();
+ let handle = tokio::runtime::Handle::current();
+
+ let load_handle = thread::spawn(move || {
+ let data = handle.block_on(loader.load_track(spotify_uri, position_ms));
+ if let Some(data) = data {
+ let _ = result_tx.send(data);
+ }
+
+ let mut load_handles = load_handles_clone.lock().expect(LOAD_HANDLES_POISON_MSG);
+ load_handles.remove(&thread::current().id());
+ });
+
+ let mut load_handles = self.load_handles.lock().expect(LOAD_HANDLES_POISON_MSG);
+ load_handles.insert(load_handle.thread().id(), load_handle);
+
+ result_rx.map_err(|_| ())
+ }
+
+ fn preload_data_before_playback(&mut self) -> PlayerResult {
+ if let PlayerState::Playing {
+ bytes_per_second,
+ ref mut stream_loader_controller,
+ ..
+ } = self.state
+ {
+ let read_ahead_during_playback = AudioFetchParams::get().read_ahead_during_playback;
+ // Request our read ahead range
+ let request_data_length =
+ (read_ahead_during_playback.as_secs_f32() * bytes_per_second as f32) as usize;
+
+ // Request the part we want to wait for blocking. This effectively means we wait for the previous request to partially complete.
+ let wait_for_data_length =
+ (read_ahead_during_playback.as_secs_f32() * bytes_per_second as f32) as usize;
+
+ stream_loader_controller.fetch_next_and_wait(request_data_length, wait_for_data_length)
+ } else {
+ Ok(())
+ }
+ }
+}
+
+impl Drop for PlayerInternal {
+ fn drop(&mut self) {
+ debug!("drop PlayerInternal[{}]", self.player_id);
+
+ let handles: Vec<thread::JoinHandle<()>> = {
+ // waiting for the thread while holding the mutex would result in a deadlock
+ let mut load_handles = self.load_handles.lock().expect(LOAD_HANDLES_POISON_MSG);
+
+ load_handles
+ .drain()
+ .map(|(_thread_id, handle)| handle)
+ .collect()
+ };
+
+ for handle in handles {
+ let _ = handle.join();
+ }
+ }
+}
+
+impl fmt::Debug for PlayerCommand {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ PlayerCommand::Load {
+ track_id,
+ play,
+ position_ms,
+ ..
+ } => f
+ .debug_tuple("Load")
+ .field(&track_id)
+ .field(&play)
+ .field(&position_ms)
+ .finish(),
+ PlayerCommand::Preload { track_id } => {
+ f.debug_tuple("Preload").field(&track_id).finish()
+ }
+ PlayerCommand::Play => f.debug_tuple("Play").finish(),
+ PlayerCommand::Pause => f.debug_tuple("Pause").finish(),
+ PlayerCommand::Stop => f.debug_tuple("Stop").finish(),
+ PlayerCommand::Seek(position) => f.debug_tuple("Seek").field(&position).finish(),
+ PlayerCommand::SetSession(_) => f.debug_tuple("SetSession").finish(),
+ PlayerCommand::AddEventSender(_) => f.debug_tuple("AddEventSender").finish(),
+ PlayerCommand::SetSinkEventCallback(_) => {
+ f.debug_tuple("SetSinkEventCallback").finish()
+ }
+ PlayerCommand::EmitVolumeChangedEvent(volume) => f
+ .debug_tuple("EmitVolumeChangedEvent")
+ .field(&volume)
+ .finish(),
+ PlayerCommand::SetAutoNormaliseAsAlbum(setting) => f
+ .debug_tuple("SetAutoNormaliseAsAlbum")
+ .field(&setting)
+ .finish(),
+ PlayerCommand::EmitFilterExplicitContentChangedEvent(filter) => f
+ .debug_tuple("EmitFilterExplicitContentChangedEvent")
+ .field(&filter)
+ .finish(),
+ PlayerCommand::EmitSessionConnectedEvent {
+ connection_id,
+ user_name,
+ } => f
+ .debug_tuple("EmitSessionConnectedEvent")
+ .field(&connection_id)
+ .field(&user_name)
+ .finish(),
+ PlayerCommand::EmitSessionDisconnectedEvent {
+ connection_id,
+ user_name,
+ } => f
+ .debug_tuple("EmitSessionDisconnectedEvent")
+ .field(&connection_id)
+ .field(&user_name)
+ .finish(),
+ PlayerCommand::EmitSessionClientChangedEvent {
+ client_id,
+ client_name,
+ client_brand_name,
+ client_model_name,
+ } => f
+ .debug_tuple("EmitSessionClientChangedEvent")
+ .field(&client_id)
+ .field(&client_name)
+ .field(&client_brand_name)
+ .field(&client_model_name)
+ .finish(),
+ PlayerCommand::EmitShuffleChangedEvent(shuffle) => f
+ .debug_tuple("EmitShuffleChangedEvent")
+ .field(&shuffle)
+ .finish(),
+ PlayerCommand::EmitRepeatChangedEvent { context, track } => f
+ .debug_tuple("EmitRepeatChangedEvent")
+ .field(&context)
+ .field(&track)
+ .finish(),
+ PlayerCommand::EmitAutoPlayChangedEvent(auto_play) => f
+ .debug_tuple("EmitAutoPlayChangedEvent")
+ .field(&auto_play)
+ .finish(),
+ }
+ }
+}
+
+impl fmt::Debug for PlayerState {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ use PlayerState::*;
+ match self {
+ Stopped => f.debug_struct("Stopped").finish(),
+ Loading {
+ track_id,
+ play_request_id,
+ ..
+ } => f
+ .debug_struct("Loading")
+ .field("track_id", &track_id)
+ .field("play_request_id", &play_request_id)
+ .finish(),
+ Paused {
+ track_id,
+ play_request_id,
+ ..
+ } => f
+ .debug_struct("Paused")
+ .field("track_id", &track_id)
+ .field("play_request_id", &play_request_id)
+ .finish(),
+ Playing {
+ track_id,
+ play_request_id,
+ ..
+ } => f
+ .debug_struct("Playing")
+ .field("track_id", &track_id)
+ .field("play_request_id", &play_request_id)
+ .finish(),
+ EndOfTrack {
+ track_id,
+ play_request_id,
+ ..
+ } => f
+ .debug_struct("EndOfTrack")
+ .field("track_id", &track_id)
+ .field("play_request_id", &play_request_id)
+ .finish(),
+ Invalid => f.debug_struct("Invalid").finish(),
+ }
+ }
+}
+
+struct Subfile<T: Read + Seek> {
+ stream: T,
+ offset: u64,
+ length: u64,
+}
+
+impl<T: Read + Seek> Subfile<T> {
+ pub fn new(mut stream: T, offset: u64, length: u64) -> Result<Subfile<T>, io::Error> {
+ let target = SeekFrom::Start(offset);
+ stream.seek(target)?;
+
+ Ok(Subfile {
+ stream,
+ offset,
+ length,
+ })
+ }
+}
+
+impl<T: Read + Seek> Read for Subfile<T> {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ self.stream.read(buf)
+ }
+}
+
+impl<T: Read + Seek> Seek for Subfile<T> {
+ fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+ let pos = match pos {
+ SeekFrom::Start(offset) => SeekFrom::Start(offset + self.offset),
+ SeekFrom::End(offset) => {
+ if (self.length as i64 - offset) < self.offset as i64 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "newpos would be < self.offset",
+ ));
+ }
+ pos
+ }
+ _ => pos,
+ };
+
+ let newpos = self.stream.seek(pos)?;
+ Ok(newpos - self.offset)
+ }
+}
+
+impl<R> MediaSource for Subfile<R>
+where
+ R: Read + Seek + Send + Sync,
+{
+ fn is_seekable(&self) -> bool {
+ true
+ }
+
+ fn byte_len(&self) -> Option<u64> {
+ Some(self.length)
+ }
+}
diff --git a/native/vendor/librespot-playback/src/symphonia_util.rs b/native/vendor/librespot-playback/src/symphonia_util.rs
new file mode 100644
index 0000000..deb5825
--- /dev/null
+++ b/native/vendor/librespot-playback/src/symphonia_util.rs
@@ -0,0 +1,18 @@
+use symphonia::core::meta::Metadata;
+use symphonia::core::probe::ProbeResult;
+
+pub fn get_latest_metadata(probe_result: &mut ProbeResult) -> Option<Metadata<'_>> {
+ let mut metadata = probe_result.format.metadata();
+
+ // If we can't get metadata from the container, fall back to other tags found by probing.
+ // Note that this is only relevant for local files.
+ if metadata.current().is_none() {
+ if let Some(inner_probe_metadata) = probe_result.metadata.get() {
+ metadata = inner_probe_metadata;
+ }
+ }
+
+ _ = metadata.skip_to_latest();
+
+ Some(metadata)
+}