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
Expand Up @@ -326,7 +326,8 @@ class DailyMixManager @Inject constructor(
val noveltyScore = computeNoveltyScore(song.dateAdded, now)
val favoriteScore = if (favoriteSongIds.contains(song.id)) 1.0 else 0.0
val baselineScore = if (stats == null) 0.1 else 0.0
val noise = random.nextDouble() * 0.005
// Large enough to rotate songs with similar scores day to day; the seed is per day.
val noise = random.nextDouble() * DAILY_VARIETY_NOISE

val finalScore = (preferenceScore * 0.45) +
(affinityScore * 0.25) +
Expand Down Expand Up @@ -356,13 +357,13 @@ class DailyMixManager @Inject constructor(
suspend fun generateDailyMix(
allSongs: List<Song>,
favoriteSongIds: Set<String> = emptySet(),
limit: Int = 30
limit: Int = 30,
calendar: Calendar = Calendar.getInstance()
): List<Song> {
if (allSongs.isEmpty()) {
return emptyList()
}

val calendar = Calendar.getInstance()
val seed = calendar.get(Calendar.YEAR) * 1000 + calendar.get(Calendar.DAY_OF_YEAR)
val random = java.util.Random(seed.toLong())

Expand Down Expand Up @@ -605,5 +606,6 @@ class DailyMixManager @Inject constructor(
companion object {
private const val TAG = "DailyMixManager"
private val SCORE_KEY_CANDIDATES = listOf("score", "count", "value")
private const val DAILY_VARIETY_NOISE = 0.25
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,28 @@ data class AudioMetadata(
val replayGainTrackGainDb: Float? = null,
val replayGainAlbumGainDb: Float? = null,
val rating: Int? = null,
val customFields: List<CustomMetadataField> = emptyList()
val customFields: List<CustomMetadataField> = emptyList(),
val mbRecordingId: String? = null,
val mbReleaseId: String? = null,
val mbArtistId: String? = null
)

private val MBID_REGEX =
Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOption.IGNORE_CASE)

/**
* Returns the first well-formed MusicBrainz identifier among tag values. Some taggers join
* multiple artist IDs into one value ("id1; id2" or "id1/id2"), so each value is split first.
* Malformed IDs are dropped because ListenBrainz rejects listens carrying an invalid MBID.
*/
internal fun firstMusicBrainzId(values: Iterable<String?>?): String? =
values?.asSequence().orEmpty()
.filterNotNull()
.flatMap { it.split(';', '/', ',').asSequence() }
.map { it.trim() }
.firstOrNull { MBID_REGEX.matches(it) }
?.lowercase()

/**
* Normalizes values read from repeated metadata fields without changing their source order.
*
Expand Down Expand Up @@ -146,6 +165,10 @@ object AudioMetadataReader {
propertyMap = propertyMap,
keys = listOf("REPLAYGAIN_ALBUM_GAIN", "REPLAYGAIN_ALBUM_GAIN_DB", "R128_ALBUM_GAIN")
)
// TagLib maps ID3 UFID/TXXX, MP4 freeform atoms and Vorbis comments to these keys.
val mbRecordingId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_TRACKID"]?.asIterable())
val mbReleaseId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_ALBUMID"]?.asIterable())
val mbArtistId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_ARTISTID"]?.asIterable())
val tagFamily = metadataTagFamily(file.extension)
val propertyMapRating = if (readCustomMetadata) {
listOf("RATING", "POPULARIMETER")
Expand Down Expand Up @@ -216,7 +239,10 @@ object AudioMetadataReader {
replayGainTrackGainDb = replayGainTrackGainDb ?: fallback?.replayGainTrackGainDb,
replayGainAlbumGainDb = replayGainAlbumGainDb ?: fallback?.replayGainAlbumGainDb,
rating = fallback?.rating ?: propertyMapRating,
customFields = customFields.ifEmpty { fallback?.customFields.orEmpty() }
customFields = customFields.ifEmpty { fallback?.customFields.orEmpty() },
mbRecordingId = mbRecordingId ?: fallback?.mbRecordingId,
mbReleaseId = mbReleaseId ?: fallback?.mbReleaseId,
mbArtistId = mbArtistId ?: fallback?.mbArtistId
)
}
} catch (error: Exception) {
Expand Down Expand Up @@ -296,6 +322,8 @@ object AudioMetadataReader {
null
}

fun mbid(key: FieldKey) = firstMusicBrainzId(runCatching { tag?.getAll(key) }.getOrNull())

val durationMs = header?.trackLength?.takeIf { it > 0 }?.let { it * 1000L }
val bitrate = header?.bitRateAsNumber?.takeIf { it > 0 }?.toInt()?.let { it * 1000 }
val sampleRate = header?.sampleRateAsNumber?.takeIf { it > 0 }
Expand Down Expand Up @@ -334,7 +362,10 @@ object AudioMetadataReader {
bitrate = bitrate,
sampleRate = sampleRate,
artwork = artwork,
rating = rating
rating = rating,
mbRecordingId = mbid(FieldKey.MUSICBRAINZ_TRACK_ID),
mbReleaseId = mbid(FieldKey.MUSICBRAINZ_RELEASEID),
mbArtistId = mbid(FieldKey.MUSICBRAINZ_ARTISTID)
)
} catch (e: Exception) {
Timber.tag(TAG).e(e, "JAudioTagger fallback FAILED for: ${file.name}")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.lostf1sh.pixelplayeross.data.preferences

/** What swiping a song row to the right does in playlist, album, artist, genre and mix lists. */
enum class SwipeToQueueAction(val storageKey: String) {
OFF("off"),

/** Append the song to the end of the queue. */
ADD_TO_QUEUE("add_to_queue"),

/** Insert the song right after the one playing. */
PLAY_NEXT("play_next");

companion object {
val DEFAULT = ADD_TO_QUEUE

fun fromStorageKey(value: String?): SwipeToQueueAction =
entries.firstOrNull { it.storageKey == value } ?: DEFAULT
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ constructor(
val MINI_PLAYER_SWIPE_TO_SKIP = booleanPreferencesKey("mini_player_swipe_to_skip")
val AUTOPLAY_ON_SKIP = booleanPreferencesKey("autoplay_on_skip")
val PREVIOUS_BUTTON_BEHAVIOR = stringPreferencesKey("previous_button_behavior")
val SWIPE_TO_QUEUE_ACTION = stringPreferencesKey("swipe_to_queue_action")
val HAPTICS_ENABLED = booleanPreferencesKey("haptics_enabled")
val ADVANCED_PERFORMANCE_DIAGNOSTICS_ENABLED =
booleanPreferencesKey("advanced_performance_diagnostics_enabled")
Expand Down Expand Up @@ -1998,6 +1999,17 @@ constructor(
}
}

val swipeToQueueActionFlow: Flow<SwipeToQueueAction> =
dataStore.data.map { preferences ->
SwipeToQueueAction.fromStorageKey(preferences[PreferencesKeys.SWIPE_TO_QUEUE_ACTION])
}.distinctUntilChanged()

suspend fun setSwipeToQueueAction(action: SwipeToQueueAction) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.SWIPE_TO_QUEUE_ACTION] = action.storageKey
}
}

val hapticsEnabledFlow: Flow<Boolean> =
dataStore.data.map { preferences ->
preferences[PreferencesKeys.HAPTICS_ENABLED] ?: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ import kotlinx.coroutines.launch
* tracking only wrapper-side [setVolume] calls would make every fade end at full volume and
* defeat the normalization. [getVolume] reports the logical volume during a fade rather
* than the transient mid-ramp value.
*
* A pause is reported as soon as its fade starts, not when the engine player stops at the
* end of it. Controllers show a pause optimistically; a session that went on reporting
* "playing" for the length of the fade overwrote that, so the pause button answered half a
* second late and a second tap inside the fade paused again instead of resuming.
*/
@OptIn(UnstableApi::class)
class FadingPlayer(
Expand All @@ -30,6 +35,59 @@ class FadingPlayer(
private var fadeJob: Job? = null
// Volume the player should sit at when no fade is running.
private var logicalVolume = innerPlayer.volume
// True while a pause fade ramps down: the pause is decided, only the audio trails it.
private var isFadingToPause = false
private val listeners = LinkedHashSet<Player.Listener>()

override fun addListener(listener: Player.Listener) {
listeners.add(listener)
super.addListener(listener)
}

override fun removeListener(listener: Player.Listener) {
listeners.remove(listener)
super.removeListener(listener)
}

override fun getPlayWhenReady(): Boolean = !isFadingToPause && super.getPlayWhenReady()

override fun isPlaying(): Boolean = !isFadingToPause && super.isPlaying()

override fun setPlayWhenReady(playWhenReady: Boolean) {
if (playWhenReady && isFadingToPause) {
// The engine player is still playing, so it would ignore this and the fade
// would go on to pause it.
play()
} else {
super.setPlayWhenReady(playWhenReady)
}
}

/**
* Enters or leaves the pause fade and tells listeners what that changes in the reported
* state. The engine player emits nothing here: it keeps playing until the fade ends, and
* never stopped if the fade is cut short.
*/
private fun setFadingToPause(fading: Boolean) {
if (isFadingToPause == fading) return
val playWhenReadyBefore = playWhenReady
val isPlayingBefore = isPlaying
isFadingToPause = fading
val playWhenReadyNow = playWhenReady
val isPlayingNow = isPlaying
if (playWhenReadyBefore == playWhenReadyNow && isPlayingBefore == isPlayingNow) return
for (listener in listeners.toList()) {
if (playWhenReadyBefore != playWhenReadyNow) {
listener.onPlayWhenReadyChanged(
playWhenReadyNow,
Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST
)
}
if (isPlayingBefore != isPlayingNow) {
listener.onIsPlayingChanged(isPlayingNow)
}
}
}

override fun setVolume(volume: Float) {
logicalVolume = volume
Expand All @@ -54,13 +112,15 @@ class FadingPlayer(
val targetVolume = settledVolume()
fadeJob?.cancel()
logicalVolume = targetVolume
if (isPlaying) {
if (innerPlayer.isPlaying) {
// A pause fade cut short here has left the volume partway down.
super.setVolume(targetVolume)
setFadingToPause(false)
super.play()
return
}

setFadingToPause(false)
super.setVolume(0f)
super.play()

Expand All @@ -80,13 +140,16 @@ class FadingPlayer(
val settledVolume = settledVolume()
fadeJob?.cancel()
logicalVolume = settledVolume
if (!isPlaying) {
if (!innerPlayer.isPlaying) {
super.pause()
// A play fade cut short while buffering has left the volume partway up.
super.setVolume(settledVolume)
setFadingToPause(false)
return
}

setFadingToPause(true)

// Ramp down from where the volume is now, which is below the settled level when
// this cuts a play fade short.
val startVolume = innerPlayer.volume
Expand All @@ -102,6 +165,7 @@ class FadingPlayer(
super.pause()
// Restore the logical volume so the paused player resumes from the right level.
super.setVolume(logicalVolume)
setFadingToPause(false)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ internal fun shouldReadEmbeddedMetadata(
isDefaultMetadata(rawAlbum)
}

/**
* Embedded MusicBrainz tags win; otherwise IDs stored earlier (a previous scan or a manual
* lookup) survive a rescan that did not read tags. The three IDs move together so a recording
* is never paired with another match's release or artist.
*/
internal fun SongEntity.withMusicBrainzIdsFallback(stored: SongEntity): SongEntity =
if (mbRecordingId != null) {
this
} else {
copy(
mbRecordingId = stored.mbRecordingId,
mbReleaseId = stored.mbReleaseId,
mbArtistId = stored.mbArtistId
)
}

private fun isDefaultMetadata(value: String): Boolean {
val lower = value.trim().lowercase(Locale.ROOT)
return lower.isEmpty() ||
Expand Down Expand Up @@ -1092,7 +1108,7 @@ constructor(
artistUserEdited = localSong.artistUserEdited,
albumUserEdited = localSong.albumUserEdited,
genreUserEdited = localSong.genreUserEdited
)
).withMusicBrainzIdsFallback(localSong)
} else {
scannedMediaStoreSong.entity
}
Expand Down Expand Up @@ -1157,6 +1173,9 @@ constructor(
var discNumber = raw.discNumber
var year = raw.year
var genre: String? = genreMap[raw.id] ?: raw.genre
var mbRecordingId: String? = null
var mbReleaseId: String? = null
var mbArtistId: String? = null

val shouldAugmentMetadata = shouldReadEmbeddedMetadata(
filePath = raw.filePath,
Expand Down Expand Up @@ -1190,6 +1209,11 @@ constructor(
if (meta.trackNumber != null) trackNumber = meta.trackNumber
if (meta.discNumber != null) discNumber = meta.discNumber
if (meta.year != null) year = meta.year
if (meta.mbRecordingId != null) {
mbRecordingId = meta.mbRecordingId
mbReleaseId = meta.mbReleaseId
mbArtistId = meta.mbArtistId
}
}
} catch (e: Exception) {
Timber.tag(TAG).w(e, "Failed to read metadata via TagLib for ${raw.filePath}")
Expand Down Expand Up @@ -1225,7 +1249,10 @@ constructor(
bitrate = audioMetadata?.bitrate,
sourceType = SourceType.LOCAL,
mediaStoreDateAdded = raw.dateAdded,
mediaStoreDateModified = raw.dateModified
mediaStoreDateModified = raw.dateModified,
mbRecordingId = mbRecordingId,
mbReleaseId = mbReleaseId,
mbArtistId = mbArtistId
),
artistValues = artistValues
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.lostf1sh.pixelplayeross.presentation.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Icon
Expand All @@ -19,6 +19,7 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.request.ImageRequest
Expand Down Expand Up @@ -47,9 +48,11 @@ fun AlbumArtCollage(
height: Dp = 400.dp,
padding: Dp = 0.dp,
pattern: CollagePattern = CollagePattern.default,
onSongLongClick: ((Song) -> Unit)? = null,
onSongClick: (Song) -> Unit,
) {
val context = LocalContext.current
val moreOptionsLabel = stringResource(R.string.presentation_batch_b_more_options)
val songsToShow = remember(songs) {
(songs.take(6) + List(6 - songs.size.coerceAtMost(6)) { null }).toImmutableList()
}
Expand Down Expand Up @@ -97,10 +100,13 @@ fun AlbumArtCollage(
.align(cfg.align)
.offset(cfg.offsetX, cfg.offsetY)
.graphicsLayer { rotationZ = cfg.rot }
.clickable(
.combinedClickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) { onSongClick(song) }
indication = null,
onLongClickLabel = moreOptionsLabel,
onLongClick = onSongLongClick?.let { { it(song) } },
onClick = { onSongClick(song) }
)
.background(shape = cfg.shape, color = MaterialTheme.colorScheme.surfaceContainerHigh)
.clip(cfg.shape)
)
Expand All @@ -119,10 +125,13 @@ fun AlbumArtCollage(
.align(cfg.align)
.offset(cfg.offsetX, cfg.offsetY)
.graphicsLayer { rotationZ = cfg.rot }
.clickable(
.combinedClickable(
interactionSource = remember { MutableInteractionSource() },
indication = null
) { onSongClick(song) }
indication = null,
onLongClickLabel = moreOptionsLabel,
onLongClick = onSongLongClick?.let { { it(song) } },
onClick = { onSongClick(song) }
)
.clip(cfg.shape)
)
}
Expand Down
Loading
Loading