Skip to content

Native Android client for Spotify, built with Jetpack Compose

Repeat once replays the song one time then goes on with repeat off (extension and Spotify songs, a skip or another pick cancels it); a seek to the end counts as the end, other seeks stay within the length the player knows; the Spotify copy is put back instead of followed when it moves on at a song that repeats; repeat all keeps its mode across sessions and drops the song radio; the three song lengths are logged

kota-zo0aeb5d539efc
diff --git a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
index 62644ba3..a6742e78 100644
--- a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
+++ b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
@@ -209,8 +209,9 @@ object ConnectMirror {
}
val t = LocalPlayer.current() ?: return
val (previousId, nextId) = LocalPlayer.neighbourIds()
+ // The end the local player really knows (its audio's), not Spotify's length: unknown, it is never near.
val local = MirrorRules.Local(
- SPOTIFY_TRACK_PREFIX + LocalPlayer.spotifyIdOf(t), LocalPlayer.playWhenReady(), LocalPlayer.position(), LocalPlayer.duration(),
+ SPOTIFY_TRACK_PREFIX + LocalPlayer.spotifyIdOf(t), LocalPlayer.playWhenReady(), LocalPlayer.position(), LocalPlayer.knownLength() ?: 0L,
nextUri = nextId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it },
previousUri = previousId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it },
)
@@ -219,7 +220,8 @@ object ConnectMirror {
if (quiet) { main.removeCallbacks(recheck); main.postDelayed(recheck, echo.remainingMs() + RECHECK_SLACK_MS) }
// Recovering from an ad or a reload: a song other than the asked one is the player's own play, sent back.
val sure = landed && SystemClock.elapsedRealtime() >= recoverUntil
- when (val f = MirrorRules.onWeb(web, w, local, quiet, sure, predicted, previousUri, gap, wantAt, wantLength, recentUris())) {
+ val repeats = LocalPlayer.repeatsCurrent()
+ when (val f = MirrorRules.onWeb(web, w, local, quiet, sure, predicted, previousUri, gap, wantAt, wantLength, recentUris(), repeats)) {
Follow.Nothing -> {}
// A play waits already (coalescing, backing off): not another one.
Follow.Retry -> if (pendingContext != null) Unit else if (retries++ < MAX_RETRIES) {
@@ -241,6 +243,10 @@ object ConnectMirror {
} else backOff(w)
is Follow.Play -> { log("${f.uri} picked on another device"); moved(web, s); SongPlayer.followRemotePlay(item, s.contextUri, f.positionMs) }
is Follow.Align -> command(ECHO_MS) { api.player.seek(f.ms) }
+ Follow.Back -> if (pendingContext != null) Unit else {
+ log("the page went on to ${web.uri} by itself while ${t.title} is to play again here: put back on ${w.uri}, not followed")
+ playNow(w.uri, w.uri)
+ }
}
}
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 4e45b3a0..dc94ab85 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -114,6 +114,8 @@ object LocalPlayer {
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()
+ // 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)
prefetchNext(p); continueIfLast(p)
}
@@ -231,6 +233,13 @@ object LocalPlayer {
*/
fun play(list: List<LocalTrack>, index: Int, shuffle: Boolean = false, context: String? = null, contextUri: String = "", startMs: Long = 0L, continues: Boolean = false) {
if (list.isEmpty()) return
+ // Another song picked: repeat once was for the song left.
+ val shown = SongPlayer.nowPlaying.value.uri.substringAfterLast(':')
+ val picked = list.getOrNull(index.coerceIn(0, list.lastIndex))?.let(::spotifyId).orEmpty()
+ if (SongPlayer.repeatMode.value == LocalRepeat.ONE && (picked.isBlank() || picked != shown)) {
+ log("repeat once: cancelled (another song picked), back to off")
+ SongPlayer.setRepeatMode(LocalRepeat.OFF)
+ }
SongPlayer.pauseEngineForLocal()
forgetRadio(); this.continues = continues
tracks.clear(); tracks.addAll(list); unshuffled = null
@@ -241,6 +250,10 @@ object LocalPlayer {
endFade()
val p = player()
p.shuffleModeEnabled = false
+ // A new session takes the repeat the player shows (changed on a Spotify song meanwhile).
+ replaying = null
+ repeat = SongPlayer.repeatMode.value
+ applyRepeat(p)
p.setMediaItems(list.map(::item), index.coerceIn(0, list.lastIndex), startMs.coerceAtLeast(0L))
p.prepare()
if (shuffle) setShuffle(true)
@@ -390,6 +403,7 @@ object LocalPlayer {
return endFade()
}
endFade()
+ cancelOnce("next")
exo?.let {
if (it.hasNextMediaItem()) { com.music.spotui.extensions.Extensions.skipAsked("forward"); it.seekToNextMediaItem() }
// A queue of one song repeated (see LocalRepeat): Next plays it again, as the queue's wrap would.
@@ -399,6 +413,7 @@ object LocalPlayer {
}
fun previous() {
endFade()
+ cancelOnce("previous")
exo?.let {
if (position() > 3000 || !it.hasPreviousMediaItem()) seekTo(0)
else { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() }
@@ -407,6 +422,7 @@ object LocalPlayer {
/** Back to the song before the current one, wherever this one is (a previous asked on another device). */
fun previousItem() {
endFade()
+ cancelOnce("previous")
exo?.let { if (it.hasPreviousMediaItem()) { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() } }
}
@@ -421,8 +437,14 @@ object LocalPlayer {
exo?.let { p ->
// A seek into the tail of a song is the user's choice: that song then ends as usual.
if (CrossfadeRamp.shouldStart(CrossfadePref.seconds, duration(), ms)) noFadeFor = p.currentMediaItemIndex
- if (CastPlayback.active) CastPlayback.seek(ms)
- p.seekTo(ms)
+ if (CastPlayback.active) { CastPlayback.seek(ms); p.seekTo(ms); return }
+ val known = knownLength()
+ // To the song's end: it ended, and plays again as its repeat says (never the next song then).
+ if (LocalRepeat.seekEnds(ms, known) && playAgain(p, seekAt = ms)) return
+ // Within the length the player knows: Spotify's (or an extension's) is not the audio's.
+ val to = LocalRepeat.seekTarget(ms, known)
+ if (to != ms) log("seek to $ms ms kept within the audio's $known ms")
+ p.seekTo(to)
}
}
/**
@@ -462,6 +484,7 @@ object LocalPlayer {
val p = exo ?: return
if (index !in tracks.indices) return
endFade()
+ if (index != p.currentMediaItemIndex) cancelOnce("another song picked in the queue")
val (order, at) = LocalQueueOrder.skip(tracks.toList(), p.currentMediaItemIndex, index, isQueued)
if (order != tracks) arrange(order)
p.seekTo(at, 0L); p.play()
@@ -585,6 +608,8 @@ object LocalPlayer {
private fun radioCame(p: ExoPlayer, id: String, songs: List<com.music.spotui.data.entity.SongsModel>) {
if (!active.value || radioOf != id) return
+ // Repeat all tapped meanwhile: the queue plays again from its first song instead.
+ if (repeat == LocalRepeat.ALL) { log("song radio not added: repeat all plays the queue again"); forgetRadio(); return }
val more = com.music.spotui.extensions.AudioRoute.continuation(songs, tracks.map(::spotifyId))
if (more.isEmpty()) {
radioEmpty = true
@@ -628,7 +653,51 @@ object LocalPlayer {
fun setRepeatMode(mode: Int) {
repeat = mode
- exo?.let(::applyRepeat)
+ // Repeat once tapped again, or another mode: its replay to come is cancelled.
+ if (mode != LocalRepeat.ONE) replaying = null
+ exo?.let { applyRepeat(it); if (active.value) continueIfLast(it) }
+ }
+
+ /** The song whose one replay (repeat once) plays; null: none yet. */
+ private var replaying: LocalTrack? = null
+
+ /** The current song plays again at its end (repeat once still to replay it, a one-song queue repeated). */
+ fun repeatsCurrent(): Boolean = exo?.let { p ->
+ active.value && !CastPlayback.active && LocalRepeat.atEnd(repeat, p.mediaItemCount, replayedNow()) == LocalRepeat.End.REPLAY
+ } == true
+
+ private fun replayedNow(): Boolean = replaying != null && replaying === current()
+
+ /** Manual moves (next, previous, a pick) cancel repeat once: it was for the song left. */
+ private fun cancelOnce(why: String) {
+ if (repeat != LocalRepeat.ONE) return
+ log("repeat once: cancelled ($why), back to off")
+ SongPlayer.setRepeatMode(LocalRepeat.OFF)
+ }
+
+ /** Repeat once played its song again: off now (the buttons show it), the queue goes on. */
+ private fun onceDone() {
+ log("repeat once: ${current()?.title} replayed, back to off")
+ replaying = null
+ SongPlayer.setRepeatMode(LocalRepeat.OFF)
+ }
+
+ /**
+ * The player went on to the next song by itself ([left]: the item it left, the one before) while that one was
+ * to play again: put back on it at 0:00 as its end would (the player's end must never decide
+ * past a repeat). After repeat once's replay, going on is right: the mode goes off.
+ */
+ private fun wentPastRepeat(p: ExoPlayer, left: Int): Boolean {
+ val t = tracks.getOrNull(left) ?: return false
+ if (CastPlayback.active || !active.value || left == p.currentMediaItemIndex) return false
+ when (LocalRepeat.atEnd(repeat, p.mediaItemCount, replaying === t)) {
+ LocalRepeat.End.NEXT -> return false
+ LocalRepeat.End.ONCE_DONE -> { log("repeat once: ${t.title} replayed, back to off"); replaying = null; SongPlayer.setRepeatMode(LocalRepeat.OFF); return false }
+ LocalRepeat.End.REPLAY -> {}
+ }
+ log("the player went on to item ${p.currentMediaItemIndex + 1} by itself while ${t.title} is to play again: put back on it, not followed")
+ replay(p, left, p.currentPosition)
+ return true
}
/**
@@ -644,17 +713,35 @@ object LocalPlayer {
* A song on repeat that reached its end plays again from 0:00, and the Connect mirror's copy
* plays it anew (a new play, as Spotify's repeat counts one). False: the song does not loop.
*/
- private fun playAgain(p: ExoPlayer): Boolean {
- if (CastPlayback.active || !active.value || !LocalRepeat.loopsSong(repeat, p.mediaItemCount)) return false
+ private fun playAgain(p: ExoPlayer, seekAt: Long? = null): Boolean {
+ if (CastPlayback.active || !active.value) return false
+ val end = LocalRepeat.atEnd(repeat, p.mediaItemCount, replayedNow())
+ if (end == LocalRepeat.End.NEXT) return false
// Already played again: the pause at the end and the end of the last song come together.
- if (p.playWhenReady && p.playbackState != Player.STATE_ENDED) return true
- val ended = p.currentPosition
+ if (seekAt == null && p.playWhenReady && p.playbackState != Player.STATE_ENDED) return true
+ if (end == LocalRepeat.End.ONCE_DONE) {
+ onceDone()
+ // A seek to the end: the song ends there now, as with repeat off.
+ if (seekAt != null) return false
+ if (p.hasNextMediaItem()) { endFade(); p.seekToNextMediaItem(); p.play(); return true }
+ // The last song: its end goes on as the queue's end (see atEnd), once the player is there.
+ if (p.playbackState == Player.STATE_ENDED) return false
+ p.play()
+ return true
+ }
+ if (seekAt != null) log("seek to the end of ${current()?.title} ($seekAt ms): it ended, and plays again")
+ replay(p, p.currentMediaItemIndex, seekAt ?: p.currentPosition)
+ return true
+ }
+
+ /** The song at [index] plays again from 0:00, and the Connect mirror's copy plays it anew (a new play, as Spotify's repeat counts one). */
+ private fun replay(p: ExoPlayer, index: Int, endedAt: Long) {
endFade()
- p.seekTo(p.currentMediaItemIndex, 0L)
+ if (repeat == LocalRepeat.ONE) replaying = tracks.getOrNull(index)
+ p.seekTo(index, 0L)
p.play()
- log("repeat: ${current()?.title} plays again from ${p.currentPosition} ms (it ended at $ended ms)")
+ log("repeat: ${current()?.title} plays again from ${p.currentPosition} ms (it ended at $endedAt ms)")
ConnectMirror.onLocalRepeat()
- return true
}
/**
@@ -682,6 +769,8 @@ object LocalPlayer {
fun playbackState(): String = if (CastPlayback.active) CastPlayback.state() else exo?.let { stateName(it.playbackState) } ?: "none"
fun position() = if (CastPlayback.active) CastPlayback.position() else exo?.currentPosition ?: 0L
fun duration() = exo?.duration?.takeIf { it > 0 } ?: current()?.durationMs ?: 0L
+ /** The length the player knows of the audio itself (null: not known), never Spotify's. */
+ fun knownLength(): Long? = if (CastPlayback.active) null else exo?.duration?.takeIf { it != C.TIME_UNSET && it > 0 }
fun current(): LocalTrack? = exo?.currentMediaItemIndex?.let { tracks.getOrNull(it) }
/**
@@ -717,8 +806,15 @@ object LocalPlayer {
private fun checkLength(p: ExoPlayer) {
val t = current() ?: return
if (lengthChecked === t) return
- val audio = p.duration.takeIf { it > 0 } ?: return
lengthChecked = t
+ // The three lengths, once: the audio's as the player knows it (what seeks and ends go by),
+ // the one the extension announced, and Spotify's.
+ val audio = p.duration.takeIf { it != C.TIME_UNSET && it > 0 }
+ val announced = t.uri.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }?.lastPathSegment
+ ?.let(com.music.spotui.extensions.ExtensionAudio::announcedLengthOf)
+ log("${t.title}: lengths player ${audio ?: "unknown"} ms, extension ${announced?.let { "$it ms" } ?: "none"}, Spotify ${t.durationMs} ms" +
+ if (p.isCurrentMediaItemSeekable) "" else ", NOT seekable")
+ audio ?: return
if (t.durationMs > 0 && kotlin.math.abs(audio - t.durationMs) > LENGTH_GAP_MS)
log("${t.title}: the audio lasts $audio ms, the song ${t.durationMs} ms (synced lyrics may be off by the difference)")
}
@@ -766,8 +862,10 @@ object LocalPlayer {
/** The Cast device finished the song: the next one, as this player's own end would. */
internal fun castFinished() {
val p = exo ?: return
+ val end = LocalRepeat.atEnd(repeat, p.mediaItemCount, replayedNow())
+ if (end == LocalRepeat.End.ONCE_DONE) onceDone()
when {
- LocalRepeat.loopsSong(repeat, p.mediaItemCount) -> CastPlayback.replay()
+ end == LocalRepeat.End.REPLAY -> { if (repeat == LocalRepeat.ONE) replaying = current(); CastPlayback.replay() }
p.hasNextMediaItem() -> {
val before = current()
p.seekToNextMediaItem()
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalRepeat.kt b/base/app/src/main/java/com/music/spotui/di/LocalRepeat.kt
index ec49b4e2..9b5055c6 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalRepeat.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalRepeat.kt
@@ -8,13 +8,19 @@ package com.music.spotui.di
* ExoPlayer's own repeat: that plays the song again as a new period of the same item, and with an
* extension's stream it was seen starting again near the last seek instead of at 0:00 (and earlier
* on each loop). The player pauses at the song's end instead and Myspoti puts it back at 0:00.
+ *
+ * Repeat one is "repeat once": the song plays again one time, then the queue goes on and the mode
+ * goes back to off ([atEnd]). A queue of one song repeated (repeat all) loops it for good.
*/
object LocalRepeat {
const val OFF = 0
const val ALL = 1
const val ONE = 2
- /** The song plays again at its end, put back at 0:00 by Myspoti (see the object's note). */
+ /**
+ * The song pauses at its end for Myspoti to play it again from 0:00 (see the object's note), or,
+ * after repeat once's replay, to go on to the next song ([atEnd]).
+ */
fun loopsSong(mode: Int, items: Int): Boolean = mode == ONE || mode == ALL && items == 1
/** The repeat ExoPlayer is given: its own only for a queue of several songs repeated. */
@@ -27,4 +33,48 @@ object LocalRepeat {
/** A song the player moved to by itself (the next one, the queue again) that did not start at 0:00. */
fun startedLate(positionMs: Long): Boolean = positionMs > START_SLACK_MS
+
+ /** What a song that reached its end does. */
+ enum class End {
+ /** The player's own way: the next song, the queue again (repeat all), or the queue's end. */
+ NEXT,
+ /** Played again from 0:00 by Myspoti. */
+ REPLAY,
+ /** Repeat once and its replay just ended: the mode goes back to off and the queue goes on. */
+ ONCE_DONE,
+ }
+
+ /** [replayed]: the song ending is the one repeat once already played again. */
+ fun atEnd(mode: Int, items: Int, replayed: Boolean): End = when {
+ mode == ONE -> if (replayed) End.ONCE_DONE else End.REPLAY
+ mode == ALL && items == 1 -> End.REPLAY
+ else -> End.NEXT
+ }
+
+ /** This close to the end the player knows, a seek is to the song's end (the bar dragged to its end). */
+ const val SEEK_END_SLACK_MS = 500L
+
+ /** A seek to [ms] reaches the end of a song the player knows to last [knownMs] (null: not known). */
+ fun seekEnds(ms: Long, knownMs: Long?): Boolean = knownMs != null && knownMs > 0 && ms >= knownMs - SEEK_END_SLACK_MS
+
+ /**
+ * Where a seek to [ms] goes: within the length the player knows ([knownMs], null: not known),
+ * never past it (a length told by Spotify or an extension is not the audio's).
+ */
+ fun seekTarget(ms: Long, knownMs: Long?): Long =
+ if (knownMs != null && knownMs > 0) ms.coerceIn(0L, knownMs - 1) else ms.coerceAtLeast(0L)
+
+ /**
+ * Repeat once on a Spotify song: Spotify's repeat-track loops for good, so the page seen
+ * starting the same song again ([sameSong]) near 0 ([nowMs]) when its clock had it at the end
+ * ([beforeMs] of [lengthMs]) is the one replay: repeat goes back to off, the replay then ends
+ * into the next song.
+ */
+ fun pageRestarted(sameSong: Boolean, beforeMs: Long, lengthMs: Long, nowMs: Long): Boolean =
+ sameSong && lengthMs > 0 && beforeMs >= lengthMs - PAGE_END_WINDOW_MS && nowMs <= PAGE_RESTART_MS && nowMs < beforeMs
+
+ /** The page's clock this close to the end: the song was ending (the page reports every few seconds). */
+ const val PAGE_END_WINDOW_MS = 5_000L
+ /** A song the page shows this close to 0:00 started again. */
+ const val PAGE_RESTART_MS = 10_000L
}
diff --git a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
index 2403bc5f..88e911be 100644
--- a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
+++ b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
@@ -57,6 +57,11 @@ object MirrorRules {
data class Play(val uri: String, val positionMs: Long) : Follow
/** Only drift: the unheard Web Player is put on the local position (no jump is heard). */
data class Align(val ms: Long) : Follow
+ /**
+ * The Web Player went on by itself (its song ended, or its own repeat moved it) while the
+ * local song is to play again: put back on the local song, the local player not moved.
+ */
+ data object Back : Follow
}
/**
@@ -69,11 +74,13 @@ object MirrorRules {
* [wantAtMs], [wantLengthMs]: where the Web Player is in [want]'s song and that song's length as it
* has it (a stream of the extension can be longer than Spotify's track). [recentUris]: the songs
* the mirror itself asked the Web Player to play lately: a state on one of them is a late answer.
+ * [repeats]: the local song plays again at its end (repeat once still to replay it, or a queue
+ * of one song repeated): the Web Player going on at the end is never followed, it is put back.
*/
fun onWeb(
web: Web, want: Want, local: Local, quiet: Boolean, landed: Boolean, predictedMs: Long?,
previousUri: String? = null, gapFromMs: Long? = null, wantAtMs: Long? = null, wantLengthMs: Long = 0,
- recentUris: Collection<String> = emptyList(),
+ recentUris: Collection<String> = emptyList(), repeats: Boolean = false,
): Follow {
val late = web.uri != want.uri && web.uri in recentUris
// During an echo, only a third song once it landed is remote (a double skip on another
@@ -87,6 +94,8 @@ object MirrorRules {
// The local player went on by itself, or the song is ending (on either side): the Web
// Player's move is that end, and the local side sends what comes next.
val pageEnding = wantLengthMs > 0 && wantAtMs != null && wantLengthMs - wantAtMs < END_WINDOW_MS
+ // The local song plays again: the Web Player ending it and going on is its own move, undone.
+ if (repeats && local.uri == want.uri && web.uri != want.uri && (local.nearEnd || pageEnding)) return Follow.Back
if (local.uri != want.uri || local.nearEnd || pageEnding) return Follow.Nothing
if (web.uri != want.uri) return when (web.uri) {
local.nextUri -> Follow.Next
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index d196b1d4..bf3b2763 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -562,6 +562,7 @@ object SongPlayer {
playing = resolvePlaying(s.isPaused)
bufferingState.value = waiting(s)
SpeakerKeepAlive.set(playing && _activeDevice.value == null)
+ val lengthBefore = durationMs
durationMs = item?.durationMs ?: 0L
val reported = s.positionAt(System.currentTimeMillis())
// A seek on its way: the page's old position does not take the clock back (see [seekTo]).
@@ -574,6 +575,18 @@ object SongPlayer {
}
val leftId = trackIdOf(_nowPlaying.value.uri)
val trackChanged = uri != _nowPlaying.value.uri
+ // Repeat once on a Spotify song: the page's repeat-track loops for good. The page seen
+ // starting the song again is its one replay: repeat goes off there, and that replay ends
+ // into the next song. Another song under repeat-track (a skip, a pick) cancels it.
+ if (item != null && s.repeat == Repeat.TRACK && _repeatMode.value == LocalRepeat.ONE) {
+ if (LocalRepeat.pageRestarted(!trackChanged, predicted, lengthBefore, reported)) {
+ app.myspoti.host.android.Logbook.log("repeat once: ${item.name} replayed, back to off")
+ setRepeatMode(LocalRepeat.OFF)
+ } else if (trackChanged && _nowPlaying.value.uri.isNotBlank() && !seeking) {
+ app.myspoti.host.android.Logbook.log("repeat once: cancelled (${item.name} plays now), back to off")
+ setRepeatMode(LocalRepeat.OFF)
+ }
+ }
// Autoplay off: stop once, when the player moves on to a track it picked itself.
// Tracks only: this is the music setting (similar songs). An episode the page rolls on
// to after the previous one belongs to the show, not to that recommendation autoplay —
@@ -1281,6 +1294,7 @@ object SongPlayer {
app.myspoti.host.android.Logbook.log("next asked by $by")
Haptics.click()
if (LocalPlayer.active.value) { LocalPlayer.next(); return }
+ cancelRepeatOnce("next")
com.music.spotui.extensions.Extensions.skipAsked("forward")
// Spotify is refusing licences: every skip asks for one more and makes the limit last
// (a tester's log: 183 refusals in 8 min of fast skipping, the page then skipping on its
@@ -1483,6 +1497,7 @@ object SongPlayer {
app.myspoti.host.android.Logbook.log("previous asked by $by")
Haptics.click()
if (LocalPlayer.active.value) { LocalPlayer.previous(); return }
+ cancelRepeatOnce("previous")
if (getCurrentPosition() <= 3_000) com.music.spotui.extensions.Extensions.skipAsked("backward")
intendPlaying()
// A previous counts as -1 in the burst. Skips still waiting to be sent (nexts tapped
@@ -1624,7 +1639,7 @@ object SongPlayer {
fun setRepeat(on: Boolean) = setRepeatMode(if (on) 1 else 0)
fun setRepeatMode(mode: Int) {
- if (LocalPlayer.active.value) { _repeatMode.value = mode; LocalPlayer.setRepeatMode(mode); return }
+ if (LocalPlayer.active.value) { _repeatMode.value = mode; boundState?.repeat?.value = mode != 0; LocalPlayer.setRepeatMode(mode); return }
Haptics.toggle(mode != 0)
_repeatMode.value = mode
repeatWanted = mode
@@ -1650,6 +1665,13 @@ object SongPlayer {
fun cycleRepeat() = setRepeatMode((_repeatMode.value + 1) % 3)
+ /** A manual move on a Spotify song cancels repeat once: it was for the song left. */
+ private fun cancelRepeatOnce(why: String) {
+ if (_repeatMode.value != LocalRepeat.ONE) return
+ app.myspoti.host.android.Logbook.log("repeat once: cancelled ($why), back to off")
+ setRepeatMode(LocalRepeat.OFF)
+ }
+
/** Podcast playback speed (Spotify refuses it on music). */
fun setSpeed(speed: Double) {
_speed.value = speed
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
index d17eb988..69a81a4f 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
@@ -118,6 +118,9 @@ object ExtensionAudio {
/** The quality the extension announced for the song [trackId] ("FLAC · 24-bit · 96 kHz"), or null. */
fun qualityOf(trackId: String): String? = known[trackId]?.stream?.qualityLabel()
+ /** The length the extension announced for the song [trackId]'s audio, ms, or null (none said, not answered). */
+ fun announcedLengthOf(trackId: String): Long? = known[trackId]?.stream?.durationMs
+
/** How the audio of the song [trackId] comes, for the diagnostic ("dash", "url audio/flac"), or null. */
fun deliveryOf(trackId: String): String? =
known[trackId]?.stream?.let { if (it.manifest != null) "dash" else "url ${it.mimeType ?: "untyped"}" }
diff --git a/base/app/src/main/res/values-fr/immersive_player_strings.xml b/base/app/src/main/res/values-fr/immersive_player_strings.xml
index 4de549b2..6a26ed21 100644
--- a/base/app/src/main/res/values-fr/immersive_player_strings.xml
+++ b/base/app/src/main/res/values-fr/immersive_player_strings.xml
@@ -17,7 +17,7 @@
<string name="immersive_player_shuffle_off">Aléatoire : désactivé</string>
<string name="immersive_player_repeat_off">Répétition : désactivée</string>
<string name="immersive_player_repeat_all">Répétition : tout</string>
- <string name="immersive_player_repeat_one">Répétition : un titre</string>
+ <string name="immersive_player_repeat_one">Répéter une fois</string>
<string name="immersive_player_volume_down">Volume moins</string>
<string name="immersive_player_volume_up">Volume plus</string>
<string name="immersive_player_ad">Publicité</string>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 197a1b28..7fa7128b 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -10,7 +10,7 @@
<string name="welcome_privacy">Vous vous connectez sur la page officielle de Spotify. Myspoti ne voit jamais votre mot de passe.</string>
<string name="remove_from_liked">Retirer des Titres likés</string>
<string name="repeat_on">Répéter : activé</string>
- <string name="repeat_one">Répéter le titre</string>
+ <string name="repeat_one">Répéter une fois</string>
<string name="repeat_off">Répéter : désactivé</string>
<string name="headphones">Écouteurs</string>
<string name="listen_on">Écouter sur</string>
diff --git a/base/app/src/main/res/values/immersive_player_strings.xml b/base/app/src/main/res/values/immersive_player_strings.xml
index 70d72c6b..d6764a25 100644
--- a/base/app/src/main/res/values/immersive_player_strings.xml
+++ b/base/app/src/main/res/values/immersive_player_strings.xml
@@ -17,7 +17,7 @@
<string name="immersive_player_shuffle_off">Shuffle: off</string>
<string name="immersive_player_repeat_off">Repeat: off</string>
<string name="immersive_player_repeat_all">Repeat: all</string>
- <string name="immersive_player_repeat_one">Repeat: one</string>
+ <string name="immersive_player_repeat_one">Repeat once</string>
<string name="immersive_player_volume_down">Volume down</string>
<string name="immersive_player_volume_up">Volume up</string>
<string name="immersive_player_ad">Advertisement</string>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 11416ef6..4abb0782 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -10,7 +10,7 @@
<string name="welcome_privacy">You sign in on Spotify\'s own page. Myspoti never sees your password.</string>
<string name="remove_from_liked">Remove from Liked Songs</string>
<string name="repeat_on">Repeat: on</string>
- <string name="repeat_one">Repeat one</string>
+ <string name="repeat_one">Repeat once</string>
<string name="repeat_off">Repeat: off</string>
<string name="headphones">Headphones</string>
<string name="listen_on">Listen on</string>
diff --git a/base/app/src/test/java/com/music/spotui/di/LocalRepeatTest.kt b/base/app/src/test/java/com/music/spotui/di/LocalRepeatTest.kt
index c9defa8d..ca1bb131 100644
--- a/base/app/src/test/java/com/music/spotui/di/LocalRepeatTest.kt
+++ b/base/app/src/test/java/com/music/spotui/di/LocalRepeatTest.kt
@@ -37,4 +37,55 @@ class LocalRepeatTest {
// The loops of the report: 193311, 192908 ms instead of 0.
assertTrue(LocalRepeat.startedLate(193_311))
}
+
+ // ── Repeat once ──
+
+ @Test fun repeatOncePlaysTheSongAgainOneTimeThenGoesOn() {
+ assertEquals(LocalRepeat.End.REPLAY, LocalRepeat.atEnd(LocalRepeat.ONE, 50, replayed = false))
+ assertEquals(LocalRepeat.End.ONCE_DONE, LocalRepeat.atEnd(LocalRepeat.ONE, 50, replayed = true))
+ // The only song of the queue too: once, then the queue's end (its song radio).
+ assertEquals(LocalRepeat.End.REPLAY, LocalRepeat.atEnd(LocalRepeat.ONE, 1, replayed = false))
+ assertEquals(LocalRepeat.End.ONCE_DONE, LocalRepeat.atEnd(LocalRepeat.ONE, 1, replayed = true))
+ // Repeat once still pauses at the end in both turns: Myspoti decides, never the player.
+ assertTrue(LocalRepeat.loopsSong(LocalRepeat.ONE, 50))
+ }
+
+ @Test fun repeatAllOfOneSongLoopsForGood() {
+ assertEquals(LocalRepeat.End.REPLAY, LocalRepeat.atEnd(LocalRepeat.ALL, 1, replayed = false))
+ assertEquals(LocalRepeat.End.REPLAY, LocalRepeat.atEnd(LocalRepeat.ALL, 1, replayed = true))
+ }
+
+ @Test fun offAndRepeatAllOfSeveralSongsGoOn() {
+ assertEquals(LocalRepeat.End.NEXT, LocalRepeat.atEnd(LocalRepeat.OFF, 50, replayed = false))
+ assertEquals(LocalRepeat.End.NEXT, LocalRepeat.atEnd(LocalRepeat.OFF, 1, replayed = false))
+ assertEquals(LocalRepeat.End.NEXT, LocalRepeat.atEnd(LocalRepeat.ALL, 50, replayed = false))
+ }
+
+ @Test fun aSeekToTheEndIsTheSongEnding() {
+ // The report: the bar dragged to 2:11 of a 131000 ms song.
+ assertTrue(LocalRepeat.seekEnds(131_000, 131_000))
+ assertTrue(LocalRepeat.seekEnds(140_000, 131_000))
+ assertTrue(LocalRepeat.seekEnds(130_600, 131_000))
+ assertFalse(LocalRepeat.seekEnds(120_000, 131_000))
+ // Not known: never taken for the end (Spotify's length is not the audio's).
+ assertFalse(LocalRepeat.seekEnds(131_000, null))
+ }
+
+ @Test fun seeksStayWithinTheLengthThePlayerKnows() {
+ assertEquals(130_999, LocalRepeat.seekTarget(131_000, 131_000))
+ assertEquals(125_000, LocalRepeat.seekTarget(140_000, 125_001))
+ assertEquals(60_000, LocalRepeat.seekTarget(60_000, 131_000))
+ assertEquals(0, LocalRepeat.seekTarget(-5, 131_000))
+ assertEquals(140_000, LocalRepeat.seekTarget(140_000, null))
+ }
+
+ @Test fun theSpotifyPageStartingTheSongAgainIsTheReplay() {
+ assertTrue(LocalRepeat.pageRestarted(sameSong = true, beforeMs = 130_500, lengthMs = 131_000, nowMs = 40))
+ assertTrue(LocalRepeat.pageRestarted(sameSong = true, beforeMs = 131_000, lengthMs = 131_000, nowMs = 2_000))
+ // A seek back mid-song, another song, a state just later in the song: not a replay.
+ assertFalse(LocalRepeat.pageRestarted(sameSong = true, beforeMs = 60_000, lengthMs = 131_000, nowMs = 0))
+ assertFalse(LocalRepeat.pageRestarted(sameSong = false, beforeMs = 130_500, lengthMs = 131_000, nowMs = 40))
+ assertFalse(LocalRepeat.pageRestarted(sameSong = true, beforeMs = 128_000, lengthMs = 131_000, nowMs = 129_000))
+ assertFalse(LocalRepeat.pageRestarted(sameSong = true, beforeMs = 130_500, lengthMs = 0, nowMs = 40))
+ }
}
diff --git a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
index a4dfdd87..2d5e4f2e 100644
--- a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
+++ b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
@@ -24,8 +24,30 @@ class MirrorRulesTest {
private fun onWeb(
web: Web, want: Want = Want(a, false), local: Local = local(), quiet: Boolean = false, landed: Boolean = true,
predicted: Long? = web.positionMs, previousUri: String? = null, gapFromMs: Long? = null, wantAtMs: Long? = null, wantLengthMs: Long = 0,
- recentUris: List<String> = emptyList(),
- ) = MirrorRules.onWeb(web, want, local, quiet, landed, predicted, previousUri, gapFromMs, wantAtMs, wantLengthMs, recentUris)
+ recentUris: List<String> = emptyList(), repeats: Boolean = false,
+ ) = MirrorRules.onWeb(web, want, local, quiet, landed, predicted, previousUri, gapFromMs, wantAtMs, wantLengthMs, recentUris, repeats)
+
+ // ── A local song to play again (repeat once, a one-song queue repeated) ──
+
+ @Test fun `the page going on at the end of a song to repeat is put back, never followed`() {
+ // The report: Mentir sought to its end (130999 of 131000 ms), the page went on to the next song.
+ val ending = local(at = 130_999, length = 131_000)
+ assertEquals(Follow.Back, onWeb(Web(b, paused = false, positionMs = 12), local = ending, repeats = true))
+ // The page's own end (another song than the queue's next, Spotify's relinked id): put back as well.
+ assertEquals(Follow.Back, onWeb(Web(d, paused = false, positionMs = 0), local = local(at = 100_000), wantAtMs = 178_000, wantLengthMs = 180_000, repeats = true))
+ // Without a repeat the local player goes on by itself: nothing to follow.
+ assertEquals(Follow.Nothing, onWeb(Web(b, paused = false, positionMs = 12), local = ending))
+ }
+
+ @Test fun `a skip on another device mid-song is still followed with a repeat on`() {
+ assertEquals(Follow.Next, onWeb(Web(b, paused = false, positionMs = 0), repeats = true))
+ }
+
+ @Test fun `a song whose length the player does not know is never near its end`() {
+ // The mirror passes 0 when the audio's length is unknown: Spotify's length does not decide the end.
+ assertFalse(local(at = 130_999, length = 0).nearEnd)
+ assertEquals(Follow.Next, onWeb(Web(b, paused = false, positionMs = 0), local = local(at = 130_999, length = 0), repeats = true))
+ }
// ── Which songs are mirrored ──