Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Open the artist and the playlist from the player's own text
Lelonio01979315d240
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.ktindex 92e50a2..325201e 100644--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt@@ -23,6 +23,8 @@ data class CatalogTrack(val uri: String,val name: String,val artist: String,+ /** The first artist's own uri, when the source gives one; see catalog.rs. */+ val artistUri: String? = null,val album: String = "",val durationMs: Long = 0,val explicit: Boolean = false,@@ -69,6 +71,7 @@ fun TrackDto.toCatalogTrack(addedAt: String? = null): CatalogTrack = CatalogTracuri = uri,name = name,artist = artists.joinToString(", ") { it.name },+ artistUri = artists.firstOrNull()?.uri,album = album?.name.orEmpty(),durationMs = durationMs,explicit = explicit,diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.ktindex c204c03..a903dee 100644--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt@@ -135,6 +135,26 @@ interface SpotifyApi {@Query("limit") limit: Int = 20,): PageDto<AlbumDto>+ /**+ * The three below exist for one field each: the picture at the top of a+ * page opened by name alone.+ *+ * Most of the app reaches a playlist or an artist through a row that+ * already carries its image. A tap on the player's own text does not: all+ * it has is the URI, so the page has to go and ask.+ */+ @GET("v1/artists/{id}")+ suspend fun artist(@Path("id") artistId: String): ArtistDto++ @GET("v1/albums/{id}")+ suspend fun album(@Path("id") albumId: String): AlbumDto++ @GET("v1/playlists/{id}")+ suspend fun playlist(+ @Path("id") playlistId: String,+ @Query("fields") fields: String = "id,uri,name,images",+ ): PlaylistDto+/*** Every device the account can currently play on.*diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.ktindex 5fe470b..c5a567c 100644--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt@@ -739,6 +739,23 @@ class LibrespotPlayer(* exists. It clears what the app believes about it, so the queue coming* back from storage is loaded rather than skipped as "already playing".*/+ /**+ * Hands the queue back to an engine that has just been rebuilt.+ *+ * Everything on this side is still true — the list, the order, the track —+ * and only the engine's copy went away with its session, so this pushes it+ * again at the position it had reached rather than starting anything over.+ */+ fun reloadQueue(playing: Boolean, positionMs: Long) {+ if (released || queue.items.isEmpty()) return+ engineQueueStale = true+ engineIndex = -1+ this.positionMs = positionMs+ wantPlay = playing+ pushQueue(startPlaying = playing, positionMs = positionMs.toInt())+ invalidateState()+ }+fun clearForRestart() {queue.replace(emptyList(), 0)wantPlay = false@@ -1031,13 +1048,22 @@ class LibrespotPlayer(.setTitle(track.title).setArtist(track.artist).setArtworkUri(track.artworkUri)- // Put back, because this item is rebuilt rather- // than passed through; see PlayQueue.contextLabel.+ // Put back, because this item is rebuilt rather than+ // passed through: whatever is not restored here is+ // lost to everything reading the player, which is+ // how the artist's name stopped being a link the+ // moment the queue was rebuilt..setExtras(- queue.contextLabel.takeIf { it.isNotEmpty() }?.let {- android.os.Bundle().apply {+ android.os.Bundle().apply {+ queue.contextLabel.takeIf { it.isNotEmpty() }?.let {putString(EXTRA_CONTEXT_LABEL, it)}+ queue.contextUri?.let {+ putString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI, it)+ }+ track.artistUri?.let {+ putString(dev.lelonio.square.ui.EXTRA_ARTIST_URI, it)+ }},).build(),diff --git a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.ktindex 5dc6eed..c9755d4 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt@@ -28,6 +28,8 @@ class PlayQueue {val uri: String,val title: String,val artist: String,+ /** The first artist's uri, when it is known; see EXTRA_ARTIST_URI. */+ val artistUri: String? = null,val durationMs: Long,val artworkUri: Uri?,/**@@ -291,6 +293,7 @@ class PlayQueue {uri = uri,title = metadata.title?.toString().orEmpty(),artist = metadata.artist?.toString().orEmpty(),+ artistUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ARTIST_URI),durationMs = metadata.durationMs ?: 0L,artworkUri = metadata.artworkUri,queued = metadata.extras?.getBoolean(EXTRA_PLAY_NEXT) == true,diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.ktindex a36ace2..1829e89 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt@@ -113,6 +113,8 @@ class PlaybackService : MediaLibraryService() {.apply { setSmallIcon(dev.lelonio.square.R.drawable.ic_notification) },)+ // Already read by the application object, and harmless twice: `load`+ // returns at once once the file is open.AudioEffects.load(this)// The bitrate is fixed when the player is built, so a change means a new@@ -120,14 +122,25 @@ class PlaybackService : MediaLibraryService() {// the service owns the engine's lifetime, and it is the only place that// can put playback back afterwards.scope.launch {- quality.quality.drop(1).collect { restartForQuality() }+ quality.quality.drop(1).collect { reconfigureEngine("quality") }+ }++ // Which stretcher does speed and pitch. Unlike the bitrate this one is+ // switchable while playing: it is a property of the output, not of the+ // session.+ scope.launch {+ container.effectQuality.quality.collect { quality ->+ audioOutput.setLightEffects(+ quality == dev.lelonio.square.data.EffectQuality.Light,+ )+ }}// 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") }+ crossfade.seconds.drop(1).collect { reconfigureEngine("crossfade") }}// Playback handed to this phone from another client's device list.@@ -333,39 +346,40 @@ class PlaybackService : MediaLibraryService() {* session is torn down and started again. The queue and position are saved* first and put back after, which is the same path a cold start takes.*/- private fun restartForQuality() = rebuildEngine("quality")-/**- * Tears the engine down and brings it back with the queue where it was.+ * Rebuilds the player so a new bitrate or crossfade takes effect.*- * The same path for a bitrate change and for a lost Connect device, because- * it is the same operation: the engine cannot be reconfigured or repaired- * in place, only replaced. The queue and position are saved first and put- * back by restoreQueue, which is what a cold start does too.+ * The engine is not shut down for this any more. Tearing it down from here+ * meant dropping the tokio runtime from a JNI thread while librespot's own+ * threads were still inside it, which aborted the process on a destroyed+ * mutex: that is the crash that came back the moment the audio quality was+ * changed. The engine can now replace its session and player on its own and+ * leave the runtime and the output alone; all this side has to do is hand+ * the queue back afterwards, since the new Connect device has never seen it.*/- private fun rebuildEngine(reason: String) {+ private fun reconfigureEngine(reason: String) {if (rebuilding) returnval engine = librespot ?: return+ if (!engineStarted) returnrebuilding = trueval wasPlaying = player.playWhenReady+ val position = player.currentPosition.coerceAtLeast(0)runCatching { savePlayback() }- android.util.Log.i(TAG, "rebuilding the engine ($reason)")+ android.util.Log.i(TAG, "rebuilding the player ($reason)")scope.launch {- // Off the main thread, and this is not optional. Shutting the engine- // down stops its threads and closes its session, and with no network- // that waits on timeouts: run here it blocks the looper long enough- // to take the process down, which is exactly what pausing with the- // connection gone used to do. switchBackend has said so all along.- runCatching { withContext(Dispatchers.IO) { NativeBridge.shutdown() } }- engineStarted = false- engine.clearForRestart()-- connectEngine().join()- // restoreQueue, run by connectEngine, puts the queue back at the- // position that was just saved, paused.- if (wasPlaying && player.mediaItemCount > 0) player.play()+ val ok = withContext(Dispatchers.IO) {+ runCatching {+ NativeBridge.setQuality(quality.bitrateKbps(), crossfade.durationMs())+ }+ .onFailure { android.util.Log.e(TAG, "could not rebuild the player: $it") }+ .isSuccess+ }rebuilding = false+ if (!ok) return@launch+ // The queue on screen is untouched and is still the right one; the+ // engine's copy went with the session.+ engine.reloadQueue(playing = wasPlaying, positionMs = position)}}@@ -581,6 +595,10 @@ class PlaybackService : MediaLibraryService() {uri = item.mediaId,name = metadata.title?.toString().orEmpty(),artist = metadata.artist?.toString().orEmpty(),+ // Kept per track rather than taken from the current one: the+ // artist page a row opens is its own.+ artistUri = metadata.extras+ ?.getString(dev.lelonio.square.ui.EXTRA_ARTIST_URI),durationMs = metadata.durationMs ?: 0L,artworkUrl = metadata.artworkUri?.toString(),)@@ -630,6 +648,9 @@ class PlaybackService : MediaLibraryService() {.setArtworkUri(track.artworkUrl?.let(android.net.Uri::parse)).setExtras(android.os.Bundle().apply {+ track.artistUri?.let {+ putString(dev.lelonio.square.ui.EXTRA_ARTIST_URI, it)+ }saved.contextUri?.let {putString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI, it)}@@ -659,6 +680,7 @@ class PlaybackService : MediaLibraryService() {uri = track.uri,name = track.title,artist = track.artist,+ artistUri = track.artistUri,durationMs = track.durationMs,artworkUrl = track.artworkUri?.toString(),)@@ -667,6 +689,7 @@ class PlaybackService : MediaLibraryService() {uri = track.uri,title = track.name,artist = track.artist,+ artistUri = track.artistUri,durationMs = track.durationMs,artworkUri = track.artworkUrl?.let(android.net.Uri::parse),)diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.ktindex 5505bce..e30d75c 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt@@ -221,6 +221,9 @@ class MainActivity : ComponentActivity() {if (contextLabel.isNotEmpty()) {putString(EXTRA_CONTEXT_LABEL, contextLabel)}+ // So the artist's name in the player is a way to+ // reach them, rather than a caption.+ track.artistUri?.let { putString(EXTRA_ARTIST_URI, it) }if (playNext) putBoolean(EXTRA_PLAY_NEXT, true)},)@@ -243,3 +246,6 @@ const val EXTRA_PLAY_NEXT = "dev.lelonio.square.PLAY_NEXT"/** What to show the listener: "Playlist · Estate 2025", "Ricerca". */const val EXTRA_CONTEXT_LABEL = "dev.lelonio.square.CONTEXT_LABEL"++/** The first artist's own uri, so the player's second line can be opened. */+const val EXTRA_ARTIST_URI = "dev.lelonio.square.ARTIST_URI"diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 1543c30..fcbd4f1 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -1174,7 +1174,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val kind = kindOf(playlist.uri)playlistJob?.cancel()- val base = PlaylistState(+ // Reassigned when the picture arrives late; every state published below+ // is built from this, so filling it in one place is what stops a later+ // write from taking the picture back off the screen.+ var base = PlaylistState(uri = playlist.uri,name = playlist.name,artworkUrl = playlist.artworkUrl,@@ -1188,6 +1191,17 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {)playlistJob = viewModelScope.launch {+ // Opened by URI alone, from a tap on the player's text: there was no+ // row to take the picture from. Asked for alongside the track list+ // rather than before it, since the list is what the page is for.+ if (base.artworkUrl == null) launch {+ val art = artworkFor(playlist.uri, kind) ?: return@launch+ base = base.copy(artworkUrl = art)+ if (_playlist.value.uri == playlist.uri) {+ _playlist.value = _playlist.value.copy(artworkUrl = art)+ }+ }+// The disk copy, if this run has not opened the playlist yet. Read// before anything is asked of the network: the whole point is that a// list already known appears at once rather than filling in.@@ -1227,6 +1241,39 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}+ /**+ * The picture at the top of a page opened by URI alone.+ *+ * The account's own playlists are already in hand, so those cost nothing.+ * Anything else is one request, and a page without a picture is a perfectly+ * good page, so every failure here is silent.+ */+ private suspend fun artworkFor(uri: String, kind: DetailKind): String? {+ (_state.value as? UiState.Ready)?.playlists+ ?.firstOrNull { it.uri == uri }+ ?.artworkUrl+ ?.let { return it }++ val id = uri.substringAfterLast(':')+ if (container.webApi.isReady) {+ val fetched = runCatching {+ when (kind) {+ DetailKind.ARTIST -> container.api.artist(id).images+ DetailKind.ALBUM -> container.api.album(id).images+ DetailKind.PLAYLIST -> container.api.playlist(id).images+ }.firstOrNull()?.url+ }+ .onFailure { android.util.Log.w(TAG, "no cover for $uri: ${describe(it)}") }+ .getOrNull()+ if (fetched != null) return fetched+ }++ // An album's cover is on every one of its tracks, which is the way in+ // when the user has not registered an application of their own.+ if (kind != DetailKind.ALBUM) return null+ return contextCache[uri]?.tracks?.firstNotNullOfOrNull { it.artworkUrl }+ }+/*** Whether the stored copy of a playlist is still the current one.*diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex c1de930..cf30ff9 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -977,6 +977,14 @@ fun SquareApp(onSelectDevice = {viewModel.transferPlayback(it, positionMs.value)},+ // The artist line and the line naming what is+ // playing both open the page they name. The+ // player has already folded itself away by the+ // time this runs, so the page arrives in front.+ onOpenUri = { uri, name ->+ viewModel.openContext(uri, name)+ navController.navigate(Routes.PLAYLIST)+ },onAddToPlaylist = {viewModel.openAddToPlaylist(playback.mediaId,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.ktindex 71387d9..04c514e 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@@ -46,6 +46,15 @@ data class PlaybackState(* album, an artist or a search.*/val source: String = "",+ /**+ * Where the line under the title leads, when it leads anywhere.+ *+ * Both are null on a queue that came from somewhere with no page of its+ * own: a handful of search results, a track handed over by another device.+ * The labels are then plain text, which is what they have always been.+ */+ val artistUri: String? = null,+ val contextUri: String? = null,)/**@@ -166,6 +175,8 @@ fun rememberPlaybackState(speed = player.playbackParameters.speed,pitch = player.playbackParameters.pitch,source = metadata.extras?.getString(EXTRA_CONTEXT_LABEL).orEmpty(),+ artistUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ARTIST_URI),+ contextUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI),)if (next.hasItem) {seenItem.value = truediff --git a/native/src/catalog.rs b/native/src/catalog.rsindex 2ffb9e7..df30ffd 100644--- a/native/src/catalog.rs+++ b/native/src/catalog.rs@@ -263,6 +263,13 @@ fn track_json(track: &Track) -> Value {.map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "),+ // The first artist's own uri, so a name on screen can be tapped. The+ // first rather than all of them: a track credited to three people has+ // one page a listener means when they press the line.+ "artistUri": track+ .artists+ .first()+ .and_then(|a| a.id.to_uri().ok()),"album": track.album.name,"durationMs": track.duration,"explicit": track.is_explicit,