Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Merge the AutoMix rewrite (two decks, whole-song analysis) into the next version
kota-zo16b54b510181
diff --cc base/app/src/main/java/com/music/spotui/cli/CliReceiver.ktindex 6f2fee97,4faea3d6..e460be01--- a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt+++ b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt@@@ -199,19 -194,25 +199,37 @@@ class CliReceiver : BroadcastReceiver(put("bytes", values.entries.sumOf { it.key.length + it.value.length })}}- is CliCommand.Play -> onMain { SongPlayer.playSong(c.uri, contextUri = c.context); JsonNull }+ is CliCommand.Play -> {+ // With a context, its songs too, as Android Auto and the phone give them: an audio-source+ // extension plays the list on from the song, under its name. `songs` says how many were+ // handed over (0: none, or a list without the song, which then plays alone as before).+ val page = c.context?.let { pageOf(it) }+ val songs = page?.tracks?.takeIf { it.isNotEmpty() }+ onMain {+ page?.let { SongPlayer.registerContextName(it.uri, it.name) }+ SongPlayer.playSong(c.uri, contextUri = c.context, songs = songs)+ }+ val id = c.uri.substringAfterLast(':')+ if (c.context == null) JsonNull else buildJsonObject { put("songs", songs?.takeIf { l -> l.any { it.spotifyTrackId == id } }?.size ?: 0) }+ }+ is CliCommand.AutoMixSet -> onMain {+ c.on?.let { com.music.spotui.automix.AutoMix.set(it); com.music.spotui.di.LocalPlayer.autoMixChanged(it) }+ JsonPrimitive(com.music.spotui.di.LocalPlayer.autoMixState())+ }+ CliCommand.AutoMixStatus -> onMain {+ buildJsonObject {+ put("state", com.music.spotui.di.LocalPlayer.autoMixState())+ put("journal", JsonArray(com.music.spotui.automix.AutoMix.journalLines().takeLast(30).map(::JsonPrimitive)))+ }+ }+ is CliCommand.AutoMixFiles -> {+ val all = com.music.spotui.data.local.LocalMusic.tracks(ctx, refresh = true)+ // Each name: a piece of "folder + title" (e.g. "Spotiflaccc/24").+ val picked = c.names.map { n -> all.firstOrNull { (it.folder + it.title).contains(n, ignoreCase = true) }+ ?: throw CliError("automix.files: no phone song matches $n") }+ onMain { com.music.spotui.di.LocalPlayer.play(picked, 0, context = "AutoMix test"); JsonArray(picked.map { JsonPrimitive(it.title) }) }+ }+ is CliCommand.AutoMixSeek -> onMain { com.music.spotui.di.LocalPlayer.seekTo(c.ms); JsonNull }CliCommand.Pause -> onMain { SongPlayer.pause(by = "cli"); JsonNull }CliCommand.Resume -> onMain { SongPlayer.play(by = "cli"); JsonNull }CliCommand.Next -> onMain { SongPlayer.next(); JsonNull }diff --cc base/app/src/main/java/com/music/spotui/data/local/LocalMusic.ktindex 50e353d8,1a40c8ed..e6a6c6bc--- a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt@@@ -21,14 -21,8 +21,16 @@@ data class LocalTrackval artUri: Uri,/** The file's folder on the phone, e.g. "Music/Album/" (MediaStore relative path). */val folder: String = "",+ /**+ * A Live Radio station (radio/ module) wrapped as a one-item "queue", not a file on this+ * phone: [id] is below both MediaStore's ids and the downloads' (see RadioPlayer.stableId)+ * and [uri] is the stream's address. This is how Radio shows in the mini player,+ * the full player, the notification and the lock screen exactly as a Local Files song does,+ * with no separate player or session of its own.+ */+ val isRadio: Boolean = false,+ /** MediaStore's track number (disc × 1000 + track), 0 unknown (streams and downloads have none). */+ val trackNo: Int = 0,)/** The device's music files, read through MediaStore (no file access beyond audio). */diff --cc base/app/src/main/java/com/music/spotui/di/LocalPlayer.ktindex bfa4d843,de5cabbc..0fc3a7a1--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt@@@ -74,20 -74,29 +74,31 @@@ object LocalPlayer.also(::tune)/**- * The default renderers, with the equalizer in the audio chain (each player its own, see- * EqualizerProcessor), ahead of the silence skipping and the speed the sink adds after it.+ * The default renderers, with the equalizer and the spatial stage after it in the audio chain+ * (each player its own, see EqualizerProcessor and SpatialProcessor), ahead of the silence+ * skipping and the speed the sink adds after them. The spatial stage is last of the two: its+ * limiter is what keeps a widened peak under full scale.*/@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)- private object Renderers : androidx.media3.exoplayer.DefaultRenderersFactory(Graph.app) {+ private open class AudioRenderers : androidx.media3.exoplayer.DefaultRenderersFactory(Graph.app) {override fun buildAudioSink(context: android.content.Context, enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean): androidx.media3.exoplayer.audio.AudioSink =androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context).setEnableFloatOutput(enableFloatOutput).setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)- .setAudioProcessors(arrayOf(EqualizerProcessor()))+ .setAudioProcessors(arrayOf(EqualizerProcessor(), SpatialProcessor())).build()}+ private object Renderers : AudioRenderers()++ /**+ * An AutoMix deck's renderers: its speed is the AudioTrack's own (set while it plays, at once and+ * without a break), not the sink's Sonic, which drains and starts over at each change (a click,+ * heard on some phones) and is heard only after the whole buffer.+ */+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)+ private object DeckRenderers : AudioRenderers() {+ init { setEnableAudioTrackPlaybackParams(true) }+ }private fun tune(p: ExoPlayer) {val pref = com.music.spotui.data.preferences.EqualizerPref@@@ -210,6 -124,102 +126,112 @@@setRepeatMode(SongPlayer.repeatMode.value)}+ /** The main player's listener: it moves to the deck that takes over at an AutoMix (see [takeOver]). */+ private var mainListener: Player.Listener? = null++ private fun listenerFor(p: ExoPlayer): Player.Listener = object : Player.Listener {+ override fun onEvents(player: Player, events: Player.Events) = publish()++ // Each change of what the player does, one line each, so a song that never starts says why.+ override fun onPlaybackStateChanged(state: Int) {+ log("state ${stateName(state)} at ${p.currentPosition} ms, item ${p.currentMediaItemIndex + 1}/${p.mediaItemCount}")+ // Casting: this player keeps the queue only, stopped; the song plays on the device.+ if (CastPlayback.active && state != Player.STATE_IDLE) { p.stop(); return }+ if (state == Player.STATE_READY) checkLength(p)++ // A station's server that closes the stream: a drop like any other, never "the end".++ val station = current()?.takeIf { it.isRadio }++ if (state == Player.STATE_ENDED && station != null) { reconnectRadio(p, station); return }+ if (state == Player.STATE_ENDED && !playAgain(p)) atEnd(p)+ }+ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {+ log("playWhenReady $playWhenReady (${PLAY_WHEN_READY_REASONS.getOrElse(reason - 1) { "reason $reason" }})")+ // A song on repeat paused at its end (see LocalRepeat): it starts again at 0:00.+ if (reason == Player.PLAY_WHEN_READY_CHANGE_REASON_END_OF_MEDIA_ITEM && playAgain(p)) return+ // A pause (or a lost focus) during a fade stops the fading-out song too.+ outgoing?.playWhenReady = playWhenReady+ if (!playWhenReady) mixPaused()+ if (playWhenReady && CastPlayback.active) { p.pause(); CastPlayback.play() }+ }+ // Moves the player makes by itself (not a seek, not a song's end): logged, so a song+ // jumping elsewhere shows where it went and why.+ override fun onPositionDiscontinuity(old: Player.PositionInfo, new: Player.PositionInfo, reason: Int) {+ if (reason == Player.DISCONTINUITY_REASON_SEEK) { mixMoved(); return }+ if (reason == Player.DISCONTINUITY_REASON_AUTO_TRANSITION) return+ log("moved by the player from ${old.positionMs} to ${new.positionMs} ms (reason $reason), item ${new.mediaItemIndex + 1}")+ }+ // The queue grew or shrank: a queue of one song repeated loops it as repeat one does.+ override fun onTimelineChanged(timeline: androidx.media3.common.Timeline, reason: Int) = applyRepeat(p)+ override fun onIsPlayingChanged(isPlaying: Boolean) {+ log("isPlaying $isPlaying at ${p.currentPosition} ms")+ if (isPlaying) errors.played()+ if (isPlaying) tick.run()++ // A station that plays on for a while has its reconnect tries back (see reconnectRadio).++ handler.removeCallbacks(radioSteady)++ if (isPlaying && current()?.isRadio == true) handler.postDelayed(radioSteady, RADIO_STEADY_MS)+ }+ override fun onPlaybackSuppressionReasonChanged(reason: Int) =+ log("suppressed: ${if (reason == Player.PLAYBACK_SUPPRESSION_REASON_NONE) "no" else "reason $reason"}")++ // The next song an extension streams is asked for as soon as this one starts: it then+ // starts at once instead of waiting for the extension when this one ends.+ // The last one starting asks what goes on after it (see continueIfLast).+ override fun onMediaItemTransition(mediaItem: androidx.media3.common.MediaItem?, reason: Int) {+ // Anything but the transition the fade itself makes (a skip, a tap in the queue) ends the fade.+ if (!startingFade) endFade()+ planned = null; dropped = null++ // From a station to a song or back: a station's repeat is off (see applyRepeat).++ applyRepeat(p)+ // The song kept from fading out is left behind: the next one fades as usual.+ if (p.currentMediaItemIndex != noFadeFor) noFadeFor = -1+ // A song to play again that the player went past by itself: put back, never followed.+ if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO && wentPastRepeat(p, p.previousMediaItemIndex)) return+ if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT) startsAtZero(p)+ if (skipHidden(p, reason)) return+ prefetchNext(p); continueIfLast(p)+ }++ // A song whose audio an extension did not give or that would not play (audio-source+ // hook) is never skipped silently: asked again once if the stream itself failed,+ // then Spotify plays it, where it was, and goes on; a queue that keeps failing stops.+ override fun onPlayerError(error: androidx.media3.common.PlaybackException) {+ log("error ${error.errorCodeName}: ${generic(error.cause?.toString() ?: error.message.orEmpty())}")++ val station = current()?.takeIf { it.isRadio }++ if (station != null) { radioError(p, station, error); return }+ val item = p.currentMediaItem?.localConfiguration?.uri ?: return+ if (item.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME) com.music.spotui.extensions.Extensions.noteAttempt(item.lastPathSegment) { it.copy(error = "${error.errorCodeName}: ${error.cause ?: error.message.orEmpty()}") }+ // A file that is gone (a download deleted while the queue played): never left stopped on it.+ if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME && DeletedDownloads.isMissingFile(error.errorCode, error.cause)) return fileGone(p, item)+ if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME) return+ val t = current() ?: return+ val noAudio = com.music.spotui.extensions.AudioRoute.isNoAudio(error)+ // No extension had it (the data source already asked twice): Spotify, no new ask.+ val again = errors.alreadyRetried(item.toString())+ if (!noAudio && !again) {+ log("${t.title}: the stream failed, the extensions are asked again once")+ val at = p.currentPosition+ prefetch.launch {+ runCatching { com.music.spotui.extensions.ExtensionAudio.resolve(item, again = true) }+ handler.post { if (exo === p && p.currentMediaItem?.localConfiguration?.uri == item) { p.prepare(); p.seekTo(at); p.play() } }+ }+ return+ }+ if (SongPlayer.playUnavailableOnSpotify(t, p.currentPosition)) return+ when (errors.failed(item.toString(), p.hasNextMediaItem())) {+ StreamErrors.Step.SKIP -> {+ log("skipped ${t.title}: no extension had it and Spotify cannot play it now")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable_skipped, t.title), android.widget.Toast.LENGTH_SHORT).show()+ p.seekToNextMediaItem()+ p.prepare()+ p.play()+ }+ else -> {+ log("stopped on ${t.title}: it cannot be played, and the songs after it failed too or none follows")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable, t.title), android.widget.Toast.LENGTH_LONG).show()+ }+ }+ }+ }+/*** The player's load errors: a song no extension gave usable audio for fails at once (each* retry would ask the extensions again, five asks in two seconds were seen); others as usual.