Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/nightly-notes/2026-11-16-fix-issues-2160-2164.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## Improved
- Picking a new song from Home or any list now crossfades from the one playing, while Fade when you skip is on (#2163)
- Repeated lyric lines show the count in brackets, like (×2) (#2164)
- Selected filter chips no longer show a checkmark

## Fixed
- Flow no longer crashes when a linked device on the same Wi-Fi drops off (#2161)
- Next and Previous from the notification and headphones no longer go silent before the next song (#2163)
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,13 @@ import androidx.media3.common.MediaItem
import androidx.media3.common.Metadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.inspector.MetadataRetriever
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import dagger.hilt.android.qualifiers.ApplicationContext
import io.github.aedev.flow.utils.await
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.ExecutionException
import javax.inject.Inject
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

/**
* Reads the tags Flow embedded into a download (see [Mp4Remuxer] and [Mp4TagWriter]) back from a
Expand Down Expand Up @@ -81,23 +76,6 @@ class DownloadTagReader
}
}

private suspend fun <T> ListenableFuture<T>.await(): T =
suspendCancellableCoroutine { continuation ->
addListener(
{
try {
continuation.resume(get())
} catch (e: ExecutionException) {
continuation.resumeWithException(e.cause ?: e)
} catch (e: CancellationException) {
continuation.cancel(e)
}
},
MoreExecutors.directExecutor(),
)
continuation.invokeOnCancellation { cancel(false) }
}

private companion object {
const val TAG = "DownloadTagReader"
const val TIMEOUT_MS = 10_000L
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import io.github.aedev.flow.player.error.PlayerDiagnostics
import io.github.aedev.flow.player.musicvideo.MusicVideoItems
import io.github.aedev.flow.player.musicvideo.MusicVideoPlanner
import io.github.aedev.flow.service.Media3MusicService
import io.github.aedev.flow.utils.await
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -118,6 +119,7 @@ object EnhancedMusicPlayerManager {
private var pendingSkip: PendingSkip? = null
private var skipJob: kotlinx.coroutines.Job? = null
private var heldSkipLimit: kotlinx.coroutines.Job? = null
private var queueHold: kotlinx.coroutines.Job? = null

/** Reads what a skip has to respect from storage. The app's ViewModel sets it; until then a skip rebuilds. */
private var readSkipStored: (suspend (MusicTrack) -> MusicSkipPolicy.Stored)? = null
Expand Down Expand Up @@ -728,8 +730,11 @@ object EnhancedMusicPlayerManager {
}
val restoredStart = resumePosition?.takeIf { (id, _) -> id == track.videoId && startPositionMs == 0L }?.second
resumePosition = null
player?.stop()
player?.clearMediaItems()
val holdFrom = (player as? MediaController)?.takeIf { it.isPlaying && it.currentMediaItem?.mediaId != track.videoId }
if (holdFrom == null) {
player?.stop()
player?.clearMediaItems()
}
clearPendingPlayNext()
// A new queue ends a named station even when it shares tracks with it, which the service
// would read as the same session. Start radio re-marks it from its pending seed.
Expand Down Expand Up @@ -758,9 +763,13 @@ object EnhancedMusicPlayerManager {
val startIdx = if (startIndex >= 0) startIndex else activeQueue.indexOfFirst { it.videoId == track.videoId }.coerceAtLeast(0)

playerItemFiles = localUriOverrides
player?.setMediaItems(mediaItems, startIdx, restoredStart ?: startPositionMs)
player?.prepare()
player?.play()
if (holdFrom != null) {
replaceQueueAfterHold(holdFrom, track, mediaItems, startIdx, restoredStart ?: startPositionMs)
} else {
player?.setMediaItems(mediaItems, startIdx, restoredStart ?: startPositionMs)
player?.prepare()
player?.play()
}

prefetchNextTrack()
}
Expand Down Expand Up @@ -1128,9 +1137,50 @@ object EnhancedMusicPlayerManager {
pendingSkip?.let { Log.d("EnhancedMusicPlayer", "Skip to ${it.mediaId} dropped by a new play") }
skipJob?.cancel()
heldSkipLimit?.cancel()
queueHold?.cancel()
pendingSkip = null
}

/**
* A song picked while another plays: the player keeps the old song until the service has moved it
* to a fade tail, so it plays on while the new queue loads (#2163). Meanwhile the app already shows
* the new song, as for a held skip.
*/
private fun replaceQueueAfterHold(
controller: MediaController,
track: MusicTrack,
mediaItems: List<MediaItem>,
index: Int,
positionMs: Long,
) {
pendingSkip = mediaItems.getOrNull(index)?.let { PendingSkip(index, it.mediaId) }
_currentPosition.value = 0L
_playerState.value = _playerState.value.copy(position = 0L, duration = track.duration * 1000L)
queueHold =
scope.launch {
val held =
try {
withTimeoutOrNull(QUEUE_HOLD_LIMIT_MS) {
Media3MusicService.queueHeld(Media3MusicService.holdForNewQueue(controller).await())
} == true
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("EnhancedMusicPlayer", "The service didn't answer the new queue's hold", e)
false
}
if (player !== controller) return@launch
Log.d("EnhancedMusicPlayer", "New queue at ${track.videoId}, old song held for a fade: $held")
if (!held) {
controller.stop()
controller.clearMediaItems()
}
controller.setMediaItems(mediaItems, index, positionMs)
controller.prepare()
controller.play()
}
}

private fun skipBaseIndex(): Int = pendingSkip?.index ?: currentPlaybackQueueIndex()

/**
Expand Down Expand Up @@ -1478,6 +1528,7 @@ object EnhancedMusicPlayerManager {
clearPendingPlayNext()
skipJob?.cancel()
heldSkipLimit?.cancel()
queueHold?.cancel()
pendingSkip = null
playerItemFiles = emptyMap()
_currentPosition.value = 0L
Expand Down Expand Up @@ -1580,6 +1631,9 @@ private const val COARSE_POSITION_INTERVAL_MS = 1_000L
/** Longer than the service waits for a tail, so it only ends a skip whose song left the queue. */
private const val HELD_SKIP_LIMIT_MS = 3_000L

/** Longer than the service waits for a tail, so a new queue goes ahead even if the service never answers. */
private const val QUEUE_HOLD_LIMIT_MS = 2_000L

/** [savedCode] is how a saved queue writes the mode; [playerMode] is Media3's own value for it. */
enum class RepeatMode(
val savedCode: Int,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,18 @@ internal object CrossfadePolicy {
return minOf(SKIP_BLEND_MS, leftOnClock).coerceAtLeast(1L)
}

/**
* Whether a song picked from a list fades in over the one playing (#2163): while fades on skip are on,
* something plays, and no tail is heard yet.
*/
fun newQueueFades(
settings: Settings,
stage: CrossfadeStage,
playing: Boolean,
): Boolean = settings.fadesOnSkip && playing && stage in quietStages

private val quietStages = setOf(CrossfadeStage.IDLE, CrossfadeStage.PREPARED, CrossfadeStage.WAITING_FOR_TAIL)

/**
* A tail heard for moments, or after the song has already gone quiet, starts sooner from a sync point
* at the cost of a small jump. One carrying a whole fade straight on from the session starts exactly.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ internal data class SkipTarget(
* tail while the settings ask for a fade, and the next song stays muted until the tail plays. Either way
* the fade runs once both are playing, on the [MusicCrossfader] that owns this. A next song still loading
* [CrossfadePolicy.LATE_NEXT_SONG_MS] after the hand-off doesn't hold the old one at full volume: that one
* fades out anyway, and the next one comes in quickly once it plays (#2076).
* fades out anyway, and the next one comes in quickly once it plays (#2076). A song picked from a list
* ([holdForNewQueue]) is held the same way, with the app replacing the queue once the tail plays.
*/
internal class CrossfadeSkip(
private val session: ExoPlayer,
Expand Down Expand Up @@ -80,6 +81,13 @@ internal class CrossfadeSkip(
/** Where a skip goes once the tail plays; the session stays on the old song until then. */
private var heldTarget: SkipTarget? = null

/** Told whether the session may take a new queue, once the old song plays on its tail or can't. */
private var queueHold: ((Boolean) -> Unit)? = null

/** True while the tail carries the old song and the session, muted, waits for a new queue. */
var awaitingQueue = false
private set

/** Where a second skip goes once the song that was fading in has eased out. */
private var easingTo: SkipTarget? = null
private var easeFrom = 0f
Expand All @@ -103,6 +111,7 @@ internal class CrossfadeSkip(
private val easeStep = Runnable { ease() }
private val lateSongStep = Runnable { nextSongLate() }
private val skipTimeoutStep = Runnable { if (host.stage == CrossfadeStage.SKIP_STARTING) skipTailOutOfTime() }
private val queueTimeoutStep = Runnable { if (awaitingQueue) host.abort("the new queue never came") }

/** True while a skip waits for its tail, with the session still on the old song. */
val holding: Boolean get() = heldTarget != null
Expand All @@ -111,20 +120,70 @@ internal class CrossfadeSkip(
heldTarget = null
}

/** Lets go of where the skip was going; the caller still takes the session there. */
/** Lets go of where the skip was going; the caller still takes the session there. A new queue goes ahead unfaded. */
fun dropTargets(): SkipTarget? {
val held = heldTarget ?: easingTo
heldTarget = null
easingTo = null
forgetQueue()
queueHold?.let { answer ->
queueHold = null
answer(false)
}
return held
}

fun forgetQueue() {
awaitingQueue = false
handler.removeCallbacks(queueTimeoutStep)
}

fun cancelSteps() {
handler.removeCallbacks(easeStep)
handler.removeCallbacks(skipTimeoutStep)
handler.removeCallbacks(lateSongStep)
}

/**
* A song picked from a list replaces the whole queue (#2163). Before it does, the old song moves to a
* tail from where it is, so it plays on while the new one loads. [answer] gets true once the tail
* plays and the session can take the new queue, false when the queue should go ahead without a fade.
*/
fun holdForNewQueue(answer: (Boolean) -> Unit) {
if (awaitingQueue) {
handler.removeCallbacks(queueTimeoutStep)
handler.postDelayed(queueTimeoutStep, QUEUE_TIMEOUT_MS)
answer(true)
return
}
if (queueHold != null) {
queueHold = answer
return
}
val left = session.currentMediaItem
val durationMs = left?.let { durationOf(it, session.currentMediaItemIndex) }
val resumeAt =
left
?.takeIf { heldTarget == null && CrossfadePolicy.newQueueFades(host.settings, host.stage, session.isPlaying) }
?.let { skipResumeAt(session.currentPosition, durationMs) }
if (left == null || durationMs == null || resumeAt == null) {
answer(false)
return
}
Log.d(CROSSFADE_TAG, "new queue: holding ${left.mediaId} on a tail")
val gain = session.volume
host.abort(null)
queueHold = answer
startSkipTail(left, durationMs, resumeAt, gain, tailVolume = 0f)
}

/** The new queue has replaced the old one under the tail; the fade waits for its first song. */
fun queueArrived() {
if (!awaitingQueue) return
forgetQueue()
if (session.isPlaying) startFade() else waitForLateSong()
}

/** Next or Previous from inside the app, which plays the song at [index] (still [mediaId]) whatever else happens. */
fun skipTo(
index: Int,
Expand Down Expand Up @@ -245,7 +304,7 @@ internal class CrossfadeSkip(
host.startSkipTail(item.mediaId, gain, clockMs) {
volume = tailVolume
addAnalyticsListener(skipTailListener)
if (CrossfadePolicy.tailStartsAtSyncPoint(host.settings, heldTarget != null)) startAtSyncPoint(resumeAt)
if (CrossfadePolicy.tailStartsAtSyncPoint(host.settings, heldTarget != null || queueHold != null)) startAtSyncPoint(resumeAt)
setMediaItem(item, resumeAt)
playWhenReady = true
prepare()
Expand Down Expand Up @@ -275,6 +334,11 @@ internal class CrossfadeSkip(
skipTailPlaying()
return
}
if (queueHold != null) {
host.abort("the tail took too long before a new queue")
host.schedule()
return
}
val target = heldTarget
val index = target?.let(::indexOf)
if (target != null && index == null) {
Expand All @@ -298,6 +362,16 @@ internal class CrossfadeSkip(
"skipped $skippedId, its tail played after ${waited}ms, ${apart}ms from the session, fading over ${overlapMs}ms",
)
handler.removeCallbacks(skipTimeoutStep)
queueHold?.let { answer ->
queueHold = null
host.restoreTailGain()
host.scaleSession(0f)
host.waitForNextSong()
awaitingQueue = true
handler.postDelayed(queueTimeoutStep, QUEUE_TIMEOUT_MS)
answer(true)
return
}
val target = heldTarget
heldTarget = null
if (target != null) {
Expand Down Expand Up @@ -335,7 +409,7 @@ internal class CrossfadeSkip(

/** The next song has started: a tail already playing fades it in, and one still starting has [SKIP_START_TIMEOUT_MS] to. */
fun nextSongPlaying() {
if (heldTarget == null && easingTo == null && host.stage == CrossfadeStage.WAITING_FOR_NEXT_SONG) startFade()
if (heldTarget == null && easingTo == null && !awaitingQueue && host.stage == CrossfadeStage.WAITING_FOR_NEXT_SONG) startFade()
}

private fun startFade() {
Expand Down Expand Up @@ -392,5 +466,8 @@ internal class CrossfadeSkip(
private companion object {
const val DEFAULT_SKIP_LEAD_MS = 400L
const val SKIP_START_TIMEOUT_MS = 1_500L

/** How long a muted session waits for the app to hand it the new queue before the old song comes back. */
const val QUEUE_TIMEOUT_MS = 2_500L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ internal class MusicCrossfader(
reason: Int,
) {
if (handingOff) return
if (skip.awaitingQueue && reason == Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED) skip.queueArrived()
if (skipFade) return
val songEnded = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
if (stage == CrossfadeStage.THROUGH && songEnded) {
Expand All @@ -103,6 +104,10 @@ internal class MusicCrossfader(
val left = oldPosition.mediaItem
val changedSong = left != null && left.mediaId != newPosition.mediaItem?.mediaId
val byHand = reason == Player.DISCONTINUITY_REASON_SEEK || reason == Player.DISCONTINUITY_REASON_REMOVE
if (skip.awaitingQueue && changedSong) {
skip.queueArrived()
return
}
if (skip.holding && (changedSong || byHand)) {
abort("the player moved while a skip waited for its tail")
return
Expand Down Expand Up @@ -209,6 +214,9 @@ internal class MusicCrossfader(
mediaId: String,
) = skip.skipTo(index, mediaId)

/** A song picked from a list is about to replace the queue; [answer] is true once the old song plays on, on a tail. */
fun holdForNewQueue(answer: (Boolean) -> Unit) = skip.holdForNewQueue(answer)

private fun startFade(late: Boolean) {
stage = CrossfadeStage.FADING
val now = SystemClock.elapsedRealtime()
Expand Down Expand Up @@ -437,6 +445,7 @@ internal class MusicCrossfader(

private fun finish() {
skipFade = false
skip.forgetQueue()
releaseTail()
stage = CrossfadeStage.IDLE
restoreScale()
Expand Down
Loading
Loading