A mood with fewer tracks than a batch used to return an empty queue once the session had heard everything. Allow controlled replay of already-heard tracks once no unheard candidates remain, while still never repeating a track inside one batch and never leaving the owner's music folders.
209 lines
7.3 KiB
Kotlin
209 lines
7.3 KiB
Kotlin
package win.taptap.musicmanager.radio
|
|
|
|
import java.util.UUID
|
|
import kotlin.math.max
|
|
import kotlin.random.Random
|
|
import org.slf4j.LoggerFactory
|
|
import win.taptap.musicmanager.api.musicFolderIds
|
|
import win.taptap.musicmanager.config.LibraryConfig
|
|
import win.taptap.musicmanager.config.UserAccount
|
|
import win.taptap.musicmanager.db.LibraryRepository
|
|
import win.taptap.musicmanager.db.MoodRecord
|
|
import win.taptap.musicmanager.db.MoodRepository
|
|
import win.taptap.musicmanager.db.PlaybackSessionRecord
|
|
import win.taptap.musicmanager.db.RadioRepository
|
|
import win.taptap.musicmanager.db.SongRecord
|
|
|
|
data class StartedSession(
|
|
val session: PlaybackSessionRecord,
|
|
val songs: List<SongRecord>,
|
|
)
|
|
|
|
/**
|
|
* Server-driven mood radio.
|
|
*
|
|
* A batch is a weighted sample of the mood's world: seeds are guaranteed
|
|
* candidates, related genres/artists and free-text matches shape the pool, and
|
|
* per-user completions/skips nudge the ranking. Tracks already queued in the
|
|
* session are never repeated. The client asks for more whenever its buffer is
|
|
* low, so the queue is always generated with the latest signals.
|
|
*/
|
|
class RadioService {
|
|
|
|
private val log = LoggerFactory.getLogger(RadioService::class.java)
|
|
private val random = Random.Default
|
|
|
|
fun start(
|
|
mood: MoodRecord,
|
|
user: UserAccount,
|
|
library: LibraryConfig,
|
|
limit: Int,
|
|
): StartedSession {
|
|
val session = RadioRepository.createSession(user.name, mood.id, UUID.randomUUID().toString())
|
|
val songs = generate(mood, user, library, session.id, emptySet(), limit, persist = true)
|
|
log.info("Radio session {} started for mood {} with {} tracks", session.id, mood.name, songs.size)
|
|
return StartedSession(session, songs)
|
|
}
|
|
|
|
fun next(
|
|
mood: MoodRecord,
|
|
user: UserAccount,
|
|
library: LibraryConfig,
|
|
sessionId: String,
|
|
excluded: Set<String>,
|
|
limit: Int,
|
|
): List<SongRecord> =
|
|
generate(mood, user, library, sessionId, excluded, limit, persist = true)
|
|
|
|
/** Queue preview for the mood screen; nothing is persisted. */
|
|
fun preview(
|
|
mood: MoodRecord,
|
|
user: UserAccount,
|
|
library: LibraryConfig,
|
|
limit: Int,
|
|
): List<SongRecord> =
|
|
generate(mood, user, library, sessionId = null, excluded = emptySet(), limit, persist = false)
|
|
|
|
private fun generate(
|
|
mood: MoodRecord,
|
|
user: UserAccount,
|
|
library: LibraryConfig,
|
|
sessionId: String?,
|
|
excluded: Set<String>,
|
|
requestedLimit: Int,
|
|
persist: Boolean,
|
|
): List<SongRecord> {
|
|
val limit = requestedLimit.coerceIn(1, 50)
|
|
val folders = user.musicFolderIds(library)
|
|
if (folders.isEmpty()) return emptyList()
|
|
|
|
val sessionSongs = if (sessionId != null && persist) {
|
|
RadioRepository.queuedSongIds(sessionId)
|
|
} else {
|
|
emptySet()
|
|
}
|
|
val skip = sessionSongs + excluded
|
|
|
|
val seeds = LibraryRepository.songsByIds(
|
|
MoodRepository.seedSongIds(mood.id),
|
|
folders,
|
|
user.name,
|
|
)
|
|
val seedIds = seeds.map { it.id }.toSet()
|
|
val seedGenres = (seeds.flatMap { it.genres } + mood.genres)
|
|
.map { it.trim() }
|
|
.filter { it.isNotEmpty() }
|
|
.distinctBy { it.lowercase() }
|
|
val seedArtistIds = seeds.mapNotNull { it.artistId }.distinct()
|
|
val query = mood.query?.trim()?.takeIf { it.isNotEmpty() }
|
|
|
|
val candidates = LinkedHashMap<String, SongRecord>()
|
|
seeds.forEach { candidates[it.id] = it }
|
|
if (seedGenres.isNotEmpty()) {
|
|
LibraryRepository.songsByGenres(seedGenres, POOL_LIMIT, folders, user.name)
|
|
.forEach { candidates[it.id] = it }
|
|
}
|
|
if (seedArtistIds.isNotEmpty()) {
|
|
LibraryRepository.songsByArtists(seedArtistIds, POOL_LIMIT, folders, user.name)
|
|
.forEach { candidates[it.id] = it }
|
|
}
|
|
if (query != null) {
|
|
LibraryRepository.searchSongs(query, POOL_LIMIT, 0, folders, user.name)
|
|
.forEach { candidates[it.id] = it }
|
|
}
|
|
// A mood with no seeds and no filters still needs a starting point.
|
|
LibraryRepository.randomSongs(
|
|
size = POOL_LIMIT,
|
|
genre = null,
|
|
fromYear = null,
|
|
toYear = null,
|
|
folderIds = folders,
|
|
userName = user.name,
|
|
).forEach { candidates[it.id] = it }
|
|
|
|
candidates.keys.removeAll(skip)
|
|
|
|
// Small libraries can exhaust the mood. Replay tracks the session already
|
|
// heard instead of returning silence, but never repeat the current batch.
|
|
if (candidates.size < limit) {
|
|
LibraryRepository.randomSongs(
|
|
size = max(limit * 10, 200),
|
|
genre = null,
|
|
fromYear = null,
|
|
toYear = null,
|
|
folderIds = folders,
|
|
userName = user.name,
|
|
).forEach { song ->
|
|
if (song.id !in excluded) {
|
|
candidates.putIfAbsent(song.id, song)
|
|
}
|
|
}
|
|
}
|
|
|
|
val affinity = RadioRepository.affinity(user.name, candidates.keys)
|
|
val scored = candidates.values.map { song ->
|
|
song to score(
|
|
song = song,
|
|
seedIds = seedIds,
|
|
seedGenres = seedGenres,
|
|
seedArtistIds = seedArtistIds,
|
|
query = query,
|
|
affinity = affinity[song.id]?.score ?: 0.0,
|
|
)
|
|
}
|
|
|
|
val picks = pickDiverse(scored, limit)
|
|
if (persist && sessionId != null && picks.isNotEmpty()) {
|
|
RadioRepository.append(sessionId, picks.map { it.id })
|
|
}
|
|
return picks
|
|
}
|
|
|
|
private fun score(
|
|
song: SongRecord,
|
|
seedIds: Set<String>,
|
|
seedGenres: List<String>,
|
|
seedArtistIds: List<String>,
|
|
query: String?,
|
|
affinity: Double,
|
|
): Double {
|
|
var score = random.nextDouble(0.0, 2.0)
|
|
if (song.id in seedIds) score += 10.0
|
|
if (song.artistId != null && song.artistId in seedArtistIds) score += 3.0
|
|
score += song.genres.count { candidate ->
|
|
seedGenres.any { it.equals(candidate, ignoreCase = true) }
|
|
} * 1.5
|
|
if (query != null && song.title.contains(query, ignoreCase = true)) score += 2.0
|
|
score += affinity.coerceIn(-6.0, 6.0)
|
|
return score
|
|
}
|
|
|
|
/**
|
|
* Picks the best remaining candidate, preferring a different artist than the
|
|
* previous track so a batch does not become one album on repeat.
|
|
*/
|
|
private fun pickDiverse(
|
|
scored: List<Pair<SongRecord, Double>>,
|
|
limit: Int,
|
|
): List<SongRecord> {
|
|
val remaining = scored
|
|
.sortedWith(compareByDescending<Pair<SongRecord, Double>> { it.second })
|
|
.toMutableList()
|
|
val picked = ArrayList<SongRecord>(limit)
|
|
var lastArtist: String? = null
|
|
|
|
while (picked.size < limit && remaining.isNotEmpty()) {
|
|
val different = remaining.indexOfFirst { it.first.displayArtist != lastArtist }
|
|
val index = if (different >= 0) different else 0
|
|
val song = remaining.removeAt(index).first
|
|
picked += song
|
|
lastArtist = song.displayArtist
|
|
}
|
|
return picked
|
|
}
|
|
|
|
private companion object {
|
|
const val POOL_LIMIT = 400
|
|
}
|
|
}
|