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.

16.3 KB
Raw Blame
package dev.lelonio.square.ui.player

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.media3.common.Player
import dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL
import kotlinx.coroutines.delay

/**
 * Everything the player UI draws **except** the playback position.
 *
 * Position is deliberately kept out: it changes several times a second, and
 * anything that reads it recomposes at that rate. Keeping it in this class would
 * drag the whole screen — including a hundred-row list — along with the seek
 * bar, which is enough jank to make the audio stutter. See [rememberPositionMs].
 */
data class PlaybackState(
    val hasItem: Boolean = false,
    /** Spotify URI of the current track, for highlighting it in lists. */
    val mediaId: String? = null,
    val title: String = "",
    val artist: String = "",
    /**
     * The record it is from, where the queue knows it.
     *
     * Only the player uses it, and only to ask the other catalogue for that
     * record's own artwork — the tall picture and the moving cover a song
     * inherits from its album; see AppleCatalog.
     */
    val album: String = "",
    /** And its address, where the queue knows it; see EXTRA_ALBUM_URI. */
    val albumUri: String? = null,
    val artworkUrl: String? = null,
    /** Whether the source rates this track as explicit; see EXTRA_EXPLICIT. */
    val explicit: Boolean = false,
    val isPlaying: Boolean = false,
    /**
     * What the listener asked for, which is not always what is happening.
     *
     * A track being fetched is not playing yet, and the play button read that
     * as "still paused": every tap during a load meant play again, so the load
     * could not be called off and the button that says pause never appeared.
     * The glyph and the tap both follow this; [isPlaying] stays the fact, for
     * the things that follow the sound rather than the intent.
     */
    val wantsPlay: Boolean = false,
    val isBuffering: Boolean = false,
    val durationMs: Long = 0,
    val hasNext: Boolean = false,
    val hasPrevious: Boolean = false,
    val shuffleEnabled: Boolean = false,
    val smartShuffle: Boolean = false,
    val smartRecommended: Boolean = false,
    val repeatMode: Int = Player.REPEAT_MODE_OFF,
    /** Tempo, 1.0 being the track as recorded. */
    val speed: Float = 1f,
    /** Pitch, independent of [speed]. */
    val pitch: Float = 1f,
    /**
     * Where this queue came from, ready to read: "Playlist · Estate 2025".
     *
     * Carried on the media item rather than derived here, because by the time
     * the player sees a track the only thing left of the tap that started it is
     * a URI, and a URI does not say whether it was reached from a playlist, an
     * 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,
    /**
     * Each credited artist separately, so a line naming two of them opens the
     * one that was pressed. Empty when the source gave only the joined names.
     */
    val artists: List<dev.lelonio.square.data.CatalogArtist> = emptyList(),
    val contextUri: String? = null,
)

/**
 * 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,
    // The intent as well as the fact.
    //
    // Every glyph on this screen follows `wantsPlay`, because locally that is
    // what a tap changes and what the listener should see change. A remote
    // playback left it at its default, so music playing in another room drew a
    // play button on a moving progress bar: the bar followed the fact and the
    // button followed an intent nobody had set. On another device the two are
    // the same thing — there is no buffering to ride out here, only what that
    // device is doing.
    wantsPlay = 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

/** Mirrors the slow-changing part of a [Player] into Compose state. */
@Composable
fun rememberPlaybackState(
    player: Player?,
    /**
     * What to report until the media controller connects.
     *
     * Connecting takes a few hundred milliseconds, and the whole player is left
     * uncomposed while there is no item, so without this the app came back from
     * the launcher showing the home page underneath until the controller
     * landed. Read from the saved session, which already holds the track.
     */
    seed: PlaybackState? = null,
): State<PlaybackState> {
    val state = remember { mutableStateOf(seed ?: PlaybackState()) }
    // Whether a live player has ever answered. Once one has, the saved session
    // is out of date by definition — going back to it when the controller drops
    // is what made the player flash the previous track on the way back into the
    // app.
    val seenLive = remember { mutableStateOf(false) }
    // Whether a live player has ever had a track in it.
    //
    // Connecting and being ready are not the same thing. The controller answers
    // in a few tens of milliseconds, but when the service had been stopped the
    // player behind it is empty for another second and a half while the engine
    // reconnects and the queue is restored. Answering "no track" during that
    // window is not news, it is the service still getting dressed, and taking
    // it at its word is what made the mini player vanish on the way back in and
    // reappear a moment later.
    val seenItem = remember { mutableStateOf(false) }

    DisposableEffect(player) {
        if (player == null) {
            if (!seenLive.value) state.value = seed ?: PlaybackState()
            return@DisposableEffect onDispose {}
        }
        seenLive.value = true

        fun snapshot() {
            val metadata = player.mediaMetadata
            val next = PlaybackState(
                hasItem = player.currentMediaItem != null,
                mediaId = player.currentMediaItem?.mediaId,
                title = metadata.title?.toString().orEmpty(),
                artist = metadata.artist?.toString().orEmpty(),
                album = metadata.albumTitle?.toString().orEmpty(),
                artworkUrl = metadata.artworkUri?.toString(),
                explicit = metadata.extras
                    ?.getBoolean(dev.lelonio.square.ui.EXTRA_EXPLICIT) == true,
                isPlaying = player.isPlaying,
                wantsPlay = player.playWhenReady,
                isBuffering = player.playbackState == Player.STATE_BUFFERING,
                durationMs = metadata.durationMs ?: player.duration.coerceAtLeast(0),
                hasNext = player.hasNextMediaItem(),
                hasPrevious = player.hasPreviousMediaItem(),
                shuffleEnabled = player.shuffleModeEnabled,
                smartShuffle = player.shuffleModeEnabled && player.currentMediaItem?.mediaMetadata?.extras?.getBoolean(dev.lelonio.square.data.SmartShuffle.MODE) == true,
                smartRecommended = player.currentMediaItem?.mediaMetadata?.extras?.getBoolean(dev.lelonio.square.data.SmartShuffle.RECOMMENDED) == true,
                repeatMode = player.repeatMode,
                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),
                albumUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ALBUM_URI),
                artists = run {
                    val names = metadata.extras
                        ?.getStringArrayList(dev.lelonio.square.ui.EXTRA_ARTIST_NAMES)
                    val uris = metadata.extras
                        ?.getStringArrayList(dev.lelonio.square.ui.EXTRA_ARTIST_URIS)
                    if (names == null || uris == null) {
                        emptyList()
                    } else {
                        names.zip(uris) { name, uri ->
                            dev.lelonio.square.data.CatalogArtist(name, uri)
                        }
                    }
                },
                contextUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI),
            )
            if (next.hasItem) {
                seenItem.value = true
            } else if (!seenItem.value && state.value.hasItem) {
                // Still getting dressed: keep what is on screen rather than
                // clearing it. Bounded by seenItem, so the first real track
                // ends this for good, and by the timeout below, so a queue that
                // genuinely is empty does not leave a stale track behind for
                // the life of the screen.
                return
            }
            // Equality check, not blind assignment: the player emits events far
            // more often than these fields actually change.
            if (next != state.value) state.value = next
        }

        val listener = object : Player.Listener {
            override fun onEvents(player: Player, events: Player.Events) = snapshot()
        }
        player.addListener(listener)
        snapshot()

        onDispose { player.removeListener(listener) }
    }

    // The end of the grace period above. Long enough for a cold service to
    // restore its queue, measured at about 1.6 seconds, and short enough that
    // an empty player really is empty by the time it expires.
    LaunchedEffect(player) {
        if (player == null || seenItem.value) return@LaunchedEffect
        delay(EMPTY_PLAYER_GRACE_MS)
        if (!seenItem.value && player.currentMediaItem == null) {
            seenItem.value = true
            state.value = PlaybackState()
        }
    }

    return state
}

/**
 * The upcoming tracks, taken from the player's timeline.
 *
 * Rebuilt only when the timeline or the current item changes, not on every
 * event: walking a hundred media items is not something to do four times a
 * second.
 */
@Composable
fun rememberQueue(player: Player?): State<List<QueueEntry>> {
    val queue = remember { mutableStateOf(emptyList<QueueEntry>()) }

    DisposableEffect(player) {
        if (player == null) {
            queue.value = emptyList()
            return@DisposableEffect onDispose {}
        }

        fun rebuild() {
            val current = player.currentMediaItemIndex
            // The last few heard as well as what comes next.
            //
            // They were left out once because they pushed the upcoming tracks
            // off the bottom of the panel; the panel now opens on the playing
            // track instead, with these above it for whoever scrolls up. A song
            // that had ended simply vanished from the list, which read as the
            // app throwing it away (#30).
            val from = (current - QUEUE_HISTORY).coerceAtLeast(0)
            queue.value = (from until player.mediaItemCount).map { index ->
                val metadata = player.getMediaItemAt(index).mediaMetadata
                QueueEntry(
                    index = index,
                    uri = player.getMediaItemAt(index).mediaId,
                    title = metadata.title?.toString().orEmpty(),
                    artist = metadata.artist?.toString().orEmpty(),
                    isCurrent = index == current,
                    played = index < current,
                    recommended = metadata.extras?.getBoolean(dev.lelonio.square.data.SmartShuffle.RECOMMENDED) == true,
                    queued = metadata.extras?.getBoolean(dev.lelonio.square.ui.EXTRA_PLAY_NEXT) == true,
                    contextLabel = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL).orEmpty(),
                )
            }
        }

        val listener = object : Player.Listener {
            override fun onEvents(player: Player, events: Player.Events) {
                if (events.containsAny(
                        Player.EVENT_TIMELINE_CHANGED,
                        Player.EVENT_MEDIA_ITEM_TRANSITION,
                    )
                ) {
                    rebuild()
                }
            }
        }
        player.addListener(listener)
        rebuild()

        onDispose { player.removeListener(listener) }
    }

    return queue
}

/**
 * Playback position, polled while playing.
 *
 * Separate from [PlaybackState] so only the seek bar reads it. The engine
 * reports position once a second, which on screen would advance in visible
 * steps; polling four times a second smooths it out and costs nothing when
 * paused, because the loop simply does not run.
 */
@Composable
fun rememberPositionMs(player: Player?, isPlaying: Boolean): State<Long> {
    val position = remember { mutableLongStateOf(0L) }

    // A seek is read the moment it happens, playing or not. Polled only while
    // playing, the position stayed where it was after a seek made while paused,
    // or while a video buffered at its new place: the time on screen was wrong,
    // and the bar's thumb went back to the old place before jumping forward.
    DisposableEffect(player) {
        val listener = object : Player.Listener {
            override fun onPositionDiscontinuity(
                oldPosition: Player.PositionInfo,
                newPosition: Player.PositionInfo,
                reason: Int,
            ) {
                position.longValue = newPosition.positionMs.coerceAtLeast(0)
            }
        }
        player?.addListener(listener)
        onDispose { player?.removeListener(listener) }
    }

    LaunchedEffect(player, isPlaying) {
        if (player == null) {
            position.longValue = 0
            return@LaunchedEffect
        }
        position.longValue = player.currentPosition.coerceAtLeast(0)
        if (!isPlaying) return@LaunchedEffect

        while (true) {
            delay(250)
            position.longValue = player.currentPosition.coerceAtLeast(0)
        }
    }

    return position
}

/** How many of the tracks already heard the queue panel keeps above the playing one. */
private const val QUEUE_HISTORY = 20