diff --git a/.github/nightly-notes/2026-11-16-feat-downloads-find-in-picked-folder.md b/.github/nightly-notes/2026-11-16-feat-downloads-find-in-picked-folder.md new file mode 100644 index 0000000000..d8e0f895dc --- /dev/null +++ b/.github/nightly-notes/2026-11-16-feat-downloads-find-in-picked-folder.md @@ -0,0 +1,2 @@ +## Fixed +- After reinstalling, Flow can find your downloads again in the folder you choose (#1255) diff --git a/.github/nightly-notes/2026-11-16-feat-immersive-lyrics-in-place.md b/.github/nightly-notes/2026-11-16-feat-immersive-lyrics-in-place.md new file mode 100644 index 0000000000..ad33cc108a --- /dev/null +++ b/.github/nightly-notes/2026-11-16-feat-immersive-lyrics-in-place.md @@ -0,0 +1,2 @@ +## New +- In Immersive, lyrics can show in the player over the cover, with a full-screen button; turn on Lyrics on the cover in Player Appearance (#1278) diff --git a/.github/nightly-notes/2026-11-16-feat-lyric-repeat-count.md b/.github/nightly-notes/2026-11-16-feat-lyric-repeat-count.md new file mode 100644 index 0000000000..3c12906158 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-feat-lyric-repeat-count.md @@ -0,0 +1,2 @@ +## Improved +- Repeated lyric lines show ×2, ×3 in the mini player and lock screen (#2148) diff --git a/.github/nightly-notes/2026-11-16-fix-crossfade-skip-fade-while-loading.md b/.github/nightly-notes/2026-11-16-fix-crossfade-skip-fade-while-loading.md new file mode 100644 index 0000000000..155b848d89 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-crossfade-skip-fade-while-loading.md @@ -0,0 +1,2 @@ +## Fixed +- Fade when you skip now starts right away on Next and Previous (#2076) diff --git a/.github/nightly-notes/2026-11-16-fix-downloads-no-all-files-prompt.md b/.github/nightly-notes/2026-11-16-fix-downloads-no-all-files-prompt.md new file mode 100644 index 0000000000..8662748400 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-downloads-no-all-files-prompt.md @@ -0,0 +1,2 @@ +## Improved +- Downloads no longer ask for access to all files (#1255) diff --git a/.github/nightly-notes/2026-11-16-fix-lyric-press-box.md b/.github/nightly-notes/2026-11-16-fix-lyric-press-box.md new file mode 100644 index 0000000000..960e4ebe22 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-lyric-press-box.md @@ -0,0 +1,2 @@ +## Fixed +- Tapping a lyric line no longer draws a box around it (#2147) diff --git a/.github/nightly-notes/2026-11-16-fix-sync-streamed-hash.md b/.github/nightly-notes/2026-11-16-fix-sync-streamed-hash.md new file mode 100644 index 0000000000..d34a977fdd --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-sync-streamed-hash.md @@ -0,0 +1,2 @@ +## Fixed +- Syncing a large history no longer crashes Flow (#2145) diff --git a/.github/nightly-notes/2026-11-16-fix-wavy-seek-thumb.md b/.github/nightly-notes/2026-11-16-fix-wavy-seek-thumb.md new file mode 100644 index 0000000000..3efcb09181 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-fix-wavy-seek-thumb.md @@ -0,0 +1,2 @@ +## Fixed +- The wavy seek bar no longer pokes out past its thumb at the start of a song (#2150) diff --git a/.github/nightly-notes/2026-11-16-perf-music-preload-next.md b/.github/nightly-notes/2026-11-16-perf-music-preload-next.md new file mode 100644 index 0000000000..bb13f6c241 --- /dev/null +++ b/.github/nightly-notes/2026-11-16-perf-music-preload-next.md @@ -0,0 +1,2 @@ +## Improved +- The next song starts faster when you skip (#2076) diff --git a/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt b/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt index 1d32fb98eb..34e3a4da8b 100644 --- a/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt +++ b/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt @@ -201,6 +201,7 @@ class PlayerPreferences( val LYRICS_SHOW_ROMANIZATION = booleanPreferencesKey("lyrics_show_romanization") val LYRICS_ON_LOCK_SCREEN = booleanPreferencesKey("lyrics_on_lock_screen") val LYRICS_IN_MINI_PLAYER = booleanPreferencesKey("lyrics_in_mini_player") + val IMMERSIVE_LYRICS_ON_COVER = booleanPreferencesKey("immersive_lyrics_on_cover") val LYRICS_ON_DEMAND = booleanPreferencesKey("lyrics_on_demand") val LYRICS_ON_LOCK_SCREEN_DELAY_MS = intPreferencesKey("lyrics_on_lock_screen_delay_ms") val LYRICS_SPONSORBLOCK_TIMING = booleanPreferencesKey("lyrics_sponsorblock_timing") @@ -4744,6 +4745,14 @@ class PlayerPreferences( context.playerPreferencesDataStore.edit { it[Keys.LYRICS_IN_MINI_PLAYER] = enabled } } + /** Whether the immersive player's lyrics button shows lyrics over the cover instead of opening the sheet. */ + val immersiveLyricsOnCover: Flow = + context.playerPreferencesDataStore.data.map { it[Keys.IMMERSIVE_LYRICS_ON_COVER] ?: false } + + suspend fun setImmersiveLyricsOnCover(enabled: Boolean) { + context.playerPreferencesDataStore.edit { it[Keys.IMMERSIVE_LYRICS_ON_COVER] = enabled } + } + /** Whether lyrics are looked up only when the player or its lyrics open, or for lock screen lyrics. */ val lyricsOnDemand: Flow = context.playerPreferencesDataStore.data.map { it[Keys.LYRICS_ON_DEMAND] ?: false } diff --git a/app/src/main/java/io/github/aedev/flow/data/video/DownloadRecoveryScanner.kt b/app/src/main/java/io/github/aedev/flow/data/video/DownloadRecoveryScanner.kt index 62d3d04ea4..fc9ec9f25b 100644 --- a/app/src/main/java/io/github/aedev/flow/data/video/DownloadRecoveryScanner.kt +++ b/app/src/main/java/io/github/aedev/flow/data/video/DownloadRecoveryScanner.kt @@ -17,6 +17,7 @@ import io.github.aedev.flow.data.video.VideoDownloadManager.Companion.VIDEO_DIR import io.github.aedev.flow.data.video.downloader.tags.DownloadTagReader import io.github.aedev.flow.data.video.storage.DownloadCovers import io.github.aedev.flow.data.video.storage.DownloadFiles +import io.github.aedev.flow.data.video.storage.DownloadTree import io.github.aedev.flow.data.video.storage.StorageAccess import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers @@ -44,20 +45,27 @@ class DownloadRecoveryScanner private val preferences: PlayerPreferences, private val tagReader: DownloadTagReader, ) { + private data class Reach( + val access: StorageAccess, + val trees: Set, + ) + /** What the last scan in this process could read. */ @Volatile - private var scannedWith: StorageAccess? = null + private var scannedWith: Reach? = null /** * Whether a scan could find something the last one couldn't: none has run yet, or Flow may now - * read more shared storage, as after the viewer grants media access. + * read more shared storage, as after the viewer grants media access or picks a folder again. */ - fun needsScan(): Boolean = scannedWith != StorageAccess.read(context) + fun needsScan(): Boolean = scannedWith != reach() + + private fun reach() = Reach(StorageAccess.read(context), DownloadFiles.grantedTrees(context)) /** Records every new file it finds and returns how many that was. */ suspend fun scanAndRecoverDownloads(): Int = withContext(Dispatchers.IO) { - scannedWith = StorageAccess.read(context) + scannedWith = reach() var recovered = 0 try { val chosenFolders = chosenFolders() @@ -85,6 +93,7 @@ class DownloadRecoveryScanner } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) recovered += scanViaMediaStore(roots, exportedPaths) + recovered += scanPickedFolders(exportedPaths) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -154,8 +163,28 @@ class DownloadRecoveryScanner recovered } + /** + * The picked folders read through their grant, which needs no media access: a reinstalled Flow + * owns none of the files an earlier install saved, so the media index hides them from it. + */ + private suspend fun scanPickedFolders(exportedPaths: Set): Int { + val granted = DownloadFiles.grantedTrees(context) + var recovered = 0 + for (tree in chosenLocations().mapNotNull { it.treeUri }.distinct().filter { it in granted }) { + for (file in DownloadTree.files(context, tree, COLLECTION_DEPTH)) { + if (!RecoveredDownload.isMedia(file.name)) continue + val path = DownloadFiles.documentPath(file.uri) + if (path != null && !isNewFile(path, exportedPaths)) continue + if (recoverIfNew(file.uri, file.name, file.sizeBytes, file.modifiedAt, durationMs = null, exportedPaths)) recovered++ + } + } + return recovered + } + + private suspend fun chosenLocations() = listOf(preferences.downloadLocation.first(), preferences.musicDownloadLocation.first()) + private suspend fun chosenFolders(): List = - listOf(preferences.downloadLocation.first(), preferences.musicDownloadLocation.first()) + chosenLocations() .mapNotNull { location -> location.path?.takeIf { it.isNotBlank() } ?: location.treeUri?.let(DownloadFiles::treePath) } .distinct() @@ -186,7 +215,7 @@ class DownloadRecoveryScanner exportedPaths: Set, ): Boolean { if (!isNewFile(filePath, exportedPaths)) return false - val embedded = tagReader.read(Uri.fromFile(File(filePath))) + val embedded = tagReader.read(uriOf(filePath)) val tags = embedded?.flow val sourceUrl = embedded?.comment val videoId = RecoveredDownload.idFor(filePath, tags, sourceUrl) @@ -229,7 +258,7 @@ class DownloadRecoveryScanner ): Probe { val retriever = MediaMetadataRetriever() return try { - retriever.setDataSource(filePath) + retriever.setDataSource(context, uriOf(filePath)) val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L val frame = if (wantsFrame) { @@ -262,6 +291,8 @@ class DownloadRecoveryScanner } } + private fun uriOf(path: String): Uri = if (DownloadFiles.isDocument(path)) Uri.parse(path) else Uri.fromFile(File(path)) + private companion object { const val TAG = "DownloadRecoveryScanner" diff --git a/app/src/main/java/io/github/aedev/flow/data/video/VideoDownloadManager.kt b/app/src/main/java/io/github/aedev/flow/data/video/VideoDownloadManager.kt index e108d6cca1..144c9ee7fd 100644 --- a/app/src/main/java/io/github/aedev/flow/data/video/VideoDownloadManager.kt +++ b/app/src/main/java/io/github/aedev/flow/data/video/VideoDownloadManager.kt @@ -3,13 +3,10 @@ package io.github.aedev.flow.data.video import android.content.ContentUris import android.content.ContentValues import android.content.Context -import android.content.Intent import android.media.MediaScannerConnection -import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore -import android.provider.Settings import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import io.github.aedev.flow.data.local.PlayerPreferences @@ -141,35 +138,6 @@ class VideoDownloadManager false } - /** - * Request All Files Access permission (MANAGE_EXTERNAL_STORAGE) on Android 11+. - * This opens the system settings page where the user can grant the permission. - * Call this before starting downloads to ensure files go to public storage. - */ - fun requestAllFilesAccess(context: Context) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) { - try { - val intent = - Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { - data = Uri.parse("package:${context.packageName}") - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - } - context.startActivity(intent) - } catch (e: Exception) { - Log.w(TAG, "Failed to open MANAGE_ALL_FILES_ACCESS settings, trying fallback", e) - try { - val intent = - Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).apply { - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - } - context.startActivity(intent) - } catch (e2: Exception) { - Log.e(TAG, "Could not open file access settings", e2) - } - } - } - } - /** * Tell the Android system to scan the newly downloaded file. * This adds the file into the system's MediaStore index so it's instantly diff --git a/app/src/main/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalk.kt b/app/src/main/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalk.kt new file mode 100644 index 0000000000..5e9cb58740 --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalk.kt @@ -0,0 +1,30 @@ +package io.github.aedev.flow.data.video.storage + +/** + * The files in a picked folder and in the folders below it down to [maxDepth] levels, as + * [children] lists them. Hidden entries are skipped, which leaves out the system's `.trashed-` and + * `.pending-` files. A provider can be slow and a folder huge, so the walk stops after [limit] + * listed documents. + */ +internal fun filesInTree( + rootId: String, + maxDepth: Int, + limit: Int, + children: (String) -> List, +): List { + val files = mutableListOf() + var listed = 0 + val pending = ArrayDeque(listOf(rootId to 1)) + while (pending.isNotEmpty() && listed < limit) { + val (folderId, depth) = pending.removeFirst() + for (document in children(folderId)) { + if (++listed > limit) break + if (document.name.startsWith('.')) continue + when { + !document.isFolder -> files += document + depth < maxDepth -> pending += document.id to depth + 1 + } + } + } + return files +} diff --git a/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadFiles.kt b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadFiles.kt index 40b76a84bc..b0f98a3fec 100644 --- a/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadFiles.kt +++ b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadFiles.kt @@ -65,6 +65,12 @@ object DownloadFiles { return context.contentResolver.persistedUriPermissions.any { it.uri == uri && it.isWritePermission } } + /** The picked folders Flow may still write to. */ + fun grantedTrees(context: Context): Set = + context.contentResolver.persistedUriPermissions + .filter { it.isWritePermission } + .mapTo(mutableSetOf()) { it.uri.toString() } + fun releaseTree( context: Context, treeUri: String, diff --git a/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadLocation.kt b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadLocation.kt index 67975ac9c6..0ecdf8c348 100644 --- a/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadLocation.kt +++ b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadLocation.kt @@ -56,6 +56,22 @@ fun resolveDownloadDestination( return DownloadDestination(fallback, fellBack = chosen.isSet) } +/** + * The picked folder Flow can no longer open, as after a reinstall: the saved location comes back + * with the settings backup, but Android drops the folder's grant. Null when every picked folder can + * still be used, or when All files access reaches the folder through its path anyway. + */ +fun lostDownloadTree( + locations: List, + grantedTrees: Set, + hasAllFilesAccess: Boolean, +): String? = + locations + .firstOrNull { location -> + val tree = location.treeUri + !tree.isNullOrBlank() && tree !in grantedTrees && !(hasAllFilesAccess && !location.path.isNullOrBlank()) + }?.treeUri + /** * The file-system path behind a storage provider document id such as `primary:Movies/Flow`, or * null when the id does not name a place on a storage volume. diff --git a/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadTree.kt b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadTree.kt new file mode 100644 index 0000000000..fed8adc9da --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/data/video/storage/DownloadTree.kt @@ -0,0 +1,79 @@ +package io.github.aedev.flow.data.video.storage + +import android.content.Context +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.DocumentsContract.Document +import android.util.Log + +/** A file or folder inside a picked folder, as the storage provider lists it. */ +internal data class TreeDocument( + val id: String, + val name: String, + val isFolder: Boolean, + val sizeBytes: Long = 0L, + val modifiedAt: Long = 0L, +) + +/** A file found in a picked folder: its `content://` document and what the provider says about it. */ +internal data class TreeFile( + val uri: String, + val name: String, + val sizeBytes: Long, + val modifiedAt: Long, +) + +/** Lists picked download folders through their tree grant, which is how Flow reads them without media access. */ +internal object DownloadTree { + private const val TAG = "DownloadTree" + private const val MAX_DOCUMENTS = 20_000 + + private val Columns = + arrayOf( + Document.COLUMN_DOCUMENT_ID, + Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_MIME_TYPE, + Document.COLUMN_SIZE, + Document.COLUMN_LAST_MODIFIED, + ) + + /** The files in [treeUri] and in the folders [maxDepth] levels below it; empty when it can't be read. */ + fun files( + context: Context, + treeUri: String, + maxDepth: Int, + ): List { + val tree = Uri.parse(treeUri) + val rootId = runCatching { DocumentsContract.getTreeDocumentId(tree) }.getOrNull() ?: return emptyList() + return filesInTree(rootId, maxDepth, MAX_DOCUMENTS) { children(context, tree, it) } + .map { TreeFile(DocumentsContract.buildDocumentUriUsingTree(tree, it.id).toString(), it.name, it.sizeBytes, it.modifiedAt) } + } + + private fun children( + context: Context, + tree: Uri, + folderId: String, + ): List = + runCatching { + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, folderId) + context.contentResolver + .query(uri, Columns, null, null, null) + ?.use { cursor -> + buildList { + while (cursor.moveToNext()) { + val id = cursor.getString(0) ?: continue + add( + TreeDocument( + id = id, + name = cursor.getString(1).orEmpty(), + isFolder = cursor.getString(2) == Document.MIME_TYPE_DIR, + sizeBytes = if (cursor.isNull(3)) 0L else cursor.getLong(3), + modifiedAt = if (cursor.isNull(4)) 0L else cursor.getLong(4), + ), + ) + } + } + }.orEmpty() + }.onFailure { Log.w(TAG, "Could not list $folderId in $tree", it) } + .getOrDefault(emptyList()) +} 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 07c2dfb018..84f78c8c02 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 @@ -52,6 +52,9 @@ internal object CrossfadePolicy { /** With no old song to blend with, the next one still comes in over this long instead of at full volume. */ const val QUICK_FADE_IN_MS = 400L + /** A skipped-to song not playing this long after the old one moved to its tail is late, and the old one fades out anyway. */ + const val LATE_NEXT_SONG_MS = 1_000L + /** A lined-up tail takes over no sooner than this before the fade, so a short fade still ends with the song. */ private const val HAND_OFF_EARLY_MS = 500L @@ -234,6 +237,15 @@ internal object CrossfadePolicy { return minOf(fadeMs.coerceIn(0L, MAX_MS), leftOnClock).coerceAtLeast(1L) } + /** How long a skipped-to song that came late fades in: quickly, since the old song is already fading or gone. */ + fun lateFadeInClockMs(skipClockMs: Long): Long = minOf(QUICK_FADE_IN_MS, skipClockMs).coerceAtLeast(1L) + + /** A song's length from its metadata, or the player's own when the metadata has none; null while neither knows it. */ + fun knownDurationMs( + metadataMs: Long?, + playerMs: Long, + ): Long? = metadataMs ?: playerMs.takeIf { it > 0L } + /** How long a skip overlaps the two songs on the clock: the chosen fade, or just [SKIP_BLEND_MS] without one. */ fun skipClockMs( settings: Settings, 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 new file mode 100644 index 0000000000..92afc6a195 --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/player/crossfade/CrossfadeSkip.kt @@ -0,0 +1,396 @@ +package io.github.aedev.flow.player.crossfade + +import android.os.Handler +import android.os.SystemClock +import android.util.Log +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.Timeline +import androidx.media3.common.Tracks +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.SeekParameters +import androidx.media3.exoplayer.analytics.AnalyticsListener + +/** Where a skip goes: the queue slot, and the song that has to be there or found elsewhere in the queue. */ +internal data class SkipTarget( + val index: Int, + val mediaId: String, +) + +/** + * A song the user skips away from has no tail waiting, so one is built from where the song is. A skip + * from inside the app ([skipTo]) can wait for it: the session goes on playing the old song while the + * tail starts muted, and changes song once the tail is playing, so the old song never goes quiet. This + * runs with crossfade off too, as a [CrossfadePolicy.SKIP_BLEND_MS] overlap. A skip from the notification + * or a headset has already changed the song by the time it gets here ([beginSkipFade]), so it only gets a + * 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). + */ +internal class CrossfadeSkip( + private val session: ExoPlayer, + private val handler: Handler, + private val moment: (settings: CrossfadePolicy.Settings) -> CrossfadePolicy.Moment, + private val host: Host, +) { + /** What a skip reads and moves on the crossfader. */ + interface Host { + val stage: CrossfadeStage + val settings: CrossfadePolicy.Settings + val tail: ExoPlayer? + val sessionScale: Float + + fun scaleSession(scale: Float) + + /** Builds the tail that carries the old song for [clockMs], set up by [setUp], and starts waiting for it. */ + fun startSkipTail( + mediaId: String, + gain: Float, + clockMs: Long, + setUp: ExoPlayer.() -> Unit, + ) + + fun restoreTailGain() + + fun waitForNextSong() + + /** Starts the fade; a [late] next song isn't playing yet and comes in over [CrossfadePolicy.lateFadeInClockMs]. */ + fun startFade(late: Boolean) + + /** Holds the old song's volume where it is while the session moves to another song. */ + fun holdFade() + + fun seekSession(index: Int) + + /** Drops the tail and brings the session's song in over [CrossfadePolicy.QUICK_FADE_IN_MS], at [index] if given. */ + fun fadeNextSongIn( + reason: String, + index: Int?, + ) + + fun abort(reason: String?) + + fun schedule() + } + + /** Where a skip goes once the tail plays; the session stays on the old song until then. */ + private var heldTarget: SkipTarget? = null + + /** Where a second skip goes once the song that was fading in has eased out. */ + private var easingTo: SkipTarget? = null + private var easeFrom = 0f + private var easeBeganAtMs = 0L + private var skipPressedAtMs = 0L + private var skipLeadMs = DEFAULT_SKIP_LEAD_MS + private var skippedId: String? = null + private var overlapMs = 0L + private var waitingSinceMs = 0L + + // A started player is heard a moment after it reports playing, and only this says the audio has begun. + @OptIn(UnstableApi::class) + private val skipTailListener = + object : AnalyticsListener { + override fun onAudioPositionAdvancing( + eventTime: AnalyticsListener.EventTime, + playoutStartSystemTimeMs: Long, + ) = skipTailPlaying() + } + + private val easeStep = Runnable { ease() } + private val lateSongStep = Runnable { nextSongLate() } + private val skipTimeoutStep = Runnable { if (host.stage == CrossfadeStage.SKIP_STARTING) skipTailOutOfTime() } + + /** True while a skip waits for its tail, with the session still on the old song. */ + val holding: Boolean get() = heldTarget != null + + fun forgetHeld() { + heldTarget = null + } + + /** Lets go of where the skip was going; the caller still takes the session there. */ + fun dropTargets(): SkipTarget? { + val held = heldTarget ?: easingTo + heldTarget = null + easingTo = null + return held + } + + fun cancelSteps() { + handler.removeCallbacks(easeStep) + handler.removeCallbacks(skipTimeoutStep) + handler.removeCallbacks(lateSongStep) + } + + /** Next or Previous from inside the app, which plays the song at [index] (still [mediaId]) whatever else happens. */ + fun skipTo( + index: Int, + mediaId: String, + ) { + val target = SkipTarget(index, mediaId) + val left = session.currentMediaItem + val durationMs = left?.let { durationOf(it, session.currentMediaItemIndex) } + val resumeAt = left?.takeIf { heldTarget == null && session.isPlaying }?.let { skipResumeAt(session.currentPosition, durationMs) } + val press = CrossfadePolicy.onSkipPress(skipPhase(), session.currentMediaItemIndex == index, resumeAt != null) + Log.d(CROSSFADE_TAG, "skip to $mediaId: $press") + when (press) { + CrossfadePolicy.SkipPress.START_TAIL -> { + holdSkip(target, requireNotNull(left), requireNotNull(durationMs), requireNotNull(resumeAt)) + } + + CrossfadePolicy.SkipPress.MOVE_TARGET -> { + heldTarget = target + } + + CrossfadePolicy.SkipPress.BACK_TO_PLAYING_SONG -> { + stayOnPlayingSong() + } + + CrossfadePolicy.SkipPress.SEEK_UNDER_TAIL -> { + seekUnderTail(target) + } + + CrossfadePolicy.SkipPress.PLAIN -> { + skipPlainly(target) + } + } + } + + private fun holdSkip( + target: SkipTarget, + left: MediaItem, + durationMs: Long, + resumeAt: Long, + ) { + val gain = session.volume + host.abort(null) + heldTarget = target + startSkipTail(left, durationMs, resumeAt, gain, tailVolume = 0f) + } + + private fun stayOnPlayingSong() { + heldTarget = null + host.abort("the skip came back to the song still playing") + host.schedule() + } + + private fun skipPlainly(target: SkipTarget) { + host.abort(null) + indexOf(target)?.let(host::seekSession) + session.play() + host.schedule() + } + + private fun skipPhase(): CrossfadePolicy.SkipPhase { + val stage = host.stage + val tailCarriesOldSong = + stage == CrossfadeStage.SKIP_STARTING || stage == CrossfadeStage.WAITING_FOR_NEXT_SONG || stage == CrossfadeStage.FADING + return when { + heldTarget != null -> CrossfadePolicy.SkipPhase.HOLDING + tailCarriesOldSong -> CrossfadePolicy.SkipPhase.UNDER_TAIL + else -> CrossfadePolicy.SkipPhase.NONE + } + } + + private fun skipResumeAt( + positionMs: Long, + durationMs: Long?, + ): Long? { + if (!session.playWhenReady || moment(host.settings).showsVideo) return null + return CrossfadePolicy.skipResumeMs(positionMs, skipLeadMs, durationMs, session.playerError != null) + } + + /** Most songs carry their length; one that doesn't takes what the player found once it loaded the song at [index]. */ + private fun durationOf( + item: MediaItem, + index: Int, + ): Long? { + val timeline = session.currentTimeline + val window = if (index in 0 until timeline.windowCount) timeline.getWindow(index, Timeline.Window()) else null + val playerMs = window?.takeIf { it.mediaItem.mediaId == item.mediaId }?.durationMs ?: C.TIME_UNSET + return CrossfadePolicy.knownDurationMs(item.mediaMetadata.durationMs, playerMs) + } + + /** The song has already changed by hand: the old one returns on a tail from where it was and fades under the new one. */ + fun beginSkipFade( + left: MediaItem, + leftIndex: Int, + positionMs: Long, + ): Boolean { + if (!host.settings.fadesOnSkip) return false + val durationMs = durationOf(left, leftIndex) + val resumeAt = skipResumeAt(positionMs, durationMs) ?: return false + val gain = session.volume + host.abort(null) + host.scaleSession(0f) + startSkipTail(left, requireNotNull(durationMs), resumeAt, gain, tailVolume = gain) + return true + } + + @OptIn(UnstableApi::class) + private fun startSkipTail( + item: MediaItem, + durationMs: Long, + resumeAt: Long, + gain: Float, + tailVolume: Float, + ) { + skipPressedAtMs = SystemClock.elapsedRealtime() + val clockMs = CrossfadePolicy.skipClockMs(host.settings, resumeAt, durationMs, session.playbackParameters.speed) + skippedId = item.mediaId + overlapMs = clockMs + host.startSkipTail(item.mediaId, gain, clockMs) { + volume = tailVolume + addAnalyticsListener(skipTailListener) + if (CrossfadePolicy.tailStartsAtSyncPoint(host.settings, heldTarget != null)) startAtSyncPoint(resumeAt) + setMediaItem(item, resumeAt) + playWhenReady = true + prepare() + } + handler.postDelayed(skipTimeoutStep, SKIP_START_TIMEOUT_MS) + } + + /** + * Starting between sync points decodes from the one before first, about 500 ms the skip would wait. + * A start position ignores seek parameters, so the seek comes as soon as the tail knows its tracks. + */ + private fun ExoPlayer.startAtSyncPoint(positionMs: Long) { + setSeekParameters(SeekParameters.CLOSEST_SYNC) + addListener( + object : Player.Listener { + override fun onTracksChanged(tracks: Tracks) { + if (tracks.isEmpty) return + removeListener(this) + seekTo(positionMs) + } + }, + ) + } + + private fun skipTailOutOfTime() { + if (host.tail?.isPlaying == true) { + skipTailPlaying() + return + } + val target = heldTarget + val index = target?.let(::indexOf) + if (target != null && index == null) { + host.abort("the tail took too long after a skip") + host.schedule() + return + } + // Without a tail the old song can only fade by holding the skip back even longer, so the next one fades in instead. + heldTarget = null + easingTo = null + host.fadeNextSongIn("the tail took too long after a skip", index) + } + + private fun skipTailPlaying() { + if (host.stage != CrossfadeStage.SKIP_STARTING) return + val waited = SystemClock.elapsedRealtime() - skipPressedAtMs + skipLeadMs = CrossfadePolicy.learnedHeadStartMs(skipLeadMs, skipLeadMs - waited) + val apart = (host.tail?.currentPosition ?: 0L) - session.currentPosition + Log.d( + CROSSFADE_TAG, + "skipped $skippedId, its tail played after ${waited}ms, ${apart}ms from the session, fading over ${overlapMs}ms", + ) + handler.removeCallbacks(skipTimeoutStep) + val target = heldTarget + heldTarget = null + if (target != null) { + val index = indexOf(target) + if (index == null) { + host.abort("the skipped-to song left the queue") + return + } + host.restoreTailGain() + host.scaleSession(0f) + host.seekSession(index) + } + if (session.isPlaying) { + startFade() + } else { + host.waitForNextSong() + waitForLateSong() + } + } + + private fun waitForLateSong() { + waitingSinceMs = SystemClock.elapsedRealtime() + handler.removeCallbacks(lateSongStep) + handler.postDelayed(lateSongStep, CrossfadePolicy.LATE_NEXT_SONG_MS) + } + + /** The next song is still loading, so the old one fades out now and the next one comes in quickly once it plays. */ + private fun nextSongLate() { + if (heldTarget != null || easingTo != null || host.stage != CrossfadeStage.WAITING_FOR_NEXT_SONG || session.isPlaying) return + val waited = SystemClock.elapsedRealtime() - waitingSinceMs + Log.d(CROSSFADE_TAG, "the song after $skippedId is late, fading it out ${waited}ms after the hand-off") + handler.removeCallbacks(skipTimeoutStep) + host.startFade(late = true) + } + + /** 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() + } + + private fun startFade() { + handler.removeCallbacks(skipTimeoutStep) + handler.removeCallbacks(lateSongStep) + host.startFade(late = false) + } + + /** + * A tail already carries the old song, so only the song under it changes, and the fade waits for that one. + * A song already fading in eases out first, so it doesn't stop mid-word. + */ + private fun seekUnderTail(target: SkipTarget) { + if (easingTo != null) { + easingTo = target + return + } + if (host.stage == CrossfadeStage.FADING && host.sessionScale > 0f) { + host.holdFade() + easingTo = target + easeFrom = host.sessionScale + easeBeganAtMs = SystemClock.elapsedRealtime() + handler.post(easeStep) + return + } + moveUnderTail(target) + } + + private fun ease() { + val target = easingTo ?: return + val progress = CrossfadePolicy.progress(SystemClock.elapsedRealtime() - easeBeganAtMs, CrossfadePolicy.EASE_OUT_MS) + host.scaleSession(easeFrom * (1f - progress)) + if (progress < 1f) { + handler.postDelayed(easeStep, FADE_STEP_MS) + return + } + easingTo = null + moveUnderTail(target) + } + + private fun moveUnderTail(target: SkipTarget) { + val index = indexOf(target) ?: return + host.holdFade() + host.seekSession(index) + if (host.stage == CrossfadeStage.WAITING_FOR_NEXT_SONG && !session.isPlaying) waitForLateSong() + } + + fun indexOf(target: SkipTarget): Int? { + val count = session.mediaItemCount + if (target.index < count && session.getMediaItemAt(target.index).mediaId == target.mediaId) return target.index + return (0 until count).firstOrNull { session.getMediaItemAt(it).mediaId == target.mediaId } + } + + private companion object { + const val DEFAULT_SKIP_LEAD_MS = 400L + const val SKIP_START_TIMEOUT_MS = 1_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 f9c1fecbbb..6e2e404ef5 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 @@ -4,18 +4,13 @@ import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log -import androidx.annotation.OptIn import androidx.media3.common.MediaItem import androidx.media3.common.PlaybackException import androidx.media3.common.PlaybackParameters import androidx.media3.common.Player import androidx.media3.common.Timeline -import androidx.media3.common.Tracks -import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.PlayerMessage -import androidx.media3.exoplayer.SeekParameters -import androidx.media3.exoplayer.analytics.AnalyticsListener /** * Blends the end of a song into the next one (#1675). Media3 plays one item at a time, so the last @@ -35,13 +30,7 @@ import androidx.media3.exoplayer.analytics.AnalyticsListener * outgoing song fades until it ends and the incoming one over the chosen length, each on its own clock, * so a next song that is slow to start still gets its whole fade. * - * A song the user skips away from has no tail waiting, so one is built from where the song is. A skip - * from inside the app ([skipTo]) can wait for it: the session goes on playing the old song while the - * tail starts muted, and changes song once the tail is playing, so the old song never goes quiet. This - * runs with crossfade off too, as a [CrossfadePolicy.SKIP_BLEND_MS] overlap. A skip from the notification - * or a headset has already changed the song by the time it gets here, so it only gets a 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. + * A skip has no tail waiting, so [CrossfadeSkip] builds one from where the song is; the fade then runs here. * * Every step is driven by the players: [PlayerMessage]s at a position, their listeners for readiness, * seeks, skips and pauses. The only timed loops run while a song is changing hands: [TailAligner]'s @@ -53,29 +42,8 @@ internal class MusicCrossfader( private val moment: (settings: CrossfadePolicy.Settings) -> CrossfadePolicy.Moment, private val onSessionScaleChanged: () -> Unit, ) { - private enum class Stage { - IDLE, - PREPARED, - WAITING_FOR_TAIL, - ALIGNING, - SKIP_STARTING, - WAITING_FOR_NEXT_SONG, - FADING, - - /** No tail: the session fades its own song out. */ - THROUGH, - - /** No tail: the next song comes in quickly. */ - THROUGH_IN, - } - - private data class SkipTarget( - val index: Int, - val mediaId: String, - ) - private val handler = Handler(Looper.getMainLooper()) - private var stage = Stage.IDLE + private var stage = CrossfadeStage.IDLE private var settings = CrossfadePolicy.Settings() private var tail: ExoPlayer? = null @@ -91,17 +59,7 @@ internal class MusicCrossfader( private var inRunningSinceMs: Long? = null private var inClockMs = 1L private var fadeProgress = 0f - private var skipPressedAtMs = 0L private var skipFade = false - - /** Where a skip goes once the tail plays; the session stays on the old song until then. */ - private var heldTarget: SkipTarget? = null - - /** Where a second skip goes once the song that was fading in has eased out. */ - private var easingTo: SkipTarget? = null - private var easeFrom = 0f - private var easeBeganAtMs = 0L - private var skipLeadMs = DEFAULT_SKIP_LEAD_MS private var tailGain = 1f private var handingOff = false private val aligner = @@ -109,10 +67,11 @@ internal class MusicCrossfader( session = session, handler = handler, tail = { tail }, - onTailStarted = { stage = Stage.ALIGNING }, + onTailStarted = { stage = CrossfadeStage.ALIGNING }, onAligned = ::handOff, onGaveUp = ::fadeThrough, ) + private val skip = CrossfadeSkip(session, handler, moment, SkipHost()) /** What the session player's own volume is multiplied by: below 1 only while the next song fades in. */ var sessionScale = 1f @@ -127,7 +86,7 @@ internal class MusicCrossfader( if (handingOff) return if (skipFade) return val songEnded = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT - if (stage == Stage.THROUGH && songEnded) { + if (stage == CrossfadeStage.THROUGH && songEnded) { startQuickFadeIn() return } @@ -144,13 +103,13 @@ 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 (heldTarget != null && (changedSong || byHand)) { + if (skip.holding && (changedSong || byHand)) { abort("the player moved while a skip waited for its tail") return } - if (changedSong && byHand && beginSkipFade(left, oldPosition.positionMs)) return + if (changedSong && byHand && skip.beginSkipFade(left, oldPosition.mediaItemIndex, oldPosition.positionMs)) return if (reason != Player.DISCONTINUITY_REASON_SEEK) return - if (stage != Stage.IDLE) abort("a seek") + if (stage != CrossfadeStage.IDLE) abort("a seek") schedule() } @@ -158,23 +117,27 @@ internal class MusicCrossfader( playWhenReady: Boolean, reason: Int, ) { - if (!playWhenReady && stage != Stage.IDLE) abort("a pause") + if (!playWhenReady && stage != CrossfadeStage.IDLE) abort("a pause") schedule() } override fun onPlaybackStateChanged(playbackState: Int) { - if (playbackState == Player.STATE_READY && stage == Stage.IDLE) schedule() + if (playbackState == Player.STATE_READY && stage == CrossfadeStage.IDLE) schedule() // Closing the player stops it without a pause, and the old song must stop with it. if (skipFade && (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED)) { // A failed player's recovery goes back to its song, so a seek here would only be undone. - if (playbackState == Player.STATE_IDLE) heldTarget = null + if (playbackState == Player.STATE_IDLE) skip.forgetHeld() abort("the player stopped") } } override fun onIsPlayingChanged(isPlaying: Boolean) { runIncomingClock(isPlaying) - if (isPlaying) nextSongPlaying() + if (isPlaying && (stage == CrossfadeStage.FADING || stage == CrossfadeStage.THROUGH_IN)) { + handler.removeCallbacks(fadeStep) + handler.post(fadeStep) + } + if (isPlaying) skip.nextSongPlaying() } override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters) { @@ -197,32 +160,30 @@ internal class MusicCrossfader( private val tailListener = object : Player.Listener { override fun onPlaybackStateChanged(playbackState: Int) { - if (playbackState == Player.STATE_READY && stage == Stage.WAITING_FOR_TAIL) lineUp() - if (playbackState == Player.STATE_ENDED && stage == Stage.WAITING_FOR_NEXT_SONG) finish() + if (playbackState == Player.STATE_READY && stage == CrossfadeStage.WAITING_FOR_TAIL) lineUp() + if (playbackState == Player.STATE_ENDED && stage == CrossfadeStage.WAITING_FOR_NEXT_SONG) finish() } override fun onPlayerError(error: PlaybackException) { when (stage) { - Stage.IDLE -> Unit - Stage.PREPARED, Stage.WAITING_FOR_TAIL, Stage.ALIGNING -> fadeThrough("the tail failed: ${error.errorCodeName}") - else -> abort("the tail failed: ${error.errorCodeName}") + CrossfadeStage.IDLE -> { + Unit + } + + CrossfadeStage.PREPARED, CrossfadeStage.WAITING_FOR_TAIL, CrossfadeStage.ALIGNING -> { + fadeThrough( + "the tail failed: ${error.errorCodeName}", + ) + } + + else -> { + abort("the tail failed: ${error.errorCodeName}") + } } } } - // A started player is heard a moment after it reports playing, and only this says the audio has begun. - @OptIn(UnstableApi::class) - private val skipTailListener = - object : AnalyticsListener { - override fun onAudioPositionAdvancing( - eventTime: AnalyticsListener.EventTime, - playoutStartSystemTimeMs: Long, - ) = skipTailPlaying() - } - private val fadeStep = Runnable { fade() } - private val easeStep = Runnable { ease() } - private val skipTimeoutStep = Runnable { if (stage == Stage.SKIP_STARTING) skipTailOutOfTime() } fun attach() = session.addListener(listener) @@ -232,11 +193,13 @@ internal class MusicCrossfader( if (rescheduleNeeded && !fading) schedule() } - private val fading: Boolean get() = stage == Stage.FADING || stage == Stage.THROUGH || stage == Stage.THROUGH_IN + private val fading: Boolean get() = + stage == CrossfadeStage.FADING || stage == CrossfadeStage.THROUGH || + stage == CrossfadeStage.THROUGH_IN fun release() { session.removeListener(listener) - heldTarget = null + skip.forgetHeld() abort(null) } @@ -244,216 +207,20 @@ internal class MusicCrossfader( fun skipTo( index: Int, mediaId: String, - ) { - val target = SkipTarget(index, mediaId) - val left = session.currentMediaItem - val resumeAt = - left?.takeIf { heldTarget == null && session.isPlaying }?.let { skipResumeAt(it, session.currentPosition) } - val press = CrossfadePolicy.onSkipPress(skipPhase(), session.currentMediaItemIndex == index, resumeAt != null) - Log.d(TAG, "skip to $mediaId: $press") - when (press) { - CrossfadePolicy.SkipPress.START_TAIL -> holdSkip(target, requireNotNull(left), requireNotNull(resumeAt)) - CrossfadePolicy.SkipPress.MOVE_TARGET -> heldTarget = target - CrossfadePolicy.SkipPress.BACK_TO_PLAYING_SONG -> stayOnPlayingSong() - CrossfadePolicy.SkipPress.SEEK_UNDER_TAIL -> seekUnderTail(target) - CrossfadePolicy.SkipPress.PLAIN -> skipPlainly(target) - } - } - - private fun holdSkip( - target: SkipTarget, - left: MediaItem, - resumeAt: Long, - ) { - val gain = session.volume - abort(null) - heldTarget = target - startSkipTail(left, resumeAt, gain, tailVolume = 0f) - } - - private fun stayOnPlayingSong() { - heldTarget = null - abort("the skip came back to the song still playing") - schedule() - } - - private fun skipPlainly(target: SkipTarget) { - abort(null) - indexOf(target)?.let(::seekSession) - session.play() - schedule() - } - - private fun skipPhase(): CrossfadePolicy.SkipPhase { - val tailCarriesOldSong = stage == Stage.SKIP_STARTING || stage == Stage.WAITING_FOR_NEXT_SONG || stage == Stage.FADING - return when { - heldTarget != null -> CrossfadePolicy.SkipPhase.HOLDING - tailCarriesOldSong -> CrossfadePolicy.SkipPhase.UNDER_TAIL - else -> CrossfadePolicy.SkipPhase.NONE - } - } - - private fun skipResumeAt( - left: MediaItem, - positionMs: Long, - ): Long? { - if (!session.playWhenReady || moment(settings).showsVideo) return null - return CrossfadePolicy.skipResumeMs(positionMs, skipLeadMs, left.mediaMetadata.durationMs, session.playerError != null) - } - - /** The song has already changed by hand: the old one returns on a tail from where it was and fades under the new one. */ - private fun beginSkipFade( - left: MediaItem, - positionMs: Long, - ): Boolean { - if (!settings.fadesOnSkip) return false - val resumeAt = skipResumeAt(left, positionMs) ?: return false - val gain = session.volume - abort(null) - sessionScale = 0f - onSessionScaleChanged() - startSkipTail(left, resumeAt, gain, tailVolume = gain) - return true - } - - @OptIn(UnstableApi::class) - private fun startSkipTail( - item: MediaItem, - resumeAt: Long, - gain: Float, - tailVolume: Float, - ) { - skipFade = true - skipPressedAtMs = SystemClock.elapsedRealtime() - mediaId = item.mediaId - tailGain = gain - val durationMs = item.mediaMetadata.durationMs ?: 0L - outClockMs = CrossfadePolicy.skipClockMs(settings, resumeAt, durationMs, session.playbackParameters.speed) - inClockMs = outClockMs - tail = - buildTail(outClockMs).apply { - volume = tailVolume - playbackParameters = session.playbackParameters - addListener(tailListener) - addAnalyticsListener(skipTailListener) - if (CrossfadePolicy.tailStartsAtSyncPoint(settings, heldTarget != null)) startAtSyncPoint(resumeAt) - setMediaItem(item, resumeAt) - playWhenReady = true - prepare() - } - stage = Stage.SKIP_STARTING - handler.postDelayed(skipTimeoutStep, SKIP_START_TIMEOUT_MS) - } - - /** - * Starting between sync points decodes from the one before first, about 500 ms the skip would wait. - * A start position ignores seek parameters, so the seek comes as soon as the tail knows its tracks. - */ - private fun ExoPlayer.startAtSyncPoint(positionMs: Long) { - setSeekParameters(SeekParameters.CLOSEST_SYNC) - addListener( - object : Player.Listener { - override fun onTracksChanged(tracks: Tracks) { - if (tracks.isEmpty) return - removeListener(this) - seekTo(positionMs) - } - }, - ) - } - - private fun skipTailOutOfTime() { - if (tail?.isPlaying == true) { - skipTailPlaying() - } else { - abort("the tail took too long after a skip") - schedule() - } - } - - private fun skipTailPlaying() { - if (stage != Stage.SKIP_STARTING) return - val waited = SystemClock.elapsedRealtime() - skipPressedAtMs - skipLeadMs = CrossfadePolicy.learnedHeadStartMs(skipLeadMs, skipLeadMs - waited) - val apart = (tail?.currentPosition ?: 0L) - session.currentPosition - Log.d(TAG, "skipped $mediaId, its tail played after ${waited}ms, ${apart}ms from the session, fading over ${outClockMs}ms") - handler.removeCallbacks(skipTimeoutStep) - val target = heldTarget - heldTarget = null - if (target != null) { - val index = indexOf(target) - if (index == null) { - abort("the skipped-to song left the queue") - return - } - tail?.volume = tailGain - sessionScale = 0f - onSessionScaleChanged() - seekSession(index) - } - if (session.isPlaying) startFade() else stage = Stage.WAITING_FOR_NEXT_SONG - } + ) = skip.skipTo(index, mediaId) - /** The next song has started: a tail already playing fades it in, and one still starting has [SKIP_START_TIMEOUT_MS] to. */ - private fun nextSongPlaying() { - if (heldTarget == null && easingTo == null && stage == Stage.WAITING_FOR_NEXT_SONG) startFade() - } - - /** - * A tail already carries the old song, so only the song under it changes, and the fade waits for that one. - * A song already fading in eases out first, so it doesn't stop mid-word. - */ - private fun seekUnderTail(target: SkipTarget) { - if (easingTo != null) { - easingTo = target - return - } - if (stage == Stage.FADING && sessionScale > 0f) { - pauseFade() - skipFade = true - easingTo = target - easeFrom = sessionScale - easeBeganAtMs = SystemClock.elapsedRealtime() - handler.post(easeStep) - return - } - moveUnderTail(target) - } - - private fun ease() { - val target = easingTo ?: return - val progress = CrossfadePolicy.progress(SystemClock.elapsedRealtime() - easeBeganAtMs, CrossfadePolicy.EASE_OUT_MS) - sessionScale = easeFrom * (1f - progress) - onSessionScaleChanged() - if (progress < 1f) { - handler.postDelayed(easeStep, FADE_STEP_MS) - return - } - easingTo = null - moveUnderTail(target) - } - - private fun moveUnderTail(target: SkipTarget) { - val index = indexOf(target) ?: return - if (stage == Stage.FADING) pauseFade() - skipFade = true - seekSession(index) - } - - /** Holds the old song's volume where it is while the session moves to another song. */ - private fun pauseFade() { - fadeProgress = CrossfadePolicy.progress(SystemClock.elapsedRealtime() - outBeganAtMs, outClockMs) - handler.removeCallbacks(fadeStep) - stage = Stage.WAITING_FOR_NEXT_SONG - } - - private fun startFade() { - handler.removeCallbacks(skipTimeoutStep) - stage = Stage.FADING + private fun startFade(late: Boolean) { + stage = CrossfadeStage.FADING val now = SystemClock.elapsedRealtime() outBeganAtMs = CrossfadePolicy.fadeBeganAtMs(now, fadeProgress, outClockMs) - inElapsedMs = (fadeProgress * inClockMs).toLong() - inRunningSinceMs = now + if (late) { + inClockMs = CrossfadePolicy.lateFadeInClockMs(inClockMs) + inElapsedMs = 0L + inRunningSinceMs = null + } else { + inElapsedMs = (fadeProgress * inClockMs).toLong() + inRunningSinceMs = now + } handler.post(fadeStep) } @@ -470,12 +237,6 @@ internal class MusicCrossfader( private fun incomingProgress(nowMs: Long): Float = CrossfadePolicy.progress(inElapsedMs + (inRunningSinceMs?.let { nowMs - it } ?: 0L), inClockMs) - private fun indexOf(target: SkipTarget): Int? { - val count = session.mediaItemCount - if (target.index < count && session.getMediaItemAt(target.index).mediaId == target.mediaId) return target.index - return (0 until count).firstOrNull { session.getMediaItemAt(it).mediaId == target.mediaId } - } - private fun seekSession(index: Int) { handingOff = true try { @@ -487,7 +248,7 @@ internal class MusicCrossfader( private fun schedule() { if (fading || skipFade) return - if (stage != Stage.IDLE) abort(null) + if (stage != CrossfadeStage.IDLE) abort(null) cancelMessages() if (!settings.onAutoAdvance) return val now = moment(settings) @@ -516,7 +277,11 @@ internal class MusicCrossfader( alignMessage = message(index, alignAt) { beginAlign(item.mediaId) } deadlineMessage = message(index, latest) { - if (stage == Stage.PREPARED || stage == Stage.WAITING_FOR_TAIL) fadeThrough("the tail was not ready in time") + if (stage == CrossfadeStage.PREPARED || + stage == CrossfadeStage.WAITING_FOR_TAIL + ) { + fadeThrough("the tail was not ready in time") + } } } @@ -527,15 +292,13 @@ internal class MusicCrossfader( val item = session.currentMediaItem?.takeIf { it.mediaId == id } ?: return tail?.release() tail = - buildTail(null).apply { + newTail(null).apply { volume = 0f - playbackParameters = session.playbackParameters - addListener(tailListener) setMediaItem(item, alignAt + aligner.headStartMs) playWhenReady = false prepare() } - stage = Stage.PREPARED + stage = CrossfadeStage.PREPARED } private fun beginAlign(id: String) { @@ -548,11 +311,11 @@ internal class MusicCrossfader( fadeThrough("no tail was built") return } - if (player.playbackState == Player.STATE_READY) lineUp() else stage = Stage.WAITING_FOR_TAIL + if (player.playbackState == Player.STATE_READY) lineUp() else stage = CrossfadeStage.WAITING_FOR_TAIL } private fun lineUp() { - stage = Stage.WAITING_FOR_TAIL + stage = CrossfadeStage.WAITING_FOR_TAIL aligner.startWhenLinedUp() } @@ -577,12 +340,12 @@ internal class MusicCrossfader( } finally { handingOff = false } - stage = Stage.FADING + stage = CrossfadeStage.FADING val now = SystemClock.elapsedRealtime() outBeganAtMs = now inElapsedMs = 0L inRunningSinceMs = now.takeIf { session.isPlaying } - Log.d(TAG, "handed off $mediaId to the tail ${deltaMs}ms apart, out over ${outClockMs}ms, in over ${inClockMs}ms") + Log.d(CROSSFADE_TAG, "handed off $mediaId to the tail ${deltaMs}ms apart, out over ${outClockMs}ms, in over ${inClockMs}ms") handler.post(fadeStep) } @@ -597,20 +360,20 @@ internal class MusicCrossfader( releaseTail() val plan = CrossfadePolicy.fadeThrough(session.currentPosition, session.duration, session.playbackParameters.speed, settings.fadeMs) - Log.d(TAG, "fading $id through: $reason, out over ${plan.outMs}ms after ${plan.holdMs}ms") - stage = Stage.THROUGH + Log.d(CROSSFADE_TAG, "fading $id through: $reason, out over ${plan.outMs}ms after ${plan.holdMs}ms") + stage = CrossfadeStage.THROUGH outClockMs = plan.outMs.coerceAtLeast(1L) outBeganAtMs = SystemClock.elapsedRealtime() + plan.holdMs if (plan.outMs > 0L) handler.postDelayed(fadeStep, plan.holdMs) } private fun fadeThroughIfStillOn(id: String) { - if (stage == Stage.IDLE && session.currentMediaItem?.mediaId == id) fadeThrough("too little song left for a tail") + if (stage == CrossfadeStage.IDLE && session.currentMediaItem?.mediaId == id) fadeThrough("too little song left for a tail") } private fun startQuickFadeIn() { handler.removeCallbacks(fadeStep) - stage = Stage.THROUGH_IN + stage = CrossfadeStage.THROUGH_IN sessionScale = 0f onSessionScaleChanged() inClockMs = CrossfadePolicy.QUICK_FADE_IN_MS @@ -623,11 +386,11 @@ internal class MusicCrossfader( val now = SystemClock.elapsedRealtime() val done = when (stage) { - Stage.FADING -> { + CrossfadeStage.FADING -> { fadeBoth(now) } - Stage.THROUGH -> { + CrossfadeStage.THROUGH -> { sessionScale = CrossfadePolicy.fadeOutGain(CrossfadePolicy.progress(now - outBeganAtMs, outClockMs), settings.curve) onSessionScaleChanged() // Silent until the next song arrives, which starts the quick fade-in. @@ -635,7 +398,7 @@ internal class MusicCrossfader( false } - Stage.THROUGH_IN -> { + CrossfadeStage.THROUGH_IN -> { sessionScale = CrossfadePolicy.fadeInGain(incomingProgress(now), settings.curve) onSessionScaleChanged() sessionScale >= 1f @@ -645,7 +408,14 @@ internal class MusicCrossfader( return } } - if (done) finish() else handler.postDelayed(fadeStep, FADE_STEP_MS) + when { + done -> finish() + + // Nothing moves until the next song plays, which steps the fade again. + stage != CrossfadeStage.THROUGH && tail == null && inRunningSinceMs == null -> Unit + + else -> handler.postDelayed(fadeStep, FADE_STEP_MS) + } } /** Steps both songs; true once the old song is gone and the new one is at full volume. */ @@ -668,30 +438,27 @@ internal class MusicCrossfader( private fun finish() { skipFade = false releaseTail() - stage = Stage.IDLE + stage = CrossfadeStage.IDLE restoreScale() schedule() } private fun abort(reason: String?) { - if (reason != null) Log.d(TAG, "crossfade dropped: $reason") - val held = heldTarget ?: easingTo - heldTarget = null - easingTo = null + if (reason != null) Log.d(CROSSFADE_TAG, "crossfade dropped: $reason") + val held = skip.dropTargets() skipFade = false cancelMessages() releaseTail() - stage = Stage.IDLE + stage = CrossfadeStage.IDLE restoreScale() // The press still counts, it only lost its fade. - held?.let(::indexOf)?.let(::seekSession) + held?.let(skip::indexOf)?.let(::seekSession) } private fun releaseTail() { aligner.cancel() handler.removeCallbacks(fadeStep) - handler.removeCallbacks(easeStep) - handler.removeCallbacks(skipTimeoutStep) + skip.cancelSteps() tail?.release() tail = null fadeProgress = 0f @@ -726,10 +493,93 @@ internal class MusicCrossfader( .setDeleteAfterDelivery(true) .send() - private companion object { - const val TAG = "MusicCrossfader" - const val FADE_STEP_MS = 20L - const val DEFAULT_SKIP_LEAD_MS = 400L - const val SKIP_START_TIMEOUT_MS = 1_500L + private fun newTail(skipOverlapMs: Long?): ExoPlayer = + buildTail(skipOverlapMs).apply { + playbackParameters = session.playbackParameters + addListener(tailListener) + } + + private inner class SkipHost : CrossfadeSkip.Host { + override val stage get() = this@MusicCrossfader.stage + override val settings get() = this@MusicCrossfader.settings + override val tail get() = this@MusicCrossfader.tail + override val sessionScale get() = this@MusicCrossfader.sessionScale + + override fun scaleSession(scale: Float) { + this@MusicCrossfader.sessionScale = scale + onSessionScaleChanged() + } + + override fun startSkipTail( + mediaId: String, + gain: Float, + clockMs: Long, + setUp: ExoPlayer.() -> Unit, + ) { + skipFade = true + this@MusicCrossfader.mediaId = mediaId + tailGain = gain + outClockMs = clockMs + inClockMs = clockMs + this@MusicCrossfader.tail = newTail(clockMs).apply(setUp) + this@MusicCrossfader.stage = CrossfadeStage.SKIP_STARTING + } + + override fun restoreTailGain() { + this@MusicCrossfader.tail?.volume = tailGain + } + + override fun waitForNextSong() { + this@MusicCrossfader.stage = CrossfadeStage.WAITING_FOR_NEXT_SONG + } + + override fun startFade(late: Boolean) = this@MusicCrossfader.startFade(late) + + override fun fadeNextSongIn( + reason: String, + index: Int?, + ) { + Log.d(CROSSFADE_TAG, "crossfade dropped: $reason, the next song fades in") + skipFade = false + cancelMessages() + releaseTail() + scaleSession(0f) + index?.let(this@MusicCrossfader::seekSession) + startQuickFadeIn() + } + + override fun holdFade() { + if (this@MusicCrossfader.stage == CrossfadeStage.FADING) { + fadeProgress = CrossfadePolicy.progress(SystemClock.elapsedRealtime() - outBeganAtMs, outClockMs) + handler.removeCallbacks(fadeStep) + this@MusicCrossfader.stage = CrossfadeStage.WAITING_FOR_NEXT_SONG + } + skipFade = true + } + + override fun seekSession(index: Int) = this@MusicCrossfader.seekSession(index) + + override fun abort(reason: String?) = this@MusicCrossfader.abort(reason) + + override fun schedule() = this@MusicCrossfader.schedule() } } + +internal enum class CrossfadeStage { + IDLE, + PREPARED, + WAITING_FOR_TAIL, + ALIGNING, + SKIP_STARTING, + WAITING_FOR_NEXT_SONG, + FADING, + + /** No tail: the session fades its own song out. */ + THROUGH, + + /** No tail: the next song comes in quickly. */ + THROUGH_IN, +} + +internal const val CROSSFADE_TAG = "MusicCrossfader" +internal const val FADE_STEP_MS = 20L 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 170968a1e2..0ba9300e28 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 @@ -588,6 +588,7 @@ class Media3MusicService : MediaLibraryService() { // order, the player's shuffle flag reorders nothing on its own, whichever controller sets it. player.setShuffleOrder(ShuffleOrder.UnshuffledShuffleOrder(0)) musicResume.attach(player) + MusicPreload(this, player).attach(lifecycleScope, prefs.bufferProfile) crossfader = MusicCrossfader(player, ::buildCrossfadeTail, ::crossfadeMoment, ::applyLoudnessGain).also { it.attach() } lifecycleScope.launch { combine( diff --git a/app/src/main/java/io/github/aedev/flow/service/MusicPreload.kt b/app/src/main/java/io/github/aedev/flow/service/MusicPreload.kt new file mode 100644 index 0000000000..4ab73b214e --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/service/MusicPreload.kt @@ -0,0 +1,63 @@ +package io.github.aedev.flow.service + +import android.content.Context +import androidx.annotation.OptIn +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.ExoPlayer +import io.github.aedev.flow.data.local.BufferProfile +import io.github.aedev.flow.utils.NetworkState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.launch + +/** + * Loads the start of the next song while the current one plays, so a skip has audio to start from + * (#2076). Media3 does it only while the current song isn't loading, through the same sources and + * cache. Off while Android's Data Saver or the Data saver buffer profile is on, checked on each new song. + */ +@OptIn(UnstableApi::class) +internal class MusicPreload( + private val context: Context, + private val player: ExoPlayer, +) { + private var profileSavesData = false + + private val listener = + object : Player.Listener { + override fun onMediaItemTransition( + mediaItem: MediaItem?, + reason: Int, + ) = refresh() + } + + fun attach( + scope: CoroutineScope, + bufferProfile: Flow, + ) { + player.addListener(listener) + scope.launch { + bufferProfile.collect { + profileSavesData = it == BufferProfile.DATASAVER + refresh() + } + } + } + + private fun refresh() { + val wanted = + if (profileSavesData || NetworkState.isDataSaverOn(context)) { + ExoPlayer.PreloadConfiguration.DEFAULT + } else { + ExoPlayer.PreloadConfiguration(NEXT_SONG_US) + } + if (player.preloadConfiguration.targetPreloadDurationUs != wanted.targetPreloadDurationUs) { + player.preloadConfiguration = wanted + } + } + + private companion object { + const val NEXT_SONG_US = 10_000_000L + } +} diff --git a/app/src/main/java/io/github/aedev/flow/sync/apply/SyncApplier.kt b/app/src/main/java/io/github/aedev/flow/sync/apply/SyncApplier.kt index 2ec8defad9..6a2b244e07 100644 --- a/app/src/main/java/io/github/aedev/flow/sync/apply/SyncApplier.kt +++ b/app/src/main/java/io/github/aedev/flow/sync/apply/SyncApplier.kt @@ -27,10 +27,13 @@ import java.io.File import javax.inject.Inject import javax.inject.Singleton -data class ReceivedCollection( +/** A collection as received; its [hash] is worked out on first read, since only FLOW-SYNC/1's applied-once check needs it. */ +class ReceivedCollection( val lines: List, - val hash: String, -) + knownHash: String? = null, +) { + val hash: String by lazy { knownHash ?: SyncSerialization.collectionHash(lines) } +} /** Identifies the peer for the ledger/known-devices list. */ data class PeerInfo( diff --git a/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncProtocol.kt b/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncProtocol.kt index 6b160f1236..eea0ab650a 100644 --- a/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncProtocol.kt +++ b/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncProtocol.kt @@ -259,7 +259,7 @@ class SyncProtocol( } val complete = decode(expect(FrameType.COMPLETE, NETWORK_WAIT), Complete.serializer()) if (complete.collection != name) throw protocolError("COMPLETE for ${complete.collection} ended $name") - val computed = SyncSerialization.sha256Hex(lines.joinToString("\n")) + val computed = SyncSerialization.collectionHash(lines) if (computed != complete.hash || computed != entry.hash) { throw SyncProtocolException("payload hash mismatch for $name", CODE_HASH_MISMATCH, tellPeer = true) } diff --git a/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncSerialization.kt b/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncSerialization.kt index 52a1c87e39..7d01ea0c04 100644 --- a/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncSerialization.kt +++ b/app/src/main/java/io/github/aedev/flow/sync/protocol/SyncSerialization.kt @@ -18,12 +18,17 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.encodeToJsonElement import java.security.MessageDigest -/** A serialized collection ready for the wire: NDJSON [lines], [recordCount], and content [hash]. */ -data class CollectionWire( +/** + * A serialized collection ready for the wire: NDJSON [lines], [recordCount], and content [hash]. The hash is + * worked out on first read: only FLOW-SYNC/1 sends it, and a large collection costs a pass over every record. + */ +class CollectionWire( val lines: List, val recordCount: Int, - val hash: String, -) + knownHash: String? = null, +) { + val hash: String by lazy { knownHash ?: SyncSerialization.collectionHash(lines) } +} /** * NDJSON serialization + canonical content hashing for each collection. Records are emitted in @@ -48,8 +53,22 @@ object SyncSerialization { coerceInputValues = true } - fun sha256Hex(s: String): String { - val digest = MessageDigest.getInstance("SHA-256").digest(s.toByteArray(Charsets.UTF_8)) + fun sha256Hex(s: String): String = hex(MessageDigest.getInstance("SHA-256").digest(s.toByteArray(Charsets.UTF_8))) + + /** + * The same hash as [sha256Hex] of [lines] joined by `\n`, fed line by line: joining a large + * collection first ran out of memory (#2145). + */ + fun collectionHash(lines: List): String { + val digest = MessageDigest.getInstance("SHA-256") + lines.forEachIndexed { i, line -> + if (i > 0) digest.update('\n'.code.toByte()) + digest.update(line.toByteArray(Charsets.UTF_8)) + } + return hex(digest.digest()) + } + + private fun hex(digest: ByteArray): String { val sb = StringBuilder(digest.size * 2) for (b in digest) { val v = b.toInt() and 0xFF @@ -90,7 +109,7 @@ object SyncSerialization { serializer: KSerializer, ): CollectionWire { val lines = records.map { enc(serializer, it) } - return CollectionWire(lines, lines.size, sha256Hex(lines.joinToString("\n"))) + return CollectionWire(lines, lines.size) } // --- watch history --- @@ -167,7 +186,7 @@ object SyncSerialization { // --- music brain --- fun encodeMusicBrain(brain: CanonicalMusicBrain): CollectionWire { val line = enc(CanonicalMusicBrain.serializer(), brain) - return CollectionWire(listOf(line), 1, sha256Hex(line)) + return CollectionWire(listOf(line), 1) } /** Fold every record (one snapshot per device the peer knows) so a third device converges. */ diff --git a/app/src/main/java/io/github/aedev/flow/sync2/changes/ChangeBatches.kt b/app/src/main/java/io/github/aedev/flow/sync2/changes/ChangeBatches.kt index a5aa5c2876..037bbf1c00 100644 --- a/app/src/main/java/io/github/aedev/flow/sync2/changes/ChangeBatches.kt +++ b/app/src/main/java/io/github/aedev/flow/sync2/changes/ChangeBatches.kt @@ -13,6 +13,7 @@ import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive +import java.io.ByteArrayOutputStream /** FLOW-SYNC/1's chunk size; it keeps every batch well under the 4 MiB object limit. */ private const val RECORDS_PER_BATCH = 1000 @@ -98,7 +99,13 @@ fun batchContent( lines: List, ): ByteArray { val header = SyncSerialization.canonicalJson(Json.encodeToJsonElement(BatchHeader.serializer(), BatchHeader(collection, head, link))) - return (listOf(header) + lines).joinToString("\n").toByteArray() + val out = ByteArrayOutputStream() + out.write(header.toByteArray(Charsets.UTF_8)) + for (line in lines) { + out.write('\n'.code) + out.write(line.toByteArray(Charsets.UTF_8)) + } + return out.toByteArray() } /** @@ -171,7 +178,7 @@ suspend fun applyBatches( for (line in lines) { recordKey(collection, Json.parseToJsonElement(line).jsonObject)?.let { keys.getOrPut(collection) { HashSet() } += it } } - ReceivedCollection(lines, SyncSerialization.sha256Hex(lines.joinToString("\n"))) + ReceivedCollection(lines) } val collections = keys.keys.toList() val before = ownHashes(export(collections), keys) diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/library/DownloadsRecoveryCard.kt b/app/src/main/java/io/github/aedev/flow/ui/components/library/DownloadsRecoveryCard.kt index 48e28ab43b..2accf5ab36 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/library/DownloadsRecoveryCard.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/library/DownloadsRecoveryCard.kt @@ -16,19 +16,25 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import io.github.aedev.flow.R /** - * Offered on an empty Downloads screen when Flow can't read shared media: downloads an earlier - * install saved are still on the device, but a new install sees them only with media access. + * Offered on the Downloads screen when Flow can't reach downloads an earlier install saved: by + * default, on an empty screen without media access; with the other texts, when a picked folder lost + * its grant. */ @Composable internal fun DownloadsRecoveryCard( onAllow: () -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier, + icon: ImageVector = Icons.AutoMirrored.Outlined.ManageSearch, + title: String = stringResource(R.string.downloads_recover_title), + body: String = stringResource(R.string.downloads_recover_body), + allowLabel: String = stringResource(R.string.downloads_recover_allow), ) { Surface( modifier = modifier.fillMaxWidth(), @@ -40,17 +46,17 @@ internal fun DownloadsRecoveryCard( verticalArrangement = Arrangement.spacedBy(CardSpacing), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CardSpacing)) { - Icon(Icons.AutoMirrored.Outlined.ManageSearch, contentDescription = null, tint = MaterialTheme.colorScheme.primary) - Text(stringResource(R.string.downloads_recover_title), style = MaterialTheme.typography.titleMedium) + Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary) + Text(title, style = MaterialTheme.typography.titleMedium) } Text( - stringResource(R.string.downloads_recover_body), + body, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(CardSpacing, Alignment.End)) { TextButton(onClick = onDismiss) { Text(stringResource(R.string.downloads_recover_dismiss)) } - Button(onClick = onAllow) { Text(stringResource(R.string.downloads_recover_allow)) } + Button(onClick = onAllow) { Text(allowLabel) } } } } diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/common/MusicPlayerAppearance.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/common/MusicPlayerAppearance.kt index e60803231b..9b197ae463 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/common/MusicPlayerAppearance.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/common/MusicPlayerAppearance.kt @@ -26,6 +26,7 @@ internal class MusicPlayerAppearance( val hideArtwork: Boolean, val sleepTimerButton: Boolean, val splitTransport: Boolean, + val lyricsOnCover: Boolean, val playerScheme: ColorScheme, val controlScheme: ColorScheme, ) @@ -48,6 +49,7 @@ internal fun rememberMusicPlayerAppearance( val hideArtwork by playerPreferences.hideMusicPlayerArtwork.collectAsState(initial = false) val sleepTimerButton by playerPreferences.musicSleepTimerButton.collectAsState(initial = false) val splitTransport by playerPreferences.musicSplitTransport.collectAsState(initial = true) + val lyricsOnCover by playerPreferences.immersiveLyricsOnCover.collectAsState(initial = false) val followLightTheme by playerPreferences.musicPlayerFollowLightTheme.collectAsState(initial = false) val palette = rememberMediaPalette(thumbnailUrl) val lightPlayer = musicPlayerTurnsLight(backgroundStyle, followLightTheme, MaterialTheme.colorScheme.surface) @@ -64,6 +66,7 @@ internal fun rememberMusicPlayerAppearance( hideArtwork = hideArtwork, sleepTimerButton = sleepTimerButton, splitTransport = splitTransport, + lyricsOnCover = lyricsOnCover, playerScheme = playerScheme, controlScheme = controlScheme, ) diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/PlayerSliders.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/PlayerSliders.kt index 31970fba06..d9a33e8c67 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/PlayerSliders.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/PlayerSliders.kt @@ -186,6 +186,7 @@ private fun Modifier.wavyTrack( motion: WaveMotion, amplitude: () -> Float, wavelength: Dp, + thumbWidth: Dp, gap: Dp, activeColor: Color, inactiveColor: Color, @@ -196,25 +197,27 @@ private fun Modifier.wavyTrack( val stroke = Stroke(width = strokePx, cap = StrokeCap.Round) val wavelengthPx = wavelength.toPx() val amplitudePx = WaveAmplitude.toPx() + val thumbWidthPx = thumbWidth.toPx() val gapPx = gap.toPx() val dotRadius = StopDotSize.toPx() / 2f val path = Path() onDrawBehind { val mid = size.height / 2f - val edge = strokePx / 2f - val end = size.width - edge - val at = edge + (end - edge) * fraction().coerceIn(0f, 1f) - val waveEnd = at - gapPx - val restStart = at + gapPx + val width = size.width + val at = fraction() + val start = WavyTrackGeometry.waveStart(strokePx) + val end = WavyTrackGeometry.trackEnd(width, strokePx) + val waveEnd = WavyTrackGeometry.waveEnd(width, at, thumbWidthPx, gapPx, strokePx) + val restStart = WavyTrackGeometry.restStart(width, at, thumbWidthPx, gapPx, strokePx) if (restStart < end) { drawLine(inactiveColor, Offset(restStart, mid), Offset(end, mid), strokeWidth = strokePx, cap = StrokeCap.Round) } if (stopDot) drawCircle(activeColor, radius = dotRadius, center = Offset(end, mid)) - if (waveEnd <= edge) return@onDrawBehind - val height = amplitudePx * amplitude() + if (waveEnd <= start) return@onDrawBehind + val height = amplitudePx * amplitude() * WavyTrackGeometry.heightFactor(waveEnd - start, wavelengthPx) val shift = motion.phase.floatValue * 2f * PI.toFloat() path.rewind() - var x = edge + var x = start path.moveTo(x, mid + height * sin(x / wavelengthPx * 2f * PI.toFloat() - shift)) while (x < waveEnd) { x = minOf(x + WAVE_STEP_PX, waveEnd) @@ -275,7 +278,8 @@ fun ExpressiveWavySlider( motion = motion, amplitude = amplitude, wavelength = wavelength, - gap = ExpressiveThumbPressedSize / 2 + ExpressiveThumbGap, + thumbWidth = ExpressiveThumbSize, + gap = ExpressiveThumbGap, activeColor = activeColor, inactiveColor = inactiveColor, stopDot = true, @@ -342,6 +346,7 @@ fun SquigglySlider( motion = motion, amplitude = amplitude, wavelength = SquigglyWavelength, + thumbWidth = SquigglyThumbSize.width, gap = 0.dp, activeColor = colors.activeTrackColor, inactiveColor = colors.inactiveTrackColor, diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometry.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometry.kt new file mode 100644 index 0000000000..4a4c5f0c9b --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometry.kt @@ -0,0 +1,48 @@ +package io.github.aedev.flow.ui.components.musicplayer.controls + +/** + * Where a wavy seek bar's two parts sit, in the track's own pixels. M3's Slider insets its track by + * half the thumb and centres the thumb at fraction × track width, so both parts are measured from + * there: each round cap stops [gap] short of the thumb's edge, whatever the fraction. + */ +internal object WavyTrackGeometry { + fun thumbCentre( + trackWidth: Float, + fraction: Float, + ): Float = trackWidth * fraction.coerceIn(0f, 1f) + + /** Where the wave's line starts: half a stroke in, so its round cap starts at the track's start. */ + fun waveStart(stroke: Float): Float = stroke / 2f + + /** Where the wave's line ends, never before [waveStart]. */ + fun waveEnd( + trackWidth: Float, + fraction: Float, + thumbWidth: Float, + gap: Float, + stroke: Float, + ): Float = maxOf(waveStart(stroke), thumbCentre(trackWidth, fraction) - thumbWidth / 2f - gap - stroke / 2f) + + /** Where the straight rest of the track starts, mirroring [waveEnd] on the thumb's other side. */ + fun restStart( + trackWidth: Float, + fraction: Float, + thumbWidth: Float, + gap: Float, + stroke: Float, + ): Float = thumbCentre(trackWidth, fraction) + thumbWidth / 2f + gap + stroke / 2f + + fun trackEnd( + trackWidth: Float, + stroke: Float, + ): Float = trackWidth - stroke / 2f + + /** + * How much of its full height a wave this long gets. A wave of a few pixels at full height is one + * steep hook that flips as the phase moves, so it grows in over its first [wavelength]. + */ + fun heightFactor( + waveLength: Float, + wavelength: Float, + ): Float = if (wavelength <= 0f) 1f else (waveLength / wavelength).coerceIn(0f, 1f) +} diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/CompactPlayerLayout.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/CompactPlayerLayout.kt index ae2d0e9614..69e41d856e 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/CompactPlayerLayout.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/CompactPlayerLayout.kt @@ -26,6 +26,8 @@ internal fun CompactPlayerLayout( queueFraction: () -> Float, bottomInset: Dp, modifier: Modifier = Modifier, + // Lyrics shown in place take the cover's whole space, so the cover and its skip swipes leave. + lyrics: (@Composable (Modifier) -> Unit)? = null, ) { val sidePadding = Modifier.padding(horizontal = PlayerHorizontalPadding) Column( @@ -43,17 +45,21 @@ internal fun CompactPlayerLayout( .weight(1f), ) { slots.topBar(Modifier.statusBarsPadding()) - Spacer(modifier = Modifier.weight(1f)) - slots.artwork( - sidePadding - .size(artworkSize) - .graphicsLayer { - val scale = 1f - queueFraction() * 0.10f - scaleX = scale - scaleY = scale - }, - ) - Spacer(modifier = Modifier.weight(1f)) + if (lyrics != null) { + lyrics(Modifier.fillMaxWidth().weight(1f)) + } else { + Spacer(modifier = Modifier.weight(1f)) + slots.artwork( + sidePadding + .size(artworkSize) + .graphicsLayer { + val scale = 1f - queueFraction() * 0.10f + scaleX = scale + scaleY = scale + }, + ) + Spacer(modifier = Modifier.weight(1f)) + } } Spacer(modifier = Modifier.height(16.dp)) slots.header(sidePadding) diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/FullMusicPlayerContent.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/FullMusicPlayerContent.kt index abb91da913..0fccba4f13 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/FullMusicPlayerContent.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/FullMusicPlayerContent.kt @@ -1,5 +1,6 @@ package io.github.aedev.flow.ui.components.musicplayer.full +import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues @@ -23,17 +24,14 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.min import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import io.github.aedev.flow.data.local.MusicPlayerBackgroundStyle -import io.github.aedev.flow.data.localmedia.LocalMediaIds import io.github.aedev.flow.data.music.model.MusicTrack import io.github.aedev.flow.player.EnhancedMusicPlayerManager import io.github.aedev.flow.player.SleepTimerManager -import io.github.aedev.flow.ui.components.layout.navigation.LocalMediaNavigator import io.github.aedev.flow.ui.components.musicplayer.common.PlayerBackdropColors import io.github.aedev.flow.ui.components.musicplayer.controls.PlayerProgressSlider import io.github.aedev.flow.ui.components.musicplayer.lyrics.DEFAULT_LYRICS_TEXT_SIZE @@ -42,9 +40,6 @@ import io.github.aedev.flow.ui.components.musicplayer.lyrics.lyricsBackdrop import io.github.aedev.flow.ui.components.musicplayer.motion.MusicSideSwipeHud import io.github.aedev.flow.ui.components.musicplayer.motion.musicSideSwipes import io.github.aedev.flow.ui.components.musicplayer.motion.rememberMusicSideSwipes -import io.github.aedev.flow.ui.components.musicplayer.queue.QueueList -import io.github.aedev.flow.ui.components.musicplayer.queue.QueuePullUpSheet -import io.github.aedev.flow.ui.components.musicplayer.queue.QueueSheet import io.github.aedev.flow.ui.components.musicplayer.queue.queuePullUpGesture import io.github.aedev.flow.ui.components.musicplayer.queue.rememberQueuePullUpState import io.github.aedev.flow.ui.components.musicplayer.sheet.PlayerPanel @@ -58,7 +53,6 @@ import io.github.aedev.flow.ui.screens.music.MusicVideoSwitchViewModel import io.github.aedev.flow.ui.screens.music.sharedMusicPlayerViewModel import io.github.aedev.flow.ui.utils.LocalWindowIsLandscape import io.github.aedev.flow.ui.utils.LocalWindowSizeClass -import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -71,6 +65,7 @@ internal fun FullMusicPlayerContent( hideArtwork: Boolean, sleepTimerButton: Boolean, splitTransport: Boolean = false, + lyricsOnCover: Boolean = false, // The transport, seek bar, like and download and the action row draw with this scheme. controlScheme: ColorScheme = MaterialTheme.colorScheme, onLyricsShownChange: (Boolean) -> Unit = {}, @@ -84,7 +79,6 @@ internal fun FullMusicPlayerContent( val positionState = viewModel.currentPositionMs.collectAsState() val density = LocalDensity.current val colorScheme = MaterialTheme.colorScheme - val navigator = LocalMediaNavigator.current val thumbnailUrl = uiState.currentTrack?.highResThumbnailUrl ?: track.highResThumbnailUrl val sheets = remember { FullPlayerSheetState() } @@ -157,6 +151,8 @@ internal fun FullMusicPlayerContent( val queueActions = rememberPlayerQueueActions(viewModel, sheets) val immersiveBackground = backgroundStyle == MusicPlayerBackgroundStyle.IMMERSIVE + var lyricsInPlace by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(immersiveBackground) { if (!immersiveBackground) lyricsInPlace = false } val displayTitle = previewTrack?.title ?: uiState.currentTrack?.title ?: track.title val displayArtist = previewTrack?.artist ?: uiState.currentTrack?.artist ?: track.artist @@ -167,6 +163,8 @@ internal fun FullMusicPlayerContent( if (it == MusicPlayerLayout.WIDE && !panes.showsSidePane) MusicPlayerLayout.SPLIT else it } val isWide = layout == MusicPlayerLayout.WIDE + val inPlaceAvailable = lyricsShowInPlace(lyricsOnCover, backgroundStyle, layout) + val lyricsInPlaceShown = lyricsInPlace && inPlaceAvailable var sidePaneTab by rememberSaveable { mutableStateOf(PlayerSidePaneTab.UP_NEXT) } val selectSidePaneTab: (PlayerSidePaneTab) -> Unit = { tab -> if (tab == PlayerSidePaneTab.LYRICS) uiState.currentTrack?.let { viewModel.ensureLyricsLoaded(it) } @@ -176,6 +174,10 @@ internal fun FullMusicPlayerContent( uiState.currentTrack?.let { viewModel.ensureLyricsLoaded(it) } showLyricsSheet = true } + val showLyricsInPlace = { + uiState.currentTrack?.let { viewModel.ensureLyricsLoaded(it) } + lyricsInPlace = true + } BoxWithConstraints( modifier = Modifier.fillMaxSize().musicPlayerKeyboardShortcuts(isPlayerSheetExpanded && !sheets.sleepTimer, viewModel), @@ -205,6 +207,8 @@ internal fun FullMusicPlayerContent( selectSidePaneTab(tab) } else if (queue) { queueState.open() + } else if (inPlaceAvailable) { + showLyricsInPlace() } else { openLyricsSheet() } @@ -236,67 +240,38 @@ internal fun FullMusicPlayerContent( ) }, artwork = { modifier -> - PlayerArtworkFrame( + NowPlayingArtwork( immersive = immersiveBackground, isPlaying = uiState.isPlaying, + thumbnailUrl = thumbnailUrl, + previousTrack = previousTrack, + nextTrack = nextTrack, + previewDirection = previewDirection, + // Spinners in the warm, collapsed tree animate at alpha 0 otherwise. + isLoading = (uiState.isLoading || videoLoading) && isPlayerSheetExpanded, + hideArtwork = hideArtwork, + videoShowing = videoShowing, + videoPlayer = videoPlayer, + animatedArtwork = animatedArtwork, + viewModel = viewModel, + onDragPreviewChange = { artworkDragPreview = it }, + onVideoShowingChange = { videoShowing = it }, modifier = modifier, - ) { - PlayerArtwork( - thumbnailUrl = thumbnailUrl, - previousThumbnailUrl = previousTrack?.highResThumbnailUrl, - nextThumbnailUrl = nextTrack?.highResThumbnailUrl, - previewDirection = previewDirection, - // Spinners in the warm, collapsed tree animate at alpha 0 otherwise. - isLoading = (uiState.isLoading || videoLoading) && isPlayerSheetExpanded, - hideArtwork = hideArtwork || immersiveBackground || videoShowing, - hiddenArtworkColor = - if (immersiveBackground || videoShowing) Color.Unspecified else colorScheme.surfaceContainerHigh, - onSkipPrevious = { viewModel.skipToPrevious() }, - onSkipNext = { viewModel.skipToNext() }, - modifier = Modifier.fillMaxSize(), - onDragPreviewChange = { artworkDragPreview = it }, - underlay = - videoPlayer?.let { player -> - { - PlayerVideo( - player = player, - cornerRadius = PlayerArtworkCornerRadius, - onShowingChange = { videoShowing = it }, - modifier = Modifier.fillMaxSize(), - ) - } - }, - overlay = animatedArtwork.takeUnless { immersiveBackground }, - ) - } + ) }, header = { modifier -> - MaterialTheme(colorScheme = controlScheme) { - PlayerTrackHeader( - title = displayTitle, - artist = displayArtist, - onArtistClick = { - val track = previewTrack ?: uiState.currentTrack - if (track != null) { - artistScope.launch { - val artists = viewModel.resolveArtists(track) - when { - artists.size > 1 -> sheets.artists = artists - artists.size == 1 -> navigator.openArtist(artists.first().id.orEmpty()) - } - } - } - }, - animateTrackText = isPlayerSheetExpanded && uiState.isPlaying && !showLyricsSheet && !queueCoversArtwork, - showLibraryActions = !LocalMediaIds.isLocal(uiState.currentTrack?.videoId), - isLiked = uiState.isLiked, - isDownloaded = uiState.downloadedTrackIds.contains(uiState.currentTrack?.videoId), - onLikeClick = { viewModel.toggleLike() }, - onDownloadClick = { viewModel.downloadTrack() }, - onAddToPlaylist = { sheets.save = true }, - modifier = modifier, - ) - } + NowPlayingHeader( + title = displayTitle, + artist = displayArtist, + track = previewTrack ?: uiState.currentTrack, + uiState = uiState, + animateTrackText = isPlayerSheetExpanded && uiState.isPlaying && !showLyricsSheet && !queueCoversArtwork, + controlScheme = controlScheme, + viewModel = viewModel, + sheets = sheets, + artistScope = artistScope, + modifier = modifier, + ) }, progress = { modifier -> MaterialTheme(colorScheme = controlScheme) { @@ -330,10 +305,17 @@ internal fun FullMusicPlayerContent( MaterialTheme(colorScheme = controlScheme) { // Wide windows show lyrics and the queue in the side pane, so the buttons pick its tab. PlayerActionRow( - lyricsActive = if (isWide) sidePaneTab == PlayerSidePaneTab.LYRICS else showLyricsSheet, + lyricsActive = if (isWide) sidePaneTab == PlayerSidePaneTab.LYRICS else showLyricsSheet || lyricsInPlaceShown, shuffleEnabled = uiState.shuffleEnabled, repeatMode = uiState.repeatMode, - onLyricsClick = { if (isWide) selectSidePaneTab(PlayerSidePaneTab.LYRICS) else openLyricsSheet() }, + onLyricsClick = { + when { + isWide -> selectSidePaneTab(PlayerSidePaneTab.LYRICS) + lyricsInPlaceShown -> lyricsInPlace = false + inPlaceAvailable -> showLyricsInPlace() + else -> openLyricsSheet() + } + }, onShuffleClick = { viewModel.toggleShuffle() }, onRepeatClick = { viewModel.toggleRepeat() }, onQueueClick = { if (isWide) selectSidePaneTab(PlayerSidePaneTab.UP_NEXT) else queueState.open() }, @@ -347,6 +329,12 @@ internal fun FullMusicPlayerContent( }, ) + val lyricsDim = + animateFloatAsState( + targetValue = if (lyricsInPlaceShown) IN_PLACE_LYRICS_DIM else 0f, + animationSpec = MaterialTheme.motionScheme.defaultEffectsSpec(), + label = "inPlaceLyricsDim", + ) PlayerBackground( thumbnailUrl = backgroundThumbnailUrl, style = backgroundStyle, @@ -359,13 +347,38 @@ internal fun FullMusicPlayerContent( .orEmpty(), trackId = track.videoId, motionRunning = isPlayerSheetExpanded && uiState.isPlaying && !showLyricsSheet && !queueCoversArtwork, + dim = { lyricsDim.value }, ) - val sideSwipes = rememberMusicSideSwipes(layout, isPlayerSheetExpanded) { queueState.fraction() > 0f || showLyricsSheet } + val sideSwipes = + rememberMusicSideSwipes(layout, isPlayerSheetExpanded) { + queueState.fraction() > 0f || showLyricsSheet || lyricsInPlaceShown + } val pullUpQueue = Modifier.musicSideSwipes(sideSwipes).queuePullUpGesture(queueState, enabled = isPlayerSheetExpanded && !isWide) + val paneLyricsBackdrop = remember(palette.base) { lyricsBackdrop(palette.base) } when (layout) { MusicPlayerLayout.COMPACT -> { - CompactPlayerLayout(slots, artworkSize, queueState::fraction, navBarPadding, pullUpQueue) + val inPlaceLyrics: @Composable (Modifier) -> Unit = { modifier -> + NowPlayingLyricsInPlace( + uiState = uiState, + viewModel = viewModel, + accentColor = colorScheme.primary, + backdropColor = paneLyricsBackdrop, + contentColor = colorScheme.onSurface, + positionState = positionState, + active = inPlaceLyricsActive(isPlayerSheetExpanded, lyricsInPlaceShown, showLyricsSheet, queueCoversArtwork), + onOpenFullScreen = openLyricsSheet, + modifier = modifier, + ) + } + CompactPlayerLayout( + slots = slots, + artworkSize = artworkSize, + queueFraction = queueState::fraction, + bottomInset = navBarPadding, + modifier = pullUpQueue, + lyrics = inPlaceLyrics.takeIf { lyricsInPlaceShown }, + ) } MusicPlayerLayout.PORTRAIT_LARGE -> { @@ -383,39 +396,19 @@ internal fun FullMusicPlayerContent( } MusicPlayerLayout.WIDE -> { - val paneLyricsBackdrop = remember(palette.base) { lyricsBackdrop(palette.base) } WidePlayerLayout(slots, panes, immersive = immersiveBackground) { modifier -> - PlayerSidePane( + NowPlayingSidePane( tab = sidePaneTab, onTabChange = selectSidePaneTab, onOpenFullLyrics = openLyricsSheet, lyricsBackdrop = paneLyricsBackdrop, - upNext = { - QueueList( - queue = uiState.queue, - radioTracks = uiState.autoplaySuggestions, - currentIndex = uiState.currentQueueIndex, - // The warm tree stays composed while collapsed; the row waveform must not animate there. - isPlaying = uiState.isPlaying && isPlayerSheetExpanded, - isRadioLoading = uiState.isRadioLoading, - endlessRadioEnabled = uiState.endlessRadioEnabled, - downloadedTrackIds = uiState.downloadedTrackIds, - swipes = queueSwipes, - actions = queueActions, - clearNavigationBar = false, - selectEntry = true, - ) - }, - lyrics = { - NowPlayingLyricsPane( - uiState = uiState, - viewModel = viewModel, - accentColor = colorScheme.primary, - backdropColor = paneLyricsBackdrop, - positionState = positionState, - active = isPlayerSheetExpanded && !showLyricsSheet, - ) - }, + uiState = uiState, + viewModel = viewModel, + positionState = positionState, + isPlayerSheetExpanded = isPlayerSheetExpanded, + showLyricsSheet = showLyricsSheet, + queueSwipes = queueSwipes, + queueActions = queueActions, modifier = modifier, ) } @@ -429,23 +422,7 @@ internal fun FullMusicPlayerContent( } else { Modifier } - QueuePullUpSheet(queueState, queueSheetModifier) { cornerRadius, dragHandleModifier -> - QueueSheet( - sheetCornerRadius = cornerRadius, - queue = uiState.queue, - radioTracks = uiState.autoplaySuggestions, - currentIndex = uiState.currentQueueIndex, - isPlaying = uiState.isPlaying, - isRadioLoading = uiState.isRadioLoading, - endlessRadioEnabled = uiState.endlessRadioEnabled, - shuffleEnabled = uiState.shuffleEnabled, - repeatMode = uiState.repeatMode, - downloadedTrackIds = uiState.downloadedTrackIds, - swipes = queueSwipes, - actions = queueActions, - dragHandleModifier = dragHandleModifier, - ) - } + NowPlayingQueueSheet(queueState, uiState, queueSwipes, queueActions, queueSheetModifier) val largeLyrics = layout == MusicPlayerLayout.WIDE || layout == MusicPlayerLayout.PORTRAIT_LARGE NowPlayingLyricsSheet( diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicy.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicy.kt new file mode 100644 index 0000000000..ddbcc746eb --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicy.kt @@ -0,0 +1,24 @@ +package io.github.aedev.flow.ui.components.musicplayer.full + +import io.github.aedev.flow.data.local.MusicPlayerBackgroundStyle + +/** How dark the immersive cover goes behind lyrics shown in place, as the scrim's alpha. */ +internal const val IN_PLACE_LYRICS_DIM = 0.6f + +/** + * The lyrics button shows lyrics in the player, over the cover, only when the user turned that on, in the + * phone column with the immersive background. Otherwise it opens the lyrics sheet. + */ +internal fun lyricsShowInPlace( + enabled: Boolean, + background: MusicPlayerBackgroundStyle, + layout: MusicPlayerLayout, +): Boolean = enabled && background == MusicPlayerBackgroundStyle.IMMERSIVE && layout == MusicPlayerLayout.COMPACT + +/** Lyrics in place sync and scroll only while someone can see them: not collapsed, not under the sheet or the queue. */ +internal fun inPlaceLyricsActive( + expanded: Boolean, + inPlace: Boolean, + sheetOpen: Boolean, + queueCovers: Boolean, +): Boolean = expanded && inPlace && !sheetOpen && !queueCovers diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingLyrics.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingLyrics.kt index 49a3b86017..380649def0 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingLyrics.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingLyrics.kt @@ -1,10 +1,24 @@ package io.github.aedev.flow.ui.components.musicplayer.full +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.OpenInFull +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.res.stringResource +import io.github.aedev.flow.R import io.github.aedev.flow.data.localmedia.LocalMediaIds import io.github.aedev.flow.ui.components.musicplayer.lyrics.InlineLyricsPanel import io.github.aedev.flow.ui.components.musicplayer.lyrics.LyricsDisplayOptions @@ -127,3 +141,44 @@ private fun MusicPlayerViewModel.applyLyricsDisplay( if (new.animationStyle != old.animationStyle) setLyricsAnimationStyle(new.animationStyle) if (new.glow != old.glow) setLyricsGlow(new.glow) } + +/** + * The lyrics in place of the immersive cover on the phone layout, with a button up to the + * full-screen sheet. [active] is false whenever nobody can see them, so the panel stops. + */ +@Composable +internal fun NowPlayingLyricsInPlace( + uiState: MusicPlayerUiState, + viewModel: MusicPlayerViewModel, + accentColor: Color, + backdropColor: Color, + contentColor: Color, + positionState: State, + active: Boolean, + onOpenFullScreen: () -> Unit, + modifier: Modifier = Modifier, +) { + val appear = remember { Animatable(0f) } + val appearSpec = MaterialTheme.motionScheme.defaultEffectsSpec() + LaunchedEffect(appear) { appear.animateTo(1f, appearSpec) } + Box(modifier = modifier.graphicsLayer { alpha = appear.value }) { + NowPlayingLyricsPane( + uiState = uiState, + viewModel = viewModel, + accentColor = accentColor, + backdropColor = backdropColor, + positionState = positionState, + active = active, + ) + IconButton( + onClick = onOpenFullScreen, + colors = IconButtonDefaults.iconButtonColors(contentColor = contentColor), + modifier = Modifier.align(Alignment.TopEnd), + ) { + Icon( + imageVector = Icons.Rounded.OpenInFull, + contentDescription = stringResource(R.string.music_player_lyrics_full_screen), + ) + } + } +} diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingSlotContent.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingSlotContent.kt new file mode 100644 index 0000000000..0ada65b102 --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/NowPlayingSlotContent.kt @@ -0,0 +1,198 @@ +package io.github.aedev.flow.ui.components.musicplayer.full + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.media3.common.Player +import io.github.aedev.flow.data.localmedia.LocalMediaIds +import io.github.aedev.flow.data.music.model.MusicTrack +import io.github.aedev.flow.ui.components.layout.navigation.LocalMediaNavigator +import io.github.aedev.flow.ui.components.musicplayer.queue.QueueActions +import io.github.aedev.flow.ui.components.musicplayer.queue.QueueList +import io.github.aedev.flow.ui.components.musicplayer.queue.QueuePullUpSheet +import io.github.aedev.flow.ui.components.musicplayer.queue.QueuePullUpState +import io.github.aedev.flow.ui.components.musicplayer.queue.QueueSheet +import io.github.aedev.flow.ui.components.musicplayer.queue.QueueSwipes +import io.github.aedev.flow.ui.components.shared.SkipDirection +import io.github.aedev.flow.ui.screens.music.MusicPlayerUiState +import io.github.aedev.flow.ui.screens.music.MusicPlayerViewModel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch + +/** The artwork slot: the cover (or the music video under it), with the swipe-to-skip carousel. */ +@Composable +internal fun NowPlayingArtwork( + immersive: Boolean, + isPlaying: Boolean, + thumbnailUrl: String?, + previousTrack: MusicTrack?, + nextTrack: MusicTrack?, + previewDirection: SkipDirection?, + isLoading: Boolean, + hideArtwork: Boolean, + videoShowing: Boolean, + videoPlayer: Player?, + animatedArtwork: (@Composable () -> Unit)?, + viewModel: MusicPlayerViewModel, + onDragPreviewChange: (SkipDirection?) -> Unit, + onVideoShowingChange: (Boolean) -> Unit, + modifier: Modifier = Modifier, +) { + PlayerArtworkFrame( + immersive = immersive, + isPlaying = isPlaying, + modifier = modifier, + ) { + PlayerArtwork( + thumbnailUrl = thumbnailUrl, + previousThumbnailUrl = previousTrack?.highResThumbnailUrl, + nextThumbnailUrl = nextTrack?.highResThumbnailUrl, + previewDirection = previewDirection, + isLoading = isLoading, + hideArtwork = hideArtwork || immersive || videoShowing, + hiddenArtworkColor = + if (immersive || videoShowing) Color.Unspecified else MaterialTheme.colorScheme.surfaceContainerHigh, + onSkipPrevious = { viewModel.skipToPrevious() }, + onSkipNext = { viewModel.skipToNext() }, + modifier = Modifier.fillMaxSize(), + onDragPreviewChange = onDragPreviewChange, + underlay = + videoPlayer?.let { player -> + { + PlayerVideo( + player = player, + cornerRadius = PlayerArtworkCornerRadius, + onShowingChange = onVideoShowingChange, + modifier = Modifier.fillMaxSize(), + ) + } + }, + overlay = animatedArtwork.takeUnless { immersive }, + ) + } +} + +/** Title and artist with like, download and save; a tap on the artist opens them, or a picker for several. */ +@Composable +internal fun NowPlayingHeader( + title: String, + artist: String, + track: MusicTrack?, + uiState: MusicPlayerUiState, + animateTrackText: Boolean, + controlScheme: ColorScheme, + viewModel: MusicPlayerViewModel, + sheets: FullPlayerSheetState, + artistScope: CoroutineScope, + modifier: Modifier = Modifier, +) { + val navigator = LocalMediaNavigator.current + MaterialTheme(colorScheme = controlScheme) { + PlayerTrackHeader( + title = title, + artist = artist, + onArtistClick = { + if (track != null) { + artistScope.launch { + val artists = viewModel.resolveArtists(track) + when { + artists.size > 1 -> sheets.artists = artists + artists.size == 1 -> navigator.openArtist(artists.first().id.orEmpty()) + } + } + } + }, + animateTrackText = animateTrackText, + showLibraryActions = !LocalMediaIds.isLocal(uiState.currentTrack?.videoId), + isLiked = uiState.isLiked, + isDownloaded = uiState.downloadedTrackIds.contains(uiState.currentTrack?.videoId), + onLikeClick = { viewModel.toggleLike() }, + onDownloadClick = { viewModel.downloadTrack() }, + onAddToPlaylist = { sheets.save = true }, + modifier = modifier, + ) + } +} + +/** The wide layout's side pane: Up next or the lyrics, which stop while the player is closed or the sheet covers them. */ +@Composable +internal fun NowPlayingSidePane( + tab: PlayerSidePaneTab, + onTabChange: (PlayerSidePaneTab) -> Unit, + onOpenFullLyrics: () -> Unit, + lyricsBackdrop: Color, + uiState: MusicPlayerUiState, + viewModel: MusicPlayerViewModel, + positionState: State, + isPlayerSheetExpanded: Boolean, + showLyricsSheet: Boolean, + queueSwipes: QueueSwipes, + queueActions: QueueActions, + modifier: Modifier = Modifier, +) { + PlayerSidePane( + tab = tab, + onTabChange = onTabChange, + onOpenFullLyrics = onOpenFullLyrics, + lyricsBackdrop = lyricsBackdrop, + upNext = { + QueueList( + queue = uiState.queue, + radioTracks = uiState.autoplaySuggestions, + currentIndex = uiState.currentQueueIndex, + // The warm tree stays composed while collapsed; the row waveform must not animate there. + isPlaying = uiState.isPlaying && isPlayerSheetExpanded, + isRadioLoading = uiState.isRadioLoading, + endlessRadioEnabled = uiState.endlessRadioEnabled, + downloadedTrackIds = uiState.downloadedTrackIds, + swipes = queueSwipes, + actions = queueActions, + clearNavigationBar = false, + selectEntry = true, + ) + }, + lyrics = { + NowPlayingLyricsPane( + uiState = uiState, + viewModel = viewModel, + accentColor = MaterialTheme.colorScheme.primary, + backdropColor = lyricsBackdrop, + positionState = positionState, + active = isPlayerSheetExpanded && !showLyricsSheet, + ) + }, + modifier = modifier, + ) +} + +/** The queue pulled up over the phone layouts. */ +@Composable +internal fun NowPlayingQueueSheet( + state: QueuePullUpState, + uiState: MusicPlayerUiState, + queueSwipes: QueueSwipes, + queueActions: QueueActions, + modifier: Modifier = Modifier, +) { + QueuePullUpSheet(state, modifier) { cornerRadius, dragHandleModifier -> + QueueSheet( + sheetCornerRadius = cornerRadius, + queue = uiState.queue, + radioTracks = uiState.autoplaySuggestions, + currentIndex = uiState.currentQueueIndex, + isPlaying = uiState.isPlaying, + isRadioLoading = uiState.isRadioLoading, + endlessRadioEnabled = uiState.endlessRadioEnabled, + shuffleEnabled = uiState.shuffleEnabled, + repeatMode = uiState.repeatMode, + downloadedTrackIds = uiState.downloadedTrackIds, + swipes = queueSwipes, + actions = queueActions, + dragHandleModifier = dragHandleModifier, + ) + } +} diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/PlayerBackground.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/PlayerBackground.kt index b7b0318d5b..050ae25042 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/PlayerBackground.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/full/PlayerBackground.kt @@ -20,6 +20,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.blur +import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Brush @@ -54,6 +55,8 @@ fun PlayerBackground( trackId: String = "", // Moving colours only: whether the field may drift, false while the player is hidden or the song paused. motionRunning: Boolean = false, + // Immersive only: the scrim's alpha over the cover, read while drawing so a fade never recomposes. + dim: () -> Float = { 0f }, ) { val context = LocalContext.current LaunchedEffect(preloadCovers) { preloadCovers.forEach { context.imageLoader.execute(ImageRequest.Builder(context).data(it).build()) } } @@ -145,6 +148,14 @@ fun PlayerBackground( ), ), ) + val scrim = MaterialTheme.colorScheme.scrim + Box( + modifier = + Modifier.fillMaxSize().drawBehind { + val alpha = dim() + if (alpha > 0f) drawRect(scrim, alpha = alpha) + }, + ) } MusicPlayerBackgroundStyle.BLUR_GRADIENT -> { diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsLine.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsLine.kt index 48b14409e1..d4afee374e 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsLine.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsLine.kt @@ -23,7 +23,6 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -32,7 +31,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin @@ -226,9 +224,13 @@ internal fun LyricsLine( } else { null } - }.clip(RoundedCornerShape(8.dp)) - .combinedClickable(onClickLabel = if (isSynced) playFromHere else null, onClick = onClick) - .padding( + }.combinedClickable( + interactionSource = null, + // Lyric lines are text, not buttons: no pressed layer, the tap just plays from the line (#2147). + indication = null, + onClickLabel = if (isSynced) playFromHere else null, + onClick = onClick, + ).padding( start = 24.dp, end = 24.dp, top = if (item.isBackground) 0.dp else 12.dp, diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeats.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeats.kt new file mode 100644 index 0000000000..7b958bd0fc --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeats.kt @@ -0,0 +1,37 @@ +package io.github.aedev.flow.ui.components.musicplayer.lyrics + +import io.github.aedev.flow.data.lyrics.LyricsEntry + +/** + * How many lines in a row, ending at [index], are the same words: 1 for a line that doesn't repeat + * the one before it. Case, spacing and punctuation don't count; a blank break or a different line + * ends the run. + */ +internal fun lyricRepeatCount( + lines: List, + index: Int, +): Int { + val key = lines.getOrNull(index)?.let { repeatKey(it.text) }?.takeIf { it.isNotEmpty() } ?: return 1 + var count = 1 + var previous = index - 1 + while (previous >= 0 && repeatKey(lines[previous].text) == key) { + count++ + previous-- + } + return count +} + +private val Ignored = + setOf( + CharCategory.SPACE_SEPARATOR, + CharCategory.CONNECTOR_PUNCTUATION, + CharCategory.DASH_PUNCTUATION, + CharCategory.START_PUNCTUATION, + CharCategory.END_PUNCTUATION, + CharCategory.INITIAL_QUOTE_PUNCTUATION, + CharCategory.FINAL_QUOTE_PUNCTUATION, + CharCategory.OTHER_PUNCTUATION, + ) + +// Only punctuation and spaces go: vowel signs are marks, not letters, and they change the word. +private fun repeatKey(text: String): String = text.lowercase().filterNot { it.isWhitespace() || it.category in Ignored } diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/SyncedLyricLine.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/SyncedLyricLine.kt index c11375a1b8..d8ed07594f 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/SyncedLyricLine.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/SyncedLyricLine.kt @@ -5,9 +5,12 @@ import androidx.compose.animation.SizeTransform import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.absoluteOffset import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect @@ -16,17 +19,25 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextMeasurer import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.ResolvedTextDirection import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.LayoutDirection import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.currentStateAsState +import io.github.aedev.flow.R import io.github.aedev.flow.data.local.LyricsAnimationStyle import io.github.aedev.flow.data.local.LyricsGlow import io.github.aedev.flow.data.local.PlayerPreferences @@ -34,6 +45,7 @@ import io.github.aedev.flow.data.lyrics.LyricsEntry import io.github.aedev.flow.data.lyrics.LyricsUtils import io.github.aedev.flow.player.EnhancedMusicPlayerManager import kotlinx.coroutines.delay +import kotlin.math.roundToInt /** Alpha of the words not sung yet, against the sung colour. */ internal const val SYNCED_LINE_UNSUNG_ALPHA = 0.45f @@ -157,7 +169,10 @@ internal fun SyncedLyricLine( glow = animation.glow, ) } - if (singleLine) { + val repeat = remember(lines, shownIndex) { lyricRepeatCount(lines, shownIndex) } + if (repeat > 1) { + RepeatedLine(line.text, stringResource(R.string.lyrics_repeat_count, repeat), style, unsungColor, singleLine, karaoke) + } else if (singleLine) { BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { val measurer = rememberTextMeasurer() val widthPx = constraints.maxWidth @@ -170,6 +185,63 @@ internal fun SyncedLyricLine( } } +/** + * A line that repeats the one before it, with [count] after its last word. The line is laid out + * narrower by the count's width, so a long line wraps or is cut before it and the count always shows. + */ +@Composable +private fun RepeatedLine( + text: String, + count: String, + style: TextStyle, + countColor: Color, + singleLine: Boolean, + karaoke: @Composable (String) -> Unit, +) { + BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { + val measurer = rememberTextMeasurer() + val widthPx = constraints.maxWidth + val countLayout = remember(count, style) { measurer.measure(count, style, maxLines = 1, softWrap = false) } + val gapPx = remember(style) { measurer.measure(" ", style).size.width } + val room = (widthPx - countLayout.size.width - gapPx).coerceAtLeast(0) + val shown = remember(text, room, style, singleLine) { if (singleLine) fitOneRow(measurer, text, style, room) else text } + // Measured as KaraokeLine measures it, so the last row here is the last row it draws. + val lineLayout = + remember(shown, room, style) { measurer.measure(shown, style, constraints = Constraints(minWidth = room, maxWidth = room)) } + val rtlLayout = LocalLayoutDirection.current == LayoutDirection.Rtl + Box(modifier = Modifier.fillMaxWidth()) { + // Exactly [room] pixels: a dp round trip could wrap the line differently from [lineLayout]. + Box( + modifier = + Modifier.layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = room, maxWidth = room)) + layout(placeable.width, placeable.height) { placeable.place(0, 0) } + }, + ) { karaoke(shown) } + Text( + text = count, + style = style, + color = countColor, + maxLines = 1, + softWrap = false, + modifier = + Modifier.align(AbsoluteAlignment.TopLeft).absoluteOffset { + val last = lineLayout.lineCount - 1 + val lineStart = if (rtlLayout) widthPx - room else 0 + val x = + if (lineLayout.getParagraphDirection(lineLayout.getLineStart(last)) == ResolvedTextDirection.Rtl) { + lineStart + lineLayout.getLineLeft(last).toInt() - gapPx - countLayout.size.width + } else { + lineStart + lineLayout.getLineRight(last).roundToInt() + gapPx + } + val y = lineLayout.getLineBaseline(last) - countLayout.firstBaseline + IntOffset(x.coerceIn(0, (widthPx - countLayout.size.width).coerceAtLeast(0)), y.roundToInt()) + }, + ) + } + } +} + /** * [text] cut after the last whole word that fits one row with an ellipsis. The words past the cut * no longer match the text, so [KaraokeLine] leaves them out and fills the ellipsis after the last diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/sheet/UnifiedMusicPlayerSheet.kt b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/sheet/UnifiedMusicPlayerSheet.kt index b9cef3c51c..e8021b8545 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/sheet/UnifiedMusicPlayerSheet.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/musicplayer/sheet/UnifiedMusicPlayerSheet.kt @@ -476,6 +476,7 @@ internal fun UnifiedMusicPlayerSheet( hideArtwork = appearance.hideArtwork, sleepTimerButton = appearance.sleepTimerButton, splitTransport = appearance.splitTransport, + lyricsOnCover = appearance.lyricsOnCover, controlScheme = controlScheme, onLyricsShownChange = { state.isLyricsShown = it }, panelRequest = state.panelRequest, diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/shared/DownloadLauncher.kt b/app/src/main/java/io/github/aedev/flow/ui/components/shared/DownloadLauncher.kt index b17e7eacf6..9de32cad00 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/shared/DownloadLauncher.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/shared/DownloadLauncher.kt @@ -1,16 +1,10 @@ package io.github.aedev.flow.ui.components.shared -import android.app.Activity import android.content.Context -import android.content.Intent -import android.os.Build import android.os.Environment import android.os.StatFs -import android.provider.Settings import android.widget.Toast import androidx.core.content.ContextCompat -import androidx.core.content.edit -import androidx.core.net.toUri import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors @@ -37,36 +31,8 @@ internal data class DownloadSaveFolder( val freeBytes: Long, ) -/** Starts the downloads both download dialogs offer, asking for storage access once on the way. */ +/** Starts the downloads both download dialogs offer. */ internal object DownloadLauncher { - private const val STORAGE_PREFS = "flow_storage_prefs" - private const val STORAGE_PERMISSION_ASKED = "storage_permission_asked" - - /** - * Asks once for MANAGE_EXTERNAL_STORAGE on Android 11+. Optional: downloads still work without - * it because VideoDownloadManager falls back to app-private storage. - */ - fun promptStoragePermissionIfNeeded(context: Context) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Environment.isExternalStorageManager()) return - val prefs = context.getSharedPreferences(STORAGE_PREFS, Context.MODE_PRIVATE) - if (prefs.getBoolean(STORAGE_PERMISSION_ASKED, false)) return - prefs.edit { putBoolean(STORAGE_PERMISSION_ASKED, true) } - Toast.makeText(context, context.getString(R.string.download_storage_access_prompt), Toast.LENGTH_LONG).show() - if (context !is Activity) return - try { - context.startActivity( - Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { - data = "package:${context.packageName}".toUri() - }, - ) - } catch (_: Exception) { - try { - context.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) - } catch (_: Exception) { - } - } - } - /** * Queues the video stream and AAC audio the dialog picked. The queue re-extracts when a slot is * free and keeps these itags when they are still offered, so the choice survives a long wait. @@ -79,7 +45,6 @@ internal object DownloadLauncher { threads: Int? = null, subtitle: DownloadSubtitle? = null, ) { - promptStoragePermissionIfNeeded(context) submit( context, video.toDownloadRequest( @@ -104,7 +69,6 @@ internal object DownloadLauncher { startedMessage: String, threads: Int? = null, ): Boolean { - promptStoragePermissionIfNeeded(context) submit( context, video.toDownloadRequest( @@ -127,7 +91,6 @@ internal object DownloadLauncher { context: Context, video: Video, ) { - promptStoragePermissionIfNeeded(context) submit(context, video.toDownloadRequest(targetHeight = 0), context.getString(R.string.ui_started_download, video.title)) } diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsScreen.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsScreen.kt index a9b41fee9d..b3d79cafc5 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsScreen.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsScreen.kt @@ -18,6 +18,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Checklist import androidx.compose.material.icons.filled.SelectAll import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.FolderOpen import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -46,6 +47,7 @@ import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp +import androidx.core.net.toUri import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -93,6 +95,10 @@ fun DownloadsScreen( val snackbarHostState = shellSnackbar ?: remember { SnackbarHostState() } var access by remember { mutableStateOf(StorageAccess.read(context)) } var recoveryDismissed by rememberSaveable { mutableStateOf(false) } + val lostFolder by viewModel.lostFolder.collectAsStateWithLifecycle() + var lostFolderDismissed by rememberSaveable { mutableStateOf(false) } + val folderPicker = + rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { picked -> picked?.let(viewModel::relinkFolder) } LifecycleResumeEffect(Unit) { access = StorageAccess.read(context) viewModel.scanIfMoreIsReadable() @@ -236,7 +242,18 @@ fun DownloadsScreen( uiState.totalMusicCount == 0 && uiState.incompleteVideoDownloads.isEmpty() && uiState.incompleteMusicDownloads.isEmpty() - if (hasNothing && !access.seesAllDownloads && !recoveryDismissed) { + val lost = lostFolder + if (lost != null && !lostFolderDismissed) { + DownloadsRecoveryCard( + onAllow = { folderPicker.launch(lost.toUri()) }, + onDismiss = { lostFolderDismissed = true }, + icon = Icons.Outlined.FolderOpen, + title = stringResource(R.string.downloads_folder_lost_title), + body = stringResource(R.string.downloads_folder_lost_body), + allowLabel = stringResource(R.string.downloads_folder_lost_choose), + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } else if (hasNothing && !access.seesAllDownloads && !recoveryDismissed) { DownloadsRecoveryCard( onAllow = { accessRequest.launch(downloadReadPermissions()) }, onDismiss = { recoveryDismissed = true }, diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsViewModel.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsViewModel.kt index 875cbea080..2e247a93b3 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsViewModel.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/library/DownloadsViewModel.kt @@ -1,7 +1,9 @@ package io.github.aedev.flow.ui.screens.library import android.content.Context +import android.content.Intent import android.content.IntentSender +import android.net.Uri import android.os.StatFs import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -19,7 +21,11 @@ import io.github.aedev.flow.data.video.DownloadedVideo import io.github.aedev.flow.data.video.VideoDownloadManager import io.github.aedev.flow.data.video.downloader.collection.DownloadedCollections import io.github.aedev.flow.data.video.downloader.work.DownloadController +import io.github.aedev.flow.data.video.storage.DownloadFiles +import io.github.aedev.flow.data.video.storage.DownloadLocation +import io.github.aedev.flow.data.video.storage.StorageAccess import io.github.aedev.flow.data.video.storage.deleteRequestFor +import io.github.aedev.flow.data.video.storage.lostDownloadTree import io.github.aedev.flow.di.ApplicationScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -33,6 +39,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.mapNotNull @@ -54,7 +61,7 @@ class DownloadsViewModel private val musicDownloadManager: MusicDownloadManager, private val downloadController: DownloadController, private val collections: DownloadedCollections, - preferences: PlayerPreferences, + private val preferences: PlayerPreferences, @param:ApplicationScope private val applicationScope: CoroutineScope, ) : ViewModel() { private val _uiState = MutableStateFlow(DownloadsUiState()) @@ -84,6 +91,9 @@ class DownloadsViewModel // the free space is measured again, not only when the database changes. private val refreshTick = MutableStateFlow(0) + // Bumped on return to the screen, since a folder grant can change outside the app. + private val accessTick = MutableStateFlow(0) + init { observeDownloads() downloadController.ensureQueueRunning() @@ -284,9 +294,43 @@ class DownloadsViewModel /** On open and on return to the screen: the viewer may have granted access in system settings. */ fun scanIfMoreIsReadable() { + accessTick.update { it + 1 } if (recoveryScanner.needsScan()) scan(reportNone = false) } + /** A picked download folder Flow can no longer open, to be picked again; null when there is none. */ + val lostFolder: StateFlow = + combine( + preferences.downloadLocation, + preferences.musicDownloadLocation, + accessTick, + ) { video, music, _ -> lostTree(video, music) } + .flowOn(Dispatchers.IO) + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) + + private fun lostTree( + video: DownloadLocation, + music: DownloadLocation, + ): String? = lostDownloadTree(listOf(video, music), DownloadFiles.grantedTrees(context), StorageAccess.read(context).allFiles) + + /** Saves [picked] wherever the lost folder was the location, then looks through it for earlier downloads. */ + fun relinkFolder(picked: Uri) { + viewModelScope.launch { + val video = preferences.downloadLocation.first() + val music = preferences.musicDownloadLocation.first() + val lost = withContext(Dispatchers.IO) { lostTree(video, music) } ?: return@launch + withContext(Dispatchers.IO) { + runCatching { context.contentResolver.takePersistableUriPermission(picked, TREE_GRANT) } + } + val tree = picked.toString() + val location = DownloadLocation(path = DownloadFiles.treePath(tree), treeUri = tree) + if (video.treeUri == lost) preferences.setDownloadLocation(location) + if (music.treeUri == lost) preferences.setMusicDownloadLocation(location) + accessTick.update { it + 1 } + scan(reportNone = true) + } + } + private fun scan(reportNone: Boolean) { viewModelScope.launch { _uiState.update { it.copy(isScanning = true) } @@ -321,3 +365,5 @@ data class DownloadsUiState( val sort: DownloadSort = DownloadSort.NEWEST, val isScanning: Boolean = false, ) + +private const val TREE_GRANT = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceScreen.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceScreen.kt index 7854fa4544..4756d774a9 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceScreen.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceScreen.kt @@ -198,6 +198,9 @@ internal fun PlayerAppearanceScreen( if (musicBackground.canTurnLight) { switch(PlayerAppearanceIndex.followLightTheme, followLightTheme, viewModel::setFollowLightTheme) } + if (musicBackground == MusicPlayerBackgroundStyle.IMMERSIVE) { + switch(PlayerAppearanceIndex.lyricsOnCover, viewModel.lyricsOnCover, viewModel::setLyricsOnCover) + } switch(PlayerAppearanceIndex.hideMusicArtwork, hideMusicArtwork, viewModel::setHideMusicArtwork) switch(PlayerAppearanceIndex.animatedArtwork, animatedArtwork, viewModel::setAnimatedArtwork) if (animatedArtwork) { diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceViewModel.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceViewModel.kt index 58bad0ea74..2efcc62e05 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceViewModel.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/appearance/player/PlayerAppearanceViewModel.kt @@ -52,6 +52,7 @@ class PlayerAppearanceViewModel val musicBackground = preferences.musicPlayerBackgroundStyle.asState(MusicPlayerBackgroundStyle.BLUR_GRADIENT) val hideMusicArtwork = preferences.hideMusicPlayerArtwork.asState(false) val followLightTheme = preferences.musicPlayerFollowLightTheme.asState(false) + val lyricsOnCover = preferences.immersiveLyricsOnCover.asState(false) val artworkControlColors = preferences.musicArtworkControlColors.asState(true) val animatedArtwork = preferences.animatedArtwork.asState(false) val animatedArtworkWifiOnly = preferences.animatedArtworkWifiOnly.asState(true) @@ -117,6 +118,8 @@ class PlayerAppearanceViewModel fun setFollowLightTheme(value: Boolean) = write { preferences.setMusicPlayerFollowLightTheme(value) } + fun setLyricsOnCover(value: Boolean) = write { preferences.setImmersiveLyricsOnCover(value) } + fun setArtworkControlColors(value: Boolean) = write { preferences.setMusicArtworkControlColors(value) } fun setAnimatedArtwork(value: Boolean) = write { preferences.setAnimatedArtwork(value) } diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlayerAppearanceIndex.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlayerAppearanceIndex.kt index e7e938ba37..f13db0c0e7 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlayerAppearanceIndex.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlayerAppearanceIndex.kt @@ -77,6 +77,14 @@ internal object PlayerAppearanceIndex { R.string.settings_section_music_player, revealVia = musicBackground.key, ) + val lyricsOnCover = + entry( + "music_lyrics_on_cover", + R.string.player_appearance_lyrics_on_cover_title, + R.string.player_appearance_lyrics_on_cover_subtitle, + R.string.settings_section_music_player, + revealVia = musicBackground.key, + ) val hideMusicArtwork = entry( "hide_music_artwork", @@ -338,6 +346,7 @@ internal object PlayerAppearanceIndex { frameStep, musicBackground, followLightTheme, + lyricsOnCover, hideMusicArtwork, animatedArtwork, animatedArtworkWifiOnly, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2ed21f42cd..4d147f8e8e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -139,6 +139,8 @@ Lyrics Full screen lyrics Play from this line + + ×%1$d Translation Show a translation when the lyrics include one These lyrics have no translation @@ -177,6 +179,8 @@ Lock screen lyrics timing Move lines earlier if they feel late Lyrics in mini player + Lyrics on the cover + The lyrics button shows lyrics in the player instead of a sheet Show the line being sung in place of the artist Fit lyrics to music videos Uses SponsorBlock to skip parts with no music @@ -661,6 +665,9 @@ Flow saves downloads in Download/Flow and Music/Flow. To list the files an earlier install saved there, allow access to videos and audio. Allow access Not now + Choose your download folder again + Flow lost access to the folder you picked for downloads, as happens after a reinstall. Choose it again to find your earlier downloads and keep saving there. + Choose folder Found %d download from an earlier install Found %d downloads from an earlier install @@ -2866,7 +2873,6 @@ All languages Downloading %1$s... HDR - Grant storage access to save downloads in public folders (optional) Downloading Incomplete downloads Completed diff --git a/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt b/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt index 2c7e3ddd1b..62dd05e8ce 100644 --- a/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt +++ b/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt @@ -25,7 +25,7 @@ class DevicePreferencesSplitTest { val device = keyNames("DeviceKeys") assertThat(device).hasSize(128) - assertThat(profile).hasSize(273) + assertThat(profile).hasSize(274) assertThat(device.toSet()).hasSize(device.size) assertThat(profile.toSet()).hasSize(profile.size) assertThat(device.intersect(profile.toSet())).isEmpty() diff --git a/app/src/test/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalkTest.kt b/app/src/test/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalkTest.kt new file mode 100644 index 0000000000..d3618d0385 --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/data/video/storage/DocumentTreeWalkTest.kt @@ -0,0 +1,60 @@ +package io.github.aedev.flow.data.video.storage + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DocumentTreeWalkTest { + private fun file(name: String) = TreeDocument(id = name, name = name, isFolder = false) + + private fun folder(name: String) = TreeDocument(id = name, name = name, isFolder = true) + + private val tree = + mapOf( + "root" to listOf(file("a.mp4"), folder("Album"), file(".trashed-1-b.mp4"), folder(".hidden")), + "Album" to listOf(file("01.m4a"), folder("Nested")), + "Nested" to listOf(file("deep.mp4")), + ".hidden" to listOf(file("secret.mp4")), + ) + + private fun walk( + maxDepth: Int = 2, + limit: Int = 100, + listed: MutableList = mutableListOf(), + ) = filesInTree("root", maxDepth, limit) { id -> + listed += id + tree[id].orEmpty() + }.map { it.name } + + @Test + fun `finds files in the folder and in the folders directly inside it`() { + assertEquals(listOf("a.mp4", "01.m4a"), walk()) + } + + @Test + fun `a deeper limit reaches nested folders`() { + assertEquals(listOf("a.mp4", "01.m4a", "deep.mp4"), walk(maxDepth = 3)) + } + + @Test + fun `depth one lists only the folder itself`() { + val listed = mutableListOf() + assertEquals(listOf("a.mp4"), walk(maxDepth = 1, listed = listed)) + assertEquals(listOf("root"), listed) + } + + @Test + fun `hidden files and folders are skipped and never opened`() { + val listed = mutableListOf() + val found = walk(maxDepth = 3, listed = listed) + assertTrue(found.none { it.startsWith(".") || it == "secret.mp4" }) + assertTrue(".hidden" !in listed) + } + + @Test + fun `the walk stops after the document limit`() { + val listed = mutableListOf() + assertEquals(listOf("a.mp4"), walk(maxDepth = 3, limit = 2, listed = listed)) + assertEquals(listOf("root"), listed) + } +} diff --git a/app/src/test/java/io/github/aedev/flow/data/video/storage/DownloadLocationTest.kt b/app/src/test/java/io/github/aedev/flow/data/video/storage/DownloadLocationTest.kt index 14928ae9c4..a01d6b6421 100644 --- a/app/src/test/java/io/github/aedev/flow/data/video/storage/DownloadLocationTest.kt +++ b/app/src/test/java/io/github/aedev/flow/data/video/storage/DownloadLocationTest.kt @@ -113,4 +113,45 @@ class DownloadLocationTest { assertNull(documentIdToPath("msf:1234", root)) assertNull(documentIdToPath("1234", root)) } + + @Test + fun `a picked folder without its grant is lost`() { + val tree = "content://com.android.externalstorage.documents/tree/primary%3ADownload%2FFlow" + val lost = lostDownloadTree(listOf(DownloadLocation(treeUri = tree)), grantedTrees = emptySet(), hasAllFilesAccess = false) + assertEquals(tree, lost) + } + + @Test + fun `a picked folder still granted is not lost`() { + val tree = "content://provider/tree/a" + assertNull(lostDownloadTree(listOf(DownloadLocation(treeUri = tree)), grantedTrees = setOf(tree), hasAllFilesAccess = false)) + } + + @Test + fun `default and typed locations are never lost`() { + val locations = listOf(DownloadLocation.DEFAULT, DownloadLocation(path = "/storage/emulated/0/Movies/Flow")) + assertNull(lostDownloadTree(locations, grantedTrees = emptySet(), hasAllFilesAccess = false)) + } + + @Test + fun `all files access reaches a picked folder through its path`() { + val withPath = DownloadLocation(path = "/storage/emulated/0/Download/Flow", treeUri = "content://provider/tree/a") + assertNull(lostDownloadTree(listOf(withPath), grantedTrees = emptySet(), hasAllFilesAccess = true)) + val withoutPath = DownloadLocation(treeUri = "content://provider/tree/b") + assertEquals( + "content://provider/tree/b", + lostDownloadTree(listOf(withoutPath), grantedTrees = emptySet(), hasAllFilesAccess = true), + ) + } + + @Test + fun `the video folder is offered before the music folder`() { + val video = DownloadLocation(treeUri = "content://provider/tree/video") + val music = DownloadLocation(treeUri = "content://provider/tree/music") + assertEquals(video.treeUri, lostDownloadTree(listOf(video, music), grantedTrees = emptySet(), hasAllFilesAccess = false)) + assertEquals( + music.treeUri, + lostDownloadTree(listOf(video, music), grantedTrees = setOf(video.treeUri!!), hasAllFilesAccess = false), + ) + } } 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 0b62968fd5..32e8bc2b68 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 @@ -1,5 +1,6 @@ package io.github.aedev.flow.player.crossfade +import androidx.media3.common.C import com.google.common.truth.Truth.assertThat import io.github.aedev.flow.data.local.CrossfadeCurve import org.junit.Test @@ -383,4 +384,23 @@ class CrossfadePolicyTest { val waited = 700L assertThat(CrossfadePolicy.learnedHeadStartMs(headStartMs = 400L, deltaMs = 400L - waited)).isEqualTo(550L) } + + @Test + fun `a skipped-to song that comes late fades in quickly, never slower than the skip's own overlap`() { + assertThat(CrossfadePolicy.lateFadeInClockMs(6_000L)).isEqualTo(CrossfadePolicy.QUICK_FADE_IN_MS) + assertThat(CrossfadePolicy.lateFadeInClockMs(CrossfadePolicy.SKIP_BLEND_MS)).isEqualTo(CrossfadePolicy.SKIP_BLEND_MS) + assertThat(CrossfadePolicy.lateFadeInClockMs(0L)).isEqualTo(1L) + } + + @Test + fun `a song with no length in its metadata takes the player's, so a skip still fades it`() { + assertThat(CrossfadePolicy.knownDurationMs(metadataMs = 200_000L, playerMs = 180_000L)).isEqualTo(200_000L) + assertThat(CrossfadePolicy.knownDurationMs(metadataMs = null, playerMs = 180_000L)).isEqualTo(180_000L) + assertThat(CrossfadePolicy.knownDurationMs(metadataMs = null, playerMs = C.TIME_UNSET)).isNull() + assertThat(CrossfadePolicy.knownDurationMs(metadataMs = null, playerMs = 0L)).isNull() + + val fromPlayer = CrossfadePolicy.knownDurationMs(metadataMs = null, playerMs = 180_000L) + assertThat(CrossfadePolicy.skipResumeMs(30_000L, 400L, fromPlayer, failed = false)).isEqualTo(30_400L) + assertThat(CrossfadePolicy.skipResumeMs(30_000L, 400L, null, failed = false)).isNull() + } } diff --git a/app/src/test/java/io/github/aedev/flow/sync/CollectionHashTest.kt b/app/src/test/java/io/github/aedev/flow/sync/CollectionHashTest.kt new file mode 100644 index 0000000000..3f470537cd --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/sync/CollectionHashTest.kt @@ -0,0 +1,46 @@ +package io.github.aedev.flow.sync + +import io.github.aedev.flow.sync.protocol.CollectionWire +import io.github.aedev.flow.sync.protocol.SyncSerialization +import org.junit.Assert.assertEquals +import org.junit.Test + +class CollectionHashTest { + private fun joined(lines: List) = SyncSerialization.sha256Hex(lines.joinToString("\n")) + + @Test + fun matches_the_joined_hash() { + val lines = listOf("""{"videoId":"a"}""", """{"videoId":"b"}""", "", """{"videoId":"c"}""") + assertEquals(joined(lines), SyncSerialization.collectionHash(lines)) + } + + @Test + fun matches_the_joined_hash_for_no_lines_and_one_line() { + assertEquals(joined(emptyList()), SyncSerialization.collectionHash(emptyList())) + assertEquals(SyncSerialization.sha256Hex(""), SyncSerialization.collectionHash(emptyList())) + assertEquals(SyncSerialization.sha256Hex("x"), SyncSerialization.collectionHash(listOf("x"))) + } + + @Test + fun matches_the_joined_hash_for_non_latin_text() { + val lines = listOf("""{"title":"तुम ही हो"}""", """{"title":"日本語のタイトル"}""", """{"title":"🎵 ñandú"}""") + assertEquals(joined(lines), SyncSerialization.collectionHash(lines)) + } + + @Test + fun golden_playlist_hash_is_unchanged() { + val line = + """{"createdAtMs":1781000000000,"deleted":false,"description":"","isMusic":false,"isProtected":false,"isUserCreated":true,"items":[{"addedAtMs":1,"channelId":"uc","channelName":"c","deleted":false,"durationSeconds":212,"hlc":"100:0:aaa","isMusic":false,"position":0,"thumbnailUrl":"","title":"A","videoId":"v1"}],"origin":"local","syncId":"p1","title":"Gym","updatedHlc":"100:0:aaa","youtubeId":null}""" + assertEquals( + "a0534d548eb59e88a7125e803f5d743e55d626bbca45a8622c57d44086e1b528", + SyncSerialization.collectionHash(listOf(line)), + ) + } + + @Test + fun wire_hash_is_worked_out_from_its_lines_unless_given() { + val lines = (0 until 5_000).map { """{"title":"t","videoId":"v$it"}""" } + assertEquals(joined(lines), CollectionWire(lines, lines.size).hash) + assertEquals("given", CollectionWire(lines, lines.size, "given").hash) + } +} diff --git a/app/src/test/java/io/github/aedev/flow/sync2/BatchContentTest.kt b/app/src/test/java/io/github/aedev/flow/sync2/BatchContentTest.kt new file mode 100644 index 0000000000..2f4c09a290 --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/sync2/BatchContentTest.kt @@ -0,0 +1,49 @@ +package io.github.aedev.flow.sync2 + +import io.github.aedev.flow.sync.protocol.SyncSerialization +import io.github.aedev.flow.sync2.changes.batchContent +import io.github.aedev.flow.sync2.crypto.encodePayload +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import org.junit.Assert.assertArrayEquals +import org.junit.Test + +class BatchContentTest { + private fun joined( + collection: String, + head: String, + link: String?, + lines: List, + ): ByteArray { + val header = + SyncSerialization.canonicalJson( + buildJsonObject { + put("collection", JsonPrimitive(collection)) + put("head", JsonPrimitive(head)) + put("link", JsonPrimitive(link)) + }, + ) + return (listOf(header) + lines).joinToString("\n").toByteArray() + } + + @Test + fun same_bytes_as_joining_the_lines() { + val lines = listOf("""{"videoId":"a"}""", """{"title":"日本語 🎵","videoId":"b"}""") + assertArrayEquals(joined("watch_history", "h1", "L1", lines), batchContent("watch_history", "h1", "L1", lines)) + assertArrayEquals(joined("profiles", "h1", null, lines), batchContent("profiles", "h1", null, lines)) + } + + @Test + fun same_bytes_with_no_records() { + assertArrayEquals(joined("likes", "h", "L", emptyList()), batchContent("likes", "h", "L", emptyList())) + } + + @Test + fun same_payload_after_compression() { + val lines = (0 until 2_000).map { """{"title":"t$it","videoId":"v$it"}""" } + assertArrayEquals( + encodePayload(joined("watch_history", "h", "L", lines)), + encodePayload(batchContent("watch_history", "h", "L", lines)), + ) + } +} diff --git a/app/src/test/java/io/github/aedev/flow/sync2/ChangeBatchesTest.kt b/app/src/test/java/io/github/aedev/flow/sync2/ChangeBatchesTest.kt index 26180a91b7..79731a8ef3 100644 --- a/app/src/test/java/io/github/aedev/flow/sync2/ChangeBatchesTest.kt +++ b/app/src/test/java/io/github/aedev/flow/sync2/ChangeBatchesTest.kt @@ -3,6 +3,7 @@ package io.github.aedev.flow.sync2 import io.github.aedev.flow.sync.apply.ReceivedCollection import io.github.aedev.flow.sync.protocol.CollectionWire import io.github.aedev.flow.sync.protocol.SyncCollection +import io.github.aedev.flow.sync.protocol.SyncSerialization import io.github.aedev.flow.sync2.changes.Batch import io.github.aedev.flow.sync2.changes.applyBatches import io.github.aedev.flow.sync2.changes.markSent @@ -132,6 +133,27 @@ class ChangeBatchesTest { assertEquals(0, sentLines(sent, history(*(1..1200).map { "v$it" to "t" }.toTypedArray())).size) } + @Test + fun applying_exports_only_the_received_collections_once_before_and_once_after_the_merge() = + runTest { + val remote = outgoingBatches(MemorySent(), history("a" to "one"), head, "link-a", 0) + val exports = ArrayList>() + var received: ReceivedCollection? = null + applyBatches( + MemorySent(), + "link-a", + remote.batches.map { parseBatch(it.content) }, + 0, + { + exports += it + history("a" to "one") + }, + ) { received = it.getValue(SyncCollection.WATCH_HISTORY) } + assertEquals(listOf(listOf(SyncCollection.WATCH_HISTORY), listOf(SyncCollection.WATCH_HISTORY)), exports) + val lines = checkNotNull(received).lines + assertEquals(SyncSerialization.sha256Hex(lines.joinToString("\n")), checkNotNull(received).hash) + } + /** One device's watch history, exported in its own canonical form: Desktop orders the fields differently. */ private inner class Device( val titleFirst: Boolean, diff --git a/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometryTest.kt b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometryTest.kt new file mode 100644 index 0000000000..c2ff9fe21f --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/controls/WavyTrackGeometryTest.kt @@ -0,0 +1,66 @@ +package io.github.aedev.flow.ui.components.musicplayer.controls + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class WavyTrackGeometryTest { + private val width = 1000f + private val stroke = 15f + private val thumb = 15f + private val gap = 0f + private val wavelength = 96f + + private fun waveEnd(fraction: Float) = WavyTrackGeometry.waveEnd(width, fraction, thumb, gap, stroke) + + private fun capEnd(fraction: Float) = waveEnd(fraction) + stroke / 2f + + private fun thumbLeadingEdge(fraction: Float) = WavyTrackGeometry.thumbCentre(width, fraction) - thumb / 2f + + @Test + fun `the thumb centre is the fraction of the full track width`() { + assertThat(WavyTrackGeometry.thumbCentre(width, 0f)).isEqualTo(0f) + assertThat(WavyTrackGeometry.thumbCentre(width, 0.5f)).isEqualTo(500f) + assertThat(WavyTrackGeometry.thumbCentre(width, 1f)).isEqualTo(1000f) + assertThat(WavyTrackGeometry.thumbCentre(width, 1.5f)).isEqualTo(1000f) + } + + @Test + fun `no wave at the very start`() { + assertThat(waveEnd(0f)).isEqualTo(WavyTrackGeometry.waveStart(stroke)) + assertThat(waveEnd(0.001f)).isEqualTo(WavyTrackGeometry.waveStart(stroke)) + } + + @Test + fun `the wave's cap never passes the thumb's leading edge`() { + for (step in 0..1000) { + val fraction = step / 1000f + if (waveEnd(fraction) > WavyTrackGeometry.waveStart(stroke)) { + assertThat(capEnd(fraction)).isAtMost(thumbLeadingEdge(fraction)) + } + } + } + + @Test + fun `the wave stops the gap short of the thumb in the middle and at the end`() { + val withGap = { fraction: Float -> WavyTrackGeometry.waveEnd(width, fraction, thumb, 12f, stroke) + stroke / 2f } + assertThat(withGap(0.5f)).isEqualTo(500f - thumb / 2f - 12f) + assertThat(withGap(1f)).isEqualTo(1000f - thumb / 2f - 12f) + assertThat(capEnd(0.5f)).isEqualTo(thumbLeadingEdge(0.5f)) + } + + @Test + fun `the rest of the track starts past the thumb's trailing edge`() { + val restCapStart = WavyTrackGeometry.restStart(width, 0.5f, thumb, gap, stroke) - stroke / 2f + assertThat(restCapStart).isEqualTo(500f + thumb / 2f) + assertThat(WavyTrackGeometry.restStart(width, 1f, thumb, gap, stroke)).isGreaterThan(WavyTrackGeometry.trackEnd(width, stroke)) + } + + @Test + fun `the wave grows in over its first wavelength`() { + assertThat(WavyTrackGeometry.heightFactor(0f, wavelength)).isEqualTo(0f) + assertThat(WavyTrackGeometry.heightFactor(wavelength / 2f, wavelength)).isEqualTo(0.5f) + assertThat(WavyTrackGeometry.heightFactor(wavelength, wavelength)).isEqualTo(1f) + assertThat(WavyTrackGeometry.heightFactor(wavelength * 10f, wavelength)).isEqualTo(1f) + assertThat(WavyTrackGeometry.heightFactor(-5f, wavelength)).isEqualTo(0f) + } +} diff --git a/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicyTest.kt b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicyTest.kt new file mode 100644 index 0000000000..f0a177bd4a --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/full/ImmersiveLyricsPolicyTest.kt @@ -0,0 +1,37 @@ +package io.github.aedev.flow.ui.components.musicplayer.full + +import io.github.aedev.flow.data.local.MusicPlayerBackgroundStyle +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ImmersiveLyricsPolicyTest { + @Test + fun `with the switch on, only the immersive background in the phone column shows lyrics in place`() { + MusicPlayerBackgroundStyle.entries.forEach { style -> + MusicPlayerLayout.entries.forEach { layout -> + val expected = style == MusicPlayerBackgroundStyle.IMMERSIVE && layout == MusicPlayerLayout.COMPACT + assertEquals("$style $layout", expected, lyricsShowInPlace(true, style, layout)) + } + } + } + + @Test + fun `with the switch off, the lyrics button always opens the sheet`() { + MusicPlayerBackgroundStyle.entries.forEach { style -> + MusicPlayerLayout.entries.forEach { layout -> + assertFalse("$style $layout", lyricsShowInPlace(false, style, layout)) + } + } + } + + @Test + fun `lyrics in place run only while visible`() { + assertTrue(inPlaceLyricsActive(expanded = true, inPlace = true, sheetOpen = false, queueCovers = false)) + assertFalse(inPlaceLyricsActive(expanded = false, inPlace = true, sheetOpen = false, queueCovers = false)) + assertFalse(inPlaceLyricsActive(expanded = true, inPlace = false, sheetOpen = false, queueCovers = false)) + assertFalse(inPlaceLyricsActive(expanded = true, inPlace = true, sheetOpen = true, queueCovers = false)) + assertFalse(inPlaceLyricsActive(expanded = true, inPlace = true, sheetOpen = false, queueCovers = true)) + } +} diff --git a/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeatsTest.kt b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeatsTest.kt new file mode 100644 index 0000000000..c47ccf2267 --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/ui/components/musicplayer/lyrics/LyricsRepeatsTest.kt @@ -0,0 +1,54 @@ +package io.github.aedev.flow.ui.components.musicplayer.lyrics + +import com.google.common.truth.Truth.assertThat +import io.github.aedev.flow.data.lyrics.LyricsEntry +import org.junit.Test + +class LyricsRepeatsTest { + private fun lines(vararg texts: String) = texts.mapIndexed { i, text -> LyricsEntry(time = i * 1_000L, text = text) } + + @Test + fun `four repeats count up`() { + val song = lines("So, oh, oh-oh-oh", "So, oh, oh-oh-oh", "So, oh, oh-oh-oh", "So, oh, oh-oh-oh") + assertThat((0..3).map { lyricRepeatCount(song, it) }).containsExactly(1, 2, 3, 4).inOrder() + } + + @Test + fun `case punctuation and spacing don't break a run`() { + val song = lines("So, oh, oh-oh-oh", "so oh oh oh oh", "SO OH OH-OH-OH!") + assertThat(lyricRepeatCount(song, 2)).isEqualTo(3) + } + + @Test + fun `a blank break restarts the count`() { + val song = lines("Again", "Again", "", "Again") + assertThat(lyricRepeatCount(song, 1)).isEqualTo(2) + assertThat(lyricRepeatCount(song, 3)).isEqualTo(1) + } + + @Test + fun `a different line between restarts the count`() { + val song = lines("Again", "Something else", "Again") + assertThat(lyricRepeatCount(song, 2)).isEqualTo(1) + } + + @Test + fun `a vowel sign makes a different line`() { + val song = lines("कल", "काल") + assertThat(lyricRepeatCount(song, 1)).isEqualTo(1) + } + + @Test + fun `a line of only punctuation never counts`() { + val song = lines("...", "...") + assertThat(lyricRepeatCount(song, 1)).isEqualTo(1) + } + + @Test + fun `no line or a line out of range is one`() { + val song = lines("Again", "Again") + assertThat(lyricRepeatCount(song, -1)).isEqualTo(1) + assertThat(lyricRepeatCount(song, 2)).isEqualTo(1) + assertThat(lyricRepeatCount(emptyList(), 0)).isEqualTo(1) + } +} diff --git a/app/src/test/resources/profiles/store_inventory.tsv b/app/src/test/resources/profiles/store_inventory.tsv index c22bef3fd1..1421c0743c 100644 --- a/app/src/test/resources/profiles/store_inventory.tsv +++ b/app/src/test/resources/profiles/store_inventory.tsv @@ -35,7 +35,6 @@ shared_prefs youtube_identity main:utils/potoken/VisitorIdentityStore.kt PROFILE shared_prefs flow_prefs main:utils/potoken/VisitorIdentityStore.kt DEVICE - Only deletes the legacy visitor keys. shared_prefs flow_prefs main:utils/cipher/PipePipeNsigDecoder.kt DEVICE - Player-JS id cache with a 24 h lifetime. shared_prefs flow_language_prefs main:utils/AppLanguageManager.kt DEVICE - App language. -shared_prefs flow_storage_prefs main:ui/components/shared/DownloadLauncher.kt DEVICE - Storage permission prompt. shared_prefs flow_crash_prefs main:utils/FlowCrashHandler.kt DEVICE - Crash reports. shared_prefs music_home_cache_prefs main:data/recommendation/MusicRecommendationAlgorithm.kt CACHE - Freshness of the music home rows, which sit in each profile's database; suffixed per profile. shared_prefs flow_file_tombstones main:data/video/VideoDownloadManager.kt DEVICE - Deleted download paths.