Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -2588,6 +2589,16 @@ class PlayerPreferences(
}
}

val musicRadioSimilarMix: Flow<Boolean> =
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<Boolean> =
context.playerPreferencesDataStore.data
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
) {
Expand All @@ -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,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -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<MusicTrack>,
hiddenArtists: Set<String>,
): List<MusicTrack> {
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<Pair<String, String>>,
known: List<MusicTrack>,
hiddenArtists: Set<String>,
limit: Int,
): List<Pair<String, String>> {
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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,30 @@ internal object MusicRadioPlanner {
queueIds: Set<String>,
limit: Int,
): List<MusicTrack> = 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<MusicTrack>,
similar: List<MusicTrack>,
knownIds: Set<String>,
): List<MusicTrack> {
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<MusicTrack>(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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -113,13 +114,15 @@ 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
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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -237,6 +241,7 @@ class Media3MusicService : MediaLibraryService() {
@Volatile private var usedRadioAnchors: Set<String> = 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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 =
Expand All @@ -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

Expand All @@ -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()) {
Expand All @@ -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<MusicTrack> {
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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ class MusicHomeLibrary(
val onPlaylistClick: (String) -> Unit = {},
val onAllPlaylistsClick: () -> Unit = {},
val onAllSubscriptionsClick: () -> Unit = {},
val discoveryAvailable: Boolean = false,
val discovery: List<MusicTrack> = emptyList(),
val onDiscoveryShown: () -> Unit = {},
)
Expand Down Expand Up @@ -86,21 +85,20 @@ internal fun likedMusicCard(liked: List<LikedVideoInfo>): 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<String>,
onSongClick: (MusicTrack, List<MusicTrack>, 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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -101,7 +100,6 @@ fun EnhancedMusicScreen(
onPlaylistClick,
onAllPlaylistsClick,
onAllSubscriptionsClick,
lastFmSignedIn,
discovery,
) {
MusicHomeLibrary(
Expand All @@ -112,7 +110,6 @@ fun EnhancedMusicScreen(
onPlaylistClick = onPlaylistClick,
onAllPlaylistsClick = onAllPlaylistsClick,
onAllSubscriptionsClick = onAllSubscriptionsClick,
discoveryAvailable = lastFmSignedIn,
discovery = discovery,
onDiscoveryShown = libraryViewModel::loadDiscovery,
)
Expand Down
Loading