- V8 wipe migration and the shared song store keyed by YouTube video id - media store, indexer, downloader, recommendation top-up and refcounted GC - mood songs plus the recommendation lifecycle and mixed radio pools - new search, song and recommendation API; remove library/longform/seed routes - chart PVC/media env, docs, Nix, README and an end-to-end smoke test
208 lines
7.7 KiB
Kotlin
208 lines
7.7 KiB
Kotlin
package win.taptap.musicmanager.radio
|
|
|
|
import java.time.Instant
|
|
import java.time.temporal.ChronoUnit
|
|
import java.util.UUID
|
|
import kotlin.math.max
|
|
import kotlin.random.Random
|
|
import org.slf4j.LoggerFactory
|
|
import win.taptap.musicmanager.config.UserAccount
|
|
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 mixes the mood's permanent collection with its ready recommendation
|
|
* songs. Every slot rolls `collectionPercent` independently, so a 70% mood gets
|
|
* roughly seven collection tracks in ten. Per-user completions/skips nudge the
|
|
* ranking. Tracks already queued in the session are never repeated until the
|
|
* pool is exhausted; then the least-recently-heard tracks replay.
|
|
*/
|
|
class RadioService(
|
|
private val random: Random = Random.Default,
|
|
) {
|
|
|
|
private val log = LoggerFactory.getLogger(RadioService::class.java)
|
|
|
|
fun start(mood: MoodRecord, user: UserAccount, limit: Int): StartedSession {
|
|
val session = RadioRepository.createSession(user.name, mood.id, UUID.randomUUID().toString())
|
|
val songs = generate(mood, user, 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,
|
|
sessionId: String,
|
|
excluded: Set<String>,
|
|
limit: Int,
|
|
): List<SongRecord> = generate(mood, user, sessionId, excluded, limit, persist = true)
|
|
|
|
/** Queue preview for the mood screen; nothing is persisted. */
|
|
fun preview(mood: MoodRecord, user: UserAccount, limit: Int): List<SongRecord> =
|
|
generate(mood, user, sessionId = null, excluded = emptySet(), limit, persist = false)
|
|
|
|
private fun generate(
|
|
mood: MoodRecord,
|
|
user: UserAccount,
|
|
sessionId: String?,
|
|
excluded: Set<String>,
|
|
requestedLimit: Int,
|
|
persist: Boolean,
|
|
): List<SongRecord> {
|
|
val limit = requestedLimit.coerceIn(1, 50)
|
|
val collection = MoodRepository.songRecords(mood.id)
|
|
// A mood can only play once it has at least one permanent song.
|
|
if (collection.isEmpty()) return emptyList()
|
|
|
|
val collectionIds = collection.map { it.id }.toSet()
|
|
val recommendations = MoodRepository.readySongs(mood.id)
|
|
.filterNot { it.id in collectionIds }
|
|
|
|
val sessionSongs = if (sessionId != null && persist) {
|
|
RadioRepository.queuedSongIds(sessionId)
|
|
} else {
|
|
emptySet()
|
|
}
|
|
val skip = sessionSongs + excluded
|
|
val recent = RadioRepository.recentSongIds(
|
|
user.name,
|
|
Instant.now().minus(RECENT_DAYS, ChronoUnit.DAYS),
|
|
)
|
|
val affinity = RadioRepository.affinity(
|
|
user.name,
|
|
(collection.map { it.id } + recommendations.map { it.id }).toSet(),
|
|
)
|
|
|
|
val freshCollection = collection.filterNot { it.id in skip }
|
|
val freshRecommendations = recommendations.filterNot { it.id in skip }
|
|
|
|
val picks = pickMixed(
|
|
collectionScored = score(freshCollection, affinity, recent, heard = false),
|
|
recommendationScored = score(freshRecommendations, affinity, recent, heard = false),
|
|
limit = limit,
|
|
collectionPercent = mood.collectionPercent,
|
|
).toMutableList()
|
|
|
|
// Small moods exhaust their pool quickly. Replay the least-recently
|
|
// queued tracks instead of returning silence, but never duplicate
|
|
// within one batch.
|
|
if (picks.size < limit) {
|
|
val pickedIds = picks.map { it.id }.toSet()
|
|
val heardCollection = collection.filter { it.id in skip && it.id !in pickedIds }
|
|
val heardRecommendations = recommendations.filter { it.id in skip && it.id !in pickedIds }
|
|
picks += pickMixed(
|
|
collectionScored = score(heardCollection, affinity, recent, heard = true),
|
|
recommendationScored = score(heardRecommendations, affinity, recent, heard = true),
|
|
limit = limit - picks.size,
|
|
collectionPercent = mood.collectionPercent,
|
|
)
|
|
}
|
|
|
|
if (persist && sessionId != null && picks.isNotEmpty()) {
|
|
RadioRepository.append(sessionId, picks.map { it.id })
|
|
}
|
|
return picks
|
|
}
|
|
|
|
private fun score(
|
|
songs: List<SongRecord>,
|
|
affinity: Map<String, win.taptap.musicmanager.db.AffinityRecord>,
|
|
recent: Set<String>,
|
|
heard: Boolean,
|
|
): List<Pair<SongRecord, Double>> = songs.map { song ->
|
|
song to scoreCandidate(
|
|
song = song,
|
|
affinity = affinity[song.id]?.score ?: 0.0,
|
|
recent = song.id in recent,
|
|
jitter = random.nextDouble(0.0, 2.0),
|
|
heard = heard,
|
|
)
|
|
}
|
|
|
|
internal fun scoreCandidate(
|
|
song: SongRecord,
|
|
affinity: Double,
|
|
recent: Boolean = false,
|
|
jitter: Double = 0.0,
|
|
heard: Boolean = false,
|
|
): Double {
|
|
var score = jitter + affinity.coerceIn(-8.0, 8.0)
|
|
if (recent) score -= RECENT_PENALTY
|
|
if (heard) score -= HEARD_PENALTY
|
|
return score
|
|
}
|
|
|
|
/**
|
|
* Picks a batch with the mood's requested collection share. Each slot rolls
|
|
* the percentage independently. An exhausted pool falls back to the other
|
|
* one instead of stalling.
|
|
*/
|
|
internal fun pickMixed(
|
|
collectionScored: List<Pair<SongRecord, Double>>,
|
|
recommendationScored: List<Pair<SongRecord, Double>>,
|
|
limit: Int,
|
|
collectionPercent: Int,
|
|
artistSpacing: Int = 2,
|
|
albumSpacing: Int = 3,
|
|
): List<SongRecord> {
|
|
val collection = collectionScored
|
|
.sortedByDescending { it.second }
|
|
.toMutableList()
|
|
val recommendations = recommendationScored
|
|
.sortedByDescending { it.second }
|
|
.toMutableList()
|
|
val percent = collectionPercent.coerceIn(0, 100)
|
|
val picked = ArrayList<SongRecord>(limit)
|
|
val artists = ArrayDeque<String>()
|
|
val albums = ArrayDeque<String>()
|
|
|
|
while (picked.size < limit && (collection.isNotEmpty() || recommendations.isNotEmpty())) {
|
|
val preferCollection = when {
|
|
collection.isEmpty() -> false
|
|
recommendations.isEmpty() -> true
|
|
else -> random.nextInt(100) < percent
|
|
}
|
|
val pool = if (preferCollection) collection else recommendations
|
|
val song = pool.removeAt(diverseIndex(pool, artists, albums)).first
|
|
picked += song
|
|
|
|
artists.addLast(song.artist)
|
|
if (artists.size > artistSpacing) artists.removeFirst()
|
|
albums.addLast(albumKey(song))
|
|
if (albums.size > albumSpacing) albums.removeFirst()
|
|
}
|
|
return picked
|
|
}
|
|
|
|
private fun diverseIndex(
|
|
pool: List<Pair<SongRecord, Double>>,
|
|
artists: ArrayDeque<String>,
|
|
albums: ArrayDeque<String>,
|
|
): Int {
|
|
var index = pool.indexOfFirst { (song, _) ->
|
|
song.artist !in artists && albumKey(song) !in albums
|
|
}
|
|
if (index < 0) index = pool.indexOfFirst { (song, _) -> song.artist !in artists }
|
|
return if (index < 0) 0 else index
|
|
}
|
|
|
|
private fun albumKey(song: SongRecord): String = song.album?.takeIf { it.isNotBlank() } ?: song.id
|
|
|
|
private companion object {
|
|
const val RECENT_DAYS = 7L
|
|
const val RECENT_PENALTY = 6.0
|
|
const val HEARD_PENALTY = 20.0
|
|
}
|
|
}
|