playback: the ephemeral queue — retention, drain, shuffle pin, and persistence
This commit is contained in:
@@ -37,8 +37,14 @@ import org.oxycblt.musikr.Music
|
|||||||
* @author Alexander Capehart
|
* @author Alexander Capehart
|
||||||
*/
|
*/
|
||||||
@Database(
|
@Database(
|
||||||
entities = [PlaybackState::class, QueueHeapItem::class, QueueShuffledMappingItem::class],
|
entities =
|
||||||
version = 38,
|
[
|
||||||
|
PlaybackState::class,
|
||||||
|
QueueHeapItem::class,
|
||||||
|
QueueShuffledMappingItem::class,
|
||||||
|
QueueDeckItem::class,
|
||||||
|
],
|
||||||
|
version = 39,
|
||||||
exportSchema = false,
|
exportSchema = false,
|
||||||
)
|
)
|
||||||
@TypeConverters(Music.UID.TypeConverters::class)
|
@TypeConverters(Music.UID.TypeConverters::class)
|
||||||
@@ -65,6 +71,18 @@ abstract class PersistenceDatabase : RoomDatabase() {
|
|||||||
it.execSQL("ALTER TABLE queue_heap RENAME TO QueueHeapItem")
|
it.execSQL("ALTER TABLE queue_heap RENAME TO QueueHeapItem")
|
||||||
it.execSQL("ALTER TABLE queue_mapping RENAME TO QueueMappingItem")
|
it.execSQL("ALTER TABLE queue_mapping RENAME TO QueueMappingItem")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val MIGRATION_38_39 =
|
||||||
|
Migration(38, 39) {
|
||||||
|
// The deck is its own ordered table, and the current song's deck membership
|
||||||
|
// is a flag on the playback state.
|
||||||
|
it.execSQL(
|
||||||
|
"CREATE TABLE IF NOT EXISTS `QueueDeckItem` (`id` INTEGER PRIMARY KEY NOT NULL, `uid` TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
it.execSQL(
|
||||||
|
"ALTER TABLE `PlaybackState` ADD COLUMN `deckCurrent` INTEGER NOT NULL DEFAULT 0"
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,6 +153,23 @@ interface QueueDao {
|
|||||||
*/
|
*/
|
||||||
@Insert(onConflict = OnConflictStrategy.ABORT)
|
@Insert(onConflict = OnConflictStrategy.ABORT)
|
||||||
suspend fun insertShuffledMapping(mapping: List<QueueShuffledMappingItem>)
|
suspend fun insertShuffledMapping(mapping: List<QueueShuffledMappingItem>)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the persisted deck entries.
|
||||||
|
*
|
||||||
|
* @return A list of persisted [QueueDeckItem]s wrapping each deck song in order.
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM QueueDeckItem") suspend fun getDeck(): List<QueueDeckItem>
|
||||||
|
|
||||||
|
/** Delete any previously persisted [QueueDeckItem]s. */
|
||||||
|
@Query("DELETE FROM QueueDeckItem") suspend fun nukeDeck()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert new deck entries into the database.
|
||||||
|
*
|
||||||
|
* @param deck The list of wrapped [QueueDeckItem]s to insert.
|
||||||
|
*/
|
||||||
|
@Insert(onConflict = OnConflictStrategy.ABORT) suspend fun insertDeck(deck: List<QueueDeckItem>)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Figure out how to get RepeatMode to map to an int instead of a string
|
// TODO: Figure out how to get RepeatMode to map to an int instead of a string
|
||||||
@@ -146,8 +181,11 @@ data class PlaybackState(
|
|||||||
val repeatMode: RepeatMode,
|
val repeatMode: RepeatMode,
|
||||||
val songUid: Music.UID,
|
val songUid: Music.UID,
|
||||||
val parentUid: Music.UID?,
|
val parentUid: Music.UID?,
|
||||||
|
val deckCurrent: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID)
|
@Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID)
|
||||||
|
|
||||||
@Entity data class QueueShuffledMappingItem(@PrimaryKey val id: Int, val index: Int)
|
@Entity data class QueueShuffledMappingItem(@PrimaryKey val id: Int, val index: Int)
|
||||||
|
|
||||||
|
@Entity data class QueueDeckItem(@PrimaryKey val id: Int, val uid: Music.UID)
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class PersistenceRoomModule {
|
|||||||
"playback_persistence.db",
|
"playback_persistence.db",
|
||||||
)
|
)
|
||||||
.fallbackToDestructiveMigration()
|
.fallbackToDestructiveMigration()
|
||||||
.addMigrations(PersistenceDatabase.MIGRATION_27_32)
|
.addMigrations(PersistenceDatabase.MIGRATION_27_32, PersistenceDatabase.MIGRATION_38_39)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
@Provides fun playbackStateDao(database: PersistenceDatabase) = database.playbackStateDao()
|
@Provides fun playbackStateDao(database: PersistenceDatabase) = database.playbackStateDao()
|
||||||
|
|||||||
@@ -54,10 +54,12 @@ constructor(
|
|||||||
val playbackState: PlaybackState
|
val playbackState: PlaybackState
|
||||||
val heapItems: List<QueueHeapItem>
|
val heapItems: List<QueueHeapItem>
|
||||||
val mappingItems: List<QueueShuffledMappingItem>
|
val mappingItems: List<QueueShuffledMappingItem>
|
||||||
|
val deckItems: List<QueueDeckItem>
|
||||||
try {
|
try {
|
||||||
playbackState = playbackStateDao.getState() ?: return null
|
playbackState = playbackStateDao.getState() ?: return null
|
||||||
heapItems = queueDao.getHeap()
|
heapItems = queueDao.getHeap()
|
||||||
mappingItems = queueDao.getShuffledMapping()
|
mappingItems = queueDao.getShuffledMapping()
|
||||||
|
deckItems = queueDao.getDeck()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
L.e("Unable read playback state")
|
L.e("Unable read playback state")
|
||||||
L.e(e.stackTraceToString())
|
L.e(e.stackTraceToString())
|
||||||
@@ -66,6 +68,7 @@ constructor(
|
|||||||
|
|
||||||
val heap = heapItems.map { library.findSong(it.uid) }
|
val heap = heapItems.map { library.findSong(it.uid) }
|
||||||
val shuffledMapping = mappingItems.map { it.index }
|
val shuffledMapping = mappingItems.map { it.index }
|
||||||
|
val deck = deckItems.map { library.findSong(it.uid) }
|
||||||
val parent = playbackState.parentUid?.let { musicRepository.find(it) as? MusicParent }
|
val parent = playbackState.parentUid?.let { musicRepository.find(it) as? MusicParent }
|
||||||
|
|
||||||
return PlaybackStateManager.SavedState(
|
return PlaybackStateManager.SavedState(
|
||||||
@@ -74,6 +77,8 @@ constructor(
|
|||||||
parent = parent,
|
parent = parent,
|
||||||
heap = heap,
|
heap = heap,
|
||||||
shuffledMapping = shuffledMapping,
|
shuffledMapping = shuffledMapping,
|
||||||
|
deck = deck,
|
||||||
|
deckCurrent = playbackState.deckCurrent,
|
||||||
index = playbackState.index,
|
index = playbackState.index,
|
||||||
songUid = playbackState.songUid,
|
songUid = playbackState.songUid,
|
||||||
)
|
)
|
||||||
@@ -84,6 +89,7 @@ constructor(
|
|||||||
playbackStateDao.nukeState()
|
playbackStateDao.nukeState()
|
||||||
queueDao.nukeHeap()
|
queueDao.nukeHeap()
|
||||||
queueDao.nukeShuffledMapping()
|
queueDao.nukeShuffledMapping()
|
||||||
|
queueDao.nukeDeck()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
L.e("Unable to clear previous state")
|
L.e("Unable to clear previous state")
|
||||||
L.e(e.stackTraceToString())
|
L.e(e.stackTraceToString())
|
||||||
@@ -101,18 +107,23 @@ constructor(
|
|||||||
repeatMode = state.repeatMode,
|
repeatMode = state.repeatMode,
|
||||||
songUid = state.songUid,
|
songUid = state.songUid,
|
||||||
parentUid = state.parent?.uid,
|
parentUid = state.parent?.uid,
|
||||||
|
deckCurrent = state.deckCurrent,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Convert the remaining queue information do their database-specific counterparts.
|
// Convert the remaining queue information do their database-specific counterparts.
|
||||||
val heap =
|
val heap =
|
||||||
state.heap.mapIndexed { i, song -> QueueHeapItem(i, requireNotNull(song).uid) }
|
state.heap.mapIndexed { i, song -> QueueHeapItem(i, requireNotNull(song).uid) }
|
||||||
|
|
||||||
|
val deck =
|
||||||
|
state.deck.mapIndexed { i, song -> QueueDeckItem(i, requireNotNull(song).uid) }
|
||||||
|
|
||||||
val shuffledMapping =
|
val shuffledMapping =
|
||||||
state.shuffledMapping.mapIndexed { i, index -> QueueShuffledMappingItem(i, index) }
|
state.shuffledMapping.mapIndexed { i, index -> QueueShuffledMappingItem(i, index) }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
playbackStateDao.insertState(playbackState)
|
playbackStateDao.insertState(playbackState)
|
||||||
queueDao.insertHeap(heap)
|
queueDao.insertHeap(heap)
|
||||||
|
queueDao.insertDeck(deck)
|
||||||
queueDao.insertShuffledMapping(shuffledMapping)
|
queueDao.insertShuffledMapping(shuffledMapping)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
L.e("Unable to write new state")
|
L.e("Unable to write new state")
|
||||||
|
|||||||
@@ -125,6 +125,36 @@ class BetterShuffleOrder(private val shuffled: IntArray) : ShuffleOrder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/**
|
||||||
|
* Create a shuffle over [length] items with the [deckSize] items physically after
|
||||||
|
* [anchor] pinned in order behind it and the rest shuffled. An anchor of -1 pins the
|
||||||
|
* deck (physically at 1..[deckSize]) behind a random first item.
|
||||||
|
*/
|
||||||
|
fun createDeckPinned(length: Int, anchor: Int, deckSize: Int): BetterShuffleOrder {
|
||||||
|
val deckStart = if (anchor >= 0) anchor + 1 else 1
|
||||||
|
val deck = deckStart until deckStart + deckSize
|
||||||
|
val rest = (0 until length).filter { it != anchor && it !in deck }.shuffled()
|
||||||
|
val top = if (anchor >= 0) listOf(anchor) else rest.take(1)
|
||||||
|
val tail = if (anchor >= 0) rest else rest.drop(1)
|
||||||
|
return BetterShuffleOrder((top + deck + tail).toIntArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a shuffle from the unscrambled queue [indices] (playback order as timeline
|
||||||
|
* indices, played history included): [anchor] (a timeline index) on top, the [deckSize]
|
||||||
|
* deck items after it pinned in order, the rest shuffled.
|
||||||
|
*/
|
||||||
|
fun createDeckPinned(
|
||||||
|
indices: List<Int>,
|
||||||
|
anchor: Int,
|
||||||
|
deckSize: Int,
|
||||||
|
): BetterShuffleOrder {
|
||||||
|
val anchorAt = indices.indexOf(anchor)
|
||||||
|
val pinned = indices.subList(anchorAt, anchorAt + 1 + deckSize)
|
||||||
|
val rest = indices.take(anchorAt) + indices.drop(anchorAt + 1 + deckSize)
|
||||||
|
return BetterShuffleOrder((pinned + rest.shuffled()).toIntArray())
|
||||||
|
}
|
||||||
|
|
||||||
private fun createShuffledList(length: Int, startIndex: Int): IntArray {
|
private fun createShuffledList(length: Int, startIndex: Int): IntArray {
|
||||||
val shuffled = IntArray(length)
|
val shuffled = IntArray(length)
|
||||||
for (i in 0 until length) {
|
for (i in 0 until length) {
|
||||||
|
|||||||
@@ -246,16 +246,21 @@ class ExoPlaybackStateHolder(
|
|||||||
deferSave()
|
deferSave()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun newPlayback(command: PlaybackCommand) {
|
override fun newPlayback(command: PlaybackCommand, deck: List<Song>) {
|
||||||
parent = command.parent
|
parent = command.parent
|
||||||
player.shuffleModeEnabled = command.shuffled
|
player.shuffleModeEnabled = command.shuffled
|
||||||
player.setMediaItems(command.queue.map { it.buildMediaItem() })
|
|
||||||
val startIndex =
|
val startIndex =
|
||||||
command.song
|
command.song
|
||||||
?.let { command.queue.indexOf(it) }
|
?.let { command.queue.indexOf(it) }
|
||||||
.also { check(it != -1) { "Start song not in queue" } }
|
.also { check(it != -1) { "Start song not in queue" } }
|
||||||
|
// Retain the deck directly after the start song.
|
||||||
|
val items = command.queue.map { it.buildMediaItem() }.toMutableList()
|
||||||
|
items.addAll((startIndex ?: 0) + 1, deck.map { it.buildMediaItem() })
|
||||||
|
player.setMediaItems(items)
|
||||||
if (command.shuffled) {
|
if (command.shuffled) {
|
||||||
player.setShuffleOrder(BetterShuffleOrder(command.queue.size, startIndex ?: -1))
|
player.setShuffleOrder(
|
||||||
|
BetterShuffleOrder.createDeckPinned(items.size, startIndex ?: -1, deck.size)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
val target = startIndex ?: player.currentTimeline.getFirstWindowIndex(command.shuffled)
|
val target = startIndex ?: player.currentTimeline.getFirstWindowIndex(command.shuffled)
|
||||||
player.seekTo(target, C.TIME_UNSET)
|
player.seekTo(target, C.TIME_UNSET)
|
||||||
@@ -265,14 +270,19 @@ class ExoPlaybackStateHolder(
|
|||||||
deferSave()
|
deferSave()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun shuffled(shuffled: Boolean) {
|
override fun shuffled(shuffled: Boolean, deckSize: Int) {
|
||||||
|
// Walk the current order before the toggle, while the deck still occupies the playback
|
||||||
|
// positions directly behind the current song.
|
||||||
|
val indices = player.unscrambleQueueIndices()
|
||||||
player.setShuffleModeEnabled(shuffled)
|
player.setShuffleModeEnabled(shuffled)
|
||||||
if (player.shuffleModeEnabled) {
|
if (shuffled) {
|
||||||
// Have to manually refresh the shuffle seed and anchor it to the new current songs
|
// The deck stays pinned ahead in order; the heap shuffles beneath it.
|
||||||
player.setShuffleOrder(
|
player.setShuffleOrder(
|
||||||
BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex)
|
BetterShuffleOrder.createDeckPinned(indices, player.currentMediaItemIndex, deckSize)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// TODO: The unshuffle direction must rebuild the physical layout: deck block spliced
|
||||||
|
// after the current item, greyed heap history above it, resume song and tail below.
|
||||||
playbackManager.ack(this, StateAck.QueueReordered)
|
playbackManager.ack(this, StateAck.QueueReordered)
|
||||||
deferSave()
|
deferSave()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ constructor(
|
|||||||
else -> return
|
else -> return
|
||||||
}
|
}
|
||||||
val song = library.songs.find { it.uid == songUid } ?: return
|
val song = library.songs.find { it.uid == songUid } ?: return
|
||||||
playbackManager.addToQueue(song)
|
playbackManager.playAfter(song)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onRemoveQueueItem(description: MediaDescriptionCompat) {
|
override fun onRemoveQueueItem(description: MediaDescriptionCompat) {
|
||||||
|
|||||||
@@ -51,8 +51,14 @@ interface PlaybackStateHolder {
|
|||||||
/** The current audio session ID of the audio player. */
|
/** The current audio session ID of the audio player. */
|
||||||
val audioSessionId: Int
|
val audioSessionId: Int
|
||||||
|
|
||||||
/** Applies a completely new playback state to the holder. */
|
/**
|
||||||
fun newPlayback(command: PlaybackCommand)
|
* Applies a completely new playback state to the holder.
|
||||||
|
*
|
||||||
|
* @param command The parameters to start playback with.
|
||||||
|
* @param deck The deck songs to retain directly after the start song. Empty when no deck
|
||||||
|
* exists.
|
||||||
|
*/
|
||||||
|
fun newPlayback(command: PlaybackCommand, deck: List<Song>)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the playing state of the audio player.
|
* Update the playing state of the audio player.
|
||||||
@@ -135,8 +141,9 @@ interface PlaybackStateHolder {
|
|||||||
* Reorder the queue.
|
* Reorder the queue.
|
||||||
*
|
*
|
||||||
* @param shuffled Whether the queue should be shuffled.
|
* @param shuffled Whether the queue should be shuffled.
|
||||||
|
* @param deckSize The number of deck songs to pin in order behind the current song.
|
||||||
*/
|
*/
|
||||||
fun shuffled(shuffled: Boolean)
|
fun shuffled(shuffled: Boolean, deckSize: Int)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle a deferred playback action.
|
* Handle a deferred playback action.
|
||||||
|
|||||||
@@ -344,6 +344,10 @@ interface PlaybackStateManager {
|
|||||||
val parent: MusicParent?,
|
val parent: MusicParent?,
|
||||||
val heap: List<Song?>,
|
val heap: List<Song?>,
|
||||||
val shuffledMapping: List<Int>,
|
val shuffledMapping: List<Int>,
|
||||||
|
/** The upcoming deck songs, in order. Also physically present in [heap]. */
|
||||||
|
val deck: List<Song?>,
|
||||||
|
/** Whether the current song (at [index]) came from the deck. */
|
||||||
|
val deckCurrent: Boolean,
|
||||||
val index: Int,
|
val index: Int,
|
||||||
val songUid: Music.UID,
|
val songUid: Music.UID,
|
||||||
)
|
)
|
||||||
@@ -377,8 +381,11 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
@Volatile private var pendingDeferredPlayback: DeferredPlayback? = null
|
@Volatile private var pendingDeferredPlayback: DeferredPlayback? = null
|
||||||
@Volatile private var isInitialized = false
|
@Volatile private var isInitialized = false
|
||||||
|
|
||||||
/** Resolved-queue position just past the last deck song. Null when the deck is empty. */
|
/** The upcoming deck songs, in order. The deck sits directly behind the current song. */
|
||||||
private var deckEnd: Int? = null
|
private var deck = emptyList<Song>()
|
||||||
|
|
||||||
|
/** The current song when it came from the deck. Null when the heap is playing. */
|
||||||
|
private var deckCurrent: Song? = null
|
||||||
|
|
||||||
override val progression
|
override val progression
|
||||||
get() = stateMirror.progression
|
get() = stateMirror.progression
|
||||||
@@ -470,7 +477,9 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
L.d("Playing $command")
|
L.d("Playing $command")
|
||||||
// Played something, so we are initialized now
|
// Played something, so we are initialized now
|
||||||
isInitialized = true
|
isInitialized = true
|
||||||
stateHolder.newPlayback(command)
|
// The deck is retained ahead of the new heap; a deck-sourced current song is excluded
|
||||||
|
// and drains with the replaced timeline.
|
||||||
|
stateHolder.newPlayback(command, deck)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- QUEUE FUNCTIONS ---
|
// --- QUEUE FUNCTIONS ---
|
||||||
@@ -505,9 +514,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
val stateHolder = stateHolder ?: return
|
val stateHolder = stateHolder ?: return
|
||||||
L.d("Adding ${songs.size} songs to start of queue")
|
L.d("Adding ${songs.size} songs to start of queue")
|
||||||
stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size))
|
stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size))
|
||||||
// Inserting at the deck's top pushes the boundary down with the deck, starting
|
// Play-next joins the front of the deck.
|
||||||
// one right after the current song when the deck is empty.
|
deck = songs + deck
|
||||||
deckEnd = (deckEnd ?: (stateMirror.index + 1)) + songs.size
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -530,10 +538,10 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
play(QueueCommand(songs))
|
play(QueueCommand(songs))
|
||||||
} else {
|
} else {
|
||||||
val stateHolder = stateHolder ?: return
|
val stateHolder = stateHolder ?: return
|
||||||
val at = deckEnd ?: (stateMirror.index + 1)
|
val at = stateMirror.index + 1 + deck.size
|
||||||
L.d("Adding ${songs.size} songs at deck end $at")
|
L.d("Adding ${songs.size} songs at deck end $at")
|
||||||
stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size))
|
stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size))
|
||||||
deckEnd = at + songs.size
|
deck = deck + songs
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -561,7 +569,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
override fun shuffled(shuffled: Boolean) {
|
override fun shuffled(shuffled: Boolean) {
|
||||||
val stateHolder = stateHolder ?: return
|
val stateHolder = stateHolder ?: return
|
||||||
L.d("Reordering queue [shuffled=$shuffled]")
|
L.d("Reordering queue [shuffled=$shuffled]")
|
||||||
stateHolder.shuffled(shuffled)
|
stateHolder.shuffled(shuffled, deck.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- INTERNAL PLAYER FUNCTIONS ---
|
// --- INTERNAL PLAYER FUNCTIONS ---
|
||||||
@@ -625,10 +633,23 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
|
|
||||||
when (ack) {
|
when (ack) {
|
||||||
is StateAck.IndexMoved -> {
|
is StateAck.IndexMoved -> {
|
||||||
|
val departed = currentSong
|
||||||
|
// The departed song always sits at the old index — transitions never reorder.
|
||||||
|
val departedAt = stateMirror.index
|
||||||
val rawQueue = stateHolder.resolveQueue()
|
val rawQueue = stateHolder.resolveQueue()
|
||||||
stateMirror = stateMirror.copy(index = rawQueue.resolveIndex(), rawQueue = rawQueue)
|
stateMirror = stateMirror.copy(index = rawQueue.resolveIndex(), rawQueue = rawQueue)
|
||||||
deckEnd = null
|
|
||||||
listeners.forEach { it.onIndexMoved(stateMirror.index) }
|
listeners.forEach { it.onIndexMoved(stateMirror.index) }
|
||||||
|
// Leaving a deck song drains it: a different song is playing now. A rewind
|
||||||
|
// acks without departing and drains nothing.
|
||||||
|
if (departed != null && departed !== currentSong && departed === deckCurrent) {
|
||||||
|
deckCurrent = null
|
||||||
|
stateHolder.remove(departedAt, StateAck.Remove(departedAt))
|
||||||
|
}
|
||||||
|
// Entering the deck: the song that started playing leaves the upcoming deck.
|
||||||
|
if (deck.isNotEmpty() && currentSong === deck[0]) {
|
||||||
|
deckCurrent = deck[0]
|
||||||
|
deck = deck.drop(1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
is StateAck.PlayNext -> {
|
is StateAck.PlayNext -> {
|
||||||
val rawQueue = stateHolder.resolveQueue()
|
val rawQueue = stateHolder.resolveQueue()
|
||||||
@@ -649,6 +670,13 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
is StateAck.Move -> {
|
is StateAck.Move -> {
|
||||||
|
// Capture the pre-move coordinates and the moved song for the deck update.
|
||||||
|
val movedSong = stateMirror.queue.getOrNull(ack.from)
|
||||||
|
val deckFrom = ack.from - (stateMirror.index + 1)
|
||||||
|
val deckTo = ack.to - (stateMirror.index + 1)
|
||||||
|
// Deck membership is positional within the deck block, confirmed by identity:
|
||||||
|
// the same instance can also sit in the heap.
|
||||||
|
val fromIsDeck = deckFrom in deck.indices && deck[deckFrom] === movedSong
|
||||||
val rawQueue = stateHolder.resolveQueue()
|
val rawQueue = stateHolder.resolveQueue()
|
||||||
val newIndex = rawQueue.resolveIndex()
|
val newIndex = rawQueue.resolveIndex()
|
||||||
val change =
|
val change =
|
||||||
@@ -665,15 +693,15 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
rawQueue = rawQueue,
|
rawQueue = rawQueue,
|
||||||
)
|
)
|
||||||
|
|
||||||
// The boundary compares both endpoints in pre-move coordinates: leaving the
|
// Deck membership follows the moved song: reorder inside, leave, or enter.
|
||||||
// deck steps it down, entering the deck steps it up.
|
deck =
|
||||||
deckEnd =
|
|
||||||
deckEnd?.let { end ->
|
|
||||||
when {
|
when {
|
||||||
ack.from < end && ack.to >= end -> end - 1
|
fromIsDeck && deckTo in deck.indices ->
|
||||||
ack.from >= end && ack.to < end -> end + 1
|
deck.toMutableList().apply { add(deckTo, removeAt(deckFrom)) }
|
||||||
else -> end
|
fromIsDeck -> deck.toMutableList().apply { removeAt(deckFrom) }
|
||||||
}
|
deckTo in deck.indices && movedSong != null ->
|
||||||
|
deck.toMutableList().apply { add(deckTo, movedSong) }
|
||||||
|
else -> deck
|
||||||
}
|
}
|
||||||
|
|
||||||
listeners.forEach {
|
listeners.forEach {
|
||||||
@@ -681,6 +709,10 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
is StateAck.Remove -> {
|
is StateAck.Remove -> {
|
||||||
|
// Capture the pre-removal position relations for the deck update.
|
||||||
|
val removedSong = stateMirror.queue.getOrNull(ack.index)
|
||||||
|
val removedCurrent = ack.index == stateMirror.index
|
||||||
|
val deckIndex = ack.index - (stateMirror.index + 1)
|
||||||
val rawQueue = stateHolder.resolveQueue()
|
val rawQueue = stateHolder.resolveQueue()
|
||||||
val newIndex = rawQueue.resolveIndex()
|
val newIndex = rawQueue.resolveIndex()
|
||||||
val change =
|
val change =
|
||||||
@@ -700,8 +732,12 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
rawQueue = rawQueue,
|
rawQueue = rawQueue,
|
||||||
)
|
)
|
||||||
|
|
||||||
// A removal ahead of the boundary steps the boundary down with it.
|
// Deck membership is positional within the deck block, confirmed by identity.
|
||||||
deckEnd = deckEnd?.let { end -> if (ack.index < end) end - 1 else end }
|
if (deckIndex in deck.indices && deck[deckIndex] === removedSong) {
|
||||||
|
deck = deck.toMutableList().apply { removeAt(deckIndex) }
|
||||||
|
}
|
||||||
|
// Only removing the current position clears the playing deck song.
|
||||||
|
if (removedCurrent) deckCurrent = null
|
||||||
|
|
||||||
listeners.forEach {
|
listeners.forEach {
|
||||||
it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
|
it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
|
||||||
@@ -716,7 +752,6 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
isShuffled = rawQueue.isShuffled,
|
isShuffled = rawQueue.isShuffled,
|
||||||
rawQueue = rawQueue,
|
rawQueue = rawQueue,
|
||||||
)
|
)
|
||||||
deckEnd = null
|
|
||||||
listeners.forEach {
|
listeners.forEach {
|
||||||
it.onQueueReordered(
|
it.onQueueReordered(
|
||||||
stateMirror.queue,
|
stateMirror.queue,
|
||||||
@@ -735,7 +770,9 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
isShuffled = rawQueue.isShuffled,
|
isShuffled = rawQueue.isShuffled,
|
||||||
rawQueue = rawQueue,
|
rawQueue = rawQueue,
|
||||||
)
|
)
|
||||||
deckEnd = null
|
// A deck-sourced current song drains with the replaced timeline; the upcoming
|
||||||
|
// deck is retained (the holder spliced it into the new heap).
|
||||||
|
deckCurrent = null
|
||||||
listeners.forEach {
|
listeners.forEach {
|
||||||
it.onNewPlayback(
|
it.onNewPlayback(
|
||||||
stateMirror.parent,
|
stateMirror.parent,
|
||||||
@@ -770,6 +807,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
parent = stateMirror.parent,
|
parent = stateMirror.parent,
|
||||||
heap = stateMirror.rawQueue.heap,
|
heap = stateMirror.rawQueue.heap,
|
||||||
shuffledMapping = stateMirror.rawQueue.shuffledMapping,
|
shuffledMapping = stateMirror.rawQueue.shuffledMapping,
|
||||||
|
deck = deck,
|
||||||
|
deckCurrent = deckCurrent != null,
|
||||||
index = stateMirror.index,
|
index = stateMirror.index,
|
||||||
songUid = currentSong.uid,
|
songUid = currentSong.uid,
|
||||||
)
|
)
|
||||||
@@ -834,6 +873,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (index < 0) {
|
if (index < 0) {
|
||||||
|
deck = emptyList()
|
||||||
|
deckCurrent = null
|
||||||
stateHolder.reset(StateAck.NewPlayback)
|
stateHolder.reset(StateAck.NewPlayback)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -858,6 +899,23 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
|||||||
StateAck.NewPlayback,
|
StateAck.NewPlayback,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Restore the deck: within the block directly behind the current song, keep the
|
||||||
|
// entries whose UIDs were saved, in order; missing songs drop out individually.
|
||||||
|
val deckStart = stateMirror.index + 1
|
||||||
|
val savedDeckUids = savedState.deck.mapNotNull { it?.uid }
|
||||||
|
deck =
|
||||||
|
if (deckStart <= stateMirror.queue.size) {
|
||||||
|
stateMirror.queue
|
||||||
|
.subList(
|
||||||
|
deckStart,
|
||||||
|
minOf(deckStart + savedDeckUids.size, stateMirror.queue.size),
|
||||||
|
)
|
||||||
|
.filter { it.uid in savedDeckUids }
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
deckCurrent = if (savedState.deckCurrent) currentSong else null
|
||||||
|
|
||||||
isInitialized = true
|
isInitialized = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026 Auxio Project
|
||||||
|
* BetterShuffleOrderTest.kt is part of Auxio.
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.oxycblt.auxio.playback.service
|
||||||
|
|
||||||
|
import androidx.media3.common.C
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BetterShuffleOrderTest {
|
||||||
|
/**
|
||||||
|
* The pin anchors at the current song wherever it sits in the timeline — including inside
|
||||||
|
* played history: the anchor and the deck block after it lead the permutation, and the
|
||||||
|
* rest shuffles beneath.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `createDeckPinned pins the anchor and its deck, not the list head`() {
|
||||||
|
// A ten-item timeline in physical order; the current song is timeline index 5 with a
|
||||||
|
// two-song deck behind it.
|
||||||
|
val indices = (0 until 10).toList()
|
||||||
|
val order = BetterShuffleOrder.createDeckPinned(indices, 5, 2)
|
||||||
|
|
||||||
|
// Walk the playback order.
|
||||||
|
val playbackOrder = mutableListOf(order.getFirstIndex())
|
||||||
|
while (true) {
|
||||||
|
val next = order.getNextIndex(playbackOrder.last())
|
||||||
|
if (next == C.INDEX_UNSET) break
|
||||||
|
playbackOrder += next
|
||||||
|
}
|
||||||
|
|
||||||
|
// The anchor and its deck lead; the unpinned indices all follow.
|
||||||
|
assertEquals(listOf(5, 6, 7), playbackOrder.take(3))
|
||||||
|
assertEquals((0 until 10).toSet(), playbackOrder.toSet())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
package org.oxycblt.auxio.playback.state
|
package org.oxycblt.auxio.playback.state
|
||||||
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import java.util.UUID
|
||||||
import org.oxycblt.musikr.Album
|
import org.oxycblt.musikr.Album
|
||||||
import org.oxycblt.musikr.Artist
|
import org.oxycblt.musikr.Artist
|
||||||
import org.oxycblt.musikr.Genre
|
import org.oxycblt.musikr.Genre
|
||||||
@@ -50,8 +51,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
|
|||||||
private set
|
private set
|
||||||
|
|
||||||
override val progression = Progression.nil()
|
override val progression = Progression.nil()
|
||||||
override val repeatMode = RepeatMode.NONE
|
override var repeatMode = RepeatMode.NONE
|
||||||
override val parent: MusicParent? = null
|
private set
|
||||||
|
override var parent: MusicParent? = null
|
||||||
|
private set
|
||||||
override val audioSessionId = 0
|
override val audioSessionId = 0
|
||||||
|
|
||||||
override fun resolveQueue() = rawQueue
|
override fun resolveQueue() = rawQueue
|
||||||
@@ -62,22 +65,79 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
|
|||||||
manager?.ack(this, StateAck.IndexMoved)
|
manager?.ack(this, StateAck.IndexMoved)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun newPlayback(command: PlaybackCommand) {
|
/** Advance to the next song in playback order, as a natural track end does. */
|
||||||
rawQueue =
|
fun advanceToNext() {
|
||||||
RawQueue(
|
val queue = rawQueue
|
||||||
heap = command.queue,
|
val nextResolved = queue.resolveIndex() + 1
|
||||||
shuffledMapping = emptyList(),
|
val next =
|
||||||
heapIndex = command.song?.let(command.queue::indexOf) ?: 0,
|
if (queue.isShuffled) {
|
||||||
)
|
queue.shuffledMapping.getOrNull(nextResolved)
|
||||||
|
} else {
|
||||||
|
nextResolved.takeIf { it < queue.heap.size }
|
||||||
|
}
|
||||||
|
if (next != null) moveTo(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Return the [StateAck.IndexMoved] receipt without moving, as a rewind-in-place does. */
|
||||||
|
fun rewind() {
|
||||||
|
manager?.ack(this, StateAck.IndexMoved)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun newPlayback(command: PlaybackCommand, deck: List<Song>) {
|
||||||
|
val heap = command.queue.toMutableList()
|
||||||
|
val startIndex = command.song?.let(command.queue::indexOf) ?: 0
|
||||||
|
// Retain the deck directly after the start song.
|
||||||
|
heap.addAll(startIndex + 1, deck)
|
||||||
|
rawQueue = RawQueue(heap, emptyList(), startIndex)
|
||||||
manager?.ack(this, StateAck.NewPlayback)
|
manager?.ack(this, StateAck.NewPlayback)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun playNext(songs: List<Song>, ack: StateAck.PlayNext) {
|
override fun playNext(songs: List<Song>, ack: StateAck.PlayNext) {
|
||||||
insertions += ack
|
insertions += ack
|
||||||
|
insertAt(ack.at, songs)
|
||||||
|
manager?.ack(this, ack)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun playAfter(songs: List<Song>, ack: StateAck.PlayNext) {
|
override fun playAfter(songs: List<Song>, ack: StateAck.PlayNext) {
|
||||||
insertions += ack
|
insertions += ack
|
||||||
|
insertAt(ack.at, songs)
|
||||||
|
manager?.ack(this, ack)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert at the resolved-queue position [resolvedAt], translated to a timeline position as
|
||||||
|
* ExoPlaybackStateHolder does with unscrambleQueueIndices.
|
||||||
|
*/
|
||||||
|
private fun insertAt(resolvedAt: Int, songs: List<Song>) {
|
||||||
|
val queue = rawQueue
|
||||||
|
val heap = queue.heap.toMutableList()
|
||||||
|
val trueAt =
|
||||||
|
when {
|
||||||
|
!queue.isShuffled -> resolvedAt.coerceAtMost(heap.size)
|
||||||
|
resolvedAt < queue.shuffledMapping.size -> queue.shuffledMapping[resolvedAt]
|
||||||
|
else -> heap.size
|
||||||
|
}
|
||||||
|
heap.addAll(trueAt, songs)
|
||||||
|
val mapping =
|
||||||
|
if (queue.isShuffled) {
|
||||||
|
// Existing timeline indices shift right of the insertion; the new items take
|
||||||
|
// their playback position at resolvedAt.
|
||||||
|
val shifted =
|
||||||
|
queue.shuffledMapping.map { if (it >= trueAt) it + songs.size else it }
|
||||||
|
shifted.subList(0, resolvedAt) +
|
||||||
|
(trueAt until trueAt + songs.size).toList() +
|
||||||
|
shifted.subList(resolvedAt, shifted.size)
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
rawQueue =
|
||||||
|
RawQueue(
|
||||||
|
heap = heap,
|
||||||
|
shuffledMapping = mapping,
|
||||||
|
heapIndex =
|
||||||
|
if (trueAt <= queue.heapIndex) queue.heapIndex + songs.size
|
||||||
|
else queue.heapIndex,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun playing(playing: Boolean) {}
|
override fun playing(playing: Boolean) {}
|
||||||
@@ -88,35 +148,76 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
|
|||||||
|
|
||||||
override fun next() {}
|
override fun next() {}
|
||||||
|
|
||||||
override fun prev() {}
|
override fun prev() {
|
||||||
|
// Step back one position, as a skip back does.
|
||||||
|
if (rawQueue.heapIndex > 0) {
|
||||||
|
moveTo(rawQueue.heapIndex - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun goto(index: Int) {}
|
override fun goto(index: Int) {}
|
||||||
|
|
||||||
override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {}
|
override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {
|
||||||
|
insertAt(ack.at, songs)
|
||||||
|
manager?.ack(this, ack)
|
||||||
|
}
|
||||||
|
|
||||||
override fun move(from: Int, to: Int, ack: StateAck.Move) {
|
override fun move(from: Int, to: Int, ack: StateAck.Move) {
|
||||||
// Positions are resolved-queue positions; the fake is unshuffled, so they are heap
|
// A move is a removal plus an insertion at resolved positions.
|
||||||
// positions.
|
val song = rawQueue.resolveSongs()[from]
|
||||||
val heap = rawQueue.heap.toMutableList()
|
removeAtResolved(from)
|
||||||
heap.add(to, heap.removeAt(from))
|
insertAt(to, listOf(song))
|
||||||
rawQueue = rawQueue.copy(heap = heap)
|
|
||||||
manager?.ack(this, StateAck.Move(from, to))
|
manager?.ack(this, StateAck.Move(from, to))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun remove(at: Int, ack: StateAck.Remove) {
|
override fun remove(at: Int, ack: StateAck.Remove) {
|
||||||
// Positions are resolved-queue positions; the fake is unshuffled, so they are heap
|
removeAtResolved(at)
|
||||||
// positions.
|
|
||||||
val heap = rawQueue.heap.toMutableList()
|
|
||||||
heap.removeAt(at)
|
|
||||||
rawQueue = rawQueue.copy(heap = heap)
|
|
||||||
manager?.ack(this, StateAck.Remove(at))
|
manager?.ack(this, StateAck.Remove(at))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun shuffled(shuffled: Boolean) {
|
/**
|
||||||
// Apply a reversed mapping as a stand-in shuffle.
|
* Remove the song at the resolved-queue position [at], translating to a timeline position
|
||||||
|
* under shuffle and maintaining the permutation, as ExoPlayer's cloneAndRemove does.
|
||||||
|
*/
|
||||||
|
private fun removeAtResolved(at: Int) {
|
||||||
|
val queue = rawQueue
|
||||||
|
val trueAt = if (queue.isShuffled) queue.shuffledMapping[at] else at
|
||||||
|
val heap = queue.heap.toMutableList()
|
||||||
|
heap.removeAt(trueAt)
|
||||||
|
val mapping =
|
||||||
|
if (queue.isShuffled) {
|
||||||
|
// The permutation loses the removed timeline index; later indices shift down.
|
||||||
|
queue.shuffledMapping
|
||||||
|
.filter { it != trueAt }
|
||||||
|
.map { if (it > trueAt) it - 1 else it }
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
rawQueue =
|
||||||
|
RawQueue(
|
||||||
|
heap = heap,
|
||||||
|
shuffledMapping = mapping,
|
||||||
|
// Removing ahead of the playhead shifts it back, as ExoPlayer shifts it.
|
||||||
|
heapIndex =
|
||||||
|
if (trueAt < queue.heapIndex) queue.heapIndex - 1 else queue.heapIndex,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun shuffled(shuffled: Boolean, deckSize: Int) {
|
||||||
rawQueue =
|
rawQueue =
|
||||||
rawQueue.copy(
|
rawQueue.copy(
|
||||||
shuffledMapping = if (shuffled) rawQueue.heap.indices.reversed().toList() else emptyList()
|
shuffledMapping =
|
||||||
|
if (shuffled) {
|
||||||
|
// Stand-in pinned shuffle: current on top, deck in order, the rest
|
||||||
|
// reversed.
|
||||||
|
val current = rawQueue.heapIndex
|
||||||
|
val deck = current + 1..current + deckSize
|
||||||
|
val rest =
|
||||||
|
rawQueue.heap.indices.filter { it != current && it !in deck }
|
||||||
|
listOf(current) + deck.toList() + rest.reversed()
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
)
|
)
|
||||||
manager?.ack(this, StateAck.QueueReordered)
|
manager?.ack(this, StateAck.QueueReordered)
|
||||||
}
|
}
|
||||||
@@ -129,7 +230,12 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
|
|||||||
positionMs: Long,
|
positionMs: Long,
|
||||||
repeatMode: RepeatMode,
|
repeatMode: RepeatMode,
|
||||||
ack: StateAck.NewPlayback?,
|
ack: StateAck.NewPlayback?,
|
||||||
) {}
|
) {
|
||||||
|
this.parent = parent
|
||||||
|
this.rawQueue = rawQueue
|
||||||
|
this.repeatMode = repeatMode
|
||||||
|
if (ack != null) manager?.ack(this, ack)
|
||||||
|
}
|
||||||
|
|
||||||
override fun endSession() {}
|
override fun endSession() {}
|
||||||
|
|
||||||
@@ -137,13 +243,15 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A [Song] whose every property throws.
|
* A [Song] whose every property throws except [uid], which is real: persistence and restore
|
||||||
|
* key on it.
|
||||||
*
|
*
|
||||||
* The manager moves songs in lists without reading them. Grow a member when a test needs it.
|
* The manager moves songs in lists without reading them. Grow a member when a test needs it.
|
||||||
*/
|
*/
|
||||||
fun fakeSong(): Song =
|
fun fakeSong(): Song =
|
||||||
object : Song {
|
object : Song {
|
||||||
override val uid: Music.UID get() = TODO()
|
override val uid: Music.UID =
|
||||||
|
requireNotNull(Music.UID.fromString("uas${UUID.randomUUID()}"))
|
||||||
override val name: Name.Known get() = TODO()
|
override val name: Name.Known get() = TODO()
|
||||||
override val track: Int? get() = TODO()
|
override val track: Int? get() = TODO()
|
||||||
override val disc: Disc? get() = TODO()
|
override val disc: Disc? get() = TODO()
|
||||||
|
|||||||
+250
-20
@@ -19,9 +19,109 @@
|
|||||||
package org.oxycblt.auxio.playback.state
|
package org.oxycblt.auxio.playback.state
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertSame
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
|
||||||
class PlaybackStateManagerImplTest {
|
class PlaybackStateManagerImplTest {
|
||||||
|
/**
|
||||||
|
* Persistence: a deck song missing from the library on restore drops only itself; the
|
||||||
|
* rest of the deck survives, matching the heap's own realignment.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `a missing deck song drops only itself on restore`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue; deck of two songs.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
|
||||||
|
// Save, then restore with the first deck song gone from the library (null in the heap,
|
||||||
|
// as realignment marks missing songs).
|
||||||
|
val savedState = manager.toSavedState()!!
|
||||||
|
val shiftedState =
|
||||||
|
savedState.copy(
|
||||||
|
heap = savedState.heap.map { if (it === savedState.deck[0]) null else it }
|
||||||
|
)
|
||||||
|
val restoredManager = PlaybackStateManagerImpl()
|
||||||
|
val restoredHolder = FakePlaybackStateHolder()
|
||||||
|
restoredHolder.manager = restoredManager
|
||||||
|
restoredManager.registerStateHolder(restoredHolder)
|
||||||
|
restoredManager.applySavedState(shiftedState, destructive = true)
|
||||||
|
|
||||||
|
// The timeline restored without the missing song.
|
||||||
|
assertEquals(11, restoredManager.queue.size)
|
||||||
|
|
||||||
|
// Play after one song: behind the surviving deck song.
|
||||||
|
restoredManager.playAfter(listOf(fakeSong()))
|
||||||
|
assertEquals(StateAck.PlayNext(at = 4, size = 1), restoredHolder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistence: the deck survives a save and restore — after a restart, queue actions land
|
||||||
|
* behind the remembered deck.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `the deck survives a save and restore`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue; deck of two songs.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
|
||||||
|
// Save, then restore into a fresh manager and holder, as a restart does.
|
||||||
|
val savedState = manager.toSavedState()!!
|
||||||
|
val restoredManager = PlaybackStateManagerImpl()
|
||||||
|
val restoredHolder = FakePlaybackStateHolder()
|
||||||
|
restoredHolder.manager = restoredManager
|
||||||
|
restoredManager.registerStateHolder(restoredHolder)
|
||||||
|
restoredManager.applySavedState(savedState, destructive = true)
|
||||||
|
|
||||||
|
// The timeline survived intact.
|
||||||
|
assertEquals(12, restoredManager.queue.size)
|
||||||
|
|
||||||
|
// Play after one song: behind the remembered deck.
|
||||||
|
restoredManager.playAfter(listOf(fakeSong()))
|
||||||
|
assertEquals(StateAck.PlayNext(at = 5, size = 1), restoredHolder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reproduction harness (field failure): a deck played through under shuffle, then
|
||||||
|
* unshuffle, must leave the physical heap in playlist order.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `shuffled deck play-through leaves the heap in playlist order after unshuffle`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
|
// Deck of two songs (not heap members), then shuffle on.
|
||||||
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
manager.shuffled(true)
|
||||||
|
|
||||||
|
// Play through the deck and two songs into the tail.
|
||||||
|
repeat(4) { holder.advanceToNext() }
|
||||||
|
|
||||||
|
// Shuffle off.
|
||||||
|
manager.shuffled(false)
|
||||||
|
|
||||||
|
// The physical heap is the playlist again: the deck songs drained, nothing reordered.
|
||||||
|
assertEquals(queue, holder.rawQueue.heap)
|
||||||
|
assertEquals(queue, manager.queue)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interaction: playNext on an empty deck starts one — the deck is the songs the user
|
* Interaction: playNext on an empty deck starts one — the deck is the songs the user
|
||||||
* manually lined up, and play-next is such an act.
|
* manually lined up, and play-next is such an act.
|
||||||
@@ -225,11 +325,11 @@ class PlaybackStateManagerImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset: when the queue is reshuffled ([StateAck.QueueReordered]), the deck is forgotten and
|
* Retention: a reshuffle leaves the deck pinned directly behind the current song, in
|
||||||
* the next playAfter starts a fresh deck behind the current song's new position.
|
* order; the heap shuffles beneath it.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
fun `playAfter after a reshuffle starts a fresh deck`() {
|
fun `the deck survives a reshuffle pinned in front`() {
|
||||||
val manager = PlaybackStateManagerImpl()
|
val manager = PlaybackStateManagerImpl()
|
||||||
val holder = FakePlaybackStateHolder()
|
val holder = FakePlaybackStateHolder()
|
||||||
holder.manager = manager
|
holder.manager = manager
|
||||||
@@ -239,25 +339,26 @@ class PlaybackStateManagerImplTest {
|
|||||||
val queue = List(10) { fakeSong() }
|
val queue = List(10) { fakeSong() }
|
||||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
// Deck of 2 songs occupies positions 3 and 4.
|
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
|
||||||
// The user reshuffles; the current song lands at position 7.
|
// The user shuffles. The deck stays in order behind the current song, which lands
|
||||||
|
// at playback position 0; the heap reverses beneath (stand-in shuffle).
|
||||||
manager.shuffled(true)
|
manager.shuffled(true)
|
||||||
|
|
||||||
// Play after one song.
|
// Play after one song.
|
||||||
manager.playAfter(listOf(fakeSong()))
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
|
||||||
// Last receipt: 1 song at position 8, behind the current song's new position.
|
// Last receipt: 1 song at position 3, behind the pinned deck.
|
||||||
assertEquals(StateAck.PlayNext(at = 8, size = 1), holder.insertions.last())
|
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset: when new playback starts ([StateAck.NewPlayback]), the deck is forgotten and the
|
* Retention: new playback replaces the heap and retains the queue — the tapped song plays
|
||||||
* next playAfter starts a fresh deck behind the new queue's current song.
|
* immediately as the new heap's top, and the deck stays ahead of the new tail.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
fun `playAfter after new playback starts a fresh deck`() {
|
fun `the deck persists across new playback`() {
|
||||||
val manager = PlaybackStateManagerImpl()
|
val manager = PlaybackStateManagerImpl()
|
||||||
val holder = FakePlaybackStateHolder()
|
val holder = FakePlaybackStateHolder()
|
||||||
holder.manager = manager
|
holder.manager = manager
|
||||||
@@ -270,23 +371,23 @@ class PlaybackStateManagerImplTest {
|
|||||||
// Deck of 2 songs occupies positions 3 and 4.
|
// Deck of 2 songs occupies positions 3 and 4.
|
||||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
|
||||||
// The user starts a new 5-song album from its first song.
|
// The user taps the first song of a 5-song album.
|
||||||
val album = List(5) { fakeSong() }
|
val album = List(5) { fakeSong() }
|
||||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(album[0], null, album, false))
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(album[0], null, album, false))
|
||||||
|
|
||||||
// Play after one song.
|
// Play after one song.
|
||||||
manager.playAfter(listOf(fakeSong()))
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
|
||||||
// Last receipt: 1 song at position 1, behind the album's first song.
|
// Last receipt: 1 song at position 3, behind the retained deck on the new heap.
|
||||||
assertEquals(StateAck.PlayNext(at = 1, size = 1), holder.insertions.last())
|
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset: when the current song changes ([StateAck.IndexMoved]), the deck is forgotten and
|
* Membership: removing a heap entry whose instance is also decked keeps the deck —
|
||||||
* the next playAfter starts a fresh deck behind the new current song.
|
* membership is the position within the deck block, not the instance.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
fun `playAfter after the current song changes starts a fresh deck`() {
|
fun `removing a heap entry whose instance is decked keeps the deck`() {
|
||||||
val manager = PlaybackStateManagerImpl()
|
val manager = PlaybackStateManagerImpl()
|
||||||
val holder = FakePlaybackStateHolder()
|
val holder = FakePlaybackStateHolder()
|
||||||
holder.manager = manager
|
holder.manager = manager
|
||||||
@@ -296,18 +397,147 @@ class PlaybackStateManagerImplTest {
|
|||||||
val queue = List(10) { fakeSong() }
|
val queue = List(10) { fakeSong() }
|
||||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
// Deck of 2 then 3 songs occupies positions 3 through 7.
|
// Deck of one song: the same instance that sits at heap position 7 (8 after the
|
||||||
|
// insertion shifts it).
|
||||||
|
val duplicate = queue[7]
|
||||||
|
manager.playAfter(listOf(duplicate))
|
||||||
|
|
||||||
|
// Swipe the heap entry out of the queue.
|
||||||
|
manager.removeQueueItem(8)
|
||||||
|
|
||||||
|
// The deck entry survived at position 3.
|
||||||
|
assertEquals(10, manager.queue.size)
|
||||||
|
assertSame(duplicate, manager.queue[3])
|
||||||
|
|
||||||
|
// Play after one song: behind the surviving deck song.
|
||||||
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
assertEquals(StateAck.PlayNext(at = 4, size = 1), holder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drain: a deck song whose instance also lives in the heap drains its deck entry, never
|
||||||
|
* the heap entry.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `draining a duplicated deck song removes the deck entry not the heap entry`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
|
// Deck of one song: the same instance that sits at heap position 0.
|
||||||
|
val duplicate = queue[0]
|
||||||
|
manager.playAfter(listOf(duplicate))
|
||||||
|
|
||||||
|
// The current song ends; the deck song starts playing.
|
||||||
|
holder.moveTo(3)
|
||||||
|
|
||||||
|
// The user skips back to the heap cursor.
|
||||||
|
manager.prev()
|
||||||
|
|
||||||
|
// The heap entry survived at position 0; the deck entry drained.
|
||||||
|
assertEquals(10, manager.queue.size)
|
||||||
|
assertSame(duplicate, manager.queue[0])
|
||||||
|
|
||||||
|
// Play after one song: the deck is empty, so it lands behind the current song.
|
||||||
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drain guard: rewinding within the current song (prev past the rewind threshold) is not a
|
||||||
|
* departure — nothing drains, nothing advances.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `rewinding within a deck song does not drain it`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
|
// Deck of 2 songs occupies positions 3 and 4.
|
||||||
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
|
|
||||||
|
// The current song ends; the deck head starts playing.
|
||||||
|
holder.moveTo(3)
|
||||||
|
|
||||||
|
// The user presses prev past the rewind threshold: the song restarts in place.
|
||||||
|
holder.rewind()
|
||||||
|
|
||||||
|
// Play after one song.
|
||||||
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
|
||||||
|
// Last receipt: 1 song at position 5 — the playing deck song held, the deck intact.
|
||||||
|
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drain: skipping backward out of a deck song drains it from the queue; prev lands on the
|
||||||
|
* heap cursor.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `skipping backward out of a deck song drains it`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
|
// Deck of 3 songs occupies positions 3 through 5.
|
||||||
|
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||||
|
|
||||||
|
// The current song ends; the deck head starts playing.
|
||||||
|
holder.moveTo(3)
|
||||||
|
|
||||||
|
// The user skips back to the heap cursor.
|
||||||
|
manager.prev()
|
||||||
|
|
||||||
|
// Play after one song.
|
||||||
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
|
||||||
|
// Last receipt: 1 song at position 5, behind the two remaining deck songs — the
|
||||||
|
// departed head drained.
|
||||||
|
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retention: a track change is the queue doing its job. The deck persists, minus the song
|
||||||
|
* that started playing — it left the upcoming queue by becoming current.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun `the deck persists across track changes`() {
|
||||||
|
val manager = PlaybackStateManagerImpl()
|
||||||
|
val holder = FakePlaybackStateHolder()
|
||||||
|
holder.manager = manager
|
||||||
|
manager.registerStateHolder(holder)
|
||||||
|
|
||||||
|
// Playing index 2 of a 10-song queue.
|
||||||
|
val queue = List(10) { fakeSong() }
|
||||||
|
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||||
|
|
||||||
|
// Deck of 2 then 3 songs occupies positions 3 through 7; boundary at 8.
|
||||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||||
|
|
||||||
// The current song ends; index 3 begins.
|
// The current song ends; the deck head at position 3 starts playing.
|
||||||
holder.moveTo(3)
|
holder.moveTo(3)
|
||||||
|
|
||||||
// Play after one song.
|
// Play after one song.
|
||||||
manager.playAfter(listOf(fakeSong()))
|
manager.playAfter(listOf(fakeSong()))
|
||||||
|
|
||||||
// Last receipt: 1 song at position 4, behind the new current song.
|
// Last receipt: 1 song at position 8, behind the four remaining deck songs.
|
||||||
assertEquals(StateAck.PlayNext(at = 4, size = 1), holder.insertions.last())
|
assertEquals(StateAck.PlayNext(at = 8, size = 1), holder.insertions.last())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user