diff --git a/README.md b/README.md index 2097495..914798c 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,10 @@ albums, artists, playlists, clips), album, artist, playlist, genre and podcast p Now Playing screen with the queue and synced lyrics. Tracks can be liked, disliked, queued next or last, added to playlists, and used to start similar tracks; your own playlists can be created, renamed, made public or private, reordered and deleted. Playback runs in a media -session, so it keeps going in the background and answers the remote's media keys. Streaming +session, so it keeps going in the background and answers the remote's media keys. While +music plays, the TV's own screen saver is replaced by one that drifts through the artist's +photos and the cover with the artist, song, album and year (after the system's screen saver +delay; paused for ten minutes or with nothing queued, the system's saver returns). Streaming quality goes up to FLAC (decrypted on the fly), and the interface is in English or Russian. Hold select on a track row or a clip for its menu; the heart and the "more" button sit to diff --git a/app/src/main/java/it/panov/musyx/tv/MainActivity.kt b/app/src/main/java/it/panov/musyx/tv/MainActivity.kt index 61dbf45..eb04bd1 100644 --- a/app/src/main/java/it/panov/musyx/tv/MainActivity.kt +++ b/app/src/main/java/it/panov/musyx/tv/MainActivity.kt @@ -1,10 +1,12 @@ package it.panov.musyx.tv +import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.res.Configuration import android.os.Bundle import android.view.KeyEvent +import android.view.MotionEvent import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.LaunchedEffect @@ -17,6 +19,7 @@ import it.panov.musyx.tv.data.SettingsStore import it.panov.musyx.tv.player.PlaybackService import it.panov.musyx.tv.player.Status import it.panov.musyx.tv.ui.MusyxApp +import it.panov.musyx.tv.ui.screens.ScreenSaverState import it.panov.musyx.tv.ui.theme.MusyxTheme import it.panov.musyx.tv.ui.theme.isMusyxDark import kotlinx.coroutines.flow.drop @@ -26,6 +29,11 @@ class MainActivity : ComponentActivity() { /** Binds the playback service so it can go foreground when playback starts. */ private var controller: ListenableFuture? = null + private val saver = ScreenSaverState() + + /** The key that woke the screen saver: its release is swallowed too. */ + private var wakingKey: Int? = null + /** The interface language follows the setting, not only the system. */ override fun attachBaseContext(newBase: Context) { val tag = SettingsStore(newBase).language().tag @@ -52,7 +60,7 @@ class MainActivity : ComponentActivity() { snapshotFlow { state.settings.language }.drop(1).collect { recreate() } } MusyxTheme(dark = dark, typeScale = state.settings.fontSize.scale) { - MusyxApp(state, onExit = { finish() }) + MusyxApp(state, saver, onExit = { finish() }) } } } @@ -69,6 +77,35 @@ class MainActivity : ComponentActivity() { super.onStop() } + /** + * Any key counts as activity for the screen saver. The key that wakes it does nothing else, + * except media and volume keys, which still act. + */ + // Lint mistakes this platform Activity override for androidx.core's restricted one. + @SuppressLint("RestrictedApi") + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.action == KeyEvent.ACTION_UP && event.keyCode == wakingKey) { + wakingKey = null + return true + } + val woke = saver.onInput() + if (woke && event.action == KeyEvent.ACTION_DOWN && event.keyCode !in PASS_THROUGH_KEYS) { + wakingKey = event.keyCode + return true + } + return super.dispatchKeyEvent(event) + } + + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + if (saver.onInput() && event.actionMasked == MotionEvent.ACTION_DOWN) return true + return super.dispatchTouchEvent(event) + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + saver.onInput() + return super.dispatchGenericMotionEvent(event) + } + /** Remote media keys while the app is in front go straight to the player. */ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { val playback = Musyx.graph(this).state.playback @@ -87,5 +124,19 @@ class MainActivity : ComponentActivity() { companion object { const val SEEK_STEP_MS = 10_000L + + private val PASS_THROUGH_KEYS = setOf( + KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, + KeyEvent.KEYCODE_HEADSETHOOK, + KeyEvent.KEYCODE_MEDIA_PLAY, + KeyEvent.KEYCODE_MEDIA_PAUSE, + KeyEvent.KEYCODE_MEDIA_NEXT, + KeyEvent.KEYCODE_MEDIA_PREVIOUS, + KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, + KeyEvent.KEYCODE_MEDIA_REWIND, + KeyEvent.KEYCODE_VOLUME_UP, + KeyEvent.KEYCODE_VOLUME_DOWN, + KeyEvent.KEYCODE_VOLUME_MUTE, + ) } } diff --git a/app/src/main/java/it/panov/musyx/tv/api/Models.kt b/app/src/main/java/it/panov/musyx/tv/api/Models.kt index f9ba355..796f133 100644 --- a/app/src/main/java/it/panov/musyx/tv/api/Models.kt +++ b/app/src/main/java/it/panov/musyx/tv/api/Models.kt @@ -20,9 +20,11 @@ fun coverUrl(uri: String?, size: Int): String? { fun joinNames(artists: List): String? = artists.takeIf { it.isNotEmpty() }?.joinToString(", ") { it.name } -data class ArtistRef(val id: Long?, val name: String) +data class ArtistRef(val id: Long?, val name: String, private val coverUri: String? = null) { + fun coverUrl(size: Int): String? = coverUrl(coverUri, size) +} -data class AlbumRef(val id: Long, val title: String) +data class AlbumRef(val id: Long, val title: String, val year: Int? = null) data class Track( /** Numeric track id as a string; user-uploaded tracks use non-numeric ids. */ @@ -56,7 +58,7 @@ data class Track( fun from(t: JsonElement?): Track? { val id = t.str("id") ?: return null val album = t.list("albums").firstNotNullOfOrNull { a -> - a.long("id")?.let { AlbumRef(it, a.str("title").orEmpty()) } + a.long("id")?.let { AlbumRef(it, a.str("title").orEmpty(), a.long("year")?.toInt()) } } val info = t["lyricsInfo"] return Track( @@ -86,7 +88,11 @@ data class Track( } internal fun artistRefs(list: List): List = - list.mapNotNull { a -> a.str("name")?.let { ArtistRef(a.long("id"), it) } } + list.mapNotNull { a -> a.str("name")?.let { ArtistRef(a.long("id"), it, a["cover"].str("uri") ?: a.str("ogImage")) } } + +/** An artist's photo uris from `brief-info`: the gallery, and the artist's main photo. */ +internal fun artistPhotoUris(b: JsonElement?): List = + (b.list("allCovers").mapNotNull { it.str("uri") } + listOfNotNull(b["artist"]["cover"].str("uri"))).distinct() enum class AlbumKind { Album, Single, Compilation, Podcast, Audiobook; diff --git a/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt b/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt index 4189f2b..f2c19c9 100644 --- a/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt +++ b/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt @@ -150,6 +150,10 @@ class YmClient private constructor( page.copy(clips = clips.await().getOrElse { emptyList() }) } + /** URLs of an artist's photos at `size`×`size`, for the screen saver. */ + suspend fun artistPhotos(id: Long, size: Int): List = + artistPhotoUris(http.get("/artists/$id/brief-info")).mapNotNull { coverUrl(it, size) } + /** A playlist with all its tracks. Tracks the response didn't embed are looked up. */ suspend fun playlist(id: PlaylistId): PlaylistPage { val raw = http.get("/users/${id.owner}/playlists/${id.kind}") diff --git a/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt b/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt index ee2d03f..e47af64 100644 --- a/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt +++ b/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt @@ -71,6 +71,8 @@ import it.panov.musyx.tv.ui.screens.MiniPlayer import it.panov.musyx.tv.ui.screens.NowPlayingScreen import it.panov.musyx.tv.ui.screens.PlaylistScreen import it.panov.musyx.tv.ui.screens.PodcastsScreen +import it.panov.musyx.tv.ui.screens.ScreenSaverHost +import it.panov.musyx.tv.ui.screens.ScreenSaverState import it.panov.musyx.tv.ui.screens.SearchScreen import it.panov.musyx.tv.ui.screens.SettingsScreen import it.panov.musyx.tv.ui.screens.SheetHost @@ -86,7 +88,7 @@ private const val DRAWER_ITEM_SCALE = 1.05f private const val DRAWER_DIM = 0.4f @Composable -fun MusyxApp(state: AppState, onExit: () -> Unit) { +fun MusyxApp(state: AppState, saver: ScreenSaverState, onExit: () -> Unit) { val c = MusyxTheme.colors Box(Modifier.fillMaxSize().background(c.bg)) { when (val s = state.session) { @@ -97,6 +99,7 @@ fun MusyxApp(state: AppState, onExit: () -> Unit) { is Session.SignedIn -> Shell(state, onExit) } ToastHost(state) + if (state.session is Session.SignedIn) ScreenSaverHost(state, saver) } } diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/ScreenSaver.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/ScreenSaver.kt new file mode 100644 index 0000000..1ecc214 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/ScreenSaver.kt @@ -0,0 +1,259 @@ +// The app's own screen saver. While music plays the screen stays on, so the system's saver +// never starts; after the system's screen saver delay without input, photos of the artist and +// the cover drift across the screen with what's playing. Paused for a while, or with nothing +// queued, the app lets go and the TV's own saver and sleep take over again. +package it.panov.musyx.tv.ui.screens + +import android.content.Context +import android.os.SystemClock +import android.provider.Settings +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.Crossfade +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +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.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.TransformOrigin +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.tv.material3.Text +import coil3.SingletonImageLoader +import coil3.compose.AsyncImage +import coil3.request.ImageRequest +import it.panov.musyx.tv.api.Track +import it.panov.musyx.tv.state.AppState +import it.panov.musyx.tv.player.Status +import it.panov.musyx.tv.ui.artistsOrUnknown +import it.panov.musyx.tv.ui.theme.CoverPlaceholder +import it.panov.musyx.tv.ui.theme.MusyxTheme +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** Used when the system's screen saver delay can't be read. */ +private const val DEFAULT_DELAY_MS = 5 * 60_000L +private const val MIN_DELAY_MS = 15_000L + +/** How long a paused track still keeps the screen on before the system takes over. */ +private const val PAUSED_HOLD_MS = 10 * 60_000L + +/** How long each photo stays, and the crossfade between two. */ +private const val PHOTO_MS = 20_000L +private const val PHOTO_FADE_MS = 2_000 +private const val SAVER_FADE_MS = 1_000 + +/** How far a photo zooms in over its time on screen. */ +private const val PHOTO_ZOOM = 1.12f + +/** The largest size the image server gives. */ +private const val PHOTO_SIZE = 1000 + +/** Artists whose galleries are fetched, from the start of the track's artist list. */ +private const val GALLERY_ARTISTS = 2 + +/** When the remote was last touched, and whether the screen saver covers the app. */ +@Stable +class ScreenSaverState { + var showing by mutableStateOf(false) + private set + + var lastInputAt by mutableLongStateOf(SystemClock.uptimeMillis()) + private set + + /** Any input wakes the app. True when the saver was up, so the input only woke it. */ + fun onInput(): Boolean { + lastInputAt = SystemClock.uptimeMillis() + if (!showing) return false + showing = false + return true + } + + internal fun show() { + showing = true + } + + internal fun hide() { + showing = false + } +} + +/** + * Holds the screen on while music plays and shows the saver once the remote has been idle for + * the system's screen saver delay. + */ +@Composable +fun ScreenSaverHost(state: AppState, saver: ScreenSaverState) { + val p = state.playback.state + val playing = p.status == Status.Playing || p.status == Status.Loading + var holding by remember { mutableStateOf(false) } + LaunchedEffect(p.hasTrack, playing) { + holding = p.hasTrack + if (p.hasTrack && !playing) { + delay(PAUSED_HOLD_MS) + holding = false + } + } + + val view = LocalView.current + DisposableEffect(view, holding) { + view.keepScreenOn = holding + onDispose { view.keepScreenOn = false } + } + + val context = LocalContext.current + // A dialog is its own window, out of reach of the activity's key handling: no saver over it. + val allowed = holding && state.sheet == null + LaunchedEffect(allowed, saver.lastInputAt) { + if (!allowed) return@LaunchedEffect saver.hide() + val after = systemSaverDelayMs(context) ?: return@LaunchedEffect + delay(after - (SystemClock.uptimeMillis() - saver.lastInputAt)) + saver.show() + } + + // Artist galleries, kept for the process so a returning artist costs nothing. + val galleries = remember { mutableMapOf>() } + AnimatedVisibility(saver.showing, enter = fadeIn(tween(SAVER_FADE_MS)), exit = fadeOut(tween(SAVER_FADE_MS / 4))) { + p.track?.let { ScreenSaver(state, it, galleries) } + } +} + +/** The delay the user chose for the system's screen saver, or null when it never starts. */ +private fun systemSaverDelayMs(context: Context): Long? { + val ms = Settings.System.getLong(context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_DELAY_MS) + return if (ms <= 0 || ms >= Int.MAX_VALUE) null else ms.coerceAtLeast(MIN_DELAY_MS) +} + +/** One photo on screen; `n` tells two showings of the same photo apart. */ +private data class Slide(val url: String?, val n: Int) + +@Composable +private fun ScreenSaver(state: AppState, track: Track, galleries: MutableMap>) { + val context = LocalContext.current + var slide by remember { mutableStateOf(Slide(null, 0)) } + LaunchedEffect(track.id) { + // The cover first, so a new song shows as one; then the artists' photos. + var photos = (listOfNotNull(track.coverUrl(PHOTO_SIZE)) + track.artists.mapNotNull { it.coverUrl(PHOTO_SIZE) }).distinct() + slide = Slide(photos.firstOrNull(), slide.n + 1) + launch { + val client = state.client ?: return@launch + val more = track.artists.mapNotNull { it.id }.take(GALLERY_ARTISTS).flatMap { id -> + galleries[id] ?: runCatching { client.artistPhotos(id, PHOTO_SIZE) }.getOrNull()?.also { galleries[id] = it }.orEmpty() + } + photos = (photos + more).distinct() + } + var i = 0 + while (true) { + photos.getOrNull((i + 1) % photos.size.coerceAtLeast(1))?.let { next -> + SingletonImageLoader.get(context).enqueue(ImageRequest.Builder(context).data(next).build()) + } + delay(PHOTO_MS) + if (photos.size < 2) continue + i = (i + 1) % photos.size + slide = Slide(photos[i], slide.n + 1) + } + } + + Box(Modifier.fillMaxSize().background(Color.Black)) { + Crossfade(slide, animationSpec = tween(PHOTO_FADE_MS), label = "photo") { s -> + Photo(s, track.hues) + } + Box( + Modifier + .fillMaxSize() + .background(Brush.verticalGradient(0.45f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.8f))), + ) + // The caption changes sides with each photo, so nothing sits still on the panel. + Crossfade(slide.n % 2 == 0, animationSpec = tween(PHOTO_FADE_MS), label = "caption") { left -> + Box(Modifier.fillMaxSize().padding(horizontal = MusyxTheme.space.safeX, vertical = MusyxTheme.space.safeY)) { + Caption(state, track, left, Modifier.align(if (left) Alignment.BottomStart else Alignment.BottomEnd)) + } + } + } +} + +/** A photo that slowly zooms in toward one side while it's shown. */ +@Composable +private fun Photo(slide: Slide, hues: Pair) { + val zoom = remember { Animatable(1f) } + LaunchedEffect(Unit) { + zoom.animateTo(PHOTO_ZOOM, tween((PHOTO_MS + PHOTO_FADE_MS).toInt(), easing = LinearEasing)) + } + val origin = if (slide.n % 2 == 0) TransformOrigin(0.25f, 0.35f) else TransformOrigin(0.75f, 0.35f) + Box( + Modifier.fillMaxSize().graphicsLayer { + scaleX = zoom.value + scaleY = zoom.value + transformOrigin = origin + }, + ) { + if (slide.url == null) { + CoverPlaceholder(hues, Modifier.fillMaxSize()) + } else { + AsyncImage( + model = slide.url, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize(), + ) + } + } +} + +/** Artist, song, album and year, over a thin line of the track's progress. */ +@Composable +private fun Caption(state: AppState, track: Track, left: Boolean, modifier: Modifier) { + val type = MusyxTheme.type + val align = if (left) TextAlign.Start else TextAlign.End + val p = state.playback.state + val fraction = if (p.durationMs > 0) state.playback.positionMs.toFloat() / p.durationMs else 0f + Column( + modifier.width(560.dp), + horizontalAlignment = if (left) Alignment.Start else Alignment.End, + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text(track.artistsOrUnknown(), style = type.section, color = Color.White.copy(alpha = 0.85f), textAlign = align, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(track.fullTitle, style = type.displayM, color = Color.White, textAlign = align, maxLines = 2, overflow = TextOverflow.Ellipsis) + track.album?.let { album -> + val line = listOfNotNull(album.title.takeIf { it.isNotBlank() }, album.year?.toString()).joinToString(" · ") + if (line.isNotEmpty()) { + Text(line, style = type.body, color = Color.White.copy(alpha = 0.7f), textAlign = align, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + Box(Modifier.padding(top = MusyxTheme.space.s).fillMaxWidth().height(3.dp).background(Color.White.copy(alpha = 0.25f), RoundedCornerShape(2.dp))) { + Box( + Modifier + .fillMaxWidth(fraction.coerceIn(0f, 1f)) + .height(3.dp) + .background(MusyxTheme.colors.accent, RoundedCornerShape(2.dp)), + ) + } + } +} diff --git a/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt b/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt index 21d7a1a..60ae6b1 100644 --- a/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt +++ b/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt @@ -37,6 +37,21 @@ class ApiTest { assertEquals("12345:77", t.fullId) } + @Test + fun trackCarriesAlbumYearAndArtistPhotos() { + val t = Track.from( + json( + """{"id":1,"artists":[{"id":1,"name":"Кино","cover":{"uri":"k/%%"}},{"id":2,"name":"B"}], + "albums":[{"id":77,"title":"Группа крови","year":1988}]}""", + ), + )!! + assertEquals(1988, t.album!!.year) + assertEquals("https://k/1000x1000", t.artists[0].coverUrl(1000)) + assertNull(t.artists[1].coverUrl(1000)) + val photos = artistPhotoUris(json("""{"artist":{"cover":{"uri":"a/%%"}},"allCovers":[{"uri":"b/%%"},{"uri":"a/%%"}]}""")) + assertEquals(listOf("b/%%", "a/%%"), photos) + } + @Test fun numericIdsAndVersions() { val t = Track.from(json("""{"id":42,"title":"Song","version":"Live","artists":[]}"""))!!