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.

Choosing another device after taking playback back works, and the queue there is shown

Lelonio0d0e938de84e
diff --git a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
index 05f4089..31c1f37 100644
--- a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
+++ b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
@@ -101,8 +101,21 @@ object RemoteConnect {
android.util.Log.i(TAG, "this device is $ownId")
}
- _devices.value = runCatching { parseDevices(NativeBridge.remoteDevices()) }
+ val listed = runCatching { parseDevices(NativeBridge.remoteDevices()) }
.getOrDefault(emptyList())
+ // The account's word on which device is active is the cluster's, and the
+ // account does not tell a device about its own playing: after playback
+ // is taken back here, the cluster goes on naming the device it came
+ // from. The list then showed that device as current, this phone could
+ // not be told it was, and tapping the other device did nothing because
+ // it was "already" playing there. When the engine is the one playing,
+ // this phone is the active device, whatever the cluster still says.
+ val playingHere = !NativeBridge.playbackElsewhere
+ _devices.value = if (playingHere && listed.any { it.active && !it.isThisPhone }) {
+ listed.map { it.copy(active = it.id == ownId) }
+ } else {
+ listed
+ }
val state = runCatching { JSONObject(NativeBridge.remoteState()) }.getOrNull()
val active = state?.optString("activeDevice").orEmpty()
@@ -142,6 +155,17 @@ object RemoteConnect {
shuffle = state.optBoolean("shuffle"),
repeatContext = state.optBoolean("repeatContext"),
repeatTrack = state.optBoolean("repeatTrack"),
+ next = state.optJSONArray("next")?.let { array ->
+ (0 until array.length()).mapNotNull { index ->
+ val track = array.optJSONObject(index) ?: return@mapNotNull null
+ RemoteTrack(
+ uri = track.optString("uri").ifEmpty { return@mapNotNull null },
+ title = track.optString("title"),
+ artist = track.optString("artist"),
+ coverUri = track.optString("coverUri"),
+ )
+ }
+ }.orEmpty(),
)
}
@@ -174,15 +198,30 @@ object RemoteConnect {
/** What was learned about this track earlier, over what arrived now. */
private fun RemotePlayback.filled(): RemotePlayback {
- val earlier = known[uri] ?: return this
+ val upcoming = next.map { track -> knownNext[track.uri]?.let { track.filledFrom(it) } ?: track }
+ val earlier = known[uri] ?: return copy(next = upcoming)
return copy(
title = title.ifEmpty { earlier.title },
artist = artist.ifEmpty { earlier.artist },
album = album.ifEmpty { earlier.album },
coverUri = coverUri.ifEmpty { earlier.coverUri },
+ next = upcoming,
)
}
+ /** The upcoming tracks looked up so far, kept by uri like [known]. */
+ private val knownNext = mutableMapOf<String, RemoteTrack>()
+
+ /**
+ * What was looked up about the upcoming tracks, kept and put on the
+ * playback shown now; see [describe], which does the same for the current one.
+ */
+ fun describeNext(tracks: List<RemoteTrack>) {
+ tracks.forEach { knownNext[it.uri] = it }
+ val current = _playback.value ?: return
+ _playback.value = current.filled()
+ }
+
/** Forgets everything. For a session ending, where none of it is true any more. */
fun clear() {
playingAtOpen = null
@@ -307,6 +346,8 @@ data class RemotePlayback(
val shuffle: Boolean,
val repeatContext: Boolean,
val repeatTrack: Boolean,
+ /** What plays after it there, in that device's order; see remote.rs. */
+ val next: List<RemoteTrack> = emptyList(),
) {
/**
* The cover as something that can actually be fetched.
@@ -352,3 +393,25 @@ data class RemoteDevice(
val active: Boolean,
val isThisPhone: Boolean,
)
+
+/** One of the tracks coming up on another device. */
+data class RemoteTrack(
+ val uri: String,
+ val title: String,
+ val artist: String,
+ val coverUri: String,
+) {
+ /** See [RemotePlayback.coverUrl]. */
+ val coverUrl: String
+ get() = when {
+ coverUri.isEmpty() -> ""
+ coverUri.startsWith("http") -> coverUri
+ else -> "https://i.scdn.co/image/${coverUri.substringAfterLast(':')}"
+ }
+
+ internal fun filledFrom(earlier: RemoteTrack) = copy(
+ title = title.ifEmpty { earlier.title },
+ artist = artist.ifEmpty { earlier.artist },
+ coverUri = coverUri.ifEmpty { earlier.coverUri },
+ )
+}
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 91ff048..c40cd63 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -277,7 +277,10 @@ class LibrespotPlayer(
if (released) return
val was = remote
remote = playback
- if (was?.uri != playback?.uri) cachedPlaylist = null
+ // Rebuilt when what it shows changes — the track, its names, what comes
+ // next — and not for the position, which moves every second.
+ val shown = { p: dev.lelonio.square.data.RemotePlayback? -> p?.copy(positionMs = 0, playing = false) }
+ if (shown(was) != shown(playback)) cachedPlaylist = null
invalidateState()
}
@@ -344,29 +347,35 @@ class LibrespotPlayer(
* 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(
+ fun item(uid: String, uri: String, title: String, artist: String, album: String, cover: String) =
+ MediaItemData.Builder(uid).setMediaItem(
MediaItem.Builder()
- .setMediaId(playback.uri)
- .setUri(playback.uri)
+ .setMediaId(uri)
+ .setUri(uri)
.setMediaMetadata(
MediaMetadata.Builder()
- .setTitle(playback.title)
- .setArtist(playback.artist)
- .setAlbumTitle(playback.album)
- .setArtworkUri(
- playback.coverUrl.takeIf { it.isNotEmpty() }
- ?.let(android.net.Uri::parse),
- )
+ .setTitle(title)
+ .setArtist(artist)
+ .setAlbumTitle(album)
+ .setArtworkUri(cover.takeIf { it.isNotEmpty() }?.let(android.net.Uri::parse))
.setIsBrowsable(false)
.setIsPlayable(true)
.build(),
)
.build(),
)
- .setDurationUs(playback.durationMs * 1000)
- .build()
- .also { cachedPlaylist = listOf(it) }
+ // The track and what comes after it on that device: its own queue,
+ // rather than one track and nothing after it.
+ val items = cachedPlaylist ?: buildList {
+ add(
+ item("remote:0", playback.uri, playback.title, playback.artist, playback.album, playback.coverUrl)
+ .setDurationUs(playback.durationMs * 1000)
+ .build(),
+ )
+ playback.next.forEachIndexed { index, track ->
+ add(item("remote:${index + 1}:${track.uri}", track.uri, track.title, track.artist, "", track.coverUrl).build())
+ }
+ }.also { cachedPlaylist = it }
return State.Builder()
.setAvailableCommands(COMMANDS)
@@ -381,7 +390,7 @@ class LibrespotPlayer(
},
)
.setShuffleModeEnabled(playback.shuffle)
- .setPlaylist(listOf(item))
+ .setPlaylist(items)
.setCurrentMediaItemIndex(0)
.build()
}
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 be5f16e..5d2291f 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -1067,6 +1067,40 @@ class PlaybackService : MediaLibraryService() {
}
}
+ /** Upcoming tracks already asked about, so a run of updates asks once. */
+ private val askedNext = mutableSetOf<String>()
+
+ /**
+ * Names the tracks coming up on the other device that it did not name.
+ *
+ * The queue shown for another device is what it publishes as next, and a
+ * client that leaves the title off the current track leaves it off those
+ * too. One catalogue read for all of them; a local file is described by its
+ * own URI, which spells out its tags.
+ */
+ private suspend fun describeRemoteNext(playback: dev.lelonio.square.data.RemotePlayback) {
+ val unnamed = playback.next.filter { it.title.isEmpty() && it.uri !in askedNext }
+ if (unnamed.isEmpty()) return
+ askedNext += unnamed.map { it.uri }
+ val local = unnamed.filter { dev.lelonio.square.data.LocalLibrary.isSpotifyLocal(it.uri) }.map { track ->
+ val parts = track.uri.removePrefix(dev.lelonio.square.data.LocalLibrary.SPOTIFY_PREFIX).split(':')
+ .map { runCatching { java.net.URLDecoder.decode(it, "UTF-8") }.getOrDefault(it) }
+ track.copy(artist = parts.getOrNull(0).orEmpty(), title = parts.getOrNull(2).orEmpty())
+ }
+ val catalogue = unnamed.map { it.uri }.filter { it.startsWith("spotify:track:") }
+ val read = if (catalogue.isEmpty()) emptyList() else {
+ runCatching { dev.lelonio.square.data.Catalog.tracks(catalogue) }
+ .onFailure { android.util.Log.w(TAG, "cannot read what comes next there: $it") }
+ .getOrDefault(emptyList())
+ .map { track ->
+ dev.lelonio.square.data.RemoteTrack(track.uri, track.name, track.artist, track.artworkUrl.orEmpty())
+ }
+ }
+ if (local.isNotEmpty() || read.isNotEmpty()) {
+ dev.lelonio.square.data.RemoteConnect.describeNext(local + read)
+ }
+ }
+
/**
* Fills in what the other device did not say about its track.
*
@@ -1078,6 +1112,7 @@ class PlaybackService : MediaLibraryService() {
private suspend fun describeRemote(
playback: dev.lelonio.square.data.RemotePlayback,
): dev.lelonio.square.data.RemotePlayback {
+ describeRemoteNext(playback)
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") }
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 d15ba38..4f63920 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1044,7 +1044,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
)
}.onFailure { android.util.Log.w(TAG, "could not resume here: $it") }.isSuccess
}
- if (started) return@launch
+ if (started) {
+ // The account will not say this phone is active now; see
+ // RemoteConnect.refresh, which works it out from the engine.
+ withContext(Dispatchers.IO) { runCatching { dev.lelonio.square.data.RemoteConnect.refresh() } }
+ 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.
diff --git a/native/src/remote.rs b/native/src/remote.rs
index 645d30f..9ad90b3 100644
--- a/native/src/remote.rs
+++ b/native/src/remote.rs
@@ -188,12 +188,37 @@ pub fn state_json() -> String {
.unwrap_or_default()
};
+ // What comes next on that device, in its own order — shuffle and songs
+ // queued by hand included — so the queue shown here is the one playing
+ // there rather than the single track it used to be. Delimiters and the
+ // like are not songs, and fifty is more than a screen.
+ let next: Vec<serde_json::Value> = player
+ .next_tracks
+ .iter()
+ .filter(|track| {
+ track.uri.starts_with("spotify:track:")
+ || track.uri.starts_with("spotify:episode:")
+ || track.uri.starts_with("spotify:local:")
+ })
+ .take(50)
+ .map(|track| {
+ let meta = |key: &str| track.metadata.get(key).cloned().unwrap_or_default();
+ serde_json::json!({
+ "uri": track.uri,
+ "title": meta("title"),
+ "artist": meta("artist_name"),
+ "coverUri": meta("image_url"),
+ })
+ })
+ .collect();
+ let next = serde_json::to_string(&next).unwrap_or_else(|_| "[]".into());
+
format!(
concat!(
"{{\"activeDevice\":{},\"deviceName\":{},\"uri\":{},\"title\":{},",
"\"artist\":{},\"album\":{},\"coverUri\":{},\"contextUri\":{},\"positionMs\":{},",
"\"durationMs\":{},\"playing\":{},\"shuffle\":{},\"repeatContext\":{},",
- "\"repeatTrack\":{}}}"
+ "\"repeatTrack\":{},\"next\":{}}}"
),
escape(&cluster.active_device_id),
escape(device.map(|device| device.name.as_str()).unwrap_or("")),
@@ -209,6 +234,7 @@ pub fn state_json() -> String {
player.options.shuffling_context,
player.options.repeating_context,
player.options.repeating_track,
+ next,
)
}