diff --git a/.github/nightly-notes/2026-12-04-feat-similar-songs-radio-discover.md b/.github/nightly-notes/2026-12-04-feat-similar-songs-radio-discover.md new file mode 100644 index 0000000000..657fff2242 --- /dev/null +++ b/.github/nightly-notes/2026-12-04-feat-similar-songs-radio-discover.md @@ -0,0 +1,5 @@ +## New +- Endless radio mixes in songs similar to the one playing, with a "Mix in similar songs" switch + +## Improved +- The music home shelf "Similar to what you play" now works for everyone, no Last.fm account needed diff --git a/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt b/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt index eab918efb8..07cf76fd26 100644 --- a/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt +++ b/app/src/main/java/io/github/aedev/flow/data/local/PlayerPreferences.kt @@ -114,6 +114,7 @@ class PlayerPreferences( val START_VIDEOS_PAUSED = booleanPreferencesKey("start_videos_paused") val OPEN_VIDEOS_FULLSCREEN = booleanPreferencesKey("open_videos_fullscreen") val MUSIC_ENDLESS_RADIO_ENABLED = booleanPreferencesKey("music_endless_radio_enabled") + val MUSIC_RADIO_SIMILAR_MIX = booleanPreferencesKey("music_radio_similar_mix") val AUTOPLAY_COUNTDOWN_SECONDS = intPreferencesKey("autoplay_countdown_seconds") val VIDEO_LOOP_ENABLED = booleanPreferencesKey("video_loop_enabled") val VIDEO_AMBIENT_MODE_ENABLED = booleanPreferencesKey("video_ambient_mode_enabled") @@ -2588,6 +2589,16 @@ class PlayerPreferences( } } + val musicRadioSimilarMix: Flow = + context.playerPreferencesDataStore.data + .map { preferences -> preferences[Keys.MUSIC_RADIO_SIMILAR_MIX] ?: true } + + suspend fun setMusicRadioSimilarMix(enabled: Boolean) { + context.playerPreferencesDataStore.edit { preferences -> + preferences[Keys.MUSIC_RADIO_SIMILAR_MIX] = enabled + } + } + // Autoplay for the playback queue (playlists / watch later) — independent of related-video autoplay. val queueAutoplayEnabled: Flow = context.playerPreferencesDataStore.data diff --git a/app/src/main/java/io/github/aedev/flow/data/scrobble/LastFmDiscovery.kt b/app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarDiscovery.kt similarity index 82% rename from app/src/main/java/io/github/aedev/flow/data/scrobble/LastFmDiscovery.kt rename to app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarDiscovery.kt index b19dd52edd..9d8d84610f 100644 --- a/app/src/main/java/io/github/aedev/flow/data/scrobble/LastFmDiscovery.kt +++ b/app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarDiscovery.kt @@ -1,8 +1,9 @@ -package io.github.aedev.flow.data.scrobble +package io.github.aedev.flow.data.music.similarity import io.github.aedev.flow.data.music.YtMusicMatcher import io.github.aedev.flow.data.music.model.MusicTrack import io.github.aedev.flow.data.recommendation.music.MusicBrainEngine +import io.github.aedev.flow.data.scrobble.matchKey import io.github.aedev.flow.utils.PerformanceDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll @@ -14,15 +15,15 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Songs Last.fm's listeners pair with what the viewer has on repeat: a second opinion beside - * YouTube's own suggestions. Only for viewers signed in to Last.fm, fetched when the shelf is first - * shown and kept for [TTL_MS] while the seeds stay the same. + * Songs other listeners pair with what the viewer has on repeat: a second opinion beside YouTube's + * own suggestions, for everyone with listening history. Fetched when the shelf is first shown and + * kept for [TTL_MS] while the seeds stay the same. */ @Singleton -class LastFmDiscovery +class SimilarDiscovery @Inject constructor( - private val scrobbler: Scrobbler, + private val similarity: MusicSimilarity, private val musicBrain: MusicBrainEngine, private val matcher: YtMusicMatcher, ) { @@ -43,15 +44,15 @@ class LastFmDiscovery val now = System.currentTimeMillis() cached?.takeIf { it.seeds == seedIds && now - it.atMs < TTL_MS }?.let { return@withContext it.tracks } if (seeds.isEmpty()) return@withContext emptyList() + val seedPairs = seeds.map { (it.artists.firstOrNull()?.name ?: it.artist) to it.title } val similar = - seeds.map { seed -> - val artist = seed.artists.firstOrNull()?.name ?: seed.artist - scrobbler.similarTracks(artist, seed.title, PER_SEED).getOrDefault(emptyList()) + coroutineScope { + seedPairs.map { (artist, title) -> async { similarity.similarTracks(artist, title, PER_SEED) } }.awaitAll() } val picks = discoveryPicks( similar = similar, - seeds = seeds.map { (it.artists.firstOrNull()?.name ?: it.artist) to it.title }, + seeds = seedPairs, hiddenArtists = musicBrain.hiddenArtists.value, limit = SHOWN, ) diff --git a/app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongs.kt b/app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongs.kt new file mode 100644 index 0000000000..ef5ea3bcc7 --- /dev/null +++ b/app/src/main/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongs.kt @@ -0,0 +1,58 @@ +package io.github.aedev.flow.data.music.similarity + +import io.github.aedev.flow.data.music.YtMusicMatcher +import io.github.aedev.flow.data.music.model.MusicTrack +import io.github.aedev.flow.data.recommendation.music.isHiddenArtist +import io.github.aedev.flow.data.scrobble.matchKey +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import javax.inject.Inject +import javax.inject.Singleton + +/** + * A few songs similar to the one playing, found on YouTube Music, for endless radio to mix in. One + * similarity lookup per call, then at most [PER_CALL] searches in a single parallel round. + */ +@Singleton +class SimilarRadioSongs + @Inject + constructor( + private val similarity: MusicSimilarity, + private val matcher: YtMusicMatcher, + ) { + suspend fun forTrack( + seed: MusicTrack, + known: List, + hiddenArtists: Set, + ): List { + val artist = seed.artists.firstOrNull()?.name ?: seed.artist + if (artist.isBlank() || seed.title.isBlank()) return emptyList() + val candidates = + radioCandidates(similarity.similarTracks(artist, seed.title, CANDIDATES), known + seed, hiddenArtists, PER_CALL) + return coroutineScope { + candidates.map { (by, title) -> async { runCatching { matcher.find(by, title) }.getOrNull() } }.awaitAll() + }.filterNotNull() + .filterNot { it.isHiddenArtist(hiddenArtists) } + } + + private companion object { + const val CANDIDATES = 20 + const val PER_CALL = 3 + } + } + +/** Similar songs not already queued, pooled or by a hidden artist, best first, at most [limit]. */ +internal fun radioCandidates( + similar: List>, + known: List, + hiddenArtists: Set, + limit: Int, +): List> { + val knownKeys = known.mapTo(HashSet()) { (it.artists.firstOrNull()?.name ?: it.artist).matchKey() to it.title.matchKey() } + val hidden = hiddenArtists.mapTo(HashSet()) { it.matchKey() } + return similar + .filterNot { (artist, title) -> artist.matchKey() in hidden || (artist.matchKey() to title.matchKey()) in knownKeys } + .distinctBy { (artist, title) -> artist.matchKey() to title.matchKey() } + .take(limit) +} diff --git a/app/src/main/java/io/github/aedev/flow/player/MusicRadioPlanner.kt b/app/src/main/java/io/github/aedev/flow/player/MusicRadioPlanner.kt index 1de1b3985e..baa61969c8 100644 --- a/app/src/main/java/io/github/aedev/flow/player/MusicRadioPlanner.kt +++ b/app/src/main/java/io/github/aedev/flow/player/MusicRadioPlanner.kt @@ -146,4 +146,30 @@ internal object MusicRadioPlanner { queueIds: Set, limit: Int, ): List = pool.filterNot { it.videoId in queueIds }.take(limit) + + /** One similar song after every [SIMILAR_EVERY] - 1 ranked ones: about one in [SIMILAR_EVERY]. */ + const val SIMILAR_EVERY = 4 + + /** + * Mixes [similar] songs into a [ranked] refill, leaving out any already queued, pooled + * ([knownIds]) or in the refill itself. Songs left over go at the end, so a short refill still + * carries them. + */ + fun blendSimilar( + ranked: List, + similar: List, + knownIds: Set, + ): List { + val rankedIds = ranked.mapTo(HashSet()) { it.videoId } + val extra = similar.distinctBy { it.videoId }.filterNot { it.videoId in knownIds || it.videoId in rankedIds } + if (extra.isEmpty()) return ranked + val blended = ArrayList(ranked.size + extra.size) + var next = 0 + ranked.forEachIndexed { index, track -> + blended += track + if ((index + 1) % (SIMILAR_EVERY - 1) == 0 && next < extra.size) blended += extra[next++] + } + blended += extra.drop(next) + return blended + } } diff --git a/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt b/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt index a6c967bb08..890f125085 100644 --- a/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt +++ b/app/src/main/java/io/github/aedev/flow/service/Media3MusicService.kt @@ -55,6 +55,7 @@ import io.github.aedev.flow.data.localmedia.LocalLyricsReader import io.github.aedev.flow.data.localmedia.LocalMediaIds import io.github.aedev.flow.data.music.YouTubeMusicService import io.github.aedev.flow.data.music.model.MusicTrack +import io.github.aedev.flow.data.music.similarity.SimilarRadioSongs import io.github.aedev.flow.data.newmusic.InnertubeMusicService import io.github.aedev.flow.data.profile.ActiveProfile import io.github.aedev.flow.data.profile.ProfileSwitchGate @@ -113,6 +114,7 @@ import io.github.aedev.flow.utils.NetworkState import io.github.aedev.flow.utils.potoken.WebPoTokenSession import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine @@ -120,6 +122,7 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import java.util.Locale import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject @@ -150,6 +153,7 @@ class Media3MusicService : MediaLibraryService() { private const val RADIO_MIN_UPCOMING = 3 private const val RADIO_APPEND_BATCH = 10 private const val RADIO_POOL_LOW_WATER = 15 + private const val RADIO_SIMILAR_TIMEOUT_MS = 10_000L private const val MUSIC_URI_SCHEME = "music" private val CommandToggleShuffle = SessionCommand(ACTION_TOGGLE_SHUFFLE, Bundle.EMPTY) @@ -237,6 +241,7 @@ class Media3MusicService : MediaLibraryService() { @Volatile private var usedRadioAnchors: Set = emptySet() private var radioTopUpJob: Job? = null private var radioAutoplayEnabled = true + private var radioSimilarMixEnabled = true private var pauseWhenMuted = false private lateinit var pauseLog: MusicPauseLog private var pausedForMute = false @@ -287,6 +292,9 @@ class Media3MusicService : MediaLibraryService() { @Inject lateinit var scrobbler: io.github.aedev.flow.data.scrobble.Scrobbler + @Inject + lateinit var similarRadioSongs: SimilarRadioSongs + @Inject lateinit var videoSwitch: MusicVideoSwitch @@ -366,6 +374,7 @@ class Media3MusicService : MediaLibraryService() { if (enabled && !wasEnabled && ::player.isInitialized) maybeExtendRadio() } } + lifecycleScope.launch { prefs.musicRadioSimilarMix.collect { radioSimilarMixEnabled = it } } lifecycleScope.launch { prefs.pauseMusicWhenMuted.collect { pauseWhenMuted = it } } lifecycleScope.launch { prefs.musicLoudnessNormalizationEnabled.collect { @@ -1730,10 +1739,14 @@ class Media3MusicService : MediaLibraryService() { radioContinuation = null radioEndpoint = null mapped = - YouTubeMusicService - .getRelatedMusic(seedId, 20, audioOnly = true) + similarSongsForRadio() .filterNot { it.videoId == seedId } - .distinctBy { it.videoId } + .ifEmpty { + YouTubeMusicService + .getRelatedMusic(seedId, 20, audioOnly = true) + .filterNot { it.videoId == seedId } + .distinctBy { it.videoId } + } } else { radioContinuation = page?.continuation radioEndpoint = page?.endpoint @@ -1824,6 +1837,7 @@ class Media3MusicService : MediaLibraryService() { lifecycleScope.launch(Dispatchers.IO) { try { val manager = io.github.aedev.flow.player.EnhancedMusicPlayerManager + val similar = async { similarSongsForRadio() } val endpoint = radioEndpoint val continuation = radioContinuation val page = @@ -1837,10 +1851,16 @@ class Media3MusicService : MediaLibraryService() { ?: (manager.automixItems.value.lastOrNull() ?: manager.queue.value.lastOrNull()) ?.videoId ?.takeUnless(LocalMediaIds::isLocal) - ?: return@launch + ?: run { + similar.cancel() + return@launch + } YouTube.next(WatchEndpoint(playlistId = "RDAMVM$anchorId")).getOrNull() } - if (page == null) return@launch + if (page == null) { + similar.cancel() + return@launch + } radioContinuation = page.continuation radioEndpoint = page.endpoint @@ -1849,11 +1869,16 @@ class Media3MusicService : MediaLibraryService() { .mapNotNull { InnertubeMusicService.convertToMusicTrack(it) } .distinctBy { it.videoId } val tail = manager.automixItems.value.lastOrNull() ?: manager.queue.value.lastOrNull() + val knownIds = (manager.queue.value + manager.automixItems.value).mapTo(HashSet()) { it.videoId } val ranked = - musicBrain.sequenceRadioBatch( - musicBrain.rankTracks(mapped, "radio"), - tail, - MusicRadioPlanner.MAX_POOL_SIZE, + MusicRadioPlanner.blendSimilar( + musicBrain.sequenceRadioBatch( + musicBrain.rankTracks(mapped, "radio"), + tail, + MusicRadioPlanner.MAX_POOL_SIZE, + ), + similar.await(), + knownIds, ) Log.d(TAG, "Radio pool topped up with ${ranked.size} tracks, continuation=${radioContinuation != null}") if (ranked.isNotEmpty()) { @@ -1873,6 +1898,27 @@ class Media3MusicService : MediaLibraryService() { } } + /** + * A few songs similar to the playing one, from one similarity lookup; empty when the mix is off + * or the lookup fails or is slow, so the station carries on with YouTube's own picks. + */ + private suspend fun similarSongsForRadio(): List { + if (!radioSimilarMixEnabled) return emptyList() + val manager = io.github.aedev.flow.player.EnhancedMusicPlayerManager + val seed = manager.currentTrack.value?.takeUnless { LocalMediaIds.isLocal(it.videoId) } ?: return emptyList() + val known = manager.queue.value + manager.automixItems.value + return try { + withTimeoutOrNull(RADIO_SIMILAR_TIMEOUT_MS) { + similarRadioSongs.forTrack(seed, known, musicBrain.hiddenArtists.value) + }.orEmpty() + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Similar songs for radio failed: ${e.message}") + emptyList() + } + } + private fun updateNotification() { if (!::mediaLibrarySession.isInitialized) return diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeFeed.kt b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeFeed.kt index 842b3e606e..10a5a0c92a 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeFeed.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeFeed.kt @@ -176,7 +176,7 @@ fun LazyListScope.musicHomeFeed( } } - lastFmDiscovery(library, downloaded, onSongClick, onTrackMenu) + similarDiscovery(library, downloaded, onSongClick, onTrackMenu) sectionOrder.filter { shown(MusicHomeShelf.of(it)) }.forEach { sectionType -> when (sectionType) { diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeLibraryShelves.kt b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeLibraryShelves.kt index c1821ecb83..385c3b6bb3 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeLibraryShelves.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeLibraryShelves.kt @@ -22,7 +22,6 @@ class MusicHomeLibrary( val onPlaylistClick: (String) -> Unit = {}, val onAllPlaylistsClick: () -> Unit = {}, val onAllSubscriptionsClick: () -> Unit = {}, - val discoveryAvailable: Boolean = false, val discovery: List = emptyList(), val onDiscoveryShown: () -> Unit = {}, ) @@ -86,21 +85,20 @@ internal fun likedMusicCard(liked: List): MusicPlaylist? = } /** Asks for its songs only once it is scrolled to, and draws nothing until they arrive. */ -internal fun LazyListScope.lastFmDiscovery( +internal fun LazyListScope.similarDiscovery( library: MusicHomeLibrary, downloaded: Set, onSongClick: (MusicTrack, List, String?) -> Unit, onTrackMenu: (MusicTrack) -> Unit, ) { - if (!library.discoveryAvailable || MusicHomeShelf.LASTFM_DISCOVER in library.hidden) return + if (MusicHomeShelf.LASTFM_DISCOVER in library.hidden) return item(key = "lastfm_discover", contentType = MusicShelfContentType.Discovery) { LaunchedEffect(Unit) { library.onDiscoveryShown() } val tracks = library.discovery if (tracks.isNotEmpty()) { - val title = stringResource(R.string.music_home_lastfm_discover) + val title = stringResource(R.string.music_home_similar_discover) MusicTrackCardShelf( title = title, - subtitle = stringResource(R.string.music_home_lastfm_discover_subtitle), tracks = tracks, keyNamespace = "lastfm_discover", downloadedTrackIds = downloaded, diff --git a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeShelf.kt b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeShelf.kt index 3f738c3787..a3d32b4013 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeShelf.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/components/music/section/MusicHomeShelf.kt @@ -37,7 +37,7 @@ enum class MusicHomeShelf( POPULAR_ARTISTS(R.string.section_popular_artists), MIXED_FOR_YOU(R.string.section_mixed_for_you), MOODS_AND_GENRES(R.string.section_mood_and_genres), - LASTFM_DISCOVER(R.string.music_home_lastfm_discover), + LASTFM_DISCOVER(R.string.music_home_similar_discover), ; companion object { diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/music/EnhancedMusicScreen.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/music/EnhancedMusicScreen.kt index ab0ff36887..37bf9650d8 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/music/EnhancedMusicScreen.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/music/EnhancedMusicScreen.kt @@ -90,7 +90,6 @@ fun EnhancedMusicScreen( val likedMusic by libraryViewModel.likedMusic.collectAsStateWithLifecycle() val musicSubscriptions by libraryViewModel.subscriptions.collectAsStateWithLifecycle() val hiddenShelves by libraryViewModel.hiddenShelves.collectAsStateWithLifecycle() - val lastFmSignedIn by libraryViewModel.lastFmSignedIn.collectAsStateWithLifecycle() val discovery by libraryViewModel.discovery.collectAsStateWithLifecycle() val library = remember( @@ -101,7 +100,6 @@ fun EnhancedMusicScreen( onPlaylistClick, onAllPlaylistsClick, onAllSubscriptionsClick, - lastFmSignedIn, discovery, ) { MusicHomeLibrary( @@ -112,7 +110,6 @@ fun EnhancedMusicScreen( onPlaylistClick = onPlaylistClick, onAllPlaylistsClick = onAllPlaylistsClick, onAllSubscriptionsClick = onAllSubscriptionsClick, - discoveryAvailable = lastFmSignedIn, discovery = discovery, onDiscoveryShown = libraryViewModel::loadDiscovery, ) diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/music/MusicHomeLibraryViewModel.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/music/MusicHomeLibraryViewModel.kt index 4e00570528..9d298dbe3e 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/music/MusicHomeLibraryViewModel.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/music/MusicHomeLibraryViewModel.kt @@ -10,10 +10,8 @@ import io.github.aedev.flow.data.local.SubscriptionRepository import io.github.aedev.flow.data.music.model.ArtistDetails import io.github.aedev.flow.data.music.model.MusicPlaylist import io.github.aedev.flow.data.music.model.MusicTrack +import io.github.aedev.flow.data.music.similarity.SimilarDiscovery import io.github.aedev.flow.data.playlist.sortedFor -import io.github.aedev.flow.data.scrobble.LastFmDiscovery -import io.github.aedev.flow.data.scrobble.ScrobbleService -import io.github.aedev.flow.data.scrobble.ScrobbleStore import io.github.aedev.flow.ui.components.music.section.MusicHomeShelf import io.github.aedev.flow.ui.components.music.section.likedMusicCard import kotlinx.coroutines.Job @@ -32,8 +30,8 @@ private const val SHELF_LIMIT = 20 /** * The viewer's own corner of the music home: their liked songs and music playlists in the playlists page's order, - * the music channels they subscribe to, newest first, the sections they chose to hide, and, for - * Last.fm accounts, the discovery shelf. Only that shelf touches the network, and only once shown. + * the music channels they subscribe to, newest first, the sections they chose to hide, and the + * discovery shelf of songs similar to what they play. Only that shelf touches the network, and only once shown. */ @HiltViewModel class MusicHomeLibraryViewModel @@ -43,8 +41,7 @@ class MusicHomeLibraryViewModel likedVideosRepository: LikedVideosRepository, subscriptionRepository: SubscriptionRepository, preferences: PlayerPreferences, - scrobbleStore: ScrobbleStore, - private val lastFmDiscovery: LastFmDiscovery, + private val similarDiscovery: SimilarDiscovery, ) : ViewModel() { private val sharing = SharingStarted.WhileSubscribed(5_000) @@ -84,12 +81,6 @@ class MusicHomeLibraryViewModel } }.stateIn(viewModelScope, sharing, emptyList()) - val lastFmSignedIn: StateFlow = - scrobbleStore.settings - .map { ScrobbleService.LASTFM in it.accounts } - .distinctUntilChanged() - .stateIn(viewModelScope, sharing, false) - private val _discovery = MutableStateFlow>(emptyList()) val discovery: StateFlow> = _discovery.asStateFlow() private var discoveryJob: Job? = null @@ -98,7 +89,7 @@ class MusicHomeLibraryViewModel fun loadDiscovery() { if (discoveryJob?.isActive == true) return discoveryJob = - viewModelScope.launch { _discovery.value = runCatching { lastFmDiscovery.tracks() }.getOrDefault(_discovery.value) } + viewModelScope.launch { _discovery.value = runCatching { similarDiscovery.tracks() }.getOrDefault(_discovery.value) } } val hiddenShelves: StateFlow> = diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlaybackIndex.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlaybackIndex.kt index a22d942013..c9d87ffa1a 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlaybackIndex.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/index/PlaybackIndex.kt @@ -421,6 +421,14 @@ internal object PlaybackIndex { section = R.string.settings_section_music, destination = page, ) + val similarMix = + SettingEntry( + key = "playback.radio_similar_mix", + title = R.string.music_radio_similar_mix_title, + summary = R.string.music_radio_similar_mix_desc, + section = R.string.settings_section_music, + destination = page, + ) val pauseMusicWhenMuted = SettingEntry( key = "playback.pause_music_when_muted", @@ -548,6 +556,7 @@ internal object PlaybackIndex { PlaybackShortsIndex.all + listOf( endlessRadio, + similarMix, pauseMusicWhenMuted, musicNormalizeVolume, ) + diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSections.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSections.kt index 49b6f1581e..2e75c8ac4a 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSections.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSections.kt @@ -198,6 +198,7 @@ internal fun SettingsListScope.playbackSections( shortsPlayerSection(viewModel, state, openDialog) group(key = "playback.music", header = R.string.settings_section_music) { switch(PlaybackIndex.endlessRadio, viewModel.endlessRadio, viewModel::setEndlessRadio) + switch(PlaybackIndex.similarMix, viewModel.similarMix, viewModel::setSimilarMix) switch(PlaybackIndex.pauseMusicWhenMuted, viewModel.pauseMusicWhenMuted, viewModel::setPauseMusicWhenMuted) switch(PlaybackIndex.musicNormalizeVolume, viewModel.musicNormalizeVolume, viewModel::setMusicNormalizeVolume) switch(PlaybackCrossfadeIndex.crossfade, viewModel.crossfadeEnabled, viewModel::setCrossfadeEnabled) diff --git a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSettingsViewModel.kt b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSettingsViewModel.kt index 2a6b635f3c..7a1e68897d 100644 --- a/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSettingsViewModel.kt +++ b/app/src/main/java/io/github/aedev/flow/ui/screens/settings/playback/PlaybackSettingsViewModel.kt @@ -143,6 +143,7 @@ class PlaybackSettingsViewModel val shortsContinueIntoFeed = preferences.shortsQueueContinuesIntoFeed.asState(true) val endlessRadio = preferences.musicEndlessRadioEnabled.asState(true) + val similarMix = preferences.musicRadioSimilarMix.asState(true) val musicVideoSwitch = preferences.musicVideoSwitch.asState(false) val pauseMusicWhenMuted = preferences.pauseMusicWhenMuted.asState(false) val musicNormalizeVolume = preferences.musicLoudnessNormalizationEnabled.asState(true) @@ -351,6 +352,8 @@ class PlaybackSettingsViewModel fun setEndlessRadio(value: Boolean) = write { preferences.setMusicEndlessRadioEnabled(value) } + fun setSimilarMix(value: Boolean) = write { preferences.setMusicRadioSimilarMix(value) } + fun setMusicVideoSwitch(value: Boolean) = write { preferences.setMusicVideoSwitch(value) } fun setPauseMusicWhenMuted(value: Boolean) = write { preferences.setPauseMusicWhenMuted(value) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4f3a7db41f..27d384cb7d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2645,6 +2645,8 @@ Music recommendations Endless radio Add similar songs when the queue ends + Mix in similar songs + Endless radio adds songs other listeners pair with this one Song and video switch Switch between a song and its music video in the player Lock screen player @@ -5512,8 +5514,7 @@ Name URL An http:// or https:// address - Discover with Last.fm - Picked by Last.fm listeners from your on repeat + Similar to what you play Player Play or pause Back diff --git a/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt b/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt index ed1cb65a85..af74bf5923 100644 --- a/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt +++ b/app/src/test/java/io/github/aedev/flow/data/local/DevicePreferencesSplitTest.kt @@ -25,7 +25,7 @@ class DevicePreferencesSplitTest { val device = keyNames("DeviceKeys") assertThat(device).hasSize(153) - assertThat(profile).hasSize(308) + assertThat(profile).hasSize(309) assertThat(device.toSet()).hasSize(device.size) assertThat(profile.toSet()).hasSize(profile.size) assertThat(device.intersect(profile.toSet())).isEmpty() diff --git a/app/src/test/java/io/github/aedev/flow/data/scrobble/LastFmDiscoveryTest.kt b/app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarDiscoveryTest.kt similarity index 91% rename from app/src/test/java/io/github/aedev/flow/data/scrobble/LastFmDiscoveryTest.kt rename to app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarDiscoveryTest.kt index f432841eaf..15c64a1778 100644 --- a/app/src/test/java/io/github/aedev/flow/data/scrobble/LastFmDiscoveryTest.kt +++ b/app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarDiscoveryTest.kt @@ -1,9 +1,9 @@ -package io.github.aedev.flow.data.scrobble +package io.github.aedev.flow.data.music.similarity import com.google.common.truth.Truth.assertThat import org.junit.Test -class LastFmDiscoveryTest { +class SimilarDiscoveryTest { @Test fun `picks alternate between seeds and skip the seeds themselves and hidden artists`() { val picks = diff --git a/app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongsTest.kt b/app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongsTest.kt new file mode 100644 index 0000000000..ad53105169 --- /dev/null +++ b/app/src/test/java/io/github/aedev/flow/data/music/similarity/SimilarRadioSongsTest.kt @@ -0,0 +1,30 @@ +package io.github.aedev.flow.data.music.similarity + +import com.google.common.truth.Truth.assertThat +import io.github.aedev.flow.data.music.model.MusicTrack +import org.junit.Test + +class SimilarRadioSongsTest { + private fun track( + artist: String, + title: String, + ) = MusicTrack(videoId = "$artist-$title", title = title, artist = artist, thumbnailUrl = "", duration = 100) + + @Test + fun `candidates leave out queued songs, hidden artists and repeats, best first`() { + val similar = + listOf( + "Queued" to "Song", + "Hidden" to "Any", + "A" to "One", + "a" to "ONE", + "B" to "Two", + "C" to "Three", + "D" to "Four", + ) + + val candidates = radioCandidates(similar, known = listOf(track("queued", "song")), hiddenArtists = setOf("hidden"), limit = 3) + + assertThat(candidates).containsExactly("A" to "One", "B" to "Two", "C" to "Three").inOrder() + } +} diff --git a/app/src/test/java/io/github/aedev/flow/player/MusicRadioPlannerTest.kt b/app/src/test/java/io/github/aedev/flow/player/MusicRadioPlannerTest.kt index 0558c9e552..c1b62abeb4 100644 --- a/app/src/test/java/io/github/aedev/flow/player/MusicRadioPlannerTest.kt +++ b/app/src/test/java/io/github/aedev/flow/player/MusicRadioPlannerTest.kt @@ -267,4 +267,25 @@ class MusicRadioPlannerTest { assertThat(MusicRadioPlanner.radioAnchors("seed", page)).hasSize(MusicRadioPlanner.MAX_RADIO_ANCHORS) } + + @Test + fun `similar songs take about one slot in four and skip what is known`() { + val ranked = (1..7).map { track("r$it") } + val similar = listOf(track("s1"), track("queued"), track("r2"), track("s1"), track("s2")) + + val blended = MusicRadioPlanner.blendSimilar(ranked, similar, knownIds = setOf("queued")) + + assertThat(blended.map { it.videoId }) + .containsExactly("r1", "r2", "r3", "s1", "r4", "r5", "r6", "s2", "r7") + .inOrder() + } + + @Test + fun `similar songs left over, or with nothing ranked, go at the end`() { + assertThat(MusicRadioPlanner.blendSimilar(emptyList(), listOf(track("s1"), track("s2")), emptySet()).map { it.videoId }) + .containsExactly("s1", "s2") + .inOrder() + assertThat(MusicRadioPlanner.blendSimilar(listOf(track("r1")), emptyList(), emptySet()).map { it.videoId }) + .containsExactly("r1") + } }