Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Add podcasts and an equalizer with a curve per output
Lelonio08efc6702f9e
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.ktindex 66031be..ec84def 100644--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt@@ -55,6 +55,7 @@ class SquareApplication : Application(), ImageLoaderFactory {// exist by then and either can announce a default that would be saved// over what the listener had set.dev.lelonio.square.playback.AudioEffects.load(this)+ dev.lelonio.square.playback.Equalizer.load(this)// Where the extras live, and which tracks are worth keeping them for.// Attached here rather than in the service: Catalog reaches for it on@@ -302,6 +303,11 @@ class SquareApplication : Application(), ImageLoaderFactory {/** The user's saved speed / pitch / reverb combinations. */val effectPresets: EffectPresetStore by lazy { EffectPresetStore(this) }+ /** How far into each podcast episode the listener got; see EpisodeProgress. */+ val episodeProgress: dev.lelonio.square.data.EpisodeProgress by lazy {+ dev.lelonio.square.data.EpisodeProgress(this)+ }+/*** The Spotify source, behind the common backend interface.*diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.ktindex a161db5..aa67608 100644--- a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt@@ -28,6 +28,7 @@ data class SearchLabels(val artist: String,val album: String,val playlist: String,+ val podcast: String = "Podcast",)/**@@ -160,6 +161,12 @@ interface MusicBackend {/** The artists the account follows, for the same shelf's artists chip. */suspend fun followedArtists(): List<SearchItem> = emptyList()+ /** The podcasts the account follows, for the library's podcast chip. */+ suspend fun savedShows(): List<CatalogPlaylist> = emptyList()++ /** What those podcasts put out lately, newest first, for the New tab. */+ suspend fun newEpisodes(): List<CatalogTrack> = emptyList()+/** Tracks of a playlist, album, or artist URI this backend owns. */suspend fun tracksOf(uri: String): List<CatalogTrack>diff --git a/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyWebPlayback.kt b/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyWebPlayback.ktindex 3975836..cf66408 100644--- a/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyWebPlayback.kt+++ b/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyWebPlayback.kt@@ -108,7 +108,12 @@ object SpotifyWebPlayback {val metered = object : androidx.media3.exoplayer.DefaultRenderersFactory(context) {override fun buildAudioSink(c: Context, f: Boolean, p: Boolean) =androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(c)- .setAudioProcessors(arrayOf(androidx.media3.exoplayer.audio.TeeAudioProcessor(meter)))+ .setAudioProcessors(+ arrayOf(+ androidx.media3.exoplayer.audio.TeeAudioProcessor(meter),+ dev.lelonio.square.playback.EqualizerAudioProcessor(),+ ),+ ).build()}val exo = ExoPlayer.Builder(context, metered)diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.ktindex d03b6e1..d457ae6 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt@@ -117,6 +117,8 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {// Videos of every kind YouTube Music has: music videos, and the// uploads people listen to rather than watch (ASMR, sessions).val videos = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_VIDEO) }+ val podcasts = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_PODCAST) }+ val episodes = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_EPISODE) }SearchResults(tracks = songs.await().filterIsInstance<SongItem>().map(::toCatalogTrack),@@ -146,6 +148,16 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {artworkUrl = playlist.thumbnail?.atSize(COVER_SIZE),)},+ podcasts = podcasts.await().filterIsInstance<PodcastItem>().mapNotNull { show ->+ val tile = toCatalogPlaylist(show) ?: return@mapNotNull null+ SearchItem(+ uri = tile.uri,+ title = tile.name,+ subtitle = tile.subtitle ?: labels.podcast,+ artworkUrl = tile.artworkUrl,+ )+ },+ episodes = episodes.await().filterIsInstance<EpisodeItem>().map(::toCatalogTrack),)}}@@ -202,6 +214,28 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {}}+ /** The podcasts saved to the library, from YouTube Music's page of them. */+ override suspend fun savedShows(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {+ if (!account.isSignedIn) return@withContext emptyList()+ runCatching {+ YouTube.savedPodcastShows().getOrThrow().mapNotNull(::toCatalogPlaylist)+ }.getOrElse {+ android.util.Log.w(LOG_TAG, "saved podcasts unavailable: $it")+ emptyList()+ }+ }++ /** YouTube Music's own "New episodes" list, of the podcasts saved. */+ override suspend fun newEpisodes(): List<CatalogTrack> = withContext(Dispatchers.IO) {+ if (!account.isSignedIn) return@withContext emptyList()+ runCatching {+ YouTube.newEpisodes().getOrThrow().map { toCatalogTrack(it).copy(releasedAt = "") }+ }.getOrElse {+ android.util.Log.w(LOG_TAG, "new episodes unavailable: $it")+ emptyList()+ }+ }+/** The artists the account subscribed to, from the library page of them. */override suspend fun followedArtists(): List<SearchItem> = withContext(Dispatchers.IO) {if (!account.isSignedIn) return@withContext emptyList()@@ -424,6 +458,8 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {durationMs = item.duration?.takeIf { it > 0 }?.times(1000L) ?: 0L,explicit = item.explicit,artworkUrl = item.thumbnail,+ // Marks it as an episode; YouTube gives the day only as words.+ releasedAt = "",)/**diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.ktindex ca5e0e7..a831d1e 100644--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt@@ -70,7 +70,29 @@ data class CatalogTrack(* has nothing to play for it.*/val localFile: String? = null,-)+ /**+ * For a podcast episode: when it came out, ISO-8601. Null for music, whose+ * release is a year on its record rather than a day.+ */+ val releasedAt: String? = null,+ /** For an episode: how far into it the listener got, where the source says. */+ val resumeMs: Long = 0,+ /** For an episode: whether the listener heard it to the end. */+ val played: Boolean = false,+ /** For an episode: whether it comes with a picture as well as sound. */+ val hasVideo: Boolean = false,+ /** For an episode: what the show says it is about, as plain text. */+ val summary: String = "",+) {+ /**+ * A podcast episode rather than a song, on either source.+ *+ * What the player and the lists ask before offering what only a song has:+ * lyrics, a heart, a radio, credits.+ */+ val isEpisode: Boolean+ get() = uri.startsWith("spotify:episode:") || releasedAt != null+}/*** One line of lyrics.diff --git a/app/src/main/java/dev/lelonio/square/data/EpisodeProgress.kt b/app/src/main/java/dev/lelonio/square/data/EpisodeProgress.ktnew file mode 100644index 0000000..a4c7ab2--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/data/EpisodeProgress.kt@@ -0,0 +1,90 @@+package dev.lelonio.square.data++import android.content.Context++/**+ * How far into each podcast episode the listener got, on this phone.+ *+ * Spotify keeps its own answer and sends it with every episode, but what it+ * knows is what its own apps told it: an episode heard here, through the+ * engine, may never reach it. So the phone keeps its own, and an episode's row+ * says whichever of the two got further — unless either says it was finished,+ * which wins: an episode heard to the end elsewhere is not one to resume here.+ */+class EpisodeProgress(context: Context) {++ private val prefs = context.applicationContext+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)++ private class Entry(val positionMs: Long, val finished: Boolean, val at: Long)++ /** Where [uri] stands, from a position the player reported. */+ fun record(uri: String, positionMs: Long, durationMs: Long) {+ if (!isEpisode(uri) || positionMs < MIN_POSITION_MS) return+ val finished = durationMs > 0 && positionMs >= durationMs - END_MARGIN_MS+ write(uri, if (finished) 0 else positionMs, finished)+ }++ /** [uri] played through to the next one. */+ fun finished(uri: String) {+ if (isEpisode(uri)) write(uri, 0, true)+ }++ /** Where to start [uri] from, or zero for the beginning. */+ fun resumeFor(track: CatalogTrack): Long {+ val known = apply(track)+ if (known.played) return 0+ // Within the last half minute is the end, and starting there is+ // starting at the credits.+ if (known.durationMs > 0 && known.resumeMs >= known.durationMs - END_MARGIN_MS) return 0+ return known.resumeMs+ }++ /** [track] with this phone's progress folded into the source's. */+ fun apply(track: CatalogTrack): CatalogTrack {+ if (!track.isEpisode) return track+ val local = read(track.uri) ?: return track+ val played = track.played || local.finished+ return track.copy(+ played = played,+ resumeMs = if (played) 0 else maxOf(track.resumeMs, local.positionMs),+ )+ }++ private fun read(uri: String): Entry? {+ val raw = prefs.getString(uri, null) ?: return null+ val parts = raw.split(',')+ return Entry(+ positionMs = parts.getOrNull(0)?.toLongOrNull() ?: return null,+ finished = parts.getOrNull(1) == "1",+ at = parts.getOrNull(2)?.toLongOrNull() ?: 0L,+ )+ }++ private fun write(uri: String, positionMs: Long, finished: Boolean) {+ val edit = prefs.edit()+ .putString(uri, "$positionMs,${if (finished) 1 else 0},${System.currentTimeMillis()}")+ // Kept to the most recent few hundred: nobody is half-way through more.+ val all = prefs.all+ if (all.size > MAX_ENTRIES) {+ all.entries+ .sortedBy { (it.value as? String)?.split(',')?.getOrNull(2)?.toLongOrNull() ?: 0L }+ .take(all.size - MAX_ENTRIES)+ .forEach { edit.remove(it.key) }+ }+ edit.apply()+ }++ private fun isEpisode(uri: String) = uri.startsWith("spotify:episode:")++ private companion object {+ const val FILE_NAME = "episode_progress"+ const val MAX_ENTRIES = 400++ /** Less than this in is not having started. */+ const val MIN_POSITION_MS = 15_000L++ /** And this close to the end is having finished. */+ const val END_MARGIN_MS = 30_000L+ }+}diff --git a/app/src/main/java/dev/lelonio/square/data/Gateway.kt b/app/src/main/java/dev/lelonio/square/data/Gateway.ktindex 0cfcd63..b41c24b 100644--- a/app/src/main/java/dev/lelonio/square/data/Gateway.kt+++ b/app/src/main/java/dev/lelonio/square/data/Gateway.kt@@ -212,6 +212,105 @@ class Gateway(private val keys: PathfinderKeys) {.getOrNull()}+ /**+ * A podcast's own page: its name, who makes it, what it is about, and its+ * newest episode. The rest of the episodes are [showEpisodes].+ */+ suspend fun show(uri: String): String? {+ keys.refresh()+ return runCatching {+ query(+ operation = "queryShowMetadataV2",+ hash = keys.show,+ variables = """{"uri":"$uri","includeContentCapabilityTrait":true,""" ++ """"includeEpisodeContentRatingsV2":false}""",+ )+ }+ .onFailure { android.util.Log.i(TAG, "show unavailable: ${it.message}") }+ .getOrNull()+ }++ /** A page of a podcast's episodes, newest first; see SpotifyPodcasts. */+ suspend fun showEpisodes(uri: String, offset: Int, limit: Int = SHOW_PAGE): String? {+ keys.refresh()+ return runCatching {+ query(+ operation = "queryPodcastEpisodes",+ hash = keys.showEpisodes,+ variables = """{"uri":"$uri","offset":$offset,"limit":$limit,""" ++ """"includeEpisodeContentRatingsV2":false}""",+ )+ }+ .onFailure { android.util.Log.i(TAG, "episodes unavailable: ${it.message}") }+ .getOrNull()+ }++ /**+ * The podcasts the account follows, from its library.+ *+ * The library query with Spotify's own filter for them, which is how the+ * web player's "Podcasts & Shows" chip asks the same thing.+ */+ suspend fun followedShows(offset: Int = 0, limit: Int = SHOWS_PAGE): String? {+ keys.refresh()+ return runCatching {+ query(+ operation = "libraryV3",+ hash = keys.libraryContents,+ variables = """{"filters":["Podcasts & Shows"],"order":null,"textFilter":null,""" ++ """"features":["YOUR_EPISODES_V2","PRERELEASES","PRERELEASES_V2","EVENTS"],""" ++ """"limit":$limit,"offset":$offset,"flatten":false,"expandedFolders":[],""" ++ """"folderUri":null,"includeFoldersWhenFlattening":true}""",+ )+ }+ .onFailure { android.util.Log.i(TAG, "followed shows unavailable: ${it.message}") }+ .getOrNull()+ }++ /**+ * Puts [uris] in the account's library, or takes them out: shows, which the+ * Web API keeps behind a registered application, and anything else the web+ * player keeps the same way. True when the gateway took it.+ */+ suspend fun setInLibrary(uris: List<String>, keep: Boolean): Boolean {+ keys.refresh()+ val list = uris.joinToString(",") { org.json.JSONObject.quote(it) }+ return runCatching {+ val answer = query(+ operation = if (keep) "addToLibrary" else "removeFromLibrary",+ hash = keys.libraryEdit,+ variables = if (keep) {+ """{"libraryItemUris":[$list],"interactionId":null}"""+ } else {+ """{"libraryItemUris":[$list]}"""+ },+ )+ !org.json.JSONObject(answer).has("errors")+ }+ .onFailure { android.util.Log.i(TAG, "library edit refused: ${it.message}") }+ .getOrDefault(false)+ }++ /**+ * Spotify's home as one of its own chips has it: "podcasts-chip" is the+ * page of shows and episodes the app's Podcast chip shows.+ */+ suspend fun homeFacet(facet: String): String? {+ keys.refresh()+ val zone = org.json.JSONObject.quote(java.util.TimeZone.getDefault().id)+ return runCatching {+ query(+ operation = "home",+ hash = keys.home,+ variables = """{"homeEndUserIntegration":"INTEGRATION_WEB_PLAYER","timeZone":$zone,""" ++ """"sp_t":"","facet":"$facet","sectionItemsLimit":10,""" ++ """"includeEpisodeContentRatingsV2":false}""",+ )+ }+ .onFailure { android.util.Log.i(TAG, "home $facet unavailable: ${it.message}") }+ .getOrNull()+ }+/*** Reads a list to its end.*@@ -292,5 +391,11 @@ class Gateway(private val keys: PathfinderKeys) {/** And how much of a single row, when one is read on its own. */const val BROWSE_PAGE = 20++ /** Episodes a page, as the web player reads a show. */+ const val SHOW_PAGE = 50++ /** Podcasts followed, a page: more than most people follow. */+ const val SHOWS_PAGE = 50}}diff --git a/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt b/app/src/main/java/dev/lelonio/square/data/GatewaySearch.ktindex 1836f87..9f433d4 100644--- a/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt+++ b/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt@@ -78,6 +78,18 @@ internal object GatewaySearch {)},lyricMatches = lyricMatches,+ podcasts = search.items("podcasts").mapNotNull { wrapper ->+ val show = SpotifyPodcasts.showTile(wrapper.optJSONObject("data")) ?: return@mapNotNull null+ SearchItem(+ uri = show.uri,+ title = show.name,+ subtitle = show.subtitle ?: labels.podcast,+ artworkUrl = wrapper.optJSONObject("data")?.optJSONObject("coverArt").best(),+ )+ },+ episodes = search.items("episodes").mapNotNull { wrapper ->+ SpotifyPodcasts.episode(wrapper.optJSONObject("data"))+ },)}diff --git a/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt b/app/src/main/java/dev/lelonio/square/data/GatewayTracks.ktindex ac1c343..424e8fd 100644--- a/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt+++ b/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt@@ -15,8 +15,8 @@ import org.json.JSONObjectinternal object GatewayTracks {/**- * Null for anything that is not a playable track: a podcast episode, a- * local file, something this market has no licensed copy of. Keeping those+ * Null for anything that is not a playable track or episode: something+ * this market has no licensed copy of. Keeping those* would put items in the queue that the engine could only skip.*//**@@ -44,6 +44,10 @@ internal object GatewayTracks {fun track(data: JSONObject?, addedAt: String?): CatalogTrack? {if (data == null) return nullif (LocalLibrary.isSpotifyLocal(data.optString("uri"))) return localTrack(data, addedAt)+ // An episode in a playlist plays like a song does, so it is kept.+ if (data.optString("__typename") == "Episode") {+ return SpotifyPodcasts.episode(data)?.copy(addedAt = addedAt)+ }val uri = data.optString("uri").takeIf { it.startsWith("spotify:track:") } ?: return nullif (data.optJSONObject("playability")?.optBoolean("playable", true) == false) return nulldiff --git a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.ktindex f407981..9cba271 100644--- a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt+++ b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt@@ -61,6 +61,20 @@ class PathfinderKeys(context: Context) {val playlistSection: Stringget() = prefs.getString(KEY_PLAYLIST_SECTION, null) ?: DEFAULT_PLAYLIST_SECTION+ /** And `queryShowMetadataV2`, a podcast's own page; see SpotifyPodcasts. */+ val show: String get() = prefs.getString(KEY_SHOW, null) ?: DEFAULT_SHOW++ /** And `queryPodcastEpisodes`, a podcast's episodes a page at a time. */+ val showEpisodes: String get() = prefs.getString(KEY_SHOW_EPISODES, null) ?: DEFAULT_SHOW_EPISODES++ /** And `libraryV3`, the account's library by kind; the podcasts it follows. */+ val libraryContents: String+ get() = prefs.getString(KEY_LIBRARY_CONTENTS, null) ?: DEFAULT_LIBRARY_CONTENTS++ /** And `addToLibrary` / `removeFromLibrary`, one document for both. */+ val libraryEdit: String+ get() = prefs.getString(KEY_LIBRARY_EDIT, null) ?: DEFAULT_LIBRARY_EDIT+/** The web client version the gateway is told about. */val appVersion: String get() = prefs.getString(KEY_VERSION, null) ?: DEFAULT_VERSION@@ -99,6 +113,14 @@ class PathfinderKeys(context: Context) {?.let { edit.putString(KEY_ARTIST_OVERVIEW, it) }body.optString("playlistSection").takeIf { it.length == HASH_LENGTH }?.let { edit.putString(KEY_PLAYLIST_SECTION, it) }+ body.optString("show").takeIf { it.length == HASH_LENGTH }+ ?.let { edit.putString(KEY_SHOW, it) }+ body.optString("showEpisodes").takeIf { it.length == HASH_LENGTH }+ ?.let { edit.putString(KEY_SHOW_EPISODES, it) }+ body.optString("libraryContents").takeIf { it.length == HASH_LENGTH }+ ?.let { edit.putString(KEY_LIBRARY_CONTENTS, it) }+ body.optString("libraryEdit").takeIf { it.length == HASH_LENGTH }+ ?.let { edit.putString(KEY_LIBRARY_EDIT, it) }body.optString("appVersion").takeIf { it.isNotEmpty() }?.let { edit.putString(KEY_VERSION, it) }edit.apply()@@ -118,6 +140,10 @@ class PathfinderKeys(context: Context) {const val KEY_BROWSE_SECTION = "browse_section"const val KEY_ARTIST_OVERVIEW = "artist_overview"const val KEY_PLAYLIST_SECTION = "playlist_section"+ const val KEY_SHOW = "show"+ const val KEY_SHOW_EPISODES = "show_episodes"+ const val KEY_LIBRARY_CONTENTS = "library_contents"+ const val KEY_LIBRARY_EDIT = "library_edit"const val KEY_VERSION = "app_version"const val KEY_CHECKED = "checked_at"@@ -150,6 +176,14 @@ class PathfinderKeys(context: Context) {"9f8134ef565e78621f1e1793555bd6633c5ac144ae0f89604ed3ae3f80b3c8e6"const val DEFAULT_PLAYLIST_SECTION ="2615df403a9043c1d7d3094fbeb4c9653b07b11a33d8081fbd31f0f7959ff4a1"+ const val DEFAULT_SHOW =+ "b475447846f37cc426add800b995a7859c169c53c72b62de6338c0c40a5dacea"+ const val DEFAULT_SHOW_EPISODES =+ "3539d746cf882f3909660de40b4ef472b3f5893a0761d617c282541de5d412c5"+ const val DEFAULT_LIBRARY_CONTENTS =+ "390c78e5b951029bad359785e69b07b536a509c581cbcd0aded5e5067f187455"+ const val DEFAULT_LIBRARY_EDIT =+ "896ebcb47815681340860d121cb5d494e157e2a78d3950385cd54e0393c67148"const val DEFAULT_VERSION = "1.2.97.155.g5dd0dcaf-development"}}diff --git a/app/src/main/java/dev/lelonio/square/data/SearchResults.kt b/app/src/main/java/dev/lelonio/square/data/SearchResults.ktindex 411d7d5..86d0dc0 100644--- a/app/src/main/java/dev/lelonio/square/data/SearchResults.kt+++ b/app/src/main/java/dev/lelonio/square/data/SearchResults.kt@@ -24,10 +24,15 @@ data class SearchResults(* the row. Empty from the Web API, which does not search lyrics at all.*/val lyricMatches: Set<String> = emptySet(),+ /** Shows, which open as their list of episodes. */+ val podcasts: List<SearchItem> = emptyList(),+ /** Single episodes, which play. */+ val episodes: List<CatalogTrack> = emptyList(),) {/** How many rows this holds in total, for telling a page from an echo. */val count: Int- get() = tracks.size + artists.size + albums.size + playlists.size + videos.size+ get() = tracks.size + artists.size + albums.size + playlists.size + videos.size ++ podcasts.size + episodes.size/*** This, with another page's rows after it.@@ -48,12 +53,14 @@ data class SearchResults(playlists = playlists + page.playlists.filter { it.uri !in heldLists },videos = videos + page.videos.filter { video -> videos.none { it.uri == video.uri } },lyricMatches = lyricMatches + page.lyricMatches,+ podcasts = podcasts + page.podcasts.filter { show -> podcasts.none { it.uri == show.uri } },+ episodes = episodes + page.episodes.filter { episode -> episodes.none { it.uri == episode.uri } },)}val isEmpty: Booleanget() = tracks.isEmpty() && artists.isEmpty() && albums.isEmpty() && playlists.isEmpty() &&- videos.isEmpty()+ videos.isEmpty() && podcasts.isEmpty() && episodes.isEmpty()}/**diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyHome.ktindex c93b689..97143a0 100644--- a/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt@@ -43,7 +43,12 @@ object SpotifyHome {/** Sections whose items are one-per-row filler; see the note in [parse]. */private const val BASELINE = "HomeFeedBaselineSectionData"- fun parse(json: String): List<HomeShelf> = runCatching {+ /**+ * @param podcasts whether shows and episodes are tiles too. Off for the+ * music home, where they used to be dropped; on for the Podcast chip,+ * which is nothing but them.+ */+ fun parse(json: String, podcasts: Boolean = false): List<HomeShelf> = runCatching {val sections = JSONObject(json).getJSONObject("data").getJSONObject("home")@@ -57,7 +62,7 @@ object SpotifyHome {val section = sections.getJSONObject(index)val baseline = section.optJSONObject("data")?.optString("__typename") == BASELINEif (!baseline) {- shelf(section)?.let(rows::add)+ shelf(section, podcasts)?.let(rows::add)continue}// The endless feed at the bottom of Spotify's own home: dozens of@@ -66,7 +71,7 @@ object SpotifyHome {// the artist a section is about when it names one ("For fans of// Geolier" twice is one row), and by title when it does not ("Just// for you" five times is one row).- val one = shelf(section) ?: continue+ val one = shelf(section, podcasts) ?: continueval artist = section.optJSONObject("data")?.optJSONObject("headerEntity")?.optJSONObject("data")@@ -80,7 +85,7 @@ object SpotifyHome {rows + gathered.values}.getOrDefault(emptyList())- private fun shelf(section: JSONObject): HomeShelf? {+ private fun shelf(section: JSONObject, podcasts: Boolean): HomeShelf? {val data = section.optJSONObject("data") ?: return nullval title = data.optJSONObject("title")?.optString("transformedLabel").orEmpty()@@ -89,12 +94,12 @@ object SpotifyHome {val items = section.optJSONObject("sectionItems")?.optJSONArray("items")?: return nullval entries = (0 until items.length()).mapNotNull { index ->- entry(items.getJSONObject(index))+ entry(items.getJSONObject(index), podcasts)}return if (entries.isEmpty()) null else HomeShelf(title, entries, section.optString("uri"))}- private fun entry(item: JSONObject): CatalogPlaylist? {+ private fun entry(item: JSONObject, podcasts: Boolean): CatalogPlaylist? {val uri = item.optString("uri")if (uri.isEmpty()) return null// The DJ is a stream Spotify generates as you listen, not a list: it has@@ -126,8 +131,13 @@ object SpotifyHome {),)- // Podcasts and audiobooks come down the same pipe. This app plays- // music, and a tile that cannot be opened is worse than a gap.+ // Shows open as their list of episodes and an episode plays; both+ // only on the podcast page, where they are what was asked for.+ "Podcast" -> if (podcasts) SpotifyPodcasts.showTile(data) else null+ "Episode" -> if (podcasts) SpotifyPodcasts.episodeTile(data) else null++ // Audiobooks come down the same pipe, and a tile that cannot be+ // opened is worse than a gap.else -> null}}diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyLink.ktindex 7fa6942..2a5980c 100644--- a/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt@@ -48,5 +48,5 @@ object SpotifyLink {private fun String.isKind(): Boolean =KINDS.any { startsWith("spotify:$it:") }- private val KINDS = listOf("track", "album", "playlist", "artist")+ private val KINDS = listOf("track", "album", "playlist", "artist", "show")}diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyPodcasts.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyPodcasts.ktnew file mode 100644index 0000000..e47c545--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyPodcasts.kt@@ -0,0 +1,207 @@+package dev.lelonio.square.data++import org.json.JSONArray+import org.json.JSONObject++/**+ * Podcasts, read from Spotify's own gateway.+ *+ * A show is opened as a list of its episodes, on the same page a playlist+ * opens on, and an episode is a [CatalogTrack] with the few things only an+ * episode has filled in: the day it came out, how far in the listener got, and+ * whether it has a picture as well as sound. Everything that plays a track+ * plays an episode too — the engine takes `spotify:episode:` addresses as it+ * takes `spotify:track:` ones.+ *+ * Forgiving in the same way [SpotifyHome] is, and for the same reason: this is+ * a private interface, and a show with one odd episode should still open.+ */+object SpotifyPodcasts {++ /** A show's own page, without its episodes. */+ data class Show(+ val uri: String,+ val name: String,+ val publisher: String,+ val description: String,+ val artworkUrl: String?,+ /** Whether the account follows it. */+ val saved: Boolean?,+ )++ fun isShow(uri: String): Boolean = uri.startsWith(SHOW)++ fun isEpisode(uri: String): Boolean = uri.startsWith(EPISODE)++ /** Null when the answer was not a show: a retired hash, a removed show. */+ fun parseShow(json: String): Show? = runCatching {+ val data = JSONObject(json).getJSONObject("data").getJSONObject("podcastUnionV2")+ if (data.optString("__typename") != "Podcast") return null+ Show(+ uri = data.optString("uri"),+ name = data.optString("name"),+ publisher = data.optJSONObject("publisher")?.optString("name").orEmpty(),+ description = data.optString("description").trim(),+ artworkUrl = cover(data.optJSONObject("coverArt"), LARGE),+ saved = if (data.has("saved")) data.optBoolean("saved") else null,+ )+ }.getOrNull()++ /**+ * A page of a show's episodes.+ *+ * The show's name is passed in rather than read from each episode: the+ * episodes of one page all belong to it, and the list under its title does+ * not need it said again on every row — the player does, and gets it here.+ */+ fun parseEpisodes(json: String, showName: String): GatewayPage? = runCatching {+ val page = JSONObject(json).getJSONObject("data")+ .getJSONObject("podcastUnionV2")+ .getJSONObject("episodesV2")+ val items = page.getJSONArray("items")+ val read = (0 until items.length()).mapNotNull { index ->+ episode(+ items.optJSONObject(index)?.optJSONObject("entity")?.optJSONObject("data"),+ showName,+ )+ }+ val total = page.optInt("totalCount", items.length())+ GatewayPage(+ tracks = read,+ nextOffset = page.optJSONObject("pagingInfo")+ ?.takeIf { it.has("nextOffset") && !it.isNull("nextOffset") }+ ?.optInt("nextOffset")+ ?.takeIf { items.length() > 0 },+ total = total,+ )+ }.getOrNull()++ /** The account's podcasts, as tiles; null when the library would not answer. */+ fun parseFollowed(json: String): List<CatalogPlaylist>? = runCatching {+ val library = JSONObject(json).getJSONObject("data")+ .getJSONObject("me")+ .getJSONObject("libraryV3")+ if (library.optString("__typename") != "LibraryPage") {+ android.util.Log.i(TAG, "library answered ${library.optString("__typename")}")+ return null+ }+ val items = library.optJSONArray("items") ?: JSONArray()+ (0 until items.length()).mapNotNull { index ->+ val data = items.optJSONObject(index)?.optJSONObject("item")?.optJSONObject("data")+ ?: return@mapNotNull null+ if (data.optString("__typename") != "Podcast") return@mapNotNull null+ CatalogPlaylist(+ uri = data.optString("uri").takeIf(::isShow) ?: return@mapNotNull null,+ name = data.optString("name"),+ artworkUrl = cover(data.optJSONObject("coverArt"), LARGE),+ subtitle = data.optJSONObject("publisher")?.optString("name")?.takeIf { it.isNotEmpty() },+ )+ }+ }.getOrNull()++ /**+ * One episode, wherever it was found: a show's page, a playlist, a home+ * shelf, a search. Null for anything else, and for an episode this market+ * cannot play.+ */+ fun episode(data: JSONObject?, showName: String? = null): CatalogTrack? {+ if (data == null || data.optString("__typename") != "Episode") return null+ val uri = data.optString("uri").takeIf(::isEpisode) ?: return null+ if (data.optJSONObject("playability")?.optBoolean("playable", true) == false) return null++ val show = data.optJSONObject("podcastV2")?.optJSONObject("data")+ val name = show?.optString("name")?.takeIf { it.isNotEmpty() } ?: showName.orEmpty()+ val played = data.optJSONObject("playedState")+ val media = data.optJSONArray("mediaTypes")+ val released = data.optJSONObject("releaseDate")?.optString("isoString")?.takeIf { it.isNotEmpty() }+ return CatalogTrack(+ uri = uri,+ name = data.optString("name"),+ artist = name,+ album = name,+ albumUri = show?.optString("uri")?.takeIf(::isShow),+ durationMs = data.optJSONObject("duration")?.optLong("totalMilliseconds") ?: 0L,+ explicit = data.optJSONObject("contentRating")?.optString("label") == "EXPLICIT",+ artworkUrl = cover(data.optJSONObject("coverArt"), ROW)+ ?: cover(show?.optJSONObject("coverArt"), ROW),+ year = released?.take(4).orEmpty(),+ releasedAt = released,+ resumeMs = played?.optLong("playPositionMilliseconds") ?: 0L,+ played = played?.optString("state") == "COMPLETED",+ hasVideo = media != null && (0 until media.length()).any { media.optString(it) == "VIDEO" },+ summary = summaryOf(data),+ )+ }++ /**+ * What the show says about an episode, as one paragraph of plain text.+ *+ * From the HTML where there is some: the plain field is the same text with+ * the line breaks simply removed, which runs the end of one sentence into+ * the start of the next ("driver.Thank you").+ */+ private fun summaryOf(data: JSONObject): String {+ val html = data.optString("htmlDescription")+ val text = if (html.isNotBlank()) {+ androidx.core.text.HtmlCompat+ .fromHtml(html, androidx.core.text.HtmlCompat.FROM_HTML_MODE_COMPACT)+ .toString()+ } else {+ data.optString("description")+ }+ return text.replace(Regex("\\s+"), " ").trim().take(SUMMARY_LENGTH)+ }++ /** A show as a tile, from wherever one was found. */+ fun showTile(data: JSONObject?): CatalogPlaylist? {+ if (data == null || data.optString("__typename") != "Podcast") return null+ return CatalogPlaylist(+ uri = data.optString("uri").takeIf(::isShow) ?: return null,+ name = data.optString("name"),+ artworkUrl = cover(data.optJSONObject("coverArt"), LARGE),+ subtitle = data.optJSONObject("publisher")?.optString("name")?.takeIf { it.isNotEmpty() },+ )+ }++ /** An episode as a tile: a home shelf shows it like a record. */+ fun episodeTile(data: JSONObject?): CatalogPlaylist? {+ val episode = episode(data) ?: return null+ return CatalogPlaylist(+ uri = episode.uri,+ name = episode.name,+ artworkUrl = cover(data?.optJSONObject("coverArt"), LARGE) ?: episode.artworkUrl,+ subtitle = episode.artist.takeIf { it.isNotEmpty() },+ )+ }++ /**+ * The picture nearest [width], or whatever there is.+ *+ * Three sizes come back in no particular order; a row wants the small one+ * and a page the large.+ */+ private fun cover(holder: JSONObject?, width: Int): String? {+ val sources = holder?.optJSONArray("sources") ?: return null+ var best: String? = null+ var distance = Int.MAX_VALUE+ for (index in 0 until sources.length()) {+ val source = sources.optJSONObject(index) ?: continue+ val url = source.optString("url").takeIf { it.isNotEmpty() } ?: continue+ val gap = kotlin.math.abs(source.optInt("width", width) - width)+ if (gap < distance) {+ best = url+ distance = gap+ }+ }+ return best+ }++ private const val TAG = "SquarePodcasts"+ private const val SHOW = "spotify:show:"+ private const val EPISODE = "spotify:episode:"+ private const val ROW = 300+ private const val LARGE = 640++ /** Enough to say what an episode is about; show notes run to pages. */+ private const val SUMMARY_LENGTH = 600+}diff --git a/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt b/app/src/main/java/dev/lelonio/square/playback/AudioOutput.ktindex 0f922b7..692a687 100644--- a/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt+++ b/app/src/main/java/dev/lelonio/square/playback/AudioOutput.kt@@ -538,6 +538,7 @@ class AudioOutput {// the packets go out untouched and the rate is set on the track itself.if (lightEffects) {synchronized(this) { applyPlatformRate() }+ equalizer.apply(data, sizeInBytes, channels, sampleRate)writeAll(output, data, sizeInBytes)return}@@ -555,10 +556,16 @@ class AudioOutput {}if (stretched != null) {- writeAll(output, stretched, stretched.remaining())+ val size = stretched.remaining()+ // After the stretch, as in the other players' chain; see+ // EqualizerAudioProcessor. Its own view of the buffer, so the+ // equaliser's reads leave the position the write starts from.+ equalizer.apply(stretched.duplicate(), size, channels, sampleRate)+ writeAll(output, stretched, size)return}+ equalizer.apply(data, sizeInBytes, channels, sampleRate)writeAll(output, data, sizeInBytes)}@@ -599,6 +606,9 @@ class AudioOutput {val output = synchronized(this) { ensureTrack(sampleRate, channels) } ?: returnif (!voice) enterVoice(output)dev.lelonio.square.backend.spotify.SpotifyDj.hear(data, sizeInBytes)+ // The one thing the voice does go through: the curve is about the+ // headphones, not the music, and a voice on them needs it as much.+ equalizer.apply(data, sizeInBytes, channels, sampleRate)writeAll(output, data, sizeInBytes)}@@ -637,6 +647,9 @@ class AudioOutput {/** Takes the middle of the stage away; see [CentreExtractor]. */private val vocals = CentreExtractor()+ /** The listener's curve for whatever is plugged in; see [Equalizer]. */+ private val equalizer = EqualizerFilter()+/** What the track was last told, so it is not told again every packet. */private var platformSpeed = 1fprivate var platformPitch = 1fdiff --git a/app/src/main/java/dev/lelonio/square/playback/AudioRoute.kt b/app/src/main/java/dev/lelonio/square/playback/AudioRoute.ktnew file mode 100644index 0000000..9dfc225--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/playback/AudioRoute.kt@@ -0,0 +1,169 @@+package dev.lelonio.square.playback++import android.content.Context+import android.media.AudioAttributes+import android.media.AudioDeviceCallback+import android.media.AudioDeviceInfo+import android.media.AudioManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * Where the music is coming out: the phone, a cable, or which pair of+ * Bluetooth headphones.+ *+ * What the equaliser keys its curves by. A Bluetooth or USB device is told+ * apart by its own name — two pairs of the same model share a curve, which is+ * what they would want anyway — and the phone's speaker and a cable are one+ * place each, since a cable says nothing about what is on the end of it.+ */+object AudioRoute {++ enum class Kind { SPEAKER, WIRED, BLUETOOTH, USB, OTHER }++ data class Output(+ /** Stable across connections; what a curve is saved under. */+ val key: String,+ val kind: Kind,+ /** The device's own name for Bluetooth and USB, empty for the rest. */+ val name: String,+ )++ private val SPEAKER = Output("speaker", Kind.SPEAKER, "")++ private val _current = MutableStateFlow(SPEAKER)+ val current: StateFlow<Output> = _current.asStateFlow()++ private var manager: AudioManager? = null+ private val listeners = mutableListOf<(Output) -> Unit>()+ private val main by lazy { Handler(Looper.getMainLooper()) }++ /** Called on the main thread whenever the output changes. */+ fun onChange(listener: (Output) -> Unit) {+ listeners += listener+ }++ fun start(context: Context) {+ if (manager != null) return+ val audio = context.applicationContext.getSystemService(AudioManager::class.java) ?: return+ manager = audio+ audio.registerAudioDeviceCallback(+ object : AudioDeviceCallback() {+ override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>) = settle()+ override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>) = settle()+ },+ main,+ )+ evaluate()+ }++ /**+ * Looks again now, and twice more as the system catches up.+ *+ * A device announces itself before the audio is moved to it: asked at+ * once, the answer is still the speaker the headphones are about to+ * replace.+ */+ private fun settle() {+ evaluate()+ main.postDelayed(::evaluate, 600)+ main.postDelayed(::evaluate, 2000)+ }++ private fun evaluate() {+ val audio = manager ?: return+ val outputs = runCatching { audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS).toList() }+ .getOrDefault(emptyList())+ val chosen = routed(audio, outputs) ?: likeliest(outputs)+ val output = chosen?.let(::describe) ?: SPEAKER+ if (output == _current.value) return+ _current.value = output+ android.util.Log.i("SquareEq", "output now ${output.kind}")+ listeners.forEach { it(output) }+ }++ /**+ * The device media is actually routed to, where the system says so.+ *+ * Android 13 and later. Before that the routing is not public, and+ * [likeliest] guesses the way the system decides.+ */+ private fun routed(audio: AudioManager, outputs: List<AudioDeviceInfo>): AudioDeviceInfo? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null+ val media = AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_MEDIA)+ .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)+ .build()+ val target = runCatching { audio.getAudioDevicesForAttributes(media).firstOrNull() }+ .getOrNull() ?: return null+ return outputs.firstOrNull { it.type == target.type && it.address == target.address }+ ?: outputs.firstOrNull { it.type == target.type }+ }++ /** Whatever was plugged in last wins over the speaker, Bluetooth over a cable. */+ private fun likeliest(outputs: List<AudioDeviceInfo>): AudioDeviceInfo? =+ outputs.filter { kindOf(it.type) != Kind.OTHER || it.type == AudioDeviceInfo.TYPE_HDMI }+ .maxByOrNull {+ when (kindOf(it.type)) {+ Kind.BLUETOOTH -> if (it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) 1 else 5+ Kind.USB -> 4+ Kind.WIRED -> 3+ Kind.OTHER -> 2+ Kind.SPEAKER -> if (it.type == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) 1 else 0+ }+ }++ private fun describe(device: AudioDeviceInfo): Output {+ val kind = kindOf(device.type)+ val name = device.productName?.toString()?.trim().orEmpty()+ return when (kind) {+ Kind.SPEAKER -> SPEAKER+ Kind.WIRED -> Output("wired", Kind.WIRED, "")+ Kind.BLUETOOTH -> Output(if (name.isEmpty()) "bt" else "bt:$name", kind, name)+ Kind.USB -> Output(if (name.isEmpty()) "usb" else "usb:$name", kind, name)+ Kind.OTHER -> Output("type:${device.type}", kind, name)+ }+ }++ /** What kind of place [key] stands for, from the key alone. */+ fun kindOf(key: String): Kind = when {+ key == "speaker" -> Kind.SPEAKER+ key == "wired" -> Kind.WIRED+ key == "bt" || key.startsWith("bt:") -> Kind.BLUETOOTH+ key == "usb" || key.startsWith("usb:") -> Kind.USB+ else -> Kind.OTHER+ }++ private fun kindOf(type: Int): Kind = when (type) {+ AudioDeviceInfo.TYPE_BUILTIN_SPEAKER,+ AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE,+ AudioDeviceInfo.TYPE_BUILTIN_EARPIECE,+ -> Kind.SPEAKER++ AudioDeviceInfo.TYPE_WIRED_HEADSET,+ AudioDeviceInfo.TYPE_WIRED_HEADPHONES,+ AudioDeviceInfo.TYPE_LINE_ANALOG,+ AudioDeviceInfo.TYPE_AUX_LINE,+ -> Kind.WIRED++ AudioDeviceInfo.TYPE_BLUETOOTH_A2DP,+ AudioDeviceInfo.TYPE_BLUETOOTH_SCO,+ AudioDeviceInfo.TYPE_BLE_HEADSET,+ AudioDeviceInfo.TYPE_BLE_SPEAKER,+ AudioDeviceInfo.TYPE_BLE_BROADCAST,+ AudioDeviceInfo.TYPE_HEARING_AID,+ -> Kind.BLUETOOTH++ AudioDeviceInfo.TYPE_USB_HEADSET,+ AudioDeviceInfo.TYPE_USB_DEVICE,+ AudioDeviceInfo.TYPE_USB_ACCESSORY,+ AudioDeviceInfo.TYPE_DOCK,+ -> Kind.USB++ else -> Kind.OTHER+ }+}diff --git a/app/src/main/java/dev/lelonio/square/playback/BungeeAudioProcessor.kt b/app/src/main/java/dev/lelonio/square/playback/BungeeAudioProcessor.ktindex ed921fe..97ff69d 100644--- a/app/src/main/java/dev/lelonio/square/playback/BungeeAudioProcessor.kt+++ b/app/src/main/java/dev/lelonio/square/playback/BungeeAudioProcessor.kt@@ -190,6 +190,40 @@ class VocalAudioProcessor : BaseAudioProcessor() {}}+/**+ * The equaliser, for the players that are not the Spotify engine.+ *+ * After the stretcher, so the bands sit where they were set whatever the speed+ * and pitch: before it, a pitch shift would carry the bass boost up with the+ * bass. See [Equalizer].+ */+@OptIn(UnstableApi::class)+class EqualizerAudioProcessor : BaseAudioProcessor() {++ private val filter = EqualizerFilter()++ override fun onConfigure(+ inputAudioFormat: AudioProcessor.AudioFormat,+ ): AudioProcessor.AudioFormat {+ if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT) {+ throw AudioProcessor.UnhandledAudioFormatException(inputAudioFormat)+ }+ return inputAudioFormat+ }++ override fun queueInput(inputBuffer: ByteBuffer) {+ val size = inputBuffer.remaining()+ if (size == 0) return+ val out = replaceOutputBuffer(size)+ val start = out.position()+ out.put(inputBuffer)+ out.position(start)+ filter.apply(out, size, inputAudioFormat.channelCount, inputAudioFormat.sampleRate)+ out.position(start)+ out.limit(start + size)+ }+}+@OptIn(UnstableApi::class)class BungeeProcessorChain(private val bungee: BungeeAudioProcessor = BungeeAudioProcessor(),@@ -201,7 +235,9 @@ class BungeeProcessorChain(private val vocals = VocalAudioProcessor()- override fun getAudioProcessors(): Array<AudioProcessor> = arrayOf(vocals, bungee, *after)+ private val equalizer = EqualizerAudioProcessor()++ override fun getAudioProcessors(): Array<AudioProcessor> = arrayOf(vocals, bungee, equalizer, *after)override fun applyPlaybackParameters(playbackParameters: PlaybackParameters,diff --git a/app/src/main/java/dev/lelonio/square/playback/Equalizer.kt b/app/src/main/java/dev/lelonio/square/playback/Equalizer.ktnew file mode 100644index 0000000..aef3584--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/playback/Equalizer.kt@@ -0,0 +1,410 @@+package dev.lelonio.square.playback++import android.content.Context+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.builtins.MapSerializer+import kotlinx.serialization.builtins.serializer+import kotlinx.serialization.json.Json+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.log10+import kotlin.math.pow+import kotlin.math.roundToInt+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Ten bands of equalisation, one curve for each pair of headphones.+ *+ * Done in the app's own code rather than with the platform's+ * `android.media.audiofx.Equalizer`. That one is whatever the phone's maker put+ * behind it: five bands on one phone, eight on another, centred wherever they+ * fell, and on some phones silently not there. Every player here already hands+ * its audio through code of the app's own on the way out — the engine's sink+ * for Spotify, the processor chain for everything ExoPlayer plays — so the same+ * filters run on all of them, on every phone, and a curve sounds the same+ * wherever it was set.+ *+ * Per output, because a curve belongs to the thing it corrects: what makes one+ * pair of headphones sound right makes a car or the phone's own speaker sound+ * wrong. The output in use is watched (see [AudioRoute]) and its curve follows+ * it; a device not seen before starts flat and off.+ *+ * Like [AudioEffects], a process-wide object: the service and the UI share the+ * process, and the filters read [tuning] from the audio threads without a lock.+ */+object Equalizer {++ /** The centres of the ten bands, an octave apart. */+ val FREQUENCIES = intArrayOf(31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000)++ /** How far a band, or the preamp, can be moved either way, in dB. */+ const val RANGE_DB = 12f++ /** What one output has been given. */+ @Serializable+ data class Curve(+ val enabled: Boolean = false,+ val gains: List<Float> = List(FREQUENCIES.size) { 0f },+ val preamp: Float = 0f,+ ) {+ val isFlat: Boolean get() = preamp == 0f && gains.all { it == 0f }++ /** Whether this sounds like [preset]: the bands, not the preamp. */+ fun matches(preset: List<Float>): Boolean =+ gains.size == preset.size &&+ gains.indices.all { kotlin.math.abs(gains[it] - preset[it]) < 0.05f }+ }++ /** A curve the listener named and kept. */+ @Serializable+ data class Preset(val id: String, val name: String, val gains: List<Float>)++ /** What the filters are running, or null for nothing: off, or flat. */+ @Volatile+ var tuning: Tuning? = null+ private set++ private val _curves = MutableStateFlow<Map<String, Curve>>(emptyMap())++ /** Every output given a curve, by [AudioRoute.Output.key]. */+ val curves: StateFlow<Map<String, Curve>> = _curves.asStateFlow()++ private val _names = MutableStateFlow<Map<String, String>>(emptyMap())++ /**+ * What each output was called when it was last seen, for listing the ones+ * not plugged in now. The key says what kind it is; see [AudioRoute].+ */+ val names: StateFlow<Map<String, String>> = _names.asStateFlow()++ private val _presets = MutableStateFlow<List<Preset>>(emptyList())++ /** The listener's own presets; the built-in ones are [BuiltInEqPresets]. */+ val presets: StateFlow<List<Preset>> = _presets.asStateFlow()++ private var prefs: android.content.SharedPreferences? = null++ private val json = Json { ignoreUnknownKeys = true }++ fun load(context: Context) {+ if (prefs != null) return+ val store = context.applicationContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)+ prefs = store+ _curves.value = store.getString(KEY_CURVES, null)+ ?.let { runCatching { json.decodeFromString(curvesSerializer, it) }.getOrNull() }+ .orEmpty()+ .mapValues { (_, curve) -> curve.normalised() }+ _names.value = store.getString(KEY_NAMES, null)+ ?.let { runCatching { json.decodeFromString(namesSerializer, it) }.getOrNull() }+ .orEmpty()+ _presets.value = store.getString(KEY_PRESETS, null)+ ?.let { runCatching { json.decodeFromString(presetsSerializer, it) }.getOrNull() }+ .orEmpty()++ AudioRoute.start(context)+ AudioRoute.onChange { output -> seen(output) }+ seen(AudioRoute.current.value)+ }++ /** The curve for [key], flat and off when it has none. */+ fun curveFor(key: String): Curve = _curves.value[key] ?: Curve()++ fun setEnabled(key: String, enabled: Boolean) = edit(key) { it.copy(enabled = enabled) }++ fun setGain(key: String, band: Int, db: Float) = edit(key) { curve ->+ val gains = curve.gains.toMutableList()+ if (band !in gains.indices) return@edit curve+ gains[band] = db.coerceIn(-RANGE_DB, RANGE_DB).snapped()+ // Moving a band is asking to hear it.+ curve.copy(gains = gains, enabled = true)+ }++ fun setPreamp(key: String, db: Float) = edit(key) {+ it.copy(preamp = db.coerceIn(-RANGE_DB, RANGE_DB).snapped())+ }++ fun applyPreset(key: String, gains: List<Float>) = edit(key) {+ it.copy(gains = gains.map { g -> g.coerceIn(-RANGE_DB, RANGE_DB) }, enabled = true)+ }++ fun reset(key: String) = edit(key) { Curve(enabled = it.enabled) }++ fun savePreset(name: String, gains: List<Float>) {+ val preset = Preset(+ id = java.util.UUID.randomUUID().toString(),+ name = name.trim(),+ gains = gains,+ )+ _presets.value = _presets.value + preset+ writePresets()+ }++ fun deletePreset(id: String) {+ _presets.value = _presets.value.filterNot { it.id == id }+ writePresets()+ }++ /** Forgets an output that is not plugged in, curve and name both. */+ fun forget(key: String) {+ if (key == AudioRoute.current.value.key) return+ _curves.value = _curves.value - key+ _names.value = _names.value - key+ writeCurves()+ prefs?.edit()?.putString(KEY_NAMES, json.encodeToString(namesSerializer, _names.value))?.apply()+ }++ private fun edit(key: String, change: (Curve) -> Curve) {+ val before = curveFor(key)+ val after = change(before)+ if (after == before) return+ _curves.value = _curves.value + (key to after)+ writeCurves()+ if (key == AudioRoute.current.value.key) retune()+ }++ /** An output has come into use: remember what it is called, and follow it. */+ private fun seen(output: AudioRoute.Output) {+ if (output.name.isNotEmpty() && _names.value[output.key] != output.name) {+ _names.value = _names.value + (output.key to output.name)+ prefs?.edit()?.putString(KEY_NAMES, json.encodeToString(namesSerializer, _names.value))?.apply()+ }+ retune()+ }++ private fun retune() {+ val curve = curveFor(AudioRoute.current.value.key)+ tuning = if (curve.enabled && !curve.isFlat) Tuning(curve.gains.toFloatArray(), curve.preamp) else null+ }++ private fun writeCurves() {+ prefs?.edit()?.putString(KEY_CURVES, json.encodeToString(curvesSerializer, _curves.value))?.apply()+ }++ private fun writePresets() {+ prefs?.edit()?.putString(KEY_PRESETS, json.encodeToString(presetsSerializer, _presets.value))?.apply()+ }++ /** A curve saved with a different number of bands is read as flat. */+ private fun Curve.normalised(): Curve =+ if (gains.size == FREQUENCIES.size) this else copy(gains = List(FREQUENCIES.size) { 0f })++ /** Half a decibel is finer than anyone hears, and keeps the numbers readable. */+ private fun Float.snapped(): Float = (this * 2f).roundToInt() / 2f++ private val curvesSerializer = MapSerializer(String.serializer(), Curve.serializer())+ private val namesSerializer = MapSerializer(String.serializer(), String.serializer())+ private val presetsSerializer = ListSerializer(Preset.serializer())++ private const val FILE_NAME = "equalizer"+ private const val KEY_CURVES = "curves"+ private const val KEY_NAMES = "names"+ private const val KEY_PRESETS = "presets"++ /**+ * One curve, as the filters need it.+ *+ * Immutable, so the audio threads can be handed a new one without a lock:+ * a filter notices it has changed by identity and works its coefficients+ * out again.+ */+ class Tuning(val gains: FloatArray, val preampDb: Float) {++ /**+ * What the whole signal is multiplied by before the bands.+ *+ * The preamp, less the curve's highest point. A boost can only add+ * level, and a song mastered to within a fraction of full scale has+ * none to give: six decibels of bass on top of it is six decibels of+ * clipping. Lowering everything by the most the curve raises anything+ * keeps the peaks where they were. Equalisers that do not do this sound+ * louder in the shop and break up on the first loud chorus.+ */+ val inputGain: Double = 10.0.pow((preampDb - headroom(gains)) / 20.0)+ }++ /** The highest point of [gains]' response, in dB, never below zero. */+ fun headroom(gains: FloatArray): Float {+ var peak = 0.0+ var f = 20.0+ while (f <= 20000.0) {+ peak = maxOf(peak, responseDb(gains, f, REFERENCE_RATE))+ f *= 1.05+ }+ return peak.toFloat()+ }++ /**+ * The curve's level at [frequency], the bands added together as the+ * filters will add them: for the drawing, and for [headroom].+ */+ fun responseDb(gains: FloatArray, frequency: Double, sampleRate: Int = REFERENCE_RATE): Double {+ val w = 2.0 * PI * frequency / sampleRate+ val cosW = cos(w)+ val cos2W = cos(2 * w)+ val sinW = sin(w)+ val sin2W = sin(2 * w)+ var total = 0.0+ for (band in FREQUENCIES.indices) {+ val c = Biquad.peaking(FREQUENCIES[band].toDouble(), gains[band].toDouble(), sampleRate) ?: continue+ // H(e^jw) = (b0 + b1 e^-jw + b2 e^-2jw) / (1 + a1 e^-jw + a2 e^-2jw)+ val numRe = c.b0 + c.b1 * cosW + c.b2 * cos2W+ val numIm = -(c.b1 * sinW + c.b2 * sin2W)+ val denRe = 1.0 + c.a1 * cosW + c.a2 * cos2W+ val denIm = -(c.a1 * sinW + c.a2 * sin2W)+ val magnitude = sqrt((numRe * numRe + numIm * numIm) / (denRe * denRe + denIm * denIm))+ total += 20.0 * log10(magnitude)+ }+ return total+ }++ private const val REFERENCE_RATE = 48000+}++/** One band's coefficients, normalised so a0 is one. */+internal class Biquad(val b0: Double, val b1: Double, val b2: Double, val a1: Double, val a2: Double) {+ companion object {+ /** An octave wide: neighbouring bands meet without a dip or a bump between them. */+ private const val Q = 1.41++ /**+ * A peaking filter, from the Audio EQ Cookbook.+ *+ * Null for a band at zero, which is no filter at all, and for one too+ * near the top of what [sampleRate] can carry: at 22 kHz a 16 kHz bell+ * has no room either side and bends the whole top octave.+ */+ fun peaking(frequency: Double, gainDb: Double, sampleRate: Int): Biquad? {+ if (gainDb == 0.0 || frequency >= sampleRate * 0.45) return null+ val a = 10.0.pow(gainDb / 40.0)+ val w0 = 2.0 * PI * frequency / sampleRate+ val alpha = sin(w0) / (2.0 * Q)+ val cosW0 = cos(w0)+ val a0 = 1.0 + alpha / a+ return Biquad(+ b0 = (1.0 + alpha * a) / a0,+ b1 = -2.0 * cosW0 / a0,+ b2 = (1.0 - alpha * a) / a0,+ a1 = -2.0 * cosW0 / a0,+ a2 = (1.0 - alpha / a) / a0,+ )+ }+ }+}++/**+ * The bands themselves, run over one stream of sixteen-bit PCM.+ *+ * One per stream, because each band remembers the last two samples of every+ * channel it has filtered; two players sharing one would hear each other's+ * history. Reads [Equalizer.tuning] on every packet, so a curve moved while a+ * song plays is heard within the packet.+ */+class EqualizerFilter {++ private var tuning: Equalizer.Tuning? = null+ private var sampleRate = 0+ private var channels = 0+ private var bands: Array<Biquad> = emptyArray()++ /** Two values per band per channel: transposed direct form II. */+ private var state = DoubleArray(0)++ /** Whether there is anything to do, without touching the audio. */+ val isActive: Boolean get() = Equalizer.tuning != null++ /** In place, on [sizeInBytes] bytes of interleaved little-endian PCM. */+ fun apply(data: ByteBuffer, sizeInBytes: Int, channels: Int, sampleRate: Int) {+ val wanted = Equalizer.tuning+ if (wanted == null) {+ if (tuning != null) {+ tuning = null+ state.fill(0.0)+ }+ return+ }+ if (channels <= 0 || sampleRate <= 0) return+ if (wanted !== tuning || sampleRate != this.sampleRate || channels != this.channels) {+ configure(wanted, sampleRate, channels)+ }++ val shorts = data.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+ val samples = minOf(sizeInBytes / 2, shorts.limit())+ val gain = wanted.inputGain+ val count = bands.size+ val z = state+ var i = 0+ while (i + channels <= samples) {+ for (c in 0 until channels) {+ var x = shorts.get(i + c) * gain+ var s = c * 2+ for (b in 0 until count) {+ val f = bands[b]+ val y = f.b0 * x + z[s]+ z[s] = f.b1 * x - f.a1 * y + z[s + 1]+ z[s + 1] = f.b2 * x - f.a2 * y+ x = y+ s += channels * 2+ }+ val out = when {+ x > Short.MAX_VALUE -> Short.MAX_VALUE.toInt()+ x < Short.MIN_VALUE -> Short.MIN_VALUE.toInt()+ else -> x.roundToInt()+ }+ shorts.put(i + c, out.toShort())+ }+ i += channels+ }+ }++ private fun configure(wanted: Equalizer.Tuning, sampleRate: Int, channels: Int) {+ val fresh = Equalizer.FREQUENCIES.indices.mapNotNull { band ->+ Biquad.peaking(+ Equalizer.FREQUENCIES[band].toDouble(),+ wanted.gains[band].toDouble(),+ sampleRate,+ )+ }.toTypedArray()+ // The history carries over when only the curve moved: thrown away, the+ // filters would start from silence mid-song and click. A different+ // stream, or a different number of bands, has no history worth keeping.+ val sameShape = sampleRate == this.sampleRate && channels == this.channels &&+ fresh.size == bands.size+ if (!sameShape) state = DoubleArray(fresh.size * channels * 2)+ bands = fresh+ tuning = wanted+ this.sampleRate = sampleRate+ this.channels = channels+ }+}++/**+ * The curves everyone gets, by the name of the string that names them.+ *+ * Starting points rather than corrections: no preset knows the headphones it+ * is played on, and the point of a curve per output is that the listener moves+ * from one of these to what their own pair needs.+ */+val BuiltInEqPresets: List<Pair<Int, List<Float>>> = listOf(+ dev.lelonio.square.R.string.eq_flat to listOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f),+ dev.lelonio.square.R.string.eq_bass_boost to listOf(6f, 5f, 4f, 2f, 0.5f, 0f, 0f, 0f, 0f, 0f),+ dev.lelonio.square.R.string.eq_bass_reducer to listOf(-6f, -5f, -4f, -2f, -0.5f, 0f, 0f, 0f, 0f, 0f),+ dev.lelonio.square.R.string.eq_treble_boost to listOf(0f, 0f, 0f, 0f, 0f, 0.5f, 2f, 3.5f, 5f, 6f),+ dev.lelonio.square.R.string.eq_treble_reducer to listOf(0f, 0f, 0f, 0f, 0f, -0.5f, -2f, -3.5f, -5f, -6f),+ dev.lelonio.square.R.string.eq_vocal to listOf(-2f, -2f, -1f, 1f, 3f, 4f, 3.5f, 1.5f, 0f, -1f),+ dev.lelonio.square.R.string.eq_spoken to listOf(-4f, -3f, -1.5f, 0.5f, 2.5f, 3.5f, 4f, 2.5f, 0.5f, -2f),+ dev.lelonio.square.R.string.eq_loudness to listOf(5f, 4f, 2f, 0f, -1f, -1f, 0f, 2f, 4f, 5f),+ dev.lelonio.square.R.string.eq_rock to listOf(4.5f, 3.5f, 2f, 0.5f, -1f, -1f, 0.5f, 2f, 3f, 4f),+ dev.lelonio.square.R.string.eq_pop to listOf(-1f, 0f, 1.5f, 3f, 4f, 3f, 1.5f, 0f, -0.5f, -1f),+ dev.lelonio.square.R.string.eq_hip_hop to listOf(5f, 4.5f, 2f, 2.5f, -1f, -1f, 1f, 0f, 1.5f, 2.5f),+ dev.lelonio.square.R.string.eq_electronic to listOf(4.5f, 4f, 1.5f, 0f, -2f, 1.5f, 0.5f, 1f, 3.5f, 4.5f),+ dev.lelonio.square.R.string.eq_classical to listOf(4f, 3f, 2f, 1f, -1f, -1f, 0f, 2f, 3f, 4f),+ dev.lelonio.square.R.string.eq_jazz to listOf(3f, 2f, 1f, 2f, -1.5f, -1.5f, 0f, 1f, 2f, 3f),+ dev.lelonio.square.R.string.eq_acoustic to listOf(4f, 4f, 3f, 1f, 2f, 1.5f, 3f, 3.5f, 3f, 2f),+)diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.ktindex ec7777e..69c00e6 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt@@ -1637,6 +1637,21 @@ class PlaybackService : MediaLibraryService() {)) {savePlayback()+ recordEpisode()+ }+ }++ // An episode that ran into the next one was heard to the end.+ override fun onMediaItemTransition(+ mediaItem: androidx.media3.common.MediaItem?,+ reason: Int,+ ) {+ val left = episodePlaying+ episodePlaying = mediaItem?.mediaId+ if (left != null && left != mediaItem?.mediaId &&+ reason == androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_AUTO+ ) {+ (application as dev.lelonio.square.SquareApplication).episodeProgress.finished(left)}}})@@ -1645,7 +1660,10 @@ class PlaybackService : MediaLibraryService() {saveJob = scope.launch {while (true) {delay(SAVE_INTERVAL_MS)- if (player.isPlaying) savePlayback()+ if (player.isPlaying) {+ savePlayback()+ recordEpisode()+ }}}}@@ -1768,6 +1786,17 @@ class PlaybackService : MediaLibraryService() {* the queue knows the pre-shuffle order and the permutation on top of it;* the timeline exposes just the current sequence.*/+ /** What was playing at the last transition, for marking it heard; see observeForSaving. */+ private var episodePlaying: String? = null++ /** Where the episode playing has got to; see EpisodeProgress. */+ private fun recordEpisode() {+ val uri = player.currentMediaItem?.mediaId ?: return+ if (!uri.startsWith("spotify:episode:")) return+ (application as dev.lelonio.square.SquareApplication).episodeProgress+ .record(uri, player.currentPosition, player.duration.coerceAtLeast(0))+ }+private fun savePlayback() {// A backend with no PlayQueue behind it — the YouTube one — is saved off// the Media3 timeline instead. That loses the pre-shuffle order, whichdiff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.ktindex 0bc5b9e..ed9de32 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt@@ -328,6 +328,16 @@ class MainActivity : ComponentActivity() {) {val player = controller ?: return+ // An episode picks up where the listener left it, from whichever list+ // it was tapped in; see EpisodeProgress.+ val tapped = tracks.getOrNull(index)+ @Suppress("NAME_SHADOWING")+ val positionMs = if (positionMs == 0L && tapped?.isEpisode == true) {+ (application as dev.lelonio.square.SquareApplication).episodeProgress.resumeFor(tapped)+ } else {+ positionMs+ }+// Offline, the queue is only what can actually be played.//// The rows for the rest are already inert, so nothing here is beingdiff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 26173f0..ebef582 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -101,6 +101,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {PLAYLIST(R.string.playlist),ALBUM(R.string.album),ARTIST(R.string.artist),+ /** A podcast: its episodes are the page's list. */+ SHOW(R.string.podcast),}/**@@ -1176,6 +1178,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val open: Boolean = false,/** The track the sheet will add, captured when it opens. */val trackUri: String? = null,+ /**+ * Every track to add, when the sheet adds a whole record or list+ * rather than one song; empty for one song.+ */+ val batch: List<String> = emptyList(),val trackTitle: String = "",val playlists: List<CatalogPlaylist> = emptyList(),/** URI of the playlist currently being written to. */@@ -1266,6 +1273,80 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}+ /**+ * The same sheet for a whole album or list: every one of its songs goes+ * into the playlist picked, in order. Nothing is taken out by picking a+ * playlist twice, as one song is: with dozens of them that would be a+ * second tap undoing a first by surprise.+ */+ fun openAddAllToPlaylist(tracks: List<CatalogTrack>, title: String) {+ val backend = container.activeBackend+ val uris = tracks.map { it.uri }.filter {+ if (backend.id == BackendId.SPOTIFY) it.startsWith("spotify:track:") || it.startsWith("spotify:episode:")+ else backend.owns(it)+ }.distinct()+ _addToPlaylist.value = AddToPlaylistState(+ open = true,+ trackUri = uris.firstOrNull(),+ batch = uris,+ trackTitle = title,+ playlists = if (backend.id == BackendId.SPOTIFY) {+ (_state.value as? UiState.Ready)?.playlists.orEmpty()+ } else {+ emptyList()+ },+ error = when {+ uris.isEmpty() -> string(R.string.track_cannot_be_added)+ backend.id == BackendId.SPOTIFY && !container.webApi.isReady && !container.tokenStore.isLoggedIn ->+ string(R.string.connect_app_in_settings)+ backend.id != BackendId.SPOTIFY && !backend.canEditPlaylists ->+ string(R.string.track_cannot_be_added)+ else -> null+ },+ )+ if (backend.id != BackendId.SPOTIFY && uris.isNotEmpty()) viewModelScope.launch {+ val lists = runCatching { backend.writablePlaylists() }.getOrDefault(emptyList())+ if (_addToPlaylist.value.batch == uris) _addToPlaylist.value = _addToPlaylist.value.copy(playlists = lists)+ }+ }++ /** [openAddAllToPlaylist]'s songs, into [playlist]. */+ private fun addAllToPlaylist(playlist: CatalogPlaylist, uris: List<String>) {+ _addToPlaylist.value = _addToPlaylist.value.copy(busy = playlist.uri, done = null, removed = null, error = null)+ viewModelScope.launch {+ runCatching {+ when {+ // Liked Songs: the account's library, kept in one request.+ playlist.uri.endsWith(":collection") ->+ check(container.gateway.setInLibrary(uris, keep = true)) { "the gateway refused" }+ playlist.uri.startsWith("spotify:playlist:") -> {+ val id = playlist.uri.substringAfterLast(':')+ // A hundred a request is the most Spotify takes.+ uris.chunked(100).forEach { chunk ->+ container.api.addToPlaylist(id, AddTracksRequestDto(chunk))+ }+ }+ else -> uris.forEach { container.activeBackend.addToPlaylist(playlist.uri, it) }+ }+ }+ .onSuccess {+ _addToPlaylist.value = _addToPlaylist.value.copy(busy = null, done = playlist.name)+ _inPlaylists.value = _inPlaylists.value + uris+ invalidateContext(playlist.uri)+ if (playlist.uri.endsWith(":collection")) uris.forEach(container.likedStore::add)+ }+ .onFailure {+ android.util.Log.e(TAG, "adding a whole list failed: ${chain(it)}", it)+ val forbidden = describe(it).contains("403")+ if (forbidden) _webApi.value = _webApi.value.copy(expired = true)+ _addToPlaylist.value = _addToPlaylist.value.copy(+ busy = null,+ error = if (forbidden) string(R.string.permission_needed) else string(R.string.add_failed, playlist.name),+ )+ }+ }+ }+/*** A file on this phone, or a playlist's local entry, put into a playlist.*@@ -1325,6 +1406,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {if (current.busy != null) returnval id = playlist.uri.substringAfterLast(':')+ if (current.batch.isNotEmpty()) {+ addAllToPlaylist(playlist, current.batch)+ return+ }+if (playlist.uri.startsWith("spotify:playlist:") &&(LocalLibrary.isLocal(trackUri) || LocalLibrary.isSpotifyLocal(trackUri))) {@@ -1534,6 +1620,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {artist = string(R.string.artist),album = string(R.string.album),playlist = string(R.string.playlist),+ podcast = string(R.string.podcast),),)}@@ -1649,6 +1736,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {artist = string(R.string.artist),album = string(R.string.album),playlist = string(R.string.playlist),+ podcast = string(R.string.podcast),),offset = searchOffset,)@@ -1965,7 +2053,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {videoLookup?.cancel()_videoFileId.value = null_videoMode.value = false- if (trackUri == null || !trackUri.startsWith("spotify:track:")) return+ if (trackUri == null ||+ !(trackUri.startsWith("spotify:track:") || trackUri.startsWith("spotify:episode:"))+ ) return// Offline there is no video to offer: it is streamed, and the lookup// itself is a request. Leaving the answer null is what takes the button// off the player — the button is drawn from having one.@@ -2376,6 +2466,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {// also what clears Spotify's off the screen when the source changes.loadSavedAlbums()loadFollowedArtists()+ loadSavedShows()return@launch}@@ -2437,6 +2528,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {loadFriends()loadFollowedArtists()loadSavedAlbums()+ loadSavedShows()// The pictures of whatever is downloaded, while there is a// connection to fetch them with.keepPageCovers()@@ -2696,6 +2788,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {fun hasRadio(trackUri: String): Boolean =trackUri.startsWith("spotify:track:") || isYouTubeSong(trackUri)+ /** A YouTube Music show, which opens as a list whose id starts "MPSP". */+ private fun isYouTubePodcast(uri: String) =+ uri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.PLAYLIST_PREFIX + "MPSP")+private fun isYouTubeSong(uri: String) =uri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.TRACK_PREFIX) ||uri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.VIDEO_PREFIX)@@ -2866,6 +2962,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {* than showing a state nobody checked.*/private suspend fun savedState(uri: String): Boolean? {+ // A YouTube Music podcast: kept when it is among the saved ones.+ if (isYouTubePodcast(uri)) {+ if (_savedShows.value.isEmpty()) _savedShows.value = runCatching { readSavedShows() }.getOrDefault(emptyList())+ return _savedShows.value.any { it.uri == uri }+ }if (!container.webApi.isReady && !container.tokenStore.isLoggedIn) return nullval id = uri.substringAfterLast(':')return runCatching {@@ -2899,6 +3000,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {_playlist.value = _playlist.value.copy(saved = !was)runCatching {when {+ // A podcast is kept through the gateway, as Spotify's own+ // player keeps one: the Web API asks for an application+ // registered with permission for it, which almost nobody has.+ dev.lelonio.square.data.SpotifyPodcasts.isShow(uri) ->+ check(container.gateway.setInLibrary(listOf(uri), keep = !was)) { "the gateway refused" }++ isYouTubePodcast(uri) ->+ com.metrolist.innertube.YouTube.savePodcast(+ uri.removePrefix(dev.lelonio.square.backend.youtube.YouTubeBackend.PLAYLIST_PREFIX),+ save = !was,+ ).getOrThrow()+uri.startsWith("spotify:album:") ->if (was) container.api.removeAlbums(id) else container.api.saveAlbums(id)@@ -2909,7 +3022,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {.onSuccess {// The library is what this button is about, so it is the library// that has to show the answer.- refresh()+ if (kindOf(uri) == DetailKind.SHOW || isYouTubePodcast(uri)) loadSavedShows() else refresh()}.onFailure {android.util.Log.e(TAG, "keeping failed: ${chain(it)}", it)@@ -2955,6 +3068,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {DetailKind.ARTIST -> if (container.webApi.isReady) container.api.artist(id).name else nullDetailKind.ALBUM -> if (container.webApi.isReady) container.api.album(id).name else nullDetailKind.PLAYLIST -> if (container.webApi.isReady) container.api.playlist(id).name else null+ DetailKind.SHOW -> container.gateway.show(uri)+ ?.let(dev.lelonio.square.data.SpotifyPodcasts::parseShow)?.name}}.onFailure { android.util.Log.w(TAG, "no name for $uri: ${describe(it)}") }@@ -3667,7 +3782,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {kind = when (page.kind) {DetailKind.ALBUM -> DownloadStore.KIND_ALBUMDetailKind.ARTIST -> DownloadStore.KIND_ARTIST- DetailKind.PLAYLIST -> DownloadStore.KIND_PLAYLIST+ DetailKind.PLAYLIST, DetailKind.SHOW -> DownloadStore.KIND_PLAYLIST},),)@@ -4265,6 +4380,52 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}}+ } else if (kind == DetailKind.SHOW) {+ // A podcast: its page, then its episodes newest first. Read+ // again on every visit rather than trusted from the copy,+ // which is there to draw the page at once: a show gets new+ // episodes, and how far into each one the listener got is+ // part of what the list says.+ awaitEngine()+ val showAnswer = container.gateway.show(playlist.uri)+ val show = showAnswer?.let(dev.lelonio.square.data.SpotifyPodcasts::parseShow)+ if (show == null) {+ android.util.Log.w(TAG, "show ${playlist.uri} unreadable: ${showAnswer?.take(400)}")+ }+ if (show != null) {+ base = base.copy(+ name = base.name.ifEmpty { show.name },+ artworkUrl = show.artworkUrl ?: base.artworkUrl,+ description = show.description,+ byline = show.publisher,+ saved = show.saved ?: base.saved,+ )+ if (isActive && _playlist.value.uri == playlist.uri) {+ _playlist.value = _playlist.value.copy(+ name = base.name,+ artworkUrl = base.artworkUrl,+ description = base.description,+ byline = base.byline,+ saved = base.saved,+ )+ }+ }+ val episodes = readShow(playlist.uri, base.name) { read, more ->+ if (isActive && _playlist.value.uri == playlist.uri) {+ publishPlaylist(base.copy(tracks = read, loading = false, loadingMore = more))+ }+ }+ if (episodes != null) {+ contextCache[playlist.uri] = ContextCacheStore.Entry(+ tracks = episodes,+ snapshotId = null,+ savedAt = System.currentTimeMillis(),+ uri = playlist.uri,+ )+ container.contextCache.write(playlist.uri, episodes, null)+ } else if (cached.isEmpty()) {+ error("the show's episodes did not come back")+ }} else {val freshness = if (cached.isEmpty()) {Freshness.CHANGED@@ -4515,6 +4676,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {DetailKind.ARTIST -> if (container.webApi.isReady) container.api.artist(id).images.firstOrNull()?.url else nullDetailKind.ALBUM -> if (container.webApi.isReady) container.api.album(id).images.firstOrNull()?.url else nullDetailKind.PLAYLIST -> if (container.webApi.isReady) container.api.playlist(id).images.firstOrNull()?.url else null+ DetailKind.SHOW -> container.gateway.show(uri)+ ?.let(dev.lelonio.square.data.SpotifyPodcasts::parseShow)?.artworkUrl}}.onFailure { android.util.Log.w(TAG, "no cover for $uri: ${describe(it)}") }@@ -5736,6 +5899,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {artist = string(R.string.artist),album = string(R.string.album),playlist = string(R.string.playlist),+ podcast = string(R.string.podcast),),)}@@ -5813,6 +5977,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {artist = string(R.string.artist),album = string(R.string.album),playlist = string(R.string.playlist),+ podcast = string(R.string.podcast),),)}@@ -5883,6 +6048,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {artist = string(R.string.artist),album = string(R.string.album),playlist = string(R.string.playlist),+ podcast = string(R.string.podcast),),)}@@ -6135,6 +6301,106 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {.onFailure { android.util.Log.w(TAG, "saved albums unavailable: ${describe(it)}") }}+ private val _podcastShelves = MutableStateFlow<List<HomeShelf>>(emptyList())++ /** Spotify's own podcast home, for Home's chip of it; see [loadPodcastShelves]. */+ val podcastShelves: StateFlow<List<HomeShelf>> = _podcastShelves.asStateFlow()+ private val _podcastsLoading = MutableStateFlow(false)+ val podcastsLoading: StateFlow<Boolean> = _podcastsLoading.asStateFlow()+ private var podcastShelvesJob: Job? = null++ /** Once a session, when the chip is first chosen. */+ fun loadPodcastShelves() {+ if (podcastShelvesJob?.isActive == true || _podcastShelves.value.isNotEmpty()) return+ _podcastsLoading.value = true+ podcastShelvesJob = viewModelScope.launch {+ try {+ if (!awaitEngine()) return@launch+ val json = container.gateway.homeFacet(PODCASTS_FACET) ?: return@launch+ _podcastShelves.value = withContext(Dispatchers.Default) {+ dev.lelonio.square.data.SpotifyHome.parse(json, podcasts = true)+ }+ } finally {+ _podcastsLoading.value = false+ }+ }+ }++ private val _savedShows = MutableStateFlow<List<CatalogPlaylist>>(emptyList())++ /** The podcasts the account follows, for the library's chip of them. */+ val savedShows: StateFlow<List<CatalogPlaylist>> = _savedShows.asStateFlow()++ fun loadSavedShows() = viewModelScope.launch {+ _savedShows.value = runCatching { readSavedShows() }+ .onFailure { android.util.Log.w(TAG, "followed shows unavailable: ${describe(it)}") }+ .getOrDefault(emptyList())+ }++ /** From Spotify's library page for them, or whatever the source keeps. */+ private suspend fun readSavedShows(): List<CatalogPlaylist> {+ if (container.activeBackend.id != BackendId.SPOTIFY) return container.activeBackend.savedShows()+ if (!awaitEngine()) return emptyList()+ val gathered = mutableListOf<CatalogPlaylist>()+ while (gathered.size < MAX_SHOWS) {+ val page = container.gateway.followedShows(offset = gathered.size)+ ?.let(dev.lelonio.square.data.SpotifyPodcasts::parseFollowed)+ ?: break+ gathered += page+ if (page.isEmpty()) break+ }+ return gathered.distinctBy { it.uri }+ }++ private val _newEpisodes = MutableStateFlow<List<CatalogTrack>>(emptyList())++ /** What the followed podcasts put out lately, newest first; see [loadNewEpisodes]. */+ val newEpisodes: StateFlow<List<CatalogTrack>> = _newEpisodes.asStateFlow()+ private var newEpisodesJob: Job? = null+ private var newEpisodesAt = 0L++ /**+ * The New tab's row of episodes, read again at most every few minutes.+ *+ * On Spotify there is no one list of them: each followed show is asked for+ * its newest few, a handful at a time, and what came out in the last weeks+ * is kept. YouTube Music keeps such a list itself.+ */+ fun loadNewEpisodes() {+ if (newEpisodesJob?.isActive == true) return+ if (System.currentTimeMillis() - newEpisodesAt < NEW_EPISODES_FRESH_MS) return+ newEpisodesJob = viewModelScope.launch {+ val episodes = runCatching {+ if (container.activeBackend.id != BackendId.SPOTIFY) {+ container.activeBackend.newEpisodes()+ } else {+ val shows = _savedShows.value.ifEmpty { readSavedShows().also { _savedShows.value = it } }+ val since = java.time.Instant.now().minus(java.time.Duration.ofDays(NEW_EPISODES_DAYS)).toString()+ withContext(Dispatchers.IO) {+ shows.take(MAX_SHOWS_ASKED).chunked(SHOWS_AT_ONCE).flatMap { batch ->+ coroutineScope {+ batch.map { show ->+ async {+ container.gateway.showEpisodes(show.uri, 0, EPISODES_A_SHOW)+ ?.let { dev.lelonio.square.data.SpotifyPodcasts.parseEpisodes(it, show.name) }+ ?.tracks.orEmpty()+ }+ }.awaitAll().flatten()+ }+ }+ }+ .filter { (it.releasedAt ?: "") >= since }+ .sortedByDescending { it.releasedAt }+ .take(NEW_EPISODES)+ }.map(container.episodeProgress::apply)+ }+ .onFailure { android.util.Log.w(TAG, "new episodes unavailable: ${describe(it)}") }+ .getOrNull() ?: return@launch+ _newEpisodes.value = episodes+ newEpisodesAt = System.currentTimeMillis()+ }+ }+private val _followedArtists = MutableStateFlow<List<SearchItem>>(emptyList())/** The artists this account follows, for the library. */@@ -6172,6 +6438,34 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}+ /**+ * A show's episodes, newest first, up to [SHOW_EPISODES_LIMIT].+ *+ * Not to the end, as a playlist is read: a daily show has thousands, and a+ * page of the last few hundred is what anybody scrolls. Null when the first+ * page would not come back.+ */+ private suspend fun readShow(+ uri: String,+ showName: String,+ onPage: (List<CatalogTrack>, Boolean) -> Unit,+ ): List<CatalogTrack>? {+ val loaded = mutableListOf<CatalogTrack>()+ var offset = 0+ while (loaded.size < SHOW_EPISODES_LIMIT) {+ val page = container.gateway.showEpisodes(uri, offset)+ ?.let { dev.lelonio.square.data.SpotifyPodcasts.parseEpisodes(it, showName) }+ ?: return loaded.takeIf { it.isNotEmpty() }+ loaded += page.tracks.map(container.episodeProgress::apply)+ val next = page.nextOffset+ val more = next != null && next > offset && loaded.size < SHOW_EPISODES_LIMIT+ onPage(loaded.toList(), more)+ if (!more) break+ offset = next!!+ }+ return loaded+ }+private fun kindOf(uri: String): DetailKind = when {uri.startsWith("spotify:artist:") -> DetailKind.ARTIST// An artist on the other source is an artist too: the page they open on@@ -6179,6 +6473,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {uri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.ARTIST_PREFIX) ->DetailKind.ARTISTuri.startsWith("spotify:album:") -> DetailKind.ALBUM+ dev.lelonio.square.data.SpotifyPodcasts.isShow(uri) -> DetailKind.SHOWelse -> DetailKind.PLAYLIST}@@ -6258,6 +6553,23 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {/** How many detail pages back the in-screen history holds. */const val PAGE_HISTORY = 12+ /** Spotify's name for its home's podcast chip. */+ const val PODCASTS_FACET = "podcasts-chip"++ /** Followed podcasts read, and how many of them asked for new episodes, how many at once. */+ const val MAX_SHOWS = 500+ const val MAX_SHOWS_ASKED = 60+ const val SHOWS_AT_ONCE = 6+ const val EPISODES_A_SHOW = 5++ /** What counts as new, how much of it the tab shows, and how long it is believed. */+ const val NEW_EPISODES_DAYS = 21L+ const val NEW_EPISODES = 30+ const val NEW_EPISODES_FRESH_MS = 10 * 60 * 1000L++ /** How many of a show's episodes a page reads; see [readShow]. */+ const val SHOW_EPISODES_LIMIT = 300+/** How long a home row gets before it stops being worth scrolling. */const val FEED_ROW = 12diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex 3768576..c7d9853 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -696,6 +696,10 @@ fun SquareApp(val addFriendState by viewModel.addFriendState.collectAsStateWithLifecycle()val followedArtists by viewModel.followedArtists.collectAsStateWithLifecycle()val savedAlbums by viewModel.savedAlbums.collectAsStateWithLifecycle()+ val savedShows by viewModel.savedShows.collectAsStateWithLifecycle()+ val podcastShelves by viewModel.podcastShelves.collectAsStateWithLifecycle()+ val podcastsLoading by viewModel.podcastsLoading.collectAsStateWithLifecycle()+ val newEpisodes by viewModel.newEpisodes.collectAsStateWithLifecycle()val videoFileId by viewModel.videoFileId.collectAsStateWithLifecycle()val spotifyVideoOn by dev.lelonio.square.backend.spotify.SpotifyVideoMode.enabled.collectAsStateWithLifecycle()@@ -1685,6 +1689,23 @@ fun SquareApp(youtubeHome = youtubeHome,shelves = homeShelves,shelvesLoading = homeShelvesLoading,+ podcastShelves = podcastShelves,+ podcastsLoading = podcastsLoading,+ onWantPodcasts = viewModel::loadPodcastShelves,+ onPlayEpisode = { entry, label ->+ onPlay(+ listOf(+ dev.lelonio.square.data.CatalogTrack(+ uri = entry.uri,+ name = entry.name,+ artist = entry.subtitle.orEmpty(),+ album = entry.subtitle.orEmpty(),+ artworkUrl = entry.artworkUrl,+ ),+ ),+ 0, null, false, label, 0L,+ )+ },onPlayTrending = { tracks, index ->onPlay(tracks, index, null, false, trendingLabel, 0L)},@@ -1719,11 +1740,16 @@ fun SquareApp(// gets that page; the one below is built out of// Spotify's gateway and has nothing to show for any// other catalogue.+ LaunchedEffect(backend) { viewModel.loadNewEpisodes() }if (backend != dev.lelonio.square.backend.BackendId.SPOTIFY) {LaunchedEffect(backend) { viewModel.loadSourceNew() }+ val episodesTitle = stringResource(R.string.new_episodes)dev.lelonio.square.ui.home.SourceRowsPage(title = newLabel,- rows = sourceNew.rows,+ rows = listOfNotNull(+ dev.lelonio.square.backend.HomeRow(title = episodesTitle, tracks = newEpisodes)+ .takeIf { newEpisodes.isNotEmpty() },+ ) + sourceNew.rows,loading = sourceNew.loading,contentPadding = listPadding,onPlay = { tracks, index ->@@ -1751,6 +1777,10 @@ fun SquareApp(onSongMenu = { track ->trackMenu = TrackMenuRequest(track = track, removable = false)},+ episodes = newEpisodes,+ onPlayEpisode = { tracks, index ->+ onPlay(tracks, index, null, false, newLabel, 0L)+ },onOpen = { item ->viewModel.openContext(item.uri,@@ -1845,7 +1875,7 @@ fun SquareApp(onPlayTrack = { tracks, index ->val chosen = tracks.getOrNull(index)chosen?.let(viewModel::recordSearchPlay)- if (chosen != null && !offlineNow && viewModel.hasRadio(chosen.uri)) {+ if (chosen != null && !offlineNow && !chosen.isEpisode && viewModel.hasRadio(chosen.uri)) {// The song, and then songs like it.//// The rest of the results are not a@@ -1922,6 +1952,7 @@ fun SquareApp(},artists = followedArtists,albums = savedAlbums,+ podcasts = savedShows,onRetryOnline = viewModel::retryOnline,signInHint = backend == dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC &&youtubeAccountName == null,@@ -2066,6 +2097,10 @@ fun SquareApp(},contentPadding = listPadding,nowPlayingUri = playback.mediaId,+ nowPlaying = playback.isPlaying,+ onTogglePlay = {+ player?.let { if (it.isPlaying) it.pause() else it.play() }+ },// One route holds every detail page, so// back is the screen's own history first// and the navigation stack only once that@@ -3406,6 +3441,18 @@ fun SquareApp(viewModel.togglePinned(shownPlaylist.uri)playlistMenu = null}+ // The whole record, or the whole list, into a+ // playlist: what the open page holds, in its order.+ if (playlist.uri == shownPlaylist.uri && playlist.tracks.isNotEmpty() &&+ (playlist.kind == MainViewModel.DetailKind.ALBUM ||+ playlist.kind == MainViewModel.DetailKind.PLAYLIST)+ ) TrackSheetAction(+ stringResource(R.string.add_to_playlist),+ PhosphorIcons.Regular.Plus,+ ) {+ playlistMenu = null+ viewModel.openAddAllToPlaylist(playlist.tracks, playlist.name)+ }// Liked Songs is Spotify's own list: it can be pinned// like any other row, but there is no name to change// and no way to delete it. Nor is anything editable ondiff --git a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.ktindex 1ccb446..cb61dc7 100644--- a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt@@ -83,6 +83,9 @@ fun NewScreen(onPlaySong: (List<CatalogTrack>, Int) -> Unit,/** The same menu every other list of songs in the app opens. */onSongMenu: (CatalogTrack) -> Unit,+ /** What the followed podcasts put out lately, newest first. */+ episodes: List<CatalogTrack> = emptyList(),+ onPlayEpisode: (List<CatalogTrack>, Int) -> Unit = { _, _ -> },) {// Not held for the followed artists: reading all of them takes seconds,// and the whole page stood behind a spinner for the one row that needs it.@@ -143,6 +146,15 @@ fun NewScreen(item(contentType = "songs") { SongPages(page.songs, onSongMenu, onPlaySong) }}+ // The listener's own shows, after the music: a page of what is new is+ // a page of what is new to them, and these are new to nobody else.+ if (episodes.isNotEmpty()) {+ item(contentType = "episodesHeading") {+ Heading(stringResource(R.string.new_episodes), more = true)+ }+ item(contentType = "episodes") { SongPages(episodes, onSongMenu, onPlayEpisode) }+ }+if (followed.albums.isNotEmpty() || followed.error != null || followed.loaded || followed.loading) {item(key = "followedHeading", contentType = "shelfHeading") {Heading(stringResource(R.string.new_from_followed_artists))@@ -446,7 +458,7 @@ private fun SongRow(track: CatalogTrack, onMenu: () -> Unit, onClick: () -> Unitoverflow = TextOverflow.Ellipsis,)Text(- track.artist,+ if (track.isEpisode) dev.lelonio.square.ui.library.episodeLine(track, showName = true) else track.artist,style = MaterialTheme.typography.bodySmall,color = InkDim,maxLines = 1,diff --git a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.ktindex 86b2ccf..76c02a9 100644--- a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt@@ -108,8 +108,12 @@ import java.util.Calendarprivate enum class Feed(@StringRes val label: Int, val chip: dev.lelonio.square.data.TabContents.Chip?) {ALL(R.string.feed_all, null),FOR_YOU(R.string.feed_for_you, dev.lelonio.square.data.TabContents.Chip.FOR_YOU),- DISCOVER(R.string.feed_discover, dev.lelonio.square.data.TabContents.Chip.DISCOVER),ARTISTS(R.string.artists, dev.lelonio.square.data.TabContents.Chip.ARTISTS),+ /**+ * Spotify's own podcast page rather than a part of this one: its shows+ * and episodes come from a home of their own, asked for when the chip is.+ */+ PODCASTS(R.string.podcasts, null),}/**@@ -179,6 +183,12 @@ fun HomeScreen(shelves: List<dev.lelonio.square.data.HomeShelf> = emptyList(),/** Spotify's shelves are on their way; their outline stands in until then. */shelvesLoading: Boolean = false,+ /** Spotify's podcast home, for the chip of it; asked for with [onWantPodcasts]. */+ podcastShelves: List<dev.lelonio.square.data.HomeShelf> = emptyList(),+ podcastsLoading: Boolean = false,+ onWantPodcasts: () -> Unit = {},+ /** An episode tile: played, not opened. */+ onPlayEpisode: (CatalogPlaylist, String) -> Unit = { _, _ -> },) {if (youtubeMode) {YouTubeHome(@@ -248,9 +258,10 @@ fun HomeScreen(listOf(Feed.ALL) + Feed.entries.filter { entry ->entry.chip != null &&shelves.any { dev.lelonio.square.data.TabContents.chipOf(it) == entry.chip }- }+ } + listOfNotNull(Feed.PODCASTS.takeIf { shelves.isNotEmpty() })}val filter = chips.firstOrNull { it.name == filterName } ?: Feed.ALL+ LaunchedEffect(filter) { if (filter == Feed.PODCASTS) onWantPodcasts() }// Read once here rather than inside the rows: the label travels// with the play so the player can say where the song came from,// and that is a plain string by the time it leaves this screen.@@ -411,27 +422,40 @@ fun HomeScreen(// placeholder the page arrived in two halves and shifted under// whatever was being read.run {- val visible = if (filter == Feed.ALL) shelves- else shelves.filter { dev.lelonio.square.data.TabContents.chipOf(it) == filter.chip }+ val visible = when (filter) {+ Feed.ALL -> shelves+ Feed.PODCASTS -> podcastShelves+ else -> shelves.filter { dev.lelonio.square.data.TabContents.chipOf(it) == filter.chip }+ }// Their outline while they come, and a fade as they land// rather than the rows appearing in one frame.- if (visible.isEmpty() && shelvesLoading && filter == Feed.ALL) {+ if (visible.isEmpty() &&+ ((shelvesLoading && filter == Feed.ALL) || (podcastsLoading && filter == Feed.PODCASTS))+ ) {items(SHELF_OUTLINES, key = { "shelf-outline-$it" }, contentType = { "skeleton" }) {Box(Modifier.animateItem(fadeInSpec = null, placementSpec = null, fadeOutSpec = tween(200))) {SkeletonSection(tileWidth = 152.dp, tileHeight = 152.dp)}}}- visible.forEach { shelf ->- item(key = "shelf-heading-${shelf.title}", contentType = "shelf") {+ // Keyed by place as well as title: Spotify can send two rows+ // with the same title, and a key used twice crashes the list.+ visible.forEachIndexed { index, shelf ->+ item(key = "shelf-heading-$index-${shelf.title}", contentType = "shelf") {Box(Modifier.animateItem(fadeInSpec = tween(320), placementSpec = null, fadeOutSpec = null)) {Heading(shelf.title)}}- item(key = "shelf-${shelf.title}", contentType = "shelf") {+ item(key = "shelf-$index-${shelf.title}", contentType = "shelf") {Box(Modifier.animateItem(fadeInSpec = tween(320), placementSpec = null, fadeOutSpec = null)) {Carousel(shelf.items, key = { it.uri }) { entry ->- PlaylistTile(entry) { onOpenPlaylist(entry) }+ PlaylistTile(entry) {+ if (dev.lelonio.square.data.SpotifyPodcasts.isEpisode(entry.uri)) {+ onPlayEpisode(entry, shelf.title)+ } else {+ onOpenPlaylist(entry)+ }+ }}}}diff --git a/app/src/main/java/dev/lelonio/square/ui/library/EpisodeRow.kt b/app/src/main/java/dev/lelonio/square/ui/library/EpisodeRow.ktnew file mode 100644index 0000000..1bd4f75--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/library/EpisodeRow.kt@@ -0,0 +1,194 @@+package dev.lelonio.square.ui.library++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.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.luminance+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.adamglin.PhosphorIcons+import com.adamglin.phosphoricons.Bold+import com.adamglin.phosphoricons.Fill+import com.adamglin.phosphoricons.bold.DotsThree+import com.adamglin.phosphoricons.fill.CheckCircle+import com.adamglin.phosphoricons.fill.Pause+import com.adamglin.phosphoricons.fill.Play+import dev.lelonio.square.R+import dev.lelonio.square.data.CatalogTrack+import dev.lelonio.square.ui.components.Artwork+import dev.lelonio.square.ui.glass.pressable++/**+ * One episode, as a card rather than a song's row.+ *+ * An episode is chosen differently from a song: by what it is about, by when+ * it came out, and by whether it was already heard. So the card carries what a+ * song's row has no room for — a couple of lines of what the show says about+ * it, how far in the listener got, and a mark on the ones heard to the end —+ * and the play button is a target of its own, the way Spotify lays these out.+ */+@Composable+internal fun EpisodeRow(+ episode: CatalogTrack,+ isCurrent: Boolean,+ /** Whether the one that is current is playing right now. */+ playing: Boolean,+ onClick: () -> Unit,+ onMenu: () -> Unit,+ /** Off on a show's own page, where every card is the same show. */+ showName: Boolean = false,+ unavailable: Boolean = false,+) {+ val shape = RoundedCornerShape(16.dp)+ val ink = MaterialTheme.colorScheme.onSurface+ val dim = MaterialTheme.colorScheme.onSurfaceVariant+ Column(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 2.dp)+ .clip(shape)+ .pressable(onClick, shape = shape, pressedScale = 0.985f, onLongClick = onMenu)+ .padding(horizontal = 12.dp, vertical = 12.dp)+ .alpha(if (unavailable) 0.38f else if (episode.played && !isCurrent) 0.72f else 1f),+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Artwork(+ url = episode.artworkUrl,+ title = episode.name,+ modifier = Modifier.size(60.dp),+ corner = 10.dp,+ decodeSize = 60.dp,+ )+ Column(+ Modifier+ .weight(1f)+ .padding(start = 14.dp),+ ) {+ Text(+ episode.name,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.SemiBold,+ color = ink,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ if (showName && episode.artist.isNotBlank()) {+ Text(+ episode.artist,+ style = MaterialTheme.typography.bodySmall,+ color = dim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 2.dp),+ )+ }+ }+ }++ if (episode.summary.isNotBlank()) {+ Text(+ episode.summary,+ style = MaterialTheme.typography.bodySmall,+ color = dim,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 10.dp),+ )+ }++ Row(+ Modifier+ .fillMaxWidth()+ .padding(top = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (episode.played) {+ Icon(+ PhosphorIcons.Fill.CheckCircle,+ contentDescription = null,+ tint = MaterialTheme.colorScheme.primary,+ modifier = Modifier.size(16.dp),+ )+ }+ Text(+ episodeLine(episode, showName = false),+ style = MaterialTheme.typography.labelMedium,+ color = dim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ val started = !episode.played && episode.resumeMs > 0 && episode.durationMs > 0+ if (started) {+ Box(+ Modifier+ .width(56.dp)+ .height(4.dp)+ .clip(RoundedCornerShape(2.dp))+ .background(dim.copy(alpha = 0.25f)),+ ) {+ Box(+ Modifier+ .fillMaxHeight()+ .fillMaxWidth((episode.resumeMs.toFloat() / episode.durationMs).coerceIn(0.03f, 1f))+ .background(MaterialTheme.colorScheme.primary),+ )+ }+ }+ Spacer(Modifier.weight(1f))+ Box(+ Modifier+ .size(36.dp)+ .clip(CircleShape)+ .pressable(onMenu, shape = CircleShape, pressedScale = 0.9f),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ PhosphorIcons.Bold.DotsThree,+ contentDescription = stringResource(R.string.more),+ tint = dim,+ modifier = Modifier.size(18.dp),+ )+ }+ Box(+ Modifier+ .size(36.dp)+ .clip(CircleShape)+ .background(ink)+ .pressable(onClick, shape = CircleShape, pressedScale = 0.9f),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ if (isCurrent && playing) PhosphorIcons.Fill.Pause else PhosphorIcons.Fill.Play,+ contentDescription = stringResource(R.string.play),+ // Whatever reads on the ink it sits on, the page's own+ // colour being anything the cover made it.+ tint = if (ink.luminance() > 0.5f) Color.Black else Color.White,+ modifier = Modifier.size(16.dp),+ )+ }+ }+ }+}diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.ktindex b8f5dd5..822504a 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt@@ -1,5 +1,7 @@package dev.lelonio.square.ui.library+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.horizontalScrollimport androidx.annotation.StringResimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.animation.AnimatedContent@@ -25,6 +27,7 @@ import androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.ui.input.nestedscroll.nestedScrollimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.clickableimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.material3.MaterialTheme@@ -108,6 +111,7 @@ private enum class Filter(@StringRes val label: Int, @StringRes val count: Int)PLAYLISTS(R.string.playlists, R.string.playlist_count),ARTISTS(R.string.artists, R.string.artist_count),ALBUMS(R.string.albums, R.string.album_count),+ PODCASTS(R.string.podcasts, R.string.podcast_count),}/**@@ -143,6 +147,8 @@ fun LibraryScreen(onOpenArtist: (dev.lelonio.square.data.SearchItem) -> Unit = {},/** The albums the account has saved; see MainViewModel.savedAlbums. */albums: List<CatalogPlaylist> = emptyList(),+ /** The podcasts the account follows; none leaves their chip out. */+ podcasts: List<CatalogPlaylist> = emptyList(),/** Tries the servers again from the offline banner; null hides the button. */onRetryOnline: (suspend () -> Boolean)? = null,/**@@ -235,9 +241,10 @@ fun LibraryScreen(}// What the chips are asking for, before any sorting.- val shown = remember(state.playlists, albums, artistItems, filter) {+ val shown = remember(state.playlists, albums, artistItems, podcasts, filter) {when (filter) {- Filter.ALL -> (state.playlists + albums).distinctBy { it.uri }+ Filter.ALL -> (state.playlists + albums + podcasts).distinctBy { it.uri }+ Filter.PODCASTS -> podcasts.distinctBy { it.uri }Filter.PLAYLISTS -> state.playlists.distinctBy { it.uri }Filter.ALBUMS -> albums.distinctBy { it.uri }Filter.ARTISTS -> artistItems.distinctBy { it.uri }@@ -315,6 +322,7 @@ fun LibraryScreen(layout = layout,order = order,filter = filter,+ hasPodcasts = podcasts.isNotEmpty(),backdrop = backdrop,topPadding = contentPadding.calculateTopPadding(),onLayout = {@@ -538,6 +546,8 @@ private fun Header(layout: Layout,order: Order,filter: Filter,+ /** Whether the podcast chip has anything under it. */+ hasPodcasts: Boolean = false,backdrop: Backdrop,topPadding: Dp,onLayout: (Layout) -> Unit,@@ -626,33 +636,41 @@ private fun Header(}}- // The chips say what is being shown; the sort sits at the end of the- // same row as a menu, because it is a choice among three that is made- // once and then left alone.+ // The chips say what is being shown, the whole width to themselves:+ // the sort went up beside the other buttons, since it is a choice made+ // once and then left alone, and the chips need the room.Row(Modifier.fillMaxWidth()- .padding(start = 20.dp, end = 20.dp, top = 14.dp, bottom = 6.dp),- horizontalArrangement = Arrangement.spacedBy(8.dp),+ .padding(top = 14.dp, bottom = 6.dp),verticalAlignment = Alignment.CenterVertically,) {- Filter.entries.forEach { entry ->+ // Scrolled sideways rather than squeezed, edge to edge.+ Row(+ Modifier+ .weight(1f)+ .horizontalScroll(rememberScrollState())+ .padding(horizontal = 20.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Filter.entries.filter { it != Filter.PODCASTS || hasPodcasts }.forEach { entry ->dev.lelonio.square.ui.components.FilterChip(label = stringResource(entry.label),selected = entry == filter,onClick = { onFilter(entry) },)}+ }+ }- Spacer(Modifier.weight(1f))-- LiquidButton(- onClick = onSort,- backdrop = backdrop,- flat = true,- contentHeight = 36.dp,- contentPadding = 12.dp,- modifier = Modifier.onGloballyPositioned {+ // The order, named, just above what it orders: read with the list+ // rather than hunted for among the buttons, and out of the chips' way.+ Row(+ Modifier+ .padding(start = 14.dp, top = 2.dp, bottom = 4.dp)+ .clip(RoundedCornerShape(50))+ .clickable(onClick = onSort)+ .onGloballyPositioned {val bounds = it.boundsInRoot()onSortAnchor(androidx.compose.ui.unit.IntOffset(@@ -660,15 +678,23 @@ private fun Header(bounds.bottom.toInt(),),)- },- ) {- Icon(- PhosphorIcons.Regular.ArrowsDownUp,- contentDescription = stringResource(R.string.sort),- tint = InkDim,- modifier = Modifier.size(18.dp),- )- }+ }+ .padding(horizontal = 8.dp, vertical = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Icon(+ PhosphorIcons.Regular.ArrowsDownUp,+ contentDescription = stringResource(R.string.sort),+ tint = InkDim,+ modifier = Modifier.size(16.dp),+ )+ Text(+ stringResource(order.label),+ style = MaterialTheme.typography.labelLarge,+ color = InkDim,+ )+}}}diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.ktindex 94cbdfb..6315f16 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt@@ -23,6 +23,7 @@ import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.padding@@ -186,6 +187,10 @@ fun PlaylistScreen(state: MainViewModel.PlaylistState,contentPadding: PaddingValues,nowPlayingUri: String?,+ /** Whether what is current is playing; an episode's card shows pause then. */+ nowPlaying: Boolean = false,+ /** Pauses or resumes what is current, for that card's button. */+ onTogglePlay: () -> Unit = {},onBack: () -> Unit,/*** Plays the list. The flag says whether what is being played is the context@@ -697,7 +702,7 @@ fun PlaylistScreen(},// Only where the reference puts one: a record or a list. An artist// page keeps it in the menu, beside the rest of what a page can do.- canDownload = canDownload && !isArtist,+ canDownload = canDownload && !isArtist && state.kind != MainViewModel.DetailKind.SHOW,byline = byline,bylineArtists = if (state.kind == MainViewModel.DetailKind.ALBUM) {state.tracks.firstOrNull()?.artists.orEmpty()@@ -821,7 +826,11 @@ fun PlaylistScreen(item(contentType = "sectionTitle") {SectionHeader(title = stringResource(- if (isArtist) R.string.top_songs else R.string.tracks,+ when {+ isArtist -> R.string.top_songs+ state.kind == MainViewModel.DetailKind.SHOW -> R.string.episodes+ else -> R.string.tracks+ },),// Set as a page heading on an artist, the way the// reference does: there the songs are one section among@@ -938,6 +947,18 @@ fun PlaylistScreen(// Faded in as the list arrives; nothing moves after that.Box(Modifier.animateItem(fadeInSpec = tween(260), placementSpec = null, fadeOutSpec = null)) {SwipeToQueue(onQueue = { onEnqueue(track) }) {+ if (track.isEpisode) {+ val current = track.uri == nowPlayingUri+ EpisodeRow(+ episode = track,+ isCurrent = current,+ playing = nowPlaying,+ onClick = { if (current) onTogglePlay() else onPlay(visible, index, asContext) },+ onMenu = { onTrackMenu(track) },+ showName = state.kind != MainViewModel.DetailKind.SHOW,+ unavailable = offline && trackDownload(track) != dev.lelonio.square.data.DownloadState.Done,+ )+ } elseTrackRow(track = track,position = index + 1,@@ -947,6 +968,11 @@ fun PlaylistScreen(// record the song is on and when it came out, which// is the thing a listener is actually placing.subtitle = when {+ // When it came out and how long it is, and+ // how much is left of one already started: what+ // an episode is chosen by. The show's name is+ // the page's title.+ track.isEpisode -> episodeLine(track, showName = state.kind != MainViewModel.DetailKind.SHOW)isArtist -> track.releaseLine()// On a record by one artist, printing their// name under every title says nothing; the@@ -960,6 +986,8 @@ fun PlaylistScreen(// instead — the one thing that differs, and the// thing a record is read by.numbered = state.kind == MainViewModel.DetailKind.ALBUM,+ progress = track.takeIf { it.isEpisode && !it.played && it.resumeMs > 0 && it.durationMs > 0 }+ ?.let { (it.resumeMs.toFloat() / it.durationMs).coerceIn(0f, 1f) },isCurrent = track.uri == nowPlayingUri,onClick = { onPlay(visible, index, asContext) },onMenu = { onTrackMenu(track) },@@ -983,7 +1011,9 @@ fun PlaylistScreen(// How much of it there is, at the end rather than under the title.// That is where the reference puts it, and it is the right place: it// is what you read after the list, not before it.- if (!isArtist && state.tracks.isNotEmpty() && query.isBlank()) {+ if (!isArtist && state.kind != MainViewModel.DetailKind.SHOW &&+ state.tracks.isNotEmpty() && query.isBlank()+ ) {item(contentType = "totals") {Text(stringResource(@@ -1350,7 +1380,7 @@ fun PlaylistScreen(// one action that changes what your library holds, apart from the// controls that only start the music. Absent while the answer is// unknown and on the pages the question does not apply to.- if (state.saved != null) {+ if (state.saved != null && state.kind != MainViewModel.DetailKind.SHOW) {CollapsingSlot(collapseFraction) {CapsuleAction(tint = chromeInk,@@ -1710,6 +1740,21 @@ private fun DetailHeader()}+ // A podcast cannot be kept on the phone yet, so the place the+ // download takes on a record is where following it goes.+ if (kind == MainViewModel.DetailKind.SHOW && saved != null) {+ CircleAction(+ icon = if (saved) PhosphorIcons.Bold.Check else PhosphorIcons.Bold.Plus,+ description = stringResource(+ if (saved) R.string.remove_from_library else R.string.add_to_library,+ ),+ size = 46.dp,+ backdrop = backdrop,+ onClick = onToggleSaved,+ tint = ink,+ )+ }+if (following != null) {FollowPill(following = following, onClick = onToggleFollow)}@@ -2890,6 +2935,8 @@ private fun TrackRow(subtitle: String? = null,/** Its place on the record, drawn where the cover would be. */numbered: Boolean = false,+ /** How far into it the listener got, for an episode they started. */+ progress: Float? = null,/** Nothing is drawn until a download for this track exists; see below. */download: dev.lelonio.square.data.DownloadState =dev.lelonio.square.data.DownloadState.None,@@ -3065,6 +3112,22 @@ private fun TrackRow(overflow = TextOverflow.Ellipsis,)}+ if (progress != null) {+ Box(+ Modifier+ .padding(top = 5.dp)+ .size(width = 72.dp, height = 3.dp)+ .clip(RoundedCornerShape(2.dp))+ .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f)),+ ) {+ Box(+ Modifier+ .fillMaxHeight()+ .fillMaxWidth(progress)+ .background(MaterialTheme.colorScheme.onSurface),+ )+ }+ }}IconButton(onClick = onMenu, modifier = Modifier.size(32.dp)) {@@ -3124,6 +3187,37 @@ fun openLinkOf(uri: String): String {* year with no album name is never the case. Empty when there is neither, and* the row then falls back to the artist and the length.*/+/**+ * An episode's second line: the day it came out, then how long it is or how+ * much of it is left, or that it was heard. The show's name first where the+ * list is not the show's own.+ */+@Composable+internal fun episodeLine(track: CatalogTrack, showName: Boolean): String {+ val context = androidx.compose.ui.platform.LocalContext.current+ val day = track.releasedAt?.let { iso ->+ runCatching { java.time.Instant.parse(iso).toEpochMilli() }.getOrNull()+ }?.let { millis ->+ val thisYear = java.time.Year.now().value.toString() == track.releasedAt.take(4)+ android.text.format.DateUtils.formatDateTime(+ context,+ millis,+ android.text.format.DateUtils.FORMAT_SHOW_DATE or+ android.text.format.DateUtils.FORMAT_ABBREV_MONTH or+ if (thisYear) android.text.format.DateUtils.FORMAT_NO_YEAR else android.text.format.DateUtils.FORMAT_SHOW_YEAR,+ )+ }+ val length = when {+ track.played -> stringResource(R.string.episode_played)+ track.resumeMs > 0 && track.durationMs > track.resumeMs ->+ stringResource(R.string.episode_left, formatTotal(track.durationMs - track.resumeMs))+ track.durationMs > 0 -> formatTotal(track.durationMs)+ else -> null+ }+ return listOfNotNull(track.artist.takeIf { showName && it.isNotBlank() }, day, length)+ .joinToString(" · ")+}+private fun CatalogTrack.releaseLine(): String = listOf(album, year).filter { it.isNotBlank() }.joinToString(" · ")diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.ktindex a496a62..775ff42 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt@@ -118,6 +118,7 @@ import dev.lelonio.square.ui.glass.LiquidButtonimport dev.lelonio.square.ui.library.formatDurationimport dev.lelonio.square.ui.theme.softShadowimport com.adamglin.phosphoricons.regular.MonitorPlay+import com.adamglin.phosphoricons.regular.Gaugeimport com.adamglin.phosphoricons.regular.MusicNotesimport com.adamglin.PhosphorIconsimport com.adamglin.phosphoricons.regular.DeviceRotate@@ -1542,6 +1543,43 @@ fun PlayerScreen(.height(videoRowHeight),contentAlignment = Alignment.Center,) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // The speed, one tap a step, beside the video, and+ // only on an episode: a talk is what people speed up.+ // A song keeps the fine slider in the effects panel.+ androidx.compose.animation.AnimatedVisibility(+ visible = !panelOpen && !sideways &&+ state.mediaId?.startsWith("spotify:episode:") == true,+ enter = fadeIn(tween(260)) + scaleIn(tween(260), initialScale = 0.9f),+ exit = fadeOut(tween(180)) + scaleOut(tween(180), targetScale = 0.92f),+ ) {+ GlassSurface(+ backdrop = upperBackdrop,+ surfaceColor = LocalPlayerFilm.current,+ shape = RoundedCornerShape(50),+ modifier = Modifier.pressable(onClick = { onSpeed(nextSpeed(state.speed)) }),+ ) {+ Row(+ Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(+ PhosphorIcons.Regular.Gauge,+ contentDescription = null,+ modifier = Modifier+ .padding(end = 8.dp)+ .size(18.dp),+ )+ Text(+ speedLabel(state.speed),+ style = MaterialTheme.typography.labelLarge,+ )+ }+ }+ }androidx.compose.animation.AnimatedVisibility(visible = videoFileId != null && !panelOpen && !sideways,enter = fadeIn(tween(260)) + scaleIn(tween(260), initialScale = 0.9f),@@ -1584,6 +1622,7 @@ fun PlayerScreen(}}}+ }// On its side there is room above the title, and the// line being sung is the best thing to put in it.@@ -3106,3 +3145,18 @@ private fun CardButton()}}++/** The speeds the button steps through, in the order a listener reaches for them. */+private val SPEED_STEPS = listOf(1f, 1.25f, 1.5f, 1.75f, 2f, 0.75f)++/** The step after [speed]; a speed set on the slider goes back to normal. */+private fun nextSpeed(speed: Float): Float {+ val at = SPEED_STEPS.indexOfFirst { kotlin.math.abs(it - speed) < 0.01f }+ return if (at < 0) 1f else SPEED_STEPS[(at + 1) % SPEED_STEPS.size]+}++/** "1,5×", in the reader's own decimal mark. */+private fun speedLabel(speed: Float): String {+ val format = java.text.DecimalFormat("0.##")+ return format.format(speed.toDouble()) + "×"+}diff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.ktindex 8db87a4..12ee539 100644--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt@@ -66,6 +66,7 @@ private enum class Kind(@StringRes val label: Int) {ARTISTS(R.string.artists),ALBUMS(R.string.albums),PLAYLISTS(R.string.playlists),+ PODCASTS(R.string.podcasts),}/**@@ -152,7 +153,12 @@ fun SearchScreen(if (!state.results.isEmpty && !state.loading) {item(contentType = "chips") {// Videos only where the source has them: Spotify's search does not.- KindRow(kind, backdrop, hasVideos = state.results.videos.isNotEmpty()) { kind = it }+ KindRow(+ kind,+ backdrop,+ hasVideos = state.results.videos.isNotEmpty(),+ hasPodcasts = state.results.podcasts.isNotEmpty() || state.results.episodes.isNotEmpty(),+ ) { kind = it }}}@@ -337,6 +343,33 @@ fun SearchScreen(section(R.string.playlists, state.results.playlists, all, round = false, onOpenContext)}+ // Shows open as their episodes; an episode plays where it is.+ if (all || kind == Kind.PODCASTS) {+ section(R.string.podcasts, state.results.podcasts, all, round = false, onOpenContext)+ }+ val episodes = state.results.episodes.let { if (all) it.take(TOP_RESULTS) else it }+ if ((all || kind == Kind.PODCASTS) && episodes.isNotEmpty()) {+ item(contentType = "section") { SectionTitle(stringResource(R.string.episodes)) }+ items(+ count = episodes.size,+ key = { "episode-${episodes[it].uri}-$it" },+ contentType = { "track" },+ ) { index ->+ val episode = episodes[index]+ SwipeToQueue(onQueue = { onEnqueue(episode) }) {+ ResultRow(+ title = episode.name,+ subtitle = dev.lelonio.square.ui.library.episodeLine(episode, showName = true),+ artworkUrl = episode.artworkUrl,+ highlighted = episode.uri == nowPlayingUri,+ round = false,+ onClick = { onPlayTrack(episodes, index) },+ onMenu = { onTrackMenu(episode) },+ )+ }+ }+ }+// The page on its way, said in the one place the reader is// looking: at the bottom, where they ran out of rows.if (state.loadingMore) {@@ -363,13 +396,22 @@ fun SearchScreen(/** The same chips the home page filters with; see the note there. */@Composable-private fun KindRow(selected: Kind, backdrop: Backdrop, hasVideos: Boolean, onSelect: (Kind) -> Unit) {+private fun KindRow(+ selected: Kind,+ backdrop: Backdrop,+ hasVideos: Boolean,+ hasPodcasts: Boolean,+ onSelect: (Kind) -> Unit,+) {LazyRow(contentPadding = PaddingValues(horizontal = 20.dp),horizontalArrangement = Arrangement.spacedBy(8.dp),modifier = Modifier.padding(top = 16.dp, bottom = 4.dp),) {- items(Kind.entries.filter { it != Kind.VIDEOS || hasVideos }, key = { it.name }) { entry ->+ items(+ Kind.entries.filter { (it != Kind.VIDEOS || hasVideos) && (it != Kind.PODCASTS || hasPodcasts) },+ key = { it.name },+ ) { entry ->dev.lelonio.square.ui.components.FilterChip(label = stringResource(entry.label),selected = entry == selected,diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/EqualizerPage.kt b/app/src/main/java/dev/lelonio/square/ui/settings/EqualizerPage.ktnew file mode 100644index 0000000..9053b0b--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/settings/EqualizerPage.kt@@ -0,0 +1,472 @@+package dev.lelonio.square.ui.settings++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+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.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.clipRect+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.adamglin.PhosphorIcons+import com.adamglin.phosphoricons.Regular+import com.adamglin.phosphoricons.regular.ArrowCounterClockwise+import com.adamglin.phosphoricons.regular.Bluetooth+import com.adamglin.phosphoricons.regular.DeviceMobileSpeaker+import com.adamglin.phosphoricons.regular.Headphones+import com.adamglin.phosphoricons.regular.Plus+import com.adamglin.phosphoricons.regular.SpeakerHifi+import com.adamglin.phosphoricons.regular.Usb+import com.adamglin.phosphoricons.regular.X+import dev.lelonio.square.R+import dev.lelonio.square.playback.AudioRoute+import dev.lelonio.square.playback.BuiltInEqPresets+import dev.lelonio.square.playback.Equalizer+import dev.lelonio.square.ui.components.NameDialog+import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDim+import kotlin.math.roundToInt++/**+ * The equaliser: which output, its curve, and the presets to start from.+ *+ * The output comes first because it is what the rest belongs to. The curve+ * shown is the one for whatever is playing through now; the others the app has+ * seen are listed under it, and choosing one edits that one's curve without+ * having to plug it in.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+fun EqualizerPage(contentPadding: PaddingValues, header: @Composable () -> Unit) {+ val route by AudioRoute.current.collectAsStateWithLifecycle()+ val curves by Equalizer.curves.collectAsStateWithLifecycle()+ val names by Equalizer.names.collectAsStateWithLifecycle()+ val custom by Equalizer.presets.collectAsStateWithLifecycle()++ // Null follows the output in use; a key is one chosen from the list.+ var picked by remember { mutableStateOf<String?>(null) }+ val editing = picked ?: route.key+ val curve = curves[editing] ?: Equalizer.Curve()+ var saving by remember { mutableStateOf(false) }++ val known = remember(curves, names, route) {+ (listOf(route.key) + names.keys + curves.keys).distinct()+ }++ LazyColumn(+ Modifier.fillMaxSize(),+ contentPadding = PaddingValues(+ top = contentPadding.calculateTopPadding(),+ bottom = contentPadding.calculateBottomPadding() + 24.dp,+ ),+ ) {+ item("top") { header() }++ item("device") {+ SettingsSection(null) {+ Row(+ Modifier+ .fillMaxWidth()+ .padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 14.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ RowIcon(iconFor(editing))+ Column(Modifier.weight(1f)) {+ Text(+ outputName(editing, names),+ style = MaterialTheme.typography.bodyLarge,+ maxLines = 1,+ )+ Text(+ stringResource(+ if (editing == route.key) R.string.eq_in_use else R.string.eq_not_connected,+ ),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ )+ }+ PlainToggle(checked = curve.enabled) { Equalizer.setEnabled(editing, it) }+ }+ }+ }++ item("curve") {+ SettingsSection(stringResource(R.string.eq_curve)) {+ CurveEditor(+ gains = curve.gains,+ enabled = curve.enabled,+ onGain = { band, db -> Equalizer.setGain(editing, band, db) },+ )+ SettingsDivider()+ Column(Modifier.padding(horizontal = 18.dp, vertical = 8.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(+ stringResource(R.string.eq_preamp),+ style = MaterialTheme.typography.bodyLarge,+ modifier = Modifier.weight(1f),+ )+ Text(+ decibels(curve.preamp),+ style = MaterialTheme.typography.bodyMedium,+ color = InkDim,+ )+ }+ PlainSlider(+ value = curve.preamp,+ range = -Equalizer.RANGE_DB..Equalizer.RANGE_DB,+ onChange = { Equalizer.setPreamp(editing, it) },+ modifier = Modifier.padding(top = 6.dp, bottom = 2.dp),+ )+ }+ SettingsDivider()+ Row(+ Modifier+ .fillMaxWidth()+ .clickable { Equalizer.reset(editing) }+ .padding(horizontal = 18.dp, vertical = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ RowIcon(PhosphorIcons.Regular.ArrowCounterClockwise)+ Text(stringResource(R.string.eq_reset), style = MaterialTheme.typography.bodyLarge)+ }+ }+ }++ item("presets") {+ SettingsSection(stringResource(R.string.eq_presets)) {+ FlowRow(+ Modifier+ .fillMaxWidth()+ .padding(14.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ BuiltInEqPresets.forEach { (name, gains) ->+ PresetChip(+ label = stringResource(name),+ selected = curve.enabled && curve.matches(gains),+ ) { Equalizer.applyPreset(editing, gains) }+ }+ custom.forEach { preset ->+ PresetChip(+ label = preset.name,+ selected = curve.enabled && curve.matches(preset.gains),+ onDelete = { Equalizer.deletePreset(preset.id) },+ ) { Equalizer.applyPreset(editing, preset.gains) }+ }+ PresetChip(+ label = stringResource(R.string.eq_save_preset),+ selected = false,+ icon = PhosphorIcons.Regular.Plus,+ ) { saving = true }+ }+ }+ }++ if (known.size > 1) item("devices") {+ SettingsSection(stringResource(R.string.eq_devices)) {+ known.forEachIndexed { index, key ->+ if (index > 0) SettingsDivider()+ SettingsChoiceRow(+ label = outputName(key, names) ++ if (key == route.key) " · " + stringResource(R.string.eq_in_use) else "",+ selected = key == editing,+ icon = iconFor(key),+ ) { picked = key.takeUnless { it == route.key } }+ }+ }+ }++ item("note") {+ Text(+ stringResource(R.string.eq_note),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ modifier = Modifier.padding(horizontal = 26.dp, vertical = 6.dp),+ )+ }+ }++ if (saving) {+ NameDialog(+ title = stringResource(R.string.eq_save_preset),+ initial = "",+ confirmLabel = stringResource(R.string.save),+ onConfirm = { name ->+ if (name.isNotBlank()) Equalizer.savePreset(name, curve.gains)+ saving = false+ },+ onDismiss = { saving = false },+ )+ }+}++/**+ * The ten bands as ten sliders, with the curve they make drawn through them.+ *+ * Each band is its own upright slider, as on a mixing desk: the track the whole+ * height of the range, the bar filled up to where the band is set, and the+ * number above it. The curve runs through the ten knobs, so the shape of the+ * sound is read at a glance and each band's own height can still be told+ * exactly. A finger chooses the band it lands on and then only moves that one,+ * so a drag that drifts sideways does not start dragging the neighbours.+ */+@Composable+private fun CurveEditor(+ gains: List<Float>,+ enabled: Boolean,+ onGain: (Int, Float) -> Unit,+) {+ val accent = settingsAccent()+ val ink = Ink+ val bands = Equalizer.FREQUENCIES.size+ var active by remember { mutableStateOf<Int?>(null) }+ val latestOnGain by rememberUpdatedState(onGain)++ Column(+ Modifier+ .padding(horizontal = 8.dp, vertical = 12.dp)+ .alpha(if (enabled) 1f else 0.45f),+ ) {+ Row(Modifier.fillMaxWidth()) {+ gains.forEachIndexed { band, gain ->+ Text(+ String.format(java.util.Locale.ROOT, "%.1f", gain),+ style = MaterialTheme.typography.labelMedium,+ color = if (band == active) accent else InkDim,+ textAlign = TextAlign.Center,+ maxLines = 1,+ modifier = Modifier.weight(1f),+ )+ }+ }+ Canvas(+ Modifier+ .fillMaxWidth()+ .height(300.dp)+ .padding(vertical = 6.dp)+ .pointerInput(bands) {+ val pad = KNOB_RADIUS.toPx()+ fun dbAt(y: Float): Float {+ val span = size.height - pad * 2+ return (Equalizer.RANGE_DB - (y - pad) / span * Equalizer.RANGE_DB * 2)+ .coerceIn(-Equalizer.RANGE_DB, Equalizer.RANGE_DB)+ }+ awaitEachGesture {+ val down = awaitFirstDown()+ val band = (down.position.x / size.width * bands).toInt().coerceIn(0, bands - 1)+ active = band+ down.consume()+ latestOnGain(band, dbAt(down.position.y))+ while (true) {+ val event = awaitPointerEvent()+ val change = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!change.pressed) break+ change.consume()+ latestOnGain(band, dbAt(change.position.y))+ }+ active = null+ }+ },+ ) {+ val pad = KNOB_RADIUS.toPx()+ val span = size.height - pad * 2+ val y = { db: Float -> pad + (Equalizer.RANGE_DB - db) / (Equalizer.RANGE_DB * 2) * span }+ val column = size.width / bands+ val x = { band: Int -> column * (band + 0.5f) }+ val track = 4.dp.toPx()++ // The middle of the range, faintly: where a band does nothing.+ drawLine(+ ink.copy(alpha = 0.10f),+ Offset(0f, y(0f)),+ Offset(size.width, y(0f)),+ strokeWidth = 1.dp.toPx(),+ )++ // Each slider's whole travel, and a mark at its top.+ for (band in 0 until bands) {+ drawLine(+ accent.copy(alpha = 0.16f),+ Offset(x(band), pad),+ Offset(x(band), size.height),+ strokeWidth = track,+ cap = StrokeCap.Round,+ )+ drawCircle(ink.copy(alpha = 0.55f), 2.dp.toPx(), Offset(x(band), pad))+ }++ // The curve through the knobs, carried on flat to either edge.+ // Catmull-Rom, so it passes through every knob and bends smoothly+ // between them rather than in straight lines.+ val points = (0 until bands).map { Offset(x(it), y(gains[it])) }+ val all = listOf(Offset(0f, points.first().y)) + points + Offset(size.width, points.last().y)+ val curve = Path().apply {+ moveTo(all[0].x, all[0].y)+ for (i in 0 until all.size - 1) {+ val p0 = all[maxOf(i - 1, 0)]+ val p1 = all[i]+ val p2 = all[i + 1]+ val p3 = all[minOf(i + 2, all.size - 1)]+ cubicTo(+ p1.x + (p2.x - p0.x) / 6f, p1.y + (p2.y - p0.y) / 6f,+ p2.x - (p3.x - p1.x) / 6f, p2.y - (p3.y - p1.y) / 6f,+ p2.x, p2.y,+ )+ }+ }+ val fill = Path().apply {+ addPath(curve)+ lineTo(size.width, size.height)+ lineTo(0f, size.height)+ close()+ }+ clipRect {+ drawPath(fill, accent.copy(alpha = 0.16f))+ drawPath(curve, accent, style = Stroke(width = 3.dp.toPx(), cap = StrokeCap.Round))+ }++ // Each band's own height: the bar up to its knob.+ for (band in 0 until bands) {+ val centre = points[band]+ drawLine(+ accent,+ Offset(centre.x, size.height),+ centre,+ strokeWidth = track,+ cap = StrokeCap.Round,+ )+ val radius = KNOB_RADIUS.toPx() * if (band == active) 1.25f else 1f+ drawCircle(accent, radius, centre)+ }+ }+ Row(Modifier.fillMaxWidth()) {+ Equalizer.FREQUENCIES.forEach { frequency ->+ Text(+ frequencyLabel(frequency),+ style = MaterialTheme.typography.labelMedium,+ color = InkDim,+ textAlign = TextAlign.Center,+ maxLines = 1,+ modifier = Modifier.weight(1f),+ )+ }+ }+ Text(+ stringResource(R.string.eq_hint),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ textAlign = TextAlign.Center,+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 8.dp),+ )+ }+}++@Composable+private fun PresetChip(+ label: String,+ selected: Boolean,+ icon: ImageVector? = null,+ onDelete: (() -> Unit)? = null,+ onClick: () -> Unit,+) {+ val accent = settingsAccent()+ Row(+ Modifier+ .clip(ContinuousCapsule())+ .background(if (selected) accent else Ink.copy(alpha = 0.08f))+ .clickable(onClick = onClick)+ .padding(start = 14.dp, end = if (onDelete != null) 6.dp else 14.dp, top = 8.dp, bottom = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ val ink = if (selected) Color.White else Ink+ icon?.let { Icon(it, contentDescription = null, tint = ink, modifier = Modifier.size(16.dp)) }+ Text(label, style = MaterialTheme.typography.labelLarge, color = ink)+ if (onDelete != null) {+ Icon(+ PhosphorIcons.Regular.X,+ contentDescription = stringResource(R.string.delete),+ tint = ink.copy(alpha = 0.7f),+ modifier = Modifier+ .size(22.dp)+ .clip(ContinuousCapsule())+ .clickable(onClick = onDelete)+ .padding(4.dp),+ )+ }+ }+}++/** What an output is called on screen. */+@Composable+private fun outputName(key: String, names: Map<String, String>): String {+ names[key]?.takeIf { it.isNotBlank() }?.let { return it }+ return stringResource(+ when (AudioRoute.kindOf(key)) {+ AudioRoute.Kind.SPEAKER -> R.string.eq_speaker+ AudioRoute.Kind.WIRED -> R.string.eq_wired+ AudioRoute.Kind.BLUETOOTH -> R.string.eq_bluetooth+ AudioRoute.Kind.USB -> R.string.eq_usb+ AudioRoute.Kind.OTHER -> R.string.eq_other+ },+ )+}++private fun iconFor(key: String): ImageVector = when (AudioRoute.kindOf(key)) {+ AudioRoute.Kind.SPEAKER -> PhosphorIcons.Regular.DeviceMobileSpeaker+ AudioRoute.Kind.WIRED -> PhosphorIcons.Regular.Headphones+ AudioRoute.Kind.BLUETOOTH -> PhosphorIcons.Regular.Bluetooth+ AudioRoute.Kind.USB -> PhosphorIcons.Regular.Usb+ AudioRoute.Kind.OTHER -> PhosphorIcons.Regular.SpeakerHifi+}++private fun frequencyLabel(hz: Int): String = if (hz >= 1000) "${hz / 1000}k" else "$hz"++private fun decibels(db: Float): String {+ val rounded = (db * 2f).roundToInt() / 2f+ val text = if (rounded % 1f == 0f) rounded.toInt().toString() else rounded.toString()+ return (if (rounded > 0f) "+" else "") + text + " dB"+}++private val KNOB_RADIUS = 10.dpdiff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.ktindex a4d89af..c0c897a 100644--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt@@ -68,6 +68,7 @@ import androidx.compose.foundation.layout.heightInimport com.adamglin.phosphoricons.regular.UserCircleimport com.adamglin.phosphoricons.regular.Waveformimport com.adamglin.phosphoricons.regular.Drop+import com.adamglin.phosphoricons.regular.Equalizerimport com.adamglin.phosphoricons.regular.SlidersHorizontalimport com.adamglin.phosphoricons.regular.Infoimport com.adamglin.phosphoricons.regular.DownloadSimple@@ -286,6 +287,13 @@ fun SettingsScreen(},label = "settingsPage",) { shown ->+ if (shown == SettingsPage.Equalizer) {+ EqualizerPage(+ contentPadding = contentPadding,+ header = { heading(shown) },+ )+ return@AnimatedContent+ }if (shown == SettingsPage.Glass) {GlassPage(backdrop = backdrop,@@ -998,6 +1006,9 @@ private enum class SettingsPage(// Its own page rather than a section of the app's: the preview has to stay// on screen while the numbers under it move, and a section inside a list// scrolls away. See GlassPage.+ // Its own page for the glass's reason: the curve is moved by hand, and+ // stays on screen while it is.+ Equalizer(R.string.equalizer, R.string.page_equalizer_summary, PhosphorIcons.Regular.Equalizer),Glass(R.string.glass, R.string.page_glass_summary, PhosphorIcons.Regular.Drop),Downloads(R.string.page_downloads, R.string.page_downloads_summary, PhosphorIcons.Regular.DownloadSimple),App(R.string.page_app, R.string.page_app_summary, PhosphorIcons.Regular.SlidersHorizontal),@@ -1072,7 +1083,7 @@ private fun SettingsIndex()}- // Five places, and a sixth tile that is not a place: it leaves the app+ // Six places, and a seventh tile that is not a place: it leaves the app// for the Ko-fi page. Last, and in the same shape as the rest, because// it is an offer rather than a setting — asking louder than that would// be asking on a screen somebody opened to change something.diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex ec30e9b..784f126 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -609,4 +609,43 @@<string name="link_copied_open_browser">Der Browser ließ sich nicht öffnen. Der Link ist kopiert: füge ihn dort ein.</string><string name="youtube_signing_in">Anmeldung läuft…</string><string name="youtube_sign_in_private">Dein Passwort geht nur an Google. Square behält die Sitzung, die Google zurückgibt.</string>+ <string name="equalizer">Equalizer</string>+ <string name="page_equalizer_summary">Eine Kurve für jeden Kopfhörer</string>+ <string name="eq_speaker">Telefonlautsprecher</string>+ <string name="eq_wired">Kabelkopfhörer</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB-Audio</string>+ <string name="eq_other">Andere Ausgabe</string>+ <string name="eq_in_use">Gerade in Verwendung</string>+ <string name="eq_not_connected">Nicht verbunden</string>+ <string name="eq_devices">Geräte</string>+ <string name="eq_curve">Kurve</string>+ <string name="eq_preamp">Vorverstärkung</string>+ <string name="eq_presets">Voreinstellungen</string>+ <string name="eq_save_preset">Als Voreinstellung speichern</string>+ <string name="eq_reset">Zurücksetzen</string>+ <string name="eq_hint">Bänder antippen und ziehen</string>+ <string name="eq_note">Jede Ausgabe hat ihre eigene Kurve. Verbindest du andere Kopfhörer, wechselt Square zu deren Kurve. Anhebungen senken die Gesamtlautstärke um denselben Wert, damit nichts übersteuert.</string>+ <string name="eq_flat">Linear</string>+ <string name="eq_bass_boost">Mehr Bass</string>+ <string name="eq_bass_reducer">Weniger Bass</string>+ <string name="eq_treble_boost">Mehr Höhen</string>+ <string name="eq_treble_reducer">Weniger Höhen</string>+ <string name="eq_vocal">Gesang</string>+ <string name="eq_spoken">Sprache</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-Hop</string>+ <string name="eq_electronic">Elektronisch</string>+ <string name="eq_classical">Klassik</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Akustik</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Folgen</string>+ <string name="episode_left">noch %s</string>+ <string name="episode_played">Gehört</string>+ <string name="podcasts">Podcasts</string>+ <string name="new_episodes">Neue Folgen deiner Podcasts</string>+ <string name="podcast_count">%1$d Podcasts</string></resources>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex abff510..29f1e74 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -615,4 +615,43 @@<string name="link_copied_open_browser">No se pudo abrir el navegador. El enlace está copiado: pégalo allí.</string><string name="youtube_signing_in">Iniciando sesión…</string><string name="youtube_sign_in_private">Tu contraseña va solo a Google. Square guarda la sesión que Google devuelve.</string>+ <string name="equalizer">Ecualizador</string>+ <string name="page_equalizer_summary">Una curva para cada auricular</string>+ <string name="eq_speaker">Altavoz del teléfono</string>+ <string name="eq_wired">Auriculares con cable</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">Audio USB</string>+ <string name="eq_other">Otra salida</string>+ <string name="eq_in_use">En uso ahora</string>+ <string name="eq_not_connected">No conectado</string>+ <string name="eq_devices">Dispositivos</string>+ <string name="eq_curve">Curva</string>+ <string name="eq_preamp">Preamplificación</string>+ <string name="eq_presets">Preajustes</string>+ <string name="eq_save_preset">Guardar como preajuste</string>+ <string name="eq_reset">Restablecer</string>+ <string name="eq_hint">Toca y arrastra las bandas</string>+ <string name="eq_note">Cada salida tiene su propia curva. Cuando conectas otros auriculares, Square cambia a la suya. Los realces bajan el volumen general en la misma medida, así nada satura.</string>+ <string name="eq_flat">Plano</string>+ <string name="eq_bass_boost">Más graves</string>+ <string name="eq_bass_reducer">Menos graves</string>+ <string name="eq_treble_boost">Más agudos</string>+ <string name="eq_treble_reducer">Menos agudos</string>+ <string name="eq_vocal">Voz</string>+ <string name="eq_spoken">Habla</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Electrónica</string>+ <string name="eq_classical">Clásica</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Acústica</string>+ <string name="podcast">Pódcast</string>+ <string name="episodes">Episodios</string>+ <string name="episode_left">quedan %s</string>+ <string name="episode_played">Escuchado</string>+ <string name="podcasts">Pódcasts</string>+ <string name="new_episodes">Episodios nuevos de tus pódcasts</string>+ <string name="podcast_count">%1$d pódcasts</string></resources>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 4d56590..47d6a1e 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -609,4 +609,43 @@<string name="link_copied_open_browser">Impossible d\'ouvrir le navigateur. Le lien est copié : collez-le dedans.</string><string name="youtube_signing_in">Connexion en cours…</string><string name="youtube_sign_in_private">Votre mot de passe va uniquement à Google. Square garde la session que Google renvoie.</string>+ <string name="equalizer">Égaliseur</string>+ <string name="page_equalizer_summary">Une courbe pour chaque casque</string>+ <string name="eq_speaker">Haut-parleur du téléphone</string>+ <string name="eq_wired">Écouteurs filaires</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">Audio USB</string>+ <string name="eq_other">Autre sortie</string>+ <string name="eq_in_use">Utilisé maintenant</string>+ <string name="eq_not_connected">Non connecté</string>+ <string name="eq_devices">Appareils</string>+ <string name="eq_curve">Courbe</string>+ <string name="eq_preamp">Préampli</string>+ <string name="eq_presets">Préréglages</string>+ <string name="eq_save_preset">Enregistrer comme préréglage</string>+ <string name="eq_reset">Réinitialiser</string>+ <string name="eq_hint">Touchez et faites glisser les bandes</string>+ <string name="eq_note">Chaque sortie garde sa propre courbe. Quand vous branchez un autre casque, Square passe à la sienne. Les hausses baissent le niveau général d’autant, pour que rien ne sature.</string>+ <string name="eq_flat">Plat</string>+ <string name="eq_bass_boost">Plus de basses</string>+ <string name="eq_bass_reducer">Moins de basses</string>+ <string name="eq_treble_boost">Plus d’aigus</string>+ <string name="eq_treble_reducer">Moins d’aigus</string>+ <string name="eq_vocal">Voix</string>+ <string name="eq_spoken">Parole</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Électronique</string>+ <string name="eq_classical">Classique</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Acoustique</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Épisodes</string>+ <string name="episode_left">%s restantes</string>+ <string name="episode_played">Écouté</string>+ <string name="podcasts">Podcasts</string>+ <string name="new_episodes">Nouveaux épisodes de vos podcasts</string>+ <string name="podcast_count">%1$d podcasts</string></resources>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex 48a9746..758913d 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -624,4 +624,43 @@<string name="link_copied_open_browser">ब्राउज़र नहीं खुल सका। लिंक कॉपी हो गया है: उसे वहाँ पेस्ट करें।</string><string name="youtube_signing_in">साइन इन हो रहा है…</string><string name="youtube_sign_in_private">आपका पासवर्ड सिर्फ़ Google को जाता है। Square वही सेशन रखता है जो Google लौटाता है।</string>+ <string name="equalizer">इक्वलाइज़र</string>+ <string name="page_equalizer_summary">हर हेडफ़ोन के लिए अलग कर्व</string>+ <string name="eq_speaker">फ़ोन का स्पीकर</string>+ <string name="eq_wired">वायर्ड हेडफ़ोन</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB ऑडियो</string>+ <string name="eq_other">अन्य आउटपुट</string>+ <string name="eq_in_use">अभी उपयोग में</string>+ <string name="eq_not_connected">कनेक्ट नहीं</string>+ <string name="eq_devices">डिवाइस</string>+ <string name="eq_curve">कर्व</string>+ <string name="eq_preamp">प्रीएम्प</string>+ <string name="eq_presets">प्रीसेट</string>+ <string name="eq_save_preset">प्रीसेट के रूप में सहेजें</string>+ <string name="eq_reset">रीसेट करें</string>+ <string name="eq_hint">बैंड को छूकर खींचें</string>+ <string name="eq_note">हर आउटपुट का अपना कर्व होता है। दूसरे हेडफ़ोन जोड़ने पर Square उनका कर्व इस्तेमाल करता है। बूस्ट करने पर कुल आवाज़ उतनी ही कम हो जाती है, ताकि कुछ भी न फटे।</string>+ <string name="eq_flat">फ़्लैट</string>+ <string name="eq_bass_boost">बास बढ़ाएँ</string>+ <string name="eq_bass_reducer">बास घटाएँ</string>+ <string name="eq_treble_boost">ट्रेबल बढ़ाएँ</string>+ <string name="eq_treble_reducer">ट्रेबल घटाएँ</string>+ <string name="eq_vocal">वोकल</string>+ <string name="eq_spoken">बोलचाल</string>+ <string name="eq_loudness">लाउडनेस</string>+ <string name="eq_rock">रॉक</string>+ <string name="eq_pop">पॉप</string>+ <string name="eq_hip_hop">हिप-हॉप</string>+ <string name="eq_electronic">इलेक्ट्रॉनिक</string>+ <string name="eq_classical">क्लासिकल</string>+ <string name="eq_jazz">जैज़</string>+ <string name="eq_acoustic">अकूस्टिक</string>+ <string name="podcast">पॉडकास्ट</string>+ <string name="episodes">एपिसोड</string>+ <string name="episode_left">%s बाकी</string>+ <string name="episode_played">सुना गया</string>+ <string name="podcasts">पॉडकास्ट</string>+ <string name="new_episodes">आपके पॉडकास्ट के नए एपिसोड</string>+ <string name="podcast_count">%1$d पॉडकास्ट</string></resources>diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex 7337c36..2f04f83 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -646,4 +646,43 @@<string name="link_copied_open_browser">Impossibile aprire il browser. Il link è copiato: incollalo lì.</string><string name="youtube_signing_in">Accesso in corso…</string><string name="youtube_sign_in_private">La password va solo a Google. Square conserva la sessione che Google restituisce.</string>+ <string name="equalizer">Equalizzatore</string>+ <string name="page_equalizer_summary">Una curva per ogni cuffia</string>+ <string name="eq_speaker">Altoparlante del telefono</string>+ <string name="eq_wired">Cuffie con cavo</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">Audio USB</string>+ <string name="eq_other">Altra uscita</string>+ <string name="eq_in_use">In uso ora</string>+ <string name="eq_not_connected">Non collegato</string>+ <string name="eq_devices">Dispositivi</string>+ <string name="eq_curve">Curva</string>+ <string name="eq_preamp">Preamplificazione</string>+ <string name="eq_presets">Preset</string>+ <string name="eq_save_preset">Salva come preset</string>+ <string name="eq_reset">Azzera</string>+ <string name="eq_hint">Tocca e trascina le bande</string>+ <string name="eq_note">Ogni uscita ha la sua curva. Quando colleghi altre cuffie, Square passa alla loro. Le esaltazioni abbassano il volume generale della stessa quantità, così niente distorce.</string>+ <string name="eq_flat">Piatto</string>+ <string name="eq_bass_boost">Più bassi</string>+ <string name="eq_bass_reducer">Meno bassi</string>+ <string name="eq_treble_boost">Più acuti</string>+ <string name="eq_treble_reducer">Meno acuti</string>+ <string name="eq_vocal">Voce</string>+ <string name="eq_spoken">Parlato</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Elettronica</string>+ <string name="eq_classical">Classica</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Acustica</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Episodi</string>+ <string name="episode_left">mancano %s</string>+ <string name="episode_played">Ascoltato</string>+ <string name="podcasts">Podcast</string>+ <string name="new_episodes">Nuovi episodi dei tuoi podcast</string>+ <string name="podcast_count">%1$d podcast</string></resources>diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xmlindex 64a3964..c4f73db 100644--- a/app/src/main/res/values-ja/strings.xml+++ b/app/src/main/res/values-ja/strings.xml@@ -665,5 +665,44 @@<string name="link_copied_open_browser">ブラウザを開けませんでした。リンクをコピーしたので、ブラウザに貼り付けてください。</string><string name="youtube_signing_in">ログインしています…</string><string name="youtube_sign_in_private">パスワードは Google にのみ送られます。Square は Google から返されたセッションだけを保存します。</string>+ <string name="equalizer">イコライザー</string>+ <string name="page_equalizer_summary">ヘッドホンごとのカーブ</string>+ <string name="eq_speaker">本体スピーカー</string>+ <string name="eq_wired">有線ヘッドホン</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB オーディオ</string>+ <string name="eq_other">その他の出力</string>+ <string name="eq_in_use">使用中</string>+ <string name="eq_not_connected">未接続</string>+ <string name="eq_devices">デバイス</string>+ <string name="eq_curve">カーブ</string>+ <string name="eq_preamp">プリアンプ</string>+ <string name="eq_presets">プリセット</string>+ <string name="eq_save_preset">プリセットとして保存</string>+ <string name="eq_reset">リセット</string>+ <string name="eq_hint">バンドをタッチしてドラッグ</string>+ <string name="eq_note">出力ごとに専用のカーブを保持します。別のヘッドホンを接続すると、Square はそのカーブに切り替えます。ブーストした分だけ全体の音量を下げるので、音割れしません。</string>+ <string name="eq_flat">フラット</string>+ <string name="eq_bass_boost">低音強調</string>+ <string name="eq_bass_reducer">低音カット</string>+ <string name="eq_treble_boost">高音強調</string>+ <string name="eq_treble_reducer">高音カット</string>+ <string name="eq_vocal">ボーカル</string>+ <string name="eq_spoken">話し声</string>+ <string name="eq_loudness">ラウドネス</string>+ <string name="eq_rock">ロック</string>+ <string name="eq_pop">ポップ</string>+ <string name="eq_hip_hop">ヒップホップ</string>+ <string name="eq_electronic">エレクトロニック</string>+ <string name="eq_classical">クラシック</string>+ <string name="eq_jazz">ジャズ</string>+ <string name="eq_acoustic">アコースティック</string>+ <string name="podcast">ポッドキャスト</string>+ <string name="episodes">エピソード</string>+ <string name="episode_left">残り %s</string>+ <string name="episode_played">再生済み</string>+ <string name="podcasts">ポッドキャスト</string>+ <string name="new_episodes">フォロー中のポッドキャストの新着エピソード</string>+ <string name="podcast_count">%1$d 件のポッドキャスト</string></resources>diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xmlindex d21c0a1..53219ee 100644--- a/app/src/main/res/values-ko/strings.xml+++ b/app/src/main/res/values-ko/strings.xml@@ -633,4 +633,43 @@<string name="link_copied_open_browser">브라우저를 열 수 없습니다. 링크가 복사되었으니 브라우저에 붙여넣으세요.</string><string name="youtube_signing_in">로그인 중…</string><string name="youtube_sign_in_private">비밀번호는 Google에만 전달됩니다. Square는 Google이 돌려주는 세션만 보관합니다.</string>+ <string name="equalizer">이퀄라이저</string>+ <string name="page_equalizer_summary">헤드폰마다 다른 커브</string>+ <string name="eq_speaker">휴대전화 스피커</string>+ <string name="eq_wired">유선 헤드폰</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB 오디오</string>+ <string name="eq_other">기타 출력</string>+ <string name="eq_in_use">지금 사용 중</string>+ <string name="eq_not_connected">연결 안 됨</string>+ <string name="eq_devices">기기</string>+ <string name="eq_curve">커브</string>+ <string name="eq_preamp">프리앰프</string>+ <string name="eq_presets">프리셋</string>+ <string name="eq_save_preset">프리셋으로 저장</string>+ <string name="eq_reset">초기화</string>+ <string name="eq_hint">밴드를 터치하고 드래그하세요</string>+ <string name="eq_note">출력마다 고유한 커브를 유지합니다. 다른 헤드폰을 연결하면 Square가 그 커브로 바꿉니다. 부스트한 만큼 전체 음량을 낮춰 소리가 깨지지 않습니다.</string>+ <string name="eq_flat">플랫</string>+ <string name="eq_bass_boost">저음 강조</string>+ <string name="eq_bass_reducer">저음 감소</string>+ <string name="eq_treble_boost">고음 강조</string>+ <string name="eq_treble_reducer">고음 감소</string>+ <string name="eq_vocal">보컬</string>+ <string name="eq_spoken">음성</string>+ <string name="eq_loudness">라우드니스</string>+ <string name="eq_rock">록</string>+ <string name="eq_pop">팝</string>+ <string name="eq_hip_hop">힙합</string>+ <string name="eq_electronic">일렉트로닉</string>+ <string name="eq_classical">클래식</string>+ <string name="eq_jazz">재즈</string>+ <string name="eq_acoustic">어쿠스틱</string>+ <string name="podcast">팟캐스트</string>+ <string name="episodes">에피소드</string>+ <string name="episode_left">%s 남음</string>+ <string name="episode_played">재생함</string>+ <string name="podcasts">팟캐스트</string>+ <string name="new_episodes">내 팟캐스트의 새 에피소드</string>+ <string name="podcast_count">팟캐스트 %1$d개</string></resources>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex 396d46b..fe03e7a 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -609,4 +609,43 @@<string name="link_copied_open_browser">Não foi possível abrir o navegador. O link foi copiado: cole-o lá.</string><string name="youtube_signing_in">Entrando…</string><string name="youtube_sign_in_private">Sua senha vai só para o Google. O Square guarda a sessão que o Google devolve.</string>+ <string name="equalizer">Equalizador</string>+ <string name="page_equalizer_summary">Uma curva para cada fone</string>+ <string name="eq_speaker">Alto-falante do telefone</string>+ <string name="eq_wired">Fones com fio</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">Áudio USB</string>+ <string name="eq_other">Outra saída</string>+ <string name="eq_in_use">Em uso agora</string>+ <string name="eq_not_connected">Não conectado</string>+ <string name="eq_devices">Dispositivos</string>+ <string name="eq_curve">Curva</string>+ <string name="eq_preamp">Pré-amplificação</string>+ <string name="eq_presets">Predefinições</string>+ <string name="eq_save_preset">Salvar como predefinição</string>+ <string name="eq_reset">Redefinir</string>+ <string name="eq_hint">Toque e arraste as bandas</string>+ <string name="eq_note">Cada saída tem sua própria curva. Ao conectar outro fone, o Square passa para a dele. Os reforços baixam o volume geral na mesma medida, para nada distorcer.</string>+ <string name="eq_flat">Plano</string>+ <string name="eq_bass_boost">Mais graves</string>+ <string name="eq_bass_reducer">Menos graves</string>+ <string name="eq_treble_boost">Mais agudos</string>+ <string name="eq_treble_reducer">Menos agudos</string>+ <string name="eq_vocal">Voz</string>+ <string name="eq_spoken">Fala</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Eletrônica</string>+ <string name="eq_classical">Clássica</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Acústica</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Episódios</string>+ <string name="episode_left">faltam %s</string>+ <string name="episode_played">Ouvido</string>+ <string name="podcasts">Podcasts</string>+ <string name="new_episodes">Novos episódios dos seus podcasts</string>+ <string name="podcast_count">%1$d podcasts</string></resources>diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xmlindex a863b48..59d0314 100644--- a/app/src/main/res/values-ru/strings.xml+++ b/app/src/main/res/values-ru/strings.xml@@ -638,4 +638,43 @@<string name="link_copied_open_browser">Не удалось открыть браузер. Ссылка скопирована: вставьте её туда.</string><string name="youtube_signing_in">Выполняется вход…</string><string name="youtube_sign_in_private">Пароль получает только Google. Square хранит сессию, которую возвращает Google.</string>+ <string name="equalizer">Эквалайзер</string>+ <string name="page_equalizer_summary">Своя кривая для каждых наушников</string>+ <string name="eq_speaker">Динамик телефона</string>+ <string name="eq_wired">Проводные наушники</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB-аудио</string>+ <string name="eq_other">Другой выход</string>+ <string name="eq_in_use">Используется сейчас</string>+ <string name="eq_not_connected">Не подключено</string>+ <string name="eq_devices">Устройства</string>+ <string name="eq_curve">Кривая</string>+ <string name="eq_preamp">Предусиление</string>+ <string name="eq_presets">Пресеты</string>+ <string name="eq_save_preset">Сохранить как пресет</string>+ <string name="eq_reset">Сбросить</string>+ <string name="eq_hint">Нажмите и перетащите полосы</string>+ <string name="eq_note">У каждого выхода своя кривая. Когда вы подключаете другие наушники, Square переключается на их кривую. Усиление снижает общую громкость на ту же величину, чтобы ничего не искажалось.</string>+ <string name="eq_flat">Ровно</string>+ <string name="eq_bass_boost">Больше басов</string>+ <string name="eq_bass_reducer">Меньше басов</string>+ <string name="eq_treble_boost">Больше высоких</string>+ <string name="eq_treble_reducer">Меньше высоких</string>+ <string name="eq_vocal">Вокал</string>+ <string name="eq_spoken">Речь</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Рок</string>+ <string name="eq_pop">Поп</string>+ <string name="eq_hip_hop">Хип-хоп</string>+ <string name="eq_electronic">Электроника</string>+ <string name="eq_classical">Классика</string>+ <string name="eq_jazz">Джаз</string>+ <string name="eq_acoustic">Акустика</string>+ <string name="podcast">Подкаст</string>+ <string name="episodes">Выпуски</string>+ <string name="episode_left">осталось %s</string>+ <string name="episode_played">Прослушано</string>+ <string name="podcasts">Подкасты</string>+ <string name="new_episodes">Новые выпуски ваших подкастов</string>+ <string name="podcast_count">Подкастов: %1$d</string></resources>diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xmlindex db022a0..f39d48d 100644--- a/app/src/main/res/values-tr/strings.xml+++ b/app/src/main/res/values-tr/strings.xml@@ -622,4 +622,43 @@<string name="link_copied_open_browser">Tarayıcı açılamadı. Bağlantı kopyalandı: oraya yapıştır.</string><string name="youtube_signing_in">Giriş yapılıyor…</string><string name="youtube_sign_in_private">Şifren yalnızca Google\'a gider. Square, Google\'ın verdiği oturumu saklar.</string>+ <string name="equalizer">Ekolayzer</string>+ <string name="page_equalizer_summary">Her kulaklık için ayrı eğri</string>+ <string name="eq_speaker">Telefon hoparlörü</string>+ <string name="eq_wired">Kablolu kulaklık</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB ses</string>+ <string name="eq_other">Diğer çıkış</string>+ <string name="eq_in_use">Şu an kullanılıyor</string>+ <string name="eq_not_connected">Bağlı değil</string>+ <string name="eq_devices">Cihazlar</string>+ <string name="eq_curve">Eğri</string>+ <string name="eq_preamp">Ön yükseltme</string>+ <string name="eq_presets">Ön ayarlar</string>+ <string name="eq_save_preset">Ön ayar olarak kaydet</string>+ <string name="eq_reset">Sıfırla</string>+ <string name="eq_hint">Bantlara dokunup sürükleyin</string>+ <string name="eq_note">Her çıkışın kendi eğrisi vardır. Başka bir kulaklık bağladığınızda Square onunkine geçer. Yükseltmeler genel seviyeyi aynı miktarda düşürür, böylece hiçbir şey bozulmaz.</string>+ <string name="eq_flat">Düz</string>+ <string name="eq_bass_boost">Bas artırıcı</string>+ <string name="eq_bass_reducer">Bas azaltıcı</string>+ <string name="eq_treble_boost">Tiz artırıcı</string>+ <string name="eq_treble_reducer">Tiz azaltıcı</string>+ <string name="eq_vocal">Vokal</string>+ <string name="eq_spoken">Konuşma</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Elektronik</string>+ <string name="eq_classical">Klasik</string>+ <string name="eq_jazz">Caz</string>+ <string name="eq_acoustic">Akustik</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Bölümler</string>+ <string name="episode_left">%s kaldı</string>+ <string name="episode_played">Dinlendi</string>+ <string name="podcasts">Podcast\'ler</string>+ <string name="new_episodes">Podcast\'lerinden yeni bölümler</string>+ <string name="podcast_count">%1$d podcast</string></resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 4312f73..e905546 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -674,4 +674,43 @@<string name="link_copied_open_browser">Couldn\'t open the browser. The link is copied: paste it there.</string><string name="youtube_signing_in">Signing in…</string><string name="youtube_sign_in_private">Your password goes only to Google. Square keeps the session Google gives back.</string>+ <string name="equalizer">Equalizer</string>+ <string name="page_equalizer_summary">A curve for each pair of headphones</string>+ <string name="eq_speaker">Phone speaker</string>+ <string name="eq_wired">Wired headphones</string>+ <string name="eq_bluetooth">Bluetooth</string>+ <string name="eq_usb">USB audio</string>+ <string name="eq_other">Other output</string>+ <string name="eq_in_use">In use now</string>+ <string name="eq_not_connected">Not connected</string>+ <string name="eq_devices">Devices</string>+ <string name="eq_curve">Curve</string>+ <string name="eq_preamp">Preamp</string>+ <string name="eq_presets">Presets</string>+ <string name="eq_save_preset">Save as preset</string>+ <string name="eq_reset">Reset to flat</string>+ <string name="eq_hint">Touch and drag the bands</string>+ <string name="eq_note">Each output keeps its own curve. When you connect other headphones, Square switches to theirs. Boosts lower the overall level by the same amount, so nothing clips.</string>+ <string name="eq_flat">Flat</string>+ <string name="eq_bass_boost">Bass boost</string>+ <string name="eq_bass_reducer">Bass reducer</string>+ <string name="eq_treble_boost">Treble boost</string>+ <string name="eq_treble_reducer">Treble reducer</string>+ <string name="eq_vocal">Vocal</string>+ <string name="eq_spoken">Spoken word</string>+ <string name="eq_loudness">Loudness</string>+ <string name="eq_rock">Rock</string>+ <string name="eq_pop">Pop</string>+ <string name="eq_hip_hop">Hip-hop</string>+ <string name="eq_electronic">Electronic</string>+ <string name="eq_classical">Classical</string>+ <string name="eq_jazz">Jazz</string>+ <string name="eq_acoustic">Acoustic</string>+ <string name="podcast">Podcast</string>+ <string name="episodes">Episodes</string>+ <string name="episode_left">%s left</string>+ <string name="episode_played">Played</string>+ <string name="podcasts">Podcasts</string>+ <string name="new_episodes">New episodes from your podcasts</string>+ <string name="podcast_count">%1$d podcasts</string></resources>diff --git a/native/src/catalog.rs b/native/src/catalog.rsindex 3380d79..4ae505a 100644--- a/native/src/catalog.rs+++ b/native/src/catalog.rs@@ -626,12 +626,18 @@ pub fn track_video(track_uri: &str) -> EngineResult<String> {let uri = track_uri.to_string();block_on(async move {- let associated = match extension(&session, &uri, VIDEO_ASSOCIATIONS).await? {- Some(bytes) => uris_in(&bytes)- .into_iter()- .find(|found| found != &uri)- .ok_or_else(|| String::new()),- None => Err(String::new()),+ // A video podcast's episode is its own video: there is no second+ // entity to be pointed at, so the file is asked of the episode itself.+ let associated = if uri.starts_with("spotify:episode:") {+ Ok(uri.clone())+ } else {+ match extension(&session, &uri, VIDEO_ASSOCIATIONS).await? {+ Some(bytes) => uris_in(&bytes)+ .into_iter()+ .find(|found| found != &uri)+ .ok_or_else(|| String::new()),+ None => Err(String::new()),+ }};// No association is the ordinary answer: almost no track has a video.diff --git a/pathfinder.json b/pathfinder.jsonindex 617ffbe..d472383 100644--- a/pathfinder.json+++ b/pathfinder.json@@ -7,5 +7,9 @@"search": "db61238974d27839a136c9dc02bfdbe3fab7635f21cf85976ebff9a1ee281345","artistOverview": "9f8134ef565e78621f1e1793555bd6633c5ac144ae0f89604ed3ae3f80b3c8e6","playlistSection": "2615df403a9043c1d7d3094fbeb4c9653b07b11a33d8081fbd31f0f7959ff4a1",+ "show": "b475447846f37cc426add800b995a7859c169c53c72b62de6338c0c40a5dacea",+ "showEpisodes": "3539d746cf882f3909660de40b4ef472b3f5893a0761d617c282541de5d412c5",+ "libraryContents": "390c78e5b951029bad359785e69b07b536a509c581cbcd0aded5e5067f187455",+ "libraryEdit": "896ebcb47815681340860d121cb5d494e157e2a78d3950385cd54e0393c67148","appVersion": "1.2.97.155.g5dd0dcaf-development"}