diff --git a/.github/nightly-notes/2026-11-16-fix-issues-2160-2164.md b/.github/nightly-notes/2026-11-16-fix-issues-2160-2164.md new file mode 100644 index 0000000000..cb9a1aff89 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-issues-2160-2164.md @@ -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) diff --git a/app/src/main/java/io/github/aedev/flow/data/video/downloader/tags/DownloadTagReader.kt b/app/src/main/java/io/github/aedev/flow/data/video/downloader/tags/DownloadTagReader.kt index 5b2e046d26..5cce1ab810 100644 --- a/app/src/main/java/io/github/aedev/flow/data/video/downloader/tags/DownloadTagReader.kt +++ b/app/src/main/java/io/github/aedev/flow/data/video/downloader/tags/DownloadTagReader.kt @@ -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 @@ -81,23 +76,6 @@ class DownloadTagReader } } - private suspend fun ListenableFuture.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 diff --git a/app/src/main/java/io/github/aedev/flow/player/EnhancedMusicPlayerManager.kt b/app/src/main/java/io/github/aedev/flow/player/EnhancedMusicPlayerManager.kt index 4fffeade63..1ff6174c34 100644 --- a/app/src/main/java/io/github/aedev/flow/player/EnhancedMusicPlayerManager.kt +++ b/app/src/main/java/io/github/aedev/flow/player/EnhancedMusicPlayerManager.kt @@ -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 @@ -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 @@ -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. @@ -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() } @@ -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, + 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() /** @@ -1478,6 +1528,7 @@ object EnhancedMusicPlayerManager { clearPendingPlayNext() skipJob?.cancel() heldSkipLimit?.cancel() + queueHold?.cancel() pendingSkip = null playerItemFiles = emptyMap() _currentPosition.value = 0L @@ -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, diff --git a/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadePolicy.kt b/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadePolicy.kt index 84f78c8c02..083f297d1f 100644 --- a/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadePolicy.kt +++ b/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadePolicy.kt @@ -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. diff --git a/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadeSkip.kt b/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadeSkip.kt index 92afc6a195..d1a82d107d 100644 --- a/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadeSkip.kt +++ b/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadeSkip.kt @@ -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, @@ -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 @@ -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 @@ -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, @@ -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() @@ -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) { @@ -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) { @@ -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() { @@ -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 } } diff --git a/app/src/main/java/io/github/aedev/flow/player/crossfade/MusicCrossfader.kt b/app/src/main/java/io/github/aedev/flow/player/crossfade/MusicCrossfader.kt index 6e2e404ef5..e8ab8a1ac1 100644 --- a/app/src/main/java/io/github/aedev/flow/player/crossfade/MusicCrossfader.kt +++ b/app/src/main/java/io/github/aedev/flow/player/crossfade/MusicCrossfader.kt @@ -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) { @@ -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 @@ -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() @@ -437,6 +445,7 @@ internal class MusicCrossfader( private fun finish() { skipFade = false + skip.forgetQueue() releaseTail() stage = CrossfadeStage.IDLE restoreScale() diff --git a/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt b/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt index 0ba9300e28..18dd32d6e5 100644 --- a/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt +++ b/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt @@ -129,6 +129,8 @@ class Media3MusicService : MediaLibraryService() { private const val ACTION_SKIP_TO = "ACTION_SKIP_TO" private const val EXTRA_SKIP_INDEX = "index" private const val EXTRA_SKIP_MEDIA_ID = "mediaId" + private const val ACTION_HOLD_FOR_NEW_QUEUE = "ACTION_HOLD_FOR_NEW_QUEUE" + private const val EXTRA_QUEUE_HELD = "held" private const val MAX_RETRY_PER_SONG = 5 private const val BASE_RETRY_DELAY_MS = 3000L @@ -148,6 +150,7 @@ class Media3MusicService : MediaLibraryService() { private val CommandToggleRepeat = SessionCommand(ACTION_TOGGLE_REPEAT, Bundle.EMPTY) private val CommandStop = SessionCommand(ACTION_STOP, Bundle.EMPTY) private val CommandSkipTo = SessionCommand(ACTION_SKIP_TO, Bundle.EMPTY) + private val CommandHoldForNewQueue = SessionCommand(ACTION_HOLD_FOR_NEW_QUEUE, Bundle.EMPTY) const val ACTION_TOGGLE_LIKE = "ACTION_TOGGLE_LIKE" private val CommandToggleLike = SessionCommand(ACTION_TOGGLE_LIKE, Bundle.EMPTY) @@ -181,6 +184,15 @@ class Media3MusicService : MediaLibraryService() { putString(EXTRA_SKIP_MEDIA_ID, mediaId) }, ) + + /** + * Asked before the app replaces the queue with a song picked from a list: the service moves the + * playing song to a fade tail first. [queueHeld] on the result says whether it did. + */ + fun holdForNewQueue(controller: MediaController): ListenableFuture = + controller.sendCustomCommand(CommandHoldForNewQueue, Bundle.EMPTY) + + fun queueHeld(result: SessionResult): Boolean = result.extras.getBoolean(EXTRA_QUEUE_HELD) } private lateinit var mediaLibrarySession: MediaLibrarySession @@ -1461,7 +1473,11 @@ class Media3MusicService : MediaLibraryService() { /** The session's player: a resume from a controller turns offload back on before playback starts. */ private fun sessionPlayer(): Player = - SessionPlayer(player, { mediaLibrarySession.controllerForCurrentRequest }) { + SessionPlayer( + player, + { mediaLibrarySession.controllerForCurrentRequest }, + onSkip = { index, mediaId -> crossfader?.skipTo(index, mediaId) != null }, + ) { updateOffload { it.copy(pausedLong = false) } }.also { it.follow(lifecycleScope) @@ -2047,6 +2063,7 @@ class Media3MusicService : MediaLibraryService() { .add(CommandToggleLike) .add(CommandStop) .add(CommandSkipTo) + .add(CommandHoldForNewQueue) .build() return MediaSession.ConnectionResult .AcceptedResultBuilder(session) @@ -2121,6 +2138,15 @@ class Media3MusicService : MediaLibraryService() { return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) } + if (customCommand.customAction == ACTION_HOLD_FOR_NEW_QUEUE) { + val answer = SettableFuture.create() + val reply = { held: Boolean -> + answer.set(SessionResult(SessionResult.RESULT_SUCCESS, Bundle().apply { putBoolean(EXTRA_QUEUE_HELD, held) })) + } + crossfader?.holdForNewQueue { reply(it) } ?: reply(false) + return answer + } + if (customCommand.customAction == ACTION_STOP) { stopPlaybackAndService() return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) diff --git a/app/src/main/java/io/github/aedev/flow/service/SessionPlayer.kt b/app/src/main/java/io/github/aedev/flow/service/SessionPlayer.kt index b66145c75a..4d1213120d 100644 --- a/app/src/main/java/io/github/aedev/flow/service/SessionPlayer.kt +++ b/app/src/main/java/io/github/aedev/flow/service/SessionPlayer.kt @@ -17,12 +17,15 @@ import kotlinx.coroutines.launch * The music session's player. While the app follows another device's music (Play on), it reports * that device's play state and position, and the notification, lock screen, headset and car drive * that device; the app's own controller still reaches the player here. [onResume] runs before a - * resume here, which turns offload back on. + * resume here, which turns offload back on. A Next or Previous from those buttons that changes song + * goes to [onSkip], which holds the old song for the fade like the app's own buttons, and falls back + * to the player's seek when it returns false (#2163). */ @OptIn(UnstableApi::class) internal class SessionPlayer( player: Player, private val requester: () -> MediaSession.ControllerInfo?, + private val onSkip: (index: Int, mediaId: String) -> Boolean, private val onResume: () -> Unit, ) : ForwardingSimpleBasePlayer(player) { private var lyricLine: String? = null @@ -83,7 +86,13 @@ internal class SessionPlayer( positionMs: Long, seekCommand: Int, ): ListenableFuture<*> { - val remote = driven() ?: return super.handleSeek(mediaItemIndex, positionMs, seekCommand) + val remote = driven() + if (remote == null) { + val skipTo = + sessionSkipIndex(seekCommand, mediaItemIndex, player.currentMediaItemIndex, player.mediaItemCount, player.playWhenReady) + if (skipTo != null && onSkip(skipTo, player.getMediaItemAt(skipTo).mediaId)) return Futures.immediateVoidFuture() + return super.handleSeek(mediaItemIndex, positionMs, seekCommand) + } when (seekCommand) { COMMAND_SEEK_TO_NEXT, COMMAND_SEEK_TO_NEXT_MEDIA_ITEM -> remote.command("next") COMMAND_SEEK_TO_PREVIOUS, COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM -> remote.command("previous") @@ -93,3 +102,24 @@ internal class SessionPlayer( return Futures.immediateVoidFuture() } } + +private val songSkips = + setOf( + Player.COMMAND_SEEK_TO_NEXT, + Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, + Player.COMMAND_SEEK_TO_PREVIOUS, + Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, + ) + +/** + * The queue slot a Next or Previous from outside the app moves to, when it changes song while the + * music plays; null when the player's own seek is right (a Previous that restarts the song, a seek + * within it, or nothing playing). + */ +internal fun sessionSkipIndex( + seekCommand: Int, + targetIndex: Int, + currentIndex: Int, + itemCount: Int, + playWhenReady: Boolean, +): Int? = targetIndex.takeIf { playWhenReady && seekCommand in songSkips && it != currentIndex && it in 0 until itemCount } diff --git a/app/src/main/java/io/github/aedev/flow/sync2/live/LiveChannel.kt b/app/src/main/java/io/github/aedev/flow/sync2/live/LiveChannel.kt index b98dab3e96..53ea94fc11 100644 --- a/app/src/main/java/io/github/aedev/flow/sync2/live/LiveChannel.kt +++ b/app/src/main/java/io/github/aedev/flow/sync2/live/LiveChannel.kt @@ -1,6 +1,7 @@ package io.github.aedev.flow.sync2.live import android.content.Context +import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import io.github.aedev.flow.platform.DeviceFormFactor import io.github.aedev.flow.platform.DeviceFormFactorDetector @@ -26,6 +27,8 @@ import kotlinx.coroutines.sync.withLock import javax.inject.Inject import javax.inject.Singleton +private const val TAG = "LiveChannel" + /** Something a live envelope goes out on: the server's live socket, or a LAN session. */ interface LiveTransport { suspend fun send(envelope: ByteArray) @@ -74,7 +77,10 @@ class LiveChannel // Saved before it leaves, so a crash can't make a counter repeat. db.live().setCounter(LiveCounterRow(session.me, seq)) val envelope = session.sealLive(message, seq) - transports.value.forEach { it.send(envelope) } + deliverLive(transports.value, envelope) { transport, e -> + Log.w(TAG, "A live transport failed and was dropped: ${e.javaClass.simpleName}: ${e.message}") + transports.update { it - transport } + } sealed.emit(envelope) seq } diff --git a/app/src/main/java/io/github/aedev/flow/sync2/live/LiveDelivery.kt b/app/src/main/java/io/github/aedev/flow/sync2/live/LiveDelivery.kt new file mode 100644 index 0000000000..f0787412aa --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/sync2/live/LiveDelivery.kt @@ -0,0 +1,24 @@ +package io.github.aedev.flow.sync2.live + +import kotlinx.coroutines.CancellationException + +/** + * Hands [envelope] to each of [transports] on its own. A LAN session whose socket is already + * closing throws; it goes to [onFailed] and the rest still get the envelope, because a live message + * is never worth stopping the app for (#2161). + */ +internal suspend fun deliverLive( + transports: Collection, + envelope: ByteArray, + onFailed: (LiveTransport, Exception) -> Unit, +) { + for (transport in transports) { + try { + transport.send(envelope) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + onFailed(transport, e) + } + } +} diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/shared/FlowFilterChip.kt b/app/src/main/java/io/github/aedev/flow/ui/components/shared/FlowFilterChip.kt index 01936c8c8f..3be81d3fdb 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/shared/FlowFilterChip.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/shared/FlowFilterChip.kt @@ -8,7 +8,6 @@ package io.github.aedev.flow.ui.components.shared import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.rounded.Check import androidx.compose.material.icons.rounded.KeyboardArrowDown import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.FilterChip @@ -21,7 +20,8 @@ import androidx.compose.ui.text.style.TextOverflow /** * The single filter chip for every surface: home feed chips, search filters, browse tabs, - * library content filters. + * library content filters. Selection shows through the shape and the fill, with no check, so a + * chip keeps its width when it is picked. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable @@ -43,24 +43,12 @@ fun FlowFilterChip( }, shapes = FilterChipDefaults.shapes(), modifier = modifier, - leadingIcon = - if (selected) { - { - Icon( - imageVector = Icons.Rounded.Check, - contentDescription = null, - modifier = Modifier.size(FilterChipDefaults.IconSize), - ) - } - } else { - null - }, ) } /** * A filter chip that opens a menu instead of toggling. [selected] marks that a non-default option is - * active; the chevron replaces the check so the two kinds read differently side by side. + * active; the chevron tells it apart from a chip that toggles. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable diff --git a/app/src/main/java/io/github/aedev/flow/utils/FutureAwait.kt b/app/src/main/java/io/github/aedev/flow/utils/FutureAwait.kt new file mode 100644 index 0000000000..c9bc2788c3 --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/utils/FutureAwait.kt @@ -0,0 +1,27 @@ +package io.github.aedev.flow.utils + +import com.google.common.util.concurrent.ListenableFuture +import com.google.common.util.concurrent.MoreExecutors +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.suspendCancellableCoroutine +import java.util.concurrent.ExecutionException +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +/** Waits for a Guava future, such as a Media3 command or metadata result, and cancels it with the caller. */ +suspend fun ListenableFuture.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) } + } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4d147f8e8e..599ffdbe17 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -139,8 +139,8 @@ Lyrics Full screen lyrics Play from this line - - ×%1$d + + (×%1$d) Translation Show a translation when the lyrics include one These lyrics have no translation diff --git a/app/src/test/java/io/github/aedev/flow/player/crossfade/CrossfadePolicyTest.kt b/app/src/test/java/io/github/aedev/flow/player/crossfade/CrossfadePolicyTest.kt index 32e8bc2b68..3d11d0e4c6 100644 --- a/app/src/test/java/io/github/aedev/flow/player/crossfade/CrossfadePolicyTest.kt +++ b/app/src/test/java/io/github/aedev/flow/player/crossfade/CrossfadePolicyTest.kt @@ -373,6 +373,25 @@ class CrossfadePolicyTest { assertThat(CrossfadePolicy.tailStartsAtSyncPoint(CrossfadePolicy.Settings(), sessionStillPlaysSong = true)).isTrue() } + @Test + fun `a picked song fades in only with fades on skip, while playing, before a tail is heard`() { + val fading = CrossfadePolicy.Settings(fadeMs = 6_000L, onManualSkip = true) + assertThat(CrossfadePolicy.newQueueFades(fading, CrossfadeStage.IDLE, playing = true)).isTrue() + assertThat(CrossfadePolicy.newQueueFades(fading, CrossfadeStage.PREPARED, playing = true)).isTrue() + assertThat(CrossfadePolicy.newQueueFades(fading, CrossfadeStage.WAITING_FOR_TAIL, playing = true)).isTrue() + assertThat(CrossfadePolicy.newQueueFades(fading, CrossfadeStage.IDLE, playing = false)).isFalse() + assertThat(CrossfadePolicy.newQueueFades(fading.copy(onManualSkip = false), CrossfadeStage.IDLE, playing = true)).isFalse() + assertThat(CrossfadePolicy.newQueueFades(CrossfadePolicy.Settings(), CrossfadeStage.IDLE, playing = true)).isFalse() + listOf( + CrossfadeStage.ALIGNING, + CrossfadeStage.SKIP_STARTING, + CrossfadeStage.WAITING_FOR_NEXT_SONG, + CrossfadeStage.FADING, + CrossfadeStage.THROUGH, + CrossfadeStage.THROUGH_IN, + ).forEach { assertThat(CrossfadePolicy.newQueueFades(fading, it, playing = true)).isFalse() } + } + @Test fun `a fade kept waiting by the next song goes on from where it was`() { assertThat(CrossfadePolicy.fadeBeganAtMs(nowMs = 10_000L, progress = 0f, fadeClockMs = 6_000L)).isEqualTo(10_000L) diff --git a/app/src/test/java/io/github/aedev/flow/service/SessionSkipIndexTest.kt b/app/src/test/java/io/github/aedev/flow/service/SessionSkipIndexTest.kt new file mode 100644 index 0000000000..1d2ac4953c --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/service/SessionSkipIndexTest.kt @@ -0,0 +1,46 @@ +package io.github.aedev.flow.service + +import androidx.media3.common.Player +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class SessionSkipIndexTest { + private fun index( + command: Int, + target: Int, + current: Int = 2, + count: Int = 5, + playing: Boolean = true, + ) = sessionSkipIndex(command, target, current, count, playing) + + @Test + fun `next and previous to another song go to the crossfade`() { + assertThat(index(Player.COMMAND_SEEK_TO_NEXT, 3)).isEqualTo(3) + assertThat(index(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, 3)).isEqualTo(3) + assertThat(index(Player.COMMAND_SEEK_TO_PREVIOUS, 1)).isEqualTo(1) + assertThat(index(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, 1)).isEqualTo(1) + } + + @Test + fun `a previous that restarts the song keeps the player's seek`() { + assertThat(index(Player.COMMAND_SEEK_TO_PREVIOUS, 2)).isNull() + } + + @Test + fun `seeks within the song or to a picked item keep the player's seek`() { + assertThat(index(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, 2)).isNull() + assertThat(index(Player.COMMAND_SEEK_TO_MEDIA_ITEM, 4)).isNull() + assertThat(index(Player.COMMAND_SEEK_TO_DEFAULT_POSITION, 0)).isNull() + } + + @Test + fun `nothing playing keeps the player's seek`() { + assertThat(index(Player.COMMAND_SEEK_TO_NEXT, 3, playing = false)).isNull() + } + + @Test + fun `a slot outside the queue keeps the player's seek`() { + assertThat(index(Player.COMMAND_SEEK_TO_NEXT, -1)).isNull() + assertThat(index(Player.COMMAND_SEEK_TO_NEXT, 5)).isNull() + } +} diff --git a/app/src/test/java/io/github/aedev/flow/sync2/LiveDeliveryTest.kt b/app/src/test/java/io/github/aedev/flow/sync2/LiveDeliveryTest.kt new file mode 100644 index 0000000000..3c877e40a9 --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/sync2/LiveDeliveryTest.kt @@ -0,0 +1,60 @@ +package io.github.aedev.flow.sync2 + +import com.google.common.truth.Truth.assertThat +import io.github.aedev.flow.sync2.live.LiveTransport +import io.github.aedev.flow.sync2.live.deliverLive +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.IOException + +class LiveDeliveryTest { + private val envelope = byteArrayOf(1, 2, 3) + + private class Kept : LiveTransport { + val sent = mutableListOf() + + override suspend fun send(envelope: ByteArray) { + sent += envelope + } + } + + private class Failing( + private val error: Exception, + ) : LiveTransport { + override suspend fun send(envelope: ByteArray) = throw error + } + + @Test + fun `a closing session doesn't stop the others`() = + runTest { + val before = Kept() + val closing = Failing(IOException("WebSocket refused a 632-byte frame")) + val after = Kept() + val failed = mutableListOf() + + deliverLive(listOf(before, closing, after), envelope) { transport, _ -> failed += transport } + + assertThat(before.sent).containsExactly(envelope) + assertThat(after.sent).containsExactly(envelope) + assertThat(failed).containsExactly(closing) + } + + @Test + fun `cancellation still cancels`() { + val failed = mutableListOf() + assertThrows(CancellationException::class.java) { + kotlinx.coroutines.runBlocking { + deliverLive(listOf(Failing(CancellationException("left"))), envelope) { transport, _ -> failed += transport } + } + } + assertThat(failed).isEmpty() + } + + @Test + fun `no transports is fine`() = + runTest { + deliverLive(emptyList(), envelope) { _, _ -> error("nothing to fail") } + } +}